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
socialctl/media.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""Read and validate supplied media without altering it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import subprocess
|
|
8
|
+
import stat
|
|
9
|
+
from fractions import Fraction
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from socialctl.formatter import PLATFORM_SPECS
|
|
13
|
+
from socialctl.models import (
|
|
14
|
+
MediaAsset,
|
|
15
|
+
MediaKind,
|
|
16
|
+
PlatformPost,
|
|
17
|
+
ValidationError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
EXTENSIONES_IMAGEN = {".jpg", ".jpeg", ".png", ".webp", ".heic"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MediaNoEncontrada(Exception):
|
|
24
|
+
"""The specified media file does not exist."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MediaInvalida(Exception):
|
|
28
|
+
"""The file exists but cannot be read as media."""
|
|
29
|
+
def __init__(self, message, *, code='media_unreadable'):
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.code = code
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _ffprobe(path: Path) -> dict:
|
|
35
|
+
try:
|
|
36
|
+
salida = subprocess.run(
|
|
37
|
+
[
|
|
38
|
+
"ffprobe", "-v", "error", "-protocol_whitelist", "file",
|
|
39
|
+
"-show_entries",
|
|
40
|
+
"stream=codec_type,codec_name,width,height,avg_frame_rate,pix_fmt,sample_aspect_ratio,sample_rate,channels:stream_disposition=attached_pic:stream_tags=rotate"
|
|
41
|
+
":stream_side_data=rotation:format=format_name,duration:format_tags=major_brand",
|
|
42
|
+
"-of", "json", str(path),
|
|
43
|
+
],
|
|
44
|
+
check=True,
|
|
45
|
+
capture_output=True,
|
|
46
|
+
text=True,
|
|
47
|
+
timeout=30,
|
|
48
|
+
)
|
|
49
|
+
except FileNotFoundError as exc:
|
|
50
|
+
raise MediaInvalida('ffprobe is required to inspect supplied media', code='probe_unavailable') from exc
|
|
51
|
+
except subprocess.TimeoutExpired as exc:
|
|
52
|
+
raise MediaInvalida('media inspection exceeded 30 seconds', code='probe_timeout') from exc
|
|
53
|
+
except subprocess.CalledProcessError as exc:
|
|
54
|
+
stderr = (exc.stderr or "").strip()
|
|
55
|
+
# ffprobe suele emitir varias líneas de contexto: primero la causa
|
|
56
|
+
# concreta (p. ej. "moov atom not found") y después una genérica
|
|
57
|
+
# ("Invalid data found when processing input"). Nos quedamos con
|
|
58
|
+
# todas las líneas no vacías para no perder la información útil.
|
|
59
|
+
#
|
|
60
|
+
# ffprobe se invoca con str(path), y esa misma ruta (a menudo
|
|
61
|
+
# absoluta) puede reaparecer como prefijo en cualquiera de las
|
|
62
|
+
# líneas de stderr (p. ej. "/tmp/.../clip.mp4: Invalid data..."); la
|
|
63
|
+
# quitamos para no repetirla ni filtrar rutas del sistema, ya que
|
|
64
|
+
# nuestro propio mensaje ya identifica el archivo por su nombre.
|
|
65
|
+
prefijo = f"{path}: "
|
|
66
|
+
lineas = []
|
|
67
|
+
for linea in stderr.splitlines():
|
|
68
|
+
linea = linea.strip()
|
|
69
|
+
if not linea:
|
|
70
|
+
continue
|
|
71
|
+
if linea.startswith(prefijo):
|
|
72
|
+
linea = linea[len(prefijo):]
|
|
73
|
+
lineas.append(linea)
|
|
74
|
+
causa = "; ".join(lineas) if lineas else "ffprobe provided no further details"
|
|
75
|
+
raise MediaInvalida(
|
|
76
|
+
f"cannot read '{path.name}' as media: {causa}"
|
|
77
|
+
) from exc
|
|
78
|
+
try:
|
|
79
|
+
if len(salida.stdout) > 1_000_000:
|
|
80
|
+
raise ValueError('probe output exceeds limit')
|
|
81
|
+
data = json.loads(salida.stdout)
|
|
82
|
+
if not isinstance(data, dict):
|
|
83
|
+
raise ValueError('invalid probe shape')
|
|
84
|
+
return data
|
|
85
|
+
except (ValueError, TypeError) as exc:
|
|
86
|
+
raise MediaInvalida('invalid media inspection response') from exc
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _rotacion_grados(stream: dict) -> int:
|
|
90
|
+
"""Extract video stream rotation in degrees when present."""
|
|
91
|
+
tags = stream.get("tags") or {}
|
|
92
|
+
rotate = tags.get("rotate")
|
|
93
|
+
if rotate is not None:
|
|
94
|
+
try:
|
|
95
|
+
return int(rotate)
|
|
96
|
+
except (ValueError, TypeError):
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
for side_data in stream.get("side_data_list") or []:
|
|
100
|
+
rotation = side_data.get("rotation")
|
|
101
|
+
if rotation is not None:
|
|
102
|
+
try:
|
|
103
|
+
return int(rotation)
|
|
104
|
+
except (ValueError, TypeError):
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def leer_media(path: Path, *, ruta_relativa: str = "") -> MediaAsset:
|
|
111
|
+
"""Read supplied media metadata."""
|
|
112
|
+
if not path.exists():
|
|
113
|
+
raise MediaNoEncontrada(f"file does not exist: {path}")
|
|
114
|
+
|
|
115
|
+
before = path.stat()
|
|
116
|
+
if not stat.S_ISREG(before.st_mode) or before.st_size <= 0:
|
|
117
|
+
raise MediaInvalida('supplied media must be a nonempty regular file')
|
|
118
|
+
datos = _ffprobe(path)
|
|
119
|
+
after = path.stat()
|
|
120
|
+
if (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns):
|
|
121
|
+
raise MediaInvalida('media changed during inspection', code='media_changed')
|
|
122
|
+
kind = MediaKind.IMAGE if path.suffix.lower() in EXTENSIONES_IMAGEN else MediaKind.VIDEO
|
|
123
|
+
streams = datos.get('streams')
|
|
124
|
+
if not isinstance(streams, list):
|
|
125
|
+
raise MediaInvalida('visual stream metadata unavailable')
|
|
126
|
+
visual = [row for row in streams if isinstance(row, dict) and row.get('codec_type') == 'video'
|
|
127
|
+
and (kind is MediaKind.IMAGE or not (row.get('disposition') or {}).get('attached_pic'))]
|
|
128
|
+
if len(visual) != 1:
|
|
129
|
+
raise MediaInvalida('exactly one visual stream required; cover art is not video')
|
|
130
|
+
stream = visual[0]
|
|
131
|
+
width, height = stream.get('width'), stream.get('height')
|
|
132
|
+
if any(type(v) is not int or v <= 0 for v in (width, height)):
|
|
133
|
+
raise MediaInvalida('positive visual dimensions required')
|
|
134
|
+
try:
|
|
135
|
+
duration = float(datos.get('format', {}).get('duration')) if kind is MediaKind.VIDEO else None
|
|
136
|
+
if duration is not None and (not math.isfinite(duration) or duration <= 0):
|
|
137
|
+
raise ValueError()
|
|
138
|
+
except (TypeError, ValueError) as exc:
|
|
139
|
+
raise MediaInvalida('finite positive video duration required') from exc
|
|
140
|
+
try:
|
|
141
|
+
fps = float(Fraction(stream.get('avg_frame_rate', '0/1')))
|
|
142
|
+
if not math.isfinite(fps) or fps <= 0: fps = None
|
|
143
|
+
except (TypeError, ValueError, ZeroDivisionError):
|
|
144
|
+
fps = None
|
|
145
|
+
try:
|
|
146
|
+
sar = float(Fraction(stream.get('sample_aspect_ratio', '1:1').replace(':', '/')))
|
|
147
|
+
if not math.isfinite(sar) or sar <= 0: raise ValueError()
|
|
148
|
+
except (TypeError, AttributeError, ValueError, ZeroDivisionError):
|
|
149
|
+
sar = None
|
|
150
|
+
display_ratio = width / height * sar if sar is not None else None
|
|
151
|
+
if _rotacion_grados(stream) % 180 == 90:
|
|
152
|
+
width, height = height, width
|
|
153
|
+
if display_ratio is not None: display_ratio = 1 / display_ratio
|
|
154
|
+
technical = {'video_codec': stream.get('codec_name'), 'container': datos.get('format', {}).get('format_name'),
|
|
155
|
+
'container_brand': (datos.get('format', {}).get('tags') or {}).get('major_brand'),
|
|
156
|
+
'fps': fps, 'pixel_format': stream.get('pix_fmt'), 'display_ratio': display_ratio,
|
|
157
|
+
'audio': [{'codec': row.get('codec_name'), 'sample_rate': row.get('sample_rate'), 'channels': row.get('channels')}
|
|
158
|
+
for row in streams if isinstance(row, dict) and row.get('codec_type') == 'audio']}
|
|
159
|
+
return MediaAsset(path=path, kind=kind, width=width, height=height,
|
|
160
|
+
duration_s=duration, size_bytes=before.st_size, ruta_relativa=ruta_relativa, probe=technical)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def ruta_relativa_efectiva(asset: MediaAsset) -> str:
|
|
164
|
+
"""Return the asset's effective relative path, preserving subdirectories."""
|
|
165
|
+
return asset.ruta_relativa or asset.path.name
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _ratio(width: int, height: int) -> str:
|
|
169
|
+
"""Return the simplified width:height aspect ratio."""
|
|
170
|
+
divisor = math.gcd(width, height)
|
|
171
|
+
return f"{width // divisor}:{height // divisor}"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _ratio_compatible(ratio: str, permitidos: list[str], tolerancia: float = 0.02) -> bool:
|
|
175
|
+
"""Return whether the ratio is close to an allowed ratio."""
|
|
176
|
+
valor = float(Fraction(ratio.replace(":", "/")))
|
|
177
|
+
for permitido in permitidos:
|
|
178
|
+
objetivo = float(Fraction(permitido.replace(":", "/")))
|
|
179
|
+
if abs(valor - objetivo) <= tolerancia * objetivo:
|
|
180
|
+
return True
|
|
181
|
+
return False
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def validar_media(post: PlatformPost) -> list[ValidationError]:
|
|
185
|
+
"""Validate supplied media against the platform's limits."""
|
|
186
|
+
spec = PLATFORM_SPECS[post.platform]
|
|
187
|
+
errores: list[ValidationError] = []
|
|
188
|
+
|
|
189
|
+
if not post.media:
|
|
190
|
+
if spec.exige_media:
|
|
191
|
+
errores.append(
|
|
192
|
+
ValidationError(
|
|
193
|
+
platform=post.platform,
|
|
194
|
+
campo="media",
|
|
195
|
+
motivo=(
|
|
196
|
+
f'{post.platform.value} requires an image or video, but none was provided'
|
|
197
|
+
),
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
return errores
|
|
201
|
+
|
|
202
|
+
if len(post.media) > spec.max_media:
|
|
203
|
+
errores.append(
|
|
204
|
+
ValidationError(
|
|
205
|
+
platform=post.platform,
|
|
206
|
+
campo="media",
|
|
207
|
+
motivo=(
|
|
208
|
+
f'this route supports at most {spec.max_media} file; it does not publish carousels'
|
|
209
|
+
),
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
for asset in post.media:
|
|
214
|
+
if asset.duration_s is not None:
|
|
215
|
+
if spec.min_video_s and asset.duration_s < spec.min_video_s:
|
|
216
|
+
errores.append(
|
|
217
|
+
ValidationError(
|
|
218
|
+
platform=post.platform,
|
|
219
|
+
campo="media",
|
|
220
|
+
motivo=(
|
|
221
|
+
f"{asset.path.name} lasts {asset.duration_s:.1f}s and "
|
|
222
|
+
f"{post.platform.value} requires at least {spec.min_video_s}s"
|
|
223
|
+
),
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
if spec.max_video_s and asset.duration_s > spec.max_video_s:
|
|
227
|
+
errores.append(
|
|
228
|
+
ValidationError(
|
|
229
|
+
platform=post.platform,
|
|
230
|
+
campo="media",
|
|
231
|
+
motivo=(
|
|
232
|
+
f"{asset.path.name} lasts {asset.duration_s:.1f}s and "
|
|
233
|
+
f"{post.platform.value} allows at most {spec.max_video_s}s"
|
|
234
|
+
),
|
|
235
|
+
)
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
maximum = (8 * 1000**2 if asset.kind is MediaKind.IMAGE else 300 * 1000**2) if post.platform.value == 'instagram' else spec.max_bytes
|
|
239
|
+
if maximum and asset.size_bytes > maximum:
|
|
240
|
+
errores.append(
|
|
241
|
+
ValidationError(
|
|
242
|
+
platform=post.platform,
|
|
243
|
+
campo="media",
|
|
244
|
+
motivo=(
|
|
245
|
+
f"{asset.path.name} is {asset.size_bytes / 1024**2:.0f} MB and "
|
|
246
|
+
f"{post.platform.value} allows {maximum / 1024**2:.0f} MiB on this route"
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
if asset.width and asset.height and spec.aspect_ratios and post.platform.value != 'instagram':
|
|
252
|
+
ratio = _ratio(asset.width, asset.height)
|
|
253
|
+
if not _ratio_compatible(ratio, spec.aspect_ratios):
|
|
254
|
+
errores.append(
|
|
255
|
+
ValidationError(
|
|
256
|
+
platform=post.platform,
|
|
257
|
+
campo="media",
|
|
258
|
+
motivo=(
|
|
259
|
+
f"{asset.path.name} is {ratio} ({asset.width}x{asset.height}) "
|
|
260
|
+
f"and this SocialCli {post.platform.value} route is configured for {', '.join(spec.aspect_ratios)}"
|
|
261
|
+
),
|
|
262
|
+
)
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
from socialctl.media_requirements import technical_issues
|
|
266
|
+
for asset in post.media:
|
|
267
|
+
for issue in technical_issues(post.platform, asset):
|
|
268
|
+
errores.append(ValidationError(platform=post.platform, campo='media', motivo=issue['message']))
|
|
269
|
+
return errores
|
socialctl/media_cli.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Explicit media staging/SSH operations; ingestion never invokes a publisher."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import selectors
|
|
8
|
+
import shlex
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import typer
|
|
16
|
+
|
|
17
|
+
from socialctl.brands import cargar_brand
|
|
18
|
+
from socialctl.media_ingress import receive as ingest, verify as readiness, write_transfer
|
|
19
|
+
from socialctl.media_registry import MAX_HEADER, MAX_POST, MediaRegistryError, component, load_bundle, parse_json, relative, stage as stage_bundle
|
|
20
|
+
from socialctl.schedule_remote import DEFAULT_ROOT, RemoteConfig
|
|
21
|
+
|
|
22
|
+
media_app = typer.Typer(help="Copy and transfer supplied media; does not publish or approve schedules.")
|
|
23
|
+
MAX_RESPONSE = 12 * MAX_POST + MAX_HEADER # Both full texts, worst-case JSON escaping.
|
|
24
|
+
SECRET = re.compile(r"(?i)(?:[\"']?(?:access[_-]?token|refresh[_-]?token|client[_-]?secret|password|authorization|token)[\"']?\s*[:=]|\bbearer\s+\S+)")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _response(value, brand, ident):
|
|
28
|
+
"""Only bounded typed readiness/preview data may be printed from SSH."""
|
|
29
|
+
if not isinstance(value, dict) or value.get("bundle") != ident:
|
|
30
|
+
raise MediaRegistryError("invalid remote response")
|
|
31
|
+
if value.get("protocol") == "socialctl.media-update.v1":
|
|
32
|
+
if (set(value) != {"protocol", "bundle", "preview", "update_digest"}
|
|
33
|
+
or not isinstance(value["preview"], str) or SECRET.search(value["preview"])
|
|
34
|
+
or not re.fullmatch(r"[a-f0-9]{64}", value["update_digest"])):
|
|
35
|
+
raise MediaRegistryError("invalid remote preview")
|
|
36
|
+
elif value.get("protocol") == "socialctl.media-readiness.v1":
|
|
37
|
+
if (set(value) != {"protocol", "brand", "bundle", "local_ready", "private_ready", "hosted_ready", "public_ready", "checked_at", "attestations"}
|
|
38
|
+
or value["brand"] != brand.nombre
|
|
39
|
+
or any(type(value[key]) is not bool for key in ("local_ready", "private_ready", "hosted_ready", "public_ready"))
|
|
40
|
+
or not isinstance(value["attestations"], list)
|
|
41
|
+
or SECRET.search(json.dumps(value))):
|
|
42
|
+
raise MediaRegistryError("invalid remote state")
|
|
43
|
+
from socialctl.scheduler import parse_scheduled_at
|
|
44
|
+
from socialctl.hosted_media import MIMES, public_url, validate_url
|
|
45
|
+
parse_scheduled_at(value["checked_at"])
|
|
46
|
+
for item in value["attestations"]:
|
|
47
|
+
if (set(item) != {"url", "sha256", "size", "mime"}
|
|
48
|
+
or not re.fullmatch(r"[a-f0-9]{64}", item["sha256"])
|
|
49
|
+
or type(item["size"]) is not int or item["size"] <= 0 or item["mime"] not in MIMES.values()):
|
|
50
|
+
raise MediaRegistryError("invalid remote attestation")
|
|
51
|
+
validate_url(item["url"])
|
|
52
|
+
manifest, _ = load_bundle(brand, ident)
|
|
53
|
+
if value["public_ready"]:
|
|
54
|
+
# The expected destination comes from trusted local brand config,
|
|
55
|
+
# never from the remote response being authenticated.
|
|
56
|
+
base = (brand.cuentas.get("instagram") or {}).get("media_url_base", "")
|
|
57
|
+
expected = {(public_url(base, a["relative_path"]), a["sha256"], a["size"], a["mime"])
|
|
58
|
+
for a in manifest["assets"]}
|
|
59
|
+
actual = {(a["url"], a["sha256"], a["size"], a["mime"]) for a in value["attestations"]}
|
|
60
|
+
if actual != expected or len(value["attestations"]) != len(manifest["assets"]):
|
|
61
|
+
raise MediaRegistryError("attestation does not match selected assets")
|
|
62
|
+
if not (value["local_ready"] and value["private_ready"] and value["hosted_ready"]):
|
|
63
|
+
raise MediaRegistryError("inconsistent remote state")
|
|
64
|
+
elif value["attestations"]:
|
|
65
|
+
raise MediaRegistryError("inconsistent remote state")
|
|
66
|
+
else:
|
|
67
|
+
raise MediaRegistryError("unsupported remote protocol")
|
|
68
|
+
return value
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _capture(argv, incoming, *, timeout=300):
|
|
72
|
+
"""Drain a bounded stdout pipe and kill/reap SSH on overflow or deadline."""
|
|
73
|
+
process = subprocess.Popen(argv, stdin=incoming, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
|
74
|
+
deadline = time.monotonic() + timeout
|
|
75
|
+
raw = bytearray()
|
|
76
|
+
try:
|
|
77
|
+
with selectors.DefaultSelector() as selector:
|
|
78
|
+
selector.register(process.stdout, selectors.EVENT_READ)
|
|
79
|
+
while True:
|
|
80
|
+
remaining = deadline - time.monotonic()
|
|
81
|
+
if remaining <= 0:
|
|
82
|
+
raise MediaRegistryError("remote response timed out")
|
|
83
|
+
if not selector.select(remaining):
|
|
84
|
+
continue
|
|
85
|
+
chunk = os.read(process.stdout.fileno(), min(65536, MAX_RESPONSE + 1 - len(raw)))
|
|
86
|
+
if not chunk:
|
|
87
|
+
break
|
|
88
|
+
raw.extend(chunk)
|
|
89
|
+
if len(raw) > MAX_RESPONSE:
|
|
90
|
+
raise MediaRegistryError("remote response exceeds the limit")
|
|
91
|
+
if process.wait(timeout=max(0, deadline - time.monotonic())):
|
|
92
|
+
raise MediaRegistryError("remote ingestion failed; verify before retrying")
|
|
93
|
+
return bytes(raw)
|
|
94
|
+
finally:
|
|
95
|
+
# Diagnostics are discarded, never buffered or reflected to the caller.
|
|
96
|
+
if process.poll() is None:
|
|
97
|
+
process.kill()
|
|
98
|
+
process.wait(timeout=5)
|
|
99
|
+
process.stdout.close()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _remote(brand, ident, *, operation, preview_update=False, update_digest=None, public=False):
|
|
103
|
+
if not re.fullmatch(r"[a-f0-9]{64}", ident):
|
|
104
|
+
raise MediaRegistryError("invalid bundle")
|
|
105
|
+
config = RemoteConfig.model_validate_json(relative(brand.raiz, ".socialctl/remote-executor.json").read_bytes())
|
|
106
|
+
component(brand.nombre)
|
|
107
|
+
args = ["media", operation]
|
|
108
|
+
if operation == "verify":
|
|
109
|
+
args += [ident]
|
|
110
|
+
if public:
|
|
111
|
+
args += ["--public"]
|
|
112
|
+
elif operation == "receive":
|
|
113
|
+
if preview_update:
|
|
114
|
+
args += ["--preview-update"]
|
|
115
|
+
if update_digest:
|
|
116
|
+
if not re.fullmatch(r"[a-f0-9]{64}", update_digest) or preview_update:
|
|
117
|
+
raise MediaRegistryError("invalid update digest")
|
|
118
|
+
args += ["--update-digest", update_digest]
|
|
119
|
+
else:
|
|
120
|
+
raise MediaRegistryError("unsupported operation")
|
|
121
|
+
command = shlex.join([config.executable, *args, "--brand", brand.nombre, "--root", config.root])
|
|
122
|
+
argv = ["ssh", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
|
123
|
+
"-o", "ConnectTimeout=15", "-p", str(config.port), "--", f"{config.user}@{config.host}", command]
|
|
124
|
+
# Disk-backed bounded input; output is read incrementally into a capped buffer.
|
|
125
|
+
with tempfile.TemporaryFile() as incoming:
|
|
126
|
+
if operation == "receive":
|
|
127
|
+
write_transfer(brand, ident, incoming)
|
|
128
|
+
incoming.seek(0)
|
|
129
|
+
raw = _capture(argv, incoming)
|
|
130
|
+
return _response(parse_json(raw, limit=MAX_RESPONSE), brand, ident)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _run(operation):
|
|
134
|
+
try:
|
|
135
|
+
result = operation()
|
|
136
|
+
typer.echo(json.dumps(result, ensure_ascii=False, indent=2))
|
|
137
|
+
except MediaRegistryError as exc:
|
|
138
|
+
typer.echo(str(exc))
|
|
139
|
+
raise typer.Exit(1) from None
|
|
140
|
+
except Exception:
|
|
141
|
+
# Even parse errors and remote exceptions can contain supplied paths/secrets.
|
|
142
|
+
typer.echo("Media operation rejected: check sources, manifest, policy, space and post conflicts. Conflicts require --preview-update and its digest; active posts require queue cancellation/reconciliation first.")
|
|
143
|
+
raise typer.Exit(1) from None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@media_app.command("stage")
|
|
147
|
+
def stage(slug: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT)):
|
|
148
|
+
def operation():
|
|
149
|
+
selected = cargar_brand(root, brand)
|
|
150
|
+
manifest = stage_bundle(selected, slug)
|
|
151
|
+
return readiness(selected, manifest["digest"])
|
|
152
|
+
_run(operation)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@media_app.command("transfer")
|
|
156
|
+
def transfer(bundle: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT),
|
|
157
|
+
preview_update: bool = typer.Option(False, "--preview-update"),
|
|
158
|
+
update_digest: str | None = typer.Option(None, "--update-digest")):
|
|
159
|
+
_run(lambda: _remote(cargar_brand(root, brand), bundle, operation="receive",
|
|
160
|
+
preview_update=preview_update, update_digest=update_digest))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@media_app.command("receive", hidden=True)
|
|
164
|
+
def receive(brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT),
|
|
165
|
+
preview_update: bool = typer.Option(False, "--preview-update"),
|
|
166
|
+
update_digest: str | None = typer.Option(None, "--update-digest")):
|
|
167
|
+
_run(lambda: ingest(cargar_brand(root, brand), sys.stdin.buffer,
|
|
168
|
+
preview_update=preview_update, update_digest=update_digest))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@media_app.command("verify")
|
|
172
|
+
def verify(bundle: str, brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT),
|
|
173
|
+
remote: bool = typer.Option(False, "--remote"), public: bool = typer.Option(False, "--public")):
|
|
174
|
+
def operation():
|
|
175
|
+
selected = cargar_brand(root, brand)
|
|
176
|
+
if remote:
|
|
177
|
+
return _remote(selected, bundle, operation="verify", public=public)
|
|
178
|
+
return readiness(selected, bundle, public=public)
|
|
179
|
+
_run(operation)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
from socialctl.media_preflight import register as register_preflight
|
|
183
|
+
register_preflight(media_app, DEFAULT_ROOT)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Bounded binary ingestion into server-controlled brand policy roots."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import struct
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from socialctl.hosted_media import attest_public_media, public_url, validate_url
|
|
11
|
+
from socialctl.media_registry import (
|
|
12
|
+
MAX_HEADER, MAX_POST, MediaRegistryError, bundle_path, canonical, check_file,
|
|
13
|
+
copy_exact, digest, load_bundle, parse_json, post_media, promote, publication_gate, relative, safe, space, validate_manifest,
|
|
14
|
+
)
|
|
15
|
+
from socialctl.migration_files import durable_write, write_json
|
|
16
|
+
from socialctl.scheduler import ScheduleStore, now_utc
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def policy_for(brand) -> dict:
|
|
20
|
+
try:
|
|
21
|
+
policy = json.loads(relative(brand.raiz, ".socialctl/media-policy.json").read_bytes())
|
|
22
|
+
if (set(policy) != {"version", "brand", "private_root", "public_root", "public_url_base"}
|
|
23
|
+
or type(policy["version"]) is not int or policy["version"] != 1
|
|
24
|
+
or policy["brand"] != brand.nombre):
|
|
25
|
+
raise ValueError()
|
|
26
|
+
private, public = Path(policy["private_root"]), Path(policy["public_root"])
|
|
27
|
+
if (not private.is_absolute() or not public.is_absolute() or ".." in public.parts
|
|
28
|
+
or private != brand.raiz / "media" or public == Path("/")
|
|
29
|
+
or private == public or private in public.parents or public in private.parents):
|
|
30
|
+
raise ValueError()
|
|
31
|
+
safe(private)
|
|
32
|
+
safe(public)
|
|
33
|
+
if not public.is_dir() or public.stat().st_mode & 0o005 != 0o005:
|
|
34
|
+
raise ValueError()
|
|
35
|
+
validate_url(policy["public_url_base"])
|
|
36
|
+
if (brand.cuentas.get("instagram") or {}).get("media_url_base") != policy["public_url_base"]:
|
|
37
|
+
raise ValueError()
|
|
38
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
39
|
+
raise MediaRegistryError("server media policy is missing or invalid") from exc
|
|
40
|
+
return policy
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def read_exact(stream, count: int) -> bytes:
|
|
44
|
+
result = bytearray()
|
|
45
|
+
while len(result) < count:
|
|
46
|
+
chunk = stream.read(count - len(result))
|
|
47
|
+
if not chunk:
|
|
48
|
+
raise MediaRegistryError("truncated transfer")
|
|
49
|
+
result.extend(chunk)
|
|
50
|
+
return bytes(result)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def write_transfer(brand, ident: str, stream) -> dict:
|
|
54
|
+
manifest, post = load_bundle(brand, ident)
|
|
55
|
+
header = canonical(manifest)
|
|
56
|
+
if len(header) > MAX_HEADER:
|
|
57
|
+
raise MediaRegistryError("manifest is too large")
|
|
58
|
+
# Revalidate all selected local assets before sending even the header.
|
|
59
|
+
for item in manifest["assets"]:
|
|
60
|
+
check_file(relative(brand.raiz / "media", item["relative_path"]), item)
|
|
61
|
+
stream.write(struct.pack("!I", len(header)))
|
|
62
|
+
stream.write(header)
|
|
63
|
+
stream.write(post)
|
|
64
|
+
for item in manifest["assets"]:
|
|
65
|
+
with relative(brand.raiz / "media", item["relative_path"]).open("rb") as source:
|
|
66
|
+
copy_exact(source, stream, item["size"])
|
|
67
|
+
return manifest
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _post_matches(manifest: dict, raw: bytes) -> None:
|
|
71
|
+
if len(raw) != manifest["post_size"] or digest(raw) != manifest["post_sha256"]:
|
|
72
|
+
raise MediaRegistryError("transferred post was modified")
|
|
73
|
+
referenced = {name: set() for name in (a["relative_path"] for a in manifest["assets"])}
|
|
74
|
+
for platform, paths in post_media(raw).items():
|
|
75
|
+
for path in paths:
|
|
76
|
+
if path not in referenced:
|
|
77
|
+
raise MediaRegistryError("post references media outside the manifest")
|
|
78
|
+
referenced[path].add(manifest["slug"] + "/" + platform)
|
|
79
|
+
if any(referenced[item["relative_path"]] != set(item["uses"]) for item in manifest["assets"]):
|
|
80
|
+
raise MediaRegistryError("manifest usages do not match the post")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _inactive_draft(brand, slug: str, store: ScheduleStore) -> None:
|
|
84
|
+
entries = [entry for entry in store.load() if entry.slug == slug]
|
|
85
|
+
if any(entry.status == "published" or entry.platform_id for entry in entries):
|
|
86
|
+
raise MediaRegistryError("post has publication evidence in the queue; use a new slug")
|
|
87
|
+
if any(e.status not in {"cancelled", "error"} for e in entries):
|
|
88
|
+
raise MediaRegistryError("post is protected by an active queue; cancel/reconcile and prepare again before editing")
|
|
89
|
+
if relative(brand.raiz, f".socialctl/media-publication-started/{slug}.json").exists():
|
|
90
|
+
raise MediaRegistryError("post has a recorded publication start; use a new slug")
|
|
91
|
+
# Published or uncertain media is not an inactive draft. Fail closed on broken journals.
|
|
92
|
+
from socialctl.publication_steps import retry_media_blockers
|
|
93
|
+
from socialctl.models import Platform
|
|
94
|
+
if retry_media_blockers(brand, slug, list(Platform)):
|
|
95
|
+
raise MediaRegistryError("post has a previous or uncertain publication; reconciliation required")
|
|
96
|
+
if relative(brand.raiz, f"posts/{slug}/resultado.json").exists():
|
|
97
|
+
raise MediaRegistryError("post has a publication result; it is not an inactive draft")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _update_preview(brand, manifest, existing, proposed, store):
|
|
101
|
+
_inactive_draft(brand, manifest["slug"], store)
|
|
102
|
+
fingerprint = digest(canonical(dict(brand=brand.nombre, bundle=manifest["digest"],
|
|
103
|
+
old_sha256=digest(existing), new_sha256=digest(proposed))))
|
|
104
|
+
# Complete before/after text, without context-line truncation.
|
|
105
|
+
preview = "CURRENT POST\n" + existing.decode("utf-8") + "\nPROPOSED POST\n" + proposed.decode("utf-8")
|
|
106
|
+
return dict(protocol="socialctl.media-update.v1", bundle=manifest["digest"],
|
|
107
|
+
preview=preview, update_digest=fingerprint)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def receive(brand, stream, *, preview_update=False, update_digest=None) -> dict:
|
|
111
|
+
policy = policy_for(brand)
|
|
112
|
+
if preview_update and update_digest:
|
|
113
|
+
raise MediaRegistryError("preview does not support update approval")
|
|
114
|
+
length = struct.unpack("!I", read_exact(stream, 4))[0]
|
|
115
|
+
if not 0 < length <= MAX_HEADER:
|
|
116
|
+
raise MediaRegistryError("header exceeds the limit")
|
|
117
|
+
manifest = validate_manifest(brand, parse_json(read_exact(stream, length)))
|
|
118
|
+
post = read_exact(stream, manifest["post_size"])
|
|
119
|
+
_post_matches(manifest, post)
|
|
120
|
+
size = sum(item["size"] for item in manifest["assets"])
|
|
121
|
+
# The staging area and final private copy may coexist during promotion.
|
|
122
|
+
space(brand.raiz, size * 2 + len(post))
|
|
123
|
+
space(Path(policy["public_root"]), size)
|
|
124
|
+
inbox = relative(brand.raiz, ".socialctl/media-incoming")
|
|
125
|
+
inbox.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
126
|
+
with tempfile.TemporaryDirectory(prefix="transfer-", dir=inbox) as temporary:
|
|
127
|
+
pending = Path(temporary)
|
|
128
|
+
for index, item in enumerate(manifest["assets"]):
|
|
129
|
+
target = pending / str(index)
|
|
130
|
+
with target.open("xb") as handle:
|
|
131
|
+
remaining = item["size"]
|
|
132
|
+
while remaining:
|
|
133
|
+
chunk = read_exact(stream, min(remaining, 1024 * 1024))
|
|
134
|
+
handle.write(chunk)
|
|
135
|
+
remaining -= len(chunk)
|
|
136
|
+
handle.flush()
|
|
137
|
+
os.fsync(handle.fileno())
|
|
138
|
+
check_file(target, item)
|
|
139
|
+
if stream.read(1):
|
|
140
|
+
raise MediaRegistryError("extra bytes or frames are not supported")
|
|
141
|
+
# No canonical asset path exists until every frame and EOF are verified.
|
|
142
|
+
store = ScheduleStore(brand.raiz)
|
|
143
|
+
for path in (store.executor_lock_path, store.mutation_lock_path, store.path, store.database_path):
|
|
144
|
+
safe(path)
|
|
145
|
+
with store.executor_lock(), publication_gate(brand, manifest["slug"]), store._mutation_lock():
|
|
146
|
+
# Recheck server policy and existing bytes under authoritative locks.
|
|
147
|
+
if policy_for(brand) != policy:
|
|
148
|
+
raise MediaRegistryError("policy changed during transfer")
|
|
149
|
+
if bundle_path(brand, manifest["digest"]).exists():
|
|
150
|
+
load_bundle(brand, manifest["digest"])
|
|
151
|
+
destination = relative(brand.raiz, f"posts/{manifest['slug']}/post.yml")
|
|
152
|
+
existing = destination.read_bytes() if destination.exists() else None
|
|
153
|
+
if existing != post:
|
|
154
|
+
_inactive_draft(brand, manifest["slug"], store)
|
|
155
|
+
conflict = existing is not None and existing != post
|
|
156
|
+
if conflict:
|
|
157
|
+
preview = _update_preview(brand, manifest, existing, post, store)
|
|
158
|
+
if preview_update:
|
|
159
|
+
return preview
|
|
160
|
+
if update_digest != preview["update_digest"]:
|
|
161
|
+
raise MediaRegistryError("existing post differs; requires --preview-update and its --update-digest")
|
|
162
|
+
elif preview_update or update_digest:
|
|
163
|
+
raise MediaRegistryError("there is no text conflict to update")
|
|
164
|
+
for item in manifest["assets"]:
|
|
165
|
+
for root in (Path(policy["private_root"]), Path(policy["public_root"])):
|
|
166
|
+
target = relative(root, item["relative_path"])
|
|
167
|
+
if target.exists():
|
|
168
|
+
check_file(target, item)
|
|
169
|
+
for index, item in enumerate(manifest["assets"]):
|
|
170
|
+
promote(pending / str(index), relative(Path(policy["private_root"]), item["relative_path"]), item)
|
|
171
|
+
promote(pending / str(index), relative(Path(policy["public_root"]), item["relative_path"]), item, public=True)
|
|
172
|
+
if conflict:
|
|
173
|
+
backup = relative(brand.raiz, f".socialctl/media-post-backups/{manifest['slug']}/{digest(existing)}.yml")
|
|
174
|
+
if backup.exists() and backup.read_bytes() != existing:
|
|
175
|
+
raise MediaRegistryError("existing backup was modified")
|
|
176
|
+
if not backup.exists():
|
|
177
|
+
durable_write(backup, existing)
|
|
178
|
+
if existing != post:
|
|
179
|
+
durable_write(destination, post)
|
|
180
|
+
durable_write(bundle_path(brand, manifest["digest"], ".yml"), post)
|
|
181
|
+
write_json(bundle_path(brand, manifest["digest"]), manifest)
|
|
182
|
+
return verify(brand, manifest["digest"])
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def verify(brand, ident: str, *, public=False, client=None) -> dict:
|
|
186
|
+
manifest, post = load_bundle(brand, ident)
|
|
187
|
+
_post_matches(manifest, post)
|
|
188
|
+
result = dict(protocol="socialctl.media-readiness.v1", brand=brand.nombre, bundle=ident,
|
|
189
|
+
local_ready=True, private_ready=False, hosted_ready=False, public_ready=False,
|
|
190
|
+
checked_at=now_utc().isoformat(), attestations=[])
|
|
191
|
+
for item in manifest["assets"]:
|
|
192
|
+
check_file(relative(brand.raiz / "media", item["relative_path"]), item)
|
|
193
|
+
policy_path = relative(brand.raiz, ".socialctl/media-policy.json")
|
|
194
|
+
if policy_path.exists():
|
|
195
|
+
policy = policy_for(brand)
|
|
196
|
+
result["private_ready"] = True
|
|
197
|
+
for item in manifest["assets"]:
|
|
198
|
+
hosted = relative(Path(policy["public_root"]), item["relative_path"])
|
|
199
|
+
check_file(hosted, item)
|
|
200
|
+
if hosted.stat().st_mode & 0o444 != 0o444:
|
|
201
|
+
raise MediaRegistryError("public copy is unreadable")
|
|
202
|
+
if public:
|
|
203
|
+
result["attestations"].append(attest_public_media(
|
|
204
|
+
relative(brand.raiz / "media", item["relative_path"]),
|
|
205
|
+
public_url(policy["public_url_base"], item["relative_path"]), client=client))
|
|
206
|
+
result["hosted_ready"] = True
|
|
207
|
+
result["public_ready"] = public
|
|
208
|
+
elif public:
|
|
209
|
+
raise MediaRegistryError("public verification requires a server policy")
|
|
210
|
+
write_json(relative(brand.raiz, f".socialctl/media-readiness/{ident}.json"), result)
|
|
211
|
+
return result
|