tgdata 0.1.3__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.
Files changed (113) hide show
  1. {tgdata-0.1.3 → tgdata-0.1.4}/PKG-INFO +1 -1
  2. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/__init__.py +1 -1
  3. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_42_album_assembly.py +1 -1
  4. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_43_photo_trails.py +1 -1
  5. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_45_group_profile.py +1 -1
  6. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_46_group_activity.py +1 -1
  7. tgdata-0.1.4/tgdata/smoke_tests/test_49_worker_media.py +368 -0
  8. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/worker.py +9 -4
  9. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/worker_engine.py +24 -1
  10. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/worker_protocol.py +11 -5
  11. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata.egg-info/PKG-INFO +1 -1
  12. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata.egg-info/SOURCES.txt +1 -0
  13. {tgdata-0.1.3 → tgdata-0.1.4}/README.md +0 -0
  14. {tgdata-0.1.3 → tgdata-0.1.4}/setup.cfg +0 -0
  15. {tgdata-0.1.3 → tgdata-0.1.4}/setup.py +0 -0
  16. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/_terminal_input.py +0 -0
  17. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/account_operation.py +0 -0
  18. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/account_pool.py +0 -0
  19. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/album.py +0 -0
  20. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/backfill.py +0 -0
  21. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/backfill_engine.py +0 -0
  22. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/backfill_state.py +0 -0
  23. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/batch_engine.py +0 -0
  24. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/batch_files.py +0 -0
  25. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/batch_heartbeat.py +0 -0
  26. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/budget_client.py +0 -0
  27. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/connection_engine.py +0 -0
  28. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/discovery_engine.py +0 -0
  29. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/group_activity.py +0 -0
  30. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/group_operations.py +0 -0
  31. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/group_profile.py +0 -0
  32. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/health.py +0 -0
  33. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/history_window.py +0 -0
  34. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/join_budget.py +0 -0
  35. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/join_client.py +0 -0
  36. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/login.py +0 -0
  37. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/login_cli.py +0 -0
  38. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/login_file.py +0 -0
  39. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/message_batch.py +0 -0
  40. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/message_engine.py +0 -0
  41. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/models.py +0 -0
  42. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/owned_health.py +0 -0
  43. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/photo_trails.py +0 -0
  44. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/pool_lifecycle.py +0 -0
  45. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/pool_observation.py +0 -0
  46. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/pool_result.py +0 -0
  47. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/pool_source.py +0 -0
  48. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/pool_state.py +0 -0
  49. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/progress.py +0 -0
  50. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/progress_facade.py +0 -0
  51. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/read_budget.py +0 -0
  52. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/session_store.py +0 -0
  53. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/__init__.py +0 -0
  54. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_framing.py +0 -0
  55. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_handoffs.py +0 -0
  56. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_modes.py +0 -0
  57. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/_terminal_login_observer.py +0 -0
  58. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/my_test.py +0 -0
  59. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/pool_storage_cases.py +0 -0
  60. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_00_connection.py +0 -0
  61. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_01_list_group_chats.py +0 -0
  62. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_02_get_message_count.py +0 -0
  63. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_03_get_all_messages.py +0 -0
  64. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_04_get_all_messages_in_batches.py +0 -0
  65. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_05_with_progress_feature.py +0 -0
  66. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_06_polling_simple.py +0 -0
  67. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_07_on_new_message_simple.py +0 -0
  68. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_07_real_time_event_handler.py +0 -0
  69. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_08_batch_callback.py +0 -0
  70. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_08_polling.py +0 -0
  71. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_10_advanced_features.py +0 -0
  72. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_11_discover_groups.py +0 -0
  73. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_12_proxy.py +0 -0
  74. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_13_device_identity.py +0 -0
  75. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_14_flood_threshold.py +0 -0
  76. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_15_login_checks.py +0 -0
  77. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_16_health_events.py +0 -0
  78. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_17_session_store.py +0 -0
  79. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_18_read_budget.py +0 -0
  80. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_19_message_batches.py +0 -0
  81. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_22_daily_continuation.py +0 -0
  82. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_23_fixed_windows.py +0 -0
  83. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_24_backfill_state.py +0 -0
  84. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_25_backfill_delivery.py +0 -0
  85. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_26_backfill_completion.py +0 -0
  86. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_27_backfill_pacing.py +0 -0
  87. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_28_backfill_controls.py +0 -0
  88. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_29_backfill_public.py +0 -0
  89. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_30_backfill_integration.py +0 -0
  90. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_31_account_pool.py +0 -0
  91. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_32_account_operation.py +0 -0
  92. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_33_owned_health.py +0 -0
  93. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_34_group_access.py +0 -0
  94. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_35_join_budget.py +0 -0
  95. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_36_group_join.py +0 -0
  96. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_37_worker.py +0 -0
  97. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_38_worker_process.py +0 -0
  98. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_39_pool_lifecycle.py +0 -0
  99. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_40_pool_outcomes.py +0 -0
  100. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_41_stepwise_login.py +0 -0
  101. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_44_batch_heartbeat.py +0 -0
  102. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_48_terminal_login.py +0 -0
  103. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_debug_min_id.py +0 -0
  104. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_polling_debug.py +0 -0
  105. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/smoke_tests/test_username_support.py +0 -0
  106. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/sync_engine.py +0 -0
  107. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/sync_store.py +0 -0
  108. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/tgdata.py +0 -0
  109. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata/utils.py +0 -0
  110. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata.egg-info/dependency_links.txt +0 -0
  111. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata.egg-info/entry_points.txt +0 -0
  112. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata.egg-info/requires.txt +0 -0
  113. {tgdata-0.1.3 → tgdata-0.1.4}/tgdata.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tgdata
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: A production-grade Python library for extracting and processing Telegram group and channel messages
5
5
  Author: enes kuzucu
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -74,7 +74,7 @@ from .utils import (
74
74
  # Progress tracking
75
75
  from .progress import ProgressTracker
76
76
 
77
- __version__ = "0.1.3"
77
+ __version__ = "0.1.4"
78
78
 
79
79
  __all__ = [
80
80
  # Explicit account onboarding
@@ -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.3')
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.3')
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.3'
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.3' and len(set(tgdata.__all__)) == len(tgdata.__all__)
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()
@@ -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
- return dict(accounts=accounts, worker_id=value['worker_id'], read_budget=budget, join_budget=join)
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, join_budget=join_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
- return tuple(dict(group_id=target, after_id=after, limit=limit,
145
- start_date=start, end_date=end).items())
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:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tgdata
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: A production-grade Python library for extracting and processing Telegram group and channel messages
5
5
  Author: enes kuzucu
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -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