tgdata 0.1__tar.gz → 0.1.2__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 (112) hide show
  1. {tgdata-0.1 → tgdata-0.1.2}/PKG-INFO +112 -3
  2. {tgdata-0.1 → tgdata-0.1.2}/README.md +111 -2
  3. {tgdata-0.1 → tgdata-0.1.2}/setup.py +4 -1
  4. {tgdata-0.1 → tgdata-0.1.2}/tgdata/__init__.py +13 -1
  5. tgdata-0.1.2/tgdata/_terminal_input.py +216 -0
  6. {tgdata-0.1 → tgdata-0.1.2}/tgdata/account_pool.py +16 -12
  7. tgdata-0.1.2/tgdata/album.py +246 -0
  8. {tgdata-0.1 → tgdata-0.1.2}/tgdata/backfill_engine.py +5 -2
  9. {tgdata-0.1 → tgdata-0.1.2}/tgdata/batch_engine.py +19 -3
  10. tgdata-0.1.2/tgdata/batch_heartbeat.py +150 -0
  11. {tgdata-0.1 → tgdata-0.1.2}/tgdata/connection_engine.py +5 -4
  12. tgdata-0.1.2/tgdata/group_activity.py +313 -0
  13. tgdata-0.1.2/tgdata/group_profile.py +188 -0
  14. tgdata-0.1.2/tgdata/login_cli.py +359 -0
  15. tgdata-0.1.2/tgdata/login_file.py +306 -0
  16. tgdata-0.1.2/tgdata/photo_trails.py +393 -0
  17. {tgdata-0.1 → tgdata-0.1.2}/tgdata/progress_facade.py +9 -4
  18. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_framing.py +176 -0
  19. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_handoffs.py +95 -0
  20. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_modes.py +334 -0
  21. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_observer.py +76 -0
  22. tgdata-0.1.2/tgdata/smoke_tests/test_42_album_assembly.py +951 -0
  23. tgdata-0.1.2/tgdata/smoke_tests/test_43_photo_trails.py +695 -0
  24. tgdata-0.1.2/tgdata/smoke_tests/test_44_batch_heartbeat.py +451 -0
  25. tgdata-0.1.2/tgdata/smoke_tests/test_45_group_profile.py +557 -0
  26. tgdata-0.1.2/tgdata/smoke_tests/test_46_group_activity.py +523 -0
  27. tgdata-0.1.2/tgdata/smoke_tests/test_48_terminal_login.py +977 -0
  28. {tgdata-0.1 → tgdata-0.1.2}/tgdata/sync_engine.py +5 -2
  29. {tgdata-0.1 → tgdata-0.1.2}/tgdata/tgdata.py +50 -3
  30. {tgdata-0.1 → tgdata-0.1.2}/tgdata.egg-info/PKG-INFO +112 -3
  31. {tgdata-0.1 → tgdata-0.1.2}/tgdata.egg-info/SOURCES.txt +18 -0
  32. {tgdata-0.1 → tgdata-0.1.2}/tgdata.egg-info/entry_points.txt +1 -0
  33. {tgdata-0.1 → tgdata-0.1.2}/setup.cfg +0 -0
  34. {tgdata-0.1 → tgdata-0.1.2}/tgdata/account_operation.py +0 -0
  35. {tgdata-0.1 → tgdata-0.1.2}/tgdata/backfill.py +0 -0
  36. {tgdata-0.1 → tgdata-0.1.2}/tgdata/backfill_state.py +0 -0
  37. {tgdata-0.1 → tgdata-0.1.2}/tgdata/batch_files.py +0 -0
  38. {tgdata-0.1 → tgdata-0.1.2}/tgdata/budget_client.py +0 -0
  39. {tgdata-0.1 → tgdata-0.1.2}/tgdata/discovery_engine.py +0 -0
  40. {tgdata-0.1 → tgdata-0.1.2}/tgdata/group_operations.py +0 -0
  41. {tgdata-0.1 → tgdata-0.1.2}/tgdata/health.py +0 -0
  42. {tgdata-0.1 → tgdata-0.1.2}/tgdata/history_window.py +0 -0
  43. {tgdata-0.1 → tgdata-0.1.2}/tgdata/join_budget.py +0 -0
  44. {tgdata-0.1 → tgdata-0.1.2}/tgdata/join_client.py +0 -0
  45. {tgdata-0.1 → tgdata-0.1.2}/tgdata/login.py +0 -0
  46. {tgdata-0.1 → tgdata-0.1.2}/tgdata/message_batch.py +0 -0
  47. {tgdata-0.1 → tgdata-0.1.2}/tgdata/message_engine.py +0 -0
  48. {tgdata-0.1 → tgdata-0.1.2}/tgdata/models.py +0 -0
  49. {tgdata-0.1 → tgdata-0.1.2}/tgdata/owned_health.py +0 -0
  50. {tgdata-0.1 → tgdata-0.1.2}/tgdata/pool_lifecycle.py +0 -0
  51. {tgdata-0.1 → tgdata-0.1.2}/tgdata/pool_observation.py +0 -0
  52. {tgdata-0.1 → tgdata-0.1.2}/tgdata/pool_result.py +0 -0
  53. {tgdata-0.1 → tgdata-0.1.2}/tgdata/pool_source.py +0 -0
  54. {tgdata-0.1 → tgdata-0.1.2}/tgdata/pool_state.py +0 -0
  55. {tgdata-0.1 → tgdata-0.1.2}/tgdata/progress.py +0 -0
  56. {tgdata-0.1 → tgdata-0.1.2}/tgdata/read_budget.py +0 -0
  57. {tgdata-0.1 → tgdata-0.1.2}/tgdata/session_store.py +0 -0
  58. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/__init__.py +0 -0
  59. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/my_test.py +0 -0
  60. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/pool_storage_cases.py +0 -0
  61. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_00_connection.py +0 -0
  62. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_01_list_group_chats.py +0 -0
  63. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_02_get_message_count.py +0 -0
  64. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_03_get_all_messages.py +0 -0
  65. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_04_get_all_messages_in_batches.py +0 -0
  66. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_05_with_progress_feature.py +0 -0
  67. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_06_polling_simple.py +0 -0
  68. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_07_on_new_message_simple.py +0 -0
  69. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_07_real_time_event_handler.py +0 -0
  70. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_08_batch_callback.py +0 -0
  71. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_08_polling.py +0 -0
  72. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_10_advanced_features.py +0 -0
  73. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_11_discover_groups.py +0 -0
  74. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_12_proxy.py +0 -0
  75. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_13_device_identity.py +0 -0
  76. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_14_flood_threshold.py +0 -0
  77. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_15_login_checks.py +0 -0
  78. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_16_health_events.py +0 -0
  79. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_17_session_store.py +0 -0
  80. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_18_read_budget.py +0 -0
  81. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_19_message_batches.py +0 -0
  82. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_22_daily_continuation.py +0 -0
  83. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_23_fixed_windows.py +0 -0
  84. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_24_backfill_state.py +0 -0
  85. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_25_backfill_delivery.py +0 -0
  86. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_26_backfill_completion.py +0 -0
  87. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_27_backfill_pacing.py +0 -0
  88. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_28_backfill_controls.py +0 -0
  89. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_29_backfill_public.py +0 -0
  90. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_30_backfill_integration.py +0 -0
  91. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_31_account_pool.py +0 -0
  92. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_32_account_operation.py +0 -0
  93. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_33_owned_health.py +0 -0
  94. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_34_group_access.py +0 -0
  95. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_35_join_budget.py +0 -0
  96. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_36_group_join.py +0 -0
  97. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_37_worker.py +0 -0
  98. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_38_worker_process.py +0 -0
  99. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_39_pool_lifecycle.py +0 -0
  100. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_40_pool_outcomes.py +0 -0
  101. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_41_stepwise_login.py +0 -0
  102. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_debug_min_id.py +0 -0
  103. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_polling_debug.py +0 -0
  104. {tgdata-0.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_username_support.py +0 -0
  105. {tgdata-0.1 → tgdata-0.1.2}/tgdata/sync_store.py +0 -0
  106. {tgdata-0.1 → tgdata-0.1.2}/tgdata/utils.py +0 -0
  107. {tgdata-0.1 → tgdata-0.1.2}/tgdata/worker.py +0 -0
  108. {tgdata-0.1 → tgdata-0.1.2}/tgdata/worker_engine.py +0 -0
  109. {tgdata-0.1 → tgdata-0.1.2}/tgdata/worker_protocol.py +0 -0
  110. {tgdata-0.1 → tgdata-0.1.2}/tgdata.egg-info/dependency_links.txt +0 -0
  111. {tgdata-0.1 → tgdata-0.1.2}/tgdata.egg-info/requires.txt +0 -0
  112. {tgdata-0.1 → tgdata-0.1.2}/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
+ Version: 0.1.2
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
@@ -59,6 +59,8 @@ A production-grade Python library for extracting and processing Telegram group a
59
59
  - 🩺 **Account Health Events**: Every wait, logout, ban, restriction or lost group is reported as a plain-data event — through one callback, a log line and a per-account summary — and "ok" when it ends
60
60
  - **Per-account read budgets**: An optional shared SQLite ledger limits message pulls over a rolling 24 hours, with persistent warm-up steps and recoverable partial results
61
61
  - **Versioned message batches**: Read bounded raw snapshots with canonical JSON, replayable batch IDs, safe continuation cursors and optional content-addressed media
62
+ - **Album assembly across batches**: Combine observed album members into stable post revisions, preserving every caption and media reference with explicit caller-owned persistence
63
+ - **Optional photo trails**: Associate a user's following photo-only posts in a provisional view, retaining all originals and explicit heuristic provenance
62
64
  - **Durable daily continuation**: Keep per-group progress and pending batches in a pluggable store, replay after restart, and advance only after explicit acknowledgment
63
65
  - **Reading worker**: Run a serial process that accepts explicit-account JSON jobs for batches, group lookup, access checks and joining, with correlated health replies
64
66
 
@@ -116,6 +118,22 @@ keep working, but new configs should set `session_file` and omit `username`
116
118
 
117
119
  ### Logging in
118
120
 
121
+ For a deliberate terminal login that saves the configured native session, run:
122
+
123
+ ```bash
124
+ tgdata-login --config config.ini
125
+ # Re-login at an existing destination, with explicit replacement confirmation:
126
+ tgdata-login --config config.ini --replace
127
+ ```
128
+
129
+ The command reuses `LoginFlow`, hides phone/code/password input and saves a native
130
+ `.session` file for ordinary readers. Replacement requires stopped readers;
131
+ failed saves never trigger another code request automatically. See
132
+ [terminal login](docs/terminal_login.md) for destination rules, safe retry,
133
+ publication uncertainty, supported local POSIX filesystems and exit codes.
134
+
135
+ The existing reader's first-run login behavior also remains available:
136
+
119
137
  The first run of a new session, started by hand in a terminal, asks for the
120
138
  code Telegram sends you. After that, tgdata never asks Telegram for a login
121
139
  code on its own: before connecting it checks with Telegram whether the session
@@ -565,6 +583,33 @@ Numeric channel IDs need a cached access hash. Readability is distinct from memb
565
583
  and does not promise future access. See [the group-operations contract](docs/group_operations.md)
566
584
  for input rules, result fields, errors, budget costs and the known SDK cache limitation.
567
585
 
586
+ ### Richer group profiles
587
+
588
+ `await tg.get_group_profile("@example_group", account_id=expected_id, pinned_limit=5)`
589
+ returns the description, available member/online counts and a bounded pinned-message
590
+ observation. Pins default off; the explicit limit is 1–100 and uses the existing
591
+ read budget. Returned IDs/text/dates, coverage status, count accuracy and separate
592
+ observation times distinguish empty, limited, unavailable and failed reads.
593
+
594
+ The method verifies the account and closes its temporary client. Optional pin
595
+ failures raise their original error with completed metadata on `partial_result`
596
+ when supported. Profile success makes no general history-access claim. See
597
+ [group profiles](docs/group_profiles.md) for fields, errors and heartbeat support.
598
+
599
+ ### Activity and engagement measurement
600
+
601
+ `await tg.measure_group_activity("@example_group", account_id=expected_id,
602
+ start_date=start, end_date=end, max_messages=3000)` returns raw message observations,
603
+ daily activity, author counts and views/reactions/forwards/replies distributions.
604
+ Dates are explicit aware datetimes; the publication window includes start and excludes end.
605
+
606
+ Check `coverage_complete` and `stop_reason` before treating the result as a whole-window
607
+ measurement. The cap counts every source slot; missing counters remain distinct from
608
+ zero. Counters are observed at collection time, and albums count as raw messages.
609
+ The operation uses the existing verified account, read allowance, heartbeat and
610
+ cleanup policies. See [activity measurement](docs/group_activity.md) for the example,
611
+ precise populations, partial failures and visibility limits.
612
+
568
613
  ### Group discovery — finding groups you are not in
569
614
 
570
615
  `list_groups` shows what the account already follows. To find *new* rooms there are three
@@ -807,6 +852,70 @@ refuses cleanup may leave a private temporary file. The exact schema, limits,
807
852
  interruption rules
808
853
  and delivery protocol are in [Message batch v1](docs/message_batch_v1.md).
809
854
 
855
+ ### Albums across message batches
856
+
857
+ Use the opt-in assembler to keep one logical post as more album members arrive:
858
+
859
+ ```python
860
+ from tgdata import album_post_ids, assemble_albums
861
+
862
+ # In-memory illustration for a new collection; retain these posts across calls.
863
+ known_posts = {}
864
+ for batch in batches:
865
+ previous = {key: known_posts.get(key) for key in album_post_ids(batch)}
866
+ for post in assemble_albums(batch, previous=previous):
867
+ known_posts[post.post_id] = post
868
+ print(post.post_id, post.revision, post.member_ids)
869
+ ```
870
+
871
+ Album IDs include the chat; each post retains all original member records and
872
+ captions. Identical replay keeps the same revision. Album membership remains
873
+ `unconfirmed`: a batch limit, fixed window or history end cannot prove that every
874
+ member was seen. Assembly performs no additional reads and changes no raw batch
875
+ hash, cursor or acknowledgment.
876
+
877
+ For restartable collection, commit the original records and input recognition in
878
+ your destination **before** acknowledging the raw delivery. Confirm an already
879
+ accepted input from those records without rebuilding a growing album. The SQLite
880
+ example's `accept` returns no post payload; `load(post_id)` reads the current view
881
+ separately. Do not replace lost destination state with an empty dictionary. The
882
+ [album contract](docs/album_assembly.md) explains updates, limits and storage;
883
+ `python examples/album_assembly.py --demo` demonstrates SQLite restart and lost-ack
884
+ replay without Telegram.
885
+
886
+ ### Batch-reader liveness
887
+
888
+ Pass a quick synchronous `heartbeat(phase)` to `get_message_batch`, `sync_group`
889
+ or `prepare_backfill` (also through AccountPool) to observe message, media-chunk
890
+ and request progress. This lets a caller distinguish a slow download from a
891
+ silent read. Defaults, batch hashes and acknowledgments stay unchanged. See
892
+ [heartbeat and watchdog guidance](docs/batch_heartbeat.md) for callback isolation,
893
+ replay behavior and the SDK-wait limit.
894
+
895
+ ### Optional photo trails
896
+
897
+ For a text or album followed by additional photo-only posts, explicitly enable
898
+ the conservative heuristic over your current original observations:
899
+
900
+ ```python
901
+ from tgdata import PhotoTrailPolicy, fold_photo_trails
902
+
903
+ view = fold_photo_trails(current_posts, policy=PhotoTrailPolicy(enabled=True))
904
+ print(view.groups) # tuples of original post IDs, anchor first
905
+ print(view.folded_posts, view.folded_photos)
906
+ ```
907
+
908
+ The default policy is disabled. Every original `TelegramPost` and caption remains
909
+ in `view.posts`. A later observation can withdraw an inferred association; replace
910
+ the earlier view for your chosen scope instead of appending final posts. Counts
911
+ describe the current view, not additional work on each retry.
912
+
913
+ The helper makes no source requests or acknowledgments. The optional SQLite
914
+ example reuses saved original records and refuses a range that cuts a known
915
+ album, preserving intervening context. See [photo-trail views](docs/photo_trails.md)
916
+ for policy, limits and restart/acknowledgment guidance, or run
917
+ `python examples/photo_trails.py --demo` without Telegram.
918
+
810
919
  ### Daily continuation across restarts
811
920
 
812
921
  Use a progress store when tgdata should remember unfinished delivery and the last
@@ -1176,9 +1285,9 @@ The ID must be a positive integer, not a string or boolean. The call is synchron
1176
1285
  it does no connection, authentication or recovery. The returned dictionaries are
1177
1286
  independent copies, with the same fields as the health summary above.
1178
1287
 
1179
- `lookup_group`, `check_group_access` and `join_group` populate this account-owned view. Existing
1288
+ `lookup_group`, `check_group_access`, `get_group_profile`, `measure_group_activity` and `join_group` populate this account-owned view. Existing
1180
1289
  message reads and `health_check()` still use their existing health view; the views
1181
- are not combined. A join result does not clear an earlier history-access failure.
1290
+ are not combined. A join, profile or activity result does not clear an earlier history-access failure.
1182
1291
 
1183
1292
  Internally, an observation begins after a temporary client proves the expected
1184
1293
  account. Its event and retained state keep that numeric owner even if a cached
@@ -30,6 +30,8 @@ A production-grade Python library for extracting and processing Telegram group a
30
30
  - 🩺 **Account Health Events**: Every wait, logout, ban, restriction or lost group is reported as a plain-data event — through one callback, a log line and a per-account summary — and "ok" when it ends
31
31
  - **Per-account read budgets**: An optional shared SQLite ledger limits message pulls over a rolling 24 hours, with persistent warm-up steps and recoverable partial results
32
32
  - **Versioned message batches**: Read bounded raw snapshots with canonical JSON, replayable batch IDs, safe continuation cursors and optional content-addressed media
33
+ - **Album assembly across batches**: Combine observed album members into stable post revisions, preserving every caption and media reference with explicit caller-owned persistence
34
+ - **Optional photo trails**: Associate a user's following photo-only posts in a provisional view, retaining all originals and explicit heuristic provenance
33
35
  - **Durable daily continuation**: Keep per-group progress and pending batches in a pluggable store, replay after restart, and advance only after explicit acknowledgment
34
36
  - **Reading worker**: Run a serial process that accepts explicit-account JSON jobs for batches, group lookup, access checks and joining, with correlated health replies
35
37
 
@@ -87,6 +89,22 @@ keep working, but new configs should set `session_file` and omit `username`
87
89
 
88
90
  ### Logging in
89
91
 
92
+ For a deliberate terminal login that saves the configured native session, run:
93
+
94
+ ```bash
95
+ tgdata-login --config config.ini
96
+ # Re-login at an existing destination, with explicit replacement confirmation:
97
+ tgdata-login --config config.ini --replace
98
+ ```
99
+
100
+ The command reuses `LoginFlow`, hides phone/code/password input and saves a native
101
+ `.session` file for ordinary readers. Replacement requires stopped readers;
102
+ failed saves never trigger another code request automatically. See
103
+ [terminal login](docs/terminal_login.md) for destination rules, safe retry,
104
+ publication uncertainty, supported local POSIX filesystems and exit codes.
105
+
106
+ The existing reader's first-run login behavior also remains available:
107
+
90
108
  The first run of a new session, started by hand in a terminal, asks for the
91
109
  code Telegram sends you. After that, tgdata never asks Telegram for a login
92
110
  code on its own: before connecting it checks with Telegram whether the session
@@ -536,6 +554,33 @@ Numeric channel IDs need a cached access hash. Readability is distinct from memb
536
554
  and does not promise future access. See [the group-operations contract](docs/group_operations.md)
537
555
  for input rules, result fields, errors, budget costs and the known SDK cache limitation.
538
556
 
557
+ ### Richer group profiles
558
+
559
+ `await tg.get_group_profile("@example_group", account_id=expected_id, pinned_limit=5)`
560
+ returns the description, available member/online counts and a bounded pinned-message
561
+ observation. Pins default off; the explicit limit is 1–100 and uses the existing
562
+ read budget. Returned IDs/text/dates, coverage status, count accuracy and separate
563
+ observation times distinguish empty, limited, unavailable and failed reads.
564
+
565
+ The method verifies the account and closes its temporary client. Optional pin
566
+ failures raise their original error with completed metadata on `partial_result`
567
+ when supported. Profile success makes no general history-access claim. See
568
+ [group profiles](docs/group_profiles.md) for fields, errors and heartbeat support.
569
+
570
+ ### Activity and engagement measurement
571
+
572
+ `await tg.measure_group_activity("@example_group", account_id=expected_id,
573
+ start_date=start, end_date=end, max_messages=3000)` returns raw message observations,
574
+ daily activity, author counts and views/reactions/forwards/replies distributions.
575
+ Dates are explicit aware datetimes; the publication window includes start and excludes end.
576
+
577
+ Check `coverage_complete` and `stop_reason` before treating the result as a whole-window
578
+ measurement. The cap counts every source slot; missing counters remain distinct from
579
+ zero. Counters are observed at collection time, and albums count as raw messages.
580
+ The operation uses the existing verified account, read allowance, heartbeat and
581
+ cleanup policies. See [activity measurement](docs/group_activity.md) for the example,
582
+ precise populations, partial failures and visibility limits.
583
+
539
584
  ### Group discovery — finding groups you are not in
540
585
 
541
586
  `list_groups` shows what the account already follows. To find *new* rooms there are three
@@ -778,6 +823,70 @@ refuses cleanup may leave a private temporary file. The exact schema, limits,
778
823
  interruption rules
779
824
  and delivery protocol are in [Message batch v1](docs/message_batch_v1.md).
780
825
 
826
+ ### Albums across message batches
827
+
828
+ Use the opt-in assembler to keep one logical post as more album members arrive:
829
+
830
+ ```python
831
+ from tgdata import album_post_ids, assemble_albums
832
+
833
+ # In-memory illustration for a new collection; retain these posts across calls.
834
+ known_posts = {}
835
+ for batch in batches:
836
+ previous = {key: known_posts.get(key) for key in album_post_ids(batch)}
837
+ for post in assemble_albums(batch, previous=previous):
838
+ known_posts[post.post_id] = post
839
+ print(post.post_id, post.revision, post.member_ids)
840
+ ```
841
+
842
+ Album IDs include the chat; each post retains all original member records and
843
+ captions. Identical replay keeps the same revision. Album membership remains
844
+ `unconfirmed`: a batch limit, fixed window or history end cannot prove that every
845
+ member was seen. Assembly performs no additional reads and changes no raw batch
846
+ hash, cursor or acknowledgment.
847
+
848
+ For restartable collection, commit the original records and input recognition in
849
+ your destination **before** acknowledging the raw delivery. Confirm an already
850
+ accepted input from those records without rebuilding a growing album. The SQLite
851
+ example's `accept` returns no post payload; `load(post_id)` reads the current view
852
+ separately. Do not replace lost destination state with an empty dictionary. The
853
+ [album contract](docs/album_assembly.md) explains updates, limits and storage;
854
+ `python examples/album_assembly.py --demo` demonstrates SQLite restart and lost-ack
855
+ replay without Telegram.
856
+
857
+ ### Batch-reader liveness
858
+
859
+ Pass a quick synchronous `heartbeat(phase)` to `get_message_batch`, `sync_group`
860
+ or `prepare_backfill` (also through AccountPool) to observe message, media-chunk
861
+ and request progress. This lets a caller distinguish a slow download from a
862
+ silent read. Defaults, batch hashes and acknowledgments stay unchanged. See
863
+ [heartbeat and watchdog guidance](docs/batch_heartbeat.md) for callback isolation,
864
+ replay behavior and the SDK-wait limit.
865
+
866
+ ### Optional photo trails
867
+
868
+ For a text or album followed by additional photo-only posts, explicitly enable
869
+ the conservative heuristic over your current original observations:
870
+
871
+ ```python
872
+ from tgdata import PhotoTrailPolicy, fold_photo_trails
873
+
874
+ view = fold_photo_trails(current_posts, policy=PhotoTrailPolicy(enabled=True))
875
+ print(view.groups) # tuples of original post IDs, anchor first
876
+ print(view.folded_posts, view.folded_photos)
877
+ ```
878
+
879
+ The default policy is disabled. Every original `TelegramPost` and caption remains
880
+ in `view.posts`. A later observation can withdraw an inferred association; replace
881
+ the earlier view for your chosen scope instead of appending final posts. Counts
882
+ describe the current view, not additional work on each retry.
883
+
884
+ The helper makes no source requests or acknowledgments. The optional SQLite
885
+ example reuses saved original records and refuses a range that cuts a known
886
+ album, preserving intervening context. See [photo-trail views](docs/photo_trails.md)
887
+ for policy, limits and restart/acknowledgment guidance, or run
888
+ `python examples/photo_trails.py --demo` without Telegram.
889
+
781
890
  ### Daily continuation across restarts
782
891
 
783
892
  Use a progress store when tgdata should remember unfinished delivery and the last
@@ -1147,9 +1256,9 @@ The ID must be a positive integer, not a string or boolean. The call is synchron
1147
1256
  it does no connection, authentication or recovery. The returned dictionaries are
1148
1257
  independent copies, with the same fields as the health summary above.
1149
1258
 
1150
- `lookup_group`, `check_group_access` and `join_group` populate this account-owned view. Existing
1259
+ `lookup_group`, `check_group_access`, `get_group_profile`, `measure_group_activity` and `join_group` populate this account-owned view. Existing
1151
1260
  message reads and `health_check()` still use their existing health view; the views
1152
- are not combined. A join result does not clear an earlier history-access failure.
1261
+ are not combined. A join, profile or activity result does not clear an earlier history-access failure.
1153
1262
 
1154
1263
  Internally, an observation begins after a temporary client proves the expected
1155
1264
  account. Its event and retained state keep that numeric owner even if a cached
@@ -30,7 +30,10 @@ setup(
30
30
  long_description_content_type='text/markdown', # Type of the long description
31
31
 
32
32
  packages=find_packages(), # Automatically find packages in the directory
33
- entry_points={'console_scripts': ['tgdata-worker=tgdata.worker:main']},
33
+ entry_points={'console_scripts': [
34
+ 'tgdata-worker=tgdata.worker:main',
35
+ 'tgdata-login=tgdata.login_cli:main',
36
+ ]},
34
37
  install_requires=[
35
38
  # min_id is exclusive in Telethon 1.x (the off-by-one fix relies on it);
36
39
  # 2.0 is a breaking API rewrite, so cap below it. Verified on 1.40.
@@ -22,6 +22,8 @@ from .message_engine import GroupAccessError
22
22
  from .group_operations import (
23
23
  GroupMetadata, GroupLookup, GroupAccess, GroupJoin, GroupReferenceError, GroupResponseError,
24
24
  )
25
+ from .group_profile import GroupProfile, GroupPinnedMessage
26
+ from .group_activity import GroupActivity, ActivityMessage
25
27
  from .connection_engine import AuthRequiredError, ProxyConfigError
26
28
  from .login import LoginFlow, LoginStatus, LoginError
27
29
  from .discovery_engine import DiscoveryInterrupted
@@ -72,7 +74,7 @@ from .utils import (
72
74
  # Progress tracking
73
75
  from .progress import ProgressTracker
74
76
 
75
- __version__ = "0.1"
77
+ __version__ = "0.1.2"
76
78
 
77
79
  __all__ = [
78
80
  # Explicit account onboarding
@@ -112,6 +114,10 @@ __all__ = [
112
114
  "GroupLookup",
113
115
  "GroupAccess",
114
116
  "GroupJoin",
117
+ "GroupProfile",
118
+ "GroupPinnedMessage",
119
+ "GroupActivity",
120
+ "ActivityMessage",
115
121
  "GroupReferenceError",
116
122
  "GroupResponseError",
117
123
  "AuthRequiredError",
@@ -182,3 +188,9 @@ __all__ = [
182
188
  # Progress
183
189
  "ProgressTracker"
184
190
  ]
191
+
192
+ from .album import TelegramPost, AlbumAssemblyError, album_post_ids, assemble_albums
193
+ __all__ += ["TelegramPost", "AlbumAssemblyError", "album_post_ids", "assemble_albums"]
194
+
195
+ from .photo_trails import PhotoTrailPolicy, PhotoTrailView, PhotoTrailError, fold_photo_trails
196
+ __all__ += ["PhotoTrailPolicy", "PhotoTrailView", "PhotoTrailError", "fold_photo_trails"]
@@ -0,0 +1,216 @@
1
+ """Private bounded terminal input, retired before a value is admitted."""
2
+ import os
3
+ import select
4
+ import sys
5
+
6
+ try:
7
+ import termios
8
+ except ImportError:
9
+ termios = None
10
+
11
+ _LIMIT = 128
12
+
13
+
14
+ class TerminalInputError(Exception):
15
+ def __init__(self, kind, *, operation_kind=None, cleanup_kinds=()):
16
+ self.kind = kind
17
+ self.operation_kind = operation_kind
18
+ self.cleanup_kinds = tuple(cleanup_kinds)
19
+ super().__init__(kind)
20
+
21
+
22
+ class TerminalStopped(EOFError):
23
+ pass
24
+
25
+
26
+ def _control(value):
27
+ if isinstance(value, bytes) and len(value) == 1:
28
+ return value[0]
29
+ if type(value) is int and 0 <= value <= 255:
30
+ return value
31
+ raise TerminalInputError('terminal_controls_unsupported')
32
+
33
+
34
+ def _validate(fd, attrs):
35
+ if os.tcgetpgrp(fd) != os.getpgrp():
36
+ raise TerminalInputError('terminal_not_foreground')
37
+ allowed = 0
38
+ for name in ('ECHO', 'ECHOE', 'ECHOK', 'ECHONL', 'ECHOCTL', 'ECHOKE',
39
+ 'ECHOPRT', 'ISIG', 'ICANON', 'IEXTEN', 'NOFLSH', 'TOSTOP'):
40
+ allowed |= getattr(termios, name, 0)
41
+ forbidden = (termios.ISTRIP | termios.IGNCR | termios.INLCR
42
+ | termios.PARMRK | getattr(termios, 'IUCLC', 0))
43
+ if (attrs[3] & ~allowed or not attrs[3] & termios.ICANON
44
+ or not attrs[3] & termios.ISIG or not attrs[0] & termios.ICRNL
45
+ or attrs[0] & forbidden or attrs[2] & termios.CSIZE != termios.CS8):
46
+ raise TerminalInputError('terminal_mode_unsupported')
47
+ controls = tuple(_control(attrs[6][i]) for i in
48
+ (termios.VERASE, termios.VKILL, termios.VEOF, termios.VINTR))
49
+ if (len(set(controls)) != 4 or controls[3] != 3
50
+ or any(v in (10, 13) or not (0 < v < 32 or v == 127) for v in controls)):
51
+ raise TerminalInputError('terminal_controls_unsupported')
52
+ disabled = os.fpathconf(fd, 'PC_VDISABLE')
53
+ if type(disabled) is not int or not 0 <= disabled <= 255 or disabled in controls:
54
+ raise TerminalInputError('terminal_controls_unsupported')
55
+ return controls, disabled
56
+
57
+
58
+ def _open_terminal():
59
+ if termios is None or os.name != 'posix':
60
+ raise TerminalInputError('terminal_unsupported')
61
+ fd = None
62
+ try:
63
+ fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
64
+ attrs = termios.tcgetattr(fd)
65
+ controls, disabled = _validate(fd, attrs)
66
+ return fd, attrs, controls, disabled
67
+ except BaseException as error:
68
+ operation = error.kind if isinstance(error, TerminalInputError) else 'terminal_unavailable'
69
+ if fd is not None:
70
+ try:
71
+ os.close(fd)
72
+ except Exception:
73
+ raise TerminalInputError('terminal_close_failed', operation_kind=operation,
74
+ cleanup_kinds=('terminal_close_failed',)) from None
75
+ if isinstance(error, TerminalInputError) or not isinstance(error, Exception):
76
+ raise
77
+ raise TerminalInputError(operation) from None
78
+
79
+
80
+ def terminal_preflight():
81
+ fd, unused_attrs, unused_controls, unused_disabled = _open_terminal()
82
+ try:
83
+ os.close(fd)
84
+ except Exception:
85
+ raise TerminalInputError('terminal_close_failed',
86
+ cleanup_kinds=('terminal_close_failed',)) from None
87
+
88
+
89
+ def read_hidden(prompt, stop_requested):
90
+ fd = original = hidden = None
91
+ mutated = False
92
+ operation_kind = None
93
+ cleanup = []
94
+ value = None
95
+ try:
96
+ try:
97
+ fd, original, controls, disabled = _open_terminal()
98
+ erase, kill, eof, unused_intr = controls
99
+ if stop_requested():
100
+ raise TerminalStopped()
101
+ hidden = original[:]
102
+ hidden[6] = original[6][:]
103
+ hidden[0] &= ~(termios.IXON | termios.IXOFF | getattr(termios, 'IXANY', 0))
104
+ hidden[3] &= ~(termios.ECHO | termios.ECHONL | termios.ICANON | termios.IEXTEN)
105
+ hidden[6][termios.VMIN] = 1
106
+ hidden[6][termios.VTIME] = 0
107
+ hidden[6][termios.VQUIT] = bytes([disabled])
108
+ hidden[6][termios.VSUSP] = bytes([disabled])
109
+ if stop_requested():
110
+ raise TerminalStopped()
111
+ mutated = True
112
+ termios.tcsetattr(fd, termios.TCSANOW, hidden)
113
+ if termios.tcgetattr(fd) != hidden:
114
+ raise TerminalInputError('terminal_hide_failed')
115
+ if stop_requested():
116
+ raise TerminalStopped()
117
+ termios.tcflush(fd, termios.TCIFLUSH)
118
+ if stop_requested():
119
+ raise TerminalStopped()
120
+ print(prompt, end='', file=sys.stderr, flush=True)
121
+ data = bytearray()
122
+ reason = None
123
+ finished = False
124
+ while not finished:
125
+ if stop_requested():
126
+ raise TerminalStopped()
127
+ ready, unused_w, unused_x = select.select([fd], [], [], 0.05)
128
+ if stop_requested():
129
+ raise TerminalStopped()
130
+ if not ready:
131
+ continue
132
+ try:
133
+ chunk = os.read(fd, 256)
134
+ except BlockingIOError:
135
+ continue
136
+ if not chunk:
137
+ raise TerminalStopped()
138
+ for byte in chunk:
139
+ if stop_requested():
140
+ raise TerminalStopped()
141
+ if byte == 10:
142
+ finished = True
143
+ break
144
+ if byte == eof:
145
+ raise TerminalStopped()
146
+ if reason is not None:
147
+ continue
148
+ if byte == kill:
149
+ data.clear()
150
+ continue
151
+ if byte == erase:
152
+ try:
153
+ shorter = data.decode('utf-8')[:-1].encode('utf-8')
154
+ except UnicodeError:
155
+ reason = 'terminal_input_encoding'
156
+ else:
157
+ data[:] = shorter
158
+ elif byte < 32 or byte == 127:
159
+ reason = 'terminal_input_control'
160
+ elif len(data) >= _LIMIT:
161
+ reason = 'terminal_input_too_long'
162
+ else:
163
+ data.append(byte)
164
+ if reason is not None:
165
+ data.clear()
166
+ print('\nInput rejected; finishing this line. Ctrl-C stops.',
167
+ file=sys.stderr, flush=True)
168
+ print(file=sys.stderr, flush=True)
169
+ if reason is not None:
170
+ raise TerminalInputError(reason)
171
+ try:
172
+ value = data.decode('utf-8')
173
+ except UnicodeError:
174
+ raise TerminalInputError('terminal_input_encoding') from None
175
+ except TerminalStopped:
176
+ operation_kind = 'input_stopped'
177
+ raise
178
+ except TerminalInputError as error:
179
+ operation_kind = error.kind
180
+ raise
181
+ except Exception:
182
+ operation_kind = 'terminal_input_failed'
183
+ raise TerminalInputError(operation_kind) from None
184
+ finally:
185
+ if fd is not None:
186
+ if mutated:
187
+ try:
188
+ termios.tcflush(fd, termios.TCIFLUSH)
189
+ except Exception:
190
+ cleanup.append('terminal_flush_failed')
191
+ try:
192
+ # Keep all protected controls until the FINAL mode write.
193
+ settling = hidden[:]
194
+ settling[6] = hidden[6][:]
195
+ settling[3] = (settling[3] & ~termios.ICANON) | (original[3] & termios.ICANON)
196
+ termios.tcsetattr(fd, termios.TCSANOW, settling)
197
+ termios.tcflush(fd, termios.TCIFLUSH)
198
+ except Exception:
199
+ cleanup.append('terminal_restore_failed')
200
+ try:
201
+ termios.tcsetattr(fd, termios.TCSANOW, original)
202
+ if termios.tcgetattr(fd) != original:
203
+ cleanup.append('terminal_restore_failed')
204
+ except Exception:
205
+ cleanup.append('terminal_restore_failed')
206
+ try:
207
+ os.close(fd)
208
+ except Exception:
209
+ cleanup.append('terminal_close_failed')
210
+ if cleanup:
211
+ kinds = tuple(dict.fromkeys(cleanup))
212
+ kind = 'terminal_restore_failed' if 'terminal_restore_failed' in kinds else kinds[0]
213
+ raise TerminalInputError(kind, operation_kind=operation_kind, cleanup_kinds=kinds) from None
214
+ if stop_requested():
215
+ raise TerminalStopped()
216
+ return value
@@ -16,6 +16,8 @@ from uuid import uuid4
16
16
  import telethon
17
17
  from telethon import errors as rpc_errors
18
18
 
19
+ from .batch_heartbeat import heartbeat_kwargs
20
+
19
21
  from . import health
20
22
  from .batch_engine import _integer as _batch_integer
21
23
  from .batch_files import BatchStorageError, prepare_directory
@@ -468,15 +470,16 @@ class AccountPool(ProgressFacade):
468
470
  raise local from None
469
471
 
470
472
  async def _read(self, chat_id, *, after_id=0, limit=200, download_media_to=None,
471
- start_date=None, end_date=None, _capture=None):
473
+ start_date=None, end_date=None, heartbeat=None, _capture=None):
472
474
  """Read once through the first successful eligible account, with provenance."""
475
+ progress = heartbeat_kwargs(heartbeat)
473
476
  chat_id = self._group(chat_id)
474
477
  after_id = _batch_integer(after_id, 'after_id', 0, MAX_MESSAGE_ID)
475
478
  limit = _batch_integer(limit, 'limit', 1, MAX_BATCH_MESSAGES)
476
479
  _HistoryWindow.from_dates(start_date, end_date)
477
480
  root = prepare_directory(download_media_to) if download_media_to is not None else None
478
481
  options = dict(after_id=after_id, limit=limit, download_media_to=root,
479
- start_date=start_date, end_date=end_date)
482
+ start_date=start_date, end_date=end_date, **progress)
480
483
  with self._operation():
481
484
  raw, document = await self._load()
482
485
  attempts, tried = [], set()
@@ -520,33 +523,33 @@ class AccountPool(ProgressFacade):
520
523
  raise PoolUnavailable(statuses.accounts, attempts, retry_after) from None
521
524
 
522
525
  async def read(self, chat_id, *, capture, after_id=0, limit=200,
523
- download_media_to=None, start_date=None, end_date=None):
526
+ download_media_to=None, start_date=None, end_date=None, heartbeat=None):
524
527
  """Read with a caller-retained, single-use data destination."""
525
528
  with _capture_call(capture) as writer:
526
529
  result = await self._read(chat_id, after_id=after_id, limit=limit,
527
530
  download_media_to=download_media_to, start_date=start_date,
528
- end_date=end_date, _capture=writer)
531
+ end_date=end_date, _capture=writer, **heartbeat_kwargs(heartbeat))
529
532
  writer.offer(result.batch)
530
533
  return result
531
534
 
532
535
  async def _read_batch(self, group_id, *, after_id=0, limit=200,
533
- download_media_to=None, start_date=None, end_date=None, _capture=None):
536
+ download_media_to=None, start_date=None, end_date=None, heartbeat=None, _capture=None):
534
537
  result = await self._read(group_id, after_id=after_id, limit=limit,
535
538
  download_media_to=download_media_to, start_date=start_date,
536
- end_date=end_date, _capture=_capture)
539
+ end_date=end_date, _capture=_capture, **heartbeat_kwargs(heartbeat))
537
540
  return result.batch
