socialcli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of socialcli might be problematic. Click here for more details.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
"""Bounded Graph v26 methods with actual actor, Page and owned-node binding."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from socialctl.agent_errors import with_error_code, with_http_error_code, error_document
|
|
8
|
+
from socialctl.identity import credential_metadata
|
|
9
|
+
from socialctl.management.meta_schema import MetaError, MetaRejected, MetaUncertain, meta_id, validate_edit
|
|
10
|
+
from socialctl.models import Platform
|
|
11
|
+
|
|
12
|
+
GRAPH = "https://graph.facebook.com/v26.0"
|
|
13
|
+
MAX_RESPONSE = 4 * 1024 * 1024
|
|
14
|
+
PROFILE_FIELDS = {
|
|
15
|
+
"facebook": {"id", "name", "about", "bio", "description", "company_overview", "general_info", "mission", "phone", "website", "followers_count", "link"},
|
|
16
|
+
"instagram": {"id", "name", "username", "biography", "website", "followers_count", "media_count", "profile_picture_url"},
|
|
17
|
+
}
|
|
18
|
+
CONTENT_FIELDS = {
|
|
19
|
+
"post": "id,from,message,created_time,updated_time,is_published,scheduled_publish_time,permalink_url",
|
|
20
|
+
"video": "id,from,title,description,created_time,updated_time,status,published,scheduled_publish_time,permalink_url",
|
|
21
|
+
"media": "id,owner,caption,media_type,media_product_type,timestamp,permalink,is_comment_enabled,alt_text,is_ai_generated",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Only metrics already observed in the project's current Graph API reads are
|
|
25
|
+
# accepted here. This is intentionally a content-insights surface: account
|
|
26
|
+
# dashboards use the provider-specific `stats` readers and are not silently
|
|
27
|
+
# treated as interchangeable with object metrics.
|
|
28
|
+
INSIGHT_METRICS = {
|
|
29
|
+
"facebook": frozenset({
|
|
30
|
+
"post_reactions_by_type_total", "post_video_views",
|
|
31
|
+
"post_video_view_time", "post_video_avg_time_watched",
|
|
32
|
+
}),
|
|
33
|
+
"instagram": frozenset({
|
|
34
|
+
"reach", "saved", "shares", "total_interactions", "views",
|
|
35
|
+
}),
|
|
36
|
+
}
|
|
37
|
+
INSIGHT_PERIODS = frozenset({"day", "week", "days_28", "lifetime"})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class MetaClient:
|
|
41
|
+
def __init__(self, brand, platform, client, *, user_page_authorizer=None, moderation_authorizer=None):
|
|
42
|
+
if platform not in {Platform.FACEBOOK, Platform.INSTAGRAM}:
|
|
43
|
+
raise MetaError("Meta platform required")
|
|
44
|
+
self.brand, self.platform, self.client = brand, platform, client
|
|
45
|
+
# Server-only verifier for explicit asset grants when /me/accounts is
|
|
46
|
+
# completely empty. Never supplied from a proposal or remote payload.
|
|
47
|
+
self._user_page_authorizer = user_page_authorizer
|
|
48
|
+
# Only the authenticated server composition supplies this pilot verifier.
|
|
49
|
+
self._moderation_authorizer = moderation_authorizer
|
|
50
|
+
self.page_id = meta_id((brand.cuentas.get("facebook") or {}).get("page_id"))
|
|
51
|
+
self.account_id = self.page_id if platform is Platform.FACEBOOK else meta_id((brand.cuentas.get("instagram") or {}).get("ig_user_id"))
|
|
52
|
+
try:
|
|
53
|
+
secret = brand.leer_secreto(platform)
|
|
54
|
+
self._remote_user = None
|
|
55
|
+
if platform is Platform.INSTAGRAM and secret.get('auth_mode') == 'broker' and secret.get('protocol') == 'saas-v1':
|
|
56
|
+
from socialctl.connections.meta_user import RemoteMetaUser
|
|
57
|
+
self._remote_user = RemoteMetaUser(brand, platform, client)
|
|
58
|
+
if self._remote_user is not None:
|
|
59
|
+
# Receipt lookup and server-side User operations do not need a
|
|
60
|
+
# client-side Page credential. Fetch it only for a Graph call.
|
|
61
|
+
self._token = None
|
|
62
|
+
elif secret.get("auth_mode") == "broker":
|
|
63
|
+
from socialctl.connections.client import broker_access_token
|
|
64
|
+
self._token = broker_access_token(brand, platform, client, refresh=False)
|
|
65
|
+
else:
|
|
66
|
+
self._token = secret.get("access_token")
|
|
67
|
+
self.token_mode = secret.get("token_mode", "facebook_page")
|
|
68
|
+
self.actor_id = secret.get("actor_id")
|
|
69
|
+
expired = credential_metadata(secret)["expiry"]["expired"]
|
|
70
|
+
except Exception as exc:
|
|
71
|
+
raise with_error_code(MetaError("Meta credentials unavailable"), exc, read_only=False, fallback="authorization_unavailable") from None
|
|
72
|
+
if self._remote_user is None and (not isinstance(self._token, str) or not self._token or expired):
|
|
73
|
+
raise MetaError("Meta credentials missing/expired; not refreshed automatically")
|
|
74
|
+
if self.token_mode not in {"facebook_page", "facebook_user"}:
|
|
75
|
+
raise MetaError("unsupported token mode; Facebook Login required")
|
|
76
|
+
|
|
77
|
+
def request(self, method, path, *, params=None, data=None, files=None, require_success=False):
|
|
78
|
+
# Paths are built only by resource methods. No redirect/remote next URL.
|
|
79
|
+
if method not in {"GET", "POST", "DELETE"} or not re.fullmatch(r"(?:me|[0-9]+(?:_[0-9]+)?)(?:/[a-z_]+)?", path):
|
|
80
|
+
raise MetaError("endpoint/method not allowed")
|
|
81
|
+
if self._token is None:
|
|
82
|
+
try:
|
|
83
|
+
from socialctl.connections.client import broker_access_token
|
|
84
|
+
self._token = broker_access_token(self.brand, self.platform, self.client, refresh=False)
|
|
85
|
+
except Exception as exc:
|
|
86
|
+
raise with_error_code(MetaError('Meta credentials unavailable'), exc, read_only=method == 'GET', fallback='authorization_unavailable') from None
|
|
87
|
+
writing = method != "GET"
|
|
88
|
+
diagnostic = {"method": method, "path": path, "stage": "transport"}
|
|
89
|
+
try:
|
|
90
|
+
with self.client.stream(method, f"{GRAPH}/{path}", params=params, data=data, files=files,
|
|
91
|
+
headers={"Authorization": f"Bearer {self._token}"}, timeout=30, follow_redirects=False) as response:
|
|
92
|
+
diagnostic["http_status"] = response.status_code
|
|
93
|
+
if not response.is_success:
|
|
94
|
+
diagnostic["stage"] = "http"
|
|
95
|
+
error = (MetaUncertain if response.status_code >= 500 or response.is_redirect or response.status_code in {408, 429}
|
|
96
|
+
else MetaRejected) if writing else MetaError
|
|
97
|
+
from socialctl.management.meta_errors import graph_error
|
|
98
|
+
raise with_http_error_code(error(graph_error(response, method, path, self._token)), response, read_only=not writing)
|
|
99
|
+
raw = bytearray()
|
|
100
|
+
diagnostic["stage"] = "response_body"
|
|
101
|
+
for chunk in response.iter_bytes():
|
|
102
|
+
raw.extend(chunk)
|
|
103
|
+
if len(raw) > MAX_RESPONSE:
|
|
104
|
+
raise ValueError()
|
|
105
|
+
diagnostic["stage"] = "decode"
|
|
106
|
+
result = json.loads(raw)
|
|
107
|
+
error = MetaUncertain if writing else MetaError
|
|
108
|
+
if not isinstance(result, dict):
|
|
109
|
+
diagnostic["stage"] = "response_shape"
|
|
110
|
+
raise error("Meta returned a non-object JSON response; outcome unverifiable")
|
|
111
|
+
if "error" in result:
|
|
112
|
+
diagnostic["stage"] = "provider_error"
|
|
113
|
+
from socialctl.management.meta_errors import graph_error
|
|
114
|
+
raise error(graph_error(response, method, path, self._token, payload=result))
|
|
115
|
+
if require_success and result.get("success") is not True:
|
|
116
|
+
diagnostic["stage"] = "acknowledgement"
|
|
117
|
+
raise MetaUncertain("Meta did not confirm success=true; write will not be repeated")
|
|
118
|
+
return result
|
|
119
|
+
except MetaError as exc:
|
|
120
|
+
exc._meta_diagnostic = diagnostic
|
|
121
|
+
raise
|
|
122
|
+
except Exception as exc:
|
|
123
|
+
failure = with_error_code((MetaUncertain if writing else MetaError)(
|
|
124
|
+
"Meta: response/transport unverifiable"), exc, read_only=not writing)
|
|
125
|
+
failure._meta_diagnostic = diagnostic
|
|
126
|
+
raise failure from None
|
|
127
|
+
|
|
128
|
+
def listing(self, target, edge, *, fields, max_pages=10, params=None):
|
|
129
|
+
meta_id(target, composite=True)
|
|
130
|
+
if edge not in {"accounts", "permissions", "feed", "photos", "posts", "videos", "video_reels", "media", "stories", "comments", "reactions", "likes", "insights", "subscribed_apps", "scheduled_posts", "captions"}:
|
|
131
|
+
raise MetaError("unsupported read edge")
|
|
132
|
+
if type(max_pages) is not int or not 1 <= max_pages <= 50:
|
|
133
|
+
raise MetaError("maximum pages must be between 1 and 50")
|
|
134
|
+
return self._pages(f"{target}/{edge}", {"fields": fields, "limit": "100", **(params or {})}, max_pages)
|
|
135
|
+
|
|
136
|
+
def _pages(self, path, params, maximum=10, *, insight_ids=False):
|
|
137
|
+
rows, seen, ids = [], set(), set()
|
|
138
|
+
if insight_ids and 'since' in params and 'until' in params:
|
|
139
|
+
seen.add((str(params['since']), str(params['until'])))
|
|
140
|
+
for _ in range(maximum):
|
|
141
|
+
try:
|
|
142
|
+
result = self.request("GET", path, params=params)
|
|
143
|
+
except MetaError as exc:
|
|
144
|
+
if not rows:
|
|
145
|
+
raise
|
|
146
|
+
return {"data": rows, "complete": False, "absence_proven": False, "error": str(exc),
|
|
147
|
+
"error_detail": error_document(exc, read_only=True)}
|
|
148
|
+
data = result.get("data")
|
|
149
|
+
if not isinstance(data, list) or len(data) > 100 or any(not isinstance(row, dict) for row in data):
|
|
150
|
+
raise MetaError("invalid/excessive Meta list")
|
|
151
|
+
page_ids = set()
|
|
152
|
+
for row in data:
|
|
153
|
+
row_id = row.get("id")
|
|
154
|
+
if insight_ids:
|
|
155
|
+
# Metric identity is the requested resource/name/period;
|
|
156
|
+
# Graph can omit its redundant string ID.
|
|
157
|
+
name, period = row.get("name"), row.get("period")
|
|
158
|
+
if (not isinstance(name, str) or not re.fullmatch(r"[a-z_]{1,64}", name)
|
|
159
|
+
or not isinstance(period, str) or not re.fullmatch(r"[a-z_0-9]{1,32}", period)
|
|
160
|
+
or ("id" in row and row_id != f"{path}/{name}/{period}")):
|
|
161
|
+
raise MetaError("insight ID does not match its resource, metric and period")
|
|
162
|
+
row_key = (name, period)
|
|
163
|
+
elif "id" in row:
|
|
164
|
+
meta_id(row_id, composite=True)
|
|
165
|
+
row_key = row_id
|
|
166
|
+
else:
|
|
167
|
+
rows.append(row)
|
|
168
|
+
continue
|
|
169
|
+
if row_key in ids:
|
|
170
|
+
if not insight_ids or row_key in page_ids:
|
|
171
|
+
raise MetaError("repeated IDs in paginated read")
|
|
172
|
+
from socialctl.management.meta_pagination import merge_metric
|
|
173
|
+
index = next(i for i, prior in enumerate(rows)
|
|
174
|
+
if (prior.get("name"), prior.get("period")) == row_key)
|
|
175
|
+
merged = merge_metric(rows[index], row)
|
|
176
|
+
if merged is None:
|
|
177
|
+
return {"data": rows, "complete": False, "absence_proven": False,
|
|
178
|
+
"error": "Conflicting insight values across time pages; prior observations retained"}
|
|
179
|
+
rows[index] = merged
|
|
180
|
+
page_ids.add(row_key)
|
|
181
|
+
continue
|
|
182
|
+
ids.add(row_key)
|
|
183
|
+
page_ids.add(row_key)
|
|
184
|
+
rows.append(row)
|
|
185
|
+
paging = result.get("paging", {})
|
|
186
|
+
if not isinstance(paging, dict):
|
|
187
|
+
raise MetaError("invalid pagination")
|
|
188
|
+
if not paging.get("next"):
|
|
189
|
+
return {"data": rows, "complete": True, "absence_proven": False}
|
|
190
|
+
cursor = (paging.get("cursors") or {}).get("after")
|
|
191
|
+
if cursor is None and insight_ids:
|
|
192
|
+
from socialctl.management.meta_pagination import next_time_params
|
|
193
|
+
following = next_time_params(paging['next'], f'{GRAPH}/{path}', params)
|
|
194
|
+
if following is None:
|
|
195
|
+
break
|
|
196
|
+
window = (following['since'], following['until'])
|
|
197
|
+
if window in seen:
|
|
198
|
+
break
|
|
199
|
+
seen.add(window)
|
|
200
|
+
params = following
|
|
201
|
+
continue
|
|
202
|
+
if not isinstance(cursor, str) or not re.fullmatch(r"[A-Za-z0-9_=-]{1,2048}", cursor) or cursor in seen:
|
|
203
|
+
break
|
|
204
|
+
seen.add(cursor)
|
|
205
|
+
params = {**params, "after": cursor}
|
|
206
|
+
return {"data": rows, "complete": False, "absence_proven": False}
|
|
207
|
+
|
|
208
|
+
def identity(self, *, user_required=False):
|
|
209
|
+
if user_required and self.token_mode != "facebook_user":
|
|
210
|
+
raise MetaError("Instagram DELETE requires Facebook USER token and instagram_basic + instagram_manage_contents; Page token is not substituted")
|
|
211
|
+
me = self.request("GET", "me", params={"fields": "id,instagram_business_account"} if self.token_mode == "facebook_page" else {"fields": "id"})
|
|
212
|
+
actor = meta_id(me.get("id"))
|
|
213
|
+
if self.token_mode == "facebook_page":
|
|
214
|
+
if actor != self.page_id:
|
|
215
|
+
raise MetaError("authenticated Page does not match brand")
|
|
216
|
+
selected = me
|
|
217
|
+
else:
|
|
218
|
+
if actor != meta_id(self.actor_id):
|
|
219
|
+
raise MetaError("authenticated USER actor does not match configured actor")
|
|
220
|
+
pages = self._pages("me/accounts", {"fields": "id,tasks,instagram_business_account", "limit": "100"})
|
|
221
|
+
matches = [p for p in pages["data"] if p.get("id") == self.page_id]
|
|
222
|
+
if pages['complete'] and not pages['data'] and self._user_page_authorizer is not None:
|
|
223
|
+
selected = self._user_page_authorizer(actor)
|
|
224
|
+
if not isinstance(selected, dict) or selected.get('id') != self.page_id:
|
|
225
|
+
raise MetaError('Explicit USER Page authorization did not match the selected Page')
|
|
226
|
+
else:
|
|
227
|
+
if not pages["complete"] or len(matches) != 1 or not matches[0].get("tasks"):
|
|
228
|
+
raise MetaError("Page managed by USER actor was not verified")
|
|
229
|
+
selected = matches[0]
|
|
230
|
+
if user_required:
|
|
231
|
+
permissions = self._pages("me/permissions", {"limit": "100"})
|
|
232
|
+
granted = {p.get("permission") for p in permissions["data"] if p.get("status") == "granted"}
|
|
233
|
+
if not permissions["complete"] or not {"instagram_basic", "instagram_manage_contents"} <= granted:
|
|
234
|
+
raise MetaError("granted instagram_basic + instagram_manage_contents permissions missing for DELETE")
|
|
235
|
+
if self.platform is Platform.INSTAGRAM and (selected.get("instagram_business_account") or {}).get("id") != self.account_id:
|
|
236
|
+
raise MetaError("linked Instagram account does not match brand")
|
|
237
|
+
return {"actor_id": actor, "token_mode": self.token_mode, "page_id": self.page_id, "account_id": self.account_id}
|
|
238
|
+
|
|
239
|
+
def profile(self, fields=None):
|
|
240
|
+
self.identity()
|
|
241
|
+
allowed = PROFILE_FIELDS[self.platform.value]
|
|
242
|
+
fields = sorted(allowed) if fields is None else fields
|
|
243
|
+
if not fields or set(fields) - allowed:
|
|
244
|
+
raise MetaError("profile fields outside documented list")
|
|
245
|
+
result = self.request("GET", self.account_id, params={"fields": ",".join(sorted(set(fields) | {"id"}))})
|
|
246
|
+
if result.get("id") != self.account_id:
|
|
247
|
+
raise MetaError("profile ID mismatch")
|
|
248
|
+
return {k: result[k] for k in set(fields) | {"id"} if k in result}
|
|
249
|
+
|
|
250
|
+
def content(self, target_id, kind=None):
|
|
251
|
+
self.identity()
|
|
252
|
+
kind = kind or ("media" if self.platform is Platform.INSTAGRAM else "post")
|
|
253
|
+
if kind not in CONTENT_FIELDS or (kind == "media") != (self.platform is Platform.INSTAGRAM):
|
|
254
|
+
raise MetaError("incompatible content type/platform")
|
|
255
|
+
meta_id(target_id, composite=kind == "post")
|
|
256
|
+
result = self.request("GET", target_id, params={"fields": CONTENT_FIELDS[kind]})
|
|
257
|
+
owner = "owner" if kind == "media" else "from"
|
|
258
|
+
if result.get("id") != target_id or (result.get(owner) or {}).get("id") != self.account_id:
|
|
259
|
+
raise MetaError("exact content owner was not verified")
|
|
260
|
+
return {k: result[k] for k in CONTENT_FIELDS[kind].split(",") if k in result}
|
|
261
|
+
|
|
262
|
+
def deletion_content(self, target_id):
|
|
263
|
+
"""Classify owned IG media before requesting product-specific fields."""
|
|
264
|
+
self.identity()
|
|
265
|
+
meta_id(target_id)
|
|
266
|
+
fields = "id,owner,media_type,media_product_type,timestamp,permalink"
|
|
267
|
+
result = self.request("GET", target_id, params={"fields": fields})
|
|
268
|
+
owner = result.get("owner")
|
|
269
|
+
if (result.get("id") != target_id or not isinstance(owner, dict)
|
|
270
|
+
or owner.get("id") != self.account_id):
|
|
271
|
+
raise MetaError("exact content owner was not verified")
|
|
272
|
+
media_type, product = result.get("media_type"), result.get("media_product_type")
|
|
273
|
+
allowed = {"STORY": {"IMAGE", "VIDEO"}, "REELS": {"VIDEO"},
|
|
274
|
+
"FEED": {"IMAGE", "VIDEO", "CAROUSEL_ALBUM"}}
|
|
275
|
+
if (not isinstance(product, str) or product not in allowed
|
|
276
|
+
or not isinstance(media_type, str) or media_type not in allowed[product]):
|
|
277
|
+
raise MetaError("Instagram media classification was not verified")
|
|
278
|
+
if product == "STORY":
|
|
279
|
+
return {k: result[k] for k in fields.split(",") if k in result}
|
|
280
|
+
# Preserve the full existing feed/Reel baseline, including editable fields.
|
|
281
|
+
content = self.content(target_id)
|
|
282
|
+
if any(content.get(k) != result[k] for k in ("media_type", "media_product_type")):
|
|
283
|
+
raise MetaError("Instagram media classification changed during inspection")
|
|
284
|
+
return content
|
|
285
|
+
|
|
286
|
+
def content_list(self, edge=None, max_pages=10, *, for_comments=False):
|
|
287
|
+
self.identity()
|
|
288
|
+
edge = edge or ("media" if self.platform is Platform.INSTAGRAM else "posts")
|
|
289
|
+
valid = {"media", "stories"} if self.platform is Platform.INSTAGRAM else {"feed", "photos", "posts", "videos", "video_reels", "stories", "scheduled_posts"}
|
|
290
|
+
if edge not in valid:
|
|
291
|
+
raise MetaError("listing unsupported for platform")
|
|
292
|
+
kind = "media" if self.platform is Platform.INSTAGRAM else ("video" if edge in {"videos", "video_reels"} else "post")
|
|
293
|
+
owner = "owner" if kind == "media" else "from"
|
|
294
|
+
# Comment traversal needs only IDs and exact ownership. Optional edit,
|
|
295
|
+
# disclosure or scheduling fields must not block an otherwise readable inbox.
|
|
296
|
+
fields = f'id,{owner}' if for_comments else CONTENT_FIELDS[kind]
|
|
297
|
+
if self.platform is Platform.INSTAGRAM and edge == "stories" and not for_comments:
|
|
298
|
+
# Story media rejects the comment controls used by feed/Reel media.
|
|
299
|
+
fields = "id,owner,media_type,media_product_type,timestamp,permalink"
|
|
300
|
+
result = self.listing(self.account_id, edge, fields=fields, max_pages=max_pages)
|
|
301
|
+
for row in result["data"]:
|
|
302
|
+
meta_id(row.get("id"), composite=kind == "post")
|
|
303
|
+
if (row.get(owner) or {}).get("id") != self.account_id:
|
|
304
|
+
raise MetaError("owner not verified in listing")
|
|
305
|
+
return result
|
|
306
|
+
|
|
307
|
+
def insights(self, target_id, metrics, *, period=None, since=None, until=None,
|
|
308
|
+
breakdown=None, max_pages=10):
|
|
309
|
+
"""Read explicitly selected, owned content insights.
|
|
310
|
+
|
|
311
|
+
The account-level Graph insights catalogue changes independently from
|
|
312
|
+
object metrics. Requiring an explicit owned target keeps this method
|
|
313
|
+
from turning an account metric name into a false zero or an invented
|
|
314
|
+
compatibility claim; the account-wide snapshot remains `stats`.
|
|
315
|
+
"""
|
|
316
|
+
self.identity()
|
|
317
|
+
target_id = meta_id(target_id, composite=self.platform is Platform.FACEBOOK)
|
|
318
|
+
self.content(target_id)
|
|
319
|
+
if not isinstance(metrics, (list, tuple)) or not metrics:
|
|
320
|
+
raise MetaError("select at least one content metric")
|
|
321
|
+
names = list(metrics)
|
|
322
|
+
if len(names) > 20 or len(set(names)) != len(names) or any(
|
|
323
|
+
not isinstance(name, str) or name not in INSIGHT_METRICS[self.platform.value]
|
|
324
|
+
for name in names
|
|
325
|
+
):
|
|
326
|
+
raise MetaError("Meta metric not allowed or repeated for this platform")
|
|
327
|
+
if period is not None and period not in INSIGHT_PERIODS:
|
|
328
|
+
raise MetaError("undocumented Meta period")
|
|
329
|
+
for value, label in ((since, "since"), (until, "until")):
|
|
330
|
+
if value is not None and (type(value) is not int or value < 0):
|
|
331
|
+
raise MetaError(f"{label} must be an integer Unix timestamp")
|
|
332
|
+
if since is not None and until is not None and since >= until:
|
|
333
|
+
raise MetaError("since must precede until")
|
|
334
|
+
if breakdown is not None:
|
|
335
|
+
if not isinstance(breakdown, (list, tuple)) or not breakdown or len(breakdown) > 3:
|
|
336
|
+
raise MetaError("breakdown must contain between 1 and 3 values")
|
|
337
|
+
if any(not isinstance(value, str) or not re.fullmatch(r"[a-z_]{1,64}", value) for value in breakdown):
|
|
338
|
+
raise MetaError("breakdown contains an invalid value")
|
|
339
|
+
params = {"metric": ",".join(names), "limit": "100"}
|
|
340
|
+
if period is not None:
|
|
341
|
+
params["period"] = period
|
|
342
|
+
if since is not None:
|
|
343
|
+
params["since"] = str(since)
|
|
344
|
+
if until is not None:
|
|
345
|
+
params["until"] = str(until)
|
|
346
|
+
if breakdown is not None:
|
|
347
|
+
params["breakdown"] = ",".join(breakdown)
|
|
348
|
+
result = self._pages(f"{target_id}/insights", params, max_pages, insight_ids=True)
|
|
349
|
+
for row in result["data"]:
|
|
350
|
+
if not isinstance(row.get("name"), str) or row["name"] not in names:
|
|
351
|
+
raise MetaError("insights response contains an unrequested metric")
|
|
352
|
+
if period is not None and row.get("period") != period:
|
|
353
|
+
raise MetaError("insights response contains an unrequested period")
|
|
354
|
+
if not isinstance(row.get("values"), list) or any(not isinstance(value, dict) for value in row["values"]):
|
|
355
|
+
raise MetaError("insights response lacks verifiable values")
|
|
356
|
+
return {"target_id": target_id, "metrics": names, **result}
|
|
357
|
+
|
|
358
|
+
def content_publishing_limit(self):
|
|
359
|
+
"""Read business publishing limit (Instagram) without writes."""
|
|
360
|
+
if self.platform is not Platform.INSTAGRAM:
|
|
361
|
+
raise MetaError("publishing_limit.get applies only to Instagram")
|
|
362
|
+
self.identity()
|
|
363
|
+
payload = self.request("GET", f"{self.account_id}/content_publishing_limit")
|
|
364
|
+
if not isinstance(payload, dict):
|
|
365
|
+
raise MetaError("publishing limit response lacks valid structure")
|
|
366
|
+
return payload
|
|
367
|
+
|
|
368
|
+
def comments(self, target_id, max_pages=10):
|
|
369
|
+
self.content(target_id)
|
|
370
|
+
fields = "id,message,from,is_hidden" if self.platform is Platform.FACEBOOK else "id,text,from,hidden"
|
|
371
|
+
return self.listing(target_id, "comments", fields=fields, max_pages=max_pages)
|
|
372
|
+
|
|
373
|
+
def reactions(self, target_id, max_pages=10):
|
|
374
|
+
if self.platform is not Platform.FACEBOOK:
|
|
375
|
+
raise MetaError("reactions documented only for Facebook")
|
|
376
|
+
self.content(target_id)
|
|
377
|
+
return self.listing(target_id, "reactions", fields="id,name,type", max_pages=max_pages)
|
|
378
|
+
|
|
379
|
+
def subscriptions(self):
|
|
380
|
+
self.identity()
|
|
381
|
+
if self.platform is not Platform.FACEBOOK or self.token_mode != "facebook_page":
|
|
382
|
+
raise MetaError("subscribed_apps is implemented for Page with Page token; does not enable Instagram Login or messaging")
|
|
383
|
+
app_id = meta_id((self.brand.cuentas.get("facebook") or {}).get("app_id"))
|
|
384
|
+
rows = self.listing(self.page_id, "subscribed_apps", fields="id,subscribed_fields")
|
|
385
|
+
if not rows["complete"]:
|
|
386
|
+
raise MetaError("incomplete subscriptions")
|
|
387
|
+
matches = [r for r in rows["data"] if r.get("id") == app_id]
|
|
388
|
+
if len(matches) > 1:
|
|
389
|
+
raise MetaError("ambiguous subscription")
|
|
390
|
+
fields = matches[0].get("subscribed_fields") if matches else []
|
|
391
|
+
if not isinstance(fields, list) or any(not isinstance(f, str) for f in fields):
|
|
392
|
+
raise MetaError("subscription fields unverifiable")
|
|
393
|
+
return {"id": self.page_id, "app_id": app_id, "subscribed_fields": sorted(fields)}
|
|
394
|
+
|
|
395
|
+
def inspect_mention(self, media_id, comment_id=None):
|
|
396
|
+
meta_id(media_id)
|
|
397
|
+
if comment_id is not None:
|
|
398
|
+
meta_id(comment_id)
|
|
399
|
+
if self._remote_user is not None:
|
|
400
|
+
body = {'media_id': media_id}
|
|
401
|
+
if comment_id is not None:
|
|
402
|
+
body['comment_id'] = comment_id
|
|
403
|
+
observation = self._remote_user.request('inspect', mention=body)['before']
|
|
404
|
+
if (observation.get('id') != (comment_id or media_id)
|
|
405
|
+
or observation.get('media_id') != media_id):
|
|
406
|
+
raise MetaError('Mention response does not match the selected target')
|
|
407
|
+
return observation
|
|
408
|
+
if comment_id is not None:
|
|
409
|
+
return self.mentioned_comment(comment_id, media_id)
|
|
410
|
+
return self.mentioned_media(media_id)
|
|
411
|
+
|
|
412
|
+
def mentioned_media(self, media_id):
|
|
413
|
+
meta_id(media_id)
|
|
414
|
+
if self.platform is not Platform.INSTAGRAM or self.token_mode != 'facebook_user':
|
|
415
|
+
raise MetaError('Mentions require an Instagram Facebook Login User token')
|
|
416
|
+
self.identity()
|
|
417
|
+
result = self.request('GET', self.account_id, params={
|
|
418
|
+
'fields': f'id,mentioned_media.media_id({media_id}){{id,caption,media_type}}'})
|
|
419
|
+
mention = result.get('mentioned_media')
|
|
420
|
+
if (result.get('id') != self.account_id or not isinstance(mention, dict)
|
|
421
|
+
or mention.get('id') != media_id or not isinstance(mention.get('caption'), str)
|
|
422
|
+
or mention.get('media_type') not in {'IMAGE', 'VIDEO', 'CAROUSEL_ALBUM'}):
|
|
423
|
+
raise MetaError('Exact media mention of selected account was not verified')
|
|
424
|
+
return {'id': media_id, 'media_id': media_id, 'caption': mention['caption'],
|
|
425
|
+
'media_type': mention['media_type']}
|
|
426
|
+
|
|
427
|
+
def mentioned_comment(self, comment_id, media_id):
|
|
428
|
+
if self.platform is not Platform.INSTAGRAM or self.token_mode != "facebook_user":
|
|
429
|
+
raise MetaError("mentions requires Instagram Facebook Login with USER token and comment permissions")
|
|
430
|
+
self.identity()
|
|
431
|
+
meta_id(comment_id)
|
|
432
|
+
meta_id(media_id)
|
|
433
|
+
result = self.request("GET", self.account_id, params={"fields": f"id,mentioned_comment.comment_id({comment_id}){{id,text,media{{id}}}}"})
|
|
434
|
+
mention = result.get("mentioned_comment")
|
|
435
|
+
if (result.get("id") != self.account_id or not isinstance(mention, dict) or mention.get("id") != comment_id
|
|
436
|
+
or (mention.get("media") or {}).get("id") != media_id or not isinstance(mention.get("text"), str)):
|
|
437
|
+
raise MetaError("exact mention of selected account was not verified")
|
|
438
|
+
return {"id": comment_id, "media_id": media_id, "text": mention["text"]}
|
|
439
|
+
|
|
440
|
+
def _uses_remote_user(self, edit):
|
|
441
|
+
return self._remote_user is not None and edit.action in {'media-delete', 'mention-reply', 'comment-moderate'}
|
|
442
|
+
|
|
443
|
+
def operation_identity(self, edit):
|
|
444
|
+
if self._uses_remote_user(edit):
|
|
445
|
+
return self._remote_user.request('identity', edit)['identity']
|
|
446
|
+
return self.identity(user_required=edit.action == 'media-delete')
|
|
447
|
+
|
|
448
|
+
def recover_receipt(self, edit, change):
|
|
449
|
+
if self._uses_remote_user(edit):
|
|
450
|
+
# Status already performs independent moderation reconciliation.
|
|
451
|
+
# Explicit server uncertainty must keep the local change unresolved:
|
|
452
|
+
# a later GET can see a newer state without releasing the server guard.
|
|
453
|
+
# A successful verified_readback response has no provider receipt.
|
|
454
|
+
return self._remote_user.request('status', edit, change=change).get('receipt')
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
def require_write_capability(self, edit):
|
|
458
|
+
"""Enforce disabled write scopes without blocking historical reads."""
|
|
459
|
+
if self.platform is Platform.INSTAGRAM and edit.action == 'comment-moderate':
|
|
460
|
+
if self._uses_remote_user(edit):
|
|
461
|
+
self._remote_user.request('identity', edit)
|
|
462
|
+
return
|
|
463
|
+
if self.token_mode=='facebook_user' and self._moderation_authorizer is not None:
|
|
464
|
+
self._moderation_authorizer(edit)
|
|
465
|
+
return
|
|
466
|
+
raise MetaError('Instagram comment moderation is disabled without an exact server-side User-token pilot.')
|
|
467
|
+
|
|
468
|
+
def validate_action(self, edit):
|
|
469
|
+
edit = validate_edit(edit)
|
|
470
|
+
ig = self.platform is Platform.INSTAGRAM
|
|
471
|
+
if edit.action in {"media-update", "media-delete", "mention-reply"} and not ig:
|
|
472
|
+
raise MetaError("Instagram-only action")
|
|
473
|
+
if ig and edit.action in {"profile-update", "post-update", "video-update", "post-delete", "video-delete", "like", "unlike", "schedule-reprogram", "schedule-cancel"}:
|
|
474
|
+
raise MetaError("action undocumented for Instagram; content is not deleted/recreated for editing")
|
|
475
|
+
self.operation_identity(edit)
|
|
476
|
+
if edit.action.startswith("subscription-"):
|
|
477
|
+
if ig or self.token_mode != "facebook_page" or edit.target_id != self.page_id:
|
|
478
|
+
raise MetaError("subscription requires selected Page and its Page token")
|
|
479
|
+
if edit.subscribed_fields is not None and set(edit.subscribed_fields) - {"feed"}:
|
|
480
|
+
raise MetaError("only feed is enabled; messaging/leadgen/other products are not activated")
|
|
481
|
+
return edit
|
|
482
|
+
|
|
483
|
+
def snapshot(self, edit):
|
|
484
|
+
edit = validate_edit(edit)
|
|
485
|
+
if self._uses_remote_user(edit):
|
|
486
|
+
return self._remote_user.request('inspect', edit)['before']
|
|
487
|
+
edit = self.validate_action(edit)
|
|
488
|
+
if edit.action.startswith("subscription-"):
|
|
489
|
+
return self.subscriptions()
|
|
490
|
+
if edit.action == "mention-reply":
|
|
491
|
+
if edit.target_id != self.account_id:
|
|
492
|
+
raise MetaError("mention must target selected Instagram account")
|
|
493
|
+
return self.mentioned_comment(edit.comment_id, edit.media_id)
|
|
494
|
+
if edit.action == "schedule-reprogram":
|
|
495
|
+
content = self.content(edit.target_id, "post")
|
|
496
|
+
if content.get("is_published"):
|
|
497
|
+
raise MetaError("published content cannot be rescheduled")
|
|
498
|
+
if not isinstance(content.get("scheduled_publish_time"), int):
|
|
499
|
+
raise MetaError("publication schedule cannot be verified")
|
|
500
|
+
return content
|
|
501
|
+
if edit.action == "schedule-cancel":
|
|
502
|
+
content = self.content(edit.target_id, "post")
|
|
503
|
+
if content.get("is_published"):
|
|
504
|
+
raise MetaError("published content cannot be cancelled")
|
|
505
|
+
if not isinstance(content.get("scheduled_publish_time"), int):
|
|
506
|
+
raise MetaError("publication schedule cannot be verified")
|
|
507
|
+
return content
|
|
508
|
+
if edit.action == "profile-update":
|
|
509
|
+
if edit.target_id != self.account_id:
|
|
510
|
+
raise MetaError("profile belongs to another account")
|
|
511
|
+
profile = self.profile(list(edit.patch))
|
|
512
|
+
missing = sorted(set(edit.patch) - set(profile))
|
|
513
|
+
if missing:
|
|
514
|
+
raise MetaError("Meta did not return profile fields: " + ", ".join(missing) +
|
|
515
|
+
"; missing does not mean unset. Cannot preview or verify this change.")
|
|
516
|
+
return profile
|
|
517
|
+
kind = "video" if edit.action.startswith("video-") else None
|
|
518
|
+
content = (self.deletion_content(edit.target_id) if edit.action == "media-delete"
|
|
519
|
+
else self.content(edit.target_id, kind))
|
|
520
|
+
if edit.action == "media-update":
|
|
521
|
+
# IG reads is_comment_enabled but accepts comment_enabled on POST.
|
|
522
|
+
# Keep the durable proposal's existing write-parameter schema; never
|
|
523
|
+
# turn an absent (e.g. album child) or malformed read into False.
|
|
524
|
+
enabled = content.get("is_comment_enabled")
|
|
525
|
+
if type(enabled) is not bool:
|
|
526
|
+
raise MetaError("Instagram comment setting is unavailable; cannot preview or verify this change")
|
|
527
|
+
return {"id": edit.target_id, "comment_enabled": enabled}
|
|
528
|
+
if edit.action == "comment-moderate":
|
|
529
|
+
result = self.comments(edit.target_id)
|
|
530
|
+
rows = [r for r in result["data"] if r.get("id") == edit.comment_id]
|
|
531
|
+
hidden = "is_hidden" if self.platform is Platform.FACEBOOK else "hidden"
|
|
532
|
+
if not rows and self.platform is Platform.INSTAGRAM and result["complete"]:
|
|
533
|
+
# Instagram omits hidden comments from /{media_id}/comments; verify
|
|
534
|
+
# the hidden comment object and its exact owned media binding.
|
|
535
|
+
direct = self.request("GET", edit.comment_id,
|
|
536
|
+
params={"fields": "id,text,from,hidden,media{id}"})
|
|
537
|
+
if (direct.get("id") == edit.comment_id
|
|
538
|
+
and (direct.get("media") or {}).get("id") == edit.target_id
|
|
539
|
+
and direct.get("hidden") is True):
|
|
540
|
+
rows = [direct]
|
|
541
|
+
if len(rows) != 1 or type(rows[0].get(hidden)) is not bool:
|
|
542
|
+
raise MetaError("comment/moderation status not verified on owned media")
|
|
543
|
+
# New server pilot proposals need visitor eligibility. Historical
|
|
544
|
+
# local readback must remain available without reopening writes.
|
|
545
|
+
if self.platform is Platform.INSTAGRAM and self._moderation_authorizer is not None:
|
|
546
|
+
actor=rows[0].get('from')
|
|
547
|
+
if not isinstance(actor,dict):
|
|
548
|
+
raise MetaError('Instagram comment author is unavailable')
|
|
549
|
+
author=actor.get('id')
|
|
550
|
+
if (not result['complete'] or meta_id(author)==self.account_id
|
|
551
|
+
or content.get('media_type') not in {'IMAGE','VIDEO','CAROUSEL_ALBUM'}
|
|
552
|
+
or content.get('media_product_type')=='LIVE'):
|
|
553
|
+
raise MetaError('Instagram moderation requires a verified visitor comment on eligible owned media')
|
|
554
|
+
return {"id": edit.comment_id, "hidden": rows[0][hidden]}
|
|
555
|
+
if edit.action in {"like", "unlike"}:
|
|
556
|
+
if self.token_mode != 'facebook_page':
|
|
557
|
+
raise MetaError('Facebook likes require the connected Page token; a user token is not substituted')
|
|
558
|
+
if edit.comment_id is not None:
|
|
559
|
+
comments = self.comments(edit.target_id)
|
|
560
|
+
matches = [row for row in comments['data'] if row.get('id') == edit.comment_id]
|
|
561
|
+
if len(matches) != 1:
|
|
562
|
+
raise MetaError('exact comment was not verified on owned media; pass target_id for the media and comment_id for its top-level comment')
|
|
563
|
+
result = self.request('GET', f'{edit.comment_id}/likes', params={'summary':'has_liked,can_like', 'limit':'0'})
|
|
564
|
+
summary = result.get('summary')
|
|
565
|
+
if not isinstance(summary, dict) or type(summary.get('has_liked')) is not bool:
|
|
566
|
+
raise MetaError('Page like state unavailable; absence is not inferred from a profile list')
|
|
567
|
+
if edit.action == 'like' and not summary['has_liked'] and summary.get('can_like') is not True:
|
|
568
|
+
raise MetaError('Facebook did not confirm that the connected Page can like this comment')
|
|
569
|
+
return {'id': edit.comment_id, 'media_id': edit.target_id,
|
|
570
|
+
'comment_text': matches[0].get('message'), 'liked_by_page': summary['has_liked']}
|
|
571
|
+
# Profile lists can omit the connected Page even after a successful
|
|
572
|
+
# like. Use the authenticated viewer's explicit state, not absence
|
|
573
|
+
# from a privacy-filtered list, for both preview and read-back.
|
|
574
|
+
result = self.request('GET', f'{edit.target_id}/likes',
|
|
575
|
+
params={'summary':'has_liked,can_like', 'limit':'0'})
|
|
576
|
+
summary = result.get('summary')
|
|
577
|
+
if not isinstance(summary, dict) or type(summary.get('has_liked')) is not bool:
|
|
578
|
+
raise MetaError('Page like state unavailable; absence is not inferred from a profile list')
|
|
579
|
+
if edit.action == 'like' and not summary['has_liked'] and summary.get('can_like') is not True:
|
|
580
|
+
raise MetaError('Facebook did not confirm that the connected Page can like this post')
|
|
581
|
+
return {"id": edit.target_id, "liked_by_page": summary['has_liked']}
|
|
582
|
+
if edit.patch:
|
|
583
|
+
if set(edit.patch) - set(content):
|
|
584
|
+
raise MetaError("resource did not return all fields to be edited")
|
|
585
|
+
return {"id": edit.target_id, **{k: content[k] for k in edit.patch}}
|
|
586
|
+
return content
|
|
587
|
+
|
|
588
|
+
def expected(self, edit, before):
|
|
589
|
+
if edit.action == "comment-moderate":
|
|
590
|
+
return {**before, "hidden": edit.hide}
|
|
591
|
+
if edit.action in {"like", "unlike"}:
|
|
592
|
+
return {**before, "liked_by_page": edit.action == "like"}
|
|
593
|
+
if edit.action == "schedule-reprogram":
|
|
594
|
+
return {**before, "scheduled_publish_time": edit.scheduled_publish_time}
|
|
595
|
+
if edit.action.startswith("subscription-"):
|
|
596
|
+
return {**before, "subscribed_fields": sorted(edit.subscribed_fields or [])}
|
|
597
|
+
return {**before, **(edit.patch or {})}
|
|
598
|
+
|
|
599
|
+
def mutate(self, edit, *, change=None):
|
|
600
|
+
edit = validate_edit(edit)
|
|
601
|
+
self.require_write_capability(edit)
|
|
602
|
+
if self._uses_remote_user(edit):
|
|
603
|
+
return self._remote_user.request('mutate', edit, change=change)['receipt']
|
|
604
|
+
edit = self.validate_action(edit)
|
|
605
|
+
if edit.action in {"profile-update", "post-update", "video-update", "media-update"}:
|
|
606
|
+
data = {k: (str(v).lower() if type(v) is bool else v) for k, v in edit.patch.items()}
|
|
607
|
+
result = self.request("POST", edit.target_id, data=data, require_success=True)
|
|
608
|
+
elif edit.action in {"post-delete", "video-delete", "media-delete"}:
|
|
609
|
+
result = self.request("DELETE", edit.target_id, require_success=True)
|
|
610
|
+
elif edit.action == "schedule-reprogram":
|
|
611
|
+
result = self.request("POST", edit.target_id, data={"scheduled_publish_time": edit.scheduled_publish_time}, require_success=True)
|
|
612
|
+
elif edit.action == "schedule-cancel":
|
|
613
|
+
result = self.request("DELETE", edit.target_id, require_success=True)
|
|
614
|
+
elif edit.action == "comment-moderate":
|
|
615
|
+
field = "is_hidden" if self.platform is Platform.FACEBOOK else "hide"
|
|
616
|
+
result = self.request("POST", edit.comment_id, data={field: str(edit.hide).lower()}, require_success=True)
|
|
617
|
+
elif edit.action in {"like", "unlike"}:
|
|
618
|
+
result = self.request("POST" if edit.action == "like" else "DELETE", f"{edit.comment_id or edit.target_id}/likes", require_success=True)
|
|
619
|
+
elif edit.action.startswith("subscription-"):
|
|
620
|
+
result = self.request("POST" if edit.action == "subscription-set" else "DELETE", f"{edit.target_id}/subscribed_apps",
|
|
621
|
+
data={"subscribed_fields": ",".join(edit.subscribed_fields)} if edit.subscribed_fields else None,
|
|
622
|
+
require_success=True)
|
|
623
|
+
elif edit.action == "mention-reply":
|
|
624
|
+
result = self.request("POST", f"{self.account_id}/mentions", data={"media_id": edit.media_id, "comment_id": edit.comment_id, "message": edit.message})
|
|
625
|
+
try:
|
|
626
|
+
return {"id": meta_id(result.get("id")), "accepted": True}
|
|
627
|
+
except MetaError:
|
|
628
|
+
raise MetaUncertain("mention reply lacks ID; do not repeat") from None
|
|
629
|
+
else:
|
|
630
|
+
raise MetaError("handler not yet implemented")
|
|
631
|
+
return {"success": True, "target_id": edit.comment_id or edit.target_id}
|