tgdata 0.1.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.1 → tgdata-0.1.2}/PKG-INFO +46 -3
  2. {tgdata-0.1.1 → tgdata-0.1.2}/README.md +45 -2
  3. {tgdata-0.1.1 → tgdata-0.1.2}/setup.py +4 -1
  4. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/__init__.py +7 -1
  5. tgdata-0.1.2/tgdata/_terminal_input.py +216 -0
  6. tgdata-0.1.2/tgdata/group_activity.py +313 -0
  7. tgdata-0.1.2/tgdata/group_profile.py +188 -0
  8. tgdata-0.1.2/tgdata/login_cli.py +359 -0
  9. tgdata-0.1.2/tgdata/login_file.py +306 -0
  10. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_framing.py +176 -0
  11. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_handoffs.py +95 -0
  12. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_modes.py +334 -0
  13. tgdata-0.1.2/tgdata/smoke_tests/_terminal_login_observer.py +76 -0
  14. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_42_album_assembly.py +1 -1
  15. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_43_photo_trails.py +1 -1
  16. tgdata-0.1.2/tgdata/smoke_tests/test_45_group_profile.py +557 -0
  17. tgdata-0.1.2/tgdata/smoke_tests/test_46_group_activity.py +523 -0
  18. tgdata-0.1.2/tgdata/smoke_tests/test_48_terminal_login.py +977 -0
  19. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/tgdata.py +44 -2
  20. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata.egg-info/PKG-INFO +46 -3
  21. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata.egg-info/SOURCES.txt +12 -0
  22. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata.egg-info/entry_points.txt +1 -0
  23. {tgdata-0.1.1 → tgdata-0.1.2}/setup.cfg +0 -0
  24. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/account_operation.py +0 -0
  25. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/account_pool.py +0 -0
  26. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/album.py +0 -0
  27. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/backfill.py +0 -0
  28. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/backfill_engine.py +0 -0
  29. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/backfill_state.py +0 -0
  30. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/batch_engine.py +0 -0
  31. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/batch_files.py +0 -0
  32. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/batch_heartbeat.py +0 -0
  33. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/budget_client.py +0 -0
  34. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/connection_engine.py +0 -0
  35. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/discovery_engine.py +0 -0
  36. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/group_operations.py +0 -0
  37. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/health.py +0 -0
  38. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/history_window.py +0 -0
  39. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/join_budget.py +0 -0
  40. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/join_client.py +0 -0
  41. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/login.py +0 -0
  42. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/message_batch.py +0 -0
  43. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/message_engine.py +0 -0
  44. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/models.py +0 -0
  45. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/owned_health.py +0 -0
  46. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/photo_trails.py +0 -0
  47. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/pool_lifecycle.py +0 -0
  48. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/pool_observation.py +0 -0
  49. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/pool_result.py +0 -0
  50. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/pool_source.py +0 -0
  51. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/pool_state.py +0 -0
  52. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/progress.py +0 -0
  53. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/progress_facade.py +0 -0
  54. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/read_budget.py +0 -0
  55. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/session_store.py +0 -0
  56. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/__init__.py +0 -0
  57. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/my_test.py +0 -0
  58. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/pool_storage_cases.py +0 -0
  59. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_00_connection.py +0 -0
  60. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_01_list_group_chats.py +0 -0
  61. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_02_get_message_count.py +0 -0
  62. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_03_get_all_messages.py +0 -0
  63. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_04_get_all_messages_in_batches.py +0 -0
  64. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_05_with_progress_feature.py +0 -0
  65. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_06_polling_simple.py +0 -0
  66. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_07_on_new_message_simple.py +0 -0
  67. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_07_real_time_event_handler.py +0 -0
  68. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_08_batch_callback.py +0 -0
  69. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_08_polling.py +0 -0
  70. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_10_advanced_features.py +0 -0
  71. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_11_discover_groups.py +0 -0
  72. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_12_proxy.py +0 -0
  73. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_13_device_identity.py +0 -0
  74. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_14_flood_threshold.py +0 -0
  75. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_15_login_checks.py +0 -0
  76. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_16_health_events.py +0 -0
  77. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_17_session_store.py +0 -0
  78. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_18_read_budget.py +0 -0
  79. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_19_message_batches.py +0 -0
  80. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_22_daily_continuation.py +0 -0
  81. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_23_fixed_windows.py +0 -0
  82. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_24_backfill_state.py +0 -0
  83. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_25_backfill_delivery.py +0 -0
  84. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_26_backfill_completion.py +0 -0
  85. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_27_backfill_pacing.py +0 -0
  86. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_28_backfill_controls.py +0 -0
  87. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_29_backfill_public.py +0 -0
  88. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_30_backfill_integration.py +0 -0
  89. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_31_account_pool.py +0 -0
  90. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_32_account_operation.py +0 -0
  91. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_33_owned_health.py +0 -0
  92. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_34_group_access.py +0 -0
  93. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_35_join_budget.py +0 -0
  94. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_36_group_join.py +0 -0
  95. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_37_worker.py +0 -0
  96. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_38_worker_process.py +0 -0
  97. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_39_pool_lifecycle.py +0 -0
  98. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_40_pool_outcomes.py +0 -0
  99. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_41_stepwise_login.py +0 -0
  100. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_44_batch_heartbeat.py +0 -0
  101. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_debug_min_id.py +0 -0
  102. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_polling_debug.py +0 -0
  103. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/smoke_tests/test_username_support.py +0 -0
  104. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/sync_engine.py +0 -0
  105. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/sync_store.py +0 -0
  106. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/utils.py +0 -0
  107. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/worker.py +0 -0
  108. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/worker_engine.py +0 -0
  109. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata/worker_protocol.py +0 -0
  110. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata.egg-info/dependency_links.txt +0 -0
  111. {tgdata-0.1.1 → tgdata-0.1.2}/tgdata.egg-info/requires.txt +0 -0
  112. {tgdata-0.1.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.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
@@ -118,6 +118,22 @@ keep working, but new configs should set `session_file` and omit `username`
118
118
 
119
119
  ### Logging in
120
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
+
121
137
  The first run of a new session, started by hand in a terminal, asks for the
122
138
  code Telegram sends you. After that, tgdata never asks Telegram for a login
123
139
  code on its own: before connecting it checks with Telegram whether the session
@@ -567,6 +583,33 @@ Numeric channel IDs need a cached access hash. Readability is distinct from memb
567
583
  and does not promise future access. See [the group-operations contract](docs/group_operations.md)
568
584
  for input rules, result fields, errors, budget costs and the known SDK cache limitation.
569
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
+
570
613
  ### Group discovery — finding groups you are not in
571
614
 
572
615
  `list_groups` shows what the account already follows. To find *new* rooms there are three
@@ -1242,9 +1285,9 @@ The ID must be a positive integer, not a string or boolean. The call is synchron
1242
1285
  it does no connection, authentication or recovery. The returned dictionaries are
1243
1286
  independent copies, with the same fields as the health summary above.
1244
1287
 
1245
- `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
1246
1289
  message reads and `health_check()` still use their existing health view; the views
1247
- 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.
1248
1291
 
1249
1292
  Internally, an observation begins after a temporary client proves the expected
1250
1293
  account. Its event and retained state keep that numeric owner even if a cached
@@ -89,6 +89,22 @@ keep working, but new configs should set `session_file` and omit `username`
89
89
 
90
90
  ### Logging in
91
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
+
92
108
  The first run of a new session, started by hand in a terminal, asks for the
93
109
  code Telegram sends you. After that, tgdata never asks Telegram for a login
94
110
  code on its own: before connecting it checks with Telegram whether the session
@@ -538,6 +554,33 @@ Numeric channel IDs need a cached access hash. Readability is distinct from memb
538
554
  and does not promise future access. See [the group-operations contract](docs/group_operations.md)
539
555
  for input rules, result fields, errors, budget costs and the known SDK cache limitation.
540
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
+
541
584
  ### Group discovery — finding groups you are not in
542
585
 
543
586
  `list_groups` shows what the account already follows. To find *new* rooms there are three
@@ -1213,9 +1256,9 @@ The ID must be a positive integer, not a string or boolean. The call is synchron
1213
1256
  it does no connection, authentication or recovery. The returned dictionaries are
1214
1257
  independent copies, with the same fields as the health summary above.
1215
1258
 
1216
- `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
1217
1260
  message reads and `health_check()` still use their existing health view; the views
1218
- 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.
1219
1262
 
1220
1263
  Internally, an observation begins after a temporary client proves the expected
1221
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.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",
@@ -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