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/publisher.py ADDED
@@ -0,0 +1,445 @@
1
+ """Validate, preview, publish and persist approved content."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Callable
7
+ from contextlib import ExitStack
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+
11
+ import httpx
12
+
13
+ from socialctl.adapters import ADAPTADORES # importar el paquete registra los cuatro
14
+ from socialctl.brands import Brand
15
+ from socialctl.formatter import PLATFORM_SPECS, privacidad_efectiva, texto_publicado, youtube_tags
16
+ from socialctl.media import ruta_relativa_efectiva
17
+ from socialctl.models import Platform, Post, PostResult, PostStatus, ValidationError
18
+ from socialctl.publication_policy import validate_derivation
19
+ from socialctl.publication_status import describe_result_with_observation
20
+ from socialctl.rutas import validar_componente_de_ruta
21
+
22
+ ICONO = {
23
+ PostStatus.PUBLICADO: "OK",
24
+ PostStatus.PENDIENTE_CONFIRMACION: "PENDING",
25
+ PostStatus.ERROR: "ERROR",
26
+ PostStatus.OMITIDO: "SKIPPED",
27
+ }
28
+
29
+
30
+ def validation_field_label(field: str) -> str:
31
+ """Translate human field labels without changing serialized validation keys."""
32
+ return {"cuenta": "account", "auditoria": "audit", "gancho": "hook",
33
+ "privacidad": "privacy", "duracion": "duration", "formato": "format",
34
+ "credenciales": "credentials", "origen": "source", "adaptador": "adapter",
35
+ "persistencia": "persistence"}.get(field, field)
36
+
37
+
38
+ class PersistenciaError(Exception):
39
+ """A publication result or history entry could not be saved."""
40
+
41
+
42
+ def validar_todo(
43
+ post: Post, brand: Brand, *,
44
+ legacy_approved_platforms: frozenset[Platform] = frozenset(),
45
+ ) -> dict[Platform, list[ValidationError]]:
46
+ """Validate every platform locally and collect failures without raising."""
47
+ # Only run-due may supply compatibility after verifying the stored v2 hash.
48
+ # It exempts missing origin only; adapter validation is always mandatory.
49
+ errores: dict[Platform, list[ValidationError]] = {}
50
+ for platform, pp in post.platforms.items():
51
+ adaptador_cls = ADAPTADORES.get(platform)
52
+ if adaptador_cls is None:
53
+ errores[platform] = [
54
+ ValidationError(
55
+ platform=platform,
56
+ campo="adaptador",
57
+ motivo=f"no adapter is registered for {platform.value}",
58
+ )
59
+ ]
60
+ continue
61
+ try:
62
+ adaptador = adaptador_cls()
63
+ except Exception as exc:
64
+ # Fallo al CONSTRUIR el adaptador (p. ej. un __init__ con un bug):
65
+ # no es un fallo de validate(), y el mensaje no debe sugerir que
66
+ # lo es, o quien lo lea buscara el bug en el sitio equivocado.
67
+ errores[platform] = [
68
+ ValidationError(
69
+ platform=platform,
70
+ campo="adaptador",
71
+ motivo=(
72
+ f"could not create the adapter for {platform.value} "
73
+ f"({type(exc).__name__})"
74
+ ),
75
+ )
76
+ ]
77
+ continue
78
+ try:
79
+ errores[platform] = adaptador.validate(pp, brand)
80
+ except Exception as exc:
81
+ errores[platform] = [
82
+ ValidationError(
83
+ platform=platform,
84
+ campo="validacion",
85
+ motivo=(
86
+ f'validation for {platform.value} failed unexpectedly ({type(exc).__name__})'
87
+ ),
88
+ )
89
+ ]
90
+ for platform, pp in post.platforms.items():
91
+ errores[platform].extend(validate_derivation(
92
+ pp, require_origin=platform not in legacy_approved_platforms))
93
+ return errores
94
+
95
+
96
+ def render_preview(
97
+ post: Post,
98
+ errores: dict[Platform, list[ValidationError]],
99
+ *,
100
+ brand: Brand | None = None,
101
+ destinos: list[Platform] | None = None,
102
+ motivo_exclusion: str = "not requested with --only",
103
+ ) -> str:
104
+ """Render the exact preview the user approves before publication, with exclusions clearly labeled."""
105
+ lineas = [f"Post: {post.slug} brand: {post.brand} campaign: {post.campaign.value}", ""]
106
+ if Platform.YOUTUBE in post.platforms and (destinos is None or Platform.YOUTUBE in destinos):
107
+ from socialctl.upload_consent import YOUTUBE_CERTIFICATION
108
+ lineas.extend([YOUTUBE_CERTIFICATION, ""])
109
+
110
+ if destinos is not None:
111
+ excluidas = [p for p in post.platforms if p not in destinos]
112
+ if excluidas:
113
+ lineas.append(
114
+ f"Will publish only on {', '.join((p.value for p in destinos))}. Excluded ({motivo_exclusion}): {', '.join((p.value for p in excluidas))}."
115
+ )
116
+ lineas.append("")
117
+
118
+ for platform, pp in post.platforms.items():
119
+ spec = PLATFORM_SPECS[platform]
120
+ marca_exclusion = (
121
+ f" [WILL NOT BE PUBLISHED: {motivo_exclusion}]"
122
+ if destinos is not None and platform not in destinos
123
+ else ""
124
+ )
125
+ lineas.append(f"--- {platform.value.upper()} ---{marca_exclusion}")
126
+ if platform is Platform.TIKTOK:
127
+ mode = (brand.cuentas.get('tiktok') or {}).get('mode', 'inbox') if brand else None
128
+ if mode == 'inbox':
129
+ lineas.append('Delivery: creator review — finish publishing in TikTok; not automatically scheduled.')
130
+ elif mode == 'direct':
131
+ lineas.append('Delivery: TikTok Direct Post is disabled and excluded. Use mode: inbox for creator-reviewed inbox upload; the creator must finish publishing in TikTok.')
132
+ else:
133
+ lineas.append('Delivery: TikTok mode unverified; inspect the explicit brand accounts.yml before approval.')
134
+ if platform is Platform.INSTAGRAM and brand:
135
+ from socialctl.connections.temporary_media import available
136
+ if available(brand) and not (brand.cuentas.get('instagram') or {}).get('media_url_base'):
137
+ lineas.append('Delivery: original media uses temporary hosting on florentino.pro; URL expires after 15 minutes including upload time, then automatic deletion. No media backups.')
138
+ if pp.title:
139
+ lineas.append(f"Title: {pp.title}")
140
+ if spec.valores_privacidad is not None:
141
+ valor_privacidad = privacidad_efectiva(pp)
142
+ aviso_publico = (
143
+ ' [WARNING: will become PUBLIC and visible to anyone as soon as the upload finishes]'
144
+ if valor_privacidad == "public"
145
+ else ""
146
+ )
147
+ lineas.append(f"Privacy: {valor_privacidad}{aviso_publico}")
148
+ lineas.append(texto_publicado(pp))
149
+ if pp.content_origin is not None:
150
+ lineas.append(f"Source: {pp.content_origin}")
151
+ if pp.source_video_id is not None:
152
+ lineas.append(f"Source long-form video ID: {pp.source_video_id}")
153
+ if pp.first_comment:
154
+ lineas.append(f"First comment: {pp.first_comment}")
155
+ if platform == Platform.YOUTUBE:
156
+ lineas.append("Visible hashtags appended to description: " + ", ".join(pp.visible_hashtags or []))
157
+ lineas.append("Internal tags: " + ", ".join(youtube_tags(pp)))
158
+ if pp.tags is None:
159
+ lineas.append("Legacy mode: post.yml hashtags are sent as internal YouTube tags.")
160
+ if not spec.hashtags_en_texto and youtube_tags(pp):
161
+ etiquetas = ", ".join(youtube_tags(pp))
162
+ lineas.append(
163
+ f"Tags (platform metadata; do NOT appear in the text above): {etiquetas}"
164
+ )
165
+ for asset in pp.media:
166
+ medidas = f"{asset.width}x{asset.height}" if asset.width else "?"
167
+ duracion = f", {asset.duration_s:.0f}s" if asset.duration_s else ""
168
+ lineas.append(f"Media: {ruta_relativa_efectiva(asset)} ({medidas}{duracion})")
169
+ if not pp.media:
170
+ lineas.append("Media: (none)")
171
+ for error in errores.get(platform, []):
172
+ lineas.append(f"PROBLEM [{validation_field_label(error.campo)}]: {error.motivo}")
173
+ lineas.append("")
174
+
175
+ # Hallazgo de revision (Menor 5): con `destinos`, los problemas de las
176
+ # redes excluidas no bloquean la publicacion (ver `_publicar_impl` en
177
+ # `socialctl/cli.py`), asi que sumar TODOS los errores en un unico
178
+ # numero podia leerse como "Problemas detectados: 1" seguido de una
179
+ # publicacion con exito (exit 0): el numero no era el que decidia el
180
+ # aborto. Cuando `destinos` deja alguno de esos errores fuera del
181
+ # conteo que bloquea, se desglosan los dos numeros en vez de mostrar
182
+ # solo el total; si coinciden (o no hay `destinos`), se muestra un
183
+ # unico numero, como antes.
184
+ total = sum(len(v) for v in errores.values())
185
+ bloqueantes = (
186
+ total if destinos is None
187
+ else sum(len(v) for p, v in errores.items() if p in destinos)
188
+ )
189
+ if bloqueantes == total:
190
+ lineas.append(f"Problems found: {total}")
191
+ else:
192
+ lineas.append(
193
+ f"Problems found: {total} "
194
+ f"({bloqueantes} on the platforms selected for publication)"
195
+ )
196
+ return "\n".join(lineas)
197
+
198
+
199
+ def publicar(
200
+ post: Post,
201
+ brand: Brand,
202
+ solo: list[Platform] | None = None,
203
+ *,
204
+ on_progreso: Callable[[Platform], None] | None = None,
205
+ on_media_result: Callable[[PostResult], None] | None = None,
206
+ on_result: Callable[[PostResult], None] | None = None,
207
+ occurrence_ids: dict[Platform, str] | None = None,
208
+ approval_provenance: str = "approved-publish-preview",
209
+ retry_guard: bool = False,
210
+ legacy_approved_platforms: frozenset[Platform] = frozenset(),
211
+ ) -> list[PostResult]:
212
+ """Execute an approved publication while excluding concurrent draft ingestion.
213
+
214
+ Preview/confirmation remains outside this gate. A durable start marker prevents
215
+ ingress replacing text after the gate releases but before CLI result persistence,
216
+ including crashes and definite failed attempts. It never blocks fresh publishing.
217
+ """
218
+ from socialctl.media_registry import publication_gate, record_publication_start
219
+ selected = [p for p in post.platforms if solo is None or p in solo]
220
+ if not selected:
221
+ return []
222
+ with ExitStack() as stack:
223
+ try:
224
+ stack.enter_context(publication_gate(brand, post.slug))
225
+ except (OSError, ValueError):
226
+ return [PostResult(platform=p, status=PostStatus.ERROR,
227
+ error="post is running concurrently or its lock is inaccessible; publication was not attempted", riesgo_duplicado=False) for p in selected]
228
+ try:
229
+ record_publication_start(brand, post, selected)
230
+ except (OSError, ValueError):
231
+ return [PostResult(platform=p, status=PostStatus.ERROR,
232
+ error="could not persist publication start; publication was not attempted", riesgo_duplicado=False) for p in selected]
233
+ # Do not classify an exception after adapter effects as safe to retry.
234
+ return _publicar_locked(post, brand, solo, on_progreso=on_progreso,
235
+ on_media_result=on_media_result, on_result=on_result, occurrence_ids=occurrence_ids,
236
+ approval_provenance=approval_provenance, retry_guard=retry_guard,
237
+ legacy_approved_platforms=legacy_approved_platforms)
238
+
239
+
240
+ def _publicar_locked(
241
+ post: Post,
242
+ brand: Brand,
243
+ solo: list[Platform] | None = None,
244
+ *,
245
+ on_progreso: Callable[[Platform], None] | None = None,
246
+ on_media_result: Callable[[PostResult], None] | None = None,
247
+ on_result: Callable[[PostResult], None] | None = None,
248
+ occurrence_ids: dict[Platform, str] | None = None,
249
+ approval_provenance: str = "approved-publish-preview",
250
+ retry_guard: bool = False,
251
+ legacy_approved_platforms: frozenset[Platform] = frozenset(),
252
+ ) -> list[PostResult]:
253
+ """Publish independently on each platform; one failure does not abort the others."""
254
+ destinos = [p for p in post.platforms if solo is None or p in solo]
255
+ resultados: list[PostResult] = []
256
+
257
+ def record(result):
258
+ resultados.append(result)
259
+ if on_result is not None:
260
+ try:
261
+ on_result(result)
262
+ except Exception:
263
+ pass # Reporting cannot retry or change provider behavior.
264
+
265
+ with httpx.Client(timeout=60) as client:
266
+ for platform in destinos:
267
+ if on_progreso is not None:
268
+ try:
269
+ on_progreso(platform)
270
+ except Exception:
271
+ pass
272
+ adaptador_cls = ADAPTADORES.get(platform)
273
+ if adaptador_cls is None:
274
+ record(
275
+ PostResult(
276
+ platform=platform,
277
+ status=PostStatus.ERROR,
278
+ error=f"no adapter is registered for {platform.value}",
279
+ )
280
+ )
281
+ continue
282
+ try:
283
+ adaptador = adaptador_cls()
284
+ except Exception as exc:
285
+ record(
286
+ PostResult(
287
+ platform=platform,
288
+ status=PostStatus.ERROR,
289
+ error=f"could not create the adapter ({type(exc).__name__})",
290
+ )
291
+ )
292
+ continue
293
+ # Revalidate immediately before effects; compatibility never skips the
294
+ # adapter's limits, media count, account or privacy checks.
295
+ try:
296
+ errors = adaptador.validate(post.platforms[platform], brand)
297
+ errors += validate_derivation(post.platforms[platform],
298
+ require_origin=platform not in legacy_approved_platforms)
299
+ except Exception as exc:
300
+ record(PostResult(platform=platform, status=PostStatus.ERROR,
301
+ error=f"validation for {platform.value} failed unexpectedly ({type(exc).__name__})"))
302
+ continue
303
+ if errors:
304
+ record(PostResult(platform=platform, status=PostStatus.ERROR,
305
+ error="; ".join(e.motivo for e in errors)))
306
+ continue
307
+ try:
308
+ if platform in {Platform.FACEBOOK, Platform.INSTAGRAM, Platform.YOUTUBE}:
309
+ from socialctl.publication_steps import publish_with_steps
310
+ record(publish_with_steps(
311
+ post, brand, platform, adaptador, client,
312
+ on_media_result=on_media_result,
313
+ on_media_observed=on_result,
314
+ occurrence_id=(occurrence_ids or {}).get(platform),
315
+ provenance=approval_provenance,
316
+ retry_guard=retry_guard,
317
+ ))
318
+ continue
319
+ record(
320
+ adaptador.publish(post.platforms[platform], brand, client)
321
+ )
322
+ except Exception as exc:
323
+ record(
324
+ PostResult(
325
+ platform=platform,
326
+ status=PostStatus.ERROR,
327
+ error=str(exc),
328
+ riesgo_duplicado=True,
329
+ )
330
+ )
331
+
332
+ return resultados
333
+
334
+
335
+ class SlugInvalido(Exception):
336
+ """The post slug is not a safe single path component."""
337
+
338
+
339
+ def _validar_slug(dir_posts: Path, slug: str) -> Path:
340
+ """Validate a slug and return its directory within the posts root."""
341
+ return validar_componente_de_ruta(dir_posts, slug, SlugInvalido, "slug")
342
+
343
+
344
+ def _cargar_resultados_previos(destino: Path) -> dict[str, dict]:
345
+ """Read previous resultado.json entries by platform, preserving an unreadable file for inspection."""
346
+ try:
347
+ contenido = destino.read_text(encoding="utf-8")
348
+ except FileNotFoundError:
349
+ return {}
350
+ except OSError:
351
+ # No es "no existe" (ese caso ya se maneja arriba): es, por ejemplo,
352
+ # un permiso denegado al leer. No hay nada que fusionar ni nada que
353
+ # respaldar (no se pudo ni abrir), así que seguimos sin datos
354
+ # previos; si el problema de fondo es de permisos de escritura,
355
+ # volverá a aparecer -y se reportará con claridad- al escribir.
356
+ return {}
357
+
358
+ try:
359
+ previo = json.loads(contenido)
360
+ if not isinstance(previo, dict):
361
+ raise ValueError("JSON root is not an object")
362
+ entradas = previo["resultados"]
363
+ if not isinstance(entradas, list):
364
+ raise ValueError("'resultados' is not a list")
365
+ indexadas: dict[str, dict] = {}
366
+ for entrada in entradas:
367
+ if not isinstance(entrada, dict) or not isinstance(
368
+ entrada.get("platform"), str
369
+ ):
370
+ raise ValueError("a 'resultados' entry does not have the expected structure")
371
+ indexadas[entrada["platform"]] = entrada
372
+ return indexadas
373
+ except (json.JSONDecodeError, KeyError, ValueError):
374
+ respaldo = destino.with_name(destino.name + ".corrupto")
375
+ try:
376
+ destino.replace(respaldo)
377
+ except OSError:
378
+ pass # si ni siquiera se puede respaldar, seguimos: prioridad es no perder lo nuevo
379
+ return {}
380
+
381
+
382
+ def guardar_resultado(post: Post, brand: Brand, resultados: list[PostResult]) -> Path:
383
+ """Write resultado.json, merging platform results without losing earlier successes."""
384
+ carpeta = _validar_slug(brand.dir_posts, post.slug)
385
+ destino = carpeta / "resultado.json"
386
+
387
+ existentes = _cargar_resultados_previos(destino)
388
+
389
+ fecha_actual = datetime.now().isoformat(timespec="seconds")
390
+ for r in resultados:
391
+ entrada = r.model_dump()
392
+ entrada["platform"] = r.platform.value
393
+ entrada["status"] = r.status.value
394
+ entrada["fecha"] = fecha_actual
395
+ existentes[r.platform.value] = entrada
396
+
397
+ orden_conocido = [p.value for p in Platform]
398
+ claves_ordenadas = sorted(
399
+ existentes,
400
+ key=lambda k: (orden_conocido.index(k) if k in orden_conocido else len(orden_conocido), k),
401
+ )
402
+
403
+ contenido = json.dumps(
404
+ {
405
+ "slug": post.slug,
406
+ "marca": post.brand,
407
+ "campana": post.campaign.value,
408
+ "actualizado": fecha_actual,
409
+ "resultados": [existentes[k] for k in claves_ordenadas],
410
+ },
411
+ indent=2,
412
+ ensure_ascii=False,
413
+ )
414
+
415
+ try:
416
+ carpeta.mkdir(parents=True, exist_ok=True)
417
+ destino.write_text(contenido, encoding="utf-8")
418
+ except OSError as exc:
419
+ raise PersistenciaError(
420
+ f"could not save the result for '{post.slug}' in {destino}: {exc}"
421
+ ) from exc
422
+
423
+ return destino
424
+
425
+
426
+ def anexar_historial(post: Post, brand: Brand, resultados: list[PostResult]) -> None:
427
+ """Append a readable history entry without changing previous entries."""
428
+ fichero = brand.raiz / "historial.md"
429
+ fecha = datetime.now().strftime("%Y-%m-%d %H:%M")
430
+
431
+ lineas = [f"\n## {post.slug} — {fecha}\n"]
432
+ for r in resultados:
433
+ detalle = r.url or r.error or ""
434
+ estado = describe_result_with_observation(r)
435
+ lineas.append(f"- {r.platform.value}: {ICONO[r.status]} {estado} {detalle}".rstrip())
436
+ contenido = "\n".join(lineas) + "\n"
437
+
438
+ try:
439
+ brand.raiz.mkdir(parents=True, exist_ok=True)
440
+ with fichero.open("a", encoding="utf-8") as f:
441
+ f.write(contenido)
442
+ except OSError as exc:
443
+ raise PersistenciaError(
444
+ f"could not append the result for '{post.slug}' to {fichero}: {exc}"
445
+ ) from exc