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.

Files changed (224) hide show
  1. socialcli-0.3.0.dist-info/METADATA +168 -0
  2. socialcli-0.3.0.dist-info/RECORD +224 -0
  3. socialcli-0.3.0.dist-info/WHEEL +4 -0
  4. socialcli-0.3.0.dist-info/entry_points.txt +3 -0
  5. socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. socialctl/__init__.py +0 -0
  7. socialctl/__main__.py +6 -0
  8. socialctl/adapters/__init__.py +6 -0
  9. socialctl/adapters/base.py +68 -0
  10. socialctl/adapters/errores.py +56 -0
  11. socialctl/adapters/facebook.py +180 -0
  12. socialctl/adapters/instagram.py +442 -0
  13. socialctl/adapters/tiktok.py +535 -0
  14. socialctl/adapters/youtube.py +331 -0
  15. socialctl/agent_errors.py +176 -0
  16. socialctl/agent_guide.py +23 -0
  17. socialctl/approval_cli.py +27 -0
  18. socialctl/auth.py +139 -0
  19. socialctl/authflow.py +344 -0
  20. socialctl/brands.py +194 -0
  21. socialctl/capabilities.py +57 -0
  22. socialctl/capabilities.yml +5945 -0
  23. socialctl/cli.py +1766 -0
  24. socialctl/connection_service/__init__.py +0 -0
  25. socialctl/connection_service/__main__.py +33 -0
  26. socialctl/connection_service/app.py +496 -0
  27. socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
  28. socialctl/connection_service/assets/connection.css +75 -0
  29. socialctl/connection_service/assets/facebook.webp +0 -0
  30. socialctl/connection_service/assets/instagram.svg +194 -0
  31. socialctl/connection_service/assets/socialcli-logo.png +0 -0
  32. socialctl/connection_service/assets/tiktok.png +0 -0
  33. socialctl/connection_service/assets/youtube.svg +1 -0
  34. socialctl/connection_service/landing.py +146 -0
  35. socialctl/connection_service/legacy.py +48 -0
  36. socialctl/connection_service/peer.py +13 -0
  37. socialctl/connection_service/providers.py +324 -0
  38. socialctl/connection_service/settings.py +76 -0
  39. socialctl/connection_service/store.py +124 -0
  40. socialctl/connections/__init__.py +0 -0
  41. socialctl/connections/account_cli.py +438 -0
  42. socialctl/connections/cli.py +379 -0
  43. socialctl/connections/client.py +126 -0
  44. socialctl/connections/credential_cli.py +224 -0
  45. socialctl/connections/credential_store.py +49 -0
  46. socialctl/connections/file_store.py +193 -0
  47. socialctl/connections/keychain.py +78 -0
  48. socialctl/connections/meta_user.py +81 -0
  49. socialctl/connections/rotation_cli.py +116 -0
  50. socialctl/connections/saas_client.py +91 -0
  51. socialctl/connections/temporary_media.py +62 -0
  52. socialctl/delivery_options.py +70 -0
  53. socialctl/engagement.py +200 -0
  54. socialctl/engagement_cli.py +50 -0
  55. socialctl/executor.py +135 -0
  56. socialctl/formatter.py +291 -0
  57. socialctl/hosted_media.py +152 -0
  58. socialctl/identity.py +200 -0
  59. socialctl/inbox.py +298 -0
  60. socialctl/inbox_cli.py +46 -0
  61. socialctl/inventory.py +155 -0
  62. socialctl/inventory_cli.py +171 -0
  63. socialctl/inventory_sources.py +101 -0
  64. socialctl/management/__init__.py +1 -0
  65. socialctl/management/batch_cli.py +115 -0
  66. socialctl/management/batches.py +325 -0
  67. socialctl/management/changes.py +485 -0
  68. socialctl/management/cli.py +227 -0
  69. socialctl/management/comments_cli.py +352 -0
  70. socialctl/management/community_batch_cli.py +63 -0
  71. socialctl/management/community_batches.py +294 -0
  72. socialctl/management/community_changes.py +370 -0
  73. socialctl/management/community_cli.py +142 -0
  74. socialctl/management/community_schema.py +119 -0
  75. socialctl/management/facebook_groups.py +1118 -0
  76. socialctl/management/groups_cli.py +274 -0
  77. socialctl/management/inbox_readers.py +87 -0
  78. socialctl/management/meta_changes.py +197 -0
  79. socialctl/management/meta_cli.py +342 -0
  80. socialctl/management/meta_client.py +631 -0
  81. socialctl/management/meta_comment_inbox.py +565 -0
  82. socialctl/management/meta_comments.py +587 -0
  83. socialctl/management/meta_errors.py +59 -0
  84. socialctl/management/meta_pagination.py +52 -0
  85. socialctl/management/meta_schema.py +128 -0
  86. socialctl/management/meta_webhooks.py +147 -0
  87. socialctl/management/metadata_parts.py +144 -0
  88. socialctl/management/owned_assets.py +85 -0
  89. socialctl/management/owned_changes.py +470 -0
  90. socialctl/management/owned_cli.py +128 -0
  91. socialctl/management/owned_reorder.py +62 -0
  92. socialctl/management/owned_schema.py +368 -0
  93. socialctl/management/reply_context.py +24 -0
  94. socialctl/management/reply_evidence.py +80 -0
  95. socialctl/management/resource_changes.py +407 -0
  96. socialctl/management/resource_cli.py +136 -0
  97. socialctl/management/snippet_readback.py +26 -0
  98. socialctl/management/stories.py +713 -0
  99. socialctl/management/stories_cli.py +172 -0
  100. socialctl/management/youtube.py +323 -0
  101. socialctl/management/youtube_community.py +326 -0
  102. socialctl/management/youtube_metadata.py +122 -0
  103. socialctl/management/youtube_owned.py +259 -0
  104. socialctl/management/youtube_resources.py +305 -0
  105. socialctl/media.py +269 -0
  106. socialctl/media_cli.py +183 -0
  107. socialctl/media_ingress.py +211 -0
  108. socialctl/media_preflight.py +114 -0
  109. socialctl/media_registry.py +301 -0
  110. socialctl/media_requirements.py +52 -0
  111. socialctl/metricas/__init__.py +6 -0
  112. socialctl/metricas/almacen.py +133 -0
  113. socialctl/metricas/analytics_changes.py +295 -0
  114. socialctl/metricas/analytics_cli.py +191 -0
  115. socialctl/metricas/analytics_client.py +304 -0
  116. socialctl/metricas/analytics_ingest.py +260 -0
  117. socialctl/metricas/analytics_schema.py +174 -0
  118. socialctl/metricas/base.py +147 -0
  119. socialctl/metricas/facebook.py +418 -0
  120. socialctl/metricas/insights.py +227 -0
  121. socialctl/metricas/instagram.py +133 -0
  122. socialctl/metricas/modelos.py +87 -0
  123. socialctl/metricas/piezas.py +134 -0
  124. socialctl/metricas/reach.py +94 -0
  125. socialctl/metricas/reporting_client.py +112 -0
  126. socialctl/metricas/resumen.py +251 -0
  127. socialctl/metricas/slugs.py +89 -0
  128. socialctl/metricas/tiktok.py +185 -0
  129. socialctl/metricas/youtube.py +403 -0
  130. socialctl/migration_cli.py +60 -0
  131. socialctl/migration_files.py +68 -0
  132. socialctl/models.py +150 -0
  133. socialctl/native_schedule/__init__.py +13 -0
  134. socialctl/native_schedule/api_delivery.py +15 -0
  135. socialctl/native_schedule/api_reconcile.py +40 -0
  136. socialctl/native_schedule/approval.py +160 -0
  137. socialctl/native_schedule/cadence.py +73 -0
  138. socialctl/native_schedule/cli.py +510 -0
  139. socialctl/native_schedule/dispatcher.py +120 -0
  140. socialctl/native_schedule/facebook.py +112 -0
  141. socialctl/native_schedule/facebook_reels.py +140 -0
  142. socialctl/native_schedule/first_comment.py +181 -0
  143. socialctl/native_schedule/handoff.py +193 -0
  144. socialctl/native_schedule/instagram_delivery.py +224 -0
  145. socialctl/native_schedule/instagram_runtime.py +66 -0
  146. socialctl/native_schedule/inventory.py +70 -0
  147. socialctl/native_schedule/migration.py +310 -0
  148. socialctl/native_schedule/models.py +103 -0
  149. socialctl/native_schedule/reconcile.py +83 -0
  150. socialctl/native_schedule/remote_data.py +177 -0
  151. socialctl/native_schedule/report.py +151 -0
  152. socialctl/native_schedule/store.py +560 -0
  153. socialctl/native_schedule/verification.py +32 -0
  154. socialctl/native_schedule/youtube.py +339 -0
  155. socialctl/operation_output.py +87 -0
  156. socialctl/plantillas/accounts.yml +33 -0
  157. socialctl/plantillas/brand.md +95 -0
  158. socialctl/plantillas/estrategia.md +64 -0
  159. socialctl/postfile.py +240 -0
  160. socialctl/preflight.py +73 -0
  161. socialctl/publication_policy.py +34 -0
  162. socialctl/publication_status.py +75 -0
  163. socialctl/publication_steps.py +398 -0
  164. socialctl/publish_output.py +96 -0
  165. socialctl/publisher.py +445 -0
  166. socialctl/queue_migration.py +302 -0
  167. socialctl/read_budget.py +224 -0
  168. socialctl/read_reports.py +91 -0
  169. socialctl/rutas.py +103 -0
  170. socialctl/saas/__init__.py +1 -0
  171. socialctl/saas/access.py +75 -0
  172. socialctl/saas/auth.py +213 -0
  173. socialctl/saas/backup.py +124 -0
  174. socialctl/saas/billing.py +327 -0
  175. socialctl/saas/billing_enrollment.py +1237 -0
  176. socialctl/saas/billing_enrollment_schema.py +519 -0
  177. socialctl/saas/billing_inventory.py +775 -0
  178. socialctl/saas/billing_reconcile.py +127 -0
  179. socialctl/saas/billing_routes.py +27 -0
  180. socialctl/saas/budget.py +66 -0
  181. socialctl/saas/connections.py +374 -0
  182. socialctl/saas/consent.py +52 -0
  183. socialctl/saas/lifecycle.py +341 -0
  184. socialctl/saas/mail.py +89 -0
  185. socialctl/saas/maintenance.py +68 -0
  186. socialctl/saas/meta_user.py +298 -0
  187. socialctl/saas/meta_webhooks.py +358 -0
  188. socialctl/saas/migration.py +107 -0
  189. socialctl/saas/models.py +8 -0
  190. socialctl/saas/operations.py +102 -0
  191. socialctl/saas/pages.py +126 -0
  192. socialctl/saas/pairing.py +158 -0
  193. socialctl/saas/permissions.py +57 -0
  194. socialctl/saas/reminders.py +128 -0
  195. socialctl/saas/renewal.py +74 -0
  196. socialctl/saas/restore_guard.py +229 -0
  197. socialctl/saas/revocation.py +97 -0
  198. socialctl/saas/rotation.py +114 -0
  199. socialctl/saas/routes.py +221 -0
  200. socialctl/saas/settings.py +34 -0
  201. socialctl/saas/store.py +106 -0
  202. socialctl/saas/temporary_media.py +245 -0
  203. socialctl/saas/webhooks.py +76 -0
  204. socialctl/schedule_remote.py +262 -0
  205. socialctl/schedule_sqlite.py +44 -0
  206. socialctl/scheduler.py +581 -0
  207. socialctl/scheduler_launchd.py +319 -0
  208. socialctl/scheduler_systemd.py +167 -0
  209. socialctl/source_links.py +119 -0
  210. socialctl/ui/__init__.py +1 -0
  211. socialctl/ui/assets/agent-manual.md +850 -0
  212. socialctl/ui/assets/agents.md +27 -0
  213. socialctl/ui/assets/components.css +20 -0
  214. socialctl/ui/assets/connection-layout.css +53 -0
  215. socialctl/ui/assets/otp.template.html +10 -0
  216. socialctl/ui/assets/tokens.css +1 -0
  217. socialctl/ui/assets/trial.template.html +11 -0
  218. socialctl/ui/assets/web-layout.css +38 -0
  219. socialctl/ui/email/otp.html +10 -0
  220. socialctl/ui/email/trial.html +11 -0
  221. socialctl/upload_consent.py +13 -0
  222. socialctl/workspace.py +8 -0
  223. socialctl/youtube_data.py +471 -0
  224. socialctl/youtube_data_service.py +225 -0
