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,398 @@
|
|
|
1
|
+
"""Durable Meta/YouTube publication occurrences and separately recoverable comments.
|
|
2
|
+
|
|
3
|
+
The caller has already approved the complete publication preview. Each explicit
|
|
4
|
+
publish creates a fresh occurrence. A scheduler supplies a stable occurrence UUID;
|
|
5
|
+
comment retry only consumes the original occurrence, never invokes an uploader.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import uuid
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
|
|
17
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
18
|
+
|
|
19
|
+
from socialctl.management.meta_comments import (
|
|
20
|
+
CommentError, CommentStore, MetaCommentsClient, apply_comment, prepare_comment,
|
|
21
|
+
)
|
|
22
|
+
from socialctl.models import Platform, PostResult, PostStatus
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Publication(BaseModel):
|
|
26
|
+
model_config = ConfigDict(extra="forbid")
|
|
27
|
+
version: int = 1
|
|
28
|
+
id: str
|
|
29
|
+
brand: str
|
|
30
|
+
brand_root: str
|
|
31
|
+
platform: str
|
|
32
|
+
slug: str
|
|
33
|
+
account: dict
|
|
34
|
+
text: str | None
|
|
35
|
+
provenance: str
|
|
36
|
+
source_mapping_digest: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
37
|
+
fingerprint: str
|
|
38
|
+
created_at: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
39
|
+
state: str = "uploading"
|
|
40
|
+
media: dict | None = None
|
|
41
|
+
comment_change_id: str | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _fingerprint(data):
|
|
45
|
+
immutable = {key: value for key, value in data.items()
|
|
46
|
+
if key not in {"fingerprint", "state", "media", "comment_change_id"}}
|
|
47
|
+
return hashlib.sha256(json.dumps(immutable, sort_keys=True, ensure_ascii=False,
|
|
48
|
+
separators=(",", ":")).encode()).hexdigest()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class PublicationStore(CommentStore):
|
|
52
|
+
def __init__(self, brand_root: Path):
|
|
53
|
+
self.root = brand_root / ".socialctl" / "publications"
|
|
54
|
+
|
|
55
|
+
def load(self, identifier):
|
|
56
|
+
try:
|
|
57
|
+
data = Publication.model_validate_json(self.path_for(identifier).read_text()).model_dump()
|
|
58
|
+
except (OSError, ValidationError):
|
|
59
|
+
raise CommentError("attempt has no durable journal: manual reconciliation required; do not repeat the comment") from None
|
|
60
|
+
if data["id"] != identifier or data["version"] != 1 or not hmac.compare_digest(data["fingerprint"], _fingerprint(data)):
|
|
61
|
+
raise CommentError("publication journal was modified")
|
|
62
|
+
return data
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _account(brand, platform):
|
|
66
|
+
account = brand.cuentas.get(platform.value) or {}
|
|
67
|
+
if platform is Platform.YOUTUBE:
|
|
68
|
+
return {"account_id": account.get("channel_id")}
|
|
69
|
+
return {"account_id": account.get("page_id" if platform is Platform.FACEBOOK else "ig_user_id"),
|
|
70
|
+
"page_id": (brand.cuentas.get("facebook") or {}).get("page_id")}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _bound(brand, data):
|
|
74
|
+
platform = Platform(data["platform"])
|
|
75
|
+
if (data["brand"], data["brand_root"], data["account"]) != (
|
|
76
|
+
brand.nombre, str(brand.raiz.resolve()), _account(brand, platform)):
|
|
77
|
+
raise CommentError("brand or account differs from the approved attempt")
|
|
78
|
+
if not data["provenance"]:
|
|
79
|
+
raise CommentError("approval provenance is missing; manual review required")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _stored_media(data):
|
|
83
|
+
"""Validate association independently of current credentials or comment state."""
|
|
84
|
+
if data["media"] is None:
|
|
85
|
+
return None
|
|
86
|
+
try:
|
|
87
|
+
result = PostResult.model_validate(data["media"])
|
|
88
|
+
except ValidationError:
|
|
89
|
+
raise CommentError("invalid media result in the journal; manual review required") from None
|
|
90
|
+
if result.platform.value != data["platform"] or result.publication_id != data["id"]:
|
|
91
|
+
raise CommentError("media result is not linked to its journal")
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def retry_media_blockers(brand, slug, platforms):
|
|
96
|
+
"""Read structured brand-local history; do not infer chronology from filenames.
|
|
97
|
+
|
|
98
|
+
Old records have no ordering evidence. Any protected matching occurrence holds
|
|
99
|
+
retry; an explicit fresh publish remains available after manual reconciliation.
|
|
100
|
+
An unreadable record cannot safely be classified as unrelated.
|
|
101
|
+
"""
|
|
102
|
+
selected = set(platforms) & {Platform.FACEBOOK, Platform.INSTAGRAM, Platform.YOUTUBE}
|
|
103
|
+
blockers = {}
|
|
104
|
+
if not selected:
|
|
105
|
+
return blockers
|
|
106
|
+
store = PublicationStore(brand.raiz)
|
|
107
|
+
try:
|
|
108
|
+
with os.scandir(store.root) as directory:
|
|
109
|
+
identifiers = [entry.name[:-5] for entry in directory if entry.name.endswith(".json")]
|
|
110
|
+
except FileNotFoundError:
|
|
111
|
+
if not store.root.is_symlink():
|
|
112
|
+
return blockers
|
|
113
|
+
raise CommentError("journal directory is inaccessible; retry blocked") from None
|
|
114
|
+
except OSError:
|
|
115
|
+
raise CommentError("journal directory is unreadable; retry blocked") from None
|
|
116
|
+
for identifier in identifiers:
|
|
117
|
+
try:
|
|
118
|
+
data = store.load(identifier)
|
|
119
|
+
if (data["brand"], data["brand_root"]) != (brand.nombre, str(brand.raiz.resolve())):
|
|
120
|
+
raise CommentError("journal is outside its brand directory")
|
|
121
|
+
platform = Platform(data["platform"])
|
|
122
|
+
except (CommentError, ValueError):
|
|
123
|
+
raise CommentError("publication journal is unreadable or lacks a reliable link; retry blocked") from None
|
|
124
|
+
if data["slug"] != slug or platform not in selected:
|
|
125
|
+
continue
|
|
126
|
+
try:
|
|
127
|
+
_bound(brand, data)
|
|
128
|
+
result = _stored_media(data)
|
|
129
|
+
definite_failure = (result is not None and result.status is PostStatus.ERROR
|
|
130
|
+
and data["state"] == "upload_result" and not result.platform_id
|
|
131
|
+
and data["media"].get("riesgo_duplicado") is False)
|
|
132
|
+
except CommentError:
|
|
133
|
+
definite_failure = False
|
|
134
|
+
result = None
|
|
135
|
+
if not definite_failure:
|
|
136
|
+
detail = f"media published {result.platform_id}" if result and result.status is PostStatus.PUBLICADO else "media is uncertain or lacks a verifiable link"
|
|
137
|
+
blockers.setdefault(platform, []).append(f"journal {identifier}: {detail}; do not upload again")
|
|
138
|
+
return blockers
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _comment_issue(result, data):
|
|
142
|
+
result.warnings.append("Media published; first comment needs review. Use comments retry-first with the attempt ID.")
|
|
143
|
+
result.first_comment_status = "manual_review"
|
|
144
|
+
result.first_comment_change_id = data["comment_change_id"]
|
|
145
|
+
return result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _observe_media(callback, result):
|
|
149
|
+
"""Advisory output cannot replace the critical persisted-media callback."""
|
|
150
|
+
if callback is not None:
|
|
151
|
+
try:
|
|
152
|
+
callback(result)
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _resume_publication(brand, http, store, data, *, on_media_result=None, on_media_observed=None):
|
|
158
|
+
result = _stored_media(data)
|
|
159
|
+
if result is None:
|
|
160
|
+
return PostResult(platform=Platform(data["platform"]), status=PostStatus.ERROR,
|
|
161
|
+
publication_id=data["id"], riesgo_duplicado=True,
|
|
162
|
+
error="journal has no media result: uncertain outcome; manual reconciliation required")
|
|
163
|
+
try:
|
|
164
|
+
_bound(brand, data)
|
|
165
|
+
_observe_media(on_media_observed, result)
|
|
166
|
+
if on_media_result is not None:
|
|
167
|
+
on_media_result(result)
|
|
168
|
+
if result.status is not PostStatus.PUBLICADO or not result.platform_id:
|
|
169
|
+
return result # Keep definite failure distinct from uncertain upload.
|
|
170
|
+
return _first_comment(brand, http, store, data)
|
|
171
|
+
except Exception:
|
|
172
|
+
if result.status is PostStatus.PUBLICADO and result.platform_id:
|
|
173
|
+
return _comment_issue(result, data)
|
|
174
|
+
# No next step attempted; the stored upload outcome remains authoritative.
|
|
175
|
+
result.warnings.append("Could not resume the journal; review manually before taking another step.")
|
|
176
|
+
return result
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _pending_source(brand, data):
|
|
180
|
+
from socialctl.source_links import verify_source_binding
|
|
181
|
+
try:
|
|
182
|
+
verify_source_binding(brand, data['slug'], data.get('source_mapping_digest'))
|
|
183
|
+
except ValueError as exc:
|
|
184
|
+
raise CommentError(str(exc)) from None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _first_comment(brand, http, store, data, *, retry_rejected=False, reconcile_only=False):
|
|
188
|
+
_bound(brand, data)
|
|
189
|
+
if not data["media"]:
|
|
190
|
+
raise CommentError("media has no durable result; reconcile manually, do not upload again")
|
|
191
|
+
result = PostResult.model_validate(data["media"])
|
|
192
|
+
if result.status is not PostStatus.PUBLICADO or not result.platform_id:
|
|
193
|
+
raise CommentError("media is unconfirmed; comment requires manual review")
|
|
194
|
+
if not data["text"]:
|
|
195
|
+
return result
|
|
196
|
+
if data['provenance'].startswith('native-schedule:'):
|
|
197
|
+
from socialctl.native_schedule.first_comment import validate_native_publication
|
|
198
|
+
validate_native_publication(brand, http, data)
|
|
199
|
+
if not data['comment_change_id']:
|
|
200
|
+
if reconcile_only:
|
|
201
|
+
return result
|
|
202
|
+
if result.first_comment_status == 'observed_existing':
|
|
203
|
+
return result
|
|
204
|
+
if _native_existing_comment(brand, http, store, data, result):
|
|
205
|
+
return result
|
|
206
|
+
if reconcile_only and not data['comment_change_id']:
|
|
207
|
+
return result
|
|
208
|
+
if result.platform is Platform.YOUTUBE:
|
|
209
|
+
return _youtube_first_comment(brand, http, store, data, result, retry_rejected=retry_rejected, reconcile_only=reconcile_only)
|
|
210
|
+
comments = CommentStore(brand.raiz)
|
|
211
|
+
client = MetaCommentsClient(brand, result.platform, http)
|
|
212
|
+
if data["comment_change_id"]:
|
|
213
|
+
change = comments.load(data["comment_change_id"])
|
|
214
|
+
if reconcile_only and change.status in {"proposed", "rejected"}:
|
|
215
|
+
return result
|
|
216
|
+
if change.status == "proposed" or (change.status == "rejected" and retry_rejected):
|
|
217
|
+
_pending_source(brand, data)
|
|
218
|
+
if change.status == "rejected" and retry_rejected:
|
|
219
|
+
previous = change.id
|
|
220
|
+
change = prepare_comment(client, comments, media_id=result.platform_id, text=data["text"])
|
|
221
|
+
change.journal.append({"event": "explicit_retry_after_definitive_rejection", "previous_change": previous})
|
|
222
|
+
comments.save(change)
|
|
223
|
+
data["comment_change_id"] = change.id
|
|
224
|
+
store.write_json(data["id"], data)
|
|
225
|
+
else:
|
|
226
|
+
_pending_source(brand, data)
|
|
227
|
+
change = prepare_comment(client, comments, media_id=result.platform_id, text=data["text"])
|
|
228
|
+
data["comment_change_id"] = change.id
|
|
229
|
+
store.write_json(data["id"], data) # Reference persisted before comment intent/POST.
|
|
230
|
+
if (change.text, change.media_id, change.action, change.brand, change.brand_root) != (
|
|
231
|
+
data["text"], result.platform_id, "add", data["brand"], data["brand_root"]):
|
|
232
|
+
raise CommentError("comment differs from the approved first comment")
|
|
233
|
+
# A persisted proposed reference can survive a restart before write intent.
|
|
234
|
+
# Recheck current complete enumeration before every new native Meta add,
|
|
235
|
+
# including an explicitly approved retry after definitive rejection. Existing
|
|
236
|
+
# write intents/receipts only reconcile; a list can never authorize replay.
|
|
237
|
+
if data['provenance'].startswith('native-schedule:') and change.status == 'proposed':
|
|
238
|
+
if _native_existing_comment(brand, http, store, data, result):
|
|
239
|
+
return result
|
|
240
|
+
# Approval is inherited only from this immutable, approved publication;
|
|
241
|
+
# callers cannot pass unrelated ChangeSets or silently adopt legacy comments.
|
|
242
|
+
change = apply_comment(client, comments, change.id, change.fingerprint)
|
|
243
|
+
result.warnings = [warning for warning in result.warnings
|
|
244
|
+
if not warning.startswith("Media published; first comment ")]
|
|
245
|
+
result.first_comment_change_id = change.id
|
|
246
|
+
result.first_comment_id = change.remote_id
|
|
247
|
+
result.first_comment_status = change.status
|
|
248
|
+
if change.status != "verified":
|
|
249
|
+
result.warnings.append(f"Media published; first comment {change.status}. Check comments status {change.id}.")
|
|
250
|
+
data["media"] = result.model_dump(mode="json")
|
|
251
|
+
store.write_json(data["id"], data)
|
|
252
|
+
return result
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _native_existing_comment(brand, http, store, data, result):
|
|
256
|
+
"""A complete initial read prevents duplicate writes; an observation is not a receipt."""
|
|
257
|
+
if result.platform is Platform.YOUTUBE:
|
|
258
|
+
from socialctl.management.youtube_community import YouTubeCommunityClient, FILTERS
|
|
259
|
+
client = YouTubeCommunityClient(brand, http)
|
|
260
|
+
matches = []
|
|
261
|
+
for state in FILTERS:
|
|
262
|
+
listing = client.list_threads(result.platform_id, moderation_status=state)
|
|
263
|
+
if not listing['complete']:
|
|
264
|
+
raise CommentError('Initial comment read incomplete; no new comment attempted')
|
|
265
|
+
for row in listing['items']:
|
|
266
|
+
comment = row['snippet']['topLevelComment']
|
|
267
|
+
if (comment['snippet'].get('authorChannelId', {}).get('value') == data['account']['account_id']
|
|
268
|
+
and comment['snippet'].get('textOriginal') == data['text']):
|
|
269
|
+
matches.append(comment['id'])
|
|
270
|
+
else:
|
|
271
|
+
client = MetaCommentsClient(brand, result.platform, http)
|
|
272
|
+
listing = client.list_comments(result.platform_id)
|
|
273
|
+
if not listing['complete']:
|
|
274
|
+
raise CommentError('Initial comment read incomplete; no new comment attempted')
|
|
275
|
+
field = 'message' if result.platform is Platform.FACEBOOK else 'text'
|
|
276
|
+
matches = [row['id'] for row in listing['data']
|
|
277
|
+
if row.get(field) == data['text'] and (row.get('from') or {}).get('id') == client.account_id]
|
|
278
|
+
if not matches:
|
|
279
|
+
return False
|
|
280
|
+
result.first_comment_status = 'observed_existing'
|
|
281
|
+
result.first_comment_change_id = data['comment_change_id']
|
|
282
|
+
result.warnings.append('An existing own exact comment was observed; creation by this occurrence is unproven. No new comment attempted.')
|
|
283
|
+
data['media'] = result.model_dump(mode='json')
|
|
284
|
+
store.write_json(data['id'], data)
|
|
285
|
+
return True
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _youtube_first_comment(brand, http, store, data, result, *, retry_rejected, reconcile_only=False):
|
|
289
|
+
from socialctl.management.community_changes import CommunityStore, prepare_community, apply_community
|
|
290
|
+
from socialctl.management.youtube_community import YouTubeCommunityClient
|
|
291
|
+
comments = CommunityStore(brand.raiz)
|
|
292
|
+
client = YouTubeCommunityClient(brand, http)
|
|
293
|
+
edit = {"action": "add", "video_id": result.platform_id, "text": data["text"]}
|
|
294
|
+
previous = None
|
|
295
|
+
if data["comment_change_id"]:
|
|
296
|
+
change = comments.load(data["comment_change_id"])
|
|
297
|
+
if reconcile_only and change.status in {"proposed", "failed"}:
|
|
298
|
+
return result
|
|
299
|
+
if change.status == "proposed" or (change.status == "failed" and retry_rejected):
|
|
300
|
+
_pending_source(brand, data)
|
|
301
|
+
if change.status == "failed" and retry_rejected:
|
|
302
|
+
previous = change.id
|
|
303
|
+
change = prepare_community(client, comments, edit)
|
|
304
|
+
else:
|
|
305
|
+
_pending_source(brand, data)
|
|
306
|
+
change = prepare_community(client, comments, edit)
|
|
307
|
+
if (change.target_brand, change.brand_root, change.target_account, change.edit) != (
|
|
308
|
+
data["brand"], data["brand_root"], data["account"]["account_id"], {"version": 1, **edit}):
|
|
309
|
+
raise CommentError("YouTube comment differs from the originally approved text/video/actor")
|
|
310
|
+
if data["comment_change_id"] != change.id:
|
|
311
|
+
if previous:
|
|
312
|
+
change.journal.append({"event": "explicit_retry_after_definitive_rejection", "previous_change": previous})
|
|
313
|
+
comments.save(change)
|
|
314
|
+
data["comment_change_id"] = change.id
|
|
315
|
+
store.write_json(data["id"], data) # Durable reference before comment POST.
|
|
316
|
+
change = apply_community(client, comments, change.id, change.fingerprint)
|
|
317
|
+
result.warnings = [w for w in result.warnings if not w.startswith("Media published; first comment ")]
|
|
318
|
+
result.first_comment_change_id = change.id
|
|
319
|
+
result.first_comment_id = change.result_id
|
|
320
|
+
result.first_comment_status = change.status
|
|
321
|
+
if change.status != "verified":
|
|
322
|
+
result.warnings.append(f"Media published; first comment {change.status}. Check content youtube-community status {change.id}.")
|
|
323
|
+
data["media"] = result.model_dump(mode="json")
|
|
324
|
+
store.write_json(data["id"], data)
|
|
325
|
+
return result
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def retry_first_comment(brand, http, publication_id):
|
|
329
|
+
store = PublicationStore(brand.raiz)
|
|
330
|
+
with store.apply_lock(publication_id):
|
|
331
|
+
return _first_comment(brand, http, store, store.load(publication_id), retry_rejected=True)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def publish_with_steps(post, brand, platform, adapter, http, *, on_media_result=None, on_media_observed=None,
|
|
335
|
+
occurrence_id=None, provenance="approved-publish-preview", retry_guard=False):
|
|
336
|
+
store = PublicationStore(brand.raiz)
|
|
337
|
+
gate = str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps([
|
|
338
|
+
"publication-gate", str(brand.raiz.resolve()), post.slug, platform.value])))
|
|
339
|
+
with store.apply_lock(gate):
|
|
340
|
+
if retry_guard:
|
|
341
|
+
blockers = retry_media_blockers(brand, post.slug, [platform])
|
|
342
|
+
if platform in blockers:
|
|
343
|
+
raise CommentError("; ".join(blockers[platform]))
|
|
344
|
+
return _publish_occurrence(post, brand, platform, adapter, http,
|
|
345
|
+
on_media_result=on_media_result, on_media_observed=on_media_observed,
|
|
346
|
+
occurrence_id=occurrence_id, provenance=provenance)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _publish_occurrence(post, brand, platform, adapter, http, *, on_media_result=None, on_media_observed=None,
|
|
350
|
+
occurrence_id=None, provenance):
|
|
351
|
+
store = PublicationStore(brand.raiz)
|
|
352
|
+
identifier = occurrence_id or str(uuid.uuid4())
|
|
353
|
+
if post.brand != brand.nombre:
|
|
354
|
+
raise CommentError("post brand does not match the approved brand")
|
|
355
|
+
with store.apply_lock(identifier):
|
|
356
|
+
if store.path_for(identifier).exists():
|
|
357
|
+
# Stable scheduler occurrence: never upload again after an interruption.
|
|
358
|
+
existing = store.load(identifier)
|
|
359
|
+
if (existing["slug"], existing["platform"], existing["brand"], existing["brand_root"]) != (
|
|
360
|
+
post.slug, platform.value, brand.nombre, str(brand.raiz.resolve())):
|
|
361
|
+
raise CommentError("journal UUID belongs to another post, platform or brand")
|
|
362
|
+
return _resume_publication(brand, http, store, existing, on_media_result=on_media_result,
|
|
363
|
+
on_media_observed=on_media_observed)
|
|
364
|
+
data = Publication(id=identifier, brand=brand.nombre, brand_root=str(brand.raiz.resolve()),
|
|
365
|
+
created_at=datetime.now(timezone.utc).isoformat(),
|
|
366
|
+
platform=platform.value, slug=post.slug, account=_account(brand, platform),
|
|
367
|
+
text=post.platforms[platform].first_comment, provenance=provenance,
|
|
368
|
+
source_mapping_digest=post.source_mapping_digest, fingerprint="").model_dump()
|
|
369
|
+
data["fingerprint"] = _fingerprint(data)
|
|
370
|
+
try:
|
|
371
|
+
store.write_json(identifier, data)
|
|
372
|
+
except CommentError:
|
|
373
|
+
return PostResult(platform=platform, status=PostStatus.ERROR,
|
|
374
|
+
error="could not save the intent; publication was not attempted")
|
|
375
|
+
try:
|
|
376
|
+
result = adapter.publish(post.platforms[platform], brand, http)
|
|
377
|
+
except Exception:
|
|
378
|
+
result = PostResult(platform=platform, status=PostStatus.ERROR,
|
|
379
|
+
error="publication interrupted; remote outcome is uncertain", riesgo_duplicado=True)
|
|
380
|
+
result.publication_id = identifier
|
|
381
|
+
if data["text"]:
|
|
382
|
+
result.first_comment_status = "pending"
|
|
383
|
+
_observe_media(on_media_observed, result)
|
|
384
|
+
data["media"] = result.model_dump(mode="json")
|
|
385
|
+
data["state"] = "published" if result.status is PostStatus.PUBLICADO else "upload_result"
|
|
386
|
+
try:
|
|
387
|
+
store.write_json(identifier, data)
|
|
388
|
+
if on_media_result is not None:
|
|
389
|
+
on_media_result(result) # Critical: a failure blocks the next remote step.
|
|
390
|
+
except Exception:
|
|
391
|
+
result.warnings.append("Media persistence did not complete; comment blocked. Review the journal manually.")
|
|
392
|
+
return result
|
|
393
|
+
if result.status is not PostStatus.PUBLICADO or not result.platform_id:
|
|
394
|
+
return result
|
|
395
|
+
try:
|
|
396
|
+
return _first_comment(brand, http, store, data)
|
|
397
|
+
except Exception:
|
|
398
|
+
return _comment_issue(result, data)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Opt-in publication reports retain observations across incomplete execution."""
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
from contextlib import redirect_stdout
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from socialctl.agent_errors import error_document, error_for_code
|
|
9
|
+
from socialctl.read_reports import safe_error
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PublishOutput:
|
|
13
|
+
def __init__(self, enabled, *, command, brand, slug):
|
|
14
|
+
self.enabled = enabled
|
|
15
|
+
self.command, self.brand, self.slug = command, brand, slug
|
|
16
|
+
self.started = False
|
|
17
|
+
self.status = None
|
|
18
|
+
self.preview = None
|
|
19
|
+
self.results = {}
|
|
20
|
+
self.errors = []
|
|
21
|
+
self.persistence = {'complete': None}
|
|
22
|
+
self.retry = {'blocked': [], 'selected': []}
|
|
23
|
+
|
|
24
|
+
def __enter__(self):
|
|
25
|
+
if not self.enabled:
|
|
26
|
+
return None
|
|
27
|
+
self.redirect = redirect_stdout(sys.stderr)
|
|
28
|
+
self.redirect.__enter__()
|
|
29
|
+
return self
|
|
30
|
+
|
|
31
|
+
def __exit__(self, kind, exc, traceback):
|
|
32
|
+
if not self.enabled:
|
|
33
|
+
return False
|
|
34
|
+
self.redirect.__exit__(kind, exc, traceback)
|
|
35
|
+
if exc is not None and not isinstance(exc, (Exception, KeyboardInterrupt)):
|
|
36
|
+
return False
|
|
37
|
+
code = (exc.exit_code or 0) if isinstance(exc, typer.Exit) else 130 if isinstance(exc, KeyboardInterrupt) else 1
|
|
38
|
+
if exc is not None:
|
|
39
|
+
if isinstance(exc, (KeyboardInterrupt, typer.Abort)) and not self.started:
|
|
40
|
+
self.status = 'cancelled'
|
|
41
|
+
self.add_error('operation_cancelled')
|
|
42
|
+
elif not isinstance(exc, typer.Exit):
|
|
43
|
+
self.errors.append(error_for_code('operation_uncertain') if self.started
|
|
44
|
+
else error_document(exc, read_only=False))
|
|
45
|
+
elif code and not self.errors and not self._result_errors():
|
|
46
|
+
self.add_error('operation_uncertain' if self.started else 'invalid_input')
|
|
47
|
+
failed = bool(self.errors or self._result_errors())
|
|
48
|
+
status = self.status
|
|
49
|
+
if status not in {'preview', 'cancelled'}:
|
|
50
|
+
observed = any(r['status'] in {'publicado', 'pendiente_confirmacion'} for r in self.results.values())
|
|
51
|
+
status = ('partial' if observed else 'error') if failed else ('ok' if observed else 'noop')
|
|
52
|
+
payload = {'version': 1, 'command': self.command, 'brand': self.brand,
|
|
53
|
+
'slug': self.slug, 'status': status, 'resultados': list(self.results.values()),
|
|
54
|
+
'errors': self.errors, 'persistence': self.persistence}
|
|
55
|
+
if self.preview is not None:
|
|
56
|
+
payload['preview'] = self.preview
|
|
57
|
+
if self.command == 'retry':
|
|
58
|
+
payload['retry'] = self.retry
|
|
59
|
+
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
60
|
+
if exc is not None and not isinstance(exc, typer.Exit):
|
|
61
|
+
raise typer.Exit(code) from None
|
|
62
|
+
return False
|
|
63
|
+
|
|
64
|
+
def _result_errors(self):
|
|
65
|
+
return any('error_detail' in row or 'first_comment_error_detail' in row for row in self.results.values())
|
|
66
|
+
|
|
67
|
+
def add_error(self, code, **context):
|
|
68
|
+
self.errors.append({**context, **error_for_code(code, read_only=False)})
|
|
69
|
+
|
|
70
|
+
def begin_write(self):
|
|
71
|
+
self.started = True
|
|
72
|
+
self.persistence = {'complete': False}
|
|
73
|
+
|
|
74
|
+
def observe_safely(self, result):
|
|
75
|
+
try:
|
|
76
|
+
self.observe(result)
|
|
77
|
+
except Exception:
|
|
78
|
+
if not any(error['code'] == 'reporting_incomplete' for error in self.errors):
|
|
79
|
+
self.add_error('reporting_incomplete')
|
|
80
|
+
|
|
81
|
+
def observe(self, result):
|
|
82
|
+
row = result.model_dump(mode='json')
|
|
83
|
+
if row.get('error') is not None:
|
|
84
|
+
row['error'] = safe_error(row['error'])
|
|
85
|
+
if row.get('url') is not None:
|
|
86
|
+
row['url'] = safe_error(row['url'])
|
|
87
|
+
row['warnings'] = [safe_error(value) for value in row.get('warnings', [])]
|
|
88
|
+
if row['riesgo_duplicado'] is True:
|
|
89
|
+
row['error_detail'] = error_for_code('operation_uncertain', read_only=False)
|
|
90
|
+
elif row['status'] == 'error':
|
|
91
|
+
row['error_detail'] = error_for_code('operation_rejected', read_only=False)
|
|
92
|
+
elif row['status'] == 'pendiente_confirmacion':
|
|
93
|
+
row['error_detail'] = error_for_code('publication_pending', read_only=False)
|
|
94
|
+
if row.get('first_comment_status') not in {None, 'verified'}:
|
|
95
|
+
row['first_comment_error_detail'] = error_for_code('comment_incomplete', read_only=False)
|
|
96
|
+
self.results[row['platform']] = row
|