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,470 @@
|
|
|
1
|
+
"""Durable, exact approval and read-only recovery for owned YouTube resources."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import copy
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import uuid
|
|
9
|
+
from contextlib import ExitStack
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Literal
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
15
|
+
|
|
16
|
+
from socialctl.management.changes import ApprovalMismatch, now_utc
|
|
17
|
+
from socialctl.management.resource_changes import ResourceStore, digest, _event
|
|
18
|
+
from socialctl.management.owned_schema import build_after, edit_raw, editable, owned_resource_id, mapping, merge, validate_edit, target
|
|
19
|
+
from socialctl.management.owned_assets import inspect_owned_asset, banner_url
|
|
20
|
+
from socialctl.management.youtube_resources import ResourceError, ResourceConflict, ResourceRejected, ResourceUncertain, resource_id
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class OwnedChange(BaseModel):
|
|
24
|
+
model_config = ConfigDict(extra="forbid")
|
|
25
|
+
version: Literal[1] = 1
|
|
26
|
+
kind: Literal["youtube-owned-resource"] = "youtube-owned-resource"
|
|
27
|
+
id: str
|
|
28
|
+
target_brand: str
|
|
29
|
+
target_account: str
|
|
30
|
+
edit: dict
|
|
31
|
+
resource: Literal["playlists", "playlistItems", "channelSections", "channels", "playlistImages", "videos"]
|
|
32
|
+
target_id: str | None = None
|
|
33
|
+
before: dict
|
|
34
|
+
after: dict
|
|
35
|
+
asset: dict | None = None
|
|
36
|
+
effects: list[str]
|
|
37
|
+
plan: list[dict] = Field(default_factory=list)
|
|
38
|
+
fingerprint: str = ""
|
|
39
|
+
created_at: datetime
|
|
40
|
+
updated_at: datetime
|
|
41
|
+
status: Literal["proposed", "applying", "uncertain", "failed", "conflict", "partial", "verified", "accepted_unverifiable"] = "proposed"
|
|
42
|
+
verified: bool = False
|
|
43
|
+
result_id: str | None = None
|
|
44
|
+
receipt: dict | None = None
|
|
45
|
+
steps: list[dict] = Field(default_factory=list)
|
|
46
|
+
journal: list[dict] = Field(default_factory=list)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def fingerprint(change):
|
|
50
|
+
raw = change.model_dump(mode="json")
|
|
51
|
+
return digest(json.dumps({k: v for k, v in raw.items() if k not in {
|
|
52
|
+
"fingerprint", "updated_at", "status", "verified", "result_id", "receipt", "steps", "journal"}},
|
|
53
|
+
sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class OwnedStore(ResourceStore):
|
|
57
|
+
model_type = OwnedChange
|
|
58
|
+
fingerprint_for = staticmethod(fingerprint)
|
|
59
|
+
|
|
60
|
+
def __init__(self, brand_root):
|
|
61
|
+
self.root = Path(brand_root) / ".socialctl" / "youtube-owned"
|
|
62
|
+
|
|
63
|
+
def completed_history(self, change_id):
|
|
64
|
+
"""A verified retention tombstone has no unresolved owned-resource write.
|
|
65
|
+
|
|
66
|
+
This is only a replay-scan predicate, never a way to load/apply an
|
|
67
|
+
expired proposal. Unknown/partial outcomes still fail closed in load().
|
|
68
|
+
"""
|
|
69
|
+
try:
|
|
70
|
+
raw = json.loads(self.path_for(change_id).read_text(encoding='utf-8'))
|
|
71
|
+
if not isinstance(raw, dict) or set(raw) != {
|
|
72
|
+
'data_lifecycle', 'replay_blocked', 'id', 'platform',
|
|
73
|
+
'prior_state', 'fingerprint', 'user_input',
|
|
74
|
+
}:
|
|
75
|
+
return False
|
|
76
|
+
if (raw['data_lifecycle'] != 'purged' or raw['replay_blocked'] is not True
|
|
77
|
+
or raw['id'] != change_id or raw['platform'] != 'youtube'
|
|
78
|
+
or raw['prior_state'] != 'verified'
|
|
79
|
+
or not isinstance(raw['fingerprint'], str)
|
|
80
|
+
or not re.fullmatch(r'[0-9a-f]{64}', raw['fingerprint'])
|
|
81
|
+
or not isinstance(raw['user_input'], dict)
|
|
82
|
+
or set(raw['user_input']) != {'edit'}):
|
|
83
|
+
return False
|
|
84
|
+
validate_edit(raw['user_input']['edit'])
|
|
85
|
+
return True
|
|
86
|
+
except (OSError, ValueError, TypeError):
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def complete(report):
|
|
91
|
+
if not report["complete"]:
|
|
92
|
+
raise ResourceError("incomplete list; cannot prepare/apply: " + str(report.get("error")))
|
|
93
|
+
return report["items"]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def ordered(rows):
|
|
97
|
+
rows = sorted(copy.deepcopy(rows), key=lambda r: r["snippet"]["position"])
|
|
98
|
+
if [r["snippet"]["position"] for r in rows] != list(range(len(rows))):
|
|
99
|
+
raise ResourceError("incomplete list: noncontiguous or duplicate positions")
|
|
100
|
+
return rows
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def baseline(client, edit):
|
|
104
|
+
resource, rid = target(edit)
|
|
105
|
+
if resource == "channels":
|
|
106
|
+
row = client.inspect_channel(rid)
|
|
107
|
+
elif resource == "videos":
|
|
108
|
+
row = client.inspect_video(rid)
|
|
109
|
+
elif rid:
|
|
110
|
+
row = client.one(resource, rid, parent=edit.playlist_id)
|
|
111
|
+
elif resource in {"playlistItems", "playlistImages"}:
|
|
112
|
+
row = client.one("playlists", edit.playlist_id)
|
|
113
|
+
else:
|
|
114
|
+
row = client.inspect_channel(client.configured_channel_id)
|
|
115
|
+
before = {"resource": row}
|
|
116
|
+
if edit.action.startswith("watermark-"):
|
|
117
|
+
before["watermark_state"] = {"known": False, "reason": "no_public_read_method"}
|
|
118
|
+
if resource == "playlistItems":
|
|
119
|
+
before["parent"] = client.one("playlists", edit.playlist_id)
|
|
120
|
+
if edit.action in {"item-insert", "items-reorder"} or (edit.action == "item-update" and "snippet" in edit.patch):
|
|
121
|
+
before["collection"] = ordered(complete(client.list_items(edit.playlist_id)))
|
|
122
|
+
if edit.action == "item-insert":
|
|
123
|
+
if any(r["snippet"]["resourceId"]["videoId"] == edit.video_id for r in before["collection"]):
|
|
124
|
+
raise ResourceConflict("membership with this videoId already exists; no title-based deduplication")
|
|
125
|
+
if edit.position > len(before["collection"]):
|
|
126
|
+
raise ResourceError("insertion position outside list")
|
|
127
|
+
if resource == "playlistImages":
|
|
128
|
+
before["parent"] = client.one("playlists", edit.playlist_id)
|
|
129
|
+
before["collection"] = complete(client.list_images(edit.playlist_id))
|
|
130
|
+
if edit.action == "image-insert" and any(r["snippet"]["type"] == edit.image_type for r in before["collection"]):
|
|
131
|
+
raise ResourceConflict("image with this type already exists; explicit image-update required")
|
|
132
|
+
if edit.action == "playlist-create":
|
|
133
|
+
before["collection"] = complete(client.list_playlists())
|
|
134
|
+
if edit.action == "playlist-update" and isinstance(edit.patch.get("status"), dict) and edit.patch["status"].get("podcastStatus") == "enabled":
|
|
135
|
+
before["image_eligibility"] = complete(client.list_images(edit.playlist_id))
|
|
136
|
+
if not before["image_eligibility"]:
|
|
137
|
+
raise ResourceError("podcastStatus=enabled requires existing image; not created automatically")
|
|
138
|
+
if edit.action == "section-create":
|
|
139
|
+
before["collection"] = complete(client.list_sections())
|
|
140
|
+
if len(before["collection"]) >= 10:
|
|
141
|
+
raise ResourceError("documented maximum of 10 sections")
|
|
142
|
+
return before
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def effects_for(edit):
|
|
146
|
+
notes = ["Approval covers only displayed brand/account, IDs and complete values; effective permissions/eligibility depend on provider."]
|
|
147
|
+
if edit.action.endswith("-delete"):
|
|
148
|
+
notes.append("Irreversible deletion of exact ID; snapshot is evidence, not a restorable backup or automatic restoration.")
|
|
149
|
+
if edit.action in {"playlist-delete", "item-delete"}:
|
|
150
|
+
notes.append("Deleting playlist/membership does not delete underlying videos.")
|
|
151
|
+
if edit.action in {"item-insert", "items-reorder", "item-update"}:
|
|
152
|
+
notes.append("playlistItemId, playlistId and videoId are distinct IDs; position changes shift other memberships. ManualSortRequired requires explicit external adjustment; never changed automatically.")
|
|
153
|
+
if edit.action == "item-update":
|
|
154
|
+
notes.append("Deprecated startAt/endAt are forwarded only if already present when preserving contentDetails; YouTube ignores them. Editing disabled; restoration or retention not promised.")
|
|
155
|
+
if edit.action == "items-reorder":
|
|
156
|
+
notes.append("Multi-item ordering is NOT atomic: durable partial results per item; reconcile only rereads and never continues writes.")
|
|
157
|
+
if edit.action == "channel-audience":
|
|
158
|
+
notes.append("Explicit selfDeclaredMadeForKids audience declaration; not inferred. Documentation mismatch or status rejection preserved without claiming success.")
|
|
159
|
+
if edit.action.startswith("image-"):
|
|
160
|
+
notes.append("playlistImage does not document ETag: preflight value/owner checks with remote read-write race; no conditional guarantee. Playlist ETag is never used as image ETag.")
|
|
161
|
+
if edit.file:
|
|
162
|
+
notes.append("Exact supplied bytes without generation/conversion. Local container/dimension validation; provider validates processing. Metadata readback does not prove visual or byte equality.")
|
|
163
|
+
if edit.action == "image-update" and edit.file:
|
|
164
|
+
notes.append("Media update: supplied square JPEG/PNG up to 52428800 bytes (50MiB), Discovery limit. Image insert retains documented 2MiB limit.")
|
|
165
|
+
if edit.action == "banner-upload":
|
|
166
|
+
notes.append("Only uploads banner and durably stores URL; does not apply branding. banner-apply prepares separate exact approval for that URL.")
|
|
167
|
+
if edit.action == "banner-apply":
|
|
168
|
+
notes.append("Applies durable upload receipt URL via separate channels.update; does not change channel title.")
|
|
169
|
+
if edit.action.startswith("watermark-"):
|
|
170
|
+
notes.append("Previous watermark state UNKNOWN: no public read method and channels.list does not accept invideoBranding. Channel freshness/ownership does not prove watermark status or provide If-Match condition. A 204 yields only accepted_unverifiable, never proves bytes, metadata or absence.")
|
|
171
|
+
if edit.action == "watermark-set":
|
|
172
|
+
notes.append("Explicit full watermark replacement with approved file/timing/targetChannelId; unknown previous values are not preserved. durationMs='omit' intentionally omits that field rather than preserving it.")
|
|
173
|
+
return notes
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def watermark_after(edit, before):
|
|
177
|
+
timing = dict(mapping(edit.timing, {"type", "offsetMs", "durationMs"}, "timing"))
|
|
178
|
+
if (set(timing) != {"type", "offsetMs", "durationMs"} or not isinstance(timing.get("type"), str)
|
|
179
|
+
or timing["type"] not in {"offsetFromStart", "offsetFromEnd"}):
|
|
180
|
+
raise ResourceError("replacement requires explicit timing type/offsetMs/durationMs; durationMs='omit' means intentional omission")
|
|
181
|
+
if timing["durationMs"] == "omit":
|
|
182
|
+
del timing["durationMs"]
|
|
183
|
+
for key in {"offsetMs", "durationMs"} & set(timing):
|
|
184
|
+
if not isinstance(timing[key], str) or not re.fullmatch(r"\d{1,20}", timing[key]) or int(timing[key]) > 18446744073709551615:
|
|
185
|
+
raise ResourceError("timing requires decimal uint64 as text")
|
|
186
|
+
target_channel = resource_id(edit.target_channel_id)
|
|
187
|
+
return {"timing": timing, "targetChannelId": target_channel}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def reorder_plan(edit, before):
|
|
191
|
+
rows = ordered(before["collection"])
|
|
192
|
+
positions = [p.model_dump() for p in edit.positions]
|
|
193
|
+
if ({p["item_id"] for p in positions} != {r["id"] for r in rows}
|
|
194
|
+
or len(positions) != len(rows) or sorted(p["position"] for p in positions) != list(range(len(rows)))):
|
|
195
|
+
raise ResourceError("reorder requires each exact playlistItemId once and all positions contiguous")
|
|
196
|
+
plan = []
|
|
197
|
+
for wanted in sorted(positions, key=lambda p: p["position"]):
|
|
198
|
+
row = next(r for r in rows if r["id"] == wanted["item_id"])
|
|
199
|
+
if row["snippet"]["position"] == wanted["position"]:
|
|
200
|
+
continue
|
|
201
|
+
body = {"snippet": {**editable("playlistItems", "snippet", row), "position": wanted["position"]}}
|
|
202
|
+
plan.append({"item_id": row["id"], "body": body})
|
|
203
|
+
rows.remove(row)
|
|
204
|
+
rows.insert(wanted["position"], row)
|
|
205
|
+
for pos, other in enumerate(rows):
|
|
206
|
+
other["snippet"]["position"] = pos
|
|
207
|
+
return {"positions": positions}, plan
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def expected_body(edit, resource, rid, before, account, asset):
|
|
211
|
+
"""Reconstruct outgoing parts from the strict edit, never trust stored after."""
|
|
212
|
+
after, plan = {}, []
|
|
213
|
+
if edit.action == "items-reorder":
|
|
214
|
+
after, plan = reorder_plan(edit, before)
|
|
215
|
+
elif edit.action == "watermark-set":
|
|
216
|
+
after = watermark_after(edit, before)
|
|
217
|
+
elif edit.action == "banner-apply":
|
|
218
|
+
url = banner_url(before["upload_receipt"]["url"])
|
|
219
|
+
after = {"brandingSettings": merge(editable("channels", "brandingSettings", before["resource"]), {"image": {"bannerExternalUrl": url}})}
|
|
220
|
+
elif not edit.action.endswith("-delete") and edit.action not in {"watermark-unset", "banner-upload"}:
|
|
221
|
+
after = build_after(edit, resource, before["resource"] if rid else {}, account)
|
|
222
|
+
if resource == "playlistImages" and asset:
|
|
223
|
+
explicit_dimensions = (edit.patch or {}).get("snippet", {})
|
|
224
|
+
for field in ("width", "height"):
|
|
225
|
+
if field in explicit_dimensions and explicit_dimensions[field] != asset[field]:
|
|
226
|
+
raise ResourceError("explicit dimensions do not match supplied bytes")
|
|
227
|
+
after["snippet"][field] = asset[field]
|
|
228
|
+
if edit.action == "item-update" and "collection" in before and after["snippet"]["position"] >= len(before["collection"]):
|
|
229
|
+
raise ResourceError("update position outside list")
|
|
230
|
+
return after, plan
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def prepare_owned(client, store, edit):
|
|
234
|
+
edit = validate_edit(edit)
|
|
235
|
+
resource, rid = target(edit)
|
|
236
|
+
account = client.identity()
|
|
237
|
+
before = baseline(client, edit)
|
|
238
|
+
if edit.action == "banner-apply":
|
|
239
|
+
uploaded = store.load(edit.upload_change_id)
|
|
240
|
+
if (uploaded.edit["action"] != "banner-upload" or uploaded.target_brand != client.brand.nombre
|
|
241
|
+
or uploaded.target_account != account or uploaded.status != "accepted_unverifiable" or not uploaded.receipt):
|
|
242
|
+
raise ResourceError("banner-apply requires durable upload receipt from same brand/account")
|
|
243
|
+
url = banner_url(uploaded.receipt.get("url"))
|
|
244
|
+
before["upload_receipt"] = {"change_id": uploaded.id, "fingerprint": uploaded.fingerprint, "url": url}
|
|
245
|
+
asset = None
|
|
246
|
+
if edit.file:
|
|
247
|
+
asset, _ = inspect_owned_asset(edit.file, edit.action)
|
|
248
|
+
edit.file = asset["path"]
|
|
249
|
+
after, plan = expected_body(edit, resource, rid, before, account, asset)
|
|
250
|
+
moment = now_utc()
|
|
251
|
+
change = OwnedChange(id=str(uuid.uuid4()), target_brand=client.brand.nombre, target_account=account,
|
|
252
|
+
edit=edit_raw(edit), resource=resource, target_id=rid, before=before, after=after, asset=asset,
|
|
253
|
+
effects=effects_for(edit), plan=plan, created_at=moment, updated_at=moment)
|
|
254
|
+
change.fingerprint = fingerprint(change)
|
|
255
|
+
_event(change, "prepared")
|
|
256
|
+
store.save(change)
|
|
257
|
+
return change
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def identity(client, change):
|
|
261
|
+
if client.brand.nombre != change.target_brand or client.configured_channel_id != change.target_account:
|
|
262
|
+
raise ResourceError("brand/account does not match proposal")
|
|
263
|
+
if client.identity() != change.target_account:
|
|
264
|
+
raise ResourceError("authenticated channel mismatch")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def operation_key(change):
|
|
268
|
+
edit = validate_edit(change.edit)
|
|
269
|
+
# Serialize all ordering/membership operations per playlist. Unknown create
|
|
270
|
+
# outcomes block the entire create family, even if the user changes a title.
|
|
271
|
+
if change.resource in {"playlistItems", "playlistImages"}:
|
|
272
|
+
target_key = [change.resource, edit.playlist_id]
|
|
273
|
+
elif edit.action in {"playlist-create", "section-create"}:
|
|
274
|
+
target_key = [change.resource, "create"]
|
|
275
|
+
else:
|
|
276
|
+
target_key = [change.resource, change.target_id]
|
|
277
|
+
return json.dumps([change.target_account, *target_key])
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def receipt_for(change, response):
|
|
281
|
+
edit = validate_edit(change.edit)
|
|
282
|
+
if edit.action == "banner-upload":
|
|
283
|
+
# Store the returned URL before validating it or preparing application.
|
|
284
|
+
return {"url": response.get("url"), "accepted": True}
|
|
285
|
+
if edit.action.endswith("-delete") or edit.action.startswith("watermark-"):
|
|
286
|
+
return response
|
|
287
|
+
try:
|
|
288
|
+
rid = owned_resource_id(change.resource, response.get("id"))
|
|
289
|
+
except ResourceError:
|
|
290
|
+
rid = None
|
|
291
|
+
change.result_id = rid
|
|
292
|
+
valid = bool(rid) and (change.target_id is None or rid == change.target_id)
|
|
293
|
+
snip = response.get("snippet", {})
|
|
294
|
+
if change.target_id is None:
|
|
295
|
+
valid = valid and rid not in {row["id"] for row in change.before.get("collection", [])}
|
|
296
|
+
if not isinstance(snip, dict):
|
|
297
|
+
valid = False
|
|
298
|
+
elif change.resource in {"playlistItems", "playlistImages"}:
|
|
299
|
+
valid = valid and all(snip.get(k) == v for k, v in change.after["snippet"].items())
|
|
300
|
+
else:
|
|
301
|
+
valid = valid and snip.get("channelId") == change.target_account
|
|
302
|
+
if "kind" in response:
|
|
303
|
+
from socialctl.management.youtube_owned import KINDS
|
|
304
|
+
valid = valid and response["kind"] == KINDS[change.resource]
|
|
305
|
+
return {"id": rid, "identity_valid": valid}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _metadata_matches(resource, expected, actual):
|
|
309
|
+
if actual == expected:
|
|
310
|
+
return True
|
|
311
|
+
if resource != "playlists" or "localizations" not in expected:
|
|
312
|
+
return False
|
|
313
|
+
snippet = expected.get("snippet", {})
|
|
314
|
+
language = snippet.get("defaultLanguage")
|
|
315
|
+
if (not language or language in expected["localizations"]
|
|
316
|
+
or not {"title", "description"} <= snippet.keys()):
|
|
317
|
+
return False
|
|
318
|
+
# YouTube can add the original-language text to the translation map.
|
|
319
|
+
# Accept only that exact redundant entry; every approved field and every
|
|
320
|
+
# other language still must match. Keep the raw observation in the journal
|
|
321
|
+
# and never modify the approved after-values or their fingerprint.
|
|
322
|
+
mirrored = copy.deepcopy(expected)
|
|
323
|
+
mirrored["localizations"][language] = {
|
|
324
|
+
"title": snippet["title"], "description": snippet["description"]}
|
|
325
|
+
return actual == mirrored
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def readback(client, store, change):
|
|
329
|
+
edit = validate_edit(change.edit)
|
|
330
|
+
try:
|
|
331
|
+
identity(client, change)
|
|
332
|
+
if edit.action == "banner-upload":
|
|
333
|
+
if change.receipt and banner_url(change.receipt.get("url")):
|
|
334
|
+
change.status = "accepted_unverifiable"
|
|
335
|
+
_event(change, "upload_only_no_branding_readback")
|
|
336
|
+
elif edit.action == "items-reorder":
|
|
337
|
+
rows = ordered(complete(client.list_items(edit.playlist_id)))
|
|
338
|
+
actual = {r["id"]: r["snippet"]["position"] for r in rows}
|
|
339
|
+
expected = {p["item_id"]: p["position"] for p in change.after["positions"]}
|
|
340
|
+
_event(change, "order_readback", positions=actual)
|
|
341
|
+
if actual == expected and len(change.steps) == len(change.plan) and all(s["status"] == "verified" for s in change.steps):
|
|
342
|
+
change.status, change.verified = "verified", True
|
|
343
|
+
elif edit.action.startswith("watermark-"):
|
|
344
|
+
_event(change, "watermark_readback_unavailable", state_known=False,
|
|
345
|
+
reason="no_public_read_method", bytes_verified=False, absence_verified=False)
|
|
346
|
+
if change.receipt and change.receipt.get("http_status") == 204:
|
|
347
|
+
change.status, change.verified = "accepted_unverifiable", False
|
|
348
|
+
elif edit.action.endswith("-delete"):
|
|
349
|
+
row = client.one(change.resource, change.target_id, parent=edit.playlist_id, optional=True)
|
|
350
|
+
_event(change, "delete_readback", absent_observed=row is None, absence_alone_is_not_proof=True)
|
|
351
|
+
if row is None and change.receipt and change.receipt.get("http_status") == 204:
|
|
352
|
+
change.status, change.verified = "verified", True
|
|
353
|
+
elif change.receipt and change.receipt.get("identity_valid"):
|
|
354
|
+
row = client.one(change.resource, change.result_id, parent=edit.playlist_id)
|
|
355
|
+
actual = {p: editable(change.resource, p, row) for p in change.after}
|
|
356
|
+
match = _metadata_matches(change.resource, change.after, actual)
|
|
357
|
+
raw_type = ({"provider_section_type": row.get("snippet", {}).get("type")}
|
|
358
|
+
if change.resource == "channelSections" else {})
|
|
359
|
+
_event(change, "metadata_readback", matches=match, observed=actual, bytes_verified=False, **raw_type)
|
|
360
|
+
if match:
|
|
361
|
+
if change.asset:
|
|
362
|
+
change.status = "accepted_unverifiable"
|
|
363
|
+
else:
|
|
364
|
+
change.status, change.verified = "verified", True
|
|
365
|
+
else:
|
|
366
|
+
_event(change, "identity_unresolved", limitation="Identity is not inferred from titles or candidates; create is not repeated.")
|
|
367
|
+
except ResourceError as exc:
|
|
368
|
+
_event(change, "readback_unavailable", error=str(exc))
|
|
369
|
+
store.save(change)
|
|
370
|
+
return change
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def reconcile_owned(client, store, change_id):
|
|
374
|
+
with store.apply_lock(change_id):
|
|
375
|
+
change = store.load(change_id)
|
|
376
|
+
identity(client, change)
|
|
377
|
+
if change.status in {"applying", "uncertain", "partial", "accepted_unverifiable"}:
|
|
378
|
+
if change.status == "applying":
|
|
379
|
+
change.status = "uncertain"
|
|
380
|
+
return readback(client, store, change)
|
|
381
|
+
return change
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _same_owned_baseline(resource, expected, current):
|
|
385
|
+
if resource != "videos":
|
|
386
|
+
return current == expected
|
|
387
|
+
from socialctl.management.youtube_metadata import same_metadata_snapshot
|
|
388
|
+
if set(expected) != set(current) or "resource" not in expected:
|
|
389
|
+
return False
|
|
390
|
+
before, after = expected["resource"], current["resource"]
|
|
391
|
+
for row in (before, after):
|
|
392
|
+
if (not isinstance(row, dict) or not isinstance(row.get("etag"), str)
|
|
393
|
+
or not row["etag"] or not isinstance(row.get("snippet"), dict)
|
|
394
|
+
or not row.get("id") or not row.get("kind")
|
|
395
|
+
or not row["snippet"].get("channelId")):
|
|
396
|
+
return False
|
|
397
|
+
return (all(current[k] == expected[k] for k in expected if k != "resource")
|
|
398
|
+
and same_metadata_snapshot(before, after))
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def apply_owned(client, store, change_id, approval_digest):
|
|
402
|
+
with ExitStack() as locks:
|
|
403
|
+
locks.enter_context(store.apply_lock(change_id))
|
|
404
|
+
change = store.load(change_id)
|
|
405
|
+
edit = validate_edit(change.edit)
|
|
406
|
+
if target(edit) != (change.resource, change.target_id) or bool(edit.file) != bool(change.asset):
|
|
407
|
+
raise ResourceError("proposal does not match resource/file schema")
|
|
408
|
+
if not hmac.compare_digest(approval_digest, change.fingerprint):
|
|
409
|
+
raise ApprovalMismatch("approval does not match exact fingerprint")
|
|
410
|
+
key = operation_key(change)
|
|
411
|
+
locks.enter_context(store.apply_lock(str(uuid.uuid5(uuid.NAMESPACE_URL, key))))
|
|
412
|
+
identity(client, change)
|
|
413
|
+
if change.status != "proposed":
|
|
414
|
+
if change.status in {"applying", "uncertain", "partial", "accepted_unverifiable"}:
|
|
415
|
+
if change.status == "applying":
|
|
416
|
+
change.status = "uncertain"
|
|
417
|
+
return readback(client, store, change)
|
|
418
|
+
return change
|
|
419
|
+
for path in store.root.glob("*.json"):
|
|
420
|
+
if path.stem != change.id and store.completed_history(path.stem):
|
|
421
|
+
continue
|
|
422
|
+
other = store.load(path.stem)
|
|
423
|
+
unresolved_steps = any(s.get("status") in {"applying", "uncertain"} for s in other.steps)
|
|
424
|
+
if other.id != change.id and operation_key(other) == key and (other.status in {"applying", "uncertain"} or unresolved_steps):
|
|
425
|
+
raise ResourceError(f"uncertain outcome pending in {other.id}; another UUID does not allow repeating write")
|
|
426
|
+
try:
|
|
427
|
+
current = baseline(client, edit)
|
|
428
|
+
expected = {k: v for k, v in change.before.items() if k != "upload_receipt"}
|
|
429
|
+
if not _same_owned_baseline(change.resource, expected, current):
|
|
430
|
+
raise ResourceConflict("conflict: resource/listing changed since preview")
|
|
431
|
+
if edit.action == "banner-apply":
|
|
432
|
+
uploaded = store.load(edit.upload_change_id)
|
|
433
|
+
binding = change.before["upload_receipt"]
|
|
434
|
+
if (uploaded.fingerprint != binding["fingerprint"] or not uploaded.receipt or uploaded.receipt.get("url") != binding["url"]
|
|
435
|
+
or uploaded.status != "accepted_unverifiable" or uploaded.target_account != change.target_account or uploaded.target_brand != change.target_brand):
|
|
436
|
+
raise ResourceConflict("conflict: banner receipt changed")
|
|
437
|
+
except ResourceConflict:
|
|
438
|
+
change.status = "conflict"
|
|
439
|
+
_event(change, "pre_write_conflict")
|
|
440
|
+
store.save(change)
|
|
441
|
+
raise
|
|
442
|
+
data = None
|
|
443
|
+
if change.asset:
|
|
444
|
+
asset, data = inspect_owned_asset(edit.file, edit.action)
|
|
445
|
+
if asset != change.asset:
|
|
446
|
+
raise ResourceError("file/bytes changed since approved fingerprint")
|
|
447
|
+
after, plan = expected_body(edit, change.resource, change.target_id, change.before, change.target_account, change.asset)
|
|
448
|
+
if after != change.after or plan != change.plan or effects_for(edit) != change.effects:
|
|
449
|
+
raise ResourceError("body/plan/effects do not match proposal schema")
|
|
450
|
+
if edit.action == "items-reorder":
|
|
451
|
+
from socialctl.management.owned_reorder import apply_order
|
|
452
|
+
return apply_order(client, store, change, edit, approval_digest)
|
|
453
|
+
change.status = "applying"
|
|
454
|
+
_event(change, "write_intent", approval_digest=approval_digest)
|
|
455
|
+
store.save(change)
|
|
456
|
+
try:
|
|
457
|
+
response = client.effect(edit, change.resource, change.target_id, change.after,
|
|
458
|
+
etag=None if change.target_id is None else current["resource"].get("etag"), asset=change.asset, data=data)
|
|
459
|
+
except ResourceRejected as exc:
|
|
460
|
+
change.status = "conflict" if isinstance(exc, ResourceConflict) else "failed"
|
|
461
|
+
_event(change, "write_rejected", error=str(exc))
|
|
462
|
+
except ResourceUncertain as exc:
|
|
463
|
+
change.status = "uncertain"
|
|
464
|
+
_event(change, "write_uncertain", error=str(exc))
|
|
465
|
+
else:
|
|
466
|
+
change.status = "uncertain"
|
|
467
|
+
change.receipt = receipt_for(change, response)
|
|
468
|
+
_event(change, "write_response", result_id=change.result_id, receipt=change.receipt)
|
|
469
|
+
store.save(change)
|
|
470
|
+
return readback(client, store, change) if change.status == "uncertain" else change
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Named owned YouTube operations; preparation always shows the entire dry-run."""
|
|
2
|
+
import json
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from socialctl.approval_cli import read_approval
|
|
9
|
+
|
|
10
|
+
from socialctl.management.changes import ChangeError
|
|
11
|
+
from socialctl.management.owned_schema import load_owned_edit
|
|
12
|
+
from socialctl.management.owned_changes import OwnedStore, prepare_owned, apply_owned, reconcile_owned
|
|
13
|
+
from socialctl.management.youtube_owned import PARTS, YouTubeOwnedClient
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def make_http_client():
|
|
17
|
+
return httpx.Client(timeout=60.0, follow_redirects=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _json(value):
|
|
21
|
+
return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def render_owned_preview(change):
|
|
25
|
+
return ("DRY-RUN — FULL PREVIEW of owned YouTube resource\n"
|
|
26
|
+
+ _json(change.model_dump(mode="json"))
|
|
27
|
+
+ "\nApproval covers complete before, after, effects, plan and bytes with their SHA256."
|
|
28
|
+
+ "\nUncertain outcomes are not repeated with another UUID. Reconcile only rereads; does not restore or continue effects."
|
|
29
|
+
+ f"\nExact fingerprint for approval: {change.fingerprint}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def register(content_app, default_root):
|
|
33
|
+
from socialctl.management.cli import _brand, _fail
|
|
34
|
+
|
|
35
|
+
owned = typer.Typer(help="Playlists, channel, sections and owned resources; strict proposals and durable approval.")
|
|
36
|
+
content_app.add_typer(owned, name="youtube-owned")
|
|
37
|
+
|
|
38
|
+
def read(root, brand, callback):
|
|
39
|
+
selected = _brand(root, brand)
|
|
40
|
+
try:
|
|
41
|
+
with make_http_client() as http:
|
|
42
|
+
result = callback(YouTubeOwnedClient(selected, http))
|
|
43
|
+
except (ChangeError, OSError, ValueError) as exc:
|
|
44
|
+
_fail(str(exc))
|
|
45
|
+
typer.echo(_json(result))
|
|
46
|
+
|
|
47
|
+
@owned.command("playlists-list")
|
|
48
|
+
def playlists_list(brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root"),
|
|
49
|
+
max_pages: int = typer.Option(100, "--max-pages", min=1, max=100)):
|
|
50
|
+
read(root, brand, lambda client: client.list_playlists(max_pages=max_pages))
|
|
51
|
+
|
|
52
|
+
@owned.command("items-list")
|
|
53
|
+
def items_list(playlist_id: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root"),
|
|
54
|
+
max_pages: int = typer.Option(100, "--max-pages", min=1, max=100)):
|
|
55
|
+
read(root, brand, lambda client: client.list_items(playlist_id, max_pages=max_pages))
|
|
56
|
+
|
|
57
|
+
@owned.command("sections-list")
|
|
58
|
+
def sections_list(brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root")):
|
|
59
|
+
read(root, brand, lambda client: client.list_sections())
|
|
60
|
+
|
|
61
|
+
@owned.command("images-list")
|
|
62
|
+
def images_list(playlist_id: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root"),
|
|
63
|
+
max_pages: int = typer.Option(100, "--max-pages", min=1, max=100)):
|
|
64
|
+
read(root, brand, lambda client: client.list_images(playlist_id, max_pages=max_pages))
|
|
65
|
+
|
|
66
|
+
@owned.command("channel-show")
|
|
67
|
+
def channel_show(channel_id: str, parts: str = typer.Option(PARTS["channels"], "--parts"),
|
|
68
|
+
brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root")):
|
|
69
|
+
read(root, brand, lambda client: client.inspect_channel(channel_id, parts=parts.split(",")))
|
|
70
|
+
|
|
71
|
+
@owned.command("video-show")
|
|
72
|
+
def video_show(video_id: str, parts: str = typer.Option("snippet,recordingDetails", "--parts"),
|
|
73
|
+
brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root")):
|
|
74
|
+
read(root, brand, lambda client: client.inspect_video(video_id, parts=parts.split(",")))
|
|
75
|
+
|
|
76
|
+
@owned.command("prepare")
|
|
77
|
+
def prepare(file: Path = typer.Option(..., "--file", help="YAML version1, action and specific fields; never arbitrary endpoint/payload."),
|
|
78
|
+
brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root"),
|
|
79
|
+
dry_run: bool = typer.Option(False, "--dry-run")):
|
|
80
|
+
"""Prepare locally and always display full dry-run without writing to YouTube."""
|
|
81
|
+
selected = _brand(root, brand)
|
|
82
|
+
try:
|
|
83
|
+
edit = load_owned_edit(file)
|
|
84
|
+
with make_http_client() as http:
|
|
85
|
+
change = prepare_owned(YouTubeOwnedClient(selected, http), OwnedStore(selected.raiz), edit)
|
|
86
|
+
except (ChangeError, OSError, ValueError) as exc:
|
|
87
|
+
_fail(str(exc))
|
|
88
|
+
typer.echo(render_owned_preview(change))
|
|
89
|
+
|
|
90
|
+
@owned.command("status")
|
|
91
|
+
def status(change_id: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root")):
|
|
92
|
+
selected = _brand(root, brand)
|
|
93
|
+
try:
|
|
94
|
+
change = OwnedStore(selected.raiz).load(change_id)
|
|
95
|
+
except ChangeError as exc:
|
|
96
|
+
_fail(str(exc))
|
|
97
|
+
typer.echo(_json(change.model_dump(mode="json")))
|
|
98
|
+
|
|
99
|
+
@owned.command("apply")
|
|
100
|
+
def apply(change_id: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root"),
|
|
101
|
+
approval_fingerprint: str | None = typer.Option(None, "--approval-fingerprint", "--approval", "--approval-digest", help="Exact fingerprint from the approved complete preview."),
|
|
102
|
+
approval_stdin: bool = typer.Option(False, "--approval-stdin", help="Explicitly read one approval line from stdin.")):
|
|
103
|
+
selected = _brand(root, brand)
|
|
104
|
+
store = OwnedStore(selected.raiz)
|
|
105
|
+
try:
|
|
106
|
+
change = store.load(change_id)
|
|
107
|
+
typer.echo(render_owned_preview(change))
|
|
108
|
+
approval = read_approval(approval_fingerprint, approval_stdin=approval_stdin)
|
|
109
|
+
if approval != change.fingerprint:
|
|
110
|
+
_fail("approval does not match exact fingerprint")
|
|
111
|
+
with make_http_client() as http:
|
|
112
|
+
result = apply_owned(YouTubeOwnedClient(selected, http), store, change_id, approval)
|
|
113
|
+
except (ChangeError, OSError, ValueError) as exc:
|
|
114
|
+
_fail(str(exc))
|
|
115
|
+
typer.echo(_json(result.model_dump(mode="json")))
|
|
116
|
+
if result.status != "verified":
|
|
117
|
+
raise typer.Exit(1)
|
|
118
|
+
|
|
119
|
+
@owned.command("reconcile")
|
|
120
|
+
def reconcile(change_id: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(default_root, "--root")):
|
|
121
|
+
"""Remote reads only; never resend or continue writes."""
|
|
122
|
+
selected = _brand(root, brand)
|
|
123
|
+
try:
|
|
124
|
+
with make_http_client() as http:
|
|
125
|
+
result = reconcile_owned(YouTubeOwnedClient(selected, http), OwnedStore(selected.raiz), change_id)
|
|
126
|
+
except (ChangeError, OSError, ValueError) as exc:
|
|
127
|
+
_fail(str(exc))
|
|
128
|
+
typer.echo(_json(result.model_dump(mode="json")))
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Non-atomic playlist reordering: persist every intent/result before the next move."""
|
|
2
|
+
import copy
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from socialctl.management.resource_changes import _event, digest
|
|
6
|
+
from socialctl.management.owned_changes import complete, ordered, readback, identity
|
|
7
|
+
from socialctl.management.owned_schema import OwnedEdit
|
|
8
|
+
from socialctl.management.youtube_resources import ResourceError, ResourceRejected, ResourceConflict, ResourceUncertain
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def semantic(rows):
|
|
12
|
+
return [{k: v for k, v in row.items() if k != "etag"} for row in ordered(rows)]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def apply_order(client, store, change, edit, approval_digest):
|
|
16
|
+
expected = ordered(change.before["collection"])
|
|
17
|
+
change.status = "applying"
|
|
18
|
+
_event(change, "order_intent", approval_digest=approval_digest, atomic=False)
|
|
19
|
+
store.save(change)
|
|
20
|
+
for plan in change.plan:
|
|
21
|
+
try:
|
|
22
|
+
identity(client, change)
|
|
23
|
+
current = ordered(complete(client.list_items(edit.playlist_id)))
|
|
24
|
+
if current != expected:
|
|
25
|
+
raise ResourceConflict("conflict: list changed before next move")
|
|
26
|
+
row = next(r for r in current if r["id"] == plan["item_id"])
|
|
27
|
+
step = {"item_id": row["id"], "status": "applying", "etag": row["etag"], "result_id": None}
|
|
28
|
+
change.steps.append(step)
|
|
29
|
+
_event(change, "write_intent", item_id=row["id"], approval_digest=approval_digest)
|
|
30
|
+
store.save(change)
|
|
31
|
+
move = OwnedEdit(action="item-update", playlist_id=edit.playlist_id, item_id=row["id"], patch={"snippet": {"position": plan["body"]["snippet"]["position"]}})
|
|
32
|
+
response = client.effect(move, "playlistItems", row["id"], plan["body"], etag=row["etag"])
|
|
33
|
+
step["result_id"] = response.get("id")
|
|
34
|
+
step["status"] = "uncertain"
|
|
35
|
+
_event(change, "write_response", item_id=row["id"], result_id=step["result_id"])
|
|
36
|
+
store.save(change)
|
|
37
|
+
if step["result_id"] != row["id"]:
|
|
38
|
+
raise ResourceUncertain("reorder returned an unexpected playlistItemId")
|
|
39
|
+
predicted = copy.deepcopy(current)
|
|
40
|
+
moved = next(r for r in predicted if r["id"] == row["id"])
|
|
41
|
+
predicted.remove(moved)
|
|
42
|
+
predicted.insert(plan["body"]["snippet"]["position"], moved)
|
|
43
|
+
for index, other in enumerate(predicted):
|
|
44
|
+
other["snippet"]["position"] = index
|
|
45
|
+
observed = ordered(complete(client.list_items(edit.playlist_id)))
|
|
46
|
+
if semantic(observed) != semantic(predicted):
|
|
47
|
+
raise ResourceUncertain("order readback mismatch or another field changed")
|
|
48
|
+
step["status"] = "verified"
|
|
49
|
+
step["readback"] = next(r for r in observed if r["id"] == row["id"])
|
|
50
|
+
step["collection_digest"] = digest(json.dumps(observed, sort_keys=True, separators=(",", ":")).encode())
|
|
51
|
+
_event(change, "move_verified", item_id=row["id"])
|
|
52
|
+
store.save(change)
|
|
53
|
+
expected = observed
|
|
54
|
+
except ResourceError as exc:
|
|
55
|
+
if change.steps and change.steps[-1]["status"] in {"applying", "uncertain"}:
|
|
56
|
+
change.steps[-1]["status"] = ("conflict" if isinstance(exc, ResourceConflict) else "failed") if isinstance(exc, ResourceRejected) else "uncertain"
|
|
57
|
+
change.status = "partial" if any(s["status"] == "verified" for s in change.steps) else ("failed" if isinstance(exc, ResourceRejected) else "uncertain")
|
|
58
|
+
_event(change, "order_stopped", error=str(exc), atomic=False)
|
|
59
|
+
store.save(change)
|
|
60
|
+
return change
|
|
61
|
+
change.status = "uncertain"
|
|
62
|
+
return readback(client, store, change)
|