538
541
 
539
542
  async def get_message_batch(self, group_id, *, capture, after_id=0, limit=200,
540
- download_media_to=None, start_date=None, end_date=None):
543
+ download_media_to=None, start_date=None, end_date=None, heartbeat=None):
541
544
  """Return a bounded batch; keep capture to inspect data after a stop."""
542
545
  with _capture_call(capture) as writer:
543
546
  batch = await self._read_batch(group_id, after_id=after_id, limit=limit,
544
547
  download_media_to=download_media_to, start_date=start_date,
545
- end_date=end_date, _capture=writer)
548
+ end_date=end_date, _capture=writer, **heartbeat_kwargs(heartbeat))
546
549
  writer.offer(batch)
547
550
  return batch
548
551
 
549
- async def sync_group(self, chat_id, *, capture, limit=200, download_media_to=None):
552
+ async def sync_group(self, chat_id, *, capture, limit=200, download_media_to=None, heartbeat=None):
550
553
  """Prepare/replay daily delivery with a new caller-retained capture.
551
554
 
552
555
  Only the saved pending batch's receipt can acknowledge progress. The
@@ -554,22 +557,23 @@ class AccountPool(ProgressFacade):
554
557
  """
555
558
  with _capture_call(capture) as writer:
556
559
  batch = await self.sync_engine.prepare(chat_id, limit=limit,
557
- download_media_to=download_media_to, _capture=writer)
560
+ download_media_to=download_media_to, _capture=writer, **heartbeat_kwargs(heartbeat))
558
561
  writer.offer(batch)
559
562
  return batch
560
563
 
561
564
  def _new_backfill_engine(self, collection):
562
565
  return BackfillEngine(self._backfill_store, collection, read_batch=self._read_batch)
563
566
 
564
- async def prepare_backfill(self, context, *, capture, download_media_to=None):
567
+ async def prepare_backfill(self, context, *, capture, download_media_to=None, heartbeat=None):
565
568
  """Prepare/replay one historical turn with a new retained capture.
566
569
 
567
570
  Source closure and progress publication have separate lifetimes; this
568
571
  call finalizes its capture only after its own preparation ends.
569
572
  """
570
573
  with _capture_call(capture) as writer:
574
+ progress = heartbeat_kwargs(heartbeat)
571
575
  engine, context = self._backfill_for(context, BackfillPrepareContext)
572
- turn = await engine.prepare(context, download_media_to=download_media_to, _capture=writer)
576
+ turn = await engine.prepare(context, download_media_to=download_media_to, _capture=writer, **progress)
573
577
  writer.offer(turn.batch)
574
578
  return turn
575
579