socialcli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of socialcli might be problematic. Click here for more details.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
socialctl/inventory.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Durable account-bound content snapshots, independent of drafts and metrics."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import fcntl
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import uuid
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
|
|
12
|
+
from socialctl.identity import IdentityClient, ReadError, remote_id
|
|
13
|
+
from socialctl.inventory_sources import read_page
|
|
14
|
+
from socialctl.media_registry import safe
|
|
15
|
+
from socialctl.migration_files import write_json
|
|
16
|
+
from socialctl.models import Platform
|
|
17
|
+
from socialctl.scheduler import ScheduleStore
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def now():
|
|
21
|
+
return datetime.now(timezone.utc).isoformat()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class InventoryStore:
|
|
25
|
+
def __init__(self, brand, platform, account_id):
|
|
26
|
+
self.binding = {"brand": brand.nombre, "brand_root": str(brand.raiz.resolve()),
|
|
27
|
+
"platform": platform.value, "account_id": remote_id(account_id)}
|
|
28
|
+
self.base = safe(brand.raiz / ".socialctl")
|
|
29
|
+
key = hashlib.sha256(account_id.encode()).hexdigest()
|
|
30
|
+
self.path = safe(self.base / "inventory" / platform.value / key / "snapshot.json")
|
|
31
|
+
|
|
32
|
+
def load(self):
|
|
33
|
+
safe(self.path)
|
|
34
|
+
if not self.path.exists():
|
|
35
|
+
return {"version": 1, **self.binding, "items": {}, "sync": None}
|
|
36
|
+
try:
|
|
37
|
+
data = json.loads(self.path.read_bytes())
|
|
38
|
+
if data["version"] != 1 or any(data.get(k) != v for k, v in self.binding.items()):
|
|
39
|
+
raise ValueError()
|
|
40
|
+
if not isinstance(data["items"], dict):
|
|
41
|
+
raise ValueError()
|
|
42
|
+
for key, row in data["items"].items():
|
|
43
|
+
if row["remote_id"] != remote_id(key) or any(row.get(k) != self.binding[k] for k in ("brand", "platform", "account_id")):
|
|
44
|
+
raise ValueError()
|
|
45
|
+
if self.binding['platform']=='youtube':
|
|
46
|
+
from socialctl.youtube_data import require_fresh_api_data
|
|
47
|
+
for row in data['items'].values():require_fresh_api_data(row.get('first_observed_at'))
|
|
48
|
+
return data
|
|
49
|
+
except (ValueError, KeyError, TypeError, OSError):
|
|
50
|
+
raise ReadError("inventory_invalid") from None
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def public_items(state):
|
|
54
|
+
"""Sanitize one already-loaded snapshot without reopening its path."""
|
|
55
|
+
return [{k: v for k, v in row.items() if k != "raw"}
|
|
56
|
+
for _, row in sorted(state["items"].items())]
|
|
57
|
+
|
|
58
|
+
def list_items(self):
|
|
59
|
+
return self.public_items(self.load())
|
|
60
|
+
|
|
61
|
+
def _prepare(self):
|
|
62
|
+
chain = [self.base, self.base / "inventory", self.path.parent.parent, self.path.parent]
|
|
63
|
+
for directory in chain:
|
|
64
|
+
safe(directory).mkdir(mode=0o700, exist_ok=True)
|
|
65
|
+
directory.chmod(0o700)
|
|
66
|
+
ScheduleStore._sync_directory(directory.parent)
|
|
67
|
+
|
|
68
|
+
@contextmanager
|
|
69
|
+
def lock(self):
|
|
70
|
+
self._prepare()
|
|
71
|
+
fd = os.open(safe(self.path.parent / "sync.lock"), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
72
|
+
try:
|
|
73
|
+
try:
|
|
74
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
75
|
+
except BlockingIOError:
|
|
76
|
+
raise ReadError("inventory_locked") from None
|
|
77
|
+
yield
|
|
78
|
+
finally:
|
|
79
|
+
os.close(fd)
|
|
80
|
+
|
|
81
|
+
def save(self, state):
|
|
82
|
+
safe(self.path)
|
|
83
|
+
write_json(self.path, state)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def sync_content(brand, platform, client, *, max_pages=20, resume=False):
|
|
87
|
+
if platform not in {Platform.YOUTUBE, Platform.FACEBOOK, Platform.INSTAGRAM}:
|
|
88
|
+
raise ReadError('unsupported_platform')
|
|
89
|
+
if type(max_pages) is not int or not 1 <= max_pages <= 100:
|
|
90
|
+
raise ReadError("invalid_page_limit")
|
|
91
|
+
probe = IdentityClient(brand, platform, client)
|
|
92
|
+
identity = probe.verify() # Wrong identity cannot even create a local inventory.
|
|
93
|
+
store = InventoryStore(brand, platform, probe.account_id)
|
|
94
|
+
with store.lock():
|
|
95
|
+
state = store.load()
|
|
96
|
+
previous = state.get("sync")
|
|
97
|
+
if resume:
|
|
98
|
+
if not previous or previous["complete"] or not previous.get("resumable"):
|
|
99
|
+
raise ReadError("resume_unavailable")
|
|
100
|
+
run = previous
|
|
101
|
+
else:
|
|
102
|
+
run = {"id": str(uuid.uuid4()), "started_at": now(), "complete": False,
|
|
103
|
+
"next_cursor": None, "cursors": [], "seen_ids": [], "pages": 0,
|
|
104
|
+
"missing_resource_ids": [], "resumable": True}
|
|
105
|
+
run["failure_class"] = None
|
|
106
|
+
run["identity"] = identity
|
|
107
|
+
for _ in range(max_pages):
|
|
108
|
+
requested = run["next_cursor"]
|
|
109
|
+
try:
|
|
110
|
+
items, following, missing, source = read_page(probe, requested)
|
|
111
|
+
except ReadError as exc:
|
|
112
|
+
run["failure_class"] = exc.code
|
|
113
|
+
break
|
|
114
|
+
observed_at = now()
|
|
115
|
+
for row in items:
|
|
116
|
+
identifier = row["remote_id"]
|
|
117
|
+
old = state["items"].get(identifier) or {}
|
|
118
|
+
row["first_observed_at"] = old.get("first_observed_at", observed_at)
|
|
119
|
+
row["last_observed_at"] = observed_at
|
|
120
|
+
row["last_sync_id"] = run["id"]
|
|
121
|
+
state["items"][identifier] = row
|
|
122
|
+
run["seen_ids"] = sorted(set(run["seen_ids"]) | {i["remote_id"] for i in items})
|
|
123
|
+
run["missing_resource_ids"] = sorted(set(run["missing_resource_ids"]) | set(missing))
|
|
124
|
+
run["source"] = source
|
|
125
|
+
run["pages"] += 1
|
|
126
|
+
if requested:
|
|
127
|
+
run["cursors"].append(requested)
|
|
128
|
+
run["next_cursor"] = following
|
|
129
|
+
if following and following in run["cursors"]:
|
|
130
|
+
run["failure_class"], run["resumable"] = "repeated_cursor", False
|
|
131
|
+
elif not following:
|
|
132
|
+
run["complete"], run["resumable"] = True, False
|
|
133
|
+
for identifier, row in state["items"].items():
|
|
134
|
+
if identifier not in run["seen_ids"]:
|
|
135
|
+
row["presence"] = "not_observed"
|
|
136
|
+
row["absence_observed_at"] = observed_at
|
|
137
|
+
run["updated_at"] = observed_at
|
|
138
|
+
state["sync"] = run
|
|
139
|
+
store.save(state) # Page and checkpoint commit in one atomic durable file.
|
|
140
|
+
if run["complete"] or run["failure_class"]:
|
|
141
|
+
break
|
|
142
|
+
if not run["complete"] and not run["failure_class"]:
|
|
143
|
+
run["failure_class"] = "page_limit"
|
|
144
|
+
run["updated_at"] = now()
|
|
145
|
+
state["sync"] = run
|
|
146
|
+
store.save(state)
|
|
147
|
+
return {"version": 1, "brand": brand.nombre, "platform": platform.value,
|
|
148
|
+
"account_id": probe.account_id, "identity": identity, "sync_id": run["id"],
|
|
149
|
+
"complete": run["complete"], "failure_class": run["failure_class"],
|
|
150
|
+
"pagination_complete": run["complete"],
|
|
151
|
+
"details_complete": run["complete"] and not run["missing_resource_ids"],
|
|
152
|
+
"resume_available": run["resumable"], "pages": run["pages"],
|
|
153
|
+
"observed_items": len(run["seen_ids"]), "stored_items": len(state["items"]),
|
|
154
|
+
"missing_resource_ids": run["missing_resource_ids"], "deletion_proven": False,
|
|
155
|
+
"source": run.get("source"), "updated_at": run["updated_at"]}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Versioned read-only inventory/status commands; never interactive authorization."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shlex
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
import typer
|
|
13
|
+
|
|
14
|
+
from socialctl.brands import cargar_brand
|
|
15
|
+
from socialctl.identity import SUPPORTED, ReadError, auth_status, configured_account
|
|
16
|
+
from socialctl.inventory import InventoryStore, sync_content
|
|
17
|
+
from socialctl.media_cli import _capture as capture_remote
|
|
18
|
+
from socialctl.media_registry import safe
|
|
19
|
+
from socialctl.models import Platform
|
|
20
|
+
from socialctl.schedule_remote import RemoteConfig, is_remote
|
|
21
|
+
|
|
22
|
+
from socialctl.workspace import default_root
|
|
23
|
+
|
|
24
|
+
DEFAULT_ROOT = default_root()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def make_http_client():
|
|
28
|
+
return httpx.Client(timeout=30)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def emit(data, json_output):
|
|
32
|
+
if json_output:
|
|
33
|
+
typer.echo(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True))
|
|
34
|
+
else:
|
|
35
|
+
typer.echo(json.dumps(data, ensure_ascii=False, indent=2))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def guarded(operation, json_output):
|
|
39
|
+
try:
|
|
40
|
+
data = operation()
|
|
41
|
+
except ReadError as exc:
|
|
42
|
+
data = {"version": 1, "failure_class": exc.code}
|
|
43
|
+
except Exception:
|
|
44
|
+
data = {"version": 1, "failure_class": "local_state_invalid"}
|
|
45
|
+
emit(data, json_output)
|
|
46
|
+
if data.get("failure_class"):
|
|
47
|
+
raise typer.Exit(1)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def show_auth_status(root, brand, platform, json_output):
|
|
51
|
+
def operation():
|
|
52
|
+
if platform is None:
|
|
53
|
+
raise ReadError("platform_required")
|
|
54
|
+
selected = cargar_brand(root, brand)
|
|
55
|
+
with make_http_client() as client:
|
|
56
|
+
return auth_status(selected, platform, client)
|
|
57
|
+
guarded(operation, json_output)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def remote_health(brand):
|
|
61
|
+
"""Only the fixed server health read. Never local queue state as a proxy."""
|
|
62
|
+
if not is_remote(brand.raiz):
|
|
63
|
+
return {"authority": "local", "configured": False, "state": "not_probed"}
|
|
64
|
+
result = {"authority": "remote", "configured": True, "state": "unknown"}
|
|
65
|
+
try:
|
|
66
|
+
path = safe(brand.raiz / ".socialctl/remote-executor.json")
|
|
67
|
+
config = RemoteConfig.model_validate_json(path.read_bytes())
|
|
68
|
+
command = shlex.join([config.executable, "schedule-health", "--brand", brand.nombre,
|
|
69
|
+
"--root", config.root])
|
|
70
|
+
response = capture_remote(["ssh", "-T", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
|
71
|
+
"-o", "ConnectTimeout=15", "-p", str(config.port), "--", f"{config.user}@{config.host}", command],
|
|
72
|
+
subprocess.DEVNULL, timeout=30)
|
|
73
|
+
data = json.loads(response)
|
|
74
|
+
if data.get("state") not in {"unknown", "started", "finished", "error"} or type(data.get("stale")) is not bool or data.get("backend") not in {"json", "sqlite"}:
|
|
75
|
+
raise ReadError("remote_health_invalid")
|
|
76
|
+
result.update({"state": data["state"], "stale": data["stale"], "backend": data["backend"], "failure_class": None})
|
|
77
|
+
except ReadError as exc:
|
|
78
|
+
result["failure_class"] = exc.code
|
|
79
|
+
except Exception:
|
|
80
|
+
result["failure_class"] = "remote_health_unavailable"
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def register(app, content_app):
|
|
85
|
+
@content_app.command("sync")
|
|
86
|
+
def sync(platform: Platform = typer.Option(..., "--platform"),
|
|
87
|
+
brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
|
|
88
|
+
max_pages: int = typer.Option(20, "--max-pages", min=1, max=100),
|
|
89
|
+
resume: bool = typer.Option(False, "--resume"), json_output: bool = typer.Option(False, "--json")):
|
|
90
|
+
"""Read owned content and save complete pages under verified identity."""
|
|
91
|
+
def operation():
|
|
92
|
+
selected = cargar_brand(root, brand)
|
|
93
|
+
with make_http_client() as client:
|
|
94
|
+
return sync_content(selected, platform, client, max_pages=max_pages, resume=resume)
|
|
95
|
+
guarded(operation, json_output)
|
|
96
|
+
|
|
97
|
+
def listing(root, brand, platform, account):
|
|
98
|
+
selected = cargar_brand(root, brand)
|
|
99
|
+
configured = configured_account(selected, platform)
|
|
100
|
+
selected_account = account or configured
|
|
101
|
+
store = InventoryStore(selected, platform, selected_account)
|
|
102
|
+
state = store.load()
|
|
103
|
+
run = state.get("sync") or {}
|
|
104
|
+
return {"version": 1, "brand": brand, "platform": platform.value, "account_id": selected_account,
|
|
105
|
+
"configured_account_id": configured, "historical_account": selected_account != configured,
|
|
106
|
+
"authority": "cached_observation", "sync": {k: run.get(k) for k in (
|
|
107
|
+
"id", "complete", "failure_class", "updated_at", "pages", "source", "missing_resource_ids")},
|
|
108
|
+
"items": store.public_items(state), "failure_class": None}
|
|
109
|
+
|
|
110
|
+
@content_app.command("list")
|
|
111
|
+
def list_content(platform: Platform = typer.Option(..., "--platform"),
|
|
112
|
+
brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
|
|
113
|
+
account: str | None = typer.Option(None, "--account", help="Explicit historical ID; never reassigned."),
|
|
114
|
+
json_output: bool = typer.Option(False, "--json")):
|
|
115
|
+
"""List latest local observations without network access."""
|
|
116
|
+
guarded(lambda: listing(root, brand, platform, account), json_output)
|
|
117
|
+
|
|
118
|
+
@content_app.command("export")
|
|
119
|
+
def export(platform: Platform = typer.Option(..., "--platform"),
|
|
120
|
+
brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
|
|
121
|
+
account: str | None = typer.Option(None, "--account"),
|
|
122
|
+
json_output: bool = typer.Option(False, "--json")):
|
|
123
|
+
"""Export public inventory fields to stdout; private raw data stays local."""
|
|
124
|
+
guarded(lambda: listing(root, brand, platform, account), json_output)
|
|
125
|
+
|
|
126
|
+
@app.command("preflight")
|
|
127
|
+
@app.command("doctor")
|
|
128
|
+
def doctor(brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
|
|
129
|
+
platform: Platform | None = typer.Option(None, "--platform"),
|
|
130
|
+
media_files: list[Path] = typer.Option(None, "--media", help="Inspect an already-produced file; repeat for multiple files."),
|
|
131
|
+
post: str | None = typer.Option(None, "--post", help="Validate a supplied post and its platform media rules."),
|
|
132
|
+
require_scope: list[str] = typer.Option(None, "--require-scope", help="Require an exact granted scope; requires --platform. Does not request permissions."),
|
|
133
|
+
json_output: bool = typer.Option(False, "--json")):
|
|
134
|
+
"""Check configuration, local media, identity and configured remote executor health."""
|
|
135
|
+
def operation():
|
|
136
|
+
from socialctl.preflight import credential_status, supplied_media_status, post_status, scope_requirements
|
|
137
|
+
if require_scope and platform is None:
|
|
138
|
+
raise ReadError("platform_required_for_scope_check")
|
|
139
|
+
selected = cargar_brand(root, brand)
|
|
140
|
+
media = safe(selected.raiz / "media")
|
|
141
|
+
media_status = {"directory_exists": media.is_dir(), "readable": os.access(media, os.R_OK),
|
|
142
|
+
"ffprobe_available": shutil.which("ffprobe") is not None,
|
|
143
|
+
"file_integrity": "not_checked"}
|
|
144
|
+
media_status["files"] = supplied_media_status(media_files or [])
|
|
145
|
+
if media_files:
|
|
146
|
+
media_status["file_integrity"] = "checked" if all(r["valid"] for r in media_status["files"]) else "failed"
|
|
147
|
+
credentials = credential_status(selected)
|
|
148
|
+
checked_post = post_status(selected, post)
|
|
149
|
+
platforms = [platform] if platform else [p for p in Platform if selected.cuentas.get(p.value)]
|
|
150
|
+
with make_http_client() as client:
|
|
151
|
+
statuses = [auth_status(selected, p, client) for p in platforms]
|
|
152
|
+
requirements = scope_requirements(statuses, require_scope or [])
|
|
153
|
+
queue = remote_health(selected)
|
|
154
|
+
failed = not media_status["directory_exists"] or not media_status["readable"] or any(r["failure_class"] for r in statuses) or queue.get("failure_class") or queue.get("stale") or queue["state"] == "error"
|
|
155
|
+
failed = failed or not credentials["available"] or any(not r["valid"] for r in media_status["files"]) or any(not r["satisfied"] for r in requirements) or (checked_post is not None and not checked_post["valid"])
|
|
156
|
+
return {"version": 1, "brand": brand, "configuration": "loaded", "media": media_status,
|
|
157
|
+
"credential_store": credentials, "post": checked_post, "scope_requirements": requirements,
|
|
158
|
+
"accounts": statuses, "queue": queue, "failure_class": "doctor_unhealthy" if failed else None}
|
|
159
|
+
guarded(operation, json_output)
|
|
160
|
+
|
|
161
|
+
@app.command("capabilities")
|
|
162
|
+
def capabilities(brand: str = typer.Option(..., "--brand"), root: Path = typer.Option(DEFAULT_ROOT, "--root"),
|
|
163
|
+
platform: str | None = typer.Option(None, "--platform"),
|
|
164
|
+
json_output: bool = typer.Option(False, "--json")):
|
|
165
|
+
"""Documented classification; does not indicate granted permissions or account availability."""
|
|
166
|
+
from socialctl.capabilities import capability_report
|
|
167
|
+
def operation():
|
|
168
|
+
selected = cargar_brand(root, brand)
|
|
169
|
+
return {**capability_report(platform), "brand": selected.nombre,
|
|
170
|
+
"account_eligibility": "not_probed", "failure_class": None}
|
|
171
|
+
guarded(operation, json_output)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Provider inventory reads with explicit field and ownership boundaries."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from socialctl.identity import ReadError, remote_id
|
|
5
|
+
from socialctl.models import Platform
|
|
6
|
+
|
|
7
|
+
YOUTUBE_PARTS = "snippet,status,contentDetails,processingDetails,localizations"
|
|
8
|
+
FACEBOOK_FIELDS = "id,from,title,description,created_time,updated_time,status,published,permalink_url"
|
|
9
|
+
INSTAGRAM_FIELDS = "id,owner,caption,media_type,media_product_type,timestamp,permalink"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def cursor(value):
|
|
13
|
+
if not isinstance(value, str) or not value or len(value) > 2048 or any(ord(c) < 32 for c in value):
|
|
14
|
+
raise ReadError("invalid_cursor")
|
|
15
|
+
return value
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def read_page(probe, next_cursor):
|
|
19
|
+
if probe.identity is None:
|
|
20
|
+
raise ReadError("identity_unverified")
|
|
21
|
+
if probe.platform is Platform.YOUTUBE:
|
|
22
|
+
playlist = remote_id(probe.uploads_playlist)
|
|
23
|
+
params = {"part": "contentDetails", "playlistId": playlist, "maxResults": "50"}
|
|
24
|
+
if next_cursor:
|
|
25
|
+
params["pageToken"] = cursor(next_cursor)
|
|
26
|
+
data = probe.get("playlistItems", params)
|
|
27
|
+
entries = data.get("items")
|
|
28
|
+
if not isinstance(entries, list):
|
|
29
|
+
raise ReadError("invalid_response")
|
|
30
|
+
try:
|
|
31
|
+
ids = [remote_id(row["contentDetails"]["videoId"]) for row in entries]
|
|
32
|
+
except (KeyError, TypeError):
|
|
33
|
+
raise ReadError("invalid_response") from None
|
|
34
|
+
if len(ids) > 50:
|
|
35
|
+
raise ReadError("invalid_response")
|
|
36
|
+
rows = []
|
|
37
|
+
if ids:
|
|
38
|
+
videos = probe.get("videos", {"part": YOUTUBE_PARTS, "id": ",".join(ids), "maxResults": "50"})
|
|
39
|
+
rows = videos.get("items")
|
|
40
|
+
if not isinstance(rows, list) or any(not isinstance(row, dict) or row.get("id") not in ids for row in rows):
|
|
41
|
+
raise ReadError("invalid_response")
|
|
42
|
+
following = data.get("nextPageToken")
|
|
43
|
+
missing = sorted(set(ids) - {row["id"] for row in rows})
|
|
44
|
+
source = "youtube.uploads_playlist"
|
|
45
|
+
else:
|
|
46
|
+
facebook = probe.platform is Platform.FACEBOOK
|
|
47
|
+
edge = "videos" if facebook else "media"
|
|
48
|
+
params = {"fields": FACEBOOK_FIELDS if facebook else INSTAGRAM_FIELDS, "limit": "100"}
|
|
49
|
+
if next_cursor:
|
|
50
|
+
params["after"] = cursor(next_cursor)
|
|
51
|
+
data = probe.get(f"{probe.account_id}/{edge}", params)
|
|
52
|
+
rows = data.get("data")
|
|
53
|
+
if not isinstance(rows, list) or len(rows) > 100 or any(not isinstance(row, dict) for row in rows):
|
|
54
|
+
raise ReadError("invalid_response")
|
|
55
|
+
paging = data.get("paging", {})
|
|
56
|
+
if not isinstance(paging, dict):
|
|
57
|
+
raise ReadError("invalid_response")
|
|
58
|
+
cursors = paging.get("cursors", {})
|
|
59
|
+
if not isinstance(cursors, dict):
|
|
60
|
+
raise ReadError("invalid_response")
|
|
61
|
+
for direction in ("before", "after"):
|
|
62
|
+
if direction in cursors:
|
|
63
|
+
cursor(cursors[direction])
|
|
64
|
+
if "next" in paging:
|
|
65
|
+
if not isinstance(paging["next"], str) or not paging["next"]:
|
|
66
|
+
raise ReadError("invalid_response")
|
|
67
|
+
following = cursor(cursors.get("after"))
|
|
68
|
+
else:
|
|
69
|
+
following = None
|
|
70
|
+
missing, source = [], f"{probe.platform.value}.{edge}"
|
|
71
|
+
# Never request provider-supplied paging URLs; retain only opaque cursors.
|
|
72
|
+
if following is not None:
|
|
73
|
+
following = cursor(following)
|
|
74
|
+
items = [normalize(probe, row, source) for row in rows]
|
|
75
|
+
return items, following, missing, source
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def normalize(probe, row, source):
|
|
79
|
+
identifier = remote_id(row.get("id"))
|
|
80
|
+
for field in ("snippet", "contentDetails", "processingDetails", "from", "owner"):
|
|
81
|
+
if row.get(field) is not None and not isinstance(row[field], dict):
|
|
82
|
+
raise ReadError("invalid_response")
|
|
83
|
+
snippet = row.get("snippet") or {}
|
|
84
|
+
if probe.platform is Platform.YOUTUBE:
|
|
85
|
+
owner = snippet.get("channelId")
|
|
86
|
+
else:
|
|
87
|
+
owner = (row.get("from" if probe.platform is Platform.FACEBOOK else "owner") or {}).get("id")
|
|
88
|
+
if owner != probe.account_id:
|
|
89
|
+
raise ReadError("content_owner_mismatch")
|
|
90
|
+
details = row.get("contentDetails") or {}
|
|
91
|
+
return {"version": 1, "brand": probe.brand.nombre, "platform": probe.platform.value,
|
|
92
|
+
"account_id": probe.account_id, "remote_id": identifier, "source": source,
|
|
93
|
+
"format": row.get("media_product_type") or row.get("media_type") or ("video" if probe.platform is not Platform.INSTAGRAM else None),
|
|
94
|
+
"language": snippet.get("defaultLanguage"), "audio_language": snippet.get("defaultAudioLanguage"),
|
|
95
|
+
"title": snippet.get("title", row.get("title")),
|
|
96
|
+
"description": snippet.get("description", row.get("description", row.get("caption"))),
|
|
97
|
+
"published_at": snippet.get("publishedAt", row.get("timestamp", row.get("created_time"))),
|
|
98
|
+
"updated_at": row.get("updated_time"), "observed_status": row.get("status"),
|
|
99
|
+
"published": row.get("published"), "processing": row.get("processingDetails"),
|
|
100
|
+
"restrictions": details.get("regionRestriction"), "duration": details.get("duration"),
|
|
101
|
+
"presence": "observed", "deletion_proven": False, "raw": row}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Management services for existing remote content."""
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Full batch previews and the same exact-digest approval used by V1 commands."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import difflib
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from socialctl.approval_cli import read_approval
|
|
11
|
+
|
|
12
|
+
from socialctl.management.batches import BatchStore, apply_batch, prepare_batch, prepare_restore
|
|
13
|
+
from socialctl.management.changes import ChangeError
|
|
14
|
+
from socialctl.management.youtube import YouTubeManagementError
|
|
15
|
+
from socialctl.management.youtube_metadata import YouTubeMetadataClient
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def render_batch_preview(batch):
|
|
19
|
+
def formatted(value):
|
|
20
|
+
return json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False)
|
|
21
|
+
lines = [f"V2 batch: {batch.id}", f"Brand: {batch.brand} ({batch.brand_root})",
|
|
22
|
+
f"Channel: {batch.account}", f"Exact fingerprint for approval: {batch.fingerprint}",
|
|
23
|
+
"Linked files:\n" + formatted(batch.source_files)]
|
|
24
|
+
if batch.restored_from:
|
|
25
|
+
lines.append(f"Proposed restoration of: {batch.restored_from}")
|
|
26
|
+
for number, op in enumerate(batch.operations, 1):
|
|
27
|
+
before, after = formatted(op.before), formatted(op.after)
|
|
28
|
+
lines.extend([f"\nOperation {number}: {op.video_id} / {op.kind} / {op.status}",
|
|
29
|
+
f"Operation fingerprint: {op.fingerprint}",
|
|
30
|
+
"Explicit patch:\n" + formatted(op.patch),
|
|
31
|
+
"Before:\n" + before, "After (complete body per part):\n" + after,
|
|
32
|
+
"Diff:\n" + ("\n".join(difflib.unified_diff(before.splitlines(), after.splitlines(),
|
|
33
|
+
fromfile="current", tofile="proposed", lineterm="")) or "(no differences)")])
|
|
34
|
+
snippet = op.after.get("snippet", op.observed["snippet"])
|
|
35
|
+
visible = re.findall(r"(?<!\w)#[\w]+", snippet.get("title", "") + "\n" + snippet.get("description", ""))
|
|
36
|
+
lines.append("Internal tags: " + formatted(snippet.get("tags", [])))
|
|
37
|
+
lines.append("Visible hashtags in title/description: " + formatted(visible))
|
|
38
|
+
if op.resets:
|
|
39
|
+
lines.append("Explicit resets: " + formatted(op.resets))
|
|
40
|
+
if op.kind == "schedule":
|
|
41
|
+
lines.append("YouTube native scheduling: private + user declaration of never published; "
|
|
42
|
+
"API determines historical eligibility. This is separate from the server queue.")
|
|
43
|
+
if op.kind == "chapters":
|
|
44
|
+
lines.append("Chapters: supplied text validated against API duration; does not prove UI feature availability.")
|
|
45
|
+
lines.extend(["Restoration unavailable: " + formatted(batch.unavailable),
|
|
46
|
+
"Limitations: metadata only; does not restore deletions or media uploads. "
|
|
47
|
+
"defaultAudioLanguage is preserved; editing it is unverified."])
|
|
48
|
+
return "\n".join(lines)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def apply_selected(selected, change_id, yes, approval_fingerprint=None, *, approval_stdin=False):
|
|
52
|
+
from socialctl.management import cli
|
|
53
|
+
store = BatchStore(selected.raiz)
|
|
54
|
+
batch = store.load(change_id)
|
|
55
|
+
typer.echo("Complete DRY-RUN before approval; no YouTube writes performed.")
|
|
56
|
+
typer.echo(render_batch_preview(batch))
|
|
57
|
+
if yes:
|
|
58
|
+
typer.echo("--yes does not replace exact batch approval.")
|
|
59
|
+
try:
|
|
60
|
+
approval = read_approval(approval_fingerprint, approval_stdin=approval_stdin, prompt="Enter the exact batch fingerprint to approve")
|
|
61
|
+
except ValueError as exc:
|
|
62
|
+
cli._fail(str(exc))
|
|
63
|
+
except (EOFError, KeyboardInterrupt):
|
|
64
|
+
cli._fail("Application cancelled: exact approval missing")
|
|
65
|
+
if approval != batch.fingerprint:
|
|
66
|
+
cli._fail("Application cancelled: incorrect fingerprint")
|
|
67
|
+
with cli.make_http_client() as http:
|
|
68
|
+
result = apply_batch(YouTubeMetadataClient(selected, http), store, change_id, approval)
|
|
69
|
+
for op in result.operations:
|
|
70
|
+
typer.echo(f"{op.video_id}: {op.status}")
|
|
71
|
+
if any(op.status != "applied" for op in result.operations):
|
|
72
|
+
typer.echo("Partial result. Resume processes only pending operations; uncertain attempts are reread only.")
|
|
73
|
+
raise typer.Exit(1)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def register(content_app, changes_app, default_root):
|
|
77
|
+
@content_app.command("edit-batch")
|
|
78
|
+
def content_edit_batch(
|
|
79
|
+
file: Path = typer.Option(..., "--file"),
|
|
80
|
+
brand: str = typer.Option(..., "--brand"),
|
|
81
|
+
root: Path = typer.Option(default_root, "--root"),
|
|
82
|
+
dry_run: bool = typer.Option(False, "--dry-run"),
|
|
83
|
+
):
|
|
84
|
+
"""Prepare a V2 batch with explicit IDs and one operation per video."""
|
|
85
|
+
from socialctl.management import cli
|
|
86
|
+
if not dry_run:
|
|
87
|
+
cli._fail("Preparing a batch requires --dry-run and its full preview")
|
|
88
|
+
selected = cli._brand(root, brand)
|
|
89
|
+
try:
|
|
90
|
+
with cli.make_http_client() as http:
|
|
91
|
+
batch = prepare_batch(YouTubeMetadataClient(selected, http), BatchStore(selected.raiz), file)
|
|
92
|
+
except (ChangeError, YouTubeManagementError, OSError) as exc:
|
|
93
|
+
cli._fail(str(exc))
|
|
94
|
+
typer.echo("DRY-RUN: no YouTube writes performed.")
|
|
95
|
+
typer.echo(render_batch_preview(batch))
|
|
96
|
+
|
|
97
|
+
@changes_app.command("restore")
|
|
98
|
+
def changes_restore(
|
|
99
|
+
change_id: str = typer.Argument(...),
|
|
100
|
+
brand: str = typer.Option(..., "--brand"),
|
|
101
|
+
root: Path = typer.Option(default_root, "--root"),
|
|
102
|
+
dry_run: bool = typer.Option(False, "--dry-run"),
|
|
103
|
+
):
|
|
104
|
+
"""Propose restoring saved fields against a fresh remote read."""
|
|
105
|
+
from socialctl.management import cli
|
|
106
|
+
if not dry_run:
|
|
107
|
+
cli._fail("Restoration requires --dry-run; then approve the new fingerprint")
|
|
108
|
+
selected = cli._brand(root, brand)
|
|
109
|
+
try:
|
|
110
|
+
with cli.make_http_client() as http:
|
|
111
|
+
batch = prepare_restore(YouTubeMetadataClient(selected, http), BatchStore(selected.raiz), change_id)
|
|
112
|
+
except (ChangeError, YouTubeManagementError, OSError) as exc:
|
|
113
|
+
cli._fail(str(exc))
|
|
114
|
+
typer.echo("DRY-RUN: new local proposal, no remote writes.")
|
|
115
|
+
typer.echo(render_batch_preview(batch))
|