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,259 @@
1
+ """Fixed YouTube owned-resource reads and single effects; never retries a write."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import uuid
6
+
7
+ from socialctl.management.owned_schema import image_id, owned_resource_id, resource_id, target, validate_edit
8
+ from socialctl.management.youtube_resources import API, UPLOAD, YouTubeResourcesClient, ResourceError, ResourceUncertain
9
+
10
+ VIDEO_PARTS = {"snippet", "status", "localizations", "contentDetails", "processingDetails", "statistics", "recordingDetails", "fileDetails", "suggestions", "player", "topicDetails", "liveStreamingDetails", "paidProductPlacementDetails"}
11
+ CHANNEL_PARTS = {"snippet", "brandingSettings", "status", "localizations", "contentDetails", "statistics", "topicDetails", "contentOwnerDetails"}
12
+ PARTS = {"playlists": "snippet,status,localizations,contentDetails", "playlistItems": "snippet,contentDetails,status",
13
+ "channelSections": "snippet,contentDetails", "playlistImages": "snippet",
14
+ "channels": "snippet,brandingSettings,status,localizations", "videos": "snippet,recordingDetails"}
15
+ KINDS = {"playlists": "youtube#playlist", "playlistItems": "youtube#playlistItem", "channelSections": "youtube#channelSection", "playlistImages": "youtube#playlistImage", "channels": "youtube#channel", "videos": "youtube#video"}
16
+
17
+
18
+ class YouTubeOwnedClient(YouTubeResourcesClient):
19
+ def _endpoint_allowed(self, method, path):
20
+ regular = {("GET", name) for name in PARTS}
21
+ regular |= {(verb, name) for name in {"playlists", "playlistItems", "channelSections", "playlistImages"} for verb in {"POST", "PUT", "DELETE"}}
22
+ regular |= {("PUT", "channels"), ("PUT", "videos"), ("DELETE", "videos"), ("POST", "watermarks/unset")}
23
+ uploads = {("POST", "channelBanners/insert"), ("POST", "watermarks/set"), ("POST", "playlistImages"), ("PUT", "playlistImages")}
24
+ return any(method == verb and path == "/youtube/v3/" + name for verb, name in regular) or any(
25
+ method == verb and path == "/upload/youtube/v3/" + name for verb, name in uploads)
26
+
27
+ def identity(self):
28
+ configured = self.configured_channel_id
29
+ if self._authenticated_channel(self._token()) != configured:
30
+ raise ResourceError("authenticated channel does not match configured brand/account")
31
+ return configured
32
+
33
+ def _validate_row(self, resource, row, *, parent=None):
34
+ if not isinstance(row, dict):
35
+ raise ResourceError("invalid resource")
36
+ owned_resource_id(resource, row.get("id"))
37
+ if row.get("kind", KINDS[resource]) != KINDS[resource]:
38
+ raise ResourceError("unexpected resource type")
39
+ if resource != "playlistImages" and (not isinstance(row.get("etag"), str) or not row["etag"]):
40
+ raise ResourceError("resource lacks verifiable ETag")
41
+ snip = row.get("snippet")
42
+ if not isinstance(snip, dict):
43
+ raise ResourceError("resource lacks verifiable snippet")
44
+ if resource == "channels":
45
+ owned = row["id"] == self.configured_channel_id
46
+ elif resource in {"playlistImages", "playlistItems"}:
47
+ owned = bool(parent) and snip.get("playlistId") == parent
48
+ if resource == "playlistItems":
49
+ rid = snip.get("resourceId")
50
+ if not isinstance(rid, dict) or set(rid) != {"kind", "videoId"} or rid["kind"] != "youtube#video":
51
+ raise ResourceError("playlistItem lacks explicit videoId/resourceId")
52
+ resource_id(rid["videoId"])
53
+ if type(snip.get("position")) is not int or snip["position"] < 0:
54
+ raise ResourceError("invalid playlistItem position")
55
+ content = row.get("contentDetails", {})
56
+ if not isinstance(content, dict) or ("videoId" in content and content["videoId"] != rid["videoId"]):
57
+ raise ResourceError("playlistItem has contradictory video identities")
58
+ owned = owned and snip.get("channelId") == self.configured_channel_id
59
+ else:
60
+ if snip.get("type") != "hero" or set(snip) - {"playlistId", "type", "width", "height"}:
61
+ raise ResourceError("unknown image type/fields")
62
+ for field in {"width", "height"} & set(snip):
63
+ if type(snip[field]) is not int or snip[field] <= 0:
64
+ raise ResourceError("invalid remote image dimensions")
65
+ else:
66
+ owned = snip.get("channelId") == self.configured_channel_id
67
+ if not owned:
68
+ raise ResourceError("resource does not belong to configured channel/playlist")
69
+ return row
70
+
71
+ def one(self, resource, rid, *, parent=None, parts=None, optional=False):
72
+ if resource not in PARTS:
73
+ raise ResourceError("unsupported read resource")
74
+ self.identity()
75
+ if resource in {"playlistItems", "playlistImages"}:
76
+ self.one("playlists", resource_id(parent))
77
+ if resource == "playlistImages":
78
+ result = self.list_images(parent)
79
+ if not result["complete"]:
80
+ raise ResourceError("incomplete image listing; identity unverifiable")
81
+ rows = [r for r in result["items"] if r["id"] == image_id(rid)]
82
+ else:
83
+ owned_resource_id(resource, rid)
84
+ try:
85
+ payload = self._json(self._request("GET", f"{API}/{resource}", params={"part": parts or PARTS[resource], "id": rid}))
86
+ except ResourceError as exc:
87
+ # Only this method's documented exact-ID reason is absence.
88
+ # The caller still needs a durable delete receipt to prove success.
89
+ if optional and resource == "channelSections" and exc.http_status == 404 and exc.provider_reason == "channelSectionNotFound":
90
+ return None
91
+ raise
92
+ rows = self._section_rows(payload) if resource == "channelSections" else payload.get("items")
93
+ if rows is None and self._empty_complete(payload):
94
+ rows = []
95
+ if not isinstance(rows, list) or len(rows) > 1 or any(k in payload for k in ("nextPageToken", "prevPageToken")):
96
+ raise ResourceError("incomplete or ambiguous ID read")
97
+ page = payload.get("pageInfo")
98
+ if page is not None and (not isinstance(page, dict) or type(page.get("totalResults")) is not int or page["totalResults"] != len(rows)):
99
+ raise ResourceError("contradictory ID read: totalResults mismatch")
100
+ if not rows:
101
+ if optional:
102
+ return None
103
+ raise ResourceError("owned ID not found; absence/permissions inconclusive")
104
+ row = self._validate_row(resource, rows[0], parent=parent)
105
+ if row["id"] != rid:
106
+ raise ResourceError("returned ID does not match requested ID")
107
+ return row
108
+
109
+ @staticmethod
110
+ def _section_rows(payload):
111
+ # Discovery's unpaginated response has no pageInfo or continuation. An
112
+ # omitted optional items array is empty only in the valid method envelope.
113
+ if (set(payload) - {"kind", "etag", "items", "eventId", "visitorId"}
114
+ or payload.get("kind") != "youtube#channelSectionListResponse"
115
+ or not isinstance(payload.get("etag"), str) or not payload["etag"]):
116
+ raise ResourceError("invalid unpaginated sections envelope")
117
+ rows = payload.get("items", [])
118
+ if not isinstance(rows, list) or len(rows) > 10:
119
+ raise ResourceError("invalid section items or limit exceeded")
120
+ return rows
121
+
122
+ @staticmethod
123
+ def _empty_complete(payload):
124
+ page = payload.get("pageInfo")
125
+ return (isinstance(page, dict) and type(page.get("totalResults")) is int and page["totalResults"] == 0
126
+ and type(page.get("resultsPerPage")) is int and 0 < page["resultsPerPage"] <= 50
127
+ and not any(k in payload for k in ("nextPageToken", "prevPageToken")))
128
+
129
+ def _list(self, resource, params, *, parent=None, max_pages=100):
130
+ if type(max_pages) is not int or not 1 <= max_pages <= 100:
131
+ raise ResourceError("max-pages requires integer between 1 and 100")
132
+ self.identity()
133
+ report = {"items": [], "complete": False, "absence_proven": False, "pages": 0,
134
+ "limitation": "Bounded read; list does not prove global absence or write permissions.", "error": None}
135
+ tokens, ids = set(), set()
136
+ token = None
137
+ expected_total = None
138
+ for _ in range(max_pages):
139
+ try:
140
+ query = {"part": PARTS[resource], **params}
141
+ if resource != "channelSections":
142
+ query["maxResults"] = 50
143
+ if token is not None:
144
+ query["pageToken"] = token
145
+ payload = self._json(self._request("GET", f"{API}/{resource}", params=query))
146
+ rows = self._section_rows(payload) if resource == "channelSections" else payload.get("items")
147
+ if rows is None and self._empty_complete(payload):
148
+ rows = []
149
+ if not isinstance(rows, list) or len(rows) > (10 if resource == "channelSections" else 50):
150
+ raise ResourceError("invalid items or limit exceeded")
151
+ page_rows = []
152
+ for row in rows:
153
+ self._validate_row(resource, row, parent=parent)
154
+ if row["id"] in ids:
155
+ raise ResourceError("incomplete list: duplicate ID across pages")
156
+ ids.add(row["id"])
157
+ page_rows.append(row)
158
+ report["items"].extend(page_rows)
159
+ report["pages"] += 1
160
+ next_token = payload.get("nextPageToken")
161
+ if resource == "channelSections":
162
+ if any(k in payload for k in ("nextPageToken", "prevPageToken")):
163
+ raise ResourceError("undocumented section pagination")
164
+ report["complete"] = True
165
+ break
166
+ page = payload.get("pageInfo")
167
+ if not isinstance(page, dict) or type(page.get("totalResults")) is not int or page["totalResults"] < 0:
168
+ raise ResourceError("missing valid totalResults; incomplete list")
169
+ if expected_total is not None and page["totalResults"] != expected_total:
170
+ raise ResourceError("list total changed during read")
171
+ expected_total = page["totalResults"]
172
+ if "nextPageToken" not in payload:
173
+ report["complete"] = len(report["items"]) == expected_total
174
+ if not report["complete"]:
175
+ report["error"] = "totalResults does not match IDs read; incomplete list"
176
+ break
177
+ if not isinstance(next_token, str) or not next_token or len(next_token) > 2048 or next_token in tokens:
178
+ raise ResourceError("incomplete list: invalid/repeated continuation")
179
+ tokens.add(next_token)
180
+ token = next_token
181
+ except ResourceError as exc:
182
+ report["error"] = str(exc)
183
+ break
184
+ if not report["complete"] and not report["error"]:
185
+ report["error"] = "page limit; incomplete list"
186
+ return report
187
+
188
+ def list_playlists(self, *, max_pages=100):
189
+ return self._list("playlists", {"mine": "true"}, max_pages=max_pages)
190
+
191
+ def list_items(self, playlist_id, *, max_pages=100):
192
+ self.one("playlists", resource_id(playlist_id))
193
+ return self._list("playlistItems", {"playlistId": playlist_id}, parent=playlist_id, max_pages=max_pages)
194
+
195
+ def list_sections(self):
196
+ return self._list("channelSections", {"channelId": self.configured_channel_id})
197
+
198
+ def list_images(self, playlist_id, *, max_pages=100):
199
+ self.one("playlists", resource_id(playlist_id))
200
+ # Current discovery20260910 plus actual controller GET evidence. The
201
+ # method page's id/playlistId filters contradict the service schema.
202
+ return self._list("playlistImages", {"parent": playlist_id}, parent=playlist_id, max_pages=max_pages)
203
+
204
+ def inspect_channel(self, channel_id, *, parts=None):
205
+ selected = set(parts or PARTS["channels"].split(","))
206
+ if not selected or selected - CHANNEL_PARTS:
207
+ raise ResourceError("unsupported channel read parts")
208
+ selected.add("snippet")
209
+ if resource_id(channel_id) != self.configured_channel_id:
210
+ raise ResourceError("channel does not match brand")
211
+ return self.one("channels", channel_id, parts=",".join(sorted(selected)))
212
+
213
+ def inspect_video(self, video_id, *, parts=None):
214
+ selected = set(parts or PARTS["videos"].split(","))
215
+ if not selected or selected - VIDEO_PARTS:
216
+ raise ResourceError("unsupported video read parts")
217
+ selected.add("snippet")
218
+ return self.one("videos", video_id, parts=",".join(sorted(selected)))
219
+
220
+ def effect(self, edit, resource, rid, body, *, etag=None, asset=None, data=None):
221
+ """One fixed effect. Only the durable coordinator calls this method."""
222
+ edit = validate_edit(edit)
223
+ if target(edit) != (resource, rid):
224
+ raise ResourceError("action and ID do not match target resource")
225
+ action = edit.action
226
+ deleting = action.endswith("-delete")
227
+ inserting = action in {"playlist-create", "item-insert", "section-create", "image-insert"}
228
+ headers = {"If-Match": etag} if etag and resource != "playlistImages" else {}
229
+ if action == "banner-upload":
230
+ response = self._request("POST", f"{UPLOAD}/channelBanners/insert",
231
+ headers={"Content-Type": asset["mime"]}, params={"uploadType": "media"}, content=data)
232
+ return self._json(response, writing=True)
233
+ if action == "watermark-unset":
234
+ response = self._request("POST", f"{API}/watermarks/unset", params={"channelId": edit.channel_id})
235
+ elif deleting:
236
+ response = self._request("DELETE", f"{API}/{resource}", headers=headers, params={"id": rid})
237
+ else:
238
+ outgoing = dict(body) if inserting or action == "watermark-set" else {"id": rid, **body}
239
+ params = {"part": ",".join(sorted(body))}
240
+ endpoint, method = resource, "POST" if inserting else "PUT"
241
+ if action == "watermark-set":
242
+ endpoint, method, params, headers = "watermarks/set", "POST", {"channelId": edit.channel_id}, {}
243
+ if data is None:
244
+ response = self._request(method, f"{API}/{endpoint}", headers=headers, params=params, json=outgoing)
245
+ else:
246
+ boundary = "socialctl_" + uuid.uuid4().hex
247
+ while boundary.encode() in data:
248
+ boundary = "socialctl_" + uuid.uuid4().hex
249
+ content = (f"--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n".encode()
250
+ + json.dumps(outgoing, ensure_ascii=False).encode()
251
+ + f"\r\n--{boundary}\r\nContent-Type: {asset['mime']}\r\n\r\n".encode()
252
+ + data + f"\r\n--{boundary}--\r\n".encode())
253
+ response = self._request(method, f"{UPLOAD}/{endpoint}", params={**params, "uploadType": "multipart"},
254
+ headers={**headers, "Content-Type": f"multipart/related; boundary={boundary}"}, content=content)
255
+ if deleting or action in {"watermark-set", "watermark-unset"}:
256
+ if response.status_code != 204:
257
+ raise ResourceUncertain("expected 204 No Content; outcome unconfirmed")
258
+ return {"http_status": 204}
259
+ return self._json(response, writing=True)
@@ -0,0 +1,305 @@
1
+ """Fixed-host supplied thumbnail/caption transport. No video download or conversion."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ import uuid
7
+ from urllib.parse import quote
8
+
9
+ import httpx
10
+ from socialctl.read_budget import ReadDeadlineExceeded, transport_label
11
+
12
+ from socialctl.agent_errors import with_error_code
13
+ from socialctl.auth import obtener_token
14
+ from socialctl.management.changes import ChangeError
15
+ from socialctl.management.youtube_metadata import same_metadata_snapshot
16
+ from socialctl.management.youtube import YouTubeManagementClient, YouTubeManagementError
17
+ from socialctl.models import Platform
18
+
19
+ API = "https://www.googleapis.com/youtube/v3"
20
+ UPLOAD = "https://www.googleapis.com/upload/youtube/v3"
21
+ MAX_CAPTION = 100 * 1024 * 1024
22
+
23
+
24
+ class ResourceError(ChangeError):
25
+ def __init__(self, message, *, http_status=None, provider_reason=None):
26
+ super().__init__(message)
27
+ self.http_status = http_status
28
+ self.provider_reason = provider_reason
29
+
30
+
31
+ class ResourceRejected(ResourceError):
32
+ pass
33
+
34
+
35
+ class ResourceConflict(ResourceRejected):
36
+ pass
37
+
38
+
39
+ class ResourceUncertain(ResourceError):
40
+ pass
41
+
42
+
43
+ # Only fixed public machine labels may enter diagnostics/journals. Provider
44
+ # messages, locations, request data and unknown reason strings are never echoed.
45
+ SAFE_REASONS = frozenset({"manualSortRequired", "channelSectionNotFound",
46
+ "channelSectionForbidden", "channelNotFound", "idInvalid", "invalidCriteria",
47
+ "forbidden", "insufficientPermissions", "quotaExceeded", "notFound",
48
+ "playlistNotFound", "playlistItemNotFound", "videoNotFound", "invalidValue",
49
+ "commentsDisabled"})
50
+
51
+
52
+ def provider_reason(response, token):
53
+ try:
54
+ data = bytearray()
55
+ for chunk in response.iter_bytes(chunk_size=16385):
56
+ if len(data) + len(chunk) > 16384:
57
+ return None
58
+ data.extend(chunk)
59
+ error = json.loads(data).get("error")
60
+ if not isinstance(error, dict) or error.get("code", response.status_code) != response.status_code:
61
+ return None
62
+ errors = error.get("errors")
63
+ if not isinstance(errors, list) or len(errors) != 1 or not isinstance(errors[0], dict):
64
+ return None
65
+ reason = errors[0].get("reason")
66
+ return reason if isinstance(reason, str) and reason in SAFE_REASONS and reason != token else None
67
+ except Exception:
68
+ return None
69
+
70
+
71
+ def resource_id(value):
72
+ if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_=-]{1,512}", value):
73
+ raise ResourceError("Invalid YouTube ID; URLs and paths are not accepted")
74
+ return value
75
+
76
+
77
+ def thumbnail_snapshot(video):
78
+ """Complete state observed by the owned-video snippet read."""
79
+ return {"id": video.video_id, "channel_id": video.channel_id,
80
+ "etag": video.etag, "snippet": video.snippet}
81
+
82
+
83
+ def validate_thumbnail_snapshot(change, video):
84
+ current = thumbnail_snapshot(video)
85
+ approved = change.before.get("video_snapshot")
86
+ if approved is None:
87
+ matches = {"etag": video.etag, "thumbnails": video.snippet.get("thumbnails", {})} == change.before
88
+ else:
89
+ matches = (approved.get("id") == change.video_id
90
+ and approved.get("channel_id") == change.target_account
91
+ and approved.get("etag") == change.before.get("etag")
92
+ and approved.get("snippet", {}).get("thumbnails", {}) == change.before.get("thumbnails")
93
+ and same_metadata_snapshot(approved, current))
94
+ if not matches:
95
+ raise ResourceConflict("conflict: thumbnail or video changed since preview")
96
+ return video.etag
97
+
98
+
99
+ class _FixedOAuth:
100
+ def __init__(self, client):
101
+ self.client = client
102
+
103
+ def post(self, url, **kwargs):
104
+ if url != "https://oauth2.googleapis.com/token":
105
+ raise ResourceError("OAuth endpoint not allowed")
106
+ return self.client.post(url, follow_redirects=False, **kwargs)
107
+
108
+
109
+ class YouTubeResourcesClient(YouTubeManagementClient):
110
+ """Reuse exact authenticated-channel/video ownership, with redirect-safe reads."""
111
+
112
+ def __init__(self, brand, client):
113
+ super().__init__(brand, client)
114
+ self._access_token = None
115
+
116
+ @property
117
+ def configured_channel_id(self):
118
+ try:
119
+ return resource_id(super().configured_channel_id)
120
+ except YouTubeManagementError:
121
+ raise ResourceError("brand configuration lacks a valid YouTube channel") from None
122
+
123
+ def _authenticated_channel(self, token):
124
+ payload = self._json(self._request("GET", f"{API}/channels", params={"part": "id", "mine": "true"}))
125
+ items = payload.get("items")
126
+ if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
127
+ raise ResourceError("ambiguous identity: exactly one authenticated channel was not returned")
128
+ # channels.list is paginated. One item on this page is not evidence of
129
+ # one authenticated channel unless totalResults confirms it. The API
130
+ # reports resultsPerPage as capacity (observed: 5 for one result), not
131
+ # necessarily the number of returned items. Its documented maximum is 50.
132
+ # Token presence (including malformed/empty values) cannot be accepted
133
+ # as a complete first and only page; no pagination is needed to reject it.
134
+ page = payload.get("pageInfo")
135
+ if (any(key in payload for key in ("nextPageToken", "prevPageToken"))
136
+ or not isinstance(page, dict)
137
+ or type(page.get("totalResults")) is not int or page["totalResults"] != 1
138
+ or type(page.get("resultsPerPage")) is not int
139
+ or not len(items) <= page["resultsPerPage"] <= 50):
140
+ raise ResourceError("incomplete or ambiguous channel identity: requires totalResults=1 and valid resultsPerPage capacity (1–50)")
141
+ return resource_id(items[0].get("id"))
142
+
143
+ def _token(self):
144
+ # Pin the credential for this client so ownership and effects use one token.
145
+ if self._access_token is None:
146
+ try:
147
+ credential = self.brand.leer_secreto(Platform.YOUTUBE)
148
+ transport = self.client if credential.get("auth_mode") == "broker" else _FixedOAuth(self.client)
149
+ self._access_token = obtener_token(self.brand, Platform.YOUTUBE, transport)
150
+ except ReadDeadlineExceeded:
151
+ raise
152
+ except Exception as exc:
153
+ raise with_error_code(ResourceError("YouTube credentials unavailable; refresh unconfirmed"), exc, read_only=True, fallback="authorization_unavailable") from None
154
+ return self._access_token
155
+
156
+ def inspect(self, video_id):
157
+ try:
158
+ return super().inspect(resource_id(video_id))
159
+ except YouTubeManagementError as exc:
160
+ raise with_error_code(ResourceError(str(exc)), exc, read_only=True) from None
161
+
162
+ def _request(self, method, url, *, headers=None, max_response=4 * 1024 * 1024, **kwargs):
163
+ # All call sites use literal known endpoints; reject future accidental expansion.
164
+ parsed = httpx.URL(url)
165
+ if parsed.scheme != "https" or parsed.host != "www.googleapis.com" or parsed.port not in {None, 443} or parsed.userinfo or parsed.query or not self._endpoint_allowed(method, parsed.path):
166
+ raise ResourceError("YouTube host or endpoint not allowed")
167
+ writing = method != "GET"
168
+ try:
169
+ token = self._token()
170
+ except YouTubeManagementError as exc:
171
+ raise with_error_code(ResourceError("YouTube credentials unavailable"), exc, read_only=True) from None
172
+ try:
173
+ with self.client.stream(method, url,
174
+ headers={**(headers or {}), "Authorization": f"Bearer {token}", "Accept-Encoding": "identity"},
175
+ follow_redirects=False, **kwargs) as response:
176
+ if response.status_code == 412 and writing:
177
+ raise ResourceConflict("conflict: YouTube rejected If-Match (412)")
178
+ if not response.is_success:
179
+ error = ((ResourceUncertain if response.is_redirect or response.status_code >= 500
180
+ else ResourceRejected) if writing else ResourceError)
181
+ reason = provider_reason(response, token)
182
+ detail = f"; reason={reason}" if reason else ""
183
+ raise error(f"YouTube HTTP {response.status_code}{detail}; request not completed",
184
+ http_status=response.status_code, provider_reason=reason)
185
+ data = bytearray()
186
+ for chunk in response.iter_bytes():
187
+ if len(data) + len(chunk) > max_response:
188
+ raise (ResourceUncertain if writing else ResourceError)("YouTube response exceeds byte limit")
189
+ data.extend(chunk)
190
+ response_headers = {k: v for k, v in response.headers.items()
191
+ if k.lower() not in {"content-encoding", "content-length"}}
192
+ return httpx.Response(response.status_code, headers=response_headers,
193
+ content=bytes(data), request=response.request)
194
+ except ReadDeadlineExceeded:
195
+ if writing:
196
+ raise ResourceUncertain('YouTube: transport deadline exceeded; outcome unconfirmed') from None
197
+ raise
198
+ except ResourceError:
199
+ raise
200
+ except httpx.TransportError as exc:
201
+ raise with_error_code((ResourceUncertain if writing else ResourceError)(
202
+ f"YouTube: transport interrupted ({transport_label(exc)}); outcome unconfirmed"), exc, read_only=not writing) from None
203
+ except Exception as exc:
204
+ raise with_error_code((ResourceUncertain if writing else ResourceError)(
205
+ "YouTube: transport interrupted; outcome unconfirmed"), exc, read_only=not writing) from None
206
+
207
+ def _endpoint_allowed(self, method, path):
208
+ paths = {"/youtube/v3/channels", "/youtube/v3/videos", "/youtube/v3/captions",
209
+ "/upload/youtube/v3/captions", "/upload/youtube/v3/thumbnails/set"}
210
+ download = method == "GET" and re.fullmatch(r"/youtube/v3/captions/[A-Za-z0-9_=%-]+", path)
211
+ return path in paths or bool(download)
212
+
213
+ def _json(self, response, *, writing=False):
214
+ try:
215
+ payload = response.json()
216
+ if not isinstance(payload, dict) or "error" in payload:
217
+ raise ValueError()
218
+ return payload
219
+ except Exception:
220
+ raise (ResourceUncertain if writing else ResourceError)("YouTube: unverifiable response") from None
221
+
222
+ def _get_json(self, url, token, *, params, operation):
223
+ return self._json(self._request("GET", url, params=params))
224
+
225
+ def list_captions(self, video_id):
226
+ self.inspect(video_id)
227
+ payload = self._json(self._request("GET", f"{API}/captions",
228
+ params={"part": "snippet", "videoId": resource_id(video_id)}))
229
+ # captions.list documents no pagination parameters or continuation schema.
230
+ if payload.get("nextPageToken") or payload.get("next") or payload.get("pageInfo"):
231
+ raise ResourceError("incomplete list: pagination is undocumented for captions.list")
232
+ items = payload.get("items")
233
+ if not isinstance(items, list):
234
+ raise ResourceError("invalid captions list")
235
+ ids = set()
236
+ for item in items:
237
+ if not isinstance(item, dict):
238
+ raise ResourceError("invalid caption")
239
+ cid = resource_id(item.get("id"))
240
+ snippet = item.get("snippet")
241
+ if (cid in ids or not isinstance(snippet, dict) or snippet.get("videoId") != video_id
242
+ or not isinstance(item.get("etag"), str) or not item["etag"]
243
+ or type(snippet.get("isDraft")) is not bool
244
+ or not isinstance(snippet.get("language"), str) or not snippet["language"]
245
+ or not isinstance(snippet.get("name"), str)):
246
+ raise ResourceError("caption lacks verifiable identity, ownership, ETag or status")
247
+ ids.add(cid)
248
+ return items
249
+
250
+ def find_caption(self, video_id, track_id):
251
+ resource_id(track_id)
252
+ matches = [t for t in self.list_captions(video_id) if t["id"] == track_id]
253
+ if len(matches) != 1:
254
+ raise ResourceError("caption was not verified on owned video; absence or permissions inconclusive")
255
+ return matches[0]
256
+
257
+ def download_caption(self, video_id, track_id):
258
+ self.find_caption(video_id, track_id)
259
+ # No tfmt/tlang: keep exactly the API's original-format response bytes.
260
+ response = self._request("GET", f"{API}/captions/{quote(resource_id(track_id), safe='')}", max_response=MAX_CAPTION)
261
+ data = response.content
262
+ if not data or len(data) > MAX_CAPTION:
263
+ raise ResourceError("caption download is empty or exceeds 100MB")
264
+ return data
265
+
266
+ def mutate(self, change, data, *, validated_video=None):
267
+ """Exactly one request; caller has persisted intent before entering."""
268
+ headers = {"If-Match": change.before["etag"]}
269
+ if change.action == "thumbnail-set":
270
+ if validated_video is None:
271
+ raise ResourceConflict("thumbnail write requires validated owned-video state")
272
+ headers = {"If-Match": validate_thumbnail_snapshot(change, validated_video)}
273
+ response = self._request("POST", f"{UPLOAD}/thumbnails/set", headers={
274
+ **headers, "Content-Type": change.asset["mime"]},
275
+ params={"videoId": change.video_id, "uploadType": "media"}, content=data)
276
+ elif change.action == "caption-delete":
277
+ response = self._request("DELETE", f"{API}/captions", headers=headers,
278
+ params={"id": change.track_id})
279
+ if response.status_code != 204:
280
+ raise ResourceUncertain("captions.delete did not return 204; uncertain outcome")
281
+ return {"deleted_id": change.track_id, "http_status": 204}
282
+ else:
283
+ inserting = change.action == "caption-insert"
284
+ body = ({"snippet": {"videoId": change.video_id, "language": change.language,
285
+ "name": change.name, "isDraft": change.draft}} if inserting else {"id": change.track_id})
286
+ if not inserting and change.draft_changed:
287
+ body["snippet"] = {"isDraft": change.draft}
288
+ params = {"part": "snippet" if "snippet" in body else "id"}
289
+ if inserting:
290
+ # A video ETag is not a caption-insert precondition supported by the API.
291
+ headers = {}
292
+ if data is None:
293
+ response = self._request("PUT", f"{API}/captions", headers=headers, params=params, json=body)
294
+ else:
295
+ boundary = "socialctl_" + uuid.uuid4().hex
296
+ while boundary.encode() in data:
297
+ boundary = "socialctl_" + uuid.uuid4().hex
298
+ content = (f"--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n".encode()
299
+ + json.dumps(body, ensure_ascii=False).encode("utf-8")
300
+ + f"\r\n--{boundary}\r\nContent-Type: {change.asset['mime']}\r\n\r\n".encode()
301
+ + data + f"\r\n--{boundary}--\r\n".encode())
302
+ response = self._request("POST" if inserting else "PUT", f"{UPLOAD}/captions",
303
+ headers={**headers, "Content-Type": f"multipart/related; boundary={boundary}"},
304
+ params={**params, "uploadType": "multipart"}, content=content)
305
+ return self._json(response, writing=True)