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.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Bounded fixed-host community reads and one explicit effect, without retry."""
|
|
2
|
+
import json
|
|
3
|
+
from socialctl.agent_errors import error_document
|
|
4
|
+
import re
|
|
5
|
+
from socialctl.read_budget import ReadDeadlineExceeded
|
|
6
|
+
|
|
7
|
+
from socialctl.management.community_schema import opaque_id
|
|
8
|
+
from socialctl.management.youtube_resources import API, YouTubeResourcesClient, ResourceError, ResourceUncertain, resource_id
|
|
9
|
+
|
|
10
|
+
CATALOGS = {"languages": "i18nLanguages", "regions": "i18nRegions", "categories": "videoCategories", "abuse-reasons": "videoAbuseReportReasons"}
|
|
11
|
+
FILTERS = ("published", "heldForReview", "likelySpam")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def complete(report):
|
|
15
|
+
if not report["complete"]:
|
|
16
|
+
raise ResourceError("incomplete list: " + str(report.get("error")))
|
|
17
|
+
return report["items"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class YouTubeCommunityClient(YouTubeResourcesClient):
|
|
21
|
+
def _endpoint_allowed(self, method, path):
|
|
22
|
+
reads = {"channels", "videos", "commentThreads", "comments", "subscriptions", "activities", "search", "videos/getRating", *CATALOGS.values()}
|
|
23
|
+
writes = {("POST", "commentThreads"), ("POST", "comments"), ("PUT", "comments"), ("DELETE", "comments"),
|
|
24
|
+
("POST", "comments/setModerationStatus"), ("POST", "subscriptions"), ("DELETE", "subscriptions"),
|
|
25
|
+
("POST", "videos/rate"), ("POST", "videos/reportAbuse")}
|
|
26
|
+
return (method == "GET" and path in {"/youtube/v3/" + r for r in reads}) or any(
|
|
27
|
+
method == verb and path == "/youtube/v3/" + name for verb, name in writes)
|
|
28
|
+
|
|
29
|
+
def identity(self):
|
|
30
|
+
if self._authenticated_channel(self._token()) != self.configured_channel_id:
|
|
31
|
+
raise ResourceError("authenticated channel differs from configured brand")
|
|
32
|
+
return self.configured_channel_id
|
|
33
|
+
|
|
34
|
+
def _pages(self, resource, params, validate, *, max_pages=100, paginated=True):
|
|
35
|
+
from socialctl.management.changes import now_utc
|
|
36
|
+
if type(max_pages) is not int or not 1 <= max_pages <= 100:
|
|
37
|
+
raise ResourceError("max-pages must be between 1 and 100")
|
|
38
|
+
self.identity()
|
|
39
|
+
result = {"items": [], "complete": False, "pages": 0, "absence_proven": False, "error": None,
|
|
40
|
+
"observed_at": now_utc().isoformat(), "source": f"{API}/{resource}",
|
|
41
|
+
"scope": {"resource": resource, **params}, "limitation": "Complete only for this filter; does not prove global absence, write permissions or complete replies within threads."}
|
|
42
|
+
token, tokens, ids = None, set(), set()
|
|
43
|
+
expected_total = None
|
|
44
|
+
for _ in range(max_pages):
|
|
45
|
+
try:
|
|
46
|
+
query = dict(params)
|
|
47
|
+
if paginated:
|
|
48
|
+
query["maxResults"] = 50
|
|
49
|
+
if token is not None:
|
|
50
|
+
query["pageToken"] = token
|
|
51
|
+
payload = self._json(self._request("GET", f"{API}/{resource}", params=query))
|
|
52
|
+
if "items" not in payload and not (isinstance(payload.get("kind"), str) and isinstance(payload.get("etag"), str) and payload["etag"]):
|
|
53
|
+
raise ResourceError("empty unverifiable envelope")
|
|
54
|
+
rows = payload.get("items", [])
|
|
55
|
+
if not isinstance(rows, list) or len(rows) > (50 if paginated else 5000):
|
|
56
|
+
raise ResourceError("invalid items or limit exceeded")
|
|
57
|
+
accepted = []
|
|
58
|
+
for row in rows:
|
|
59
|
+
key = validate(row)
|
|
60
|
+
if key in ids:
|
|
61
|
+
raise ResourceError("duplicate ID during pagination")
|
|
62
|
+
ids.add(key)
|
|
63
|
+
accepted.append(row)
|
|
64
|
+
result["items"].extend(accepted)
|
|
65
|
+
result["pages"] += 1
|
|
66
|
+
next_token = payload.get("nextPageToken")
|
|
67
|
+
if "nextPageToken" in payload and (not isinstance(next_token, str) or not 0 < len(next_token) <= 2048 or next_token in tokens):
|
|
68
|
+
raise ResourceError("invalid or repeated pagination")
|
|
69
|
+
if not paginated and any(k in payload for k in ("nextPageToken", "prevPageToken")):
|
|
70
|
+
raise ResourceError("undocumented catalog pagination")
|
|
71
|
+
if not rows and next_token:
|
|
72
|
+
raise ResourceError("contradictory empty page")
|
|
73
|
+
if next_token is None and expected_total is not None and expected_total != len(result['items']):
|
|
74
|
+
raise ResourceError("total does not match received list; partial read")
|
|
75
|
+
if paginated:
|
|
76
|
+
page = payload.get("pageInfo")
|
|
77
|
+
if page is None:
|
|
78
|
+
raise ResourceError("pagination metadata missing; verified items retained")
|
|
79
|
+
if not isinstance(page, dict):
|
|
80
|
+
raise ResourceError("pagination lacks verifiable metadata")
|
|
81
|
+
# Missing fields permit supervised replies with verified
|
|
82
|
+
# rows. Invalid or contradictory supplied fields do not.
|
|
83
|
+
if ('totalResults' in page and (type(page['totalResults']) is not int or page['totalResults'] < 0 or (resource != 'search' and page['totalResults'] < len(result['items'])))) or ('resultsPerPage' in page and (type(page['resultsPerPage']) is not int or not len(rows) <= page['resultsPerPage'] <= 50)):
|
|
84
|
+
raise ResourceError("pagination lacks verifiable metadata")
|
|
85
|
+
if not rows and 'totalResults' in page and page['totalResults'] != 0:
|
|
86
|
+
raise ResourceError("contradictory empty page")
|
|
87
|
+
if resource != "search" and 'totalResults' in page: # Search documents approximate totals.
|
|
88
|
+
if expected_total is not None and page["totalResults"] != expected_total:
|
|
89
|
+
raise ResourceError("total changed during pagination")
|
|
90
|
+
expected_total = page["totalResults"]
|
|
91
|
+
if next_token is None and expected_total is not None and expected_total != len(result['items']):
|
|
92
|
+
raise ResourceError("total does not match received list; partial read")
|
|
93
|
+
# Live comments.list envelopes may omit totalResults. The
|
|
94
|
+
# cursor still drives traversal; retain every supplied-total
|
|
95
|
+
# consistency check and require the typed provider envelope.
|
|
96
|
+
optional_comment_total = (
|
|
97
|
+
resource == 'comments' and 'resultsPerPage' in page
|
|
98
|
+
and payload.get('kind') == 'youtube#commentListResponse'
|
|
99
|
+
and isinstance(payload.get('etag'), str) and bool(payload['etag']))
|
|
100
|
+
required = {'resultsPerPage'} if optional_comment_total else {'totalResults', 'resultsPerPage'}
|
|
101
|
+
if required - page.keys():
|
|
102
|
+
raise ResourceError("pagination metadata missing; verified items retained")
|
|
103
|
+
if next_token is None:
|
|
104
|
+
if expected_total is not None and expected_total != len(result["items"]):
|
|
105
|
+
raise ResourceError("total does not match received list; partial read")
|
|
106
|
+
result["complete"] = True
|
|
107
|
+
break
|
|
108
|
+
tokens.add(next_token)
|
|
109
|
+
token = next_token
|
|
110
|
+
except KeyboardInterrupt:
|
|
111
|
+
result["error"] = "Read interrupted; verified items retained"
|
|
112
|
+
result["interrupted"] = True
|
|
113
|
+
break
|
|
114
|
+
except ReadDeadlineExceeded as exc:
|
|
115
|
+
result['error'] = str(exc)
|
|
116
|
+
result['timed_out'] = True
|
|
117
|
+
break
|
|
118
|
+
except ResourceError as exc:
|
|
119
|
+
result["error"] = str(exc)
|
|
120
|
+
result["error_detail"] = error_document(exc, read_only=True)
|
|
121
|
+
break
|
|
122
|
+
if not result["complete"] and result["error"] is None:
|
|
123
|
+
result["error"] = "page limit reached"
|
|
124
|
+
if not result["complete"] and token and result["error"] == "page limit reached":
|
|
125
|
+
result["cursor"] = token
|
|
126
|
+
return result
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def _row(row, kind=None):
|
|
130
|
+
if not isinstance(row, dict) or not isinstance(row.get("snippet"), dict):
|
|
131
|
+
raise ResourceError("resource lacks snippet")
|
|
132
|
+
if kind and row.get("kind", kind) != kind:
|
|
133
|
+
raise ResourceError("unexpected resource type")
|
|
134
|
+
return opaque_id(row.get("id"))
|
|
135
|
+
|
|
136
|
+
def _comment(self, row, *, parent=None):
|
|
137
|
+
cid = self._row(row, "youtube#comment")
|
|
138
|
+
snip = row["snippet"]
|
|
139
|
+
if not isinstance(row.get("etag"), str) or not row["etag"]:
|
|
140
|
+
raise ResourceError("comment lacks ETag")
|
|
141
|
+
if snip.get("parentId") != parent or ("channelId" in snip and snip["channelId"] != self.configured_channel_id):
|
|
142
|
+
raise ResourceError("comment belongs to another parent/channel")
|
|
143
|
+
author = snip.get("authorChannelId")
|
|
144
|
+
if author is not None and (not isinstance(author, dict) or not isinstance(author.get("value"), str)):
|
|
145
|
+
raise ResourceError("invalid comment author")
|
|
146
|
+
return cid
|
|
147
|
+
|
|
148
|
+
def _thread(self, row, video_id):
|
|
149
|
+
tid = self._row(row, "youtube#commentThread")
|
|
150
|
+
snip = row["snippet"]
|
|
151
|
+
if snip.get("videoId") != video_id or snip.get("channelId") != self.configured_channel_id:
|
|
152
|
+
raise ResourceError("thread belongs to another video/channel")
|
|
153
|
+
self._comment(snip.get("topLevelComment"))
|
|
154
|
+
return tid
|
|
155
|
+
|
|
156
|
+
def list_threads(self, video_id, *, moderation_status="published", max_pages=100):
|
|
157
|
+
self.inspect(resource_id(video_id))
|
|
158
|
+
if moderation_status not in FILTERS:
|
|
159
|
+
raise ResourceError("undocumented moderation filter")
|
|
160
|
+
return self._pages("commentThreads", {"part": "snippet", "videoId": video_id,
|
|
161
|
+
"moderationStatus": moderation_status, "textFormat": "plainText"},
|
|
162
|
+
lambda row: self._thread(row, video_id), max_pages=max_pages)
|
|
163
|
+
|
|
164
|
+
def thread(self, video_id, thread_id):
|
|
165
|
+
self.inspect(resource_id(video_id))
|
|
166
|
+
payload = self._json(self._request("GET", f"{API}/commentThreads", params={"part": "snippet", "id": opaque_id(thread_id), "textFormat": "plainText"}))
|
|
167
|
+
rows = payload.get("items")
|
|
168
|
+
if not isinstance(rows, list) or len(rows) != 1 or any(k in payload for k in ("nextPageToken", "prevPageToken")):
|
|
169
|
+
raise ResourceError("thread unverifiable by ID; absence/permissions inconclusive")
|
|
170
|
+
self._exact_total(payload)
|
|
171
|
+
if self._thread(rows[0], video_id) != thread_id:
|
|
172
|
+
raise ResourceError("thread ID mismatch")
|
|
173
|
+
return rows[0]
|
|
174
|
+
|
|
175
|
+
def list_replies(self, video_id, thread_id, parent_id, *, max_pages=100):
|
|
176
|
+
thread = self.thread(video_id, thread_id)
|
|
177
|
+
if thread["snippet"]["topLevelComment"]["id"] != opaque_id(parent_id):
|
|
178
|
+
raise ResourceError("parent_id is not thread's top-level comment")
|
|
179
|
+
return self._pages("comments", {"part": "snippet", "parentId": parent_id, "textFormat": "plainText"},
|
|
180
|
+
lambda row: self._comment(row, parent=parent_id), max_pages=max_pages)
|
|
181
|
+
|
|
182
|
+
def find_comment(self, video_id, thread_id, comment_id, parent_id=None, *, moderation=False, cache=None, allow_partial=False):
|
|
183
|
+
opaque_id(comment_id)
|
|
184
|
+
cache = {} if cache is None else cache
|
|
185
|
+
if parent_id is not None:
|
|
186
|
+
key = (video_id, thread_id, parent_id)
|
|
187
|
+
if key not in cache:
|
|
188
|
+
report = self.list_replies(video_id, thread_id, parent_id)
|
|
189
|
+
if not report['complete'] and not (allow_partial and str(report.get('error', '')).startswith('pagination metadata missing')):
|
|
190
|
+
complete(report)
|
|
191
|
+
cache[key] = report['items']
|
|
192
|
+
rows = cache[key]
|
|
193
|
+
elif moderation:
|
|
194
|
+
rows = []
|
|
195
|
+
for state in FILTERS:
|
|
196
|
+
key = (video_id, state)
|
|
197
|
+
if key not in cache:
|
|
198
|
+
cache[key] = complete(self.list_threads(video_id, moderation_status=state))
|
|
199
|
+
for thread in cache[key]:
|
|
200
|
+
if thread["id"] == thread_id:
|
|
201
|
+
rows.append(thread["snippet"]["topLevelComment"])
|
|
202
|
+
# Threads with held replies can also appear in published; same top is
|
|
203
|
+
# allowed only if the returned resource itself agrees exactly.
|
|
204
|
+
rows = list({json.dumps(r, sort_keys=True): r for r in rows}.values())
|
|
205
|
+
else:
|
|
206
|
+
rows = [self.thread(video_id, thread_id)["snippet"]["topLevelComment"]]
|
|
207
|
+
found = [r for r in rows if r["id"] == comment_id]
|
|
208
|
+
if len(found) != 1:
|
|
209
|
+
raise ResourceError("comment unverifiable in thread/parent; absence/permissions inconclusive")
|
|
210
|
+
return found[0]
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def _exact_total(payload):
|
|
214
|
+
page = payload.get("pageInfo")
|
|
215
|
+
if page is not None and (not isinstance(page, dict) or type(page.get("totalResults")) is not int or page["totalResults"] != 1):
|
|
216
|
+
raise ResourceError("ID response has ambiguous total")
|
|
217
|
+
|
|
218
|
+
def external(self, resource, rid):
|
|
219
|
+
if resource not in {"videos", "channels"}:
|
|
220
|
+
raise ResourceError("unsupported external target")
|
|
221
|
+
self.identity()
|
|
222
|
+
payload = self._json(self._request("GET", f"{API}/{resource}", params={"part": "snippet", "id": resource_id(rid)}))
|
|
223
|
+
rows = payload.get("items")
|
|
224
|
+
if not isinstance(rows, list) or len(rows) != 1 or any(k in payload for k in ("nextPageToken", "prevPageToken")):
|
|
225
|
+
raise ResourceError("external target unverifiable")
|
|
226
|
+
self._exact_total(payload)
|
|
227
|
+
if self._row(rows[0]) != rid:
|
|
228
|
+
raise ResourceError("external target ID mismatch")
|
|
229
|
+
return rows[0]
|
|
230
|
+
|
|
231
|
+
def _subscription(self, row):
|
|
232
|
+
rid = self._row(row, "youtube#subscription")
|
|
233
|
+
snip = row["snippet"]
|
|
234
|
+
target = snip.get("resourceId")
|
|
235
|
+
if snip.get("channelId") != self.configured_channel_id or not isinstance(target, dict) or target.get("kind") != "youtube#channel":
|
|
236
|
+
raise ResourceError("subscription belongs to another actor or invalid target")
|
|
237
|
+
resource_id(target.get("channelId"))
|
|
238
|
+
return rid
|
|
239
|
+
|
|
240
|
+
def list_subscriptions(self, *, max_pages=100):
|
|
241
|
+
return self._pages("subscriptions", {"part": "snippet", "mine": "true"}, self._subscription, max_pages=max_pages)
|
|
242
|
+
|
|
243
|
+
def get_rating(self, video_id):
|
|
244
|
+
self.external("videos", video_id)
|
|
245
|
+
payload = self._json(self._request("GET", f"{API}/videos/getRating", params={"id": video_id}))
|
|
246
|
+
rows = payload.get("items")
|
|
247
|
+
if (not isinstance(rows, list) or len(rows) != 1 or not isinstance(rows[0], dict)
|
|
248
|
+
or rows[0].get("videoId") != video_id or rows[0].get("rating") not in {"like", "dislike", "none", "unspecified"}
|
|
249
|
+
or any(k in payload for k in ("nextPageToken", "prevPageToken"))):
|
|
250
|
+
raise ResourceError("rating unverifiable for exact ID")
|
|
251
|
+
return rows[0]
|
|
252
|
+
|
|
253
|
+
def catalog(self, name, *, language="en", region=None):
|
|
254
|
+
if name not in CATALOGS or not isinstance(language, str) or not re.fullmatch(r"[A-Za-z_0-9-]{1,35}", language):
|
|
255
|
+
raise ResourceError("unsupported catalog/language")
|
|
256
|
+
params = {"part": "snippet", "hl": language}
|
|
257
|
+
if name == "categories":
|
|
258
|
+
if not isinstance(region, str) or not re.fullmatch(r"[A-Z]{2}", region):
|
|
259
|
+
raise ResourceError("categories requires explicit ISO region")
|
|
260
|
+
params["regionCode"] = region
|
|
261
|
+
elif region is not None:
|
|
262
|
+
raise ResourceError("region accepted only for categories")
|
|
263
|
+
return self._pages(CATALOGS[name], params, self._row, paginated=False)
|
|
264
|
+
|
|
265
|
+
def search(self, query, *, kind="video", order="relevance", channel_id=None, max_pages=100):
|
|
266
|
+
if not isinstance(query, str) or not 0 < len(query.strip()) <= 1000 or kind not in {"video", "channel", "playlist"} or order not in {"date", "rating", "relevance", "title", "videoCount", "viewCount"}:
|
|
267
|
+
raise ResourceError("invalid search query/type/order")
|
|
268
|
+
params = {"part": "snippet", "q": query, "type": kind, "order": order}
|
|
269
|
+
if channel_id is not None:
|
|
270
|
+
params["channelId"] = resource_id(channel_id)
|
|
271
|
+
def validate(row):
|
|
272
|
+
if not isinstance(row, dict) or not isinstance(row.get("id"), dict) or not isinstance(row.get("snippet"), dict):
|
|
273
|
+
raise ResourceError("invalid search result")
|
|
274
|
+
rid = row["id"]
|
|
275
|
+
if rid.get("kind") != "youtube#" + kind:
|
|
276
|
+
raise ResourceError("unexpected search result type")
|
|
277
|
+
if channel_id is not None and row["snippet"].get("channelId") != channel_id:
|
|
278
|
+
raise ResourceError("search returned another channel")
|
|
279
|
+
return resource_id(rid.get(kind + "Id"))
|
|
280
|
+
return self._pages("search", params, validate, max_pages=max_pages)
|
|
281
|
+
|
|
282
|
+
def activities(self, *, published_after=None, published_before=None, max_pages=100):
|
|
283
|
+
from datetime import datetime
|
|
284
|
+
params = {"part": "snippet,contentDetails", "channelId": self.configured_channel_id}
|
|
285
|
+
for key, value in (("publishedAfter", published_after), ("publishedBefore", published_before)):
|
|
286
|
+
if value is not None:
|
|
287
|
+
try:
|
|
288
|
+
stamp = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
289
|
+
if stamp.tzinfo is None:
|
|
290
|
+
raise ValueError()
|
|
291
|
+
except (ValueError, AttributeError):
|
|
292
|
+
raise ResourceError("activities timestamp requires RFC3339 with timezone") from None
|
|
293
|
+
params[key] = value
|
|
294
|
+
def validate(row):
|
|
295
|
+
rid = self._row(row, "youtube#activity")
|
|
296
|
+
if row["snippet"].get("channelId") != self.configured_channel_id:
|
|
297
|
+
raise ResourceError("activity from another channel")
|
|
298
|
+
return rid
|
|
299
|
+
return self._pages("activities", params, validate, max_pages=max_pages)
|
|
300
|
+
|
|
301
|
+
def effect(self, edit, body, before):
|
|
302
|
+
action = edit.action
|
|
303
|
+
headers = {}
|
|
304
|
+
if action in {"edit", "delete"}:
|
|
305
|
+
headers["If-Match"] = before["comment"]["etag"]
|
|
306
|
+
if action in {"add", "reply", "edit", "subscribe"}:
|
|
307
|
+
name = {"add": "commentThreads", "subscribe": "subscriptions"}.get(action, "comments")
|
|
308
|
+
response = self._request("PUT" if action == "edit" else "POST", f"{API}/{name}",
|
|
309
|
+
params={"part": "snippet"}, headers=headers, json=body)
|
|
310
|
+
return self._json(response, writing=True)
|
|
311
|
+
if action in {"delete", "unsubscribe"}:
|
|
312
|
+
name = "comments" if action == "delete" else "subscriptions"
|
|
313
|
+
response = self._request("DELETE", f"{API}/{name}", params={"id": edit.comment_id if action == "delete" else edit.subscription_id}, headers=headers)
|
|
314
|
+
elif action == "moderate":
|
|
315
|
+
response = self._request("POST", f"{API}/comments/setModerationStatus", params={
|
|
316
|
+
"id": ",".join(t.comment_id for t in edit.targets), "moderationStatus": edit.moderation_status,
|
|
317
|
+
**({"banAuthor": "true"} if edit.ban_author else {})})
|
|
318
|
+
elif action == "rate":
|
|
319
|
+
response = self._request("POST", f"{API}/videos/rate", params={"id": edit.video_id, "rating": edit.rating})
|
|
320
|
+
elif action == "report-abuse":
|
|
321
|
+
response = self._request("POST", f"{API}/videos/reportAbuse", json=body)
|
|
322
|
+
else:
|
|
323
|
+
raise ResourceError("unsupported community action")
|
|
324
|
+
if response.status_code != 204:
|
|
325
|
+
raise ResourceUncertain("bodyless method did not return 204; uncertain outcome")
|
|
326
|
+
return {"http_status": 204}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Owned video metadata parts over documented Data API v3 GET/PUT endpoints."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import copy
|
|
6
|
+
import re
|
|
7
|
+
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
|
|
8
|
+
from typing import Any, Callable
|
|
9
|
+
|
|
10
|
+
from socialctl.management.changes import ChangeError, _validate_snippet
|
|
11
|
+
from socialctl.management.metadata_parts import STATUS_FIELDS, STATUS_READ_ONLY, editable_parts, validate_localizations, validate_status
|
|
12
|
+
from socialctl.management.youtube import (READ_ONLY_SNIPPET_FIELDS, VIDEOS_URL,
|
|
13
|
+
WRITABLE_SNIPPET_FIELDS, YouTubeManagementClient, YouTubeManagementError, YouTubeUpdateConflict, YouTubeUpdateRejected)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class MetadataVideo:
|
|
18
|
+
video_id: str
|
|
19
|
+
channel_id: str
|
|
20
|
+
etag: str
|
|
21
|
+
resource: dict[str, Any]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def same_metadata_snapshot(before, after, *, allow_etag_only=False):
|
|
25
|
+
"""Compare every returned field, normalizing signed thumbnails and opt-in ETags."""
|
|
26
|
+
if before == after:
|
|
27
|
+
return True
|
|
28
|
+
left, right = copy.deepcopy(before), copy.deepcopy(after)
|
|
29
|
+
changed = False
|
|
30
|
+
for value in (left, right):
|
|
31
|
+
thumbnails = value.get('snippet', {}).get('thumbnails', {})
|
|
32
|
+
if not isinstance(thumbnails, dict):
|
|
33
|
+
return False
|
|
34
|
+
for thumbnail in thumbnails.values():
|
|
35
|
+
if not isinstance(thumbnail, dict) or not isinstance(thumbnail.get('url'), str):
|
|
36
|
+
return False
|
|
37
|
+
parts = urlsplit(thumbnail['url'])
|
|
38
|
+
if parts.scheme != 'https' or not re.fullmatch(r'i\d+\.ytimg\.com', parts.netloc):
|
|
39
|
+
continue
|
|
40
|
+
query = parse_qsl(parts.query, keep_blank_values=True)
|
|
41
|
+
if {'sqp', 'rs'} <= {k for k, _ in query}:
|
|
42
|
+
thumbnail['url'] = urlunsplit(parts._replace(query=urlencode([(k,v) for k,v in query if k not in {'sqp','rs'}])))
|
|
43
|
+
changed = before.get('snippet', {}).get('thumbnails') != after.get('snippet', {}).get('thumbnails')
|
|
44
|
+
if not changed and not allow_etag_only:
|
|
45
|
+
return False # Other caller contracts retain strict ETag-only conflicts.
|
|
46
|
+
left.pop('etag', None)
|
|
47
|
+
right.pop('etag', None)
|
|
48
|
+
return left == right
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class YouTubeMetadataClient(YouTubeManagementClient):
|
|
52
|
+
def inspect(self, video_id: str) -> MetadataVideo:
|
|
53
|
+
configured = self.configured_channel_id
|
|
54
|
+
token = self._token()
|
|
55
|
+
if self._authenticated_channel(token) != configured:
|
|
56
|
+
raise YouTubeManagementError("authenticated channel does not match brand")
|
|
57
|
+
payload = self._get_json(VIDEOS_URL, token,
|
|
58
|
+
params={"part": "snippet,status,localizations,contentDetails", "id": video_id}, operation="read metadata")
|
|
59
|
+
items = payload.get("items")
|
|
60
|
+
if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
|
|
61
|
+
raise YouTubeManagementError("YouTube did not return a unique verifiable video")
|
|
62
|
+
resource = items[0]
|
|
63
|
+
if resource.get("id") != video_id or not isinstance(resource.get("etag"), str) or not resource["etag"]:
|
|
64
|
+
raise YouTubeManagementError("unexpected video or ETag")
|
|
65
|
+
snippet, status = resource.get("snippet"), resource.get("status")
|
|
66
|
+
if not isinstance(snippet, dict) or not isinstance(status, dict):
|
|
67
|
+
raise YouTubeManagementError("snippet/status missing or invalid")
|
|
68
|
+
if snippet.get("channelId") != configured:
|
|
69
|
+
raise YouTubeManagementError("video does not belong to configured channel")
|
|
70
|
+
if set(snippet) - WRITABLE_SNIPPET_FIELDS - READ_ONLY_SNIPPET_FIELDS:
|
|
71
|
+
raise YouTubeManagementError("snippet contains unknown field; editing blocked")
|
|
72
|
+
if set(status) - STATUS_FIELDS - STATUS_READ_ONLY:
|
|
73
|
+
raise YouTubeManagementError("status contains unknown field; editing blocked")
|
|
74
|
+
validate_localizations(resource.get("localizations", {}))
|
|
75
|
+
validate_status({key: value for key, value in status.items() if key in STATUS_FIELDS})
|
|
76
|
+
return MetadataVideo(video_id, configured, resource["etag"], resource)
|
|
77
|
+
|
|
78
|
+
def update_parts(
|
|
79
|
+
self, video_id: str, parts: dict[str, Any], *, etag: str,
|
|
80
|
+
expected_resource: dict[str, Any] | None = None,
|
|
81
|
+
before_write: Callable[[str], None] | None = None,
|
|
82
|
+
) -> None:
|
|
83
|
+
if not parts or set(parts) - {"snippet", "status", "localizations"}:
|
|
84
|
+
raise YouTubeUpdateRejected("unknown mutable part")
|
|
85
|
+
current = self.inspect(video_id)
|
|
86
|
+
if expected_resource is not None:
|
|
87
|
+
if (expected_resource.get("id") != video_id
|
|
88
|
+
or expected_resource.get("etag") != etag
|
|
89
|
+
or not same_metadata_snapshot(expected_resource, current.resource, allow_etag_only=True)):
|
|
90
|
+
raise YouTubeUpdateConflict("Observed metadata changed before PUT; no write performed")
|
|
91
|
+
elif current.etag != etag:
|
|
92
|
+
raise YouTubeUpdateConflict("ETag changed before PUT; no write performed")
|
|
93
|
+
current_parts = editable_parts(current.resource)
|
|
94
|
+
try:
|
|
95
|
+
for part, value in parts.items():
|
|
96
|
+
if not isinstance(value, dict):
|
|
97
|
+
raise ChangeError("invalid part")
|
|
98
|
+
if set(current_parts[part]) - set(value):
|
|
99
|
+
raise ChangeError("present mutable fields cannot be omitted; complete part required")
|
|
100
|
+
if part == "snippet":
|
|
101
|
+
if set(value) - WRITABLE_SNIPPET_FIELDS:
|
|
102
|
+
raise ChangeError("snippet contains unknown or read-only field")
|
|
103
|
+
_validate_snippet(value)
|
|
104
|
+
current_audio = current.resource["snippet"].get("defaultAudioLanguage")
|
|
105
|
+
if value.get("defaultAudioLanguage") != current_audio:
|
|
106
|
+
raise ChangeError("defaultAudioLanguage is preserved only; editing unverified")
|
|
107
|
+
elif part == "status":
|
|
108
|
+
validate_status(value, outgoing=True)
|
|
109
|
+
else:
|
|
110
|
+
validate_localizations(value)
|
|
111
|
+
except ChangeError as exc:
|
|
112
|
+
raise YouTubeUpdateRejected(str(exc)) from None
|
|
113
|
+
def validate_before_put():
|
|
114
|
+
try:
|
|
115
|
+
if "status" in parts:
|
|
116
|
+
validate_status(parts["status"], outgoing=True)
|
|
117
|
+
except ChangeError as exc:
|
|
118
|
+
raise YouTubeUpdateRejected(str(exc)) from None
|
|
119
|
+
|
|
120
|
+
if before_write is not None:
|
|
121
|
+
before_write(current.etag)
|
|
122
|
+
self._update_parts(video_id, parts, etag=current.etag, before_put=validate_before_put)
|