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,713 @@
1
+ """Durable Meta Stories with exact approval and no blind remote replay.
2
+
3
+ Instagram uses the public container flow (``media_type=STORIES``). Facebook
4
+ Page Stories is a documented public capability, but its distinct photo/video
5
+ upload contract is deliberately left as an explicit handoff in this phase.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import time
13
+ import uuid
14
+ from contextlib import ExitStack
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+ from typing import Literal
18
+
19
+ import httpx
20
+ from pydantic import BaseModel, ConfigDict, Field
21
+
22
+ from socialctl.hosted_media import HostedMediaError, file_digest, validate_url
23
+ from socialctl.management.changes import ChangeError, ChangeStore, now_utc
24
+ from socialctl.management.meta_client import MetaClient
25
+ from socialctl.management.meta_schema import MetaError, MetaRejected, MetaUncertain, meta_id
26
+ from socialctl.media import MediaInvalida, _ffprobe, _rotacion_grados
27
+ from socialctl.models import MediaKind, Platform, StoryPost
28
+
29
+
30
+ class StoryError(ChangeError):
31
+ """Sanitized validation, binding, persistence or state error."""
32
+
33
+
34
+ # Contrato conservador de Instagram Stories documentado por Meta. Meta expresa
35
+ # estos límites en MB decimales: JPEG hasta 8 MB; MP4/MOV H.264 o HEVC, audio
36
+ # AAC cuando exista, 3-60 s y hasta 100 MB.
37
+ # https://developers.facebook.com/documentation/instagram-platform/
38
+ # instagram-graph-api/reference/ig-user/media
39
+ STORY_IMAGE_MAX_BYTES = 8 * 1000**2
40
+ STORY_VIDEO_MAX_BYTES = 100 * 1000**2
41
+ STORY_VIDEO_MIN_DURATION_S = 3.0
42
+ STORY_VIDEO_MAX_DURATION_S = 60.0
43
+ STORY_VIDEO_CODECS = frozenset({"h264", "hevc"})
44
+ STORY_AUDIO_CODEC = "aac"
45
+
46
+
47
+ class StoryChange(BaseModel):
48
+ model_config = ConfigDict(extra="forbid")
49
+
50
+ id: str
51
+ version: Literal[1] = 1
52
+ kind: Literal["meta-story"] = "meta-story"
53
+ brand: str
54
+ brand_root: str
55
+ account_id: str
56
+ story: StoryPost
57
+ relative_media: str
58
+ media_sha256: str
59
+ media_size_bytes: int = Field(gt=0)
60
+ dedupe_key: str
61
+ capability: Literal[
62
+ "instagram_public_api_write_grant_unverified",
63
+ "facebook_page_stories_api_pending_implementation",
64
+ ]
65
+ created_at: datetime
66
+ updated_at: datetime
67
+ fingerprint: str = ""
68
+ status: Literal[
69
+ "prepared",
70
+ "approved",
71
+ "applying",
72
+ "container_created",
73
+ "publishing",
74
+ "sent",
75
+ "verified",
76
+ "uncertain",
77
+ "blocked",
78
+ "expired",
79
+ "handoff_required",
80
+ ] = "prepared"
81
+ container_id: str | None = None
82
+ remote_id: str | None = None
83
+ receipt: dict | None = None
84
+ last_error: str | None = None
85
+ journal: list[dict] = Field(default_factory=list)
86
+
87
+
88
+ _MUTABLE = {
89
+ "fingerprint",
90
+ "updated_at",
91
+ "status",
92
+ "container_id",
93
+ "remote_id",
94
+ "receipt",
95
+ "last_error",
96
+ "journal",
97
+ }
98
+
99
+
100
+ def story_fingerprint(change: StoryChange) -> str:
101
+ raw = change.model_dump(mode="json", exclude=_MUTABLE)
102
+ encoded = json.dumps(
103
+ raw, sort_keys=True, ensure_ascii=False, separators=(",", ":")
104
+ ).encode("utf-8")
105
+ return hashlib.sha256(encoded).hexdigest()
106
+
107
+
108
+ class StoryStore(ChangeStore):
109
+ model_type = StoryChange
110
+ fingerprint_for = staticmethod(story_fingerprint)
111
+
112
+ def __init__(self, brand_root: Path):
113
+ self.root = Path(brand_root) / ".socialctl" / "stories"
114
+
115
+
116
+ def _event(change: StoryChange, name: str, **details) -> None:
117
+ change.updated_at = now_utc()
118
+ change.journal.append({"at": change.updated_at.isoformat(), "event": name, **details})
119
+
120
+
121
+ def _read_edges(path: Path) -> tuple[bytes, bytes]:
122
+ try:
123
+ with path.open("rb") as handle:
124
+ head = handle.read(64)
125
+ handle.seek(-2, 2)
126
+ tail = handle.read(2)
127
+ except OSError as exc:
128
+ raise StoryError(f"failed to inspect Story media: {exc}") from None
129
+ return head, tail
130
+
131
+
132
+ def _probe_story(path: Path, kind: MediaKind, extension: str) -> tuple[int, int, float | None]:
133
+ """Validate actual container/codec and return observed metadata."""
134
+ head, tail = _read_edges(path)
135
+ if kind is MediaKind.IMAGE and (
136
+ not head.startswith(b"\xff\xd8\xff") or tail != b"\xff\xd9"
137
+ ):
138
+ raise StoryError("unsupported actual image format: JPEG bytes required")
139
+ if kind is MediaKind.VIDEO and (
140
+ len(head) < 12 or head[4:8] != b"ftyp"
141
+ ):
142
+ raise StoryError("unsupported actual video format: MP4 or MOV container required")
143
+ try:
144
+ probe = _ffprobe(path)
145
+ except (MediaInvalida, OSError, ValueError, json.JSONDecodeError) as exc:
146
+ raise StoryError(f"media does not contain an actual readable {extension.upper()}: {exc}") from None
147
+
148
+ streams = probe.get("streams") or []
149
+ video_stream = next(
150
+ (stream for stream in streams if stream.get("codec_type") == "video"),
151
+ streams[0] if streams else None,
152
+ )
153
+ if not isinstance(video_stream, dict):
154
+ raise StoryError("Story media does not contain a readable image or video track")
155
+ width = video_stream.get("width")
156
+ height = video_stream.get("height")
157
+ if not isinstance(width, int) or not isinstance(height, int) or width <= 0 or height <= 0:
158
+ raise StoryError("Story media must have positive actual dimensions")
159
+ if _rotacion_grados(video_stream) % 180 == 90:
160
+ width, height = height, width
161
+
162
+ format_name = str((probe.get("format") or {}).get("format_name") or "")
163
+ codec = str(video_stream.get("codec_name") or "").lower()
164
+ if kind is MediaKind.IMAGE:
165
+ # ffprobe may select the generic image2 demuxer for a valid JPEG.
166
+ # Retain the byte signature and codec checks above/below.
167
+ if codec != "mjpeg" or not ("jpeg" in format_name or format_name == "image2"):
168
+ raise StoryError("unsupported actual image format: readable JPEG required")
169
+ return width, height, None
170
+
171
+ if "mp4" not in format_name:
172
+ raise StoryError("unsupported actual video format: MP4 or MOV container required")
173
+ if codec not in STORY_VIDEO_CODECS:
174
+ raise StoryError("unsupported Story codec: use H.264 or HEVC video")
175
+ audio_streams = [
176
+ stream for stream in streams if stream.get("codec_type") == "audio"
177
+ ]
178
+ if any(
179
+ str(stream.get("codec_name") or "").lower() != STORY_AUDIO_CODEC
180
+ for stream in audio_streams
181
+ ):
182
+ raise StoryError("unsupported Story audio codec: use AAC")
183
+ raw_duration = (probe.get("format") or {}).get("duration")
184
+ try:
185
+ duration = float(raw_duration)
186
+ except (TypeError, ValueError):
187
+ raise StoryError("Story video must have a verifiable actual duration") from None
188
+ return width, height, duration
189
+
190
+
191
+ def _media_contract(story: StoryPost, brand) -> tuple[StoryPost, str, str, int]:
192
+ media_root = (brand.raiz / "media").resolve()
193
+ if story.media.path.is_symlink():
194
+ raise StoryError("Story media must be a regular file, not a symlink")
195
+ try:
196
+ path = story.media.path.resolve(strict=True)
197
+ relative = path.relative_to(media_root).as_posix()
198
+ except (OSError, ValueError):
199
+ raise StoryError("Story media must exist inside the brand media folder") from None
200
+ if not path.is_file():
201
+ raise StoryError("Story media must be a regular file, not a symlink")
202
+
203
+ extension = path.suffix.lower()
204
+ image_extensions = {".jpg", ".jpeg"}
205
+ video_extensions = {".mp4", ".mov"}
206
+ if story.media.kind is MediaKind.IMAGE and extension not in image_extensions:
207
+ raise StoryError("unsupported Story image format: use JPEG (.jpg or .jpeg)")
208
+ if story.media.kind is MediaKind.VIDEO and extension not in video_extensions:
209
+ raise StoryError("unsupported Story video format: use MP4 or MOV")
210
+ size = path.stat().st_size
211
+ if size <= 0 or story.media.size_bytes != size:
212
+ raise StoryError("media size mismatch or file is empty")
213
+
214
+ width, height, duration = _probe_story(path, story.media.kind, extension)
215
+ if story.media.kind is MediaKind.IMAGE:
216
+ if size > STORY_IMAGE_MAX_BYTES:
217
+ raise StoryError("Story image exceeds documented 8 MB maximum")
218
+ else:
219
+ if size > STORY_VIDEO_MAX_BYTES:
220
+ raise StoryError("Story video exceeds documented 100 MB maximum")
221
+ if not STORY_VIDEO_MIN_DURATION_S <= duration <= STORY_VIDEO_MAX_DURATION_S:
222
+ raise StoryError("Story video must last between 3 and 60 seconds")
223
+
224
+ normalized_media = story.media.model_copy(
225
+ update={
226
+ "path": path,
227
+ "ruta_relativa": relative,
228
+ "width": width,
229
+ "height": height,
230
+ "duration_s": duration,
231
+ "size_bytes": size,
232
+ }
233
+ )
234
+ return story.model_copy(update={"media": normalized_media}), relative, file_digest(path), size
235
+
236
+
237
+ def _validate_story(story: StoryPost, brand, *, at: datetime | None = None) -> tuple[StoryPost, str, str, int, str]:
238
+ moment = at or now_utc()
239
+ if story.expires_at <= moment:
240
+ raise StoryError("Story proposal expired; prepare a new one")
241
+ if story.platform is Platform.INSTAGRAM:
242
+ if story.public_url is None:
243
+ raise StoryError("Instagram requires a public HTTPS URL for media")
244
+ try:
245
+ validate_url(story.public_url)
246
+ except HostedMediaError as exc:
247
+ raise StoryError(str(exc)) from None
248
+ account = (brand.cuentas.get("instagram") or {}).get("ig_user_id")
249
+ elif story.platform is Platform.FACEBOOK:
250
+ if story.public_url is not None:
251
+ try:
252
+ validate_url(story.public_url)
253
+ except HostedMediaError as exc:
254
+ raise StoryError(str(exc)) from None
255
+ account = (brand.cuentas.get("facebook") or {}).get("page_id")
256
+ else:
257
+ raise StoryError("Stories supported only on Facebook or Instagram")
258
+ try:
259
+ account_id = meta_id(account)
260
+ except MetaError:
261
+ raise StoryError("accounts.yml lacks a valid Meta account ID") from None
262
+ normalized, relative, digest, size = _media_contract(story, brand)
263
+ return normalized, relative, digest, size, account_id
264
+
265
+
266
+ def _dedupe_payload(story: StoryPost, account_id: str, media_sha256: str) -> str:
267
+ # Instagram no recibe text/source_video_id y distintas URLs que sirven los
268
+ # mismos bytes producen el mismo efecto remoto: una nueva Story idéntica.
269
+ raw = {
270
+ "platform": story.platform.value,
271
+ "account_id": account_id,
272
+ "media_sha256": media_sha256,
273
+ }
274
+ return hashlib.sha256(
275
+ json.dumps(raw, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
276
+ ).hexdigest()
277
+
278
+
279
+ def _iter_changes(store: StoryStore):
280
+ if not store.root.exists():
281
+ return
282
+ for path in sorted(store.root.glob("*.json")):
283
+ yield store.load(path.stem)
284
+
285
+
286
+ def _active_duplicate(store: StoryStore, key: str, *, excluding: str | None = None) -> StoryChange | None:
287
+ now = now_utc()
288
+ locally_active = {"prepared", "approved", "handoff_required"}
289
+ remote_effect_possible = {
290
+ "applying",
291
+ "container_created",
292
+ "publishing",
293
+ "sent",
294
+ "verified",
295
+ "uncertain",
296
+ }
297
+ for other in _iter_changes(store):
298
+ # Desde el primer write intent puede existir estado remoto. La caducidad
299
+ # editorial local no demuestra que Meta ya no retenga o sirva la Story,
300
+ # ni siquiera cuando la creación quedó sent/verified. Sin un estado
301
+ # remoto explícito que pruebe expiración, esos ChangeSets bloquean la
302
+ # misma operación de forma durable.
303
+ if (
304
+ other.id != excluding
305
+ and other.dedupe_key == key
306
+ and (
307
+ other.status in remote_effect_possible
308
+ or (
309
+ other.status in locally_active
310
+ and other.story.expires_at > now
311
+ )
312
+ )
313
+ ):
314
+ return other
315
+ return None
316
+
317
+
318
+ def prepare_story(brand, store: StoryStore, story: StoryPost) -> StoryChange:
319
+ normalized, relative, media_sha256, media_size_bytes, account_id = _validate_story(story, brand)
320
+ key = _dedupe_payload(normalized, account_id, media_sha256)
321
+ lock_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f"story:{brand.raiz.resolve()}:{key}"))
322
+ with store.apply_lock(lock_id):
323
+ duplicate = _active_duplicate(store, key)
324
+ if duplicate is not None:
325
+ raise StoryError(
326
+ f"Duplicate Story: active proposal {duplicate.id} already exists "
327
+ f"with status {duplicate.status}"
328
+ )
329
+ moment = now_utc()
330
+ capability = (
331
+ "instagram_public_api_write_grant_unverified"
332
+ if normalized.platform is Platform.INSTAGRAM
333
+ else "facebook_page_stories_api_pending_implementation"
334
+ )
335
+ change = StoryChange(
336
+ id=str(uuid.uuid4()),
337
+ brand=brand.nombre,
338
+ brand_root=str(brand.raiz.resolve()),
339
+ account_id=account_id,
340
+ story=normalized,
341
+ relative_media=relative,
342
+ media_sha256=media_sha256,
343
+ media_size_bytes=media_size_bytes,
344
+ dedupe_key=key,
345
+ capability=capability,
346
+ created_at=moment,
347
+ updated_at=moment,
348
+ )
349
+ change.fingerprint = story_fingerprint(change)
350
+ _event(change, "prepared_local_no_remote_write")
351
+ store.save(change)
352
+ return change
353
+
354
+
355
+ class MetaStoryClient:
356
+ """Small Instagram Story adapter over the bounded Graph client."""
357
+
358
+ def __init__(self, brand, platform: Platform, client: httpx.Client, *, poll_wait_s: float = 60.0, poll_attempts: int = 5):
359
+ if platform is not Platform.INSTAGRAM:
360
+ raise StoryError("remote Stories adapter is implemented only for Instagram")
361
+ self.brand = brand
362
+ self.platform = platform
363
+ self.graph = MetaClient(brand, platform, client)
364
+ self.http = client
365
+ self.poll_wait_s = poll_wait_s
366
+ self.poll_attempts = poll_attempts
367
+
368
+ @property
369
+ def account_id(self) -> str:
370
+ return self.graph.account_id
371
+
372
+ def identity(self) -> dict:
373
+ return self.graph.identity()
374
+
375
+ def preflight_public_url(self, change: StoryChange) -> None:
376
+ story = change.story
377
+ assert story.public_url is not None
378
+ expected_size = change.media_size_bytes
379
+ expected_digest = change.media_sha256
380
+ remote_digest = hashlib.sha256()
381
+ total = 0
382
+ try:
383
+ with self.http.stream(
384
+ "GET",
385
+ story.public_url,
386
+ headers={"Accept-Encoding": "identity"},
387
+ follow_redirects=False,
388
+ timeout=30,
389
+ ) as response:
390
+ if response.status_code != 200:
391
+ raise StoryError(
392
+ "public Story URL must return HTTP 200; "
393
+ f"returned {response.status_code}"
394
+ )
395
+ expected = "image/" if story.media.kind is MediaKind.IMAGE else "video/"
396
+ content_type = response.headers.get("content-type", "").lower()
397
+ if content_type and not content_type.startswith(expected):
398
+ raise StoryError(
399
+ "public Content-Type does not match Story format"
400
+ )
401
+ if response.headers.get("content-encoding", "identity") != "identity":
402
+ raise StoryError("public media must not be compressed")
403
+ length = response.headers.get("content-length")
404
+ if length is not None and (
405
+ not length.isdigit() or int(length) != expected_size
406
+ ):
407
+ raise StoryError("public media size does not match approved file")
408
+ for chunk in response.iter_bytes():
409
+ total += len(chunk)
410
+ if total > expected_size:
411
+ raise StoryError("public media exceeds approved file size")
412
+ remote_digest.update(chunk)
413
+ except httpx.HTTPError:
414
+ raise StoryError("failed to check public Story URL") from None
415
+ if total != expected_size or remote_digest.hexdigest() != expected_digest:
416
+ raise StoryError("public media bytes do not match approved file")
417
+
418
+ def create_container(self, story: StoryPost) -> str:
419
+ assert story.public_url is not None
420
+ url_field = "image_url" if story.media.kind is MediaKind.IMAGE else "video_url"
421
+ result = self.graph.request(
422
+ "POST",
423
+ f"{self.account_id}/media",
424
+ data={"media_type": "STORIES", url_field: story.public_url},
425
+ )
426
+ try:
427
+ return meta_id(result.get("id"))
428
+ except MetaError:
429
+ raise MetaUncertain("Meta accepted container creation but returned no valid ID; do not repeat") from None
430
+
431
+ def container_status(self, container_id: str) -> str:
432
+ result = self.graph.request("GET", meta_id(container_id), params={"fields": "status_code"})
433
+ status = result.get("status_code")
434
+ if status not in {"EXPIRED", "ERROR", "FINISHED", "IN_PROGRESS", "PUBLISHED"}:
435
+ raise StoryError("Meta returned unverifiable container status")
436
+ return status
437
+
438
+ def publish_container(self, container_id: str) -> str:
439
+ result = self.graph.request(
440
+ "POST",
441
+ f"{self.account_id}/media_publish",
442
+ data={"creation_id": meta_id(container_id)},
443
+ )
444
+ try:
445
+ return meta_id(result.get("id"))
446
+ except MetaError:
447
+ raise MetaUncertain("Meta accepted media_publish but returned no valid ID; do not repeat") from None
448
+
449
+ def verify_media(self, remote_id: str) -> dict:
450
+ result = self.graph.request(
451
+ "GET",
452
+ meta_id(remote_id),
453
+ params={"fields": "id,owner,media_product_type,permalink,timestamp"},
454
+ )
455
+ if (
456
+ result.get("id") != remote_id
457
+ or (result.get("owner") or {}).get("id") != self.account_id
458
+ or result.get("media_product_type") != "STORY"
459
+ ):
460
+ raise StoryError("remote ID was not verified as an account-owned Story")
461
+ return result
462
+
463
+
464
+ def _bound(client, change: StoryChange) -> None:
465
+ if (
466
+ client.brand.nombre != change.brand
467
+ or str(client.brand.raiz.resolve()) != change.brand_root
468
+ or client.platform.value != change.story.platform.value
469
+ or client.account_id != change.account_id
470
+ ):
471
+ raise StoryError("brand/account does not match Story proposal")
472
+ identity = client.identity()
473
+ if identity.get("account_id") != change.account_id:
474
+ raise StoryError("authenticated identity does not match prepared Story")
475
+
476
+
477
+ def _recheck_local(change: StoryChange, brand) -> None:
478
+ normalized, relative, digest, size, account_id = _validate_story(change.story, brand)
479
+ if (
480
+ normalized != change.story
481
+ or relative != change.relative_media
482
+ or digest != change.media_sha256
483
+ or size != change.media_size_bytes
484
+ or account_id != change.account_id
485
+ ):
486
+ raise StoryError("media, URL, expiry or account changed since preview")
487
+
488
+
489
+ def _save_failure(store: StoryStore, change: StoryChange, status: str, error: str, event: str) -> StoryChange:
490
+ change.status = status
491
+ change.last_error = error
492
+ _event(change, event)
493
+ store.save(change)
494
+ return change
495
+
496
+
497
+ def _verify(client, store: StoryStore, change: StoryChange) -> StoryChange:
498
+ if not change.remote_id:
499
+ if change.status in {"applying", "publishing"}:
500
+ change.status = "uncertain"
501
+ change.last_error = "uncertain remote outcome without ID; POST will not be repeated"
502
+ _event(change, "missing_remote_id_no_replay")
503
+ store.save(change)
504
+ return change
505
+ try:
506
+ receipt = client.verify_media(change.remote_id)
507
+ except (MetaError, StoryError):
508
+ change.status = "sent"
509
+ change.last_error = "Meta returned an ID, but Story could not yet be verified by GET"
510
+ _event(change, "verification_unavailable_no_replay")
511
+ else:
512
+ change.status = "verified"
513
+ change.receipt = receipt
514
+ change.last_error = None
515
+ _event(change, "remote_story_verified")
516
+ store.save(change)
517
+ return change
518
+
519
+
520
+ def verify_story(client, store: StoryStore, change_id: str) -> StoryChange:
521
+ with store.apply_lock(change_id):
522
+ change = store.load(change_id)
523
+ if change.story.platform is Platform.FACEBOOK:
524
+ return change
525
+ _bound(client, change)
526
+ if change.status == "verified":
527
+ return change
528
+ if change.container_id and not change.remote_id:
529
+ try:
530
+ status = client.container_status(change.container_id)
531
+ except (MetaError, StoryError):
532
+ change.last_error = "failed to verify current container status"
533
+ _event(change, "container_verification_unavailable")
534
+ else:
535
+ _event(change, "container_status_verified", status_code=status)
536
+ if status == "EXPIRED":
537
+ change.status = "expired"
538
+ change.last_error = "Instagram container expired before publication"
539
+ elif status == "ERROR":
540
+ change.status = "blocked"
541
+ change.last_error = "Meta could not process Story media"
542
+ elif status == "PUBLISHED":
543
+ change.status = "uncertain"
544
+ change.last_error = (
545
+ "container shows PUBLISHED without a durable remote ID; "
546
+ "media_publish will not be repeated"
547
+ )
548
+ else:
549
+ change.status = "container_created"
550
+ change.last_error = (
551
+ "container is ready" if status == "FINISHED"
552
+ else "container is still processing"
553
+ )
554
+ store.save(change)
555
+ return change
556
+ return _verify(client, store, change)
557
+
558
+
559
+ def apply_story(
560
+ client,
561
+ store: StoryStore,
562
+ change_id: str,
563
+ approval_digest: str,
564
+ *,
565
+ brand=None,
566
+ ) -> StoryChange:
567
+ with ExitStack() as locks:
568
+ locks.enter_context(store.apply_lock(change_id))
569
+ change = store.load(change_id)
570
+ if not hmac.compare_digest(change.fingerprint, approval_digest):
571
+ raise StoryError("approval does not match exact Story fingerprint")
572
+ dedupe_lock = str(uuid.uuid5(uuid.NAMESPACE_URL, f"story:{change.brand_root}:{change.dedupe_key}"))
573
+ locks.enter_context(store.apply_lock(dedupe_lock))
574
+ duplicate = _active_duplicate(store, change.dedupe_key, excluding=change.id)
575
+ if duplicate is not None:
576
+ raise StoryError(f"Duplicate Story blocked by active operation {duplicate.id}")
577
+
578
+ if change.status == "verified":
579
+ return change
580
+ if change.status in {"blocked", "expired", "handoff_required"}:
581
+ return change
582
+ current_brand = client.brand if client is not None else brand
583
+ if current_brand is None:
584
+ raise StoryError("explicit brand required to apply Story")
585
+ if (
586
+ change.story.expires_at <= now_utc()
587
+ and change.container_id is None
588
+ and change.remote_id is None
589
+ ):
590
+ return _save_failure(
591
+ store, change, "expired", "Story approval expired", "approval_expired_no_write"
592
+ )
593
+
594
+ if change.story.platform is Platform.FACEBOOK:
595
+ try:
596
+ _recheck_local(change, current_brand)
597
+ except StoryError as exc:
598
+ return _save_failure(store, change, "blocked", str(exc), "local_binding_changed_no_write")
599
+ change.status = "handoff_required"
600
+ change.last_error = (
601
+ "Facebook Page Stories has a public API, but its photo_stories/video_stories flow "
602
+ "is not yet implemented; publish through Business Suite and record evidence"
603
+ )
604
+ _event(change, "facebook_page_story_handoff_no_remote_write")
605
+ store.save(change)
606
+ return change
607
+
608
+ if client is None:
609
+ raise StoryError("Instagram adapter required to apply Story")
610
+ try:
611
+ _bound(client, change)
612
+ except (MetaError, StoryError) as exc:
613
+ return _save_failure(
614
+ store, change, "blocked",
615
+ f"identity or read permission unavailable: {exc}; write grant remains unverified",
616
+ "identity_or_permission_blocked_no_write",
617
+ )
618
+
619
+ # Si el proceso cayó después de persistir un write intent, el POST
620
+ # puede haber llegado a Meta. Solo se permite lectura/verificación.
621
+ if change.status in {"applying", "uncertain", "publishing", "sent"}:
622
+ return _verify(client, store, change)
623
+ if (
624
+ change.story.expires_at <= now_utc()
625
+ and change.container_id is None
626
+ and change.remote_id is None
627
+ ):
628
+ return _save_failure(
629
+ store, change, "expired", "Story approval expired", "approval_expired_no_write"
630
+ )
631
+ if change.container_id is None:
632
+ try:
633
+ _recheck_local(change, current_brand)
634
+ except StoryError as exc:
635
+ return _save_failure(store, change, "blocked", str(exc), "local_binding_changed_no_write")
636
+
637
+ if change.container_id is None:
638
+ try:
639
+ client.preflight_public_url(change)
640
+ except StoryError as exc:
641
+ return _save_failure(store, change, "blocked", str(exc), "public_url_preflight_failed_no_write")
642
+ change.status = "approved"
643
+ change.last_error = None
644
+ _event(change, "approved_exact_digest")
645
+ store.save(change)
646
+ change.status = "applying"
647
+ _event(change, "container_write_intent")
648
+ store.save(change)
649
+ try:
650
+ change.container_id = client.create_container(change.story)
651
+ except MetaRejected:
652
+ return _save_failure(
653
+ store, change, "blocked",
654
+ "Meta rejected Story creation; check instagram_content_publish, eligibility and public URL. Write grant is unverified",
655
+ "container_write_rejected",
656
+ )
657
+ except (MetaUncertain, Exception) as exc:
658
+ message = str(exc) if isinstance(exc, MetaUncertain) else "unexpected failure after starting POST"
659
+ return _save_failure(store, change, "uncertain", message, "container_write_uncertain_no_replay")
660
+ change.status = "container_created"
661
+ _event(change, "container_id_persisted", container_id=change.container_id)
662
+ store.save(change)
663
+
664
+ status = None
665
+ for attempt in range(client.poll_attempts):
666
+ try:
667
+ status = client.container_status(change.container_id)
668
+ except (MetaError, StoryError):
669
+ change.last_error = "failed to read container status; ID preserved to continue without recreating it"
670
+ _event(change, "container_status_unavailable_safe_to_resume")
671
+ store.save(change)
672
+ return change
673
+ _event(change, "container_status_observed", status_code=status)
674
+ store.save(change)
675
+ if status == "FINISHED":
676
+ break
677
+ if status == "ERROR":
678
+ return _save_failure(store, change, "blocked", "Meta could not process Story media", "container_processing_error")
679
+ if status == "EXPIRED":
680
+ return _save_failure(store, change, "expired", "Instagram container expired before publication", "container_expired")
681
+ if status == "PUBLISHED":
682
+ return _save_failure(
683
+ store, change, "uncertain",
684
+ "container shows PUBLISHED without a durable remote ID; media_publish will not be repeated",
685
+ "container_already_published_no_remote_id",
686
+ )
687
+ if attempt < client.poll_attempts - 1:
688
+ time.sleep(client.poll_wait_s)
689
+ if status != "FINISHED":
690
+ change.last_error = "container is still processing; run apply or verify again later"
691
+ _event(change, "container_still_processing_safe_to_resume")
692
+ store.save(change)
693
+ return change
694
+
695
+ change.status = "publishing"
696
+ change.last_error = None
697
+ _event(change, "media_publish_write_intent")
698
+ store.save(change)
699
+ try:
700
+ change.remote_id = client.publish_container(change.container_id)
701
+ except MetaRejected:
702
+ return _save_failure(
703
+ store, change, "blocked",
704
+ "Meta rejected media_publish; check instagram_content_publish and eligibility. Write grant was unverified",
705
+ "media_publish_rejected",
706
+ )
707
+ except (MetaUncertain, Exception) as exc:
708
+ message = str(exc) if isinstance(exc, MetaUncertain) else "uncertain outcome after media_publish"
709
+ return _save_failure(store, change, "uncertain", message, "media_publish_uncertain_no_replay")
710
+ change.status = "sent"
711
+ _event(change, "remote_id_persisted", remote_id=change.remote_id)
712
+ store.save(change)
713
+ return _verify(client, store, change)