socialcli 0.3.0__py3-none-any.whl

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.

Potentially problematic release.


This version of socialcli might be problematic. Click here for more details.

Files changed (224) hide show
  1. socialcli-0.3.0.dist-info/METADATA +168 -0
  2. socialcli-0.3.0.dist-info/RECORD +224 -0
  3. socialcli-0.3.0.dist-info/WHEEL +4 -0
  4. socialcli-0.3.0.dist-info/entry_points.txt +3 -0
  5. socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. socialctl/__init__.py +0 -0
  7. socialctl/__main__.py +6 -0
  8. socialctl/adapters/__init__.py +6 -0
  9. socialctl/adapters/base.py +68 -0
  10. socialctl/adapters/errores.py +56 -0
  11. socialctl/adapters/facebook.py +180 -0
  12. socialctl/adapters/instagram.py +442 -0
  13. socialctl/adapters/tiktok.py +535 -0
  14. socialctl/adapters/youtube.py +331 -0
  15. socialctl/agent_errors.py +176 -0
  16. socialctl/agent_guide.py +23 -0
  17. socialctl/approval_cli.py +27 -0
  18. socialctl/auth.py +139 -0
  19. socialctl/authflow.py +344 -0
  20. socialctl/brands.py +194 -0
  21. socialctl/capabilities.py +57 -0
  22. socialctl/capabilities.yml +5945 -0
  23. socialctl/cli.py +1766 -0
  24. socialctl/connection_service/__init__.py +0 -0
  25. socialctl/connection_service/__main__.py +33 -0
  26. socialctl/connection_service/app.py +496 -0
  27. socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
  28. socialctl/connection_service/assets/connection.css +75 -0
  29. socialctl/connection_service/assets/facebook.webp +0 -0
  30. socialctl/connection_service/assets/instagram.svg +194 -0
  31. socialctl/connection_service/assets/socialcli-logo.png +0 -0
  32. socialctl/connection_service/assets/tiktok.png +0 -0
  33. socialctl/connection_service/assets/youtube.svg +1 -0
  34. socialctl/connection_service/landing.py +146 -0
  35. socialctl/connection_service/legacy.py +48 -0
  36. socialctl/connection_service/peer.py +13 -0
  37. socialctl/connection_service/providers.py +324 -0
  38. socialctl/connection_service/settings.py +76 -0
  39. socialctl/connection_service/store.py +124 -0
  40. socialctl/connections/__init__.py +0 -0
  41. socialctl/connections/account_cli.py +438 -0
  42. socialctl/connections/cli.py +379 -0
  43. socialctl/connections/client.py +126 -0
  44. socialctl/connections/credential_cli.py +224 -0
  45. socialctl/connections/credential_store.py +49 -0
  46. socialctl/connections/file_store.py +193 -0
  47. socialctl/connections/keychain.py +78 -0
  48. socialctl/connections/meta_user.py +81 -0
  49. socialctl/connections/rotation_cli.py +116 -0
  50. socialctl/connections/saas_client.py +91 -0
  51. socialctl/connections/temporary_media.py +62 -0
  52. socialctl/delivery_options.py +70 -0
  53. socialctl/engagement.py +200 -0
  54. socialctl/engagement_cli.py +50 -0
  55. socialctl/executor.py +135 -0
  56. socialctl/formatter.py +291 -0
  57. socialctl/hosted_media.py +152 -0
  58. socialctl/identity.py +200 -0
  59. socialctl/inbox.py +298 -0
  60. socialctl/inbox_cli.py +46 -0
  61. socialctl/inventory.py +155 -0
  62. socialctl/inventory_cli.py +171 -0
  63. socialctl/inventory_sources.py +101 -0
  64. socialctl/management/__init__.py +1 -0
  65. socialctl/management/batch_cli.py +115 -0
  66. socialctl/management/batches.py +325 -0
  67. socialctl/management/changes.py +485 -0
  68. socialctl/management/cli.py +227 -0
  69. socialctl/management/comments_cli.py +352 -0
  70. socialctl/management/community_batch_cli.py +63 -0
  71. socialctl/management/community_batches.py +294 -0
  72. socialctl/management/community_changes.py +370 -0
  73. socialctl/management/community_cli.py +142 -0
  74. socialctl/management/community_schema.py +119 -0
  75. socialctl/management/facebook_groups.py +1118 -0
  76. socialctl/management/groups_cli.py +274 -0
  77. socialctl/management/inbox_readers.py +87 -0
  78. socialctl/management/meta_changes.py +197 -0
  79. socialctl/management/meta_cli.py +342 -0
  80. socialctl/management/meta_client.py +631 -0
  81. socialctl/management/meta_comment_inbox.py +565 -0
  82. socialctl/management/meta_comments.py +587 -0
  83. socialctl/management/meta_errors.py +59 -0
  84. socialctl/management/meta_pagination.py +52 -0
  85. socialctl/management/meta_schema.py +128 -0
  86. socialctl/management/meta_webhooks.py +147 -0
  87. socialctl/management/metadata_parts.py +144 -0
  88. socialctl/management/owned_assets.py +85 -0
  89. socialctl/management/owned_changes.py +470 -0
  90. socialctl/management/owned_cli.py +128 -0
  91. socialctl/management/owned_reorder.py +62 -0
  92. socialctl/management/owned_schema.py +368 -0
  93. socialctl/management/reply_context.py +24 -0
  94. socialctl/management/reply_evidence.py +80 -0
  95. socialctl/management/resource_changes.py +407 -0
  96. socialctl/management/resource_cli.py +136 -0
  97. socialctl/management/snippet_readback.py +26 -0
  98. socialctl/management/stories.py +713 -0
  99. socialctl/management/stories_cli.py +172 -0
  100. socialctl/management/youtube.py +323 -0
  101. socialctl/management/youtube_community.py +326 -0
  102. socialctl/management/youtube_metadata.py +122 -0
  103. socialctl/management/youtube_owned.py +259 -0
  104. socialctl/management/youtube_resources.py +305 -0
  105. socialctl/media.py +269 -0
  106. socialctl/media_cli.py +183 -0
  107. socialctl/media_ingress.py +211 -0
  108. socialctl/media_preflight.py +114 -0
  109. socialctl/media_registry.py +301 -0
  110. socialctl/media_requirements.py +52 -0
  111. socialctl/metricas/__init__.py +6 -0
  112. socialctl/metricas/almacen.py +133 -0
  113. socialctl/metricas/analytics_changes.py +295 -0
  114. socialctl/metricas/analytics_cli.py +191 -0
  115. socialctl/metricas/analytics_client.py +304 -0
  116. socialctl/metricas/analytics_ingest.py +260 -0
  117. socialctl/metricas/analytics_schema.py +174 -0
  118. socialctl/metricas/base.py +147 -0
  119. socialctl/metricas/facebook.py +418 -0
  120. socialctl/metricas/insights.py +227 -0
  121. socialctl/metricas/instagram.py +133 -0
  122. socialctl/metricas/modelos.py +87 -0
  123. socialctl/metricas/piezas.py +134 -0
  124. socialctl/metricas/reach.py +94 -0
  125. socialctl/metricas/reporting_client.py +112 -0
  126. socialctl/metricas/resumen.py +251 -0
  127. socialctl/metricas/slugs.py +89 -0
  128. socialctl/metricas/tiktok.py +185 -0
  129. socialctl/metricas/youtube.py +403 -0
  130. socialctl/migration_cli.py +60 -0
  131. socialctl/migration_files.py +68 -0
  132. socialctl/models.py +150 -0
  133. socialctl/native_schedule/__init__.py +13 -0
  134. socialctl/native_schedule/api_delivery.py +15 -0
  135. socialctl/native_schedule/api_reconcile.py +40 -0
  136. socialctl/native_schedule/approval.py +160 -0
  137. socialctl/native_schedule/cadence.py +73 -0
  138. socialctl/native_schedule/cli.py +510 -0
  139. socialctl/native_schedule/dispatcher.py +120 -0
  140. socialctl/native_schedule/facebook.py +112 -0
  141. socialctl/native_schedule/facebook_reels.py +140 -0
  142. socialctl/native_schedule/first_comment.py +181 -0
  143. socialctl/native_schedule/handoff.py +193 -0
  144. socialctl/native_schedule/instagram_delivery.py +224 -0
  145. socialctl/native_schedule/instagram_runtime.py +66 -0
  146. socialctl/native_schedule/inventory.py +70 -0
  147. socialctl/native_schedule/migration.py +310 -0
  148. socialctl/native_schedule/models.py +103 -0
  149. socialctl/native_schedule/reconcile.py +83 -0
  150. socialctl/native_schedule/remote_data.py +177 -0
  151. socialctl/native_schedule/report.py +151 -0
  152. socialctl/native_schedule/store.py +560 -0
  153. socialctl/native_schedule/verification.py +32 -0
  154. socialctl/native_schedule/youtube.py +339 -0
  155. socialctl/operation_output.py +87 -0
  156. socialctl/plantillas/accounts.yml +33 -0
  157. socialctl/plantillas/brand.md +95 -0
  158. socialctl/plantillas/estrategia.md +64 -0
  159. socialctl/postfile.py +240 -0
  160. socialctl/preflight.py +73 -0
  161. socialctl/publication_policy.py +34 -0
  162. socialctl/publication_status.py +75 -0
  163. socialctl/publication_steps.py +398 -0
  164. socialctl/publish_output.py +96 -0
  165. socialctl/publisher.py +445 -0
  166. socialctl/queue_migration.py +302 -0
  167. socialctl/read_budget.py +224 -0
  168. socialctl/read_reports.py +91 -0
  169. socialctl/rutas.py +103 -0
  170. socialctl/saas/__init__.py +1 -0
  171. socialctl/saas/access.py +75 -0
  172. socialctl/saas/auth.py +213 -0
  173. socialctl/saas/backup.py +124 -0
  174. socialctl/saas/billing.py +327 -0
  175. socialctl/saas/billing_enrollment.py +1237 -0
  176. socialctl/saas/billing_enrollment_schema.py +519 -0
  177. socialctl/saas/billing_inventory.py +775 -0
  178. socialctl/saas/billing_reconcile.py +127 -0
  179. socialctl/saas/billing_routes.py +27 -0
  180. socialctl/saas/budget.py +66 -0
  181. socialctl/saas/connections.py +374 -0
  182. socialctl/saas/consent.py +52 -0
  183. socialctl/saas/lifecycle.py +341 -0
  184. socialctl/saas/mail.py +89 -0
  185. socialctl/saas/maintenance.py +68 -0
  186. socialctl/saas/meta_user.py +298 -0
  187. socialctl/saas/meta_webhooks.py +358 -0
  188. socialctl/saas/migration.py +107 -0
  189. socialctl/saas/models.py +8 -0
  190. socialctl/saas/operations.py +102 -0
  191. socialctl/saas/pages.py +126 -0
  192. socialctl/saas/pairing.py +158 -0
  193. socialctl/saas/permissions.py +57 -0
  194. socialctl/saas/reminders.py +128 -0
  195. socialctl/saas/renewal.py +74 -0
  196. socialctl/saas/restore_guard.py +229 -0
  197. socialctl/saas/revocation.py +97 -0
  198. socialctl/saas/rotation.py +114 -0
  199. socialctl/saas/routes.py +221 -0
  200. socialctl/saas/settings.py +34 -0
  201. socialctl/saas/store.py +106 -0
  202. socialctl/saas/temporary_media.py +245 -0
  203. socialctl/saas/webhooks.py +76 -0
  204. socialctl/schedule_remote.py +262 -0
  205. socialctl/schedule_sqlite.py +44 -0
  206. socialctl/scheduler.py +581 -0
  207. socialctl/scheduler_launchd.py +319 -0
  208. socialctl/scheduler_systemd.py +167 -0
  209. socialctl/source_links.py +119 -0
  210. socialctl/ui/__init__.py +1 -0
  211. socialctl/ui/assets/agent-manual.md +850 -0
  212. socialctl/ui/assets/agents.md +27 -0
  213. socialctl/ui/assets/components.css +20 -0
  214. socialctl/ui/assets/connection-layout.css +53 -0
  215. socialctl/ui/assets/otp.template.html +10 -0
  216. socialctl/ui/assets/tokens.css +1 -0
  217. socialctl/ui/assets/trial.template.html +11 -0
  218. socialctl/ui/assets/web-layout.css +38 -0
  219. socialctl/ui/email/otp.html +10 -0
  220. socialctl/ui/email/trial.html +11 -0
  221. socialctl/upload_consent.py +13 -0
  222. socialctl/workspace.py +8 -0
  223. socialctl/youtube_data.py +471 -0
  224. socialctl/youtube_data_service.py +225 -0
