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,13 @@
1
+ """Native scheduling contracts, durable ledger, and operator evidence."""
2
+ from .models import NativeJob, NativeObservation
3
+ from .handoff import mark_ui_submit_started, prepare_handoff, record_observation
4
+ from .verification import verify
5
+
6
+ __all__ = [
7
+ 'NativeJob',
8
+ 'NativeObservation',
9
+ 'mark_ui_submit_started',
10
+ 'prepare_handoff',
11
+ 'record_observation',
12
+ 'verify',
13
+ ]
@@ -0,0 +1,15 @@
1
+ """Narrow contract for approved API delivery; provider clients live elsewhere."""
2
+
3
+ from typing import Callable, Protocol
4
+
5
+ from .models import NativeJob
6
+
7
+
8
+ class DeliveryUncertain(RuntimeError):
9
+ """A remote write may have been accepted; reconcile before another send."""
10
+
11
+
12
+ class DeliveryAdapter(Protocol):
13
+ def deliver(self, job: NativeJob, payload: dict,
14
+ checkpoint: Callable[[dict], None]) -> str:
15
+ """Return the remote ID after sending the approved content."""
@@ -0,0 +1,40 @@
1
+ """Read-only API reconciliation for an already claimed approved occurrence."""
2
+
3
+ from collections.abc import Callable
4
+
5
+ from .approval import verify_approval
6
+ from .models import NativeJob, NativeObservation
7
+ from .store import NativeStore
8
+
9
+
10
+ def reconcile_api(job_id: str, *, store: NativeStore,
11
+ reader: Callable[[NativeJob, dict], dict]) -> NativeObservation | None:
12
+ """Confirm only a complete, identity-bound provider readback.
13
+
14
+ A partial result is never evidence of absence. The reader must compare
15
+ actual remote copy/options with the approved payload before `matches=True`.
16
+ """
17
+ job = store.get(job_id)
18
+ if job is None or job.brand != store.brand or job.route != 'api':
19
+ raise ValueError('Owned API job required')
20
+ payload = store.get_payload(job_id)
21
+ verify_approval(job, payload)
22
+ result = reader(job, payload)
23
+ if not isinstance(result, dict) or not result.get('complete'):
24
+ store.notice(job_id, 'API readback incomplete; absence not proven')
25
+ return None
26
+ if not result.get('matches'):
27
+ store.notice(job_id, 'API readback differs from approved content or account')
28
+ return None
29
+ observation = result.get('observation')
30
+ if (not isinstance(observation, NativeObservation) or observation.job_id != job.id
31
+ or observation.source != 'api' or observation.account_id != job.account_id
32
+ or observation.remote_ref != job.remote_id or
33
+ observation.content_hash != job.content_hash or
34
+ observation.approval_digest != job.approval_digest):
35
+ store.notice(job_id, 'API readback lacks exact remote identity')
36
+ return None
37
+ if not store.record_observation(observation, now=observation.observed_at):
38
+ store.notice(job_id, 'API observation did not prove publication')
39
+ return None
40
+ return observation
@@ -0,0 +1,160 @@
1
+ """Approval binds immutable intent and freshly read existing media bytes."""
2
+ import hashlib
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ from urllib.parse import parse_qsl, unquote, urlsplit
7
+
8
+ from .models import NativeJob
9
+
10
+ SCHEMA = 'socialctl.native-schedule.approval.v1'
11
+ _SECRET = re.compile(r'(?i)(access.?token|refresh.?token|client.?secret|password|authorization|api.?key|\bbearer\s+\S+|[?&](?:token|sig|signature|key)=)')
12
+
13
+
14
+ def reject_secrets(value):
15
+ """Fail closed before rendering; never interpolate the offending value."""
16
+ text = json.dumps(value, ensure_ascii=False, allow_nan=False)
17
+ candidate = value if isinstance(value, str) else text
18
+ if _SECRET.search(candidate) or re.search(r'(?i)["\']?(?:token|secret|credentials)["\']?\s*[:=]', candidate):
19
+ raise ValueError('Secret-bearing payload rejected')
20
+ if isinstance(value, dict):
21
+ for key, item in value.items():
22
+ if key.lower() in {'token', 'secret', 'credentials', 'upload_url', 'signed_url'}:
23
+ raise ValueError('Secret-bearing payload rejected')
24
+ reject_secrets(item)
25
+ elif isinstance(value, list):
26
+ for item in value:
27
+ reject_secrets(item)
28
+ elif isinstance(value, str):
29
+ # Find intact raw tokens first: decoded whitespace/quotes must never
30
+ # truncate the token and hide later signed/credential parameters.
31
+ for match in re.findall(r'https?://[^\s"<>]+', value, flags=re.IGNORECASE):
32
+ url = urlsplit(match)
33
+ netloc = _decode_component(url.netloc)
34
+ query = _decode_component(url.query)
35
+ fragment = _decode_component(url.fragment)
36
+ # Only known public parameters may cross the preview boundary.
37
+ public = {'v', 't', 'start', 'end', 'list', 'index', 'page', 'q', 'search', 'lang'}
38
+ if ('@' in netloc or fragment or
39
+ any(key.lower() not in public for key, _ in parse_qsl(query, keep_blank_values=True))):
40
+ raise ValueError('Credential-capable URL rejected')
41
+
42
+
43
+ def _decode_component(value: str) -> str:
44
+ """Bounded repeated decoding for inspection only; original copy is retained."""
45
+ for _ in range(8):
46
+ newer = unquote(value)
47
+ if newer == value:
48
+ return value
49
+ value = newer
50
+ raise ValueError('Excessively encoded URL component rejected')
51
+
52
+
53
+
54
+ def native_api_followup_pending(payload: dict) -> str | None:
55
+ """Deny combinations whose approved follow-up cannot be fulfilled."""
56
+ if payload.get('first_comment') and payload.get('options', {}).get('selfDeclaredMadeForKids') is True:
57
+ return 'First comments are unavailable for videos made for kids; no submission attempted'
58
+ if payload.get('first_comment') and payload.get('visibility') != 'public':
59
+ return 'Native first comments require eventual public visibility; no submission attempted'
60
+ return None
61
+
62
+
63
+ def validate_payload(platform: str, payload: dict) -> None:
64
+ """Validate content semantics separately from file provenance; never rewrite."""
65
+ from socialctl.models import MediaAsset, MediaKind, Platform, PlatformPost
66
+ from socialctl.publication_policy import validate_derivation
67
+
68
+ origin = payload.get('content_origin')
69
+ if origin not in {'standalone', 'youtube_long'}:
70
+ raise ValueError('content_origin must explicitly be standalone or youtube_long')
71
+ options = payload.get('options')
72
+ if not isinstance(options, dict):
73
+ raise ValueError('Content options required')
74
+ # There is one canonical source identity, not competing adapter-specific ones.
75
+ for key in ('content_origin', 'source_video_id'):
76
+ if key in options:
77
+ raise ValueError('Declare content_origin/source_video_id at payload level, not options')
78
+ media = payload.get('media')
79
+ if not isinstance(media, list):
80
+ raise ValueError('Media list required')
81
+ if options.get('format') == 'text':
82
+ if platform != 'facebook' or media or not isinstance(payload.get('copy'), str) or not payload['copy'].strip():
83
+ raise ValueError('Text-only content requires Facebook, nonempty copy and no media')
84
+ elif not media:
85
+ raise ValueError('Media content requires existing supplied files')
86
+ assets = []
87
+ for item in media:
88
+ if not isinstance(item, dict) or not isinstance(item.get('path'), str):
89
+ raise ValueError('Media path required')
90
+ kind = MediaKind.VIDEO if options.get('format') in {'video','reel'} or Path(item['path']).suffix.lower() in {'.mp4','.mov','.webm','.mkv','.avi'} else MediaKind.IMAGE
91
+ assets.append(MediaAsset(path=Path(item['path']),kind=kind))
92
+ post = PlatformPost(platform=Platform(platform),body=payload['copy'],media=assets,
93
+ content_origin=origin,source_video_id=payload.get('source_video_id'),
94
+ first_comment=payload.get('first_comment'))
95
+ errors = validate_derivation(post,require_origin=True)
96
+ if errors:
97
+ raise ValueError('Invalid content origin/source_video_id/first_comment contract')
98
+
99
+
100
+ def canonical(value) -> bytes:
101
+ return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False,
102
+ allow_nan=False).encode('utf-8')
103
+
104
+
105
+ def hash_value(value) -> str:
106
+ return hashlib.sha256(canonical(value)).hexdigest()
107
+
108
+
109
+ def media_hashes(payload: dict) -> list[dict]:
110
+ reject_secrets(payload)
111
+ media = payload.get('media')
112
+ if not isinstance(media, list) or (not media and payload.get('options', {}).get('format') != 'text'):
113
+ raise ValueError('Existing media with path and origin required')
114
+ result = []
115
+ for item in media:
116
+ if (not isinstance(item, dict) or not isinstance(item.get('path'), str)
117
+ or not isinstance(item.get('origin'), str) or not item['origin'].strip()):
118
+ raise ValueError('Existing media requires path and explicit origin; legacy content is not modified')
119
+ path = Path(item['path'])
120
+ if not path.is_absolute() or not path.is_file() or path.stat().st_size == 0:
121
+ raise ValueError('Media must be an existing nonempty absolute file')
122
+ with path.open('rb') as stream:
123
+ sha = hashlib.file_digest(stream, 'sha256').hexdigest()
124
+ result.append({'path': str(path), 'sha256': sha})
125
+ return result
126
+
127
+
128
+ def approval_document(job: NativeJob, payload: dict) -> dict:
129
+ # Lifecycle IDs/timestamps/evidence are not user intent.
130
+ fields = ('brand', 'platform', 'account_id', 'legacy_entry_id', 'publish_at',
131
+ 'timezone_name', 'dispatch_after', 'route', 'media_hash', 'content_hash')
132
+ raw = job.model_dump(mode='json')
133
+ document = {'schema': SCHEMA, 'intent': {key:raw[key] for key in fields},
134
+ 'payload': payload, 'media': media_hashes(payload)}
135
+ if job.platform == 'youtube':
136
+ from socialctl.upload_consent import youtube_certification
137
+ document['uploader_certification'] = youtube_certification()
138
+ document['data_retention_notice'] = ('Reconcile active YouTube schedules at least every six days. '
139
+ 'Expired local receipts block local management but do not cancel a video already scheduled on YouTube. '
140
+ 'Inspect or cancel it in YouTube Studio before preparing any replacement.')
141
+ # Existing approvals predate this field. Their serialization is immutable.
142
+ if job.schedule_mode != 'legacy_daily':
143
+ document['intent']['schedule_mode'] = job.schedule_mode
144
+ reject_secrets(document)
145
+ return document
146
+
147
+
148
+ def native_digest(job: NativeJob, payload: dict) -> str:
149
+ return hash_value(approval_document(job, payload))
150
+
151
+
152
+ def verify_approval(job: NativeJob, payload: dict, digest: str | None = None) -> str:
153
+ validate_payload(job.platform, payload)
154
+ actual = native_digest(job, payload)
155
+ expected = digest if digest is not None else job.approval_digest
156
+ if not expected or actual != expected:
157
+ raise ValueError('Approval digest missing or changed; show a new preview')
158
+ if hash_value(media_hashes(payload)) != job.media_hash or hash_value(payload) != job.content_hash:
159
+ raise ValueError('Approval digest content/media mismatch; show a new preview')
160
+ return actual
@@ -0,0 +1,73 @@
1
+ """Exact customer instants alongside approved 08:00/09:00 legacy reservations."""
2
+ from datetime import date, datetime, time, timedelta, timezone
3
+ from zoneinfo import ZoneInfo
4
+
5
+ from .models import aware
6
+
7
+ ZONE_NAME = 'America/New_York'
8
+ ZONE = ZoneInfo(ZONE_NAME)
9
+
10
+
11
+ def slot(day: date, *, hour: int = 9) -> datetime:
12
+ return datetime.combine(day, time(hour), ZONE).astimezone(timezone.utc)
13
+
14
+
15
+ def reservation_day(publish_at: datetime, timezone_name: str) -> str:
16
+ local = aware(publish_at).astimezone(ZONE)
17
+ if timezone_name != ZONE_NAME or local.time() not in {time(8), time(9)}:
18
+ raise ValueError('Content must be scheduled at approved 08:00 or legacy 09:00 America/New_York')
19
+ return local.date().isoformat()
20
+
21
+
22
+ def reservation_key(job) -> str:
23
+ if job.schedule_mode == 'legacy_daily':
24
+ return reservation_day(job.publish_at, job.timezone_name)
25
+ instant = aware(job.publish_at)
26
+ if instant.microsecond:
27
+ raise ValueError('Exact scheduling requires whole seconds; no silent rounding')
28
+ return 'at:' + instant.isoformat()
29
+
30
+
31
+ def slot_day(key: str) -> str:
32
+ if key.startswith('at:'):
33
+ return aware(datetime.fromisoformat(key[3:])).astimezone(ZONE).date().isoformat()
34
+ return date.fromisoformat(key).isoformat()
35
+
36
+
37
+ def slots_conflict(first: str, second: str) -> bool:
38
+ if first.startswith('at:') and second.startswith('at:'):
39
+ return first == second
40
+ return slot_day(first) == slot_day(second)
41
+
42
+
43
+ def exact_time(value: datetime, timezone_name: str) -> datetime:
44
+ """Require explicit, valid local wall time and offset; never guess a DST fold."""
45
+ try:
46
+ zone = ZoneInfo(timezone_name)
47
+ except (KeyError, ValueError, TypeError) as exc:
48
+ raise ValueError('Unknown IANA timezone') from exc
49
+ instant = aware(value)
50
+ local = instant.astimezone(zone)
51
+ if value.microsecond:
52
+ raise ValueError('Exact scheduling requires whole seconds; no silent rounding')
53
+ if (local.replace(tzinfo=None) != value.replace(tzinfo=None)
54
+ or local.utcoffset() != value.utcoffset()):
55
+ raise ValueError('Publication time offset does not match the timezone, or local time does not exist')
56
+ return instant
57
+
58
+
59
+ def plan_slots(requested: list[datetime], *, occupied: set[str] | None = None,
60
+ now: datetime | None = None) -> list[datetime]:
61
+ """Stable input-order overflow for ONE explicit platform/account; no writes."""
62
+ now = aware(now or datetime.now(timezone.utc))
63
+ used = set(occupied or ())
64
+ result = []
65
+ for requested_at in requested:
66
+ requested_local = aware(requested_at).astimezone(ZONE)
67
+ hour = 8 if requested_local.time() == time(8) else 9
68
+ day = max(aware(requested_at).astimezone(ZONE).date(), now.astimezone(ZONE).date())
69
+ while day.isoformat() in used or slot(day, hour=hour) <= now or slot(day, hour=hour) < aware(requested_at):
70
+ day += timedelta(days=1)
71
+ used.add(day.isoformat())
72
+ result.append(slot(day, hour=hour))
73
+ return result