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/executor.py ADDED
@@ -0,0 +1,135 @@
1
+ """Per-brand slot admission and durable executor heartbeat.
2
+
3
+ Call heartbeat/admitted_groups while holding ScheduleStore.executor_lock.
4
+ Slot windows own elapsed instants: where windows overlap the latest start wins.
5
+ The end is exclusive; previous-day windows may extend across midnight.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from datetime import datetime, time, timedelta, timezone
12
+ from typing import Callable, Iterator
13
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
14
+
15
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
16
+
17
+ from socialctl.migration_files import write_json
18
+ from socialctl.scheduler import ScheduleEntry, ScheduleError, ScheduleStore
19
+
20
+
21
+ class ExecutionPolicy(BaseModel):
22
+ model_config = ConfigDict(extra="forbid", strict=True)
23
+ timezone: str
24
+ slots: list[str] = Field(min_length=1)
25
+ window_minutes: int = Field(gt=0, le=1440)
26
+ max_groups_per_slot: int = Field(gt=0, le=100)
27
+
28
+ @field_validator("timezone")
29
+ @classmethod
30
+ def valid_zone(cls, value):
31
+ try:
32
+ ZoneInfo(value)
33
+ except (ValueError, ZoneInfoNotFoundError) as exc:
34
+ raise ValueError("invalid IANA timezone") from exc
35
+ return value
36
+
37
+ @field_validator("slots")
38
+ @classmethod
39
+ def valid_slots(cls, value):
40
+ if len(set(value)) != len(value) or any(not re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", slot) for slot in value):
41
+ raise ValueError("slots must be unique HH:MM values")
42
+ return sorted(value)
43
+
44
+ def active_slot(self, moment: datetime) -> str | None:
45
+ if moment.utcoffset() is None:
46
+ raise ScheduleError("the clock requires a timezone")
47
+ zone = ZoneInfo(self.timezone)
48
+ instant = moment.astimezone(timezone.utc)
49
+ today = instant.astimezone(zone).date()
50
+ candidates = []
51
+ for day in (today - timedelta(days=1), today):
52
+ for slot in self.slots:
53
+ wall = datetime.combine(day, time.fromisoformat(slot))
54
+ start = wall.replace(tzinfo=zone, fold=0).astimezone(timezone.utc)
55
+ if start.astimezone(zone).replace(tzinfo=None) != wall:
56
+ continue # nonexistent wall time
57
+ if start <= instant < start + timedelta(minutes=self.window_minutes):
58
+ candidates.append((start, f"{day.isoformat()}/{slot}"))
59
+ return max(candidates)[1] if candidates else None
60
+
61
+
62
+ def load_state(store: ScheduleStore) -> dict:
63
+ path = store.root / "executor-state.json"
64
+ if not path.exists():
65
+ return {"version": 1, "slots": {}}
66
+ try:
67
+ state = json.loads(path.read_bytes())
68
+ if state["version"] != 1 or not isinstance(state["slots"], dict):
69
+ raise ValueError()
70
+ for count in state["slots"].values():
71
+ if type(count) is not int or count < 0:
72
+ raise ValueError()
73
+ return state
74
+ except (OSError, ValueError, KeyError, TypeError) as exc:
75
+ raise ScheduleError("executor state is unreadable; review required") from exc
76
+
77
+
78
+ def save_state(store: ScheduleStore, state: dict) -> None:
79
+ try:
80
+ write_json(store.root / "executor-state.json", state)
81
+ except OSError as exc:
82
+ raise ScheduleError("could not save executor state") from exc
83
+
84
+
85
+ def heartbeat(store: ScheduleStore, state: str, moment: datetime) -> None:
86
+ data = load_state(store)
87
+ started = moment.isoformat() if state == "started" else data.get("heartbeat", {}).get("started_at")
88
+ data["heartbeat"] = {"state": state, "timestamp": moment.isoformat(),
89
+ "started_at": started,
90
+ "backend": "sqlite" if store.database_path.exists() else "json"}
91
+ save_state(store, data)
92
+
93
+
94
+ def admitted_groups(store: ScheduleStore, moment: datetime, *,
95
+ clock: Callable[[], datetime] | None = None) -> Iterator[list[ScheduleEntry]]:
96
+ policy_path = store.root / "executor-policy.json"
97
+ policy = None
98
+ if policy_path.exists():
99
+ try:
100
+ policy = ExecutionPolicy.model_validate_json(policy_path.read_bytes())
101
+ except (OSError, ValueError) as exc:
102
+ raise ScheduleError("invalid executor policy") from exc
103
+ groups: dict[tuple[str, datetime], list[ScheduleEntry]] = {}
104
+ for entry in sorted(store.due(moment), key=lambda e: e.scheduled_at.astimezone(timezone.utc)):
105
+ groups.setdefault((entry.slug, entry.scheduled_at.astimezone(timezone.utc)), []).append(entry)
106
+ for group in groups.values():
107
+ if policy:
108
+ slot = policy.active_slot(clock() if clock else moment)
109
+ if slot is None:
110
+ return
111
+ state = load_state(store)
112
+ used = state["slots"].get(slot, 0)
113
+ if used >= policy.max_groups_per_slot:
114
+ return
115
+ state["slots"][slot] = used + 1
116
+ save_state(store, state) # fail closed, even if persistence outcome is uncertain
117
+ yield group
118
+
119
+
120
+ def health(store: ScheduleStore, moment: datetime) -> dict:
121
+ state = load_state(store).get("heartbeat", {})
122
+ try:
123
+ stamp = datetime.fromisoformat(state["timestamp"])
124
+ if stamp.utcoffset() is None:
125
+ raise ValueError()
126
+ age = (moment - stamp).total_seconds()
127
+ status = state["state"]
128
+ if status not in {"started", "finished", "error"}:
129
+ raise ValueError()
130
+ return {"state": status, "timestamp": stamp.isoformat(),
131
+ "backend": "sqlite" if store.database_path.exists() else "json",
132
+ "stale": age > 180 or age < -60}
133
+ except (KeyError, ValueError, TypeError):
134
+ return {"state": "unknown", "stale": True,
135
+ "backend": "sqlite" if store.database_path.exists() else "json"}
socialctl/formatter.py ADDED
@@ -0,0 +1,291 @@
1
+ """Platform-specific formatting rules and limits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from pydantic import BaseModel
8
+
9
+ from socialctl.models import Platform, PlatformPost, ValidationError
10
+
11
+
12
+ class PlatformSpec(BaseModel):
13
+ max_title: int | None = None
14
+ exige_title: bool = False
15
+ max_body: int
16
+ unidad_max_body: Literal["caracteres", "bytes_utf8", "unidades_utf16"] = "caracteres"
17
+ """Unit used to measure the composed body: code points, UTF-8 bytes or UTF-16 units, according to the platform."""
18
+ hook_chars: int | None = None # chars visibles antes del "ver más"
19
+ max_hashtags: int | None
20
+ """Maximum number of hashtag or tag elements; every platform must declare this explicitly."""
21
+ max_tags_chars: int | None = None
22
+ """Aggregate tag character limit, including separators, for YouTube snippet.tags."""
23
+ hashtags_en_texto: bool = True
24
+ """Whether hashtags are included in the published text; YouTube sends legacy hashtags as separate tag metadata."""
25
+ incluye_link_en_texto: bool = False
26
+ """Whether to append the optional link to published text; currently only Facebook does so."""
27
+ valores_privacidad: list[str] | None = None
28
+ """Supported privacy values, or None when this generic field is unsupported. Unsupported explicit values are rejected."""
29
+ privacidad_por_defecto: str | None = None
30
+ """Default effective privacy for supported platforms; YouTube defaults to private."""
31
+ acepta_solo_texto: bool = False
32
+ exige_media: bool
33
+ max_media: int = 1
34
+ min_video_s: float | None = None
35
+ max_video_s: float | None = None
36
+ max_bytes: int | None = None
37
+ aspect_ratios: list[str] = []
38
+
39
+
40
+ PLATFORM_SPECS: dict[Platform, PlatformSpec] = {
41
+ Platform.YOUTUBE: PlatformSpec(
42
+ max_title=100, # "maximum length of 100 characters" (confirmado, en caracteres).
43
+ exige_title=True,
44
+ max_body=5000,
45
+ unidad_max_body="bytes_utf8", # snippet.description: "limited to 5000 bytes".
46
+ # snippet.tags no tiene un tope documentado de número de elementos:
47
+ # la cifra "15 hashtags" no aparece en la Data API (parece una
48
+ # política de la Central de Ayuda sobre #hashtags escritos como
49
+ # texto en título/descripción, no sobre este campo). Se deja en
50
+ # None -explícito, no un olvido- y se sustituye por max_tags_chars,
51
+ # que sí es el límite real documentado para tags.
52
+ max_hashtags=None,
53
+ max_tags_chars=500, # snippet.tags: "500 characters, where commas between tags contribute to the total length" (Revision History, 13 mar 2014).
54
+ # adapters/youtube.py publica post.body TAL CUAL como
55
+ # snippet.description y post.hashtags aparte como snippet.tags: los
56
+ # hashtags nunca llegan a aparecer dentro del texto de la
57
+ # descripción, así que aquí es explícito -no el valor por defecto
58
+ # heredado sin más- que esta red es la excepción.
59
+ hashtags_en_texto=False,
60
+ # status.privacyStatus: "public", "private" o "unlisted" (confirmado
61
+ # con Context7 en developers.google.com/youtube/v3/guides/uploading_a_video:
62
+ # "The privacy status of an uploaded video can be set to public,
63
+ # private, or unlisted"). El propio ejemplo de esa guía recomienda
64
+ # "private" o "unlisted" para vídeos de prueba, precisamente para no
65
+ # dejarlos visibles al público por accidente -el mismo motivo por el
66
+ # que este proyecto elige "private" como valor por defecto, nunca
67
+ # "public" (ver privacidad_por_defecto)-.
68
+ valores_privacidad=["public", "unlisted", "private"],
69
+ privacidad_por_defecto="private",
70
+ exige_media=True,
71
+ min_video_s=1,
72
+ max_video_s=None,
73
+ max_bytes=256 * 1024**3, # videos.insert: "Uploaded files must not exceed 256GB" (subido desde 128GB en abr. 2022).
74
+ aspect_ratios=["9:16", "16:9"],
75
+ ),
76
+ Platform.FACEBOOK: PlatformSpec(
77
+ max_body=63206,
78
+ max_hashtags=30,
79
+ acepta_solo_texto=True,
80
+ # adapters/facebook.py añade post.link (si lo hay) al final del
81
+ # texto compuesto, tanto en el post de solo texto (message) como en
82
+ # el de imagen (caption) o vídeo (description): explícito -no el
83
+ # valor por defecto- porque es la única de las cuatro redes que lo
84
+ # hace.
85
+ incluye_link_en_texto=True,
86
+ exige_media=False,
87
+ max_video_s=90 * 60,
88
+ max_bytes=10 * 1024**3,
89
+ aspect_ratios=["9:16", "16:9", "1:1", "4:5"],
90
+ ),
91
+ Platform.INSTAGRAM: PlatformSpec(
92
+ max_body=2200,
93
+ hook_chars=125,
94
+ max_hashtags=30,
95
+ exige_media=True,
96
+ min_video_s=3,
97
+ max_video_s=15 * 60,
98
+ # Este adaptador publica el vídeo SIEMPRE como Reels
99
+ # (instagram.py fija media_type="REELS"), y "Reel Specifications"
100
+ # (ig-user/media, confirmado con Context7) dice: "Reels must be...
101
+ # a maximum file size of 300MB". El valor viejo (1 GB) triplicaba
102
+ # el límite real: dejaba pasar localmente un archivo que Instagram
103
+ # rechazaría minutos después, de forma opaca, en el sondeo del
104
+ # contenedor (status_code=ERROR).
105
+ max_bytes=300 * 1024**2,
106
+ aspect_ratios=["9:16", "1:1", "4:5"],
107
+ ),
108
+ Platform.TIKTOK: PlatformSpec(
109
+ max_body=2200,
110
+ # post_info.title: "maximum length of 2200 UTF-16 characters"
111
+ # (content-posting-api-reference-direct-post, confirmado con
112
+ # Context7) -no caracteres Python ni bytes UTF-8, ver docstring de
113
+ # unidad_max_body.
114
+ unidad_max_body="unidades_utf16",
115
+ max_hashtags=30,
116
+ exige_media=True,
117
+ min_video_s=3,
118
+ max_video_s=10 * 60,
119
+ max_bytes=4 * 1024**3,
120
+ aspect_ratios=["9:16"],
121
+ ),
122
+ }
123
+
124
+
125
+ def componer_caption(body: str, hashtags: list[str]) -> str:
126
+ """Join body text and hashtags with the standard separator."""
127
+ if not hashtags:
128
+ return body
129
+ etiquetas = " ".join(f"#{h.lstrip('#')}" for h in hashtags)
130
+ return f"{body}\n\n{etiquetas}"
131
+
132
+
133
+ def texto_publicado(post: PlatformPost) -> str:
134
+ """Return the exact text sent by the platform adapter."""
135
+ spec = PLATFORM_SPECS[post.platform]
136
+ texto = componer_caption(post.body, post.hashtags) if spec.hashtags_en_texto else componer_caption(post.body, post.visible_hashtags or [])
137
+ if spec.incluye_link_en_texto and post.link:
138
+ texto = f"{texto}\n\n{post.link}"
139
+ return texto
140
+
141
+
142
+ def youtube_tags(post: PlatformPost) -> list[str]:
143
+ """Explicit internal tags, or the unchanged legacy `hashtags` mapping."""
144
+ return post.tags if post.tags is not None else post.hashtags
145
+
146
+
147
+ def privacidad_efectiva(post: PlatformPost) -> str | None:
148
+ """Return the privacy value actually sent to the API, or None if unsupported."""
149
+ spec = PLATFORM_SPECS[post.platform]
150
+ if spec.valores_privacidad is None:
151
+ return None
152
+ return post.privacy if post.privacy is not None else spec.privacidad_por_defecto
153
+
154
+
155
+ def validar_privacidad(post: PlatformPost) -> list[ValidationError]:
156
+ """Validate privacy against the platform's supported values."""
157
+ spec = PLATFORM_SPECS[post.platform]
158
+ errores: list[ValidationError] = []
159
+
160
+ if post.privacy is None:
161
+ return errores
162
+
163
+ if spec.valores_privacidad is None:
164
+ errores.append(
165
+ ValidationError(
166
+ platform=post.platform,
167
+ campo="privacy",
168
+ motivo=(
169
+ f"{post.platform.value} does not support the 'privacy' field "
170
+ f"(received '{post.privacy}'); remove it from the block "
171
+ f"for {post.platform.value} in post.yml"
172
+ ),
173
+ )
174
+ )
175
+ elif post.privacy not in spec.valores_privacidad:
176
+ validos = ", ".join(spec.valores_privacidad)
177
+ errores.append(
178
+ ValidationError(
179
+ platform=post.platform,
180
+ campo="privacy",
181
+ motivo=(
182
+ f"'{post.privacy}' is not a valid privacy value "
183
+ f"for {post.platform.value}. Valid values: {validos}"
184
+ ),
185
+ )
186
+ )
187
+
188
+ return errores
189
+
190
+
191
+ def _longitud_utf16(texto: str) -> int:
192
+ """Count UTF-16 code units, as required by TikTok."""
193
+ return len(texto.encode("utf-16-le")) // 2
194
+
195
+
196
+ def _longitud_agregada_tags(tags: list[str]) -> int:
197
+ """Count aggregate YouTube tag length, including separators and quoted spaces."""
198
+ if not tags:
199
+ return 0
200
+ piezas = [f'"{t}"' if " " in t else t for t in tags]
201
+ return len(",".join(piezas))
202
+
203
+
204
+ def validar_texto(post: PlatformPost) -> list[ValidationError]:
205
+ """Validate post text against the platform's limits."""
206
+ spec = PLATFORM_SPECS[post.platform]
207
+ errores: list[ValidationError] = []
208
+
209
+ if spec.exige_title and not post.title:
210
+ errores.append(
211
+ ValidationError(
212
+ platform=post.platform,
213
+ campo="title",
214
+ motivo=f"{post.platform.value} requires a title, but none was provided",
215
+ )
216
+ )
217
+
218
+ if post.title and spec.max_title and len(post.title) > spec.max_title:
219
+ errores.append(
220
+ ValidationError(
221
+ platform=post.platform,
222
+ campo="title",
223
+ motivo=(
224
+ f"the title has {len(post.title)} characters "
225
+ f"; the maximum is {spec.max_title}"
226
+ ),
227
+ )
228
+ )
229
+
230
+ caption = texto_publicado(post) if post.platform == Platform.YOUTUBE else componer_caption(post.body, post.hashtags)
231
+ if spec.unidad_max_body == "bytes_utf8":
232
+ longitud_body = len(caption.encode("utf-8"))
233
+ unidad_body = "bytes"
234
+ elif spec.unidad_max_body == "unidades_utf16":
235
+ longitud_body = _longitud_utf16(caption)
236
+ unidad_body = "UTF-16 units"
237
+ else:
238
+ longitud_body = len(caption)
239
+ unidad_body = "characters"
240
+
241
+ if longitud_body > spec.max_body:
242
+ errores.append(
243
+ ValidationError(
244
+ platform=post.platform,
245
+ campo="body",
246
+ motivo=(
247
+ f"the text uses {longitud_body} {unidad_body} "
248
+ f"; the maximum is {spec.max_body} {unidad_body}"
249
+ ),
250
+ )
251
+ )
252
+
253
+ if spec.max_hashtags is not None and len(post.hashtags) > spec.max_hashtags:
254
+ errores.append(
255
+ ValidationError(
256
+ platform=post.platform,
257
+ campo="hashtags",
258
+ motivo=(
259
+ f"there are {len(post.hashtags)} hashtags "
260
+ f"; the maximum is {spec.max_hashtags}"
261
+ ),
262
+ )
263
+ )
264
+
265
+ if spec.max_tags_chars is not None:
266
+ longitud_tags = _longitud_agregada_tags(youtube_tags(post))
267
+ if longitud_tags > spec.max_tags_chars:
268
+ errores.append(
269
+ ValidationError(
270
+ platform=post.platform,
271
+ campo="tags" if post.tags is not None else "hashtags",
272
+ motivo=(
273
+ f"tags use {longitud_tags} characters "
274
+ f"combined; the maximum is {spec.max_tags_chars}"
275
+ ),
276
+ )
277
+ )
278
+
279
+ if spec.hook_chars and not post.body[: spec.hook_chars].strip():
280
+ errores.append(
281
+ ValidationError(
282
+ platform=post.platform,
283
+ campo="gancho",
284
+ motivo=(
285
+ f"the first {spec.hook_chars} characters are empty; "
286
+ "the feed truncates there, leaving no visible text"
287
+ ),
288
+ )
289
+ )
290
+
291
+ return errores
@@ -0,0 +1,152 @@
1
+ """Read-only, bounded full-byte verification of content-addressed hosted media."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import time
8
+ import uuid
9
+ from pathlib import Path
10
+ from urllib.parse import quote, urlsplit
11
+
12
+ import httpx
13
+
14
+ MAX_BYTES = 1024 * 1024 * 1024
15
+ TIMEOUT_SECONDS = 120.0
16
+ MIMES = {".mp4": "video/mp4", ".mov": "video/quicktime", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp"}
17
+
18
+
19
+ class HostedMediaError(ValueError):
20
+ pass
21
+
22
+
23
+ def file_digest(path: Path) -> str:
24
+ digest = hashlib.sha256()
25
+ with path.open("rb") as handle:
26
+ while chunk := handle.read(1024 * 1024):
27
+ digest.update(chunk)
28
+ return digest.hexdigest()
29
+
30
+
31
+ def validate_url(url: str) -> str:
32
+ parsed = urlsplit(url)
33
+ if (parsed.scheme != "https" or not parsed.hostname or parsed.username is not None
34
+ or parsed.password is not None or parsed.query or parsed.fragment
35
+ or any(ord(c) < 33 for c in url) or "\\" in url):
36
+ raise HostedMediaError("unsafe public URL: requires HTTPS without credentials, query or fragment")
37
+ return url
38
+
39
+
40
+ def public_url(base: str, relative: str) -> str:
41
+ validate_url(base)
42
+ return validate_url(base.rstrip("/") + "/" + "/".join(quote(part, safe="") for part in relative.split("/")))
43
+
44
+
45
+ def attest_public_media(path: Path, url: str, *, client: httpx.Client | None = None,
46
+ max_bytes: int = MAX_BYTES, timeout_s: float = TIMEOUT_SECONDS) -> dict:
47
+ validate_url(url)
48
+ if not re.fullmatch(r"[0-9a-f]{64}", path.stem):
49
+ raise HostedMediaError("scheduled media requires a SHA-256 filename")
50
+ size = path.stat().st_size
51
+ mime = MIMES.get(path.suffix.lower())
52
+ if not mime or size <= 0 or size > max_bytes or file_digest(path) != path.stem:
53
+ raise HostedMediaError("invalid local media: MIME type, size or SHA-256")
54
+ if client is None:
55
+ with httpx.Client(timeout=httpx.Timeout(timeout_s), follow_redirects=False, trust_env=False) as owned:
56
+ return attest_public_media(path, url, client=owned, max_bytes=max_bytes, timeout_s=timeout_s)
57
+ started = time.monotonic()
58
+ digest = hashlib.sha256()
59
+ total = 0
60
+ try:
61
+ # Standalone request avoids forwarding a caller's cookies/default headers.
62
+ request = httpx.Request("GET", url, headers={"Accept-Encoding": "identity"},
63
+ extensions={"timeout": {name: timeout_s for name in ("connect", "read", "write", "pool")}})
64
+ response = client.send(request, stream=True, follow_redirects=False, auth=None)
65
+ try:
66
+ if response.status_code != 200:
67
+ raise HostedMediaError("public media does not return HTTP 200 (redirects are not followed)")
68
+ if response.headers.get("content-type", "").split(";")[0].strip().lower() != mime:
69
+ raise HostedMediaError("public MIME type does not match")
70
+ if response.headers.get("content-encoding", "identity") != "identity":
71
+ raise HostedMediaError("public media must not be compressed")
72
+ length = response.headers.get("content-length")
73
+ if length is not None and (not length.isdigit() or int(length) != size):
74
+ raise HostedMediaError("public size does not match")
75
+ # Do not accumulate tiny transport chunks before checking budgets.
76
+ for chunk in response.iter_bytes():
77
+ total += len(chunk)
78
+ if total > min(size, max_bytes) or time.monotonic() - started > timeout_s:
79
+ raise HostedMediaError("public media exceeds the byte or time limit")
80
+ digest.update(chunk)
81
+ finally:
82
+ response.close()
83
+ except httpx.HTTPError as exc:
84
+ raise HostedMediaError(f"could not verify public media ({type(exc).__name__})") from exc
85
+ if total != size or digest.hexdigest() != path.stem:
86
+ raise HostedMediaError("public SHA-256 or size does not match the supplied bytes")
87
+ return {"url": url, "sha256": path.stem, "size": size, "mime": mime}
88
+
89
+
90
+ def _migration_attestations(brand, entry) -> list[dict] | None:
91
+ """A queue binding survives missing audit files; new approvals have none."""
92
+ proposal_id = entry.approval_migration
93
+ if proposal_id is None:
94
+ return None
95
+ from socialctl.rutas import validar_ruta_relativa
96
+ from socialctl.queue_migration import _digest
97
+ try:
98
+ if str(uuid.UUID(proposal_id)) != proposal_id:
99
+ raise ValueError("invalid UUID")
100
+ directory = validar_ruta_relativa(brand.raiz, f".socialctl/migrations/{proposal_id}", HostedMediaError, "attestation")
101
+ intent = json.loads((directory / "intent.json").read_bytes())
102
+ proposal = json.loads((directory / "proposal.json").read_bytes())
103
+ stored = json.loads((brand.raiz / ".socialctl/media-attestations.json").read_bytes())
104
+ matching = [item for item in intent["approvals"]
105
+ if item["id"] == entry.id and item["slug"] == entry.slug
106
+ and item["platform"] == entry.platform
107
+ and item["created_at"] == entry.created_at.isoformat()
108
+ and item["new_hash"] == entry.content_hash
109
+ and item["approval_migration"] == proposal_id]
110
+ if (intent["status"] != "committed" or intent["proposal"] != proposal_id
111
+ or stored["proposal"] != proposal_id or len(matching) != 1
112
+ or proposal["id"] != proposal_id or proposal["brand"] != brand.nombre
113
+ or proposal["digest"] != _digest(proposal)
114
+ or intent["digest"] != proposal["digest"]
115
+ or matching[0] not in proposal["approvals"]
116
+ or not isinstance(intent["attestations"], list)
117
+ or stored["attestations"] != intent["attestations"]):
118
+ raise ValueError("provenance or attestation does not match")
119
+ return stored["attestations"]
120
+ except (OSError, ValueError, KeyError, TypeError) as exc:
121
+ raise HostedMediaError("valid historical evidence of the migrated approval is missing") from exc
122
+
123
+
124
+ def verify_scheduled_instagram(post, brand, *, entry, client: httpx.Client | None = None) -> None:
125
+ """Verify frozen migration attestation and fresh public bytes before writes."""
126
+ from socialctl.media import ruta_relativa_efectiva
127
+ from socialctl.models import Platform
128
+ from socialctl.migration_files import write_json
129
+ from socialctl.scheduler import now_utc
130
+ base = brand.cuentas.get("instagram", {}).get("media_url_base", "")
131
+ stored = _migration_attestations(brand, entry)
132
+ from socialctl.connections.temporary_media import available
133
+ if not base and stored is None and available(brand):
134
+ # Approval fingerprints already bind local bytes. Upload at dispatch,
135
+ # never when scheduling: a 15-minute URL cannot survive a future queue.
136
+ return
137
+ results = []
138
+ for asset in post.platforms[Platform.INSTAGRAM].media:
139
+ url = public_url(base, ruta_relativa_efectiva(asset))
140
+ if stored is not None:
141
+ matching = [item for item in stored if item["url"] == url]
142
+ if (len(matching) != 1 or matching[0]["sha256"] != asset.path.stem
143
+ or matching[0]["size"] != asset.path.stat().st_size
144
+ or matching[0]["mime"] != MIMES.get(asset.path.suffix.lower())):
145
+ raise HostedMediaError("media does not match the persisted attestation")
146
+ results.append(attest_public_media(asset.path, url, client=client))
147
+ if not results:
148
+ raise HostedMediaError("scheduled media is missing")
149
+ write_json(brand.raiz / ".socialctl/last-media-preflight.json", {
150
+ "slug": post.slug, "entry_id": entry.id, "created_at": entry.created_at.isoformat(),
151
+ "content_hash": entry.content_hash, "approval_migration": entry.approval_migration,
152
+ "checked_at": now_utc().isoformat(), "attestations": results})