socialctl/identity.py ADDED
@@ -0,0 +1,200 @@
1
+ """Bounded read-only identity checks; stored metadata is never permission proof."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import time
6
+
7
+ import httpx
8
+
9
+ from socialctl.brands import Brand
10
+ from socialctl.models import Platform
11
+
12
+ YOUTUBE = "https://www.googleapis.com/youtube/v3"
13
+ GRAPH = "https://graph.facebook.com/v26.0"
14
+ TIKTOK = "https://open.tiktokapis.com/v2"
15
+ SUPPORTED = (Platform.YOUTUBE, Platform.FACEBOOK, Platform.INSTAGRAM, Platform.TIKTOK)
16
+
17
+
18
+ class ReadError(ValueError):
19
+ def __init__(self, code: str):
20
+ self.code = code
21
+ super().__init__(code)
22
+
23
+
24
+ def remote_id(value):
25
+ if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,256}", value):
26
+ raise ReadError("invalid_remote_id")
27
+ return value
28
+
29
+
30
+ def configured_account(brand: Brand, platform: Platform) -> str:
31
+ if platform not in SUPPORTED:
32
+ raise ReadError("unsupported_platform")
33
+ key = {Platform.YOUTUBE: "channel_id", Platform.FACEBOOK: "page_id",
34
+ Platform.INSTAGRAM: "ig_user_id", Platform.TIKTOK: "open_id"}[platform]
35
+ account = brand.cuentas.get(platform.value)
36
+ if not isinstance(account, dict) or not account.get(key):
37
+ raise ReadError("configuration_missing")
38
+ return remote_id(account[key])
39
+
40
+
41
+ def credential_metadata(secret):
42
+ scopes = secret.get("granted_scopes", secret.get("scope"))
43
+ if isinstance(scopes, str):
44
+ scopes = scopes.replace(",", " ").split()
45
+ known = isinstance(scopes, list) and all(isinstance(s, str) and s.strip() for s in scopes)
46
+ expiry = secret.get("expira_en")
47
+ expiry_known = type(expiry) in {int, float} and 0 < expiry < float("inf")
48
+ return {
49
+ "granted_scopes": {"state": "known" if known else "unknown",
50
+ "values": sorted(set(scopes)) if known else None,
51
+ "source": "stored_token_response" if known else None},
52
+ "expiry": {"state": "known" if expiry_known else "unknown",
53
+ "unix_seconds": expiry if expiry_known else None,
54
+ "expired": expiry <= time.time() if expiry_known else None},
55
+ "write_permissions_verified": False,
56
+ "quota_balance": {"state": "unknown", "value": None},
57
+ }
58
+
59
+
60
+ def record_granted_scopes(secret, response):
61
+ """Keep only scopes returned for this token, never requested OAuth scopes."""
62
+ secret.pop("scope", None)
63
+ secret.pop("granted_scopes", None)
64
+ granted = response.get("scope")
65
+ if isinstance(granted, str):
66
+ secret["granted_scopes"] = sorted(set(granted.replace(",", " ").split()))
67
+
68
+
69
+ class IdentityClient:
70
+ """Only fixed provider hosts, GET, bearer headers, and explicit account IDs."""
71
+ def __init__(self, brand: Brand, platform: Platform, client: httpx.Client):
72
+ self.brand, self.platform, self.client = brand, platform, client
73
+ self.account_id = configured_account(brand, platform)
74
+ try:
75
+ secret = brand.leer_secreto(platform)
76
+ self.metadata = credential_metadata(secret)
77
+ if secret.get("auth_mode") == "broker":
78
+ from socialctl.connections.client import broker_access_token
79
+ self._token = broker_access_token(brand, platform, client, refresh=False)
80
+ else:
81
+ self._token = secret.get("access_token")
82
+ except Exception:
83
+ raise ReadError("credentials_invalid") from None
84
+ if not isinstance(self._token, str) or not self._token:
85
+ raise ReadError("credentials_missing")
86
+ if self.metadata["expiry"]["expired"]:
87
+ # Status/sync/doctor never invoke refresh POST or interactive auth.
88
+ raise ReadError("credentials_expired")
89
+ self.identity = None
90
+
91
+ def get(self, endpoint: str, params: dict):
92
+ allowed = {"channels", "playlistItems", "videos"} if self.platform is Platform.YOUTUBE else {
93
+ "me", f"{self.account_id}/videos", f"{self.account_id}/media"}
94
+ if self.platform is Platform.TIKTOK:
95
+ allowed = {'user/info/'}
96
+ if endpoint not in allowed:
97
+ raise ReadError("endpoint_not_allowed")
98
+ base = YOUTUBE if self.platform is Platform.YOUTUBE else GRAPH
99
+ if self.platform is Platform.TIKTOK:
100
+ base = TIKTOK
101
+ try:
102
+ response = self.client.get(f"{base}/{endpoint}", params=params,
103
+ headers={"Authorization": f"Bearer {self._token}"}, timeout=30,
104
+ follow_redirects=False)
105
+ except httpx.TimeoutException:
106
+ raise ReadError("timeout") from None
107
+ except Exception:
108
+ raise ReadError("transport_error") from None
109
+ if response.status_code == 429:
110
+ raise ReadError("rate_limited")
111
+ if response.status_code in {401, 403}:
112
+ # YouTube quota exhaustion commonly uses HTTP403.
113
+ try:
114
+ reasons = [e["reason"] for e in response.json().get("error", {}).get("errors", [])
115
+ if isinstance(e, dict) and isinstance(e.get("reason"), str)]
116
+ except Exception:
117
+ reasons = []
118
+ if set(reasons) & {"quotaExceeded", "dailyLimitExceeded", "rateLimitExceeded", "userRateLimitExceeded"}:
119
+ raise ReadError("rate_limited")
120
+ raise ReadError("permission_denied")
121
+ if response.status_code == 404:
122
+ raise ReadError("not_found_or_inaccessible")
123
+ if not response.is_success:
124
+ raise ReadError("provider_error")
125
+ try:
126
+ data = response.json()
127
+ if not isinstance(data, dict):
128
+ raise ValueError()
129
+ if self.platform is Platform.TIKTOK:
130
+ if not isinstance(data.get('error'), dict) or not isinstance(data['error'].get('code'), str):
131
+ raise ValueError()
132
+ if data['error']['code'] != 'ok':
133
+ raise ReadError('provider_error')
134
+ elif 'error' in data:
135
+ raise ValueError()
136
+ return data
137
+ except ReadError:
138
+ raise
139
+ except Exception:
140
+ raise ReadError("invalid_response") from None
141
+
142
+ def verify(self):
143
+ configured_page = None
144
+ if self.platform is Platform.YOUTUBE:
145
+ data = self.get("channels", {"part": "id,contentDetails", "mine": "true", "maxResults": "50"})
146
+ items = data.get("items")
147
+ if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict) or data.get("nextPageToken"):
148
+ raise ReadError("identity_ambiguous")
149
+ row = items[0]
150
+ authenticated = row.get("id")
151
+ details = row.get("contentDetails") or {}
152
+ related = details.get("relatedPlaylists") if isinstance(details, dict) else None
153
+ self.uploads_playlist = related.get("uploads") if isinstance(related, dict) else None
154
+ page = None
155
+ elif self.platform is Platform.TIKTOK:
156
+ data = self.get('user/info/', {'fields':'open_id'})
157
+ payload = data.get('data')
158
+ row = payload.get('user') if isinstance(payload, dict) else None
159
+ if not isinstance(row, dict):
160
+ raise ReadError('invalid_response')
161
+ authenticated, page = row.get('open_id'), None
162
+ else:
163
+ fields = "id,instagram_business_account" if self.platform is Platform.INSTAGRAM else "id"
164
+ row = self.get("me", {"fields": fields})
165
+ page = row.get("id")
166
+ configured_page = configured_account(self.brand, Platform.FACEBOOK)
167
+ linked = row.get("instagram_business_account") or {}
168
+ authenticated = (linked.get("id") if isinstance(linked, dict) else None) if self.platform is Platform.INSTAGRAM else page
169
+ # Only safe IDs may enter public status; raw provider errors are never printed.
170
+ def public_id(value):
171
+ if value == self._token:
172
+ return None
173
+ try:
174
+ return remote_id(value)
175
+ except ReadError:
176
+ return None
177
+ authenticated, page = public_id(authenticated), public_id(page)
178
+ self.identity = {"configured_account_id": self.account_id, "authenticated_account_id": authenticated,
179
+ "configured_page_id": configured_page, "authenticated_page_id": page,
180
+ "verified": authenticated == self.account_id and page == configured_page}
181
+ if not self.identity["verified"]:
182
+ raise ReadError("identity_mismatch")
183
+ return self.identity
184
+
185
+
186
+ def auth_status(brand, platform, client):
187
+ result = {"version": 1, "brand": brand.nombre, "platform": platform.value,
188
+ "failure_class": None, "identity": {"verified": False}, **credential_metadata({})}
189
+ probe = None
190
+ try:
191
+ result.update(credential_metadata(brand.leer_secreto(platform)))
192
+ probe = IdentityClient(brand, platform, client)
193
+ result["identity"] = probe.verify()
194
+ except ReadError as exc:
195
+ result["failure_class"] = exc.code
196
+ if probe is not None and probe.identity is not None:
197
+ result["identity"] = probe.identity
198
+ except Exception:
199
+ result["failure_class"] = "credentials_invalid"
200
+ return result
socialctl/inbox.py ADDED
@@ -0,0 +1,298 @@
1
+ """Coverage-aware observations of owned-account comments; never writes to providers."""
2
+ from __future__ import annotations
3
+ import json
4
+ import re
5
+ from datetime import datetime,date,time,timedelta,timezone
6
+ from pathlib import Path
7
+ from zoneinfo import ZoneInfo,ZoneInfoNotFoundError
8
+
9
+ from socialctl.models import Platform
10
+ from socialctl.read_budget import read_client, ReadDeadlineExceeded
11
+ from socialctl.read_reports import ReadReport,safe_error,annotate_partial_read
12
+ from socialctl.agent_errors import error_document
13
+ from socialctl.management.meta_comment_inbox import CommentInboxStore,sync_inbox
14
+ from socialctl.migration_files import write_json
15
+ from socialctl.management.reply_evidence import bound_evidence, retain_positive, reply_evidence, youtube_reply_evidence
16
+
17
+
18
+ def resolve_since(value,timezone_name,now):
19
+ zone=None
20
+ if timezone_name:
21
+ try:zone=ZoneInfo(timezone_name)
22
+ except (ZoneInfoNotFoundError,ValueError):raise ValueError('invalid IANA timezone') from None
23
+ if not isinstance(value,str):raise ValueError('--since requires a date or RFC3339 timestamp')
24
+ if value.casefold() in {'ayer','yesterday'} or re.fullmatch(r'\d{4}-\d{2}-\d{2}',value):
25
+ if zone is None:raise ValueError('relative dates and calendar dates require --timezone or brand inbox.yml timezone')
26
+ if now.tzinfo is None:raise ValueError('current observation time must include a timezone')
27
+ day=now.astimezone(zone).date()-timedelta(days=1) if value.casefold() in {'ayer','yesterday'} else date.fromisoformat(value)
28
+ local=datetime.combine(day,time.min,tzinfo=zone)
29
+ if local.astimezone(timezone.utc).astimezone(zone).replace(tzinfo=None)!=local.replace(tzinfo=None) or local.utcoffset()!=local.replace(fold=1).utcoffset():
30
+ raise ValueError('ambiguous/nonexistent local midnight; supply explicit RFC3339 offset')
31
+ return local.astimezone(timezone.utc)
32
+ try:stamp=datetime.fromisoformat(value.replace('Z','+00:00'))
33
+ except ValueError:raise ValueError('--since requires yesterday/ayer, YYYY-MM-DD or RFC3339') from None
34
+ if stamp.tzinfo is None:raise ValueError('--since timestamp must include its timezone offset')
35
+ return stamp.astimezone(timezone.utc)
36
+
37
+
38
+ class UnifiedInboxStore:
39
+ def __init__(self,root):
40
+ self.root=Path(root)
41
+ self.path=self.root/'.socialctl'/'unified-inbox'/'state.json'
42
+ def load(self):
43
+ if not self.path.exists():return {'version':1,'items':{},'watermarks':{}}
44
+ try:
45
+ data=json.loads(self.path.read_text())
46
+ if data.get('version')!=1 or not isinstance(data.get('items'),dict) or not isinstance(data.get('watermarks'),dict):raise ValueError()
47
+ except (OSError,ValueError):raise ValueError('unified inbox state is invalid; preserve it before recovery') from None
48
+ from socialctl.youtube_data import require_fresh_api_data
49
+ for row in data['items'].values():
50
+ if row.get('platform')=='youtube':require_fresh_api_data(row.get('first_observed_at'))
51
+ return data
52
+ @staticmethod
53
+ def key(row):return json.dumps([row['platform'],row['account_id'],row['comment_id']],separators=(',',':'))
54
+ def observe(self,rows,*,observed_at,scope=None,complete=False):
55
+ changed=[]
56
+ with CommentInboxStore(self.root).lock():
57
+ data=self.load()
58
+ for row in rows:
59
+ key=self.key(row);old=data['items'].get(key)
60
+ evidence=retain_positive(bound_evidence(old) if old else None, bound_evidence(row))
61
+ if evidence: row={**row, 'reply_evidence':evidence}
62
+ if old and (old['media_id'],old.get('parent_id'))!=(row['media_id'],row.get('parent_id')):
63
+ raise ValueError('comment identity changed media/parent; observation is ambiguous')
64
+ history=list(old.get('history',[])) if old else []
65
+ if old and old['text']!=row['text']:
66
+ history.append({'observed_at':observed_at,'before':old['text'],'after':row['text']});changed.append(key)
67
+ data['items'][key]={**row,'original_text':old['original_text'] if old else row['text'],
68
+ 'first_observed_at':old['first_observed_at'] if old else observed_at,
69
+ 'last_observed_at':observed_at,'history':history}
70
+ if scope and complete:data['watermarks'][scope]=observed_at
71
+ self.path.parent.mkdir(parents=True,exist_ok=True)
72
+ write_json(self.path,data)
73
+ return changed
74
+
75
+
76
+ class InboxInterrupted(KeyboardInterrupt):
77
+ def __init__(self, rows):
78
+ self.rows = rows
79
+
80
+
81
+ def _partial_problem(report):
82
+ detail = annotate_partial_read({**report, 'complete': False})['error_detail']
83
+ return {'code': detail['code'], 'message': safe_error(report.get('error') or 'Read incomplete')}
84
+
85
+
86
+ def _exception_problem(exc):
87
+ return {**error_document(exc, read_only=True), 'message': safe_error(str(exc))}
88
+
89
+
90
+ def _problem_document(problem):
91
+ if isinstance(problem, dict):
92
+ return {'code': problem.get('code', 'read_partial'),
93
+ 'message': safe_error(problem.get('message', 'Read incomplete'))}
94
+ return {'message': safe_error(str(problem))}
95
+
96
+
97
+ def _youtube_rows(client, video_id):
98
+ report = client.list_threads(video_id)
99
+ rows, errors = [], []
100
+ complete = report['complete']
101
+ timed_out = report.get('timed_out', False)
102
+ if report.get('error'):
103
+ errors.append(_partial_problem(report))
104
+
105
+ def observe(row, parent, thread_id):
106
+ nonlocal complete
107
+ snippet = row['snippet']
108
+ author = (snippet.get('authorChannelId') or {}).get('value')
109
+ if author == client.configured_channel_id:
110
+ return
111
+ text = snippet.get('textOriginal', snippet.get('textDisplay'))
112
+ if not isinstance(author, str) or not author or not isinstance(text, str):
113
+ complete = False
114
+ errors.append('comment author/text unavailable')
115
+ return
116
+ created = snippet.get('publishedAt')
117
+ if created is None:
118
+ complete = False
119
+ errors.append('comment creation time unavailable; interval membership unknown')
120
+ rows.append({'platform': 'youtube', 'account_id': client.configured_channel_id,
121
+ 'media_id': video_id, 'thread_id': thread_id, 'parent_id': parent,
122
+ 'comment_id': row['id'], 'author_id': author, 'text': text,
123
+ 'created_time': created, 'provider_updated_at': snippet.get('updatedAt'),
124
+ 'status': 'observed'})
125
+
126
+ try:
127
+ for thread in report['items']:
128
+ top = thread['snippet']['topLevelComment']
129
+ observe(top, None, thread['id'])
130
+ parent_row = next((r for r in rows if r['comment_id'] == top['id']), None)
131
+ if parent_row is not None:
132
+ parent_row['reply_evidence'] = reply_evidence('youtube', client.configured_channel_id, video_id, top['id'], thread_id=thread['id'])
133
+ count = thread['snippet'].get('totalReplyCount')
134
+ if type(count) is int and count == 0:
135
+ if parent_row is not None:
136
+ parent_row['reply_evidence'] = reply_evidence('youtube', client.configured_channel_id, video_id, top['id'], thread_id=thread['id'], complete=True)
137
+ continue
138
+ if report.get('interrupted') or timed_out:
139
+ continue
140
+ try:
141
+ replies = client.list_replies(video_id, thread['id'], top['id'])
142
+ except ReadDeadlineExceeded as exc:
143
+ replies = {'items': [], 'complete': False, 'error': str(exc), 'timed_out': True}
144
+ except Exception as exc:
145
+ replies = {'items': [], 'complete': False, 'error': safe_error(str(exc)),
146
+ 'error_detail': error_document(exc, read_only=True)}
147
+ if parent_row is not None:
148
+ parent_row['reply_evidence'] = youtube_reply_evidence(client, video_id, thread['id'], top['id'], replies)
149
+ timed_out = replies.get('timed_out', False)
150
+ complete = complete and replies['complete']
151
+ if replies.get('error'):
152
+ errors.append(_partial_problem(replies))
153
+ for reply in replies['items']:
154
+ observe(reply, top['id'], thread['id'])
155
+ if replies.get('interrupted'):
156
+ raise InboxInterrupted(rows)
157
+ except KeyboardInterrupt:
158
+ raise InboxInterrupted(rows) from None
159
+ if report.get("interrupted"):
160
+ raise InboxInterrupted(rows)
161
+ return rows, complete, errors
162
+
163
+
164
+ def sync_brand_inbox(brand,*,since,budget,only=None):
165
+ from socialctl.management.meta_client import MetaClient
166
+ from socialctl.management.inbox_readers import MetaInboxClient, YouTubeInboxClient
167
+ from socialctl.inventory import sync_content,InventoryStore
168
+ from socialctl.management.changes import now_utc
169
+ store=UnifiedInboxStore(brand.raiz);coverage=[];errors=[];edited=set();observed_keys=set()
170
+ observed=now_utc().isoformat()
171
+ fields={'youtube':'channel_id','facebook':'page_id','instagram':'ig_user_id','tiktok':'open_id'}
172
+ platforms=list(dict.fromkeys(only)) if only else list(Platform)
173
+ pending_providers=sum(bool((brand.cuentas.get(p.value) or {}).get(fields[p.value])) for p in platforms if p is not Platform.TIKTOK)
174
+ from socialctl.read_budget import ReadProgress
175
+ with ReadProgress('inbox') as progress, read_client(budget,progress=progress) as http:
176
+ for platform in platforms:
177
+ account=(brand.cuentas.get(platform.value) or {}).get(fields[platform.value])
178
+ row={'platform':platform.value,'account_id':account or None,'complete':False,'scopes':[]}
179
+ coverage.append(row)
180
+ if platform is Platform.TIKTOK:
181
+ row['state']='unsupported';errors.append({'platform':'tiktok','code':'unsupported_operation','message':'Comment inbox unsupported by the configured TikTok integration'});continue
182
+ if not account:
183
+ row['state']='unavailable';errors.append({'platform':platform.value,'code':'account_not_configured','message':'No account configured'});continue
184
+ try:
185
+ share_count=pending_providers
186
+ pending_providers-=1
187
+ with budget.share(share_count):
188
+ budget.check()
189
+ if platform is Platform.YOUTUBE:
190
+ from socialctl.identity import credential_metadata
191
+ grant=credential_metadata(brand.leer_secreto(platform))['granted_scopes']
192
+ management_scopes={'https://www.googleapis.com/auth/youtube.force-ssl','https://www.googleapis.com/auth/youtube'}
193
+ if grant['state']=='known' and not management_scopes.intersection(grant['values']):
194
+ row['state']='error'
195
+ errors.append({'platform':'youtube','code':'permissions_required',
196
+ 'message':'YouTube comment inbox requires management consent. Ask the owner to authorize connect youtube --management --analytics --no-browser with the explicit --brand and --root. Do not reconnect automatically.'})
197
+ continue
198
+ inventory_store=InventoryStore(brand,platform,account)
199
+ prior=inventory_store.load().get('sync') or {}
200
+ resume=not prior.get('complete',True) and prior.get('resumable',False)
201
+ inventory=sync_content(brand,platform,http,resume=resume)
202
+ if resume and inventory['failure_class'] in {'invalid_cursor','provider_error'}:
203
+ budget.check()
204
+ inventory=sync_content(brand,platform,http,resume=False)
205
+ media=[v['remote_id'] for v in InventoryStore(brand,platform,account).list_items() if v.get('last_sync_id')==inventory['sync_id']]
206
+ complete=inventory['complete'] and inventory['details_complete']
207
+ client=YouTubeInboxClient(brand,http)
208
+ for ident in media:
209
+ budget.check()
210
+ try:items,ok,problems=_youtube_rows(client,ident)
211
+ except InboxInterrupted as exc:
212
+ store.observe(exc.rows,observed_at=observed)
213
+ observed_keys.update(store.key(i) for i in exc.rows)
214
+ row['scopes'].append({'media_id':ident,'filter':'published','complete':False})
215
+ raise KeyboardInterrupt() from None
216
+ except Exception as exc:
217
+ items,ok,problems=[],False,[_exception_problem(exc)]
218
+ scope=json.dumps([platform.value,account,ident,'published'])
219
+ edited.update(store.observe(items,observed_at=observed,scope=scope,complete=ok))
220
+ observed_keys.update(store.key(i) for i in items)
221
+ row['scopes'].append({'media_id':ident,'filter':'published','complete':ok})
222
+ complete=complete and ok
223
+ errors.extend({**_problem_document(e),'platform':platform.value,'media_id':ident} for e in problems)
224
+ else:
225
+ meta=MetaClient(brand,platform,http)
226
+ listing=meta.content_list('posts' if platform is Platform.FACEBOOK else 'media',for_comments=True)
227
+ if listing.get('error'):
228
+ errors.append({**_partial_problem(listing),'platform':platform.value})
229
+ complete=listing['complete'];client=MetaInboxClient(brand,platform,http)
230
+ inbox=CommentInboxStore(brand.raiz)
231
+ for media in listing['data']:
232
+ budget.check();ident=media['id']
233
+ try:
234
+ result=sync_inbox(client,inbox,media_id=ident,since=since.isoformat(),resume=True)
235
+ results=[result]; problems=[];items=[]
236
+ def collect(observation):
237
+ row['unknown_author'] = row.get('unknown_author', 0) + observation.get('unknown_author', 0)
238
+ counts = row.setdefault('skipped_comments', {'own':0, 'before_since':0, 'unverifiable':0})
239
+ for label in counts:
240
+ counts[label] += observation.get('skipped_' + label, 0)
241
+ records=[r for r in inbox.load().comments if r.platform==platform.value and r.account_id==account and r.media_id==ident and (r.last_observed_at==observation['observed_at'] or r.comment_id==observation.get('reply_parent_id'))]
242
+ fresh=[{'platform':r.platform,'account_id':r.account_id,'media_id':r.media_id,'parent_id':r.parent_id,
243
+ 'comment_id':r.comment_id,'author_id':r.author_id,'text':r.text,'created_time':r.created_time,
244
+ 'provider_updated_at':r.provider_updated_at,'status':r.status,'draft_change_id':r.change_id,
245
+ **({'reply_evidence':r.reply_evidence} if r.reply_evidence else {})} for r in records]
246
+ edited.update(store.observe(fresh,observed_at=observed))
247
+ observed_keys.update(store.key(i) for i in fresh)
248
+ items.extend(fresh)
249
+ collect(result)
250
+ if result.get('interrupted'):
251
+ row['scopes'].append({'media_id':ident,'filter':'top_level_and_direct_replies','complete':False})
252
+ raise KeyboardInterrupt()
253
+ for parent_id in result['parent_ids']:
254
+ budget.check()
255
+ try:
256
+ reply_result=sync_inbox(client,inbox,media_id=ident,parent_id=parent_id,since=since.isoformat(),resume=True)
257
+ results.append(reply_result);collect(reply_result)
258
+ if reply_result.get('interrupted'):raise KeyboardInterrupt()
259
+ except Exception as exc:
260
+ problems.append(_exception_problem(exc))
261
+ except KeyboardInterrupt:
262
+ row['scopes'].append({'media_id':ident,'filter':'top_level_and_direct_replies','complete':False})
263
+ raise
264
+ ok=not problems and all(r['complete'] for r in results)
265
+ problems.extend(_partial_problem(r) for r in results if not r['complete'])
266
+ row['scopes'].append({'media_id':ident,'filter':'top_level_and_direct_replies','complete':ok})
267
+ except Exception as exc:
268
+ items,ok,problems=[],False,[_exception_problem(exc)]
269
+ scope=json.dumps([platform.value,account,ident,'top_level_and_direct_replies'])
270
+ edited.update(store.observe(items,observed_at=observed,scope=scope,complete=ok))
271
+ observed_keys.update(store.key(i) for i in items)
272
+ complete=complete and ok
273
+ errors.extend({**_problem_document(e),'platform':platform.value,'media_id':ident} for e in problems)
274
+ row['complete']=complete;row['state']='ok' if complete else 'partial'
275
+ if not complete and not any(e.get('platform')==platform.value for e in errors):errors.append({'platform':platform.value,'message':'Owned content enumeration incomplete'})
276
+ except (Exception,KeyboardInterrupt) as exc:
277
+ row['state']='partial' if row['scopes'] else 'error'
278
+ errors.append({**error_document(exc,read_only=True),'platform':platform.value,'message':'Read interrupted' if isinstance(exc,KeyboardInterrupt) else safe_error(str(exc))})
279
+ if isinstance(exc,KeyboardInterrupt):break
280
+ covered={r['platform'] for r in coverage}
281
+ for platform in platforms:
282
+ if platform.value not in covered:
283
+ coverage.append({'platform':platform.value,'account_id':(brand.cuentas.get(platform.value) or {}).get(fields[platform.value]),
284
+ 'complete':False,'scopes':[],'state':'not_attempted'})
285
+ errors.append({'platform':platform.value,'code':'not_attempted','message':'Not attempted after interruption'})
286
+ data=store.load();items=[]
287
+ for key in observed_keys:
288
+ item=data['items'][key];created=item.get('created_time')
289
+ if item.get('author_id') == item['account_id']:
290
+ continue
291
+ try:inside=created is None or datetime.fromisoformat(created.replace('Z','+00:00')).astimezone(timezone.utc)>=since
292
+ except (ValueError,AttributeError):inside=True
293
+ if inside or key in edited:items.append({**item,'edited_this_sync':key in edited})
294
+ status='ok' if coverage and all(r['complete'] for r in coverage) else 'partial' if observed_keys or any(r['complete'] or any(scope['complete'] for scope in r['scopes']) for r in coverage) else 'error'
295
+ return ReadReport(status=status,coverage=coverage,errors=errors,
296
+ data={'brand':brand.nombre,'resolved_since':since.isoformat(),'observed_until':observed,
297
+ 'filter_semantics':'created at/after since, plus previously observed comments edited during this sync',
298
+ 'items':sorted(items,key=lambda r:(r['platform'],r['account_id'],r['comment_id'])),'watermarks':data['watermarks']})
socialctl/inbox_cli.py ADDED
@@ -0,0 +1,46 @@
1
+ """Read/sync a brand's supported comment inbox without proposing remote effects."""
2
+ from datetime import datetime,timezone
3
+ from pathlib import Path
4
+ import typer
5
+ import yaml
6
+ from socialctl.inbox import resolve_since,sync_brand_inbox
7
+ from socialctl.read_budget import ReadBudget
8
+ from socialctl.read_reports import emit_report,ReadReport,safe_error,read_exit_code
9
+ from socialctl.models import Platform
10
+
11
+
12
+ def register(app,default_root):
13
+ from socialctl.engagement_cli import register as register_engagement
14
+ register_engagement(app,default_root)
15
+ from socialctl.brands import cargar_brand,BrandNoEncontrada,NombreDeMarcaInvalido,AccountsInvalido
16
+ @app.command('inbox')
17
+ def inbox(brand:str=typer.Option(...,'--brand'),since:str=typer.Option(...,'--since'),timezone_name:str|None=typer.Option(None,'--timezone'),json_output:bool=typer.Option(False,'--json'),timeout:float=typer.Option(300,'--timeout',help='Total read budget in seconds; use --only to give one platform the full budget.'),only:list[Platform]=typer.Option(None,'--only',help='Read only selected platforms; repeat to select more than one.'),root:Path=typer.Option(default_root,'--root')):
18
+ try:
19
+ selected=cargar_brand(root,brand)
20
+ zone=timezone_name
21
+ config=selected.raiz/'inbox.yml'
22
+ if zone is None and config.exists():
23
+ raw=yaml.safe_load(config.read_text())
24
+ if not isinstance(raw,dict) or set(raw)!={'version','timezone'} or type(raw['version']) is not int or raw['version']!=1:raise ValueError('inbox.yml requires version 1 and timezone')
25
+ zone=raw['timezone']
26
+ if not isinstance(zone,str) or not zone:raise ValueError('inbox.yml timezone must be an IANA name')
27
+ start=resolve_since(since,zone,datetime.now(timezone.utc))
28
+ budget=ReadBudget(timeout)
29
+ except (ValueError,OSError,yaml.YAMLError,BrandNoEncontrada,NombreDeMarcaInvalido,AccountsInvalido) as exc:
30
+ if json_output:emit_report(ReadReport(status='error',errors=[{'code':'invalid_input','message':safe_error(str(exc))}]))
31
+ else:typer.echo(safe_error(str(exc)),err=True)
32
+ raise typer.Exit(2)
33
+ try:
34
+ report=sync_brand_inbox(selected,since=start,budget=budget,**({"only":only} if only else {}))
35
+ except Exception as exc:
36
+ from socialctl.agent_errors import error_document
37
+ report=ReadReport(status='error',errors=[error_document(exc,read_only=True)])
38
+ if json_output:raise typer.Exit(emit_report(report))
39
+ typer.echo(report.errors[0]['message'],err=True)
40
+ raise typer.Exit(1)
41
+ if json_output:raise typer.Exit(emit_report(report))
42
+ typer.echo(f'Inbox for {brand} since {report.data["resolved_since"]}: {len(report.data["items"])} comments; {report.status}')
43
+ for coverage in report.coverage:typer.echo(f'{coverage["platform"]}: {coverage["state"]}')
44
+ for error in report.errors:typer.echo(error['message'],err=True)
45
+ for row in report.data['items']:typer.echo(f'{row["platform"]} {row["comment_id"]} — {row["text"]}')
46
+ raise typer.Exit(read_exit_code(report.status))