tgdata 0.1.2__tar.gz → 0.1.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {tgdata-0.1.2 → tgdata-0.1.4}/PKG-INFO +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/__init__.py +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/_terminal_input.py +2 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_modes.py +21 -10
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_42_album_assembly.py +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_43_photo_trails.py +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_45_group_profile.py +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_46_group_activity.py +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_48_terminal_login.py +1 -1
- tgdata-0.1.4/tgdata/smoke_tests/test_49_worker_media.py +368 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/worker.py +9 -4
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/worker_engine.py +24 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/worker_protocol.py +11 -5
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata.egg-info/PKG-INFO +1 -1
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata.egg-info/SOURCES.txt +1 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/README.md +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/setup.cfg +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/setup.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/account_operation.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/account_pool.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/album.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/backfill.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/backfill_engine.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/backfill_state.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/batch_engine.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/batch_files.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/batch_heartbeat.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/budget_client.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/connection_engine.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/discovery_engine.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/group_activity.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/group_operations.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/group_profile.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/health.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/history_window.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/join_budget.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/join_client.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/login.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/login_cli.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/login_file.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/message_batch.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/message_engine.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/models.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/owned_health.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/photo_trails.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/pool_lifecycle.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/pool_observation.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/pool_result.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/pool_source.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/pool_state.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/progress.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/progress_facade.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/read_budget.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/session_store.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/__init__.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_framing.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_handoffs.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_observer.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/my_test.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/pool_storage_cases.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_00_connection.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_01_list_group_chats.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_02_get_message_count.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_03_get_all_messages.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_04_get_all_messages_in_batches.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_05_with_progress_feature.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_06_polling_simple.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_07_on_new_message_simple.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_07_real_time_event_handler.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_08_batch_callback.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_08_polling.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_10_advanced_features.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_11_discover_groups.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_12_proxy.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_13_device_identity.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_14_flood_threshold.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_15_login_checks.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_16_health_events.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_17_session_store.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_18_read_budget.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_19_message_batches.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_22_daily_continuation.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_23_fixed_windows.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_24_backfill_state.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_25_backfill_delivery.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_26_backfill_completion.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_27_backfill_pacing.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_28_backfill_controls.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_29_backfill_public.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_30_backfill_integration.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_31_account_pool.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_32_account_operation.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_33_owned_health.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_34_group_access.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_35_join_budget.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_36_group_join.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_37_worker.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_38_worker_process.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_39_pool_lifecycle.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_40_pool_outcomes.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_41_stepwise_login.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_44_batch_heartbeat.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_debug_min_id.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_polling_debug.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/smoke_tests/test_username_support.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/sync_engine.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/sync_store.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/tgdata.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata/utils.py +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata.egg-info/dependency_links.txt +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata.egg-info/entry_points.txt +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata.egg-info/requires.txt +0 -0
- {tgdata-0.1.2 → tgdata-0.1.4}/tgdata.egg-info/top_level.txt +0 -0
|
@@ -34,9 +34,10 @@ def _control(value):
|
|
|
34
34
|
def _validate(fd, attrs):
|
|
35
35
|
if os.tcgetpgrp(fd) != os.getpgrp():
|
|
36
36
|
raise TerminalInputError('terminal_not_foreground')
|
|
37
|
+
# The kernel may report pending input; the owned flush settles it while hidden.
|
|
37
38
|
allowed = 0
|
|
38
39
|
for name in ('ECHO', 'ECHOE', 'ECHOK', 'ECHONL', 'ECHOCTL', 'ECHOKE',
|
|
39
|
-
'ECHOPRT', 'ISIG', 'ICANON', 'IEXTEN', 'NOFLSH', 'TOSTOP'):
|
|
40
|
+
'ECHOPRT', 'ISIG', 'ICANON', 'IEXTEN', 'NOFLSH', 'TOSTOP', 'PENDIN'):
|
|
40
41
|
allowed |= getattr(termios, name, 0)
|
|
41
42
|
forbidden = (termios.ISTRIP | termios.IGNCR | termios.INLCR
|
|
42
43
|
| termios.PARMRK | getattr(termios, 'IUCLC', 0))
|
|
@@ -18,12 +18,18 @@ MODES=FIRST+['after_restore_normal','after_restore_eof']+['stop_'+p for p in ('a
|
|
|
18
18
|
'unicode','editing','limit128','limit129','kernel_overflow','invalid_utf8','partial_eof','typeahead',
|
|
19
19
|
'two_terminals','no_controlling','background','noncanonical','istrip','istrip_afterphone','bad_cr','small_canon','no_termios','echo_off']
|
|
20
20
|
BASE_MODES=tuple(MODES)
|
|
21
|
-
PROFILE_MODES=('no_isig','inlcr','parmrk','no_icrnl','
|
|
21
|
+
PROFILE_MODES=('no_isig','inlcr','parmrk','no_icrnl','flusho','unknown_lflag','bad_intr','disabled_eof','overlap_controls','newline_control','bad_vdisable','short_cc','thread','running_loop')
|
|
22
22
|
CONTROL_MODES=('quit_intermediate','suspend_intermediate','intr_intermediate','keyboard_cancel','keyboard_discard')
|
|
23
|
-
|
|
23
|
+
PENDIN_MODES=('pendin','pendin_password','pendin_first_phone_normal','pendin_first_phone_eof',
|
|
24
|
+
'pendin_first_code_eof','pendin_first_password_normal','pendin_first_replace_normal',
|
|
25
|
+
'pendin_first_retry_eof','pendin_keyboard_discard','pendin_kernel_overflow','pendin_unknown_lflag')
|
|
26
|
+
MODES+=list(PROFILE_MODES)+list(CONTROL_MODES)+list(PENDIN_MODES)
|
|
24
27
|
|
|
25
28
|
|
|
26
29
|
def child(mode):
|
|
30
|
+
case=mode
|
|
31
|
+
pendin_context=mode=='pendin' or mode.startswith('pendin_')
|
|
32
|
+
if mode.startswith('pendin_'):mode=mode[len('pendin_'):]
|
|
27
33
|
if mode=='background':
|
|
28
34
|
pid=os.fork()
|
|
29
35
|
if pid:
|
|
@@ -44,7 +50,7 @@ def child(mode):
|
|
|
44
50
|
if mode=='inlcr':attrs[0]|=termios.INLCR
|
|
45
51
|
if mode=='parmrk':attrs[0]|=termios.PARMRK
|
|
46
52
|
if mode=='no_icrnl':attrs[0]&=~termios.ICRNL
|
|
47
|
-
if
|
|
53
|
+
if pendin_context:attrs[3]|=termios.PENDIN
|
|
48
54
|
if mode=='flusho':attrs[3]|=termios.FLUSHO
|
|
49
55
|
if mode=='bad_intr':attrs[6][termios.VINTR]=b'\x18'
|
|
50
56
|
if mode=='disabled_eof':attrs[6][termios.VEOF]=b'\xff'
|
|
@@ -52,8 +58,9 @@ def child(mode):
|
|
|
52
58
|
if mode=='newline_control':attrs[6][termios.VEOF]=b'\n'
|
|
53
59
|
if attrs is not None and mode!='background':termios.tcsetattr(control,termios.TCSANOW,attrs)
|
|
54
60
|
before_control=termios.tcgetattr(control) if control is not None else None
|
|
61
|
+
if pendin_context:assert before_control[3]&termios.PENDIN
|
|
55
62
|
before_stdin=termios.tcgetattr(0)
|
|
56
|
-
phase=mode.split('_')[1] if mode.startswith('first_') else 'phone'
|
|
63
|
+
phase=mode.split('_')[1] if mode.startswith('first_') else 'password' if mode=='password' else 'phone'
|
|
57
64
|
two_factor=phase=='password'
|
|
58
65
|
existing=phase in ('replace','retry')
|
|
59
66
|
state=dict(selected=False, fd=None, fired=False, restored=False, reads=0, value=False, two_observed=False, candidate_mode_writes=0, hidden=False, intermediate=False, key_signals=0, quit_signals=0, suspend_signals=0)
|
|
@@ -218,7 +225,7 @@ def child(mode):
|
|
|
218
225
|
if mode=='two_terminals':assert state['two_observed'] and get(0)==before_stdin
|
|
219
226
|
assert signal.getsignal(signal.SIGINT)==original_handler
|
|
220
227
|
assert all(not w.up for w in service.wires)
|
|
221
|
-
saved=mode in ('typeahead','two_terminals','echo_off','small_canon')
|
|
228
|
+
saved=mode in ('typeahead','two_terminals','echo_off','small_canon','pendin','password')
|
|
222
229
|
expected_code=0 if saved else 2 if mode in ('no_controlling','background','noncanonical','istrip','bad_cr','no_termios')+PROFILE_MODES else 3 if (mode.startswith('fault_') and mode!='fault_restore_stop') or mode in ('limit129','kernel_overflow','invalid_utf8','istrip_afterphone') else 130
|
|
223
230
|
assert code==expected_code,(mode,code,expected_code)
|
|
224
231
|
if mode in PROFILE_MODES or mode in ('background','no_controlling','noncanonical','istrip','bad_cr','no_termios','stop_acquire','stop_snapshot'):
|
|
@@ -230,12 +237,14 @@ def child(mode):
|
|
|
230
237
|
expected_codes=1 if phase!='phone' or saved or mode=='istrip_afterphone' else 0
|
|
231
238
|
assert service.calls.count('SendCodeRequest')==expected_codes,(mode,service.calls)
|
|
232
239
|
if phase=='code' or mode=='istrip_afterphone':assert 'SignInRequest' not in service.calls
|
|
233
|
-
if phase=='password':assert 'CheckPasswordRequest' not in service.calls
|
|
240
|
+
if phase=='password' and not saved:assert 'CheckPasswordRequest' not in service.calls
|
|
241
|
+
if mode=='password':assert service.srp_accepted==1
|
|
234
242
|
if mode in ('unicode','editing','limit128'):assert state['value']
|
|
235
243
|
if mode.startswith(('first_','after_restore_','stop_','fault_')):assert state['fired'],mode
|
|
236
|
-
result=dict(mode=
|
|
244
|
+
result=dict(mode=case,exit=code,terminal_restored=restoration_observed,codes=expected_codes,saved=saved,
|
|
237
245
|
signal_or_fault_fired=state['fired'],value_checked=state['value'],two_terminals_observed=state['two_observed'])
|
|
238
246
|
result['candidate_mode_writes']=state['candidate_mode_writes']
|
|
247
|
+
result['initial_pendin']=bool(before_control is not None and before_control[3]&termios.PENDIN)
|
|
239
248
|
result['key_signals']=state['key_signals']
|
|
240
249
|
if mode=='flusho':put(control,termios.TCSANOW,original_control)
|
|
241
250
|
print('\nMATRIX_RESULT '+json.dumps(result),flush=True)
|
|
@@ -248,6 +257,8 @@ def child(mode):
|
|
|
248
257
|
|
|
249
258
|
|
|
250
259
|
def parent(mode):
|
|
260
|
+
case=mode
|
|
261
|
+
if mode.startswith('pendin_'):mode=mode[len('pendin_'):]
|
|
251
262
|
master,slave=pty.openpty(); extra=[]
|
|
252
263
|
stdin_slave=slave
|
|
253
264
|
if mode=='two_terminals':
|
|
@@ -255,14 +266,14 @@ def parent(mode):
|
|
|
255
266
|
def control():
|
|
256
267
|
os.setsid()
|
|
257
268
|
if mode!='no_controlling':fcntl.ioctl(slave,termios.TIOCSCTTY,0)
|
|
258
|
-
process=subprocess.Popen([sys.executable,str(Path(__file__).resolve()),'--child',
|
|
269
|
+
process=subprocess.Popen([sys.executable,str(Path(__file__).resolve()),'--child',case],
|
|
259
270
|
stdin=stdin_slave,stdout=slave,stderr=slave,preexec_fn=control,pass_fds=(slave,),
|
|
260
271
|
env=dict(os.environ,PYTHONDONTWRITEBYTECODE='1'))
|
|
261
272
|
os.close(slave)
|
|
262
273
|
if mode=='two_terminals':os.close(stdin_slave);extra.remove(stdin_slave)
|
|
263
274
|
os.set_blocking(master,False)
|
|
264
275
|
data=bytearray();seen={};deadline=time.monotonic()+15;pending=b'';written=0;requested=0;stage_sent=False;cancel_sent=False
|
|
265
|
-
target_phase=mode.split('_')[1] if mode.startswith('first_') else 'phone'
|
|
276
|
+
target_phase=mode.split('_')[1] if mode.startswith('first_') else 'password' if mode=='password' else 'phone'
|
|
266
277
|
try:
|
|
267
278
|
while time.monotonic()<deadline:
|
|
268
279
|
reads,writes,_=select.select([master],[master] if pending else [],[],0.005)
|
|
@@ -325,7 +336,7 @@ def run():
|
|
|
325
336
|
results=[]
|
|
326
337
|
for mode in MODES:
|
|
327
338
|
row=parent(mode);results.append(row)
|
|
328
|
-
print(('OWNED_TERMINAL ' if mode in BASE_MODES else 'PROFILE_CONTROL ')+json.dumps(row),flush=True)
|
|
339
|
+
print(('OWNED_TERMINAL ' if mode in BASE_MODES else 'PENDIN_CONTEXT ' if mode in PENDIN_MODES else 'PROFILE_CONTROL ')+json.dumps(row),flush=True)
|
|
329
340
|
return results
|
|
330
341
|
|
|
331
342
|
if __name__=='__main__':
|
|
@@ -124,7 +124,7 @@ class AlbumTests(unittest.TestCase):
|
|
|
124
124
|
for name in ('TelegramPost', 'AlbumAssemblyError', 'album_post_ids', 'assemble_albums'):
|
|
125
125
|
self.assertIs(getattr(tgdata, name), globals()[name])
|
|
126
126
|
self.assertIn(name, tgdata.__all__)
|
|
127
|
-
self.assertEqual(tgdata.__version__, '0.1.
|
|
127
|
+
self.assertEqual(tgdata.__version__, '0.1.4')
|
|
128
128
|
|
|
129
129
|
def test_sdk_large_ids_captions_and_cross_chat(self):
|
|
130
130
|
rows = (record(1, 'first'), record(2, 'second'))
|
|
@@ -123,7 +123,7 @@ class PhotoTrailTests(unittest.TestCase):
|
|
|
123
123
|
self.assertEqual(member_groups(result), ((1,), (2,)))
|
|
124
124
|
self.assertFalse(result.policy.enabled)
|
|
125
125
|
self.assertEqual((result.folded_posts,result.folded_photos),(0,0))
|
|
126
|
-
self.assertEqual(tgdata.__version__, '0.1.
|
|
126
|
+
self.assertEqual(tgdata.__version__, '0.1.4')
|
|
127
127
|
|
|
128
128
|
def test_policy_validation_and_immutable_roundtrip(self):
|
|
129
129
|
self.assertEqual(PhotoTrailPolicy.from_dict(ON.to_dict()), ON)
|
|
@@ -78,7 +78,7 @@ async def test_defaults_and_full_metadata():
|
|
|
78
78
|
async def test_public_exports_and_detached_immutable_values():
|
|
79
79
|
import tgdata
|
|
80
80
|
assert {'GroupProfile', 'GroupPinnedMessage'} <= set(tgdata.__all__)
|
|
81
|
-
assert tgdata.__version__ == '0.1.
|
|
81
|
+
assert tgdata.__version__ == '0.1.4'
|
|
82
82
|
assert len(tgdata.__all__) == len(set(tgdata.__all__))
|
|
83
83
|
tg, _ = setup(pin_response=pins([message()]))
|
|
84
84
|
value = await profile(tg, 3)
|
|
@@ -76,7 +76,7 @@ async def test_exports_frozen_values_and_json():
|
|
|
76
76
|
assert isinstance(value, GroupActivity) and isinstance(value.messages[0], ActivityMessage)
|
|
77
77
|
assert value.schema_version == 1 and value.account_id == 222
|
|
78
78
|
assert {'GroupActivity', 'ActivityMessage'} <= set(tgdata.__all__)
|
|
79
|
-
assert tgdata.__version__ == '0.1.
|
|
79
|
+
assert tgdata.__version__ == '0.1.4' and len(set(tgdata.__all__)) == len(tgdata.__all__)
|
|
80
80
|
for obj, key in ((value, 'coverage_complete'), (value.messages[0], 'views'), (value.group, 'title')):
|
|
81
81
|
fx.refuses(FrozenInstanceError, lambda: setattr(obj, key, 42))
|
|
82
82
|
data = value.to_dict()
|
|
@@ -945,7 +945,7 @@ def _native_matrix(module, prefixes, expected):
|
|
|
945
945
|
|
|
946
946
|
|
|
947
947
|
def test_native_terminal_profiles_and_controls():
|
|
948
|
-
_native_matrix('_terminal_login_modes', ('OWNED_TERMINAL ', 'PROFILE_CONTROL '),
|
|
948
|
+
_native_matrix('_terminal_login_modes', ('OWNED_TERMINAL ', 'PROFILE_CONTROL ', 'PENDIN_CONTEXT '), 80)
|
|
949
949
|
|
|
950
950
|
|
|
951
951
|
def test_native_input_framing():
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""Worker media options over real SDK readers, files, SQLite and process pipes.
|
|
2
|
+
|
|
3
|
+
Only Telegram replies/transport and named failure timing are controlled. No login
|
|
4
|
+
or remote sockets. Run: python -m tgdata.smoke_tests.test_49_worker_media
|
|
5
|
+
"""
|
|
6
|
+
import asyncio
|
|
7
|
+
from contextlib import ExitStack
|
|
8
|
+
import hashlib
|
|
9
|
+
import inspect
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import socket
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import tempfile
|
|
18
|
+
import traceback
|
|
19
|
+
from unittest.mock import patch
|
|
20
|
+
|
|
21
|
+
ROOT = Path(__file__).resolve().parents[2]
|
|
22
|
+
sys.path.insert(0, str(ROOT))
|
|
23
|
+
import tgdata
|
|
24
|
+
assert Path(tgdata.__file__).resolve().parents[1] == ROOT
|
|
25
|
+
from telethon import errors, functions, types
|
|
26
|
+
from tgdata import MessageBatch, ReadBudget
|
|
27
|
+
from tgdata import batch_files, worker, worker_protocol as wire
|
|
28
|
+
from tgdata.worker_engine import Worker, WorkerAccount
|
|
29
|
+
from tgdata.smoke_tests import test_37_worker as f
|
|
30
|
+
|
|
31
|
+
PHOTO = b'photo-bytes\x00' * 701
|
|
32
|
+
VIDEO = bytes(range(256)) * 601
|
|
33
|
+
ASSET_PHOTO, ASSET_VIDEO = 9001, 9002
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def media_messages():
|
|
37
|
+
photo = f.b.photo(101, sizes=[types.PhotoSize('w', 100, 100, len(PHOTO))])
|
|
38
|
+
photo.media.photo.id = ASSET_PHOTO
|
|
39
|
+
video = f.b.document(102, asset_id=ASSET_VIDEO, data=VIDEO, mime='video/mp4')
|
|
40
|
+
video.media.document.attributes.append(types.DocumentAttributeVideo(2, 100, 100))
|
|
41
|
+
return [photo, video]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def configure_media(item):
|
|
45
|
+
item.scripts['GetHistoryRequest'] = [f.b.f.response(list(reversed(media_messages())))]
|
|
46
|
+
item.file_requests = []
|
|
47
|
+
def hook(client, sender):
|
|
48
|
+
original = sender.send
|
|
49
|
+
def send(request, ordered=False):
|
|
50
|
+
r = f.b.f.unwrap(request)
|
|
51
|
+
if not isinstance(r, functions.upload.GetFileRequest):
|
|
52
|
+
return original(request, ordered=ordered)
|
|
53
|
+
bytes(request) # Native TL encoding, with real-width fields.
|
|
54
|
+
sender.calls.append(type(r).__name__)
|
|
55
|
+
sender.requests.append(r)
|
|
56
|
+
item.file_requests.append((r.location.id, r.offset, r.limit))
|
|
57
|
+
if item.trace is not None:
|
|
58
|
+
item.trace('request', type(r).__name__)
|
|
59
|
+
if getattr(item, 'file_pending', None) is not None:
|
|
60
|
+
return item.file_pending
|
|
61
|
+
future = asyncio.get_running_loop().create_future()
|
|
62
|
+
if r.location.id == getattr(item, 'fail_asset', None):
|
|
63
|
+
error = getattr(item, 'file_error', errors.FloodWaitError(request=r, capture=30))
|
|
64
|
+
future.set_exception(error)
|
|
65
|
+
else:
|
|
66
|
+
data = {ASSET_PHOTO: PHOTO, ASSET_VIDEO: VIDEO}[r.location.id]
|
|
67
|
+
future.set_result(types.upload.File(types.storage.FileUnknown(), 0,
|
|
68
|
+
data[r.offset:r.offset + r.limit]))
|
|
69
|
+
return future
|
|
70
|
+
sender.send = send
|
|
71
|
+
if getattr(item, 'close_release', None) is not None:
|
|
72
|
+
sender.close_release = item.close_release
|
|
73
|
+
if getattr(item, 'close_error', None) is not None:
|
|
74
|
+
sender.close_error = item.close_error
|
|
75
|
+
item.hook = hook
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def enable(s, directory=None):
|
|
79
|
+
directory = s.root / 'media' if directory is None else directory
|
|
80
|
+
s.worker = Worker(s.worker.accounts, worker_id='test-worker', read_budget=s.budget,
|
|
81
|
+
join_budget=s.join, media_directory=directory)
|
|
82
|
+
return Path(directory).resolve()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def params(media=True):
|
|
86
|
+
result = dict(group_id='@synthetic_room', after_id='100', limit=2)
|
|
87
|
+
if media is not None:
|
|
88
|
+
result['download_media'] = media
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def check_files(root, document):
|
|
93
|
+
batch = MessageBatch.from_json(json.dumps(document))
|
|
94
|
+
assert batch.to_dict() == document
|
|
95
|
+
assert batch.media_mode == 'download'
|
|
96
|
+
for row in batch.messages:
|
|
97
|
+
if row['media'] is None or not row['media']['downloadable']:
|
|
98
|
+
continue
|
|
99
|
+
blob = row['media']['blob']
|
|
100
|
+
assert blob['path'] == blob['sha256'] and not Path(blob['path']).is_absolute()
|
|
101
|
+
data = (root / blob['path']).read_bytes()
|
|
102
|
+
assert len(data) == blob['size']
|
|
103
|
+
assert hashlib.sha256(data).hexdigest() == blob['sha256']
|
|
104
|
+
assert not list(root.glob('.tgdata-media-*'))
|
|
105
|
+
return batch
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def test_default_false_matches_omission_without_directory_io():
|
|
109
|
+
async with f.Setup() as s:
|
|
110
|
+
item = s.items[111];configure_media(item)
|
|
111
|
+
first, _ = await s.call(**params(None))
|
|
112
|
+
root = enable(s)
|
|
113
|
+
omitted, _ = await s.call(**params(None))
|
|
114
|
+
explicit, _ = await s.call(**params(False))
|
|
115
|
+
assert first['data'] == omitted['data'] == explicit['data']
|
|
116
|
+
assert first['data']['media_mode'] == 'references'
|
|
117
|
+
assert not root.exists() and not item.file_requests
|
|
118
|
+
assert s.job(**params(False)).options() == s.job(**params(None)).options()
|
|
119
|
+
assert all(c._sender.closed for c in item.clients)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def test_strict_switch_and_job_path_refusal():
|
|
123
|
+
async with f.Setup() as s:
|
|
124
|
+
enable(s)
|
|
125
|
+
cases = [params(v) for v in (0, 1, 'true', '', None, [], {})]
|
|
126
|
+
cases[4]['download_media'] = None
|
|
127
|
+
cases += [dict(params(), **{name: f.SECRET}) for name in
|
|
128
|
+
('media_directory', 'download_media_to', 'path', 'output_path')]
|
|
129
|
+
for options in cases:
|
|
130
|
+
try:s.job(**options)
|
|
131
|
+
except wire.WorkerError as error:
|
|
132
|
+
assert error.code == 'invalid_parameters'
|
|
133
|
+
assert f.SECRET not in json.dumps(s.worker.refusal(error))
|
|
134
|
+
else:raise AssertionError('Invalid job accepted')
|
|
135
|
+
for verb in ('lookup_group', 'check_group_access', 'join_group'):
|
|
136
|
+
try:s.job(verb, target='@synthetic_room', download_media=True)
|
|
137
|
+
except wire.WorkerError as error:assert error.code == 'invalid_parameters'
|
|
138
|
+
else:raise AssertionError('Other verb accepted media')
|
|
139
|
+
assert not s.items[111].clients and s.budget.status(111).used == 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
async def test_media_disabled_before_source_then_default_still_works():
|
|
143
|
+
async with f.Setup() as s:
|
|
144
|
+
value, events = await s.call(**params())
|
|
145
|
+
assert value['error']['code'] == 'media_disabled' and not events
|
|
146
|
+
assert not s.items[111].clients and s.budget.status(111).used == 0
|
|
147
|
+
assert not s.worker.stopping
|
|
148
|
+
assert (await s.call())[0]['ok']
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
async def test_native_photo_video_files_hashes_and_distinct_batch_identity():
|
|
152
|
+
async with f.Setup() as s:
|
|
153
|
+
root = enable(s);item=s.items[111];configure_media(item)
|
|
154
|
+
reference, _ = await s.call(**params(False))
|
|
155
|
+
result, events = await s.call(**params())
|
|
156
|
+
assert result['ok'] and not events
|
|
157
|
+
batch = check_files(root,result['data'])
|
|
158
|
+
assert batch.next_after_id == 102 and len(batch.messages)==2
|
|
159
|
+
assert [m['media']['kind'] for m in batch.messages] == ['photo','video']
|
|
160
|
+
assert batch.batch_id != reference['data']['batch_id']
|
|
161
|
+
assert s.budget.status(111).used == 4 # File bytes do not consume message allowance.
|
|
162
|
+
assert str(root) not in json.dumps(result)
|
|
163
|
+
assert item.clients[-1]._sender.closed
|
|
164
|
+
assert item.clients[-1]._sender.policy_at_connect['flood'] == 0
|
|
165
|
+
assert [x[0] for x in item.file_requests] == sorted(x[0] for x in item.file_requests)
|
|
166
|
+
assert len(item.file_requests)>2 # Real native multi-chunk video path.
|
|
167
|
+
again, _ = await s.call(**params())
|
|
168
|
+
assert again['data']==result['data'] and len(list(root.iterdir()))==2
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
async def test_download_failure_keeps_only_completed_prefix():
|
|
172
|
+
async with f.Setup() as s:
|
|
173
|
+
root=enable(s);item=s.items[111];configure_media(item);item.fail_asset=ASSET_VIDEO
|
|
174
|
+
value, events=await s.call(**params())
|
|
175
|
+
assert not value['ok'] and value['error']['wait_seconds']==30
|
|
176
|
+
batch=check_files(root,value['partial_result'])
|
|
177
|
+
assert batch.next_after_id==101 and len(batch.messages)==1 and batch.stop_reason=='interrupted'
|
|
178
|
+
assert len(list(root.iterdir()))==1 and s.budget.status(111).used==2
|
|
179
|
+
assert item.clients[-1]._sender.closed and not s.worker.stopping
|
|
180
|
+
assert all(e['account_id']=='111' for e in events)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
async def test_local_publication_failure_preserves_prefix_and_health():
|
|
184
|
+
async with f.Setup() as s:
|
|
185
|
+
root=enable(s);configure_media(s.items[111]);original=batch_files.os.link
|
|
186
|
+
calls=[]
|
|
187
|
+
def link(source,destination):
|
|
188
|
+
calls.append(destination)
|
|
189
|
+
if len(calls)==2:raise OSError(f.SECRET)
|
|
190
|
+
return original(source,destination)
|
|
191
|
+
with patch.object(batch_files.os,'link',link):value,events=await s.call(**params())
|
|
192
|
+
assert not value['ok'] and value['error']['type']=='OSError' and not events
|
|
193
|
+
assert check_files(root,value['partial_result']).next_after_id==101
|
|
194
|
+
assert len(list(root.iterdir()))==1
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def test_corrupt_existing_blob_refuses_without_overwrite():
|
|
198
|
+
async with f.Setup() as s:
|
|
199
|
+
root=enable(s);configure_media(s.items[111]);root.mkdir()
|
|
200
|
+
name=hashlib.sha256(PHOTO).hexdigest();(root/name).write_bytes(b'corrupt')
|
|
201
|
+
value,events=await s.call(**params())
|
|
202
|
+
assert value['error']['type']=='BatchStorageError' and not events
|
|
203
|
+
assert value['partial_result']['next_after_id']=='100'
|
|
204
|
+
assert (root/name).read_bytes()==b'corrupt' and not list(root.glob('.tgdata-media-*'))
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
async def test_reference_refresh_retains_message_budget():
|
|
208
|
+
async with f.Setup() as s:
|
|
209
|
+
root=enable(s);item=s.items[111];configure_media(item)
|
|
210
|
+
item.scripts['GetHistoryRequest']=[f.b.f.response([media_messages()[1]])]
|
|
211
|
+
item.fail_asset=ASSET_VIDEO;item.file_error=errors.FileReferenceExpiredError(request=None)
|
|
212
|
+
s.budget.configure(111,1)
|
|
213
|
+
value,events=await s.call(**dict(params(),limit=1))
|
|
214
|
+
assert value['error']['type']=='ReadBudgetExceeded' and not events
|
|
215
|
+
assert value['partial_result']['next_after_id']=='100' and s.budget.status(111).used==1
|
|
216
|
+
assert not list(root.iterdir())
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
async def test_result_delivery_failure_retains_complete_files():
|
|
220
|
+
async with f.Setup() as s:
|
|
221
|
+
root=enable(s);configure_media(s.items[111]);original=wire.encode_frame
|
|
222
|
+
def fail(frame,**kw):
|
|
223
|
+
if frame.get('kind')=='result' and frame.get('ok'):raise ValueError(f.SECRET)
|
|
224
|
+
return original(frame,**kw)
|
|
225
|
+
with patch.object(wire,'encode_frame',fail):value,events=await s.call(**params())
|
|
226
|
+
assert value['error']['code']=='delivery_failed' and value['worker_stopping'] and not events
|
|
227
|
+
assert value['source_outcome']=='returned' and value['partial_omitted']
|
|
228
|
+
assert {p.name for p in root.iterdir()}=={hashlib.sha256(x).hexdigest() for x in (PHOTO,VIDEO)}
|
|
229
|
+
assert s.items[111].clients[-1]._sender.closed
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
async def test_cancelled_download_settles_existing_cleanup():
|
|
233
|
+
async with f.Setup() as s:
|
|
234
|
+
root=enable(s);item=s.items[111];configure_media(item)
|
|
235
|
+
item.file_pending=asyncio.get_running_loop().create_future();item.close_release=asyncio.Event()
|
|
236
|
+
task=asyncio.create_task(s.worker.execute(s.job(**params())))
|
|
237
|
+
await f.until(lambda:bool(item.file_requests))
|
|
238
|
+
sender=item.clients[-1]._sender
|
|
239
|
+
assert list(root.glob('.tgdata-media-*'))
|
|
240
|
+
task.cancel();await sender.close_entered.wait();task.cancel();await asyncio.sleep(0)
|
|
241
|
+
assert not task.done() and not sender.closed and not list(root.iterdir())
|
|
242
|
+
item.close_release.set();await f.expect(asyncio.CancelledError,task)
|
|
243
|
+
assert sender.closed and item.file_pending.cancelled() and s.worker.stopping
|
|
244
|
+
# Observe before Setup's safety teardown; this is a primary sender path.
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
async def test_cleanup_failure_keeps_completed_media_and_stops_worker():
|
|
248
|
+
async with f.Setup() as s:
|
|
249
|
+
root=enable(s);item=s.items[111];configure_media(item);item.close_error=OSError(f.SECRET)
|
|
250
|
+
value,_=await s.call(**params())
|
|
251
|
+
assert value['ok'] and value['worker_stopping'];check_files(root,value['data'])
|
|
252
|
+
assert not item.clients[-1]._sender.closed
|
|
253
|
+
assert (await f.expect(wire.WorkerError,s.worker.execute(s.job(account=222)))).code=='worker_stopping'
|
|
254
|
+
assert not s.items[222].clients
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
async def test_directory_normalization_validation_and_lazy_creation():
|
|
258
|
+
async with f.Setup() as s:
|
|
259
|
+
file=s.root/'file';file.write_text('untouched')
|
|
260
|
+
for bad in ('',False,1,b'bytes',':memory:','file:///tmp/media','bad\x00path',file):
|
|
261
|
+
try:enable(s,bad)
|
|
262
|
+
except wire.WorkerError as e:
|
|
263
|
+
assert e.code=='invalid_config' and e.field=='media_directory'
|
|
264
|
+
else:raise AssertionError('Bad trusted root accepted')
|
|
265
|
+
root=enable(s,s.root/'new'/'nested');assert not root.exists()
|
|
266
|
+
configure_media(s.items[111]);value,_=await s.call(**params());check_files(root,value['data'])
|
|
267
|
+
assert file.read_text()=='untouched'
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
async def test_python_root_is_pinned_before_working_directory_changes():
|
|
271
|
+
async with f.Setup() as s:
|
|
272
|
+
previous=Path.cwd()
|
|
273
|
+
try:
|
|
274
|
+
os.chdir(s.root)
|
|
275
|
+
root=enable(s,Path('python-media'))
|
|
276
|
+
os.chdir(previous)
|
|
277
|
+
configure_media(s.items[111])
|
|
278
|
+
value,_=await s.call(**params())
|
|
279
|
+
assert root==(s.root/'python-media').resolve()
|
|
280
|
+
check_files(root,value['data'])
|
|
281
|
+
finally:
|
|
282
|
+
os.chdir(previous)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def child(root,mode):
|
|
286
|
+
root=Path(root);item=f.fixture(root,111);configure_media(item)
|
|
287
|
+
if mode=='partial':item.fail_asset=ASSET_VIDEO
|
|
288
|
+
def trace(kind,detail):
|
|
289
|
+
with (root/'trace.jsonl').open('a') as out:out.write(json.dumps([kind,detail])+'\n')
|
|
290
|
+
item.trace=trace
|
|
291
|
+
with patch.object(socket.socket,'connect',side_effect=AssertionError('no network')), \
|
|
292
|
+
patch.object(socket.socket,'connect_ex',side_effect=AssertionError('no network')), \
|
|
293
|
+
f.install_factory({111:item}):
|
|
294
|
+
code=worker.main(['--config',str(root/'worker.json')])
|
|
295
|
+
# Assert before any fixture-driven cleanup, after actual driver shutdown.
|
|
296
|
+
assert all(c._sender.closed for c in item.clients)
|
|
297
|
+
return code
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def test_cli_config_jobs_files_and_partial_results():
|
|
301
|
+
for mode in ('normal','partial','disabled','path','default','null','invalid-root'):
|
|
302
|
+
with tempfile.TemporaryDirectory(prefix='worker_media_process_') as tmp:
|
|
303
|
+
root=Path(tmp);f.fixture(root,111)
|
|
304
|
+
budget=ReadBudget(root/'read.sqlite3');budget.configure(111,20)
|
|
305
|
+
manifest=dict(version=1,worker_id='media-test',read_budget='read.sqlite3',
|
|
306
|
+
accounts=[dict(account_id='111',config_path='account-111.ini')])
|
|
307
|
+
if mode not in ('disabled','null'):manifest['media_directory']='out/nested'
|
|
308
|
+
if mode=='null':manifest['media_directory']=None
|
|
309
|
+
if mode=='invalid-root':
|
|
310
|
+
(root/'not-dir').write_text('keep');manifest['media_directory']='not-dir'
|
|
311
|
+
(root/'worker.json').write_text(json.dumps(manifest))
|
|
312
|
+
options=params(False if mode=='default' else True)
|
|
313
|
+
if mode=='path':options['download_media_to']=f.SECRET
|
|
314
|
+
raw=(json.dumps(dict(version=1,request_id=1,account_id='111',operation='read_batch',params=options))+'\n').encode()
|
|
315
|
+
command=[sys.executable,'-m','tgdata.smoke_tests.test_49_worker_media','--child',str(root),mode]
|
|
316
|
+
run=subprocess.run(command,cwd='/',env=dict(os.environ,PYTHONPATH=str(ROOT)),input=raw,capture_output=True,timeout=20)
|
|
317
|
+
assert not run.stderr,run.stderr.decode(errors='replace')
|
|
318
|
+
assert f.SECRET.encode() not in run.stdout
|
|
319
|
+
frames=[json.loads(line) for line in run.stdout.splitlines()];value=frames[-1]
|
|
320
|
+
out=root/'out'/'nested'
|
|
321
|
+
if mode=='invalid-root':
|
|
322
|
+
assert run.returncode==2 and value['kind']=='fatal' and value['error']['field']=='media_directory'
|
|
323
|
+
else:
|
|
324
|
+
assert run.returncode==0 and frames[0]['kind']=='ready'
|
|
325
|
+
if mode in ('disabled','null','path'):
|
|
326
|
+
assert value['error']['code']==('invalid_parameters' if mode=='path' else 'media_disabled')
|
|
327
|
+
assert not (root/'trace.jsonl').exists() and budget.status(111).used==0
|
|
328
|
+
elif mode=='default':assert value['data']['media_mode']=='references'
|
|
329
|
+
else:
|
|
330
|
+
batch=check_files(out,value['partial_result'] if mode=='partial' else value['data'])
|
|
331
|
+
assert batch.next_after_id==(101 if mode=='partial' else 102)
|
|
332
|
+
if mode not in ('normal','partial'):assert not out.exists()
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def test_manifest_invalid_root_types_are_sanitized():
|
|
336
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
337
|
+
root=Path(tmp);ReadBudget(root/'r.db')
|
|
338
|
+
for bad in ('',True,3,[],{},'file:/private','bad\x00path'):
|
|
339
|
+
config=root/'worker.json';config.write_text(json.dumps(dict(version=1,worker_id='w',
|
|
340
|
+
read_budget='r.db',accounts=[],media_directory=bad)))
|
|
341
|
+
try:Worker(**worker.load_inventory(config))
|
|
342
|
+
except wire.WorkerError as e:assert e.code=='invalid_config' and e.field=='media_directory'
|
|
343
|
+
else:raise AssertionError('Invalid manifest root accepted')
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def test_example_rejects_media_on_other_verbs_before_process():
|
|
347
|
+
run=subprocess.run([sys.executable,str(ROOT/'examples/reading_worker.py'),'--config','missing.json',
|
|
348
|
+
'--account','111','--target','@room','--operation','lookup_group','--download-media'],capture_output=True)
|
|
349
|
+
assert run.returncode==2 and b'only valid with read_batch' in run.stderr and not run.stdout
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def main():
|
|
353
|
+
tests=[f for n,f in globals().items() if n.startswith('test_')];passed=0
|
|
354
|
+
with patch.object(socket.socket,'connect',side_effect=AssertionError('network forbidden')), \
|
|
355
|
+
patch.object(socket.socket,'connect_ex',side_effect=AssertionError('network forbidden')):
|
|
356
|
+
for test in tests:
|
|
357
|
+
try:
|
|
358
|
+
if inspect.iscoroutinefunction(test):asyncio.run(asyncio.wait_for(test(),30))
|
|
359
|
+
else:test()
|
|
360
|
+
print('PASS',test.__name__,flush=True);passed+=1
|
|
361
|
+
except Exception:traceback.print_exc();print('FAIL',test.__name__,flush=True)
|
|
362
|
+
print('Passed: {}/{}'.format(passed,len(tests)),flush=True)
|
|
363
|
+
return int(passed!=len(tests))
|
|
364
|
+
|
|
365
|
+
if __name__=='__main__':
|
|
366
|
+
logging.disable(logging.CRITICAL)
|
|
367
|
+
if len(sys.argv)>1 and sys.argv[1]=='--child':raise SystemExit(child(sys.argv[2],sys.argv[3]))
|
|
368
|
+
raise SystemExit(main())
|
|
@@ -50,7 +50,7 @@ def load_inventory(path):
|
|
|
50
50
|
value = wire.decode_json(raw)
|
|
51
51
|
required = {'version', 'worker_id', 'read_budget', 'accounts'}
|
|
52
52
|
if (type(value) is not dict or not required <= set(value)
|
|
53
|
-
or not set(value) <= required | {'join_budget'}
|
|
53
|
+
or not set(value) <= required | {'join_budget', 'media_directory'}
|
|
54
54
|
or type(value['version']) is not int or value['version'] != wire.VERSION):
|
|
55
55
|
raise wire.WorkerError('invalid_config')
|
|
56
56
|
rows = value['accounts']
|
|
@@ -69,7 +69,11 @@ def load_inventory(path):
|
|
|
69
69
|
join = None
|
|
70
70
|
if value.get('join_budget') is not None:
|
|
71
71
|
join = JoinBudget(_path(value['join_budget'], path.parent, 'join_budget'), create=False)
|
|
72
|
-
|
|
72
|
+
options = dict(accounts=accounts, worker_id=value['worker_id'], read_budget=budget, join_budget=join)
|
|
73
|
+
if value.get('media_directory') is not None:
|
|
74
|
+
options['media_directory'] = _path(value['media_directory'], path.parent,
|
|
75
|
+
'media_directory', must_exist=False)
|
|
76
|
+
return options
|
|
73
77
|
|
|
74
78
|
|
|
75
79
|
def _raw_output(stream):
|
|
@@ -102,7 +106,7 @@ def _fatal(error, output, category='configuration_error'):
|
|
|
102
106
|
|
|
103
107
|
|
|
104
108
|
def serve(accounts, *, worker_id, read_budget, join_budget=None,
|
|
105
|
-
input_stream=None, output_stream=None):
|
|
109
|
+
media_directory=None, input_stream=None, output_stream=None):
|
|
106
110
|
"""Run in a dedicated process's main thread and return its exit code.
|
|
107
111
|
|
|
108
112
|
A Python bootstrap can supply trusted session stores via WorkerAccount.
|
|
@@ -153,7 +157,8 @@ def serve(accounts, *, worker_id, read_budget, join_budget=None,
|
|
|
153
157
|
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
154
158
|
handlers[sig] = signal.getsignal(sig)
|
|
155
159
|
signal.signal(sig, stop)
|
|
156
|
-
worker = Worker(accounts, worker_id=worker_id, read_budget=read_budget,
|
|
160
|
+
worker = Worker(accounts, worker_id=worker_id, read_budget=read_budget,
|
|
161
|
+
join_budget=join_budget, media_directory=media_directory)
|
|
157
162
|
loop = asyncio.new_event_loop()
|
|
158
163
|
asyncio.set_event_loop(loop)
|
|
159
164
|
decoder = wire.RequestDecoder()
|
|
@@ -24,6 +24,23 @@ from . import worker_protocol as wire
|
|
|
24
24
|
_CURRENT_JOB = contextvars.ContextVar('tgdata_worker_job', default=None)
|
|
25
25
|
|
|
26
26
|
|
|
27
|
+
def _media_root(value):
|
|
28
|
+
"""Pin trusted configuration without creating output for reference-only jobs."""
|
|
29
|
+
if value is None:
|
|
30
|
+
return None
|
|
31
|
+
try:
|
|
32
|
+
text = os.fspath(value)
|
|
33
|
+
if (type(text) is not str or not text or '\x00' in text
|
|
34
|
+
or text == ':memory:' or text.lower().startswith('file:')):
|
|
35
|
+
raise ValueError
|
|
36
|
+
root = Path(text).expanduser().resolve()
|
|
37
|
+
if root.exists() and not root.is_dir():
|
|
38
|
+
raise ValueError
|
|
39
|
+
return root
|
|
40
|
+
except (TypeError, ValueError, OSError, RuntimeError):
|
|
41
|
+
raise wire.WorkerError('invalid_config', field='media_directory') from None
|
|
42
|
+
|
|
43
|
+
|
|
27
44
|
@dataclass(frozen=True)
|
|
28
45
|
class WorkerAccount:
|
|
29
46
|
account_id: int
|
|
@@ -87,7 +104,8 @@ class Worker:
|
|
|
87
104
|
exclusively assigned for the lifetime of that process.
|
|
88
105
|
"""
|
|
89
106
|
|
|
90
|
-
def __init__(self, accounts, *, worker_id, read_budget, join_budget=None
|
|
107
|
+
def __init__(self, accounts, *, worker_id, read_budget, join_budget=None,
|
|
108
|
+
media_directory=None):
|
|
91
109
|
if telethon.__version__ != '1.45.0':
|
|
92
110
|
raise wire.WorkerError('unsupported_sdk')
|
|
93
111
|
if type(worker_id) is not str or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,63}', worker_id):
|
|
@@ -96,6 +114,7 @@ class Worker:
|
|
|
96
114
|
raise wire.WorkerError('invalid_config', field='read_budget')
|
|
97
115
|
if join_budget is not None and not isinstance(join_budget, JoinBudget):
|
|
98
116
|
raise wire.WorkerError('invalid_config', field='join_budget')
|
|
117
|
+
self._media_directory = _media_root(media_directory)
|
|
99
118
|
try:
|
|
100
119
|
accounts = tuple(accounts)
|
|
101
120
|
except TypeError:
|
|
@@ -163,6 +182,10 @@ class Worker:
|
|
|
163
182
|
return frame
|
|
164
183
|
|
|
165
184
|
async def _read(self, app, job, options):
|
|
185
|
+
if options.pop('download_media', False):
|
|
186
|
+
if self._media_directory is None:
|
|
187
|
+
raise wire.WorkerError('media_disabled')
|
|
188
|
+
options['download_media_to'] = self._media_directory
|
|
166
189
|
target = _parse_target(options.pop('group_id'))
|
|
167
190
|
async with app._account_health_operation(
|
|
168
191
|
job.account_id, 'worker_read_batch', target.label) as (operation, observation):
|
|
@@ -38,13 +38,13 @@ _CANONICAL_AUTH_REASONS = frozenset(
|
|
|
38
38
|
|
|
39
39
|
_CODES = frozenset(('invalid_json', 'invalid_envelope', 'invalid_request_id',
|
|
40
40
|
'stale_request_id', 'unknown_account', 'unknown_operation', 'invalid_parameters',
|
|
41
|
-
'join_disabled', 'invalid_config', 'worker_busy', 'worker_stopping',
|
|
41
|
+
'join_disabled', 'media_disabled', 'invalid_config', 'worker_busy', 'worker_stopping',
|
|
42
42
|
'delivery_failed', 'frame_too_large', 'incomplete_frame', 'input_failure',
|
|
43
43
|
'output_failure', 'unsupported_sdk'))
|
|
44
44
|
_FIELDS = frozenset(('version', 'request_id', 'account_id', 'operation', 'params',
|
|
45
45
|
'group_id', 'target', 'after_id', 'limit', 'start_date', 'end_date', 'worker_id',
|
|
46
46
|
'accounts', 'config_path', 'session_store', 'label', 'read_budget', 'join_budget',
|
|
47
|
-
'session', 'input', 'output'))
|
|
47
|
+
'session', 'input', 'output', 'download_media', 'media_directory'))
|
|
48
48
|
_IDS = frozenset(('id', 'peer_id', 'user_id', 'account_id', 'expected_account_id',
|
|
49
49
|
'actual_account_id', 'bot_id', 'query_id', 'target', 'group'))
|
|
50
50
|
_DECIMAL = re.compile(r'-?(?:0|[1-9][0-9]*)\Z')
|
|
@@ -130,9 +130,12 @@ def _parameters(operation, params):
|
|
|
130
130
|
raise WorkerError('invalid_parameters', field='params')
|
|
131
131
|
_parse_target(params['target'])
|
|
132
132
|
return (('target', params['target']),)
|
|
133
|
-
allowed = {'group_id', 'after_id', 'limit', 'start_date', 'end_date'}
|
|
133
|
+
allowed = {'group_id', 'after_id', 'limit', 'start_date', 'end_date', 'download_media'}
|
|
134
134
|
if 'group_id' not in params or not set(params) <= allowed:
|
|
135
135
|
raise WorkerError('invalid_parameters', field='params')
|
|
136
|
+
media = params.get('download_media', False)
|
|
137
|
+
if type(media) is not bool:
|
|
138
|
+
raise WorkerError('invalid_parameters', field='download_media')
|
|
136
139
|
target = params['group_id']
|
|
137
140
|
_parse_target(target)
|
|
138
141
|
after = canonical_id(params.get('after_id', '0'), 0, MAX_MESSAGE_ID, 'after_id')
|
|
@@ -141,8 +144,11 @@ def _parameters(operation, params):
|
|
|
141
144
|
raise WorkerError('invalid_parameters', field='limit')
|
|
142
145
|
start, end = (_date(params.get(name), name) for name in ('start_date', 'end_date'))
|
|
143
146
|
_HistoryWindow.from_dates(start, end)
|
|
144
|
-
|
|
145
|
-
|
|
147
|
+
options = dict(group_id=target, after_id=after, limit=limit,
|
|
148
|
+
start_date=start, end_date=end)
|
|
149
|
+
if media:
|
|
150
|
+
options['download_media'] = True
|
|
151
|
+
return tuple(options.items())
|
|
146
152
|
|
|
147
153
|
|
|
148
154
|
class RequestDecoder:
|
|
@@ -105,6 +105,7 @@ tgdata/smoke_tests/test_44_batch_heartbeat.py
|
|
|
105
105
|
tgdata/smoke_tests/test_45_group_profile.py
|
|
106
106
|
tgdata/smoke_tests/test_46_group_activity.py
|
|
107
107
|
tgdata/smoke_tests/test_48_terminal_login.py
|
|
108
|
+
tgdata/smoke_tests/test_49_worker_media.py
|
|
108
109
|
tgdata/smoke_tests/test_debug_min_id.py
|
|
109
110
|
tgdata/smoke_tests/test_polling_debug.py
|
|
110
111
|
tgdata/smoke_tests/test_username_support.py
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|