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,112 @@
1
+ """Native Facebook Reels behind an explicit account pilot gate.
2
+
3
+ Transport readback never claims Business Suite calendar visibility. Other formats
4
+ remain closed. Missing pilot evidence never falls back to immediate publication.
5
+ """
6
+ from dataclasses import dataclass
7
+ from typing import Literal
8
+
9
+ import httpx
10
+
11
+ from socialctl.brands import Brand
12
+ from socialctl.auth import obtener_token
13
+ from socialctl.models import Platform
14
+
15
+ from .approval import native_api_followup_pending, verify_approval
16
+ from .models import NativeJob
17
+ from .store import NativeStore
18
+ from .facebook_reels import FacebookReelDelivery, GRAPH, _safe_identifier
19
+ from .handoff import _target
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class FacebookEligibility:
24
+ account_id: str = ''
25
+ api_enabled: bool = False
26
+ page_pilot_verified: bool = False
27
+ evidence_ref: str = ''
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class FacebookScheduleResult:
32
+ state: Literal["ui_required", "pending_verification", "uncertain"] = "ui_required"
33
+ remote_id: str | None = None
34
+ reason: str = (
35
+ "Facebook API create/read/account eligibility is unproven; "
36
+ "reprepare and approve route=ui for Meta Business Suite"
37
+ )
38
+ source: Literal["api"] = "api"
39
+ calendar_visible: Literal[False] = False
40
+
41
+
42
+ def _context(job: NativeJob, payload: dict, brand: Brand, store: NativeStore) -> None:
43
+ page_id = (brand.cuentas.get("facebook") or {}).get("page_id")
44
+ if (
45
+ job.brand != brand.nombre
46
+ or store.brand != job.brand
47
+ or store.path.parent != brand.raiz.resolve()
48
+ or job.platform != "facebook"
49
+ or page_id != job.account_id
50
+ ):
51
+ raise ValueError("Explicit brand/account/store mismatch")
52
+ if store.get(job.id) != job or store.get_payload(job.id) != payload:
53
+ raise ValueError("Stale job or changed stored payload")
54
+ verify_approval(job, payload)
55
+
56
+
57
+ def schedule_facebook(
58
+ job: NativeJob,
59
+ payload: dict,
60
+ *,
61
+ brand: Brand,
62
+ store: NativeStore,
63
+ client: httpx.Client,
64
+ eligibility: FacebookEligibility | None = None,
65
+ ) -> FacebookScheduleResult:
66
+ """Upload directly to Meta only after immutable approval and pilot evidence."""
67
+ _context(job, payload, brand, store)
68
+ eligibility = eligibility or FacebookEligibility()
69
+ if (job.route != 'api' or eligibility.account_id != job.account_id
70
+ or eligibility.api_enabled is not True or eligibility.page_pilot_verified is not True
71
+ or not eligibility.evidence_ref or payload.get('options', {}).get('format') != 'reel'):
72
+ return FacebookScheduleResult()
73
+ if job.state in {'uncertain', 'dispatching', 'verifying'} or store.get_attempts(job.id):
74
+ target = _target(job, payload, store)
75
+ remote_id = _safe_identifier(target) if target is not None else None
76
+ return FacebookScheduleResult('uncertain', remote_id, 'Existing attempt requires reconciliation; never upload again')
77
+ pending = native_api_followup_pending(payload)
78
+ if pending:
79
+ return FacebookScheduleResult('ui_required', reason=pending)
80
+ if payload.get('delivery_mode', 'native_schedule') != 'native_schedule':
81
+ raise ValueError('Native Facebook submission requires native_schedule delivery mode')
82
+ options = payload['options']
83
+ if set(options) - {'format', 'share_to_facebook_story'} or options.get('share_to_facebook_story', False) is not False:
84
+ raise ValueError('Unsupported Reel options; prepare an exact supported preview')
85
+ if payload.get('visibility') != 'public':
86
+ raise ValueError('Scheduled Page Reel must explicitly request eventual public visibility')
87
+ token = obtener_token(brand, Platform.FACEBOOK, client)
88
+ response = client.get(f'{GRAPH}/me', params={'fields': 'id', 'access_token': token})
89
+ response.raise_for_status()
90
+ if response.json().get('id') != job.account_id:
91
+ raise ValueError('Authenticated Page differs from approved account')
92
+ adapter = FacebookReelDelivery(client, token)
93
+ adapter._schedule_time(job)
94
+ claimed = store.claim(job.id, job.state)
95
+ if claimed is None:
96
+ raise ValueError('Job could not be claimed')
97
+ remote_id = None
98
+ try:
99
+ verify_approval(claimed, payload)
100
+ remote_id = adapter.deliver(claimed, payload,
101
+ lambda value: store.checkpoint(claimed.id, claimed.attempt_id, value))
102
+ store.mark_api_submitted(claimed.id, claimed.attempt_id, remote_id)
103
+ return FacebookScheduleResult('pending_verification', remote_id,
104
+ 'Meta readback matches the schedule; fresh Business Suite calendar evidence is still required')
105
+ except Exception:
106
+ current = store.get(job.id)
107
+ if current.state in {'dispatching', 'verifying'}:
108
+ store.transition(job.id, current.state, 'uncertain')
109
+ target = _target(store.get(job.id), payload, store)
110
+ remote_id = _safe_identifier(target) if target is not None else None
111
+ return FacebookScheduleResult('uncertain', remote_id,
112
+ 'Reconcile the existing remote attempt before any further upload')
@@ -0,0 +1,140 @@
1
+ """Facebook Page Reel START/upload/FINISH through the official Graph endpoints."""
2
+
3
+ import re
4
+ from datetime import datetime, timedelta, timezone
5
+ from pathlib import Path
6
+ from urllib.parse import urlsplit
7
+
8
+ import httpx
9
+
10
+ from .api_delivery import DeliveryUncertain
11
+ from .models import NativeJob
12
+
13
+ GRAPH = 'https://graph.facebook.com/v26.0'
14
+ _IDENTIFIER = re.compile(r'[A-Za-z0-9_-]+\Z')
15
+
16
+
17
+ def _safe_identifier(value: str) -> str:
18
+ if not isinstance(value, str) or not _IDENTIFIER.fullmatch(value):
19
+ raise ValueError('Invalid Graph identifier')
20
+ return value
21
+
22
+
23
+ def _upload_url(value: str, video_id: str) -> str:
24
+ parsed = urlsplit(value)
25
+ if (parsed.scheme != 'https' or parsed.hostname != 'rupload.facebook.com'
26
+ or parsed.port not in (None, 443) or parsed.username or parsed.password
27
+ or parsed.query or parsed.fragment or
28
+ not re.fullmatch(r'/video-upload/v\d+(?:\.\d+)?/' + re.escape(video_id), parsed.path)):
29
+ raise ValueError('Untrusted Reel upload URL')
30
+ return value
31
+
32
+
33
+ class FacebookReelDelivery:
34
+ def __init__(self, client: httpx.Client, page_token: str, *, clock=None):
35
+ if not page_token:
36
+ raise ValueError('Page token required')
37
+ self.client = client
38
+ self.page_token = page_token
39
+ self.clock = clock or (lambda: datetime.now(timezone.utc))
40
+
41
+ def _schedule_time(self, job: NativeJob) -> int:
42
+ # Conservative product window; not a claim about every Graph format.
43
+ delta = job.publish_at - self.clock()
44
+ if not timedelta(minutes=10) < delta <= timedelta(days=28):
45
+ raise ValueError('Reel schedule window requires more than 10 minutes and at most 28 days')
46
+ if job.publish_at.microsecond:
47
+ raise ValueError('Reel schedule window requires whole seconds; no silent time rounding')
48
+ return int(job.publish_at.timestamp())
49
+
50
+ def deliver(self, job: NativeJob, payload: dict, checkpoint) -> str:
51
+ if job.platform != 'facebook' or payload.get('options', {}).get('format') != 'reel':
52
+ raise ValueError('Approved Facebook Reel required')
53
+ if len(payload.get('media', [])) != 1:
54
+ raise ValueError('One original Reel file required')
55
+ mode = payload.get('delivery_mode', 'native_schedule')
56
+ if mode not in {'native_schedule', 'at_time'}:
57
+ raise ValueError('Unknown delivery mode; new approval required')
58
+ if mode == 'native_schedule':
59
+ self._schedule_time(job)
60
+ page_id = _safe_identifier(job.account_id)
61
+ path = Path(payload['media'][0]['path'])
62
+ size = path.stat().st_size
63
+ if size <= 0 or not path.is_file():
64
+ raise ValueError('Nonempty original Reel file required')
65
+ edge = f'{GRAPH}/{page_id}/video_reels'
66
+
67
+ checkpoint({'phase': 'start_requested'})
68
+ response = self.client.post(edge, data={
69
+ 'access_token': self.page_token, 'upload_phase': 'START'})
70
+ response.raise_for_status()
71
+ started = response.json()
72
+ video_id = _safe_identifier(started.get('video_id'))
73
+ upload_url = _upload_url(started.get('upload_url'), video_id)
74
+ checkpoint({'phase': 'started', 'video_id': video_id})
75
+
76
+ checkpoint({'phase': 'upload_requested', 'video_id': video_id})
77
+ with path.open('rb') as original:
78
+ response = self.client.post(upload_url, headers={
79
+ 'Authorization': f'OAuth {self.page_token}',
80
+ 'offset': '0', 'file_size': str(size),
81
+ 'Content-Type': 'application/octet-stream',
82
+ }, content=original, timeout=None)
83
+ response.raise_for_status()
84
+ if response.json().get('success') is not True:
85
+ raise DeliveryUncertain('Reel upload was not confirmed')
86
+ checkpoint({'phase': 'uploaded', 'video_id': video_id})
87
+
88
+ finish = {
89
+ 'access_token': self.page_token, 'upload_phase': 'FINISH',
90
+ 'video_id': video_id, 'video_state': 'PUBLISHED',
91
+ 'description': payload['copy'],
92
+ }
93
+ if mode == 'native_schedule':
94
+ # A long upload must not silently turn an expired schedule into now.
95
+ finish.update(video_state='SCHEDULED', scheduled_publish_time=str(self._schedule_time(job)))
96
+ checkpoint({'phase': 'finish_requested', 'video_id': video_id})
97
+ response = self.client.post(edge, data=finish)
98
+ response.raise_for_status()
99
+ if response.json().get('success') is not True:
100
+ raise DeliveryUncertain('Reel finalization was not confirmed')
101
+ if mode == 'native_schedule':
102
+ checkpoint({'phase': 'schedule_submitted', 'video_id': video_id})
103
+ read_reel(video_id, page_id, self.client, self.page_token,
104
+ expected_description=payload['copy'], expected_publish_at=job.publish_at)
105
+ checkpoint({'phase': 'schedule_verified', 'video_id': video_id,
106
+ 'scheduled_publish_time': job.publish_at.isoformat()})
107
+ return video_id
108
+
109
+
110
+ def read_reel(video_id: str, page_id: str, client: httpx.Client,
111
+ page_token: str, *, expected_description: str,
112
+ expected_publish_at: datetime | None = None,
113
+ require_published: bool = False) -> dict:
114
+ """Read the Video node and compare ownership and approved description."""
115
+ video_id = _safe_identifier(video_id)
116
+ page_id = _safe_identifier(page_id)
117
+ fields = 'id,description,from,status'
118
+ if expected_publish_at is not None:
119
+ fields += ',published,scheduled_publish_time'
120
+ elif require_published:
121
+ fields += ',published'
122
+ response = client.get(f'{GRAPH}/{video_id}', params={
123
+ 'fields': fields, 'access_token': page_token})
124
+ response.raise_for_status()
125
+ item = response.json()
126
+ if item.get('id') != video_id or item.get('from', {}).get('id') != page_id:
127
+ raise ValueError('Reel readback belongs to another Page')
128
+ if item.get('description') != expected_description:
129
+ raise ValueError('Reel description differs from approved copy')
130
+ if require_published and (item.get('published') is not True
131
+ or (item.get('status') or {}).get('video_status') != 'ready'):
132
+ raise ValueError('Reel is not verified published and fully processed')
133
+ if expected_publish_at is not None:
134
+ try:
135
+ stamp = datetime.fromisoformat(item['scheduled_publish_time'].replace('Z', '+00:00'))
136
+ except (KeyError, TypeError, ValueError, AttributeError):
137
+ raise ValueError('Reel schedule readback is missing or invalid') from None
138
+ if item.get('published') is not False or stamp.utcoffset() is None or stamp != expected_publish_at:
139
+ raise ValueError('Reel schedule differs from the approved time or is already public')
140
+ return item
@@ -0,0 +1,181 @@
1
+ """Bridge approved native occurrences to the existing durable comment machinery.
2
+
3
+ The native ledger owns media evidence; PublicationStore owns the dependent effect.
4
+ No accepted receipt, UI attestation, or partial list authorizes a comment here.
5
+ """
6
+ from datetime import datetime
7
+ from hashlib import sha256
8
+ import json
9
+ import uuid
10
+
11
+ from socialctl.management.meta_comments import CommentError, MetaCommentsClient
12
+ from socialctl.models import Platform, PostResult, PostStatus
13
+ from socialctl.publication_steps import Publication, PublicationStore, _account, _fingerprint, _first_comment
14
+ from .approval import native_api_followup_pending, verify_approval
15
+ from .models import NativeObservation, aware
16
+ from .store import NativeStore, _now
17
+
18
+ PREFIX = 'native-schedule:'
19
+
20
+
21
+ def occurrence_id(brand, job):
22
+ return str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(
23
+ ['native-first-comment', str(brand.raiz.resolve()), job.id])))
24
+
25
+
26
+ def provenance(job):
27
+ return PREFIX + json.dumps([job.id, job.approval_digest], separators=(',', ':'))
28
+
29
+
30
+ def _context(brand, store, job, payload):
31
+ if (store.brand != brand.nombre or job.brand != brand.nombre
32
+ or store.path.parent != brand.raiz.resolve() or job.route != 'api'
33
+ or _account(brand, Platform(job.platform))['account_id'] != job.account_id
34
+ or store.get(job.id) != job or store.get_payload(job.id) != payload):
35
+ raise CommentError('Native comment brand/account/approved occurrence mismatch')
36
+ verify_approval(job, payload)
37
+ if (native_api_followup_pending(payload) or job.platform not in {'facebook', 'youtube', 'instagram'} or payload.get('visibility') != 'public'
38
+ or (job.platform == 'instagram' and payload.get('options', {}).get('format') == 'story')):
39
+ raise CommentError('Unsupported scheduled first-comment combination')
40
+ if job.state not in {'dispatching', 'verifying', 'uncertain', 'native_scheduled', 'published'} or not job.attempt_id:
41
+ raise CommentError('Native publication has no submitted occurrence')
42
+ action = store.get_action(job.id)
43
+ if action and action['status'] != 'confirmed':
44
+ raise CommentError('Native action requires reconciliation before comments')
45
+
46
+
47
+ def _target(job, payload, store):
48
+ refs = {job.remote_id} if job.remote_id else set()
49
+ if payload.get('options', {}).get('video_id'):
50
+ refs.add(payload['options']['video_id'])
51
+ for attempt in store.get_attempts(job.id):
52
+ checkpoint = attempt['checkpoint']
53
+ if checkpoint.get('video_id'):
54
+ refs.add(checkpoint['video_id'])
55
+ if len(refs) != 1:
56
+ raise CommentError('Native media target is missing or contradictory; no comment attempted')
57
+ return refs.pop()
58
+
59
+
60
+ def read_published(brand, http, job, payload, remote_id, *, now):
61
+ """Existing fixed-host provider readers, with a stricter public/processed gate."""
62
+ if now < job.publish_at:
63
+ raise CommentError('Approved publication time has not arrived')
64
+ if job.platform == 'youtube':
65
+ from socialctl.management.youtube_community import YouTubeCommunityClient
66
+ from .youtube import _readback
67
+ client = YouTubeCommunityClient(brand, http)
68
+ observed = _readback(job, payload, remote_id, client)
69
+ item = observed.resource or {}
70
+ if (observed.state != 'published' or item.get('status', {}).get('madeForKids') is True
71
+ or item.get('status', {}).get('uploadStatus') != 'processed'
72
+ or item.get('processingDetails', {}).get('processingStatus') != 'succeeded'):
73
+ raise CommentError('YouTube video is not verified public and fully processed')
74
+ return item
75
+ client = MetaCommentsClient(brand, Platform(job.platform), http)
76
+ client.inspect_media(remote_id) # Exact authenticated actor as well as owner.
77
+ if job.platform == 'facebook':
78
+ from .facebook_reels import read_reel
79
+ item = read_reel(remote_id, job.account_id, http, client._access_token,
80
+ expected_description=payload['copy'], require_published=True)
81
+ if 'paging' in item:
82
+ raise CommentError('Facebook published readback is incomplete')
83
+ return item
84
+ from .instagram_delivery import read_media
85
+ item = read_media(remote_id, job.account_id, http, client._access_token,
86
+ expected_caption=payload['copy'], expected_format=payload['options']['format'])
87
+ if 'paging' in item:
88
+ raise CommentError('Instagram published readback is incomplete')
89
+ try:
90
+ stamp = aware(datetime.fromisoformat(item['timestamp'].replace('Z', '+00:00')))
91
+ except (ValueError, KeyError, TypeError, AttributeError):
92
+ raise CommentError('Instagram published timestamp is missing or invalid') from None
93
+ if stamp > now:
94
+ raise CommentError('Instagram published timestamp is in the future')
95
+ return item
96
+
97
+
98
+ def validate_native_publication(brand, http, data, *, now=None):
99
+ """Also used by comments retry-first; an old public receipt cannot bypass reads."""
100
+ try:
101
+ job_id, digest = json.loads(data['provenance'][len(PREFIX):])
102
+ except (ValueError, TypeError):
103
+ raise CommentError('Invalid native approval provenance') from None
104
+ store = NativeStore(brand.raiz, brand=brand.nombre)
105
+ job = store.get(job_id)
106
+ if job is None:
107
+ raise CommentError('Native approved occurrence is missing')
108
+ payload = store.get_payload(job_id)
109
+ _context(brand, store, job, payload)
110
+ target = _target(job, payload, store)
111
+ if (data['id'] != occurrence_id(brand, job) or digest != job.approval_digest
112
+ or data['platform'] != job.platform or data['text'] != payload.get('first_comment')
113
+ or data['account'] != _account(brand, Platform(job.platform))
114
+ or data['media']['platform_id'] != target):
115
+ raise CommentError('Native comment differs from its exact approved occurrence')
116
+ return read_published(brand, http, job, payload, target, now=_now(now))
117
+
118
+
119
+ def first_comment_status(brand, job, payload):
120
+ if not payload.get('first_comment'):
121
+ return {'status': 'not_requested'}
122
+ identifier = occurrence_id(brand, job)
123
+ result = {'status': 'pending', 'publication_id': identifier}
124
+ store = PublicationStore(brand.raiz)
125
+ if store.path_for(identifier).exists():
126
+ try:
127
+ data = store.load(identifier)
128
+ if data['provenance'] != provenance(job) or data['text'] != payload['first_comment']:
129
+ raise CommentError('Native publication approval changed')
130
+ media = data.get('media') or {}
131
+ result.update(status=media.get('first_comment_status') or 'pending',
132
+ change_id=data['comment_change_id'], comment_id=media.get('first_comment_id'))
133
+ except CommentError:
134
+ result['status'] = 'manual_review'
135
+ return result
136
+
137
+
138
+ def follow_up(brand, http, store, job_id, *, now=None, read_only=False):
139
+ """One stable occurrence lock spans media proof, journal creation and comment step."""
140
+ now = _now(now)
141
+ job = store.get(job_id)
142
+ payload = store.get_payload(job_id)
143
+ if not payload.get('first_comment'):
144
+ return {'status': 'not_requested'}
145
+ publications = PublicationStore(brand.raiz)
146
+ identifier = occurrence_id(brand, job)
147
+ with publications.apply_lock(identifier):
148
+ job = store.get(job_id)
149
+ _context(brand, store, job, payload)
150
+ target = _target(job, payload, store)
151
+ item = read_published(brand, http, job, payload, target, now=now)
152
+ if job.state != 'published':
153
+ # A unique evidence artifact per read survives competing workers and restarts.
154
+ evidence_id = str(uuid.uuid4())
155
+ evidence = {'job_id': job.id, 'approval_digest': job.approval_digest,
156
+ 'observed_at': now.isoformat(), 'remote': item}
157
+ evidence_store = PublicationStore(brand.raiz)
158
+ evidence_store.root = publications.root / 'native-evidence'
159
+ evidence_store.write_json(evidence_id, evidence)
160
+ path = evidence_store.path_for(evidence_id)
161
+ observation = NativeObservation(job_id=job.id, platform=job.platform,
162
+ account_id=job.account_id, content_hash=job.content_hash, approval_digest=job.approval_digest,
163
+ remote_ref=target, publish_at=job.publish_at, observed_at=now, source='api', calendar_visible=False,
164
+ state='published', public_visible=True, processing_complete=True,
165
+ evidence_path=str(path), evidence_sha256=sha256(path.read_bytes()).hexdigest())
166
+ if not store.record_observation(observation, now=now) and store.get(job.id).state != 'published':
167
+ raise CommentError('Native published readback did not satisfy reconciliation')
168
+ if publications.path_for(identifier).exists():
169
+ data = publications.load(identifier)
170
+ else:
171
+ media = PostResult(platform=Platform(job.platform), status=PostStatus.PUBLICADO,
172
+ platform_id=target, publication_id=identifier, first_comment_status='pending')
173
+ data = Publication(id=identifier, brand=brand.nombre, brand_root=str(brand.raiz.resolve()),
174
+ platform=job.platform, slug=job.id, account=_account(brand, Platform(job.platform)),
175
+ text=payload['first_comment'], provenance=provenance(job), fingerprint='',
176
+ created_at=now.isoformat(), state='published', media=media.model_dump(mode='json')).model_dump()
177
+ data['fingerprint'] = _fingerprint(data)
178
+ publications.write_json(identifier, data)
179
+ # This also revalidates the native binding in the shared recovery path.
180
+ _first_comment(brand, http, publications, data, reconcile_only=read_only)
181
+ return first_comment_status(brand, store.get(job.id), payload)
@@ -0,0 +1,193 @@
1
+ """Local handoff manifests for trusted operators using official scheduling UIs.
2
+
3
+ This module never opens a browser or calls a platform API. It binds the exact
4
+ approved payload and current media bytes to one durable UI attempt; evidence is
5
+ accepted only after that delivery attempt has started.
6
+ """
7
+ from copy import deepcopy
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from zoneinfo import ZoneInfo
11
+
12
+ from .approval import hash_value, media_hashes, verify_approval
13
+ from .models import NativeJob, NativeObservation, aware
14
+ from .store import NativeStore
15
+
16
+
17
+ SCHEMA = 'socialctl.native-schedule.handoff.v1'
18
+ _DELIVERY_STATES = {'dispatching', 'awaiting_ui', 'verifying', 'uncertain', 'native_scheduled'}
19
+
20
+
21
+ def _now(value: datetime | None) -> datetime:
22
+ return aware(value or datetime.now(timezone.utc))
23
+
24
+
25
+ def _stored(job: NativeJob, payload: dict, store: NativeStore) -> NativeJob:
26
+ current = store.get(job.id)
27
+ stored_payload = store.get_payload(job.id)
28
+ if current is None or stored_payload is None:
29
+ raise ValueError('Job and payload must exist in the explicit store')
30
+ if current.brand != store.brand or job.brand != store.brand:
31
+ raise ValueError('Job does not belong to the explicit store brand')
32
+ # A caller may pass an earlier lifecycle snapshot, but immutable intent must
33
+ # match the authoritative row exactly.
34
+ immutable = ('id', 'brand', 'platform', 'account_id', 'media_hash',
35
+ 'content_hash', 'publish_at', 'timezone_name', 'schedule_mode', 'route')
36
+ if any(getattr(job, field) != getattr(current, field) for field in immutable):
37
+ raise ValueError('Job does not match the stored approved intent')
38
+ if payload != stored_payload:
39
+ raise ValueError('Payload does not match the stored approved intent')
40
+ return current
41
+
42
+
43
+ def _target(job: NativeJob, payload: dict, store: NativeStore) -> str | None:
44
+ candidates = []
45
+ if job.remote_id:
46
+ candidates.append(job.remote_id)
47
+ video_id = payload.get('options', {}).get('video_id')
48
+ if video_id:
49
+ candidates.append(video_id)
50
+ for attempt in store.get_attempts(job.id):
51
+ checkpoint_id = attempt['checkpoint'].get('video_id')
52
+ if checkpoint_id:
53
+ candidates.append(checkpoint_id)
54
+ if len(set(candidates)) > 1:
55
+ raise ValueError('Existing remote target identities conflict')
56
+ return candidates[0] if candidates else None
57
+
58
+
59
+ def _submit_started(job: NativeJob, store: NativeStore) -> bool:
60
+ return any(attempt['checkpoint'].get('ui_submit_started_at')
61
+ for attempt in store.get_attempts(job.id))
62
+
63
+
64
+ def _check_meta_destinations(job: NativeJob, payload: dict) -> None:
65
+ if job.platform not in {'facebook', 'instagram'}:
66
+ return
67
+ options = payload.get('options', {})
68
+ if options.get('share_to_facebook_story') is not False:
69
+ raise ValueError('Share to Facebook Story must be explicitly OFF for feed/Reel delivery')
70
+ destinations = options.get('destinations')
71
+ if destinations not in (None, [], [job.platform]):
72
+ raise ValueError('Additional Meta destinations require separately approved jobs')
73
+
74
+
75
+ def prepare_handoff(job: NativeJob, payload: dict, *, store: NativeStore,
76
+ now: datetime | None = None, require_new: bool = False) -> dict:
77
+ """Own or resume a UI attempt and return the exact operator manifest."""
78
+ now = _now(now)
79
+ current = _stored(job, payload, store)
80
+ if require_new and current.state not in {'approved','ready','waiting_window'}:
81
+ raise ValueError('Another worker already owns this delivery')
82
+ if current.route != 'ui' or current.approval_digest is None:
83
+ raise ValueError('An explicitly approved UI route is required')
84
+ _check_meta_destinations(current, payload)
85
+
86
+ target = _target(current, payload, store)
87
+ reconciling = (current.state in {'uncertain', 'verifying', 'native_scheduled'}
88
+ or _submit_started(current, store))
89
+
90
+ # This is intentionally before claim: media is re-read immediately before
91
+ # handoff and a mismatch cannot acquire an attempt.
92
+ if not reconciling:
93
+ verify_approval(current, payload)
94
+ elif hash_value(payload) != current.content_hash:
95
+ raise ValueError('Stored reconciliation payload changed')
96
+ if current.state in {'approved', 'ready', 'waiting_window'}:
97
+ claimed = store.claim(current.id, current.state, now=now)
98
+ if claimed is None:
99
+ raise ValueError('Approved UI job could not be claimed')
100
+ current = store.transition(current.id, 'dispatching', 'awaiting_ui', now=now)
101
+ if current is None:
102
+ raise ValueError('UI attempt ownership was lost')
103
+ store.checkpoint(current.id, current.attempt_id,
104
+ {'handoff_prepared_at': now.isoformat()}, now=now)
105
+ elif current.state not in {'awaiting_ui', 'uncertain', 'verifying', 'native_scheduled'}:
106
+ raise ValueError('Job is not in an approved UI delivery stage')
107
+
108
+ files = []
109
+ media_integrity = 'freshly rehashed'
110
+ try:
111
+ hashes = media_hashes(payload)
112
+ if reconciling and hash_value(hashes) != current.media_hash:
113
+ media_integrity = 'source differs from approved aggregate; upload prohibited'
114
+ for item, digest in zip(payload.get('media', []), hashes, strict=True):
115
+ path = Path(item['path'])
116
+ files.append({'path': str(path), 'origin': item['origin'],
117
+ 'sha256': digest['sha256'], 'bytes': path.stat().st_size})
118
+ except ValueError:
119
+ if not reconciling:
120
+ raise
121
+ media_integrity = 'approved aggregate retained; source unavailable'
122
+ files = [{'path': item['path'], 'origin': item['origin'],
123
+ 'sha256': None, 'bytes': None} for item in payload.get('media', [])]
124
+
125
+ if target:
126
+ delivery = {'action': 'verify_or_edit_existing', 'remote_id': target,
127
+ 'upload_allowed': False}
128
+ elif reconciling:
129
+ delivery = {'action': 'search_existing_before_retry', 'upload_allowed': False}
130
+ else:
131
+ delivery = {'action': 'upload_approved_file', 'upload_allowed': True}
132
+
133
+ local = current.publish_at.astimezone(ZoneInfo(current.timezone_name))
134
+ manifest = {
135
+ 'schema': SCHEMA,
136
+ 'state': 'awaiting_ui' if current.state == 'awaiting_ui' else current.state,
137
+ 'job': {'id': current.id, 'brand': current.brand, 'platform': current.platform,
138
+ 'account_id': current.account_id},
139
+ 'payload': deepcopy(payload),
140
+ 'schedule': {'local': local.isoformat(), 'utc': current.publish_at.isoformat(),
141
+ 'timezone': current.timezone_name},
142
+ 'approval_digest': current.approval_digest,
143
+ 'content_hash': current.content_hash,
144
+ 'media_hash': current.media_hash,
145
+ 'media': files,
146
+ 'media_integrity': media_integrity,
147
+ 'delivery': delivery,
148
+ 'operator_policy': {
149
+ 'official_ui_only': True,
150
+ 'verify_current_window_in_ui': True,
151
+ 'fresh_account_calendar_day_and_destinations_before_final_click': True,
152
+ 'mark_submit_started_before_final_confirmation': True,
153
+ 'trusted_operator_attestation_required': True,
154
+ },
155
+ }
156
+ # Defensive check that the returned package still describes exact content.
157
+ if hash_value(manifest['payload']) != current.content_hash:
158
+ raise ValueError('Handoff payload changed while packaging')
159
+ return manifest
160
+
161
+
162
+ def mark_ui_submit_started(job_id: str, *, store: NativeStore,
163
+ now: datetime | None = None) -> NativeJob:
164
+ """Persist the final-submit crash boundary before the operator confirms."""
165
+ now = _now(now)
166
+ job = store.get(job_id)
167
+ if job is None or job.state != 'awaiting_ui' or not job.attempt_id:
168
+ raise ValueError('An owned awaiting_ui attempt is required')
169
+ if job.publish_at <= now:
170
+ raise ValueError('Deadline expired; immediate publication prohibited')
171
+ verify_approval(job,store.get_payload(job_id))
172
+ store.checkpoint(job.id, job.attempt_id,
173
+ {'ui_submit_started_at': now.isoformat()}, now=now)
174
+ uncertain = store.transition(job.id, 'awaiting_ui', 'uncertain', now=now)
175
+ if uncertain is None:
176
+ raise ValueError('UI submit marker lost attempt ownership')
177
+ return uncertain
178
+
179
+
180
+ def record_observation(job_id: str, observation: NativeObservation, *,
181
+ store: NativeStore, now: datetime | None = None) -> bool:
182
+ """Import trusted operator evidence; never interpret screenshots/artifacts."""
183
+ job = store.get(job_id)
184
+ if job is None:
185
+ raise ValueError('Unknown job')
186
+ if observation.job_id != job_id:
187
+ raise ValueError('Observation belongs to a different job')
188
+ if (job.state not in _DELIVERY_STATES or not job.attempt_id
189
+ or job.approval_digest is None):
190
+ raise ValueError('Observation requires an approved delivery-stage job')
191
+ # NativeStore performs identity/date/freshness/artifact checksum checks and
192
+ # retains invalid observations for audit without promoting success.
193
+ return store.record_observation(observation, now=now)