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,485 @@
1
+ """Local immutable, verifiable ChangeSets for YouTube metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from socialctl.management.snippet_readback import same_snippet_readback
6
+
7
+ import fcntl
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import os
12
+ import tempfile
13
+ import uuid
14
+ from contextlib import contextmanager
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any, Iterator, Literal
18
+
19
+ import yaml
20
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
21
+
22
+ from socialctl.management.youtube import (
23
+ YouTubeManagementClient,
24
+ YouTubeManagementError,
25
+ YouTubeUpdateConflict,
26
+ YouTubeUpdateRejected,
27
+ YouTubeUpdateUncertain,
28
+ )
29
+
30
+ SCHEMA_VERSION = 1
31
+ PATCH_FIELDS = frozenset(
32
+ {"title", "description", "tags", "categoryId", "defaultLanguage"}
33
+ )
34
+ IMMUTABLE_FIELDS = (
35
+ "id",
36
+ "version",
37
+ "platform",
38
+ "video_id",
39
+ "patch",
40
+ "target_account",
41
+ "observed_etag",
42
+ "before",
43
+ "after",
44
+ "created_at",
45
+ )
46
+
47
+
48
+ def _validate_patch_mapping(value: Any) -> dict[str, Any]:
49
+ if not isinstance(value, dict):
50
+ raise ValueError("patch must be a mapping")
51
+ if not value:
52
+ raise ValueError("patch is empty")
53
+ unknown = set(value) - PATCH_FIELDS
54
+ if unknown:
55
+ raise ValueError(
56
+ f"unknown patch field: {', '.join(sorted(str(x) for x in unknown))}"
57
+ )
58
+ nulls = [key for key, item in value.items() if item is None]
59
+ if nulls:
60
+ raise ValueError(
61
+ f"patch does not accept null ({', '.join(sorted(nulls))}); "
62
+ "omission preserves the value"
63
+ )
64
+ _validate_patch_types(value)
65
+ return dict(value)
66
+
67
+
68
+ class ChangeError(ValueError):
69
+ """Readable ChangeSet format, persistence or state error."""
70
+
71
+
72
+ class ApprovalMismatch(ChangeError):
73
+ """Approval does not cover this proposal's exact fingerprint."""
74
+
75
+
76
+ class ChangeConflict(ChangeError):
77
+ """Remote content changed since preview or during PUT."""
78
+
79
+
80
+ class ChangeLocked(ChangeError):
81
+ """Another process is applying the same ChangeSet."""
82
+
83
+
84
+ class EditFile(BaseModel):
85
+ model_config = ConfigDict(extra="forbid")
86
+
87
+ version: Literal[1]
88
+ platform: Literal["youtube"]
89
+ video_id: str = Field(min_length=1)
90
+ patch: dict[str, Any]
91
+
92
+ @field_validator("patch", mode="before")
93
+ @classmethod
94
+ def validate_patch(cls, value: Any) -> dict[str, Any]:
95
+ return _validate_patch_mapping(value)
96
+
97
+
98
+ class ChangeSet(BaseModel):
99
+ model_config = ConfigDict(extra="forbid")
100
+
101
+ id: str
102
+ version: Literal[1] = 1
103
+ platform: Literal["youtube"] = "youtube"
104
+ video_id: str
105
+ patch: dict[str, Any]
106
+ target_account: str
107
+ observed_etag: str
108
+ before: dict[str, Any]
109
+ after: dict[str, Any]
110
+ fingerprint: str
111
+ status: str = "proposed"
112
+ verified: bool = False
113
+ created_at: datetime
114
+ updated_at: datetime
115
+ journal: list[dict[str, Any]] = []
116
+
117
+
118
+ def now_utc() -> datetime:
119
+ return datetime.now(timezone.utc)
120
+
121
+
122
+ def load_edit_file(path: Path) -> EditFile:
123
+ """Load initial proposal schema and reject ambiguous omissions."""
124
+ try:
125
+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))
126
+ except (OSError, yaml.YAMLError) as exc:
127
+ raise ChangeError(f"failed to read change file {path}: {exc}") from exc
128
+ if not isinstance(raw, dict):
129
+ raise ChangeError("change file must contain a mapping")
130
+ video_id = raw.get("video_id")
131
+ if (
132
+ not isinstance(video_id, str)
133
+ or not video_id.strip()
134
+ or video_id != video_id.strip()
135
+ ):
136
+ raise ChangeError("video_id must be nonempty text without surrounding whitespace")
137
+ try:
138
+ return EditFile.model_validate(raw)
139
+ except ValidationError as exc:
140
+ raise ChangeError(f"invalid change file (extra field or type): {exc}") from exc
141
+
142
+
143
+ def _validate_patch_types(patch: dict[str, Any]) -> None:
144
+ for field in PATCH_FIELDS - {"tags"}:
145
+ if field in patch and not isinstance(patch[field], str):
146
+ raise ChangeError(f"patch.{field} must be text")
147
+ if "tags" in patch:
148
+ tags = patch["tags"]
149
+ if not isinstance(tags, list) or any(not isinstance(tag, str) for tag in tags):
150
+ raise ChangeError("patch.tags must be a list of strings")
151
+
152
+
153
+ def _validate_snippet(snippet: dict[str, Any]) -> None:
154
+ title = snippet.get("title")
155
+ category = snippet.get("categoryId")
156
+ if not isinstance(title, str) or not title.strip():
157
+ raise ChangeError("YouTube requires a nonempty title")
158
+ if len(title) > 100:
159
+ raise ChangeError(f"title has {len(title)} characters; maximum is 100")
160
+ if not isinstance(category, str) or not category.strip():
161
+ raise ChangeError("YouTube requires a nonempty category (categoryId)")
162
+
163
+ description = snippet.get("description", "")
164
+ if not isinstance(description, str):
165
+ raise ChangeError("description must be text")
166
+ size = len(description.encode("utf-8"))
167
+ if size > 5000:
168
+ raise ChangeError(f"description uses {size} bytes; maximum is 5000 bytes")
169
+
170
+ tags = snippet.get("tags", [])
171
+ if not isinstance(tags, list) or any(not isinstance(tag, str) for tag in tags):
172
+ raise ChangeError("tags must be a list of strings")
173
+ aggregate = len(",".join(f'"{tag}"' if " " in tag else tag for tag in tags))
174
+ if aggregate > 500:
175
+ raise ChangeError(
176
+ f"tags use {aggregate} aggregate characters; maximum is 500"
177
+ )
178
+
179
+ for field in ("defaultLanguage", "defaultAudioLanguage"):
180
+ if field in snippet and not isinstance(snippet[field], str):
181
+ raise ChangeError(f"{field} must be text")
182
+
183
+
184
+ def _immutable_payload(change: ChangeSet | dict[str, Any]) -> dict[str, Any]:
185
+ raw = change.model_dump(mode="json") if isinstance(change, ChangeSet) else change
186
+ return {field: raw[field] for field in IMMUTABLE_FIELDS}
187
+
188
+
189
+ def _fingerprint(change: ChangeSet | dict[str, Any]) -> str:
190
+ canonical = json.dumps(
191
+ _immutable_payload(change),
192
+ sort_keys=True,
193
+ separators=(",", ":"),
194
+ ensure_ascii=False,
195
+ ).encode("utf-8")
196
+ return hashlib.sha256(canonical).hexdigest()
197
+
198
+
199
+ class ChangeStore:
200
+ """Atomic JSON persistence and interprocess locking per ChangeSet."""
201
+
202
+ model_type = ChangeSet
203
+ fingerprint_for = staticmethod(_fingerprint)
204
+
205
+ def __init__(self, brand_root: Path) -> None:
206
+ self.root = brand_root / ".socialctl" / "changes"
207
+
208
+ def _validate_id(self, change_id: str) -> str:
209
+ try:
210
+ parsed = uuid.UUID(change_id)
211
+ except (ValueError, TypeError, AttributeError):
212
+ raise ChangeError(f"invalid ChangeSet ID: must be a UUID, not {change_id!r}") from None
213
+ canonical = str(parsed)
214
+ if canonical != change_id:
215
+ raise ChangeError("invalid ChangeSet ID: UUID must be canonical")
216
+ return canonical
217
+
218
+ def path_for(self, change_id: str) -> Path:
219
+ return self.root / f"{self._validate_id(change_id)}.json"
220
+
221
+ def load(self, change_id: str) -> ChangeSet:
222
+ path = self.path_for(change_id)
223
+ try:
224
+ raw = json.loads(path.read_text(encoding="utf-8"))
225
+ from socialctl.youtube_data import JOURNALS, require_fresh_api_data
226
+ if self.root.name in JOURNALS:
227
+ if raw.get('data_lifecycle')=='purged':
228
+ raise ChangeError('API data removed; this operation is blocked against replay. Reconcile manually.')
229
+ require_fresh_api_data(raw.get('created_at'))
230
+ change = self.model_type.model_validate(raw)
231
+ except FileNotFoundError:
232
+ raise ChangeError(f"ChangeSet does not exist: {change_id}") from None
233
+ except (OSError, json.JSONDecodeError, ValidationError) as exc:
234
+ raise ChangeError(f"failed to read ChangeSet {change_id}: {exc}") from exc
235
+ self._validate_id(change.id)
236
+ if change.id != change_id:
237
+ raise ChangeError(
238
+ f"internal ChangeSet ID does not match filename {change_id}"
239
+ )
240
+ expected = self.fingerprint_for(change)
241
+ if not hmac.compare_digest(change.fingerprint, expected):
242
+ raise ChangeError(
243
+ f"ChangeSet {change_id} fingerprint mismatch; proposal was altered"
244
+ )
245
+ return change
246
+
247
+ def save(self, change: ChangeSet) -> None:
248
+ self._validate_id(change.id)
249
+ if not hmac.compare_digest(change.fingerprint, self.fingerprint_for(change)):
250
+ raise ChangeError("ChangeSet was not saved: immutable fingerprint mismatch")
251
+ temporary: str | None = None
252
+ try:
253
+ self._ensure_root()
254
+ fd, temporary = tempfile.mkstemp(
255
+ prefix=f"{change.id}.", suffix=".tmp", dir=self.root
256
+ )
257
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
258
+ json.dump(
259
+ change.model_dump(mode="json"),
260
+ handle,
261
+ indent=2,
262
+ ensure_ascii=False,
263
+ )
264
+ handle.write("\n")
265
+ handle.flush()
266
+ os.fsync(handle.fileno())
267
+ os.replace(temporary, self.path_for(change.id))
268
+ # El fsync del fichero temporal no hace durable el cambio de nombre:
269
+ # para que un intent persistido no pueda volver a `proposed` tras un
270
+ # corte de energía, también hay que sincronizar el directorio que
271
+ # contiene la entrada reemplazada antes de permitir el PUT remoto.
272
+ self._sync_directory(self.root)
273
+ except OSError as exc:
274
+ if temporary is not None:
275
+ try:
276
+ os.unlink(temporary)
277
+ except OSError:
278
+ pass
279
+ raise ChangeError(f"failed to save ChangeSet {change.id}: {exc}") from exc
280
+
281
+ def _ensure_root(self) -> None:
282
+ """Create and sync the storage chain on every attempt, including existing parents after a failed fsync."""
283
+ for directory in (self.root.parent, self.root):
284
+ directory.mkdir(exist_ok=True)
285
+ self._sync_directory(directory.parent)
286
+
287
+ @staticmethod
288
+ def _sync_directory(path: Path) -> None:
289
+ descriptor = os.open(path, os.O_RDONLY)
290
+ try:
291
+ os.fsync(descriptor)
292
+ finally:
293
+ os.close(descriptor)
294
+
295
+ @contextmanager
296
+ def apply_lock(self, change_id: str) -> Iterator[None]:
297
+ validated = self._validate_id(change_id)
298
+ self.root.mkdir(parents=True, exist_ok=True)
299
+ path = self.root / f"{validated}.lock"
300
+ descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
301
+ try:
302
+ try:
303
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
304
+ except BlockingIOError:
305
+ raise ChangeLocked(
306
+ f"another process is applying ChangeSet {change_id}"
307
+ ) from None
308
+ yield
309
+ finally:
310
+ try:
311
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
312
+ finally:
313
+ os.close(descriptor)
314
+
315
+
316
+ def prepare_youtube_change(
317
+ youtube: YouTubeManagementClient, store: ChangeStore, edit: EditFile
318
+ ) -> ChangeSet:
319
+ # Un modelo Pydantic puede mutarse en memoria después de su construcción
320
+ # (incluido su dict `patch`). Revalidar una copia cruda impide que un
321
+ # llamador de servicio eluda el mismo límite que aplica `load_edit_file`.
322
+ try:
323
+ validated = EditFile.model_validate(edit.model_dump(mode="python"))
324
+ except ValidationError as exc:
325
+ raise ChangeError(f"invalid proposal patch: {exc}") from exc
326
+
327
+ inspected = youtube.inspect(validated.video_id)
328
+ before = youtube.editable_snippet(inspected)
329
+ after = {**before, **validated.patch}
330
+ _validate_snippet(before)
331
+ _validate_snippet(after)
332
+ moment = now_utc()
333
+ raw: dict[str, Any] = {
334
+ "id": str(uuid.uuid4()),
335
+ "version": SCHEMA_VERSION,
336
+ "platform": "youtube",
337
+ "video_id": validated.video_id,
338
+ "patch": dict(validated.patch),
339
+ "target_account": inspected.channel_id,
340
+ "observed_etag": inspected.etag,
341
+ "before": before,
342
+ "after": after,
343
+ "fingerprint": "",
344
+ "status": "proposed",
345
+ "verified": False,
346
+ "created_at": moment,
347
+ "updated_at": moment,
348
+ "journal": [{"at": moment.isoformat(), "event": "prepared"}],
349
+ }
350
+ change = ChangeSet.model_validate(raw)
351
+ change.fingerprint = _fingerprint(change)
352
+ store.save(change)
353
+ return change
354
+
355
+
356
+ def _append(change: ChangeSet, event: str, **details: Any) -> None:
357
+ moment = now_utc()
358
+ change.updated_at = moment
359
+ change.journal.append({"at": moment.isoformat(), "event": event, **details})
360
+
361
+
362
+ def _same_snippet(current: dict[str, Any], expected: dict[str, Any]) -> bool:
363
+ return current == expected
364
+
365
+
366
+ def apply_youtube_change(
367
+ youtube: YouTubeManagementClient,
368
+ store: ChangeStore,
369
+ change_id: str,
370
+ approval_digest: str,
371
+ ) -> ChangeSet:
372
+ """Apply or reconcile a ChangeSet; never repeat an uncertain PUT."""
373
+ with store.apply_lock(change_id):
374
+ change = store.load(change_id)
375
+ if not hmac.compare_digest(approval_digest, change.fingerprint):
376
+ raise ApprovalMismatch(
377
+ "approval does not exactly match proposal fingerprint"
378
+ )
379
+ if youtube.configured_channel_id != change.target_account:
380
+ raise ChangeError("configured account no longer matches ChangeSet")
381
+
382
+ if change.status in {"applying", "uncertain"}:
383
+ return _reconcile(youtube, store, change)
384
+ if change.status != "proposed":
385
+ raise ChangeError(
386
+ f"ChangeSet status is {change.status}; PUT will not be repeated"
387
+ )
388
+
389
+ current = youtube.inspect(change.video_id)
390
+ current_snippet = youtube.editable_snippet(current)
391
+ if not _same_snippet(current_snippet, change.before):
392
+ change.status = "conflict"
393
+ _append(change, "pre_write_conflict")
394
+ store.save(change)
395
+ raise ChangeConflict(
396
+ "conflict: remote snippet changed since preview; no PUT was sent"
397
+ )
398
+
399
+ change.status = "applying"
400
+ _append(
401
+ change,
402
+ "write_intent",
403
+ approval_digest=approval_digest,
404
+ if_match=current.etag,
405
+ )
406
+ store.save(change)
407
+
408
+ try:
409
+ youtube.update_snippet(change.video_id, change.after, etag=current.etag)
410
+ except YouTubeUpdateConflict as exc:
411
+ change.status = "conflict"
412
+ _append(change, "etag_conflict", error=str(exc))
413
+ store.save(change)
414
+ raise ChangeConflict(str(exc)) from None
415
+ except YouTubeUpdateRejected as exc:
416
+ change.status = "failed"
417
+ _append(change, "write_rejected", error=str(exc))
418
+ store.save(change)
419
+ raise ChangeError(str(exc)) from None
420
+ except YouTubeUpdateUncertain as exc:
421
+ change.status = "uncertain"
422
+ _append(change, "write_uncertain", error=str(exc))
423
+ store.save(change)
424
+ raise ChangeError(str(exc)) from None
425
+ except Exception as exc:
426
+ change.status = "uncertain"
427
+ safe = f"uncertain outcome: unexpected failure ({type(exc).__name__})"
428
+ _append(change, "write_uncertain", error=safe)
429
+ store.save(change)
430
+ raise ChangeError(safe) from None
431
+
432
+ try:
433
+ verified = youtube.inspect(change.video_id)
434
+ except YouTubeManagementError as exc:
435
+ change.status = "uncertain"
436
+ _append(change, "verification_uncertain", error=str(exc))
437
+ store.save(change)
438
+ raise ChangeError(
439
+ "uncertain outcome: YouTube accepted PUT but verification failed"
440
+ ) from None
441
+ if not same_snippet_readback(youtube.editable_snippet(verified), change.after):
442
+ change.status = "uncertain"
443
+ _append(change, "verification_mismatch")
444
+ store.save(change)
445
+ raise ChangeError(
446
+ "uncertain outcome: reread snippet does not match proposal"
447
+ )
448
+
449
+ change.status = "applied"
450
+ change.verified = True
451
+ _append(change, "verified_applied", etag=verified.etag)
452
+ store.save(change)
453
+ return change
454
+
455
+
456
+ def _reconcile(
457
+ youtube: YouTubeManagementClient, store: ChangeStore, change: ChangeSet
458
+ ) -> ChangeSet:
459
+ """Reread only; never call update when resuming an uncertain attempt."""
460
+ try:
461
+ current = youtube.inspect(change.video_id)
462
+ except YouTubeManagementError as exc:
463
+ _append(change, "reconciliation_failed", error=str(exc))
464
+ store.save(change)
465
+ raise ChangeError(
466
+ "outcome remains uncertain: read-only reconciliation failed"
467
+ ) from None
468
+
469
+ snippet = youtube.editable_snippet(current)
470
+ if same_snippet_readback(snippet, change.after):
471
+ change.status = "applied"
472
+ change.verified = True
473
+ _append(change, "reconciled_applied", etag=current.etag)
474
+ store.save(change)
475
+ return change
476
+
477
+ change.status = "manual_review"
478
+ change.verified = False
479
+ event = "reconciled_still_before" if _same_snippet(snippet, change.before) else "reconciled_diverged"
480
+ _append(change, event)
481
+ store.save(change)
482
+ raise ChangeError(
483
+ "uncertain PUT requires manual review; reconciliation was read-only "
484
+ "and did not repeat the write"
485
+ )