@@ -0,0 +1,52 @@
1
+ """Read-only pagination helpers; remote links never become request URLs."""
2
+ from urllib.parse import parse_qs, urlsplit
3
+
4
+
5
+ def next_time_params(next_url, endpoint, params):
6
+ if not isinstance(next_url, str) or len(next_url) > 16384:
7
+ return None
8
+ try:
9
+ parsed, expected = urlsplit(next_url), urlsplit(endpoint)
10
+ if (parsed.scheme != 'https' or parsed.netloc != expected.netloc
11
+ or parsed.path != expected.path or parsed.fragment):
12
+ return None
13
+ query = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=30)
14
+ if any(len(values) != 1 for values in query.values()):
15
+ return None
16
+ for key in query.keys() - {'access_token', 'since', 'until'}:
17
+ if key not in params or query[key][0] != str(params[key]):
18
+ return None
19
+ dates = {key: query[key][0] for key in ('since', 'until')}
20
+ if any(not value.isascii() or not value.isdigit() or len(value) > 12 for value in dates.values()):
21
+ return None
22
+ if int(dates['since']) >= int(dates['until']):
23
+ return None
24
+ if all(str(params.get(key)) == value for key, value in dates.items()):
25
+ return None
26
+ return {**params, **dates}
27
+ except (ValueError, KeyError):
28
+ return None
29
+
30
+
31
+ def merge_metric(previous, incoming):
32
+ """Preserve exact values; never add counts or replace conflicting evidence."""
33
+ if any(previous.get(key) != incoming.get(key) for key in ('name', 'period')):
34
+ return None
35
+ if 'id' in previous and 'id' in incoming and previous['id'] != incoming['id']:
36
+ return None
37
+ old, new = previous.get('values'), incoming.get('values')
38
+ if not isinstance(old, list) or not isinstance(new, list):
39
+ return None
40
+ merged = list(old)
41
+ for value in new:
42
+ if not isinstance(value, dict):
43
+ return None
44
+ if value in merged:
45
+ continue
46
+ stamp = value.get('end_time')
47
+ if not isinstance(stamp, str) or not stamp or any(
48
+ not isinstance(v, dict) or not v.get('end_time') or v['end_time'] == stamp
49
+ for v in merged):
50
+ return None
51
+ merged.append(value)
52
+ return {**previous, 'values': merged}
@@ -0,0 +1,128 @@
1
+ """Typed, method-specific Meta edits. Read fields never imply write permission."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import yaml
9
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
10
+
11
+ from socialctl.management.changes import ChangeError
12
+
13
+
14
+ class MetaError(ChangeError):
15
+ pass
16
+
17
+
18
+ class MetaRejected(MetaError):
19
+ pass
20
+
21
+
22
+ class MetaUncertain(MetaError):
23
+ pass
24
+
25
+
26
+ def meta_id(value, *, composite=False):
27
+ pattern = r"[0-9]{1,64}(?:_[0-9]{1,64})?" if composite else r"[0-9]{1,64}"
28
+ if not isinstance(value, str) or not re.fullmatch(pattern, value):
29
+ raise MetaError("Invalid Meta ID for this resource; URLs/paths are not accepted")
30
+ return value
31
+
32
+
33
+ class Strict(BaseModel):
34
+ model_config = ConfigDict(extra="forbid", strict=True)
35
+
36
+
37
+ class PagePatch(Strict):
38
+ about: str | None = None
39
+ bio: str | None = None
40
+ description: str | None = None
41
+ company_overview: str | None = None
42
+ general_info: str | None = None
43
+ mission: str | None = None
44
+ phone: str | None = None
45
+ website: str | None = None
46
+
47
+
48
+ class PostPatch(Strict):
49
+ message: str | None = None
50
+
51
+
52
+ class VideoPatch(Strict):
53
+ description: str | None = None
54
+
55
+
56
+ class MediaPatch(Strict):
57
+ comment_enabled: bool | None = None
58
+
59
+
60
+ PATCHES = {"profile-update": PagePatch, "post-update": PostPatch,
61
+ "video-update": VideoPatch, "media-update": MediaPatch}
62
+ ACTIONS = set(PATCHES) | {"post-delete", "video-delete", "media-delete", "comment-moderate",
63
+ "like", "unlike", "subscription-set", "subscription-remove",
64
+ "schedule-reprogram", "schedule-cancel", "mention-reply"}
65
+
66
+
67
+ class MetaEdit(Strict):
68
+ version: Literal[1] = 1
69
+ action: str
70
+ target_id: str
71
+ patch: dict | None = None
72
+ comment_id: str | None = None
73
+ hide: bool | None = None
74
+ subscribed_fields: list[str] | None = None
75
+ scheduled_publish_time: int | None = Field(default=None, gt=0)
76
+ message: str | None = None
77
+ media_id: str | None = None
78
+
79
+ @model_validator(mode="before")
80
+ @classmethod
81
+ def exact_fields(cls, raw):
82
+ if not isinstance(raw, dict) or raw.get("action") not in ACTIONS:
83
+ raise MetaError("unsupported Meta action")
84
+ action = raw["action"]
85
+ optional = {"comment-moderate": {"comment_id", "hide"},
86
+ "subscription-set": {"subscribed_fields"},
87
+ "schedule-reprogram": {"scheduled_publish_time"},
88
+ "mention-reply": {"comment_id", "media_id", "message"}}
89
+ required = {"action", "target_id"} | ({"patch"} if action in PATCHES else optional.get(action, set()))
90
+ allowed = required | {"version"} | ({"comment_id"} if action in {"like", "unlike"} else set())
91
+ if required - set(raw) or set(raw) - allowed or any(raw[k] is None for k in raw):
92
+ raise MetaError("missing/extra/null action fields; omission preserves values")
93
+ meta_id(raw["target_id"], composite=True)
94
+ if "comment_id" in raw:
95
+ meta_id(raw["comment_id"], composite=True)
96
+ if "media_id" in raw:
97
+ meta_id(raw["media_id"])
98
+ if action in PATCHES:
99
+ patch = raw["patch"]
100
+ if not isinstance(patch, dict) or not patch or any(v is None for v in patch.values()):
101
+ raise MetaError("empty/null patch; omission preserves values")
102
+ PATCHES[action].model_validate(patch)
103
+ if any(isinstance(v, str) and len(v) > 63206 for v in patch.values()):
104
+ raise MetaError("text exceeds local limit")
105
+ if action == "subscription-set":
106
+ values = raw["subscribed_fields"]
107
+ if not isinstance(values, list) or not 1 <= len(values) <= 3 or len(set(values)) != len(values):
108
+ raise MetaError("select explicit, unique subscription fields")
109
+ if action == "mention-reply" and (not isinstance(raw["message"], str) or not 0 < len(raw["message"]) <= 2200):
110
+ raise MetaError("invalid explicit reply text")
111
+ return raw
112
+
113
+
114
+ def validate_edit(value):
115
+ try:
116
+ return MetaEdit.model_validate(value.model_dump(exclude_none=True) if isinstance(value, MetaEdit) else value)
117
+ except ValidationError:
118
+ raise MetaError("invalid Meta proposal types/fields") from None
119
+
120
+
121
+ def load_edit(path):
122
+ try:
123
+ path = Path(path)
124
+ if path.stat().st_size > 1024 * 1024:
125
+ raise MetaError("proposal exceeds 1 MiB")
126
+ return validate_edit(yaml.safe_load(path.read_text(encoding="utf-8")))
127
+ except (OSError, yaml.YAMLError):
128
+ raise MetaError("failed to read proposal YAML") from None
@@ -0,0 +1,147 @@
1
+ """Offline webhook boundary; no listener, subscriptions, messaging or mutations.
2
+
3
+ HMAC authenticates exact raw bytes. Events are hints for a subsequent owned GET,
4
+ never an authoritative replacement for remote content or an instruction to write.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import os
12
+ import sqlite3
13
+ from contextlib import contextmanager
14
+
15
+ from socialctl.management.meta_schema import MetaError, meta_id
16
+ from socialctl.management.resource_changes import ResourceStore
17
+ from socialctl.media_registry import parse_json
18
+
19
+ MAX_BODY = 1024 * 1024
20
+ MAX_EVENTS = 20000 # Never evict replay protection silently.
21
+
22
+
23
+ def verify_challenge(mode, provided_token, challenge, expected_token):
24
+ if (mode != "subscribe" or not all(isinstance(v, str) and v for v in (provided_token, expected_token, challenge))
25
+ or len(challenge) > 4096 or not hmac.compare_digest(provided_token.encode(), expected_token.encode())):
26
+ raise MetaError("webhook verification rejected")
27
+ return challenge
28
+
29
+
30
+ class WebhookStore:
31
+ def __init__(self, brand, platform):
32
+ if platform not in {"facebook", "instagram"}:
33
+ raise MetaError("unsupported webhook platform")
34
+ self.brand, self.platform = brand, platform
35
+ self.account_id = meta_id((brand.cuentas.get(platform) or {}).get("page_id" if platform == "facebook" else "ig_user_id"))
36
+ self.root = brand.raiz / ".socialctl" / "meta-webhooks"
37
+ self.path = self.root / f"{platform}-{self.account_id}.sqlite3"
38
+
39
+ @contextmanager
40
+ def database(self):
41
+ guard = ResourceStore(self.brand.raiz)
42
+ guard.root = self.root
43
+ guard._ensure_root()
44
+ if self.path.is_symlink():
45
+ raise MetaError("webhook DB does not accept symlinks")
46
+ fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
47
+ os.close(fd)
48
+ conn = sqlite3.connect(self.path, timeout=5)
49
+ try:
50
+ conn.execute("PRAGMA synchronous=FULL")
51
+ conn.execute("CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, target TEXT NOT NULL, source_time INTEGER NOT NULL, payload TEXT NOT NULL, stale INTEGER NOT NULL, state TEXT NOT NULL, observation TEXT)")
52
+ conn.execute("BEGIN IMMEDIATE")
53
+ yield conn
54
+ conn.commit()
55
+ except Exception:
56
+ conn.rollback()
57
+ raise
58
+ finally:
59
+ conn.close()
60
+
61
+ def ingest(self, raw, signature, app_secret):
62
+ if (not isinstance(raw, bytes) or not 0 < len(raw) <= MAX_BODY or not isinstance(signature, str)
63
+ or not isinstance(app_secret, str) or not app_secret):
64
+ raise MetaError("invalid webhook body/signature/secret")
65
+ expected = "sha256=" + hmac.new(app_secret.encode(), raw, hashlib.sha256).hexdigest()
66
+ if not hmac.compare_digest(signature.encode(), expected.encode()):
67
+ raise MetaError("invalid webhook signature")
68
+ try:
69
+ data = parse_json(raw, limit=MAX_BODY)
70
+ except (ValueError, TypeError, RecursionError):
71
+ raise MetaError("invalid webhook JSON") from None
72
+ if not isinstance(data, dict) or data.get("object") != ("page" if self.platform == "facebook" else "instagram"):
73
+ raise MetaError("webhook object does not match platform")
74
+ entries = data.get("entry")
75
+ if not isinstance(entries, list) or not 1 <= len(entries) <= 100:
76
+ raise MetaError("empty/excessive webhook entries")
77
+ events = []
78
+ for entry in entries:
79
+ if not isinstance(entry, dict) or entry.get("id") != self.account_id:
80
+ raise MetaError("webhook account not selected")
81
+ timestamp = entry.get("time")
82
+ changes = entry.get("changes")
83
+ if type(timestamp) is not int or not 0 <= timestamp <= 2**53 or not isinstance(changes, list) or not 1 <= len(changes) <= 100:
84
+ raise MetaError("invalid webhook time/changes")
85
+ for change in changes:
86
+ if not isinstance(change, dict) or change.get("field") not in ({"feed"} if self.platform == "facebook" else {"comments", "mentions"}):
87
+ raise MetaError("webhook field outside normal content; messaging is not ingested")
88
+ value = change.get("value")
89
+ if not isinstance(value, dict):
90
+ raise MetaError("invalid webhook value")
91
+ media = value.get("media")
92
+ target = value.get("post_id") if self.platform == "facebook" else value.get("media_id", media.get("id") if isinstance(media, dict) else None)
93
+ meta_id(target, composite=self.platform == "facebook")
94
+ canonical = json.dumps({"object": data["object"], "account": self.account_id, "time": timestamp,
95
+ "change": change}, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
96
+ identifier = hashlib.sha256(canonical.encode()).hexdigest()
97
+ events.append((identifier, target, timestamp, canonical))
98
+ if len(events) > 1000:
99
+ raise MetaError("too many events in one body")
100
+ counts = {"accepted": 0, "duplicates": 0, "out_of_order": 0}
101
+ with self.database() as conn:
102
+ count = conn.execute("SELECT count(*) FROM events").fetchone()[0]
103
+ for identifier, target, timestamp, canonical in events:
104
+ if conn.execute("SELECT 1 FROM events WHERE id=?", (identifier,)).fetchone():
105
+ counts["duplicates"] += 1
106
+ continue
107
+ if count >= MAX_EVENTS:
108
+ raise MetaError("webhook store full; replay evidence is not deleted automatically")
109
+ latest = conn.execute("SELECT max(source_time) FROM events WHERE target=?", (target,)).fetchone()[0]
110
+ stale = latest is not None and timestamp < latest
111
+ conn.execute("INSERT INTO events VALUES (?,?,?,?,?,?,NULL)", (identifier, target, timestamp, canonical, int(stale), "pending_read"))
112
+ counts["accepted"] += 1
113
+ counts["out_of_order"] += int(stale)
114
+ count += 1
115
+ return counts
116
+
117
+ def events(self, limit=100):
118
+ if type(limit) is not int or not 1 <= limit <= 1000:
119
+ raise MetaError("event limit out of range")
120
+ if not self.path.exists():
121
+ return []
122
+ with self.database() as conn:
123
+ rows = conn.execute("SELECT id,target,source_time,stale,state FROM events ORDER BY source_time DESC,id LIMIT ?", (limit,)).fetchall()
124
+ return [dict(zip(("id", "target_id", "source_time", "out_of_order", "state"), row)) for row in rows]
125
+
126
+ def reconcile(self, client, event_id):
127
+ if (client.brand.nombre, str(client.brand.raiz.resolve()), client.platform.value, client.account_id) != (
128
+ self.brand.nombre, str(self.brand.raiz.resolve()), self.platform, self.account_id):
129
+ raise MetaError("event and client belong to another brand/account")
130
+ with self.database() as conn:
131
+ row = conn.execute("SELECT target,payload FROM events WHERE id=?", (event_id,)).fetchone()
132
+ if row is None:
133
+ raise MetaError("unknown webhook event")
134
+ try:
135
+ payload = json.loads(row[1])["change"]
136
+ if payload["field"] == "mentions":
137
+ if "comment_id" in payload["value"]:
138
+ meta_id(payload["value"]["comment_id"])
139
+ observation = client.inspect_mention(row[0], payload["value"].get("comment_id"))
140
+ else:
141
+ observation = client.content(row[0])
142
+ state = "read_only_observed"
143
+ except MetaError:
144
+ observation, state = {"reason": "not_found_or_inaccessible_is_not_absence"}, "unresolved"
145
+ with self.database() as conn:
146
+ conn.execute("UPDATE events SET state=?,observation=? WHERE id=?", (state, json.dumps(observation), event_id))
147
+ return {"id": event_id, "state": state, "observation": observation, "remote_writes": 0}
@@ -0,0 +1,144 @@
1
+ """Strict documented YouTube metadata operations; no arbitrary HTTP patches."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import re
6
+ from datetime import datetime, timezone
7
+ from typing import Any, Literal
8
+
9
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
10
+
11
+ from socialctl.management.changes import ChangeError, PATCH_FIELDS, _validate_patch_mapping, _validate_snippet
12
+ from socialctl.management.youtube import WRITABLE_SNIPPET_FIELDS
13
+
14
+ STATUS_FIELDS = frozenset({"embeddable", "license", "privacyStatus", "publicStatsViewable",
15
+ "publishAt", "selfDeclaredMadeForKids", "containsSyntheticMedia"})
16
+ STATUS_READ_ONLY = frozenset({"uploadStatus", "failureReason", "rejectionReason", "madeForKids"})
17
+ KINDS = {
18
+ "snippet": ("snippet", PATCH_FIELDS),
19
+ "chapters": ("snippet", frozenset({"description"})),
20
+ "localizations": ("localizations", None),
21
+ "status": ("status", frozenset({"embeddable", "license", "publicStatsViewable"})),
22
+ "privacy": ("status", frozenset({"privacyStatus"})),
23
+ "schedule": ("status", frozenset({"publishAt", "privacyStatus"})),
24
+ "audience": ("status", frozenset({"selfDeclaredMadeForKids"})),
25
+ "synthetic": ("status", frozenset({"containsSyntheticMedia"})),
26
+ }
27
+
28
+
29
+ def validate_localizations(value: Any) -> None:
30
+ if not isinstance(value, dict):
31
+ raise ChangeError("localizations must be a mapping")
32
+ for language, fields in value.items():
33
+ if not isinstance(language, str) or not re.fullmatch(r"[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*", language):
34
+ raise ChangeError("localizations requires explicit language codes")
35
+ if (not isinstance(fields, dict) or set(fields) != {"title", "description"}
36
+ or any(not isinstance(text, str) for text in fields.values())):
37
+ raise ChangeError("localizations accepts only text title and description")
38
+ _validate_snippet({**fields, "categoryId": "27"})
39
+
40
+
41
+ def validate_status(value: dict[str, Any], *, outgoing: bool = False) -> None:
42
+ for key, item in value.items():
43
+ if key not in STATUS_FIELDS:
44
+ raise ChangeError(f"unknown status field: {key}")
45
+ if key in {"embeddable", "publicStatsViewable", "selfDeclaredMadeForKids", "containsSyntheticMedia"}:
46
+ if type(item) is not bool:
47
+ raise ChangeError(f"{key} must be explicit boolean")
48
+ elif key == "privacyStatus" and (not isinstance(item, str) or item not in {"private", "public", "unlisted"}):
49
+ raise ChangeError("invalid privacyStatus")
50
+ elif key == "license" and (not isinstance(item, str) or item not in {"youtube", "creativeCommon"}):
51
+ raise ChangeError("invalid license")
52
+ elif key == "publishAt":
53
+ if not isinstance(item, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})", item):
54
+ raise ChangeError("publishAt requires RFC3339 with timezone")
55
+ try:
56
+ date = datetime.fromisoformat(item.replace("Z", "+00:00"))
57
+ except ValueError:
58
+ raise ChangeError("publishAt requires RFC3339") from None
59
+ if date.tzinfo is None:
60
+ raise ChangeError("publishAt requires timezone")
61
+ if outgoing and date <= datetime.now(timezone.utc):
62
+ raise ChangeError("publishAt must be in the future; past timestamps may publish immediately")
63
+
64
+
65
+ class MetadataEdit(BaseModel):
66
+ model_config = ConfigDict(extra="forbid", strict=True)
67
+ video_id: str = Field(min_length=1, pattern=r"^[A-Za-z0-9_-]+$")
68
+ kind: Literal["snippet", "chapters", "localizations", "status", "privacy", "schedule", "audience", "synthetic"]
69
+ patch: dict[str, Any]
70
+ never_published: bool = False
71
+
72
+ @model_validator(mode="after")
73
+ def validate_operation(self):
74
+ if not self.patch:
75
+ raise ChangeError("empty patch")
76
+ part, fields = KINDS[self.kind]
77
+ if "defaultAudioLanguage" in self.patch:
78
+ raise ChangeError("defaultAudioLanguage: editing unverified by method documentation; preserved only")
79
+ if fields is not None and set(self.patch) - fields:
80
+ raise ChangeError(f"unknown field for operation {self.kind}")
81
+ if part == "snippet":
82
+ _validate_patch_mapping(self.patch)
83
+ elif part == "localizations":
84
+ validate_localizations(self.patch)
85
+ else:
86
+ validate_status(self.patch)
87
+ if self.kind == "schedule":
88
+ if not self.never_published:
89
+ raise ChangeError("schedule requires user-declared never_published: true; private status does not prove history")
90
+ if set(self.patch) != {"publishAt", "privacyStatus"} or self.patch["privacyStatus"] != "private":
91
+ raise ChangeError("schedule requires explicit publishAt and privacyStatus: private")
92
+ elif self.never_published:
93
+ raise ChangeError("never_published applies only to schedule")
94
+ return self
95
+
96
+
97
+ def editable_parts(resource: dict[str, Any]) -> dict[str, dict[str, Any]]:
98
+ return {
99
+ "snippet": {key: copy.deepcopy(value) for key, value in resource["snippet"].items()
100
+ if key in WRITABLE_SNIPPET_FIELDS and value is not None},
101
+ "status": {key: copy.deepcopy(value) for key, value in resource["status"].items() if key in STATUS_FIELDS},
102
+ "localizations": copy.deepcopy(resource.get("localizations", {})),
103
+ }
104
+
105
+
106
+ def validate_chapters(description: str, duration: str) -> None:
107
+ match = re.fullmatch(r"P(?:(\d+)D)?T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?", duration)
108
+ if not match or not any(match.groups()):
109
+ raise ChangeError("chapters: API duration missing or uninterpretable")
110
+ days, hours, minutes, seconds = [float(value or 0) for value in match.groups()]
111
+ total = days * 86400 + hours * 3600 + minutes * 60 + seconds
112
+ starts = []
113
+ for line in description.splitlines():
114
+ stamp = re.match(r"^\s*(\d+):(\d{2})(?::(\d{2}))?\s+\S", line)
115
+ if stamp:
116
+ first, second, third = stamp.groups()
117
+ if int(second) >= 60 or (third is not None and int(third) >= 60):
118
+ raise ChangeError("chapter: invalid timestamp")
119
+ starts.append(int(first) * (3600 if third is not None else 60) + int(second) * (60 if third is not None else 1) + int(third or 0))
120
+ if len(starts) < 3 or starts[0] != 0:
121
+ raise ChangeError("chapters: first start must be 0:00 and at least three chapters required")
122
+ if any(end - start < 10 for start, end in zip(starts, [*starts[1:], total])):
123
+ raise ChangeError("chapters: each chapter requires 10 seconds, including final chapter against API duration")
124
+
125
+
126
+ def propose_parts(observed, edit: MetadataEdit):
127
+ edit = MetadataEdit.model_validate(edit.model_dump())
128
+ all_parts = editable_parts(observed.resource)
129
+ part = KINDS[edit.kind][0]
130
+ before = {part: all_parts[part]}
131
+ after = {part: {**copy.deepcopy(before[part]), **copy.deepcopy(edit.patch)}}
132
+ if part == "snippet":
133
+ _validate_snippet(after[part])
134
+ elif part == "localizations":
135
+ if not all_parts["snippet"].get("defaultLanguage"):
136
+ raise ChangeError("localizations requires existing snippet.defaultLanguage")
137
+ validate_localizations(after[part])
138
+ else:
139
+ validate_status(after[part], outgoing=True)
140
+ if edit.kind == "privacy" and "publishAt" in after[part] and after[part]["privacyStatus"] != "private":
141
+ raise ChangeError("publishAt exists: privacy cannot change while preserving incompatible schedule")
142
+ if edit.kind == "chapters":
143
+ validate_chapters(edit.patch["description"], observed.resource.get("contentDetails", {}).get("duration", ""))
144
+ return before, after
@@ -0,0 +1,85 @@
1
+ """Bounded supplied PNG/JPEG inspection; no generation, decoding or conversion."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import stat
6
+ import struct
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+
11
+ from socialctl.management.resource_changes import digest
12
+ from socialctl.management.youtube_resources import ResourceError
13
+
14
+
15
+ def dimensions(data):
16
+ if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 33 and data[12:16] == b"IHDR" and data[-8:] == b"IEND\xaeB`\x82":
17
+ return "image/png", *struct.unpack(">II", data[16:24])
18
+ if data.startswith(b"\xff\xd8\xff") and data.endswith(b"\xff\xd9"):
19
+ offset = 2
20
+ while offset + 4 <= len(data):
21
+ if data[offset] != 255:
22
+ break
23
+ while offset < len(data) and data[offset] == 255:
24
+ offset += 1
25
+ if offset >= len(data):
26
+ break
27
+ marker = data[offset]
28
+ offset += 1
29
+ if marker in {0xD9, 0xDA}:
30
+ break
31
+ if marker in {0x01, *range(0xD0, 0xD9)}:
32
+ continue
33
+ if offset + 2 > len(data):
34
+ break
35
+ size = int.from_bytes(data[offset:offset + 2], "big")
36
+ if size < 2 or offset + size > len(data):
37
+ break
38
+ if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} and size >= 8:
39
+ height, width = struct.unpack(">HH", data[offset + 3:offset + 7])
40
+ return "image/jpeg", width, height
41
+ offset += size
42
+ raise ResourceError("supplied PNG/JPEG bytes with verifiable dimensions required")
43
+
44
+
45
+ def inspect_owned_asset(path, action):
46
+ maximum = {"banner-upload": 6, "watermark-set": 10, "image-insert": 2, "image-update": 50}.get(action)
47
+ if maximum is None:
48
+ raise ResourceError("action does not accept a file")
49
+ maximum *= 1024 * 1024
50
+ path = Path(path).absolute()
51
+ try:
52
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
53
+ with os.fdopen(fd, "rb") as stream:
54
+ before = os.fstat(stream.fileno())
55
+ if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= maximum:
56
+ raise ResourceError(f"file is not regular, empty or exceeds local limit of {maximum} bytes")
57
+ data = stream.read(maximum + 1)
58
+ after = os.fstat(stream.fileno())
59
+ if (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns) or len(data) != before.st_size:
60
+ raise ResourceError("file changed during read")
61
+ except OSError:
62
+ raise ResourceError("failed to read regular file without symlinks") from None
63
+ mime, width, height = dimensions(data)
64
+ if not 0 < width <= 2147483647 or not 0 < height <= 2147483647:
65
+ raise ResourceError("empty dimensions")
66
+ if action == "banner-upload" and (width < 2048 or height < 1152 or width * 9 != height * 16):
67
+ raise ResourceError("banner requires 16:9 and minimum 2048x1152")
68
+ if action.startswith("image-") and width != height:
69
+ raise ResourceError("playlist image must be square")
70
+ return {"path": str(path), "sha256": digest(data), "size": len(data), "mime": mime,
71
+ "width": width, "height": height, "local_max_bytes": maximum,
72
+ "local_format_validation": "container_header_and_dimensions/provider_validation_required"}, data
73
+
74
+
75
+ def banner_url(value):
76
+ if not isinstance(value, str) or len(value) > 8192:
77
+ raise ResourceError("invalid banner URL")
78
+ try:
79
+ url = httpx.URL(value)
80
+ except Exception:
81
+ raise ResourceError("invalid banner URL") from None
82
+ if (url.scheme != "https" or url.userinfo or url.fragment or url.port not in {None, 443}
83
+ or not url.host or not any(url.host == host or url.host.endswith("." + host) for host in ("googleusercontent.com", "ggpht.com"))):
84
+ raise ResourceError("banner URL outside YouTube HTTPS image hosts")
85
+ return value