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
@@ -0,0 +1,587 @@
1
+ """Owned-media Meta comments; exact approval, durable intent, no ambiguous replay.
2
+
3
+ Facebook Login only, Graph v26.0. A successful create does not prove pinning or
4
+ link clickability. Missing/partial comment reads never prove remote absence.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import os
12
+ import re
13
+ import tempfile
14
+ import uuid
15
+ from urllib.parse import urlsplit, parse_qs
16
+ from pathlib import Path
17
+ from contextlib import ExitStack
18
+ from typing import Literal
19
+
20
+ import httpx
21
+ from socialctl.read_budget import ReadDeadlineExceeded, transport_label
22
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
23
+
24
+ from socialctl.agent_errors import with_error_code, with_http_error_code, error_document
25
+ from socialctl.auth import AuthError, obtener_token
26
+ from socialctl.brands import Brand
27
+ from socialctl.management.changes import ChangeError, ChangeStore, now_utc
28
+ from socialctl.models import Platform
29
+
30
+ GRAPH = "https://graph.facebook.com/v26.0"
31
+
32
+
33
+ class CommentError(ChangeError):
34
+ """Sanitized read, binding, approval or persistence failure."""
35
+
36
+
37
+ class CommentAlreadyVerified(CommentError):
38
+ """Duplicate blocked before any new write intent or provider mutation."""
39
+
40
+
41
+ class CommentRejected(CommentError):
42
+ pass
43
+
44
+
45
+ class CommentUncertain(CommentError):
46
+ pass
47
+
48
+
49
+ class CommentCursorRejected(CommentError):
50
+ """Graph rejected an opaque `after` cursor supplied by this client."""
51
+
52
+
53
+ def _id(value: str) -> str:
54
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9]+(?:_[0-9]+)*", value):
55
+ raise CommentError("Meta requires a numeric ID, not a URL or path")
56
+ return value
57
+
58
+
59
+ class MetaCommentsClient:
60
+ def __init__(self, brand: Brand, platform: Platform, client: httpx.Client):
61
+ if platform not in {Platform.FACEBOOK, Platform.INSTAGRAM}:
62
+ raise CommentError("comments available only for Facebook and Instagram")
63
+ self.brand, self.platform, self.client = brand, platform, client
64
+ self._access_token = None
65
+
66
+ @property
67
+ def account_id(self):
68
+ key = "page_id" if self.platform is Platform.FACEBOOK else "ig_user_id"
69
+ return _id((self.brand.cuentas.get(self.platform.value) or {}).get(key))
70
+
71
+ def _request(self, method, path, **kwargs):
72
+ try:
73
+ # Keep the authenticated token identical across preflight, mutation
74
+ # and read-back even if another process rotates the credential file.
75
+ if self._access_token is None:
76
+ self._access_token = obtener_token(self.brand, self.platform, self.client)
77
+ token = self._access_token
78
+ except AuthError as exc:
79
+ raise with_error_code(CommentError("Meta requires valid brand credentials"), exc, read_only=True) from None
80
+ writing = method != "GET"
81
+ probe_budget = getattr(self, '_probe_budget', None)
82
+ if probe_budget is not None and not writing:
83
+ probe_budget.check()
84
+ kwargs['timeout'] = min(10, probe_budget.remaining())
85
+ kwargs['extensions'] = {'socialcli_read_budget':probe_budget}
86
+ try:
87
+ response = self.client.request(method, f"{GRAPH}/{path}",
88
+ headers={"Authorization": f"Bearer {token}"}, follow_redirects=False, **kwargs)
89
+ except ReadDeadlineExceeded:
90
+ if writing:
91
+ raise CommentUncertain('Meta: transport deadline exceeded; outcome unconfirmed') from None
92
+ raise
93
+ except httpx.TransportError as exc:
94
+ error = CommentUncertain if writing else CommentError
95
+ raise with_error_code(error(f'Meta: transport interrupted ({transport_label(exc)}); outcome unconfirmed'), exc, read_only=not writing) from None
96
+ except Exception as exc:
97
+ error = CommentUncertain if writing else CommentError
98
+ raise with_error_code(error("Meta: transport interrupted; outcome unconfirmed" if writing else
99
+ "Meta: failed to complete read"), exc, read_only=not writing) from None
100
+ if not response.is_success:
101
+ params = kwargs.get("params") or {}
102
+ if method == "GET" and isinstance(params.get("after"), str):
103
+ try:
104
+ remote_error = response.json().get("error")
105
+ except Exception:
106
+ remote_error = None
107
+ if isinstance(remote_error, dict):
108
+ message = remote_error.get("message")
109
+ if (remote_error.get("code") == 100 and isinstance(message, str)
110
+ and "cursor" in message.casefold()):
111
+ raise CommentCursorRejected(
112
+ "Meta rejected saved incremental cursor")
113
+ error = (CommentUncertain if response.status_code >= 500 or response.is_redirect
114
+ else CommentRejected) if writing else CommentError
115
+ from socialctl.management.meta_errors import graph_error
116
+ raise with_http_error_code(error(graph_error(response, method, path, token)), response, read_only=not writing)
117
+ try:
118
+ data = response.json()
119
+ if not isinstance(data, dict) or "error" in data:
120
+ raise ValueError()
121
+ except Exception:
122
+ raise (CommentUncertain if writing else CommentError)("Meta: unverifiable response") from None
123
+ return data
124
+
125
+ def inspect_media(self, media_id):
126
+ media_id = _id(media_id)
127
+ configured = self.account_id
128
+ me = self._request("GET", "me", params={"fields": "id,instagram_business_account"}
129
+ if self.platform is Platform.INSTAGRAM else {"fields": "id"})
130
+ page = _id((self.brand.cuentas.get("facebook") or {}).get("page_id"))
131
+ if me.get("id") != page:
132
+ raise CommentError("authenticated Page does not match brand")
133
+ if self.platform is Platform.INSTAGRAM and (me.get("instagram_business_account") or {}).get("id") != configured:
134
+ raise CommentError("authenticated Instagram account does not match brand")
135
+ owner_field = "from" if self.platform is Platform.FACEBOOK else "owner"
136
+ media = self._request("GET", media_id, params={"fields": f"id,{owner_field}"})
137
+ if media.get("id") != media_id or (media.get(owner_field) or {}).get("id") != configured:
138
+ raise CommentError("exact media owner was not verified")
139
+ return {"id": media_id, "owner_id": configured, "authenticated_page": page}
140
+
141
+ def list_comments(self, media_id, *, parent_id=None, max_pages=100, include_moderation=False,
142
+ after=None):
143
+ if type(include_moderation) is not bool:
144
+ raise CommentError("include_moderation must be boolean")
145
+ self.inspect_media(media_id)
146
+ if parent_id:
147
+ parent_id = self.find_comment(media_id, parent_id)["id"]
148
+ return self._list(parent_id or media_id,
149
+ "replies" if parent_id and self.platform is Platform.INSTAGRAM else "comments", max_pages,
150
+ include_moderation=include_moderation, after=after)
151
+
152
+ def _list(self, target, edge, max_pages=100, *, include_moderation=False, after=None):
153
+ path = f"{_id(target)}/{edge}"
154
+ fields = ("id,message,from{id,name},created_time,parent,is_hidden"
155
+ if self.platform is Platform.FACEBOOK else
156
+ "id,text,from{id,username},timestamp,parent_id,hidden")
157
+ if not include_moderation:
158
+ fields = ("id,message,from{id,name},created_time,parent"
159
+ if self.platform is Platform.FACEBOOK else
160
+ "id,text,from{id,username},timestamp,parent_id")
161
+ if self.platform is Platform.FACEBOOK:
162
+ fields += ',permalink_url'
163
+ params = {"fields": fields, "limit": "100"}
164
+ if after is not None:
165
+ if not isinstance(after, str) or not re.fullmatch(r"[A-Za-z0-9_=-]{1,2048}", after):
166
+ raise CommentError("invalid incremental cursor")
167
+ params["after"] = after
168
+ rows, cursors, last_cursor = [], ({after} if after else set()), None
169
+ for _ in range(max_pages):
170
+ try:
171
+ payload = self._request("GET", path, params=params)
172
+ except KeyboardInterrupt:
173
+ if not rows: raise
174
+ return {"data":rows, "complete":False, "absence_proven":False,
175
+ "next_cursor":params.get("after"), "error":"Read interrupted", "interrupted":True}
176
+ except CommentCursorRejected as exc:
177
+ if not rows: raise
178
+ return {"data":rows, "complete":False, "absence_proven":False,
179
+ "next_cursor":None, "error":str(exc)}
180
+ except CommentError as exc:
181
+ if not rows: raise
182
+ return {"data":rows, "complete":False, "absence_proven":False,
183
+ "next_cursor":params.get("after"), "error":str(exc),
184
+ "error_detail":error_document(exc, read_only=True)}
185
+ except ReadDeadlineExceeded as exc:
186
+ if not rows: raise
187
+ return {"data":rows, "complete":False, "absence_proven":False,
188
+ "next_cursor":params.get("after"), "error":str(exc), "timed_out":True}
189
+ data = payload.get("data")
190
+ if not isinstance(data, list) or any(not isinstance(row, dict) for row in data):
191
+ if not rows: raise CommentError("Meta: invalid comments list")
192
+ return {"data":rows, "complete":False, "absence_proven":False,
193
+ "next_cursor":params.get("after"), "error":"Meta: invalid later comments page"}
194
+ rows.extend(data)
195
+ paging = payload.get("paging", {})
196
+ if not isinstance(paging, dict):
197
+ break
198
+ if not paging.get("next"):
199
+ return {"data": rows, "complete": True, "absence_proven": False,
200
+ "next_cursor": None}
201
+ cursor = (paging.get("cursors") or {}).get("after")
202
+ if not isinstance(cursor, str) or not re.fullmatch(r"[A-Za-z0-9_=-]{1,2048}", cursor) or cursor in cursors:
203
+ break
204
+ cursors.add(cursor)
205
+ last_cursor = cursor
206
+ params = {**params, "after": cursor}
207
+ return {"data": rows, "complete": False, "absence_proven": False,
208
+ "next_cursor": last_cursor}
209
+
210
+ def find_comment(self, media_id, comment_id, *, parent_id=None, own=False):
211
+ comment_id = _id(comment_id)
212
+ if parent_id:
213
+ parent_id = self.find_comment(media_id, parent_id)["id"]
214
+ result = self.list_comments(media_id, parent_id=parent_id)
215
+ matches = [row for row in result["data"] if row.get("id") == comment_id]
216
+ if not matches and self.platform is Platform.FACEBOOK:
217
+ # Graph can return a video-scoped receipt but a post-scoped edge ID.
218
+ # Bind both through the specific provider permalink, never a suffix.
219
+ direct = self.inspect_comment(comment_id)
220
+ url = self._specific_permalink(direct)
221
+ author = (direct.get('from') or {}).get('id')
222
+ if (direct.get('id') != comment_id or not isinstance(author, str)
223
+ or not author or not isinstance(direct.get('message'), str)
224
+ or (direct.get('parent') or {}).get('id') not in {None, parent_id or media_id}
225
+ or (direct.get('object') or {}).get('id') not in {None, media_id}):
226
+ raise CommentError('comment alias identity or target is not verified')
227
+ matches = [row for row in result['data'] if row.get('permalink_url') == url]
228
+ if len(matches) != 1 or ((matches[0].get('from') or {}).get('id') != author
229
+ or matches[0].get('message') != direct['message']):
230
+ raise CommentError('comment alias membership is not unambiguous')
231
+ if len(matches) != 1:
232
+ raise CommentError("comment not verified on media; absence or permissions inconclusive")
233
+ row = matches[0]
234
+ if self.platform is Platform.FACEBOOK:
235
+ explicit_parent = (row.get('parent') or {}).get('id')
236
+ if explicit_parent is not None and explicit_parent != (parent_id or media_id):
237
+ raise CommentError('comment parent differs from requested target')
238
+ elif row.get('parent_id') is not None and row['parent_id'] != parent_id:
239
+ raise CommentError('comment parent differs from requested target')
240
+ field = "message" if self.platform is Platform.FACEBOOK else "text"
241
+ if not isinstance(row.get(field), str):
242
+ raise CommentError("comment does not return verifiable text")
243
+ author = row.get("from") or {}
244
+ if own and author.get("id") != self.account_id:
245
+ raise CommentError("comment's own author was not verified by ID")
246
+ return {"id": _id(row.get('id')), "text": row[field], "author_id": author.get("id"),
247
+ "media_id": media_id, "parent_id": parent_id}
248
+
249
+ def inspect_comment(self, comment_id: str) -> dict:
250
+ if self.platform is not Platform.FACEBOOK:
251
+ raise CommentError('direct comment inspection is supported here only for Facebook')
252
+ comment_id = _id(comment_id)
253
+ return self._request('GET', comment_id,
254
+ params={'fields':'id,message,from{id},parent{id},object{id},permalink_url'})
255
+
256
+ @staticmethod
257
+ def _specific_permalink(row):
258
+ url = row.get('permalink_url')
259
+ if not isinstance(url, str) or len(url) > 2048:
260
+ raise CommentError('comment permalink unavailable')
261
+ try:
262
+ parsed = urlsplit(url)
263
+ query = parse_qs(parsed.query, strict_parsing=True)
264
+ comment = query.get('comment_id', [])
265
+ valid = (parsed.scheme == 'https' and parsed.netloc == 'www.facebook.com'
266
+ and not parsed.fragment and len(comment) == 1
267
+ and re.fullmatch(r'[0-9]+', comment[0]))
268
+ except ValueError:
269
+ valid = False
270
+ if not valid:
271
+ raise CommentError('comment permalink is not a specific Facebook comment')
272
+ return url
273
+
274
+ def _permalink_membership(self, change, row):
275
+ # A received write ID and its exact direct GET are prerequisites. Never
276
+ # invent an alias from numeric suffixes or adopt a text-only candidate.
277
+ url = self._specific_permalink(row)
278
+ listing = self.list_comments(change.media_id, parent_id=change.parent_id)
279
+ matches = [candidate for candidate in listing['data']
280
+ if candidate.get('permalink_url') == url]
281
+ if len(matches) != 1:
282
+ raise CommentError('comment permalink membership is not unambiguous')
283
+ candidate = matches[0]
284
+ parent = (candidate.get('parent') or {}).get('id')
285
+ if ((candidate.get('from') or {}).get('id') != self.account_id
286
+ or candidate.get('message') != change.text
287
+ or parent not in {None, change.parent_id or change.media_id}):
288
+ raise CommentError('comment permalink member contradicts approved effect')
289
+ return {'id': _id(candidate.get('id')), 'text': row['message'], 'author_id': self.account_id,
290
+ 'media_id': change.media_id, 'parent_id': change.parent_id}
291
+
292
+ def verify_comment(self, change):
293
+ from socialctl.read_budget import ReadBudget
294
+ self._probe_budget = ReadBudget(10)
295
+ try:
296
+ return self._verify_comment(change)
297
+ except httpx.HTTPError:
298
+ raise CommentError('Meta comment verification exceeded its read budget or failed') from None
299
+ finally:
300
+ self._probe_budget = None
301
+
302
+ def _verify_comment(self, change):
303
+ current = None
304
+ if self.platform is Platform.FACEBOOK:
305
+ self.inspect_media(change.media_id)
306
+ row = None
307
+ # Read-only eventual-consistency probes. A missing direct read can fall
308
+ # back to exact membership; a contradictory object never becomes proof.
309
+ for _ in range(3):
310
+ try:
311
+ row = self.inspect_comment(change.remote_id)
312
+ break
313
+ except CommentError:
314
+ pass
315
+ if row is not None:
316
+ parent = (row.get('parent') or {}).get('id')
317
+ media = (row.get('object') or {}).get('id')
318
+ target_matches = (parent == change.parent_id and media in {None, change.media_id}) if change.parent_id else (
319
+ media == change.media_id and parent is None or parent == change.media_id and media in {None, change.media_id})
320
+ if row.get('id') != change.remote_id or (row.get('from') or {}).get('id') != self.account_id or row.get('message') != change.text:
321
+ raise CommentError('direct comment identity, actor or target does not match approved effect')
322
+ if not target_matches:
323
+ if parent is not None or media is not None:
324
+ raise CommentError('direct comment target contradicts approved effect')
325
+ current = self._permalink_membership(change, row)
326
+ else:
327
+ current = {'id':row['id'], 'text':row.get('message'), 'author_id':self.account_id,
328
+ 'media_id':change.media_id, 'parent_id':change.parent_id}
329
+ if current is None:
330
+ current = self.find_comment(change.media_id, change.remote_id,
331
+ parent_id=change.parent_id, own=True)
332
+ if current["text"] != change.text:
333
+ raise CommentError("remote text differs from approved text")
334
+ return current
335
+
336
+ def write(self, change):
337
+ if change.action == "delete":
338
+ result = self._request("DELETE", _id(change.comment_id))
339
+ elif change.action == "edit":
340
+ result = self._request("POST", _id(change.comment_id), data={"message": change.text})
341
+ else:
342
+ edge = "replies" if change.action == "reply" and self.platform is Platform.INSTAGRAM else "comments"
343
+ result = self._request("POST", f"{_id(change.parent_id or change.media_id)}/{edge}",
344
+ data={"message": change.text})
345
+ if change.action in {"delete", "edit"}:
346
+ if result.get("success") is not True:
347
+ raise CommentUncertain("Meta did not confirm comment mutation")
348
+ return change.comment_id
349
+ try:
350
+ return _id(result.get("id"))
351
+ except CommentError:
352
+ raise CommentUncertain("Meta did not return a valid comment ID; do not repeat") from None
353
+
354
+
355
+ class CommentChange(BaseModel):
356
+ model_config = ConfigDict(extra="forbid")
357
+ id: str
358
+ version: Literal[1] = 1
359
+ platform: Literal["facebook", "instagram"]
360
+ brand: str
361
+ brand_root: str
362
+ account_id: str
363
+ authenticated_page: str
364
+ media_id: str
365
+ action: Literal["add", "reply", "edit", "delete"]
366
+ parent_id: str | None = None
367
+ comment_id: str | None = None
368
+ text: str | None = None
369
+ before: dict
370
+ created_at: str
371
+ inbox_binding: dict[str, str] | None = None
372
+ fingerprint: str = ""
373
+ status: Literal["proposed", "applying", "uncertain", "rejected", "verified", "applied_unverified"] = "proposed"
374
+ remote_id: str | None = None
375
+ candidates: list[str] = Field(default_factory=list)
376
+ journal: list[dict] = Field(default_factory=list)
377
+
378
+
379
+ MUTABLE = {"fingerprint", "status", "remote_id", "candidates", "journal"}
380
+
381
+
382
+ def fingerprint(change):
383
+ # `inbox_binding` was added after version 1 shipped. Excluding its default
384
+ # preserves fingerprints for pre-existing standalone ChangeSets, while a
385
+ # populated binding becomes immutable and is covered by the approval hash.
386
+ excluded = MUTABLE | ({"inbox_binding"} if change.inbox_binding is None else set())
387
+ data = change.model_dump(mode="json", exclude=excluded)
388
+ return hashlib.sha256(json.dumps(data, sort_keys=True, ensure_ascii=False,
389
+ separators=(",", ":")).encode()).hexdigest()
390
+
391
+
392
+ class CommentStore(ChangeStore):
393
+ """Separate schema/namespace, shared UUID validation and interprocess lock."""
394
+ def __init__(self, brand_root: Path):
395
+ self.root = brand_root / ".socialctl" / "comments"
396
+
397
+ def load(self, change_id):
398
+ try:
399
+ change = CommentChange.model_validate_json(self.path_for(change_id).read_text())
400
+ except (OSError, ValidationError):
401
+ raise CommentError("failed to read comment ChangeSet") from None
402
+ if change.id != change_id or not hmac.compare_digest(fingerprint(change), change.fingerprint):
403
+ raise CommentError("comment proposal was altered")
404
+ return change
405
+
406
+ def save(self, change):
407
+ if not hmac.compare_digest(fingerprint(change), change.fingerprint):
408
+ raise CommentError("comment proposal was altered")
409
+ self.write_json(change.id, change.model_dump(mode="json"))
410
+
411
+ def write_json(self, identifier, payload):
412
+ path = self.path_for(identifier)
413
+ temporary = None
414
+ try:
415
+ self._ensure_root()
416
+ fd, temporary = tempfile.mkstemp(prefix=f"{identifier}.", suffix=".tmp", dir=self.root)
417
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
418
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
419
+ handle.flush()
420
+ os.fsync(handle.fileno())
421
+ os.replace(temporary, path)
422
+ self._sync_directory(self.root)
423
+ except OSError:
424
+ if temporary:
425
+ try: os.unlink(temporary)
426
+ except OSError: pass
427
+ raise CommentError("failed to persist durable journal; next step blocked") from None
428
+
429
+
430
+ def _validate_operation(client, *, action, text, parent_id, comment_id):
431
+ if action not in {"add", "reply", "edit", "delete"}:
432
+ raise CommentError("unknown action")
433
+ if action == "edit" and client.platform is Platform.INSTAGRAM:
434
+ raise CommentError("Instagram: text editing is unavailable; content will not be deleted and recreated")
435
+ if action != "delete" and (not isinstance(text, str) or not text.strip()):
436
+ raise CommentError("explicit nonempty text required")
437
+ if action == "delete" and text is not None:
438
+ raise CommentError("delete does not accept text")
439
+ if ((action == "reply" and parent_id is None) or (action == "add" and parent_id is not None)
440
+ or (action in {"edit", "delete"}) != (comment_id is not None)):
441
+ raise CommentError("parent/comment IDs incompatible with action")
442
+
443
+
444
+ def prepare_comment(client, store, *, media_id, text=None, action="add", parent_id=None,
445
+ comment_id=None, inbox_binding=None, reply_context=None):
446
+ _validate_operation(client, action=action, text=text, parent_id=parent_id, comment_id=comment_id)
447
+ media = client.inspect_media(media_id)
448
+ before = {"media": media}
449
+ if parent_id:
450
+ before["parent"] = client.find_comment(media_id, parent_id)
451
+ parent_id = before["parent"]["id"]
452
+ if comment_id:
453
+ before["comment"] = client.find_comment(media_id, comment_id, parent_id=parent_id, own=True)
454
+ comment_id = before["comment"]["id"]
455
+ if reply_context is not None:
456
+ from socialctl.management.reply_context import verify_reply_context
457
+ verify_reply_context(client, reply_context, media_id=media_id, parent_id=parent_id)
458
+ before['reply_context'] = reply_context
459
+ change = CommentChange(id=str(uuid.uuid4()), platform=client.platform.value,
460
+ brand=client.brand.nombre, brand_root=str(client.brand.raiz.resolve()),
461
+ account_id=client.account_id, authenticated_page=media["authenticated_page"],
462
+ media_id=media_id, action=action, parent_id=parent_id, comment_id=comment_id,
463
+ text=text, before=before, created_at=now_utc().isoformat(),
464
+ inbox_binding=inbox_binding)
465
+ change.fingerprint = fingerprint(change)
466
+ store.save(change)
467
+ return change
468
+
469
+
470
+ def _bound(client, change):
471
+ _validate_operation(client, action=change.action, text=change.text,
472
+ parent_id=change.parent_id, comment_id=change.comment_id)
473
+ if (change.brand, change.brand_root, change.platform, change.account_id) != (
474
+ client.brand.nombre, str(client.brand.raiz.resolve()), client.platform.value, client.account_id):
475
+ raise CommentError("configured brand/account does not match proposal")
476
+ if client.inspect_media(change.media_id) != change.before["media"]:
477
+ raise CommentError("remote identity or ownership changed")
478
+
479
+
480
+ def _event(change, event):
481
+ change.journal.append({"at": now_utc().isoformat(), "event": event})
482
+
483
+
484
+ def _reconcile(client, store, change):
485
+ _bound(client, change)
486
+ if change.status in {"verified", "rejected", "proposed"}:
487
+ return change
488
+ try:
489
+ if change.remote_id and change.action != "delete":
490
+ client.verify_comment(change)
491
+ change.status = "verified"
492
+ _event(change, "read_back_verified")
493
+ elif change.action == "delete":
494
+ # A missing node / empty edge can also mean lost permission.
495
+ client.list_comments(change.media_id)
496
+ _event(change, "delete_read_back_not_proof_of_absence")
497
+ else:
498
+ listing = client.list_comments(change.media_id, parent_id=change.parent_id)
499
+ field = "message" if client.platform is Platform.FACEBOOK else "text"
500
+ change.candidates = [row["id"] for row in listing["data"]
501
+ if row.get(field) == change.text and isinstance(row.get("id"), str)]
502
+ change.status = "uncertain"
503
+ _event(change, "candidates_are_not_creation_proof")
504
+ except CommentError:
505
+ _event(change, "read_back_incomplete_or_denied")
506
+ store.save(change)
507
+ return change
508
+
509
+
510
+ def reconcile_comment(client, store, change_id):
511
+ with store.apply_lock(change_id):
512
+ return _reconcile(client, store, store.load(change_id))
513
+
514
+
515
+ def operation_key(change):
516
+ return json.dumps([change.brand_root, change.platform, change.account_id, change.media_id])
517
+
518
+
519
+ def _same_verified_operation(client, previous, proposed):
520
+ if (previous.action, previous.text) != (proposed.action, proposed.text):
521
+ return False
522
+ old_parent, new_parent = previous.parent_id, proposed.parent_id
523
+ if (old_parent is None) != (new_parent is None):
524
+ return False
525
+ old_comment, new_comment = previous.comment_id, proposed.comment_id
526
+ if (old_comment is None) != (new_comment is None):
527
+ return False
528
+ if client.platform is Platform.FACEBOOK:
529
+ # Historical fingerprints and targets remain immutable. Resolve differing
530
+ # IDs only for comparison; an unreadable history cannot authorize replay.
531
+ try:
532
+ if old_parent != new_parent:
533
+ old_parent = client.find_comment(previous.media_id, old_parent)['id']
534
+ new_parent = client.find_comment(proposed.media_id, new_parent)['id']
535
+ if old_parent != new_parent:
536
+ return False
537
+ if old_comment != new_comment:
538
+ old_comment = client.find_comment(previous.media_id, old_comment,
539
+ parent_id=old_parent)['id']
540
+ new_comment = client.find_comment(proposed.media_id, new_comment,
541
+ parent_id=new_parent)['id']
542
+ except CommentError:
543
+ raise CommentError('previous verified operation cannot be distinguished safely; inspect its receipt before another write') from None
544
+ return (old_parent, old_comment) == (new_parent, new_comment)
545
+
546
+
547
+ def apply_comment(client, store, change_id, approval_digest):
548
+ with ExitStack() as locks:
549
+ locks.enter_context(store.apply_lock(change_id))
550
+ change = store.load(change_id)
551
+ if not hmac.compare_digest(approval_digest, change.fingerprint):
552
+ raise CommentError("approval does not match exact fingerprint")
553
+ locks.enter_context(store.apply_lock(str(uuid.uuid5(uuid.NAMESPACE_URL, operation_key(change)))))
554
+ _bound(client, change)
555
+ if change.status != "proposed":
556
+ return _reconcile(client, store, change)
557
+ for path in store.root.glob('*.json'):
558
+ other = store.load(path.stem)
559
+ if other.id != change.id and operation_key(other) == operation_key(change):
560
+ if other.status in {'applying','uncertain'}:
561
+ raise CommentError(f'uncertain outcome pending in {other.id}; another UUID cannot replay it')
562
+ if other.status == 'verified' and _same_verified_operation(client, other, change):
563
+ raise CommentAlreadyVerified('identical verified operation already exists; no new write started')
564
+ if change.parent_id and client.find_comment(change.media_id, change.parent_id) != change.before["parent"]:
565
+ raise CommentError("parent comment changed since preview")
566
+ if change.before.get('reply_context'):
567
+ from socialctl.management.reply_context import verify_reply_context
568
+ verify_reply_context(client, change.before['reply_context'], media_id=change.media_id, parent_id=change.parent_id)
569
+ if change.comment_id and client.find_comment(change.media_id, change.comment_id,
570
+ parent_id=change.parent_id, own=True) != change.before["comment"]:
571
+ raise CommentError("comment changed since preview")
572
+ change.status = "applying"
573
+ _event(change, "approved_exact_digest_and_write_intent")
574
+ store.save(change) # Failure here MUST block remote mutation.
575
+ try:
576
+ change.remote_id = client.write(change)
577
+ except CommentRejected:
578
+ change.status = "rejected"
579
+ _event(change, "remote_rejected_check_permissions")
580
+ except CommentUncertain:
581
+ change.status = "uncertain"
582
+ _event(change, "remote_outcome_uncertain_never_auto_repost")
583
+ else:
584
+ change.status = "applied_unverified" if change.action == "delete" else "uncertain"
585
+ _event(change, "remote_id_received")
586
+ store.save(change) # ID durable BEFORE read-back or any other remote step.
587
+ return _reconcile(client, store, change)
@@ -0,0 +1,59 @@
1
+ """Bounded Graph diagnostics; HTTP 400 alone never identifies a permission."""
2
+ import json
3
+ import re
4
+ from socialctl.read_reports import safe_error
5
+
6
+
7
+ def graph_error(response, method, path, token, *, payload=None):
8
+ try:
9
+ if payload is None:
10
+ raw = bytearray()
11
+ for chunk in response.iter_bytes(chunk_size=4096):
12
+ raw.extend(chunk)
13
+ if len(raw) > 65536:
14
+ raise ValueError()
15
+ payload = json.loads(raw)
16
+ error = payload.get('error', {})
17
+ if not isinstance(error, dict):
18
+ error = {}
19
+ except Exception:
20
+ error = {}
21
+ code, subcode = error.get('code'), error.get('error_subcode')
22
+ detail = f'Meta HTTP {response.status_code} during {method} {path}'
23
+ if type(code) is int:
24
+ detail += f'; code={code}'
25
+ if type(subcode) is int:
26
+ detail += f'; subcode={subcode}'
27
+ trace = error.get('fbtrace_id')
28
+ if isinstance(trace, str) and re.fullmatch(r'[A-Za-z0-9_-]{1,200}', trace):
29
+ detail += f'; reference={trace}'
30
+ message = error.get('message')
31
+ if isinstance(message, str):
32
+ detail += '; ' + safe_error(message, secrets=(token,))
33
+ if code in {190, 459}:
34
+ detail += '; Reconnect this account after resolving provider login/token checks.'
35
+ elif code in {10, 200, 283}:
36
+ detail += '; Check granted permissions, app eligibility and Page tasks; reconnect after consent changes.'
37
+ if path.endswith('/likes') and method != 'GET':
38
+ detail += ' Facebook likes require a Page token and pages_manage_engagement; object eligibility also applies.'
39
+ elif code == 100:
40
+ detail += '; Check the target ID, supported fields and operation; this code does not identify a missing permission.'
41
+ elif code in {4, 17, 32, 613, 80001}:
42
+ detail += '; Provider rate limit: wait before a new read; do not replay an uncertain write.'
43
+ elif code == 368:
44
+ detail += '; Provider disallowed the action; check object/account eligibility.'
45
+ return safe_error(detail, secrets=(token,))
46
+
47
+
48
+ def failure_details(exc, *, token, read_only):
49
+ """Persist bounded diagnostics, never arbitrary exception bodies or headers."""
50
+ from socialctl.agent_errors import error_document
51
+ from socialctl.management.meta_schema import MetaError
52
+
53
+ detail = error_document(exc, read_only=read_only)
54
+ message = str(exc) if isinstance(exc, MetaError) else detail['message']
55
+ result = {'error': safe_error(message, secrets=(token,)), 'error_detail': detail}
56
+ diagnostic = getattr(exc, '_meta_diagnostic', None)
57
+ if diagnostic is not None:
58
+ result['diagnostic'] = diagnostic
59
+ return result