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,1118 @@
|
|
|
1
|
+
"""Durable manual Facebook Groups queue. The retired Groups API is not used; approval prepares a package, and only user confirmation after browser publication completes it."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import uuid
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import BinaryIO, Literal, NamedTuple
|
|
13
|
+
from urllib.parse import parse_qs, urlsplit, urlunsplit
|
|
14
|
+
|
|
15
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
16
|
+
|
|
17
|
+
from socialctl.hosted_media import file_digest
|
|
18
|
+
from socialctl.management.changes import ApprovalMismatch, ChangeError, ChangeStore, now_utc
|
|
19
|
+
from socialctl.media import MediaInvalida, _ffprobe, _rotacion_grados
|
|
20
|
+
from socialctl.rutas import validar_ruta_relativa
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GroupError(ChangeError):
|
|
24
|
+
"""Readable error for a manual Group proposal."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
CONFIRMATION_PHRASE = "I CONFIRM MANUAL PUBLICATION"
|
|
28
|
+
LEGACY_CONFIRMATION_PHRASE = "CONFIRMO PUBLICADO MANUALMENTE"
|
|
29
|
+
CAPABILITY = "facebook_groups_api_removed_manual_browser_handoff"
|
|
30
|
+
_GROUP_SEGMENT = re.compile(r"^[A-Za-z0-9._-]{1,200}$")
|
|
31
|
+
_POST_SEGMENT = re.compile(r"^[A-Za-z0-9._-]{1,300}$")
|
|
32
|
+
_YOUTUBE_ID = re.compile(r"^[A-Za-z0-9_-]{11}$")
|
|
33
|
+
_SECRET_PATTERNS = (
|
|
34
|
+
re.compile(
|
|
35
|
+
r"(?i)\b(?:access[_ -]?token|client[_ -]?secret|api[_ -]?key|authorization)"
|
|
36
|
+
r"\s*[:=]\s*[^\s,;]{6,}"
|
|
37
|
+
),
|
|
38
|
+
re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._~+/-]{8,}"),
|
|
39
|
+
re.compile(r"\b(?:sk-|gh[pousr]_|xox[baprs]-)[A-Za-z0-9_-]{12,}"),
|
|
40
|
+
re.compile(r"\bEA[A-Za-z0-9]{20,}"),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _aware(value: datetime, field: str) -> datetime:
|
|
45
|
+
if value.utcoffset() is None:
|
|
46
|
+
raise GroupError(f"{field} must include a timezone")
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _plain_text(value: str, field: str, *, maximum: int) -> str:
|
|
51
|
+
if not isinstance(value, str) or not value.strip() or value != value.strip():
|
|
52
|
+
raise GroupError(f"{field} must be nonempty text without surrounding whitespace")
|
|
53
|
+
if len(value) > maximum:
|
|
54
|
+
raise GroupError(f"{field} exceeds local limit of {maximum} characters")
|
|
55
|
+
if any(ord(char) < 32 and char not in "\n\t" for char in value):
|
|
56
|
+
raise GroupError(f"{field} contains control characters")
|
|
57
|
+
if any(pattern.search(value) for pattern in _SECRET_PATTERNS):
|
|
58
|
+
raise GroupError(f"{field} may contain a secret or credential; rejected")
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _safe_https_parts(value: str, field: str):
|
|
63
|
+
value = _plain_text(value, field, maximum=2048)
|
|
64
|
+
try:
|
|
65
|
+
parsed = urlsplit(value)
|
|
66
|
+
port = parsed.port
|
|
67
|
+
except ValueError:
|
|
68
|
+
raise GroupError(f"{field} is not a valid URL") from None
|
|
69
|
+
if parsed.scheme != "https" or not parsed.hostname:
|
|
70
|
+
raise GroupError(f"{field} must be a public HTTPS URL")
|
|
71
|
+
if parsed.username is not None or parsed.password is not None or port is not None:
|
|
72
|
+
raise GroupError(f"{field} does not accept credentials or ports")
|
|
73
|
+
if parsed.fragment:
|
|
74
|
+
raise GroupError(f"{field} does not accept fragments")
|
|
75
|
+
return parsed
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def validate_group_url(value: str) -> tuple[str, str]:
|
|
79
|
+
"""Return canonical Group URL and exact slug/ID."""
|
|
80
|
+
parsed = _safe_https_parts(value, "group_url")
|
|
81
|
+
host = (parsed.hostname or "").lower()
|
|
82
|
+
if host not in {"facebook.com", "www.facebook.com", "m.facebook.com"}:
|
|
83
|
+
raise GroupError("group_url must point to a public Group on facebook.com")
|
|
84
|
+
if parsed.query:
|
|
85
|
+
raise GroupError("group_url does not accept query parameters; remove tracking or credentials")
|
|
86
|
+
parts = [part for part in parsed.path.split("/") if part]
|
|
87
|
+
if len(parts) != 2 or parts[0].lower() != "groups" or not _GROUP_SEGMENT.fullmatch(parts[1]):
|
|
88
|
+
raise GroupError("group_url must have the form https://www.facebook.com/groups/GROUP")
|
|
89
|
+
canonical = urlunsplit(("https", "www.facebook.com", f"/groups/{parts[1]}", "", ""))
|
|
90
|
+
return canonical, parts[1]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def validate_youtube_url(value: str) -> tuple[str, str]:
|
|
94
|
+
"""Accept canonical long-form video links, never API endpoints."""
|
|
95
|
+
parsed = _safe_https_parts(value, "youtube_url")
|
|
96
|
+
host = (parsed.hostname or "").lower()
|
|
97
|
+
video_id: str | None = None
|
|
98
|
+
if host in {"youtube.com", "www.youtube.com", "m.youtube.com"}:
|
|
99
|
+
if parsed.path != "/watch":
|
|
100
|
+
raise GroupError("youtube_url must point to /watch?v=VIDEO_ID")
|
|
101
|
+
query = parse_qs(parsed.query, keep_blank_values=True)
|
|
102
|
+
if set(query) != {"v"} or len(query["v"]) != 1:
|
|
103
|
+
raise GroupError("youtube_url accepts only the v parameter; remove tracking or credentials")
|
|
104
|
+
video_id = query["v"][0]
|
|
105
|
+
elif host == "youtu.be":
|
|
106
|
+
if parsed.query:
|
|
107
|
+
raise GroupError("short youtube_url does not accept parameters")
|
|
108
|
+
parts = [part for part in parsed.path.split("/") if part]
|
|
109
|
+
if len(parts) != 1:
|
|
110
|
+
raise GroupError("short youtube_url must have the form https://youtu.be/VIDEO_ID")
|
|
111
|
+
video_id = parts[0]
|
|
112
|
+
else:
|
|
113
|
+
raise GroupError("youtube_url must use youtube.com or youtu.be; private endpoints are not accepted")
|
|
114
|
+
if not _YOUTUBE_ID.fullmatch(video_id or ""):
|
|
115
|
+
raise GroupError("youtube_url does not contain a valid YouTube video ID")
|
|
116
|
+
return f"https://www.youtube.com/watch?v={video_id}", video_id
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def validate_post_url(value: str, expected_group_key: str) -> str:
|
|
120
|
+
parsed = _safe_https_parts(value, "post_url")
|
|
121
|
+
if (parsed.hostname or "").lower() not in {"facebook.com", "www.facebook.com", "m.facebook.com"}:
|
|
122
|
+
raise GroupError("post_url must point to facebook.com")
|
|
123
|
+
if parsed.query:
|
|
124
|
+
raise GroupError("post_url does not accept query parameters; remove tracking or credentials")
|
|
125
|
+
parts = [part for part in parsed.path.split("/") if part]
|
|
126
|
+
if (
|
|
127
|
+
len(parts) != 4
|
|
128
|
+
or parts[0].lower() != "groups"
|
|
129
|
+
or parts[1] != expected_group_key
|
|
130
|
+
or parts[2].lower() not in {"posts", "permalink"}
|
|
131
|
+
or not _POST_SEGMENT.fullmatch(parts[3])
|
|
132
|
+
):
|
|
133
|
+
raise GroupError("post_url must be a post/permalink URL from the same approved Group")
|
|
134
|
+
return urlunsplit(("https", "www.facebook.com", "/" + "/".join(parts), "", ""))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class GroupDestination(BaseModel):
|
|
138
|
+
model_config = ConfigDict(extra="forbid")
|
|
139
|
+
|
|
140
|
+
name: str
|
|
141
|
+
url: str
|
|
142
|
+
key: str
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class SuggestedWindow(BaseModel):
|
|
146
|
+
model_config = ConfigDict(extra="forbid")
|
|
147
|
+
|
|
148
|
+
start: datetime
|
|
149
|
+
end: datetime
|
|
150
|
+
|
|
151
|
+
@model_validator(mode="after")
|
|
152
|
+
def validate_window(self):
|
|
153
|
+
_aware(self.start, "window_start")
|
|
154
|
+
_aware(self.end, "window_end")
|
|
155
|
+
if self.end <= self.start:
|
|
156
|
+
raise ValueError("window_end must be after window_start")
|
|
157
|
+
return self
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class GroupMedia(BaseModel):
|
|
161
|
+
model_config = ConfigDict(extra="forbid")
|
|
162
|
+
|
|
163
|
+
relative_path: str
|
|
164
|
+
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
|
165
|
+
size_bytes: int = Field(gt=0)
|
|
166
|
+
kind: Literal["image", "video"]
|
|
167
|
+
width: int | None = None
|
|
168
|
+
height: int | None = None
|
|
169
|
+
duration_s: float | None = None
|
|
170
|
+
|
|
171
|
+
@model_validator(mode="after")
|
|
172
|
+
def validate_visual_metadata(self):
|
|
173
|
+
if (
|
|
174
|
+
not isinstance(self.width, int)
|
|
175
|
+
or not isinstance(self.height, int)
|
|
176
|
+
or self.width <= 0
|
|
177
|
+
or self.height <= 0
|
|
178
|
+
):
|
|
179
|
+
raise ValueError("Group media requires positive visual dimensions")
|
|
180
|
+
if self.kind == "image" and self.duration_s is not None:
|
|
181
|
+
raise ValueError("Group image does not accept duration")
|
|
182
|
+
if self.kind == "video" and (
|
|
183
|
+
self.duration_s is None or self.duration_s <= 0
|
|
184
|
+
):
|
|
185
|
+
raise ValueError("Group video requires positive duration")
|
|
186
|
+
return self
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class GroupEvidence(BaseModel):
|
|
190
|
+
model_config = ConfigDict(extra="forbid")
|
|
191
|
+
|
|
192
|
+
relative_path: str
|
|
193
|
+
sha256: str = Field(pattern=r"^[a-f0-9]{64}$")
|
|
194
|
+
size_bytes: int = Field(gt=0)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class GroupConfirmation(BaseModel):
|
|
198
|
+
model_config = ConfigDict(extra="forbid")
|
|
199
|
+
|
|
200
|
+
authority: Literal["user_supplied_manual_confirmation"] = "user_supplied_manual_confirmation"
|
|
201
|
+
confirmed_at: datetime
|
|
202
|
+
post_url: str | None = None
|
|
203
|
+
evidence: GroupEvidence | None = None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class GroupChange(BaseModel):
|
|
207
|
+
model_config = ConfigDict(extra="forbid", populate_by_name=True, serialize_by_alias=True)
|
|
208
|
+
|
|
209
|
+
id: str
|
|
210
|
+
version: Literal[1] = 1
|
|
211
|
+
kind: Literal["facebook-group-manual"] = "facebook-group-manual"
|
|
212
|
+
brand: str
|
|
213
|
+
brand_root: str
|
|
214
|
+
destination: GroupDestination
|
|
215
|
+
copy_text: str = Field(alias="copy", serialization_alias="copy")
|
|
216
|
+
youtube_url: str
|
|
217
|
+
youtube_video_id: str
|
|
218
|
+
media: GroupMedia | None = None
|
|
219
|
+
suggested_window: SuggestedWindow
|
|
220
|
+
capability: Literal["facebook_groups_api_removed_manual_browser_handoff"] = CAPABILITY
|
|
221
|
+
dedupe_key: str
|
|
222
|
+
created_at: datetime
|
|
223
|
+
updated_at: datetime
|
|
224
|
+
fingerprint: str = ""
|
|
225
|
+
status: Literal[
|
|
226
|
+
"prepared", "approved", "handoff_ready", "awaiting_manual_confirmation", "confirmed_manual"
|
|
227
|
+
] = "prepared"
|
|
228
|
+
approved_at: datetime | None = None
|
|
229
|
+
handoff_opened_at: datetime | None = None
|
|
230
|
+
confirmation: GroupConfirmation | None = None
|
|
231
|
+
last_error: str | None = None
|
|
232
|
+
journal: list[dict] = Field(default_factory=list)
|
|
233
|
+
|
|
234
|
+
@model_validator(mode="after")
|
|
235
|
+
def validate_state(self):
|
|
236
|
+
if self.status == "confirmed_manual" and self.confirmation is None:
|
|
237
|
+
raise ValueError("confirmed_manual requires user confirmation")
|
|
238
|
+
if self.status != "confirmed_manual" and self.confirmation is not None:
|
|
239
|
+
raise ValueError("evidence can only exist after manual confirmation")
|
|
240
|
+
if self.status == "awaiting_manual_confirmation" and self.handoff_opened_at is None:
|
|
241
|
+
raise ValueError("awaiting_manual_confirmation requires an open handoff")
|
|
242
|
+
return self
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
_MUTABLE = {
|
|
246
|
+
"fingerprint", "updated_at", "status", "approved_at", "handoff_opened_at",
|
|
247
|
+
"confirmation", "last_error", "journal",
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def group_fingerprint(change: GroupChange) -> str:
|
|
252
|
+
raw = change.model_dump(mode="json", by_alias=True, exclude=_MUTABLE)
|
|
253
|
+
encoded = json.dumps(raw, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()
|
|
254
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class GroupStore(ChangeStore):
|
|
258
|
+
model_type = GroupChange
|
|
259
|
+
fingerprint_for = staticmethod(group_fingerprint)
|
|
260
|
+
|
|
261
|
+
def __init__(self, brand_root: Path):
|
|
262
|
+
self.root = Path(brand_root) / ".socialctl" / "facebook-groups"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _event(change: GroupChange, name: str, **details) -> None:
|
|
266
|
+
change.updated_at = now_utc()
|
|
267
|
+
change.journal.append({"at": change.updated_at.isoformat(), "event": name, **details})
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _dedupe_payload(
|
|
271
|
+
brand: str, destination: GroupDestination, copy: str, youtube_url: str,
|
|
272
|
+
media: GroupMedia | None, window: SuggestedWindow,
|
|
273
|
+
) -> str:
|
|
274
|
+
raw = {
|
|
275
|
+
"brand": brand,
|
|
276
|
+
"group_url": destination.url,
|
|
277
|
+
"copy": copy,
|
|
278
|
+
"youtube_url": youtube_url,
|
|
279
|
+
"media_sha256": media.sha256 if media else None,
|
|
280
|
+
"window": window.model_dump(mode="json"),
|
|
281
|
+
}
|
|
282
|
+
return hashlib.sha256(
|
|
283
|
+
json.dumps(raw, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()
|
|
284
|
+
).hexdigest()
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _load_bound(brand, store: GroupStore, change_id: str) -> GroupChange:
|
|
288
|
+
change = store.load(change_id)
|
|
289
|
+
if change.brand != brand.nombre or Path(change.brand_root) != brand.raiz.resolve():
|
|
290
|
+
raise GroupError("configured brand no longer matches Group ChangeSet")
|
|
291
|
+
name = _plain_text(change.destination.name, "group_name", maximum=200)
|
|
292
|
+
group_url, group_key = validate_group_url(change.destination.url)
|
|
293
|
+
copy = _plain_text(change.copy_text, "copy", maximum=10_000)
|
|
294
|
+
youtube_url, video_id = validate_youtube_url(change.youtube_url)
|
|
295
|
+
if (
|
|
296
|
+
name != change.destination.name
|
|
297
|
+
or group_url != change.destination.url
|
|
298
|
+
or group_key != change.destination.key
|
|
299
|
+
or copy != change.copy_text
|
|
300
|
+
or youtube_url != change.youtube_url
|
|
301
|
+
or video_id != change.youtube_video_id
|
|
302
|
+
):
|
|
303
|
+
raise GroupError("canonical ChangeSet contract mismatch")
|
|
304
|
+
if change.media is not None:
|
|
305
|
+
relative = change.media.relative_path
|
|
306
|
+
if ".secrets" in Path(relative).parts:
|
|
307
|
+
raise GroupError("persisted media cannot point to .secrets")
|
|
308
|
+
validar_ruta_relativa(
|
|
309
|
+
brand.raiz / "media", relative, GroupError, "persisted Group media"
|
|
310
|
+
)
|
|
311
|
+
if change.confirmation is not None:
|
|
312
|
+
if change.confirmation.confirmed_at.utcoffset() is None:
|
|
313
|
+
raise GroupError("confirmed_at must include a timezone")
|
|
314
|
+
if change.confirmation.post_url is not None:
|
|
315
|
+
canonical_post = validate_post_url(change.confirmation.post_url, group_key)
|
|
316
|
+
if canonical_post != change.confirmation.post_url:
|
|
317
|
+
raise GroupError("persisted confirmed URL is not canonical")
|
|
318
|
+
if change.confirmation.evidence is not None:
|
|
319
|
+
evidence_path = change.confirmation.evidence.relative_path
|
|
320
|
+
if ".secrets" in Path(evidence_path).parts:
|
|
321
|
+
raise GroupError("persisted evidence cannot point to .secrets")
|
|
322
|
+
validar_ruta_relativa(brand.raiz, evidence_path, GroupError, "persisted evidence")
|
|
323
|
+
expected = _dedupe_payload(
|
|
324
|
+
change.brand, change.destination, change.copy_text, change.youtube_url,
|
|
325
|
+
change.media, change.suggested_window,
|
|
326
|
+
)
|
|
327
|
+
if not hmac.compare_digest(change.dedupe_key, expected):
|
|
328
|
+
raise GroupError("ChangeSet idempotency key mismatch")
|
|
329
|
+
return change
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def load_group(brand, store: GroupStore, change_id: str) -> GroupChange:
|
|
333
|
+
"""Public load with verified brand binding and idempotency key."""
|
|
334
|
+
return _load_bound(brand, store, change_id)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _media(brand, relative: str | None) -> GroupMedia | None:
|
|
338
|
+
if relative is None:
|
|
339
|
+
return None
|
|
340
|
+
if ".secrets" in Path(relative).parts:
|
|
341
|
+
raise GroupError("--media cannot point to .secrets")
|
|
342
|
+
path = validar_ruta_relativa(brand.raiz / "media", relative, GroupError, "Group media")
|
|
343
|
+
if path.is_symlink():
|
|
344
|
+
raise GroupError("Group media must be a regular file, not a symlink")
|
|
345
|
+
try:
|
|
346
|
+
resolved = path.resolve(strict=True)
|
|
347
|
+
except OSError as exc:
|
|
348
|
+
raise GroupError(f"failed to read Group media: {exc}") from None
|
|
349
|
+
if not resolved.is_file():
|
|
350
|
+
raise GroupError("Group media must be an existing regular file")
|
|
351
|
+
try:
|
|
352
|
+
kind, width, height, duration = _probe_visual_file(resolved, evidence=False)
|
|
353
|
+
except GroupError as exc:
|
|
354
|
+
raise GroupError(f"invalid Group media: {exc}") from None
|
|
355
|
+
return GroupMedia(
|
|
356
|
+
relative_path=relative,
|
|
357
|
+
sha256=file_digest(resolved),
|
|
358
|
+
size_bytes=resolved.stat().st_size,
|
|
359
|
+
kind=kind,
|
|
360
|
+
width=width,
|
|
361
|
+
height=height,
|
|
362
|
+
duration_s=duration,
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _verify_media_unchanged(brand, media: GroupMedia | None) -> None:
|
|
367
|
+
if media is None:
|
|
368
|
+
return
|
|
369
|
+
current = _media(brand, media.relative_path)
|
|
370
|
+
if current is None or current.model_dump() != media.model_dump():
|
|
371
|
+
raise GroupError("media changed since preview; prepare a new ChangeSet")
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _iter_changes(store: GroupStore):
|
|
375
|
+
if not store.root.exists():
|
|
376
|
+
return
|
|
377
|
+
for path in sorted(store.root.glob("*.json")):
|
|
378
|
+
yield store.load(path.stem)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def prepare_group(
|
|
382
|
+
brand,
|
|
383
|
+
store: GroupStore,
|
|
384
|
+
*,
|
|
385
|
+
group_name: str,
|
|
386
|
+
group_url: str,
|
|
387
|
+
copy: str,
|
|
388
|
+
youtube_url: str,
|
|
389
|
+
window_start: datetime,
|
|
390
|
+
window_end: datetime,
|
|
391
|
+
media: str | None = None,
|
|
392
|
+
) -> GroupChange:
|
|
393
|
+
name = _plain_text(group_name, "group_name", maximum=200)
|
|
394
|
+
text = _plain_text(copy, "copy", maximum=10_000)
|
|
395
|
+
canonical_group, group_key = validate_group_url(group_url)
|
|
396
|
+
canonical_youtube, video_id = validate_youtube_url(youtube_url)
|
|
397
|
+
try:
|
|
398
|
+
window = SuggestedWindow(start=window_start, end=window_end)
|
|
399
|
+
except ValueError as exc:
|
|
400
|
+
raise GroupError(str(exc)) from None
|
|
401
|
+
destination = GroupDestination(name=name, url=canonical_group, key=group_key)
|
|
402
|
+
supplied_media = _media(brand, media)
|
|
403
|
+
key = _dedupe_payload(brand.nombre, destination, text, canonical_youtube, supplied_media, window)
|
|
404
|
+
lock_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f"facebook-group:{brand.raiz.resolve()}:{key}"))
|
|
405
|
+
with store.apply_lock(lock_id):
|
|
406
|
+
for other in _iter_changes(store):
|
|
407
|
+
if hmac.compare_digest(other.dedupe_key, key):
|
|
408
|
+
raise GroupError(
|
|
409
|
+
f"duplicate proposal: ChangeSet {other.id} already exists with status {other.status}"
|
|
410
|
+
)
|
|
411
|
+
moment = now_utc()
|
|
412
|
+
change = GroupChange(
|
|
413
|
+
id=str(uuid.uuid4()),
|
|
414
|
+
brand=brand.nombre,
|
|
415
|
+
brand_root=str(brand.raiz.resolve()),
|
|
416
|
+
destination=destination,
|
|
417
|
+
copy_text=text,
|
|
418
|
+
youtube_url=canonical_youtube,
|
|
419
|
+
youtube_video_id=video_id,
|
|
420
|
+
media=supplied_media,
|
|
421
|
+
suggested_window=window,
|
|
422
|
+
dedupe_key=key,
|
|
423
|
+
created_at=moment,
|
|
424
|
+
updated_at=moment,
|
|
425
|
+
)
|
|
426
|
+
change.fingerprint = group_fingerprint(change)
|
|
427
|
+
_event(change, "prepared_local_no_api_write")
|
|
428
|
+
store.save(change)
|
|
429
|
+
return change
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def approve_handoff(brand, store: GroupStore, change_id: str, approval_digest: str) -> GroupChange:
|
|
433
|
+
"""Approve local package without browser opening or network access."""
|
|
434
|
+
with store.apply_lock(change_id):
|
|
435
|
+
change = _load_bound(brand, store, change_id)
|
|
436
|
+
if not isinstance(approval_digest, str) or not hmac.compare_digest(
|
|
437
|
+
approval_digest.encode(), change.fingerprint.encode()
|
|
438
|
+
):
|
|
439
|
+
raise ApprovalMismatch("approval does not match exact proposal fingerprint")
|
|
440
|
+
if change.status == "handoff_ready":
|
|
441
|
+
_verify_media_unchanged(brand, change.media)
|
|
442
|
+
return change
|
|
443
|
+
if change.status in {"awaiting_manual_confirmation", "confirmed_manual"}:
|
|
444
|
+
return change
|
|
445
|
+
if change.status not in {"prepared", "approved"}:
|
|
446
|
+
raise GroupError(f"ChangeSet status is {change.status}")
|
|
447
|
+
_verify_media_unchanged(brand, change.media)
|
|
448
|
+
if change.status == "prepared":
|
|
449
|
+
change.status = "approved"
|
|
450
|
+
change.approved_at = now_utc()
|
|
451
|
+
_event(change, "approved_exact_digest")
|
|
452
|
+
store.save(change)
|
|
453
|
+
change.status = "handoff_ready"
|
|
454
|
+
change.last_error = None
|
|
455
|
+
_event(change, "browser_handoff_ready_no_publication")
|
|
456
|
+
store.save(change)
|
|
457
|
+
return change
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def mark_handoff_opened(brand, store: GroupStore, change_id: str) -> GroupChange:
|
|
461
|
+
"""Record browser opening without claiming a post exists."""
|
|
462
|
+
with store.apply_lock(change_id):
|
|
463
|
+
change = _load_bound(brand, store, change_id)
|
|
464
|
+
if change.status in {"awaiting_manual_confirmation", "confirmed_manual"}:
|
|
465
|
+
return change
|
|
466
|
+
if change.status != "handoff_ready":
|
|
467
|
+
raise GroupError("handoff must be approved before opening browser")
|
|
468
|
+
_verify_media_unchanged(brand, change.media)
|
|
469
|
+
change.handoff_opened_at = now_utc()
|
|
470
|
+
change.status = "awaiting_manual_confirmation"
|
|
471
|
+
change.last_error = None
|
|
472
|
+
_event(change, "browser_opened_no_publication_claim")
|
|
473
|
+
store.save(change)
|
|
474
|
+
return change
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def record_handoff_error(brand, store: GroupStore, change_id: str, message: str) -> GroupChange:
|
|
478
|
+
with store.apply_lock(change_id):
|
|
479
|
+
change = _load_bound(brand, store, change_id)
|
|
480
|
+
if change.status != "handoff_ready":
|
|
481
|
+
return change
|
|
482
|
+
change.last_error = _plain_text(message, "browser error", maximum=500)
|
|
483
|
+
_event(change, "browser_open_failed")
|
|
484
|
+
store.save(change)
|
|
485
|
+
return change
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
_IMAGE_CODECS = {
|
|
489
|
+
".jpg": "mjpeg",
|
|
490
|
+
".jpeg": "mjpeg",
|
|
491
|
+
".png": "png",
|
|
492
|
+
".webp": "webp",
|
|
493
|
+
}
|
|
494
|
+
_IMAGE_DEMUXERS = {
|
|
495
|
+
".jpg": "jpeg_pipe",
|
|
496
|
+
".jpeg": "jpeg_pipe",
|
|
497
|
+
".png": "png_pipe",
|
|
498
|
+
".webp": "webp_pipe",
|
|
499
|
+
}
|
|
500
|
+
_VIDEO_EXTENSIONS = {".mp4", ".mov"}
|
|
501
|
+
_EVIDENCE_EXTENSIONS = {*_IMAGE_CODECS, ".pdf"}
|
|
502
|
+
_PDF_WHITESPACE = b"\x00\t\n\x0c\r "
|
|
503
|
+
_PDF_DELIMITERS = b"()<>[]{}/%"
|
|
504
|
+
_PDF_VERSIONS = {f"%PDF-1.{minor}".encode() for minor in range(8)} | {b"%PDF-2.0"}
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
class _PdfReference(NamedTuple):
|
|
508
|
+
object_number: int
|
|
509
|
+
generation: int
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
class _PdfName(bytes):
|
|
513
|
+
pass
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
class _PdfLexer:
|
|
517
|
+
"""Minimal PDF object lexer; strings and comments never produce keys."""
|
|
518
|
+
|
|
519
|
+
def __init__(self, data: bytes):
|
|
520
|
+
self.data = data
|
|
521
|
+
self.cursor = 0
|
|
522
|
+
self.buffer: list[tuple[str, bytes]] = []
|
|
523
|
+
|
|
524
|
+
def _skip_ignored(self) -> None:
|
|
525
|
+
while self.cursor < len(self.data):
|
|
526
|
+
if self.data[self.cursor] in _PDF_WHITESPACE:
|
|
527
|
+
self.cursor += 1
|
|
528
|
+
continue
|
|
529
|
+
if self.data[self.cursor] != ord("%"):
|
|
530
|
+
return
|
|
531
|
+
self.cursor += 1
|
|
532
|
+
while self.cursor < len(self.data) and self.data[self.cursor] not in b"\r\n":
|
|
533
|
+
self.cursor += 1
|
|
534
|
+
|
|
535
|
+
def _literal_string(self) -> tuple[str, bytes]:
|
|
536
|
+
self.cursor += 1
|
|
537
|
+
depth = 1
|
|
538
|
+
while self.cursor < len(self.data):
|
|
539
|
+
byte = self.data[self.cursor]
|
|
540
|
+
self.cursor += 1
|
|
541
|
+
if byte == ord("\\"):
|
|
542
|
+
if self.cursor < len(self.data):
|
|
543
|
+
if self.data[self.cursor] == ord("\r"):
|
|
544
|
+
self.cursor += 1
|
|
545
|
+
if self.cursor < len(self.data) and self.data[self.cursor] == ord("\n"):
|
|
546
|
+
self.cursor += 1
|
|
547
|
+
else:
|
|
548
|
+
self.cursor += 1
|
|
549
|
+
continue
|
|
550
|
+
if byte == ord("("):
|
|
551
|
+
depth += 1
|
|
552
|
+
elif byte == ord(")"):
|
|
553
|
+
depth -= 1
|
|
554
|
+
if depth == 0:
|
|
555
|
+
return ("string", b"")
|
|
556
|
+
raise GroupError("PDF evidence contains a truncated literal string")
|
|
557
|
+
|
|
558
|
+
def _hex_string(self) -> tuple[str, bytes]:
|
|
559
|
+
self.cursor += 1
|
|
560
|
+
while self.cursor < len(self.data):
|
|
561
|
+
byte = self.data[self.cursor]
|
|
562
|
+
self.cursor += 1
|
|
563
|
+
if byte == ord(">"):
|
|
564
|
+
return ("string", b"")
|
|
565
|
+
raise GroupError("PDF evidence contains a truncated hexadecimal string")
|
|
566
|
+
|
|
567
|
+
def _name(self) -> tuple[str, bytes]:
|
|
568
|
+
self.cursor += 1
|
|
569
|
+
start = self.cursor
|
|
570
|
+
while (
|
|
571
|
+
self.cursor < len(self.data)
|
|
572
|
+
and self.data[self.cursor] not in _PDF_WHITESPACE
|
|
573
|
+
and self.data[self.cursor] not in _PDF_DELIMITERS
|
|
574
|
+
):
|
|
575
|
+
self.cursor += 1
|
|
576
|
+
raw = self.data[start:self.cursor]
|
|
577
|
+
decoded = bytearray()
|
|
578
|
+
index = 0
|
|
579
|
+
while index < len(raw):
|
|
580
|
+
if raw[index] != ord("#"):
|
|
581
|
+
decoded.append(raw[index])
|
|
582
|
+
index += 1
|
|
583
|
+
continue
|
|
584
|
+
if index + 2 >= len(raw):
|
|
585
|
+
raise GroupError("PDF evidence contains an invalid escaped name")
|
|
586
|
+
try:
|
|
587
|
+
decoded.append(int(raw[index + 1:index + 3], 16))
|
|
588
|
+
except ValueError:
|
|
589
|
+
raise GroupError("PDF evidence contains an invalid escaped name") from None
|
|
590
|
+
index += 3
|
|
591
|
+
return ("name", bytes(decoded))
|
|
592
|
+
|
|
593
|
+
def _read(self) -> tuple[str, bytes] | None:
|
|
594
|
+
self._skip_ignored()
|
|
595
|
+
if self.cursor >= len(self.data):
|
|
596
|
+
return None
|
|
597
|
+
byte = self.data[self.cursor]
|
|
598
|
+
if byte == ord("("):
|
|
599
|
+
return self._literal_string()
|
|
600
|
+
if byte == ord("<"):
|
|
601
|
+
if self.data[self.cursor:self.cursor + 2] == b"<<":
|
|
602
|
+
self.cursor += 2
|
|
603
|
+
return ("dict_start", b"<<")
|
|
604
|
+
return self._hex_string()
|
|
605
|
+
if self.data[self.cursor:self.cursor + 2] == b">>":
|
|
606
|
+
self.cursor += 2
|
|
607
|
+
return ("dict_end", b">>")
|
|
608
|
+
if byte == ord("["):
|
|
609
|
+
self.cursor += 1
|
|
610
|
+
return ("array_start", b"[")
|
|
611
|
+
if byte == ord("]"):
|
|
612
|
+
self.cursor += 1
|
|
613
|
+
return ("array_end", b"]")
|
|
614
|
+
if byte == ord("/"):
|
|
615
|
+
return self._name()
|
|
616
|
+
if byte in _PDF_DELIMITERS:
|
|
617
|
+
raise GroupError("PDF evidence contains an unexpected delimiter")
|
|
618
|
+
start = self.cursor
|
|
619
|
+
while (
|
|
620
|
+
self.cursor < len(self.data)
|
|
621
|
+
and self.data[self.cursor] not in _PDF_WHITESPACE
|
|
622
|
+
and self.data[self.cursor] not in _PDF_DELIMITERS
|
|
623
|
+
):
|
|
624
|
+
self.cursor += 1
|
|
625
|
+
return ("word", self.data[start:self.cursor])
|
|
626
|
+
|
|
627
|
+
def peek(self, index: int = 0) -> tuple[str, bytes] | None:
|
|
628
|
+
while len(self.buffer) <= index:
|
|
629
|
+
token = self._read()
|
|
630
|
+
if token is None:
|
|
631
|
+
return None
|
|
632
|
+
self.buffer.append(token)
|
|
633
|
+
return self.buffer[index]
|
|
634
|
+
|
|
635
|
+
def take(self) -> tuple[str, bytes] | None:
|
|
636
|
+
if self.buffer:
|
|
637
|
+
return self.buffer.pop(0)
|
|
638
|
+
return self._read()
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def _pdf_integer(raw: bytes) -> int | None:
|
|
642
|
+
digits = raw[1:] if raw[:1] in {b"+", b"-"} else raw
|
|
643
|
+
if not digits or not digits.isdigit():
|
|
644
|
+
return None
|
|
645
|
+
return int(raw)
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _pdf_has_valid_header(header: bytes) -> bool:
|
|
649
|
+
line_end = min(
|
|
650
|
+
(index for index in (header.find(b"\r"), header.find(b"\n")) if index >= 0),
|
|
651
|
+
default=-1,
|
|
652
|
+
)
|
|
653
|
+
return line_end >= 0 and header[:line_end] in _PDF_VERSIONS
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _pdf_startxref(tail: bytes) -> int | None:
|
|
657
|
+
"""Read closure from code lines, skipping intervening comments."""
|
|
658
|
+
lines = tail.replace(b"\r\n", b"\n").replace(b"\r", b"\n").split(b"\n")
|
|
659
|
+
while lines and not lines[-1].strip():
|
|
660
|
+
lines.pop()
|
|
661
|
+
if not lines or lines.pop().strip() != b"%%EOF":
|
|
662
|
+
return None
|
|
663
|
+
code_lines = []
|
|
664
|
+
while lines and len(code_lines) < 2:
|
|
665
|
+
line = lines.pop().split(b"%", 1)[0].strip()
|
|
666
|
+
if line:
|
|
667
|
+
code_lines.append(line)
|
|
668
|
+
if len(code_lines) != 2 or code_lines[1] != b"startxref":
|
|
669
|
+
return None
|
|
670
|
+
return int(code_lines[0]) if code_lines[0].isdigit() else None
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _pdf_value(lexer: _PdfLexer, *, depth: int = 0):
|
|
674
|
+
if depth >= 256:
|
|
675
|
+
raise GroupError("PDF evidence contains excessively nested objects")
|
|
676
|
+
token = lexer.take()
|
|
677
|
+
if token is None:
|
|
678
|
+
raise GroupError("PDF evidence contains a truncated value")
|
|
679
|
+
kind, raw = token
|
|
680
|
+
if kind == "name":
|
|
681
|
+
return _PdfName(raw)
|
|
682
|
+
if kind == "string":
|
|
683
|
+
return b""
|
|
684
|
+
if kind == "array_start":
|
|
685
|
+
values = []
|
|
686
|
+
while lexer.peek() != ("array_end", b"]"):
|
|
687
|
+
if lexer.peek() is None:
|
|
688
|
+
raise GroupError("PDF evidence contains a truncated array")
|
|
689
|
+
values.append(_pdf_value(lexer, depth=depth + 1))
|
|
690
|
+
lexer.take()
|
|
691
|
+
return values
|
|
692
|
+
if kind == "dict_start":
|
|
693
|
+
dictionary = {}
|
|
694
|
+
while lexer.peek() != ("dict_end", b">>"):
|
|
695
|
+
key = lexer.take()
|
|
696
|
+
if key is None:
|
|
697
|
+
raise GroupError("PDF evidence contains a truncated dictionary")
|
|
698
|
+
if key[0] != "name":
|
|
699
|
+
raise GroupError("PDF evidence contains an invalid dictionary key")
|
|
700
|
+
if key[1] in dictionary:
|
|
701
|
+
raise GroupError("PDF evidence contains a duplicate dictionary key")
|
|
702
|
+
dictionary[key[1]] = _pdf_value(lexer, depth=depth + 1)
|
|
703
|
+
lexer.take()
|
|
704
|
+
return dictionary
|
|
705
|
+
if kind != "word":
|
|
706
|
+
raise GroupError("PDF evidence contains an unexpected value")
|
|
707
|
+
integer = _pdf_integer(raw)
|
|
708
|
+
if integer is not None:
|
|
709
|
+
generation = lexer.peek()
|
|
710
|
+
marker = lexer.peek(1)
|
|
711
|
+
generation_number = (
|
|
712
|
+
_pdf_integer(generation[1])
|
|
713
|
+
if generation and generation[0] == "word"
|
|
714
|
+
else None
|
|
715
|
+
)
|
|
716
|
+
if generation_number is not None and marker == ("word", b"R"):
|
|
717
|
+
lexer.take()
|
|
718
|
+
lexer.take()
|
|
719
|
+
if integer < 0 or generation_number < 0:
|
|
720
|
+
raise GroupError("PDF evidence contains a negative reference")
|
|
721
|
+
return _PdfReference(integer, generation_number)
|
|
722
|
+
return integer
|
|
723
|
+
return raw
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def _validate_jpeg_structure(path: Path) -> None:
|
|
727
|
+
"""Walk JPEG segments through SOS/EOI; MJPEG containers are not accepted."""
|
|
728
|
+
saw_frame = False
|
|
729
|
+
saw_scan = False
|
|
730
|
+
try:
|
|
731
|
+
with path.open("rb") as handle:
|
|
732
|
+
if handle.read(2) != b"\xff\xd8":
|
|
733
|
+
raise GroupError("JPEG image lacks SOI marker")
|
|
734
|
+
while True:
|
|
735
|
+
prefix = handle.read(1)
|
|
736
|
+
if prefix != b"\xff":
|
|
737
|
+
raise GroupError("JPEG image contains invalid segments")
|
|
738
|
+
marker = handle.read(1)
|
|
739
|
+
while marker == b"\xff":
|
|
740
|
+
marker = handle.read(1)
|
|
741
|
+
if not marker:
|
|
742
|
+
raise GroupError("JPEG image is truncated before EOI")
|
|
743
|
+
code = marker[0]
|
|
744
|
+
if code == 0xD9:
|
|
745
|
+
if not saw_frame or not saw_scan or handle.read().strip(b"\x00\t\r\n "):
|
|
746
|
+
raise GroupError("JPEG image lacks complete structure")
|
|
747
|
+
return
|
|
748
|
+
if code in {0x00, 0xD8, 0x01} or 0xD0 <= code <= 0xD7:
|
|
749
|
+
raise GroupError("JPEG image contains a misplaced marker")
|
|
750
|
+
raw_length = handle.read(2)
|
|
751
|
+
if len(raw_length) != 2:
|
|
752
|
+
raise GroupError("JPEG image contains a truncated segment")
|
|
753
|
+
length = int.from_bytes(raw_length, "big")
|
|
754
|
+
if length < 2:
|
|
755
|
+
raise GroupError("JPEG image contains a segment with invalid length")
|
|
756
|
+
if code in {
|
|
757
|
+
0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
|
|
758
|
+
0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
|
|
759
|
+
}:
|
|
760
|
+
saw_frame = True
|
|
761
|
+
if code != 0xDA:
|
|
762
|
+
if len(handle.read(length - 2)) != length - 2:
|
|
763
|
+
raise GroupError("JPEG image contains a truncated segment")
|
|
764
|
+
continue
|
|
765
|
+
|
|
766
|
+
saw_scan = True
|
|
767
|
+
if len(handle.read(length - 2)) != length - 2:
|
|
768
|
+
raise GroupError("JPEG image contains a truncated scan")
|
|
769
|
+
while True:
|
|
770
|
+
byte = handle.read(1)
|
|
771
|
+
if not byte:
|
|
772
|
+
raise GroupError("JPEG image is truncated before EOI")
|
|
773
|
+
if byte != b"\xff":
|
|
774
|
+
continue
|
|
775
|
+
next_byte = handle.read(1)
|
|
776
|
+
while next_byte == b"\xff":
|
|
777
|
+
next_byte = handle.read(1)
|
|
778
|
+
if not next_byte:
|
|
779
|
+
raise GroupError("JPEG image is truncated before EOI")
|
|
780
|
+
next_code = next_byte[0]
|
|
781
|
+
if next_code == 0x00 or 0xD0 <= next_code <= 0xD7:
|
|
782
|
+
continue
|
|
783
|
+
handle.seek(-2, 1)
|
|
784
|
+
break
|
|
785
|
+
except OSError as exc:
|
|
786
|
+
raise GroupError(f"failed to analyze JPEG image: {exc}") from None
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def _decode_first_visual_frame(path: Path, field: str) -> None:
|
|
790
|
+
"""Require ffmpeg to decode one frame; never write or transform media."""
|
|
791
|
+
try:
|
|
792
|
+
subprocess.run(
|
|
793
|
+
[
|
|
794
|
+
"ffmpeg", "-v", "error", "-i", str(path),
|
|
795
|
+
"-map", "0:v:0", "-frames:v", "1", "-f", "null", "-",
|
|
796
|
+
],
|
|
797
|
+
check=True,
|
|
798
|
+
capture_output=True,
|
|
799
|
+
)
|
|
800
|
+
except (subprocess.CalledProcessError, OSError):
|
|
801
|
+
raise GroupError(f"{field} does not contain a decodable image or video track") from None
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def _probe_visual_file(
|
|
805
|
+
path: Path, *, evidence: bool,
|
|
806
|
+
) -> tuple[Literal["image", "video"], int, int, float | None]:
|
|
807
|
+
"""Validate actual extension, container and visual stream using ffprobe/ffmpeg."""
|
|
808
|
+
extension = path.suffix.lower()
|
|
809
|
+
allowed = set(_IMAGE_CODECS) if evidence else {*_IMAGE_CODECS, *_VIDEO_EXTENSIONS}
|
|
810
|
+
if extension not in allowed:
|
|
811
|
+
expected = "JPG, PNG or WebP" if evidence else "JPG, PNG, WebP, MP4 or MOV"
|
|
812
|
+
raise GroupError(f"unsupported format: {expected} required")
|
|
813
|
+
try:
|
|
814
|
+
probe = _ffprobe(path)
|
|
815
|
+
except (MediaInvalida, OSError, ValueError, json.JSONDecodeError) as exc:
|
|
816
|
+
raise GroupError(f"failed to validate actual format of {path.name}: {exc}") from None
|
|
817
|
+
streams = probe.get("streams") or []
|
|
818
|
+
visual = next(
|
|
819
|
+
(
|
|
820
|
+
stream for stream in streams
|
|
821
|
+
if isinstance(stream, dict) and stream.get("codec_type") == "video"
|
|
822
|
+
),
|
|
823
|
+
None,
|
|
824
|
+
)
|
|
825
|
+
if visual is None:
|
|
826
|
+
raise GroupError("file must contain an image or video track; audio-only media is not accepted")
|
|
827
|
+
width = visual.get("width")
|
|
828
|
+
height = visual.get("height")
|
|
829
|
+
if not isinstance(width, int) or not isinstance(height, int) or width <= 0 or height <= 0:
|
|
830
|
+
raise GroupError("visual stream must have positive actual dimensions")
|
|
831
|
+
if _rotacion_grados(visual) % 180 == 90:
|
|
832
|
+
width, height = height, width
|
|
833
|
+
|
|
834
|
+
codec = str(visual.get("codec_name") or "").lower()
|
|
835
|
+
format_name = str((probe.get("format") or {}).get("format_name") or "").lower()
|
|
836
|
+
if extension in _IMAGE_CODECS:
|
|
837
|
+
formats = {item.strip() for item in format_name.split(",") if item.strip()}
|
|
838
|
+
if codec != _IMAGE_CODECS[extension] or _IMAGE_DEMUXERS[extension] not in formats:
|
|
839
|
+
raise GroupError("image extension does not match its actual format")
|
|
840
|
+
if extension in {".jpg", ".jpeg"}:
|
|
841
|
+
_validate_jpeg_structure(path)
|
|
842
|
+
duration = None
|
|
843
|
+
kind: Literal["image", "video"] = "image"
|
|
844
|
+
else:
|
|
845
|
+
if "mp4" not in format_name and "mov" not in format_name:
|
|
846
|
+
raise GroupError("video extension does not match an actual MP4 or MOV container")
|
|
847
|
+
try:
|
|
848
|
+
duration = float((probe.get("format") or {}).get("duration"))
|
|
849
|
+
except (TypeError, ValueError):
|
|
850
|
+
raise GroupError("video must have a verifiable actual duration") from None
|
|
851
|
+
if duration <= 0:
|
|
852
|
+
raise GroupError("video must have a positive actual duration")
|
|
853
|
+
kind = "video"
|
|
854
|
+
_decode_first_visual_frame(path, "the file")
|
|
855
|
+
return kind, width, height, duration
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def _pdf_dictionary(
|
|
859
|
+
handle: BinaryIO,
|
|
860
|
+
offset: int,
|
|
861
|
+
expected: tuple[int, int],
|
|
862
|
+
) -> dict[bytes, object]:
|
|
863
|
+
"""Resolve a classic direct object and lexically parse its dictionary."""
|
|
864
|
+
handle.seek(offset)
|
|
865
|
+
chunk = handle.read(1024 * 1024)
|
|
866
|
+
lexer = _PdfLexer(chunk)
|
|
867
|
+
object_number = _pdf_value(lexer)
|
|
868
|
+
generation = _pdf_value(lexer)
|
|
869
|
+
if (
|
|
870
|
+
not isinstance(object_number, int)
|
|
871
|
+
or not isinstance(generation, int)
|
|
872
|
+
or (object_number, generation) != expected
|
|
873
|
+
or lexer.take() != ("word", b"obj")
|
|
874
|
+
):
|
|
875
|
+
raise GroupError("PDF evidence references a nonexistent object")
|
|
876
|
+
dictionary = _pdf_value(lexer)
|
|
877
|
+
if not isinstance(dictionary, dict):
|
|
878
|
+
raise GroupError("PDF evidence contains an object without a dictionary")
|
|
879
|
+
if lexer.take() != ("word", b"endobj"):
|
|
880
|
+
raise GroupError("PDF evidence contains an object without endobj closure")
|
|
881
|
+
return dictionary
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
def _pdf_classic_xref(
|
|
885
|
+
handle: BinaryIO,
|
|
886
|
+
offset: int,
|
|
887
|
+
) -> tuple[dict[tuple[int, int], int], dict[bytes, object]]:
|
|
888
|
+
"""Parse classic xref subsections and corresponding trailer."""
|
|
889
|
+
handle.seek(offset)
|
|
890
|
+
if handle.readline().strip() != b"xref":
|
|
891
|
+
raise GroupError("PDF evidence does not use a parseable classic xref table")
|
|
892
|
+
entries: dict[tuple[int, int], int] = {}
|
|
893
|
+
while True:
|
|
894
|
+
line = handle.readline()
|
|
895
|
+
if not line:
|
|
896
|
+
raise GroupError("PDF evidence contains a truncated xref table")
|
|
897
|
+
stripped = line.strip()
|
|
898
|
+
if not stripped:
|
|
899
|
+
continue
|
|
900
|
+
if stripped == b"trailer":
|
|
901
|
+
break
|
|
902
|
+
subsection = stripped.split()
|
|
903
|
+
if len(subsection) != 2 or not all(part.isdigit() for part in subsection):
|
|
904
|
+
raise GroupError("PDF evidence contains an invalid xref subsection")
|
|
905
|
+
first, count = map(int, subsection)
|
|
906
|
+
if count > 1_000_000:
|
|
907
|
+
raise GroupError("PDF evidence declares too many objects")
|
|
908
|
+
for object_number in range(first, first + count):
|
|
909
|
+
entry = handle.readline().strip()
|
|
910
|
+
parts = entry.split()
|
|
911
|
+
if (
|
|
912
|
+
len(parts) != 3
|
|
913
|
+
or len(parts[0]) != 10
|
|
914
|
+
or not parts[0].isdigit()
|
|
915
|
+
or len(parts[1]) != 5
|
|
916
|
+
or not parts[1].isdigit()
|
|
917
|
+
or parts[2] not in {b"f", b"n"}
|
|
918
|
+
):
|
|
919
|
+
raise GroupError("PDF evidence contains an invalid xref entry")
|
|
920
|
+
if parts[2] == b"n":
|
|
921
|
+
entries[(object_number, int(parts[1]))] = int(parts[0])
|
|
922
|
+
|
|
923
|
+
lexer = _PdfLexer(handle.read(1024 * 1024))
|
|
924
|
+
trailer = _pdf_value(lexer)
|
|
925
|
+
if not isinstance(trailer, dict):
|
|
926
|
+
raise GroupError("PDF evidence contains a truncated trailer")
|
|
927
|
+
return entries, trailer
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def _pdf_pages(
|
|
931
|
+
handle: BinaryIO,
|
|
932
|
+
xref: dict[tuple[int, int], int],
|
|
933
|
+
reference: tuple[int, int],
|
|
934
|
+
expected_parent: tuple[int, int] | None,
|
|
935
|
+
visiting: set[tuple[int, int]],
|
|
936
|
+
seen: set[tuple[int, int]],
|
|
937
|
+
) -> int:
|
|
938
|
+
"""Walk /Pages tree and count resolvable /Page leaves."""
|
|
939
|
+
if reference in visiting or len(visiting) >= 10_000:
|
|
940
|
+
raise GroupError("PDF evidence contains a cyclic or excessive page tree")
|
|
941
|
+
if reference in seen:
|
|
942
|
+
raise GroupError("PDF evidence contains a duplicate or shared Kid")
|
|
943
|
+
offset = xref.get(reference)
|
|
944
|
+
if offset is None:
|
|
945
|
+
raise GroupError("PDF evidence references a nonexistent page object")
|
|
946
|
+
dictionary = _pdf_dictionary(handle, offset, reference)
|
|
947
|
+
node_type = dictionary.get(b"Type")
|
|
948
|
+
if expected_parent is None and node_type != _PdfName(b"Pages"):
|
|
949
|
+
raise GroupError(
|
|
950
|
+
"PDF evidence Catalog /Pages does not point to a /Type /Pages dictionary"
|
|
951
|
+
)
|
|
952
|
+
parent = dictionary.get(b"Parent")
|
|
953
|
+
if expected_parent is not None and parent != _PdfReference(*expected_parent):
|
|
954
|
+
raise GroupError("PDF evidence contains a nonexistent or incorrect Parent")
|
|
955
|
+
if expected_parent is None and parent is not None:
|
|
956
|
+
raise GroupError("PDF evidence contains an incorrect Parent in root Pages")
|
|
957
|
+
seen.add(reference)
|
|
958
|
+
if node_type == _PdfName(b"Page"):
|
|
959
|
+
return 1
|
|
960
|
+
if node_type != _PdfName(b"Pages"):
|
|
961
|
+
raise GroupError("PDF evidence references an object that is neither Page nor Pages")
|
|
962
|
+
declared = dictionary.get(b"Count")
|
|
963
|
+
kids = dictionary.get(b"Kids")
|
|
964
|
+
if not isinstance(declared, int) or not isinstance(kids, list):
|
|
965
|
+
raise GroupError("PDF evidence contains an incomplete Pages node")
|
|
966
|
+
if declared <= 0 or not kids or not all(isinstance(child, _PdfReference) for child in kids):
|
|
967
|
+
raise GroupError("PDF evidence contains no actual pages")
|
|
968
|
+
visiting.add(reference)
|
|
969
|
+
try:
|
|
970
|
+
actual = sum(
|
|
971
|
+
_pdf_pages(handle, xref, child, reference, visiting, seen)
|
|
972
|
+
for child in kids
|
|
973
|
+
)
|
|
974
|
+
finally:
|
|
975
|
+
visiting.remove(reference)
|
|
976
|
+
if actual != declared:
|
|
977
|
+
raise GroupError("PDF evidence declares an inconsistent page count")
|
|
978
|
+
return actual
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
def _validate_pdf(path: Path, size: int) -> None:
|
|
982
|
+
"""Resolve xref, catalog and an actual classic page tree."""
|
|
983
|
+
try:
|
|
984
|
+
with path.open("rb") as handle:
|
|
985
|
+
header = handle.read(16)
|
|
986
|
+
if not _pdf_has_valid_header(header):
|
|
987
|
+
raise GroupError("PDF evidence lacks a valid PDF signature")
|
|
988
|
+
tail_size = min(size, 128 * 1024)
|
|
989
|
+
handle.seek(size - tail_size)
|
|
990
|
+
tail = handle.read(tail_size)
|
|
991
|
+
xref_offset = _pdf_startxref(tail)
|
|
992
|
+
if xref_offset is None:
|
|
993
|
+
raise GroupError("PDF evidence lacks parseable closure and startxref")
|
|
994
|
+
if xref_offset < 0 or xref_offset >= size:
|
|
995
|
+
raise GroupError("PDF evidence contains a startxref outside the file")
|
|
996
|
+
xref, trailer = _pdf_classic_xref(handle, xref_offset)
|
|
997
|
+
declared_size = trailer.get(b"Size")
|
|
998
|
+
if (
|
|
999
|
+
not isinstance(declared_size, int)
|
|
1000
|
+
or declared_size <= 0
|
|
1001
|
+
or (xref and declared_size <= max(item[0] for item in xref))
|
|
1002
|
+
):
|
|
1003
|
+
raise GroupError("PDF evidence contains an inconsistent Size")
|
|
1004
|
+
root = trailer.get(b"Root")
|
|
1005
|
+
if not isinstance(root, _PdfReference):
|
|
1006
|
+
raise GroupError("PDF evidence contains no resolvable Root catalog")
|
|
1007
|
+
root_offset = xref.get(root)
|
|
1008
|
+
if root_offset is None:
|
|
1009
|
+
raise GroupError("PDF evidence references a nonexistent Root")
|
|
1010
|
+
catalog = _pdf_dictionary(handle, root_offset, root)
|
|
1011
|
+
if catalog.get(b"Type") != _PdfName(b"Catalog"):
|
|
1012
|
+
raise GroupError("PDF evidence Root is not a catalog")
|
|
1013
|
+
pages = catalog.get(b"Pages")
|
|
1014
|
+
if not isinstance(pages, _PdfReference):
|
|
1015
|
+
raise GroupError("PDF evidence contains no Pages tree")
|
|
1016
|
+
if _pdf_pages(handle, xref, pages, None, set(), set()) <= 0:
|
|
1017
|
+
raise GroupError("PDF evidence contains no actual pages")
|
|
1018
|
+
except OSError as exc:
|
|
1019
|
+
raise GroupError(f"failed to analyze PDF evidence: {exc}") from None
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
def _evidence(brand, relative: str | None) -> GroupEvidence | None:
|
|
1023
|
+
if relative is None:
|
|
1024
|
+
return None
|
|
1025
|
+
if ".secrets" in Path(relative).parts:
|
|
1026
|
+
raise GroupError("evidence cannot be inside .secrets")
|
|
1027
|
+
path = validar_ruta_relativa(brand.raiz, relative, GroupError, "evidence")
|
|
1028
|
+
if path.is_symlink():
|
|
1029
|
+
raise GroupError("evidence must be a regular file, not a symlink")
|
|
1030
|
+
try:
|
|
1031
|
+
resolved = path.resolve(strict=True)
|
|
1032
|
+
except OSError as exc:
|
|
1033
|
+
raise GroupError(f"failed to read evidence: {exc}") from None
|
|
1034
|
+
if not resolved.is_file() or resolved.suffix.lower() not in _EVIDENCE_EXTENSIONS:
|
|
1035
|
+
raise GroupError("evidence must be an existing JPG, PNG, WebP or PDF")
|
|
1036
|
+
size = resolved.stat().st_size
|
|
1037
|
+
if size <= 0:
|
|
1038
|
+
raise GroupError("evidence is empty")
|
|
1039
|
+
if resolved.suffix.lower() == ".pdf":
|
|
1040
|
+
_validate_pdf(resolved, size)
|
|
1041
|
+
else:
|
|
1042
|
+
_probe_visual_file(resolved, evidence=True)
|
|
1043
|
+
return GroupEvidence(relative_path=relative, sha256=file_digest(resolved), size_bytes=size)
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
def confirm_group(
|
|
1047
|
+
brand,
|
|
1048
|
+
store: GroupStore,
|
|
1049
|
+
change_id: str,
|
|
1050
|
+
*,
|
|
1051
|
+
confirmation_phrase: str,
|
|
1052
|
+
post_url: str | None = None,
|
|
1053
|
+
evidence: str | None = None,
|
|
1054
|
+
) -> GroupChange:
|
|
1055
|
+
"""Record explicit user statement without checking the web."""
|
|
1056
|
+
if not isinstance(confirmation_phrase, str):
|
|
1057
|
+
raise GroupError(f"confirmation must be exactly: {CONFIRMATION_PHRASE}")
|
|
1058
|
+
supplied = confirmation_phrase.encode()
|
|
1059
|
+
accepted = hmac.compare_digest(supplied, CONFIRMATION_PHRASE.encode())
|
|
1060
|
+
accepted |= hmac.compare_digest(supplied, LEGACY_CONFIRMATION_PHRASE.encode())
|
|
1061
|
+
if not accepted:
|
|
1062
|
+
raise GroupError(f"confirmation must be exactly: {CONFIRMATION_PHRASE}")
|
|
1063
|
+
with store.apply_lock(change_id):
|
|
1064
|
+
change = _load_bound(brand, store, change_id)
|
|
1065
|
+
canonical_post = validate_post_url(post_url, change.destination.key) if post_url else None
|
|
1066
|
+
if change.status == "confirmed_manual":
|
|
1067
|
+
existing = change.confirmation
|
|
1068
|
+
existing_evidence = (
|
|
1069
|
+
existing.evidence.relative_path
|
|
1070
|
+
if existing is not None and existing.evidence is not None
|
|
1071
|
+
else None
|
|
1072
|
+
)
|
|
1073
|
+
if (
|
|
1074
|
+
existing is not None
|
|
1075
|
+
and existing.post_url == canonical_post
|
|
1076
|
+
and existing_evidence == evidence
|
|
1077
|
+
):
|
|
1078
|
+
return change
|
|
1079
|
+
raise GroupError("ChangeSet already has a different confirmation; it will not be overwritten")
|
|
1080
|
+
supplied_evidence = _evidence(brand, evidence)
|
|
1081
|
+
if canonical_post is None and supplied_evidence is None:
|
|
1082
|
+
raise GroupError("confirm with --post-url, --evidence or both")
|
|
1083
|
+
if change.status not in {"handoff_ready", "awaiting_manual_confirmation"}:
|
|
1084
|
+
raise GroupError("handoff must be approved before confirming manual publication")
|
|
1085
|
+
change.confirmation = GroupConfirmation(
|
|
1086
|
+
confirmed_at=now_utc(), post_url=canonical_post, evidence=supplied_evidence
|
|
1087
|
+
)
|
|
1088
|
+
change.status = "confirmed_manual"
|
|
1089
|
+
change.last_error = None
|
|
1090
|
+
_event(change, "user_confirmed_manual_publication")
|
|
1091
|
+
store.save(change)
|
|
1092
|
+
return change
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def export_record(change: GroupChange) -> dict:
|
|
1096
|
+
"""Exportable view without absolute paths, internal keys or credentials."""
|
|
1097
|
+
return {
|
|
1098
|
+
"id": change.id,
|
|
1099
|
+
"brand": change.brand,
|
|
1100
|
+
"group": change.destination.model_dump(mode="json"),
|
|
1101
|
+
"copy": change.copy_text,
|
|
1102
|
+
"youtube_url": change.youtube_url,
|
|
1103
|
+
"media": change.media.model_dump(mode="json") if change.media else None,
|
|
1104
|
+
"suggested_window": change.suggested_window.model_dump(mode="json"),
|
|
1105
|
+
"status": change.status,
|
|
1106
|
+
"capability": change.capability,
|
|
1107
|
+
"fingerprint": change.fingerprint,
|
|
1108
|
+
"created_at": change.created_at.isoformat(),
|
|
1109
|
+
"updated_at": change.updated_at.isoformat(),
|
|
1110
|
+
"confirmation": change.confirmation.model_dump(mode="json") if change.confirmation else None,
|
|
1111
|
+
"reminder": "Manual publication pending in browser; socialcli does not publish to Groups via API.",
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
def export_queue(brand, store: GroupStore, change_id: str | None = None) -> list[dict]:
|
|
1116
|
+
if change_id is not None:
|
|
1117
|
+
return [export_record(_load_bound(brand, store, change_id))]
|
|
1118
|
+
return [export_record(_load_bound(brand, store, item.id)) for item in _iter_changes(store)]
|