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,418 @@
|
|
|
1
|
+
"""Read Facebook Page metrics via Graph API, degrading gracefully when removed insight names require fallback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
from datetime import date, datetime, timezone
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from socialctl.adapters.errores import mensaje_de_error
|
|
11
|
+
from socialctl.auth import obtener_token
|
|
12
|
+
from socialctl.authflow import GRAFO
|
|
13
|
+
from socialctl.brands import Brand
|
|
14
|
+
from socialctl.metricas.base import Lector, SinPermiso
|
|
15
|
+
from socialctl.metricas.modelos import (
|
|
16
|
+
Cuenta,
|
|
17
|
+
EstadoLectura,
|
|
18
|
+
LecturaRed,
|
|
19
|
+
Metricas,
|
|
20
|
+
Pieza,
|
|
21
|
+
TipoPieza,
|
|
22
|
+
)
|
|
23
|
+
from socialctl.models import Platform
|
|
24
|
+
|
|
25
|
+
# Mismo nombre de clave, mismo mecanismo de señal e importado del mismo
|
|
26
|
+
# sitio en vez de vuelto a escribir: `socialctl/metricas/youtube.py` ya
|
|
27
|
+
# resolvió cómo avisar de una lectura parcial sin tocar `estado` ni los
|
|
28
|
+
# modelos (ver su docstring, junto a `MAX_VIDEOS`). Reutilizar el símbolo,
|
|
29
|
+
# no solo el nombre, hace imposible que las dos claves diverjan en
|
|
30
|
+
# silencio -el mismo problema que tenía `VERSION_GRAFO_VERIFICADA` más
|
|
31
|
+
# abajo antes de este arreglo-.
|
|
32
|
+
from socialctl.metricas.youtube import CLAVE_ENRIQUECIMIENTO_FALLIDO
|
|
33
|
+
|
|
34
|
+
#: Fecha y versión contra las que se verificaron los nombres de métrica de
|
|
35
|
+
#: este módulo, llamando a la Página real -no leyendo documentación-. Si estás
|
|
36
|
+
#: leyendo esto mucho después, asume que algún nombre ya murió y compruébalo
|
|
37
|
+
#: antes de fiarte (Task 4, Step 1).
|
|
38
|
+
VERIFICADO_EL = "2026-09-11"
|
|
39
|
+
#: Derivada de `GRAFO` (no repetida a mano) para que esta constante y la
|
|
40
|
+
#: versión real que usan las peticiones no puedan divergir en silencio: si
|
|
41
|
+
#: `socialctl/authflow.py` sube de versión, esta cadena sube sola con ella
|
|
42
|
+
#: en vez de quedarse describiendo una v26.0 que ya nadie pide.
|
|
43
|
+
VERSION_GRAFO_VERIFICADA = GRAFO.rsplit("/", 1)[-1]
|
|
44
|
+
|
|
45
|
+
#: Nombres que en v26.0 ya NO existen: los ocho devuelven
|
|
46
|
+
#: `(#100) The value must be a valid insights metric` y tumban la petición
|
|
47
|
+
#: entera, no solo su propio campo. Están escritos aquí, y no borrados sin
|
|
48
|
+
#: más, para que nadie los reintente dentro de seis meses creyendo que fue un
|
|
49
|
+
#: olvido. El primero es el que este módulo usaba para `alcance`.
|
|
50
|
+
METRICAS_MUERTAS = (
|
|
51
|
+
"post_impressions_unique",
|
|
52
|
+
"post_impressions",
|
|
53
|
+
"post_engaged_users",
|
|
54
|
+
"post_reach",
|
|
55
|
+
"post_unique_impressions",
|
|
56
|
+
"post_impressions_organic_unique",
|
|
57
|
+
"post_video_views_unique",
|
|
58
|
+
"post_activity",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
#: Métricas de publicación que pedimos, todas comprobadas vivas el
|
|
62
|
+
#: 2026-09-11 contra la Página real en la Graph API v26.0. Si Meta retira
|
|
63
|
+
#: alguna, su valor queda `None` y el resto de la lectura sigue igual.
|
|
64
|
+
#:
|
|
65
|
+
#: **No hay alcance.** En v26.0 no existe ninguna métrica de alcance por
|
|
66
|
+
#: publicación en Facebook: los ocho nombres de `METRICAS_MUERTAS` lo cubrían
|
|
67
|
+
#: y todos fallan. No se sustituye por otra parecida -`post_clicks` o
|
|
68
|
+
#: `post_activity_by_action_type` están vivas, pero no son alcance-: el campo
|
|
69
|
+
#: `alcance` sencillamente no está en las `especificas` de esta red.
|
|
70
|
+
#:
|
|
71
|
+
#: Lo que sí hay, y sirve mejor a la meta del proyecto -saber qué funciona-,
|
|
72
|
+
#: es el tiempo visto: `post_video_avg_time_watched` es **retención**, que es
|
|
73
|
+
#: exactamente lo que mide un objetivo de "que vean el contenido", y el
|
|
74
|
+
#: alcance nunca lo midió.
|
|
75
|
+
#:
|
|
76
|
+
#: Las tres de vídeo solo tienen sentido en una publicación de vídeo: en una
|
|
77
|
+
#: foto no vienen, y ahí `None` es la respuesta correcta -"esta métrica no
|
|
78
|
+
#: aplica"-, nunca un cero que se leería como "nadie lo vio".
|
|
79
|
+
METRICAS_POST = (
|
|
80
|
+
"post_reactions_by_type_total,"
|
|
81
|
+
"post_video_views,"
|
|
82
|
+
"post_video_view_time,"
|
|
83
|
+
"post_video_avg_time_watched"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
#: El resto de `fields` del listado de publicaciones, sin el bloque de
|
|
87
|
+
#: insights: id, texto, fecha, enlace, comentarios, compartidos y el adjunto
|
|
88
|
+
#: que distingue foto de vídeo. Ninguno de estos depende de una métrica de
|
|
89
|
+
#: insights, así que ninguno se pierde cuando Meta retira un nombre y
|
|
90
|
+
#: `pedir_listado_con_insights` reintenta sin ese bloque (ver más abajo).
|
|
91
|
+
CAMPOS_POST = (
|
|
92
|
+
"id,message,created_time,permalink_url,"
|
|
93
|
+
"comments.summary(true),shares,"
|
|
94
|
+
# `attachments{media_type}` es lo que distingue una foto de un vídeo en
|
|
95
|
+
# una publicación de Página ("photo", "video", "album", "link"...). Sin
|
|
96
|
+
# pedirlo, todo entraría como imagen. `target{id}` da el id del vídeo,
|
|
97
|
+
# con el que se consulta su duración.
|
|
98
|
+
"attachments{media_type,target}"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
#: Cuántas publicaciones (o medias de Instagram) pide cada página del
|
|
102
|
+
#: listado. 100 es el máximo que acepta la Graph API para `limit`.
|
|
103
|
+
POR_PAGINA_META = 100
|
|
104
|
+
|
|
105
|
+
#: Tope de páginas que se siguen por `paging.next`. No es el tope de
|
|
106
|
+
#: publicaciones que se leen -eso lo decide la propia API, que deja de
|
|
107
|
+
#: mandar `paging.next` cuando no queda nada-, sino la red de seguridad
|
|
108
|
+
#: contra un `next` que no avanza: 50 × 100 son 5000 publicaciones, muy por
|
|
109
|
+
#: encima de cualquier marca de este proyecto.
|
|
110
|
+
#:
|
|
111
|
+
#: **Por qué paginar y no declarar un tope**, que es lo que hacen YouTube
|
|
112
|
+
#: (`MAX_VIDEOS`) y TikTok (`MAX_PAGINAS`): en esas dos, paginar cuesta algo
|
|
113
|
+
#: real -cuota de Analytics por pieza en YouTube, una API de cursor que
|
|
114
|
+
#: puede no avanzar en TikTok-. Aquí no: `paging.next` viene en la misma
|
|
115
|
+
#: respuesta, ya firmado, y seguirlo es una petición más sin coste de
|
|
116
|
+
#: insights. Con un tope, las publicaciones más antiguas desaparecían del
|
|
117
|
+
#: snapshot y de `piezas.yml` sin que nada lo dijera, y `piezas.yml` no
|
|
118
|
+
#: borra lo que ya tenía pero tampoco lo refresca: el histórico se quedaba
|
|
119
|
+
#: congelado en silencio. Si alguna vez se llega a este tope, se avisa (ver
|
|
120
|
+
#: `_seguir_paginas`), que es la diferencia con el silencio de antes.
|
|
121
|
+
MAX_PAGINAS_META = 50
|
|
122
|
+
|
|
123
|
+
#: Mismo umbral que YouTube (ver `socialctl/metricas/youtube.py`): un vídeo de
|
|
124
|
+
#: hasta 3 minutos se clasifica como vertical. Vive aquí duplicado a
|
|
125
|
+
#: propósito, como constante nombrada, para que cambiar el criterio de una red
|
|
126
|
+
#: no cambie el de la otra sin querer.
|
|
127
|
+
VERTICAL_HASTA_SEG = 180
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def valor_insight(insights: dict, nombre: str) -> object | None:
|
|
131
|
+
"""Extract Graph API insight value, preserving missing metrics as None rather than zero."""
|
|
132
|
+
for entrada in (insights or {}).get("data", []):
|
|
133
|
+
if entrada.get("name") == nombre:
|
|
134
|
+
valores = entrada.get("values") or []
|
|
135
|
+
return valores[0].get("value") if valores else None
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def segundos(milisegundos: object | None) -> float | None:
|
|
140
|
+
"""Convert Graph API milliseconds to seconds with one decimal place."""
|
|
141
|
+
if milisegundos is None:
|
|
142
|
+
return None
|
|
143
|
+
try:
|
|
144
|
+
return round(float(milisegundos) / 1000, 1)
|
|
145
|
+
except (TypeError, ValueError):
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def comprobar_permiso(
|
|
150
|
+
respuesta: httpx.Response, platform: Platform, scope: str
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Translate Meta 403/#10 to SinPermiso with exact missing scope; handle non-JSON responses safely."""
|
|
153
|
+
if respuesta.status_code not in (400, 403):
|
|
154
|
+
return
|
|
155
|
+
try:
|
|
156
|
+
error = respuesta.json().get("error") or {}
|
|
157
|
+
except (ValueError, AttributeError):
|
|
158
|
+
return
|
|
159
|
+
if not isinstance(error, dict):
|
|
160
|
+
return
|
|
161
|
+
if error.get("code") in (10, 200) or "permission" in str(
|
|
162
|
+
error.get("message", "")
|
|
163
|
+
).lower():
|
|
164
|
+
raise SinPermiso(platform, scope)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def comprobar_respuesta(
|
|
168
|
+
respuesta: httpx.Response, platform: Platform, scope: str, token: str
|
|
169
|
+
) -> dict:
|
|
170
|
+
"""Parse Graph API JSON without leaking query-string tokens; avoid raise_for_status because its URL could expose credentials."""
|
|
171
|
+
comprobar_permiso(respuesta, platform, scope)
|
|
172
|
+
if not respuesta.is_success:
|
|
173
|
+
raise RuntimeError(
|
|
174
|
+
f"{platform.value} returned {respuesta.status_code}: "
|
|
175
|
+
f"{mensaje_de_error(respuesta, token)}"
|
|
176
|
+
)
|
|
177
|
+
return respuesta.json()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def es_metrica_invalida(respuesta: httpx.Response) -> bool:
|
|
181
|
+
"""Identify 400 responses caused by a retired insights metric name."""
|
|
182
|
+
if respuesta.status_code != 400:
|
|
183
|
+
return False
|
|
184
|
+
try:
|
|
185
|
+
error = respuesta.json().get("error") or {}
|
|
186
|
+
except (ValueError, AttributeError):
|
|
187
|
+
return False
|
|
188
|
+
if not isinstance(error, dict):
|
|
189
|
+
return False
|
|
190
|
+
return error.get("code") == 100 and "must be a valid insights metric" in str(
|
|
191
|
+
error.get("message", "")
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def pedir_listado_con_insights(
|
|
196
|
+
client: httpx.Client,
|
|
197
|
+
url: str,
|
|
198
|
+
campos_base: str,
|
|
199
|
+
metricas: str,
|
|
200
|
+
extra: dict,
|
|
201
|
+
platform: Platform,
|
|
202
|
+
scope: str,
|
|
203
|
+
token: str,
|
|
204
|
+
) -> tuple[dict, str | None]:
|
|
205
|
+
"""Request listings with insights, falling back when Meta rejects retired metrics."""
|
|
206
|
+
params_con_insights = {
|
|
207
|
+
**extra,
|
|
208
|
+
"fields": f"{campos_base},insights.metric({metricas})",
|
|
209
|
+
"access_token": token,
|
|
210
|
+
}
|
|
211
|
+
r = client.get(url, params=params_con_insights)
|
|
212
|
+
if platform is Platform.FACEBOOK and "comments.summary(true)" in campos_base and r.status_code in (400, 403):
|
|
213
|
+
try:
|
|
214
|
+
error = r.json().get("error") or {}
|
|
215
|
+
except (ValueError, AttributeError):
|
|
216
|
+
error = {}
|
|
217
|
+
if isinstance(error, dict) and error.get("code") in (10, 200) and "pages_read_user_content" in str(error.get("message", "")):
|
|
218
|
+
# Comment counts need a separate permission; preserve authorized insights.
|
|
219
|
+
reduced_fields = ",".join(field for field in campos_base.split(",") if field != "comments.summary(true)")
|
|
220
|
+
data, other_reason = pedir_listado_con_insights(client, url, reduced_fields, metricas, extra, platform, scope, token)
|
|
221
|
+
reason = "Comment counts unavailable: pages_read_user_content permission not granted."
|
|
222
|
+
return data, reason + (" " + other_reason if other_reason else "")
|
|
223
|
+
if r.status_code == 400 and es_metrica_invalida(r):
|
|
224
|
+
motivo = mensaje_de_error(r, token)
|
|
225
|
+
params_sin_insights = {**extra, "fields": campos_base, "access_token": token}
|
|
226
|
+
r2 = client.get(url, params=params_sin_insights)
|
|
227
|
+
datos = comprobar_respuesta(r2, platform, scope, token)
|
|
228
|
+
return _seguir_paginas(client, datos, platform, scope, token), motivo
|
|
229
|
+
datos = comprobar_respuesta(r, platform, scope, token)
|
|
230
|
+
return _seguir_paginas(client, datos, platform, scope, token), None
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _seguir_paginas(
|
|
234
|
+
client: httpx.Client,
|
|
235
|
+
primera: dict,
|
|
236
|
+
platform: Platform,
|
|
237
|
+
scope: str,
|
|
238
|
+
token: str,
|
|
239
|
+
) -> dict:
|
|
240
|
+
"""Combine bounded Graph API pages into one data list; prevent unbounded quota use and warn on truncation."""
|
|
241
|
+
acumulado = list(primera.get("data") or [])
|
|
242
|
+
siguiente = (primera.get("paging") or {}).get("next")
|
|
243
|
+
paginas = 1
|
|
244
|
+
while siguiente and paginas < MAX_PAGINAS_META:
|
|
245
|
+
r = client.get(siguiente)
|
|
246
|
+
pagina = comprobar_respuesta(r, platform, scope, token)
|
|
247
|
+
acumulado.extend(pagina.get("data") or [])
|
|
248
|
+
siguiente = (pagina.get("paging") or {}).get("next")
|
|
249
|
+
paginas += 1
|
|
250
|
+
if siguiente:
|
|
251
|
+
warnings.warn(
|
|
252
|
+
f"{platform.value}: listing exceeds {MAX_PAGINAS_META} "
|
|
253
|
+
f"pages of {POR_PAGINA_META}; reading the "
|
|
254
|
+
f"{MAX_PAGINAS_META * POR_PAGINA_META} most recent posts "
|
|
255
|
+
"and older posts are excluded from this snapshot.",
|
|
256
|
+
stacklevel=3,
|
|
257
|
+
)
|
|
258
|
+
return {**primera, "data": acumulado}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def id_de_cuenta(brand: Brand, red: str, campo: str) -> str:
|
|
262
|
+
"""Return configured account ID or report exact missing field."""
|
|
263
|
+
valor = (brand.cuentas.get(red) or {}).get(campo) or ""
|
|
264
|
+
if not str(valor).strip():
|
|
265
|
+
raise RuntimeError(
|
|
266
|
+
f"brand '{brand.nombre}' has no '{red}.{campo}' configured in "
|
|
267
|
+
f"{brand.raiz / 'accounts.yml'}: fill it in before reading metrics "
|
|
268
|
+
f"for {red} (see SETUP.md)"
|
|
269
|
+
)
|
|
270
|
+
return str(valor).strip()
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def fecha_meta(texto: str) -> datetime:
|
|
274
|
+
"""Convert offset-aware Meta timestamp to naive UTC, preserving the actual instant."""
|
|
275
|
+
return (
|
|
276
|
+
datetime.strptime(texto, "%Y-%m-%dT%H:%M:%S%z")
|
|
277
|
+
.astimezone(timezone.utc)
|
|
278
|
+
.replace(tzinfo=None)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class FacebookLector(Lector):
|
|
283
|
+
platform = Platform.FACEBOOK
|
|
284
|
+
|
|
285
|
+
def leer(
|
|
286
|
+
self, brand: Brand, client: httpx.Client, desde: date | None
|
|
287
|
+
) -> LecturaRed:
|
|
288
|
+
token = obtener_token(brand, self.platform, client)
|
|
289
|
+
page_id = id_de_cuenta(brand, "facebook", "page_id")
|
|
290
|
+
|
|
291
|
+
cuenta_cruda = self._pedir(
|
|
292
|
+
client, f"{GRAFO}/{page_id}",
|
|
293
|
+
{"fields": "followers_count", "access_token": token},
|
|
294
|
+
)
|
|
295
|
+
cuenta = Cuenta(seguidores=cuenta_cruda.get("followers_count"))
|
|
296
|
+
|
|
297
|
+
# `pedir_listado_con_insights` pide primero con el bloque de
|
|
298
|
+
# insights, tal cual antes de este arreglo; si Meta ha retirado el
|
|
299
|
+
# nombre de alguna métrica pedida, reintenta sin ese bloque en vez
|
|
300
|
+
# de perder el listado de publicaciones entero (ver su docstring y
|
|
301
|
+
# `es_metrica_invalida`). `motivo_degradacion` es `None` salvo que
|
|
302
|
+
# haya hecho falta ese reintento.
|
|
303
|
+
posts, motivo_degradacion = pedir_listado_con_insights(
|
|
304
|
+
client, f"{GRAFO}/{page_id}/posts", CAMPOS_POST, METRICAS_POST,
|
|
305
|
+
{"limit": POR_PAGINA_META}, self.platform, "read_insights", token,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
piezas = []
|
|
309
|
+
for post in posts.get("data", []):
|
|
310
|
+
publicado = fecha_meta(post["created_time"])
|
|
311
|
+
if desde is not None and publicado.date() < desde:
|
|
312
|
+
continue
|
|
313
|
+
pieza = self._pieza(post, publicado, client, token)
|
|
314
|
+
if motivo_degradacion is not None:
|
|
315
|
+
# Señal de lectura parcial, no un cambio de `estado`: ver el
|
|
316
|
+
# docstring de `pedir_listado_con_insights` y el de
|
|
317
|
+
# `CLAVE_ENRIQUECIMIENTO_FALLIDO` en
|
|
318
|
+
# `socialctl/metricas/youtube.py`.
|
|
319
|
+
pieza.especificas[CLAVE_ENRIQUECIMIENTO_FALLIDO] = motivo_degradacion
|
|
320
|
+
piezas.append(pieza)
|
|
321
|
+
|
|
322
|
+
return LecturaRed(estado=EstadoLectura.OK, account_id=page_id, cuenta=cuenta, piezas=piezas)
|
|
323
|
+
|
|
324
|
+
def _pedir(self, client: httpx.Client, url: str, params: dict) -> dict:
|
|
325
|
+
# El token sale de los propios `params` porque es donde la Graph API
|
|
326
|
+
# lo exige: pasárselo a `comprobar_respuesta` es lo que permite
|
|
327
|
+
# redactarlo del mensaje de error.
|
|
328
|
+
r = client.get(url, params=params)
|
|
329
|
+
return comprobar_respuesta(
|
|
330
|
+
r, self.platform, "read_insights", str(params.get("access_token") or "")
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
def _adjunto(self, post: dict) -> dict:
|
|
334
|
+
adjuntos = (post.get("attachments") or {}).get("data") or []
|
|
335
|
+
return adjuntos[0] if adjuntos else {}
|
|
336
|
+
|
|
337
|
+
def _duracion_video(
|
|
338
|
+
self, client: httpx.Client, token: str, id_video: str
|
|
339
|
+
) -> int | None:
|
|
340
|
+
"""Read attached video duration in seconds; unavailable duration does not abort Page metrics."""
|
|
341
|
+
try:
|
|
342
|
+
datos = self._pedir(
|
|
343
|
+
client, f"{GRAFO}/{id_video}",
|
|
344
|
+
{"fields": "length", "access_token": token},
|
|
345
|
+
)
|
|
346
|
+
longitud = datos.get("length")
|
|
347
|
+
return int(longitud) if longitud is not None else None
|
|
348
|
+
except SinPermiso:
|
|
349
|
+
raise
|
|
350
|
+
except Exception: # noqa: BLE001 - la duración es opcional
|
|
351
|
+
return None
|
|
352
|
+
|
|
353
|
+
def _pieza(
|
|
354
|
+
self, post: dict, publicado: datetime, client: httpx.Client, token: str
|
|
355
|
+
) -> Pieza:
|
|
356
|
+
insights = post.get("insights", {})
|
|
357
|
+
reacciones = valor_insight(insights, "post_reactions_by_type_total")
|
|
358
|
+
|
|
359
|
+
adjunto = self._adjunto(post)
|
|
360
|
+
es_video = str(adjunto.get("media_type", "")).lower() == "video"
|
|
361
|
+
|
|
362
|
+
duracion = None
|
|
363
|
+
if es_video:
|
|
364
|
+
id_video = ((adjunto.get("target") or {}).get("id")) or ""
|
|
365
|
+
if id_video:
|
|
366
|
+
duracion = self._duracion_video(client, token, id_video)
|
|
367
|
+
|
|
368
|
+
if not es_video:
|
|
369
|
+
tipo = TipoPieza.IMAGEN
|
|
370
|
+
elif duracion is not None and duracion <= VERTICAL_HASTA_SEG:
|
|
371
|
+
tipo = TipoPieza.VERTICAL
|
|
372
|
+
else:
|
|
373
|
+
# Vídeo del que no se conoce la duración (o que la pasa): se
|
|
374
|
+
# clasifica como largo. Es una suposición, pero explícita y en un
|
|
375
|
+
# solo sitio; lo que no vale es marcar todo como imagen.
|
|
376
|
+
tipo = TipoPieza.LARGO
|
|
377
|
+
|
|
378
|
+
return Pieza(
|
|
379
|
+
id=post["id"],
|
|
380
|
+
url=post.get("permalink_url", ""),
|
|
381
|
+
titulo=(post.get("message") or "")[:120],
|
|
382
|
+
publicado_el=publicado,
|
|
383
|
+
tipo=tipo,
|
|
384
|
+
duracion_seg=duracion,
|
|
385
|
+
acumulado=Metricas(
|
|
386
|
+
# Solo un vídeo tiene vistas. El `if es_video` es explícito a
|
|
387
|
+
# propósito: en una foto la métrica no viene y `valor_insight`
|
|
388
|
+
# ya devolvería `None`, pero dicho aquí queda claro que el
|
|
389
|
+
# `None` de una foto significa "no aplica" y no "Meta no lo
|
|
390
|
+
# mandó". Cero no vale: se leería como "nadie lo vio".
|
|
391
|
+
vistas=valor_insight(insights, "post_video_views") if es_video else None,
|
|
392
|
+
# Igual de protegido que `shares` justo debajo: la Graph API
|
|
393
|
+
# puede devolver `"comments": null` explícito (no solo omitir
|
|
394
|
+
# la clave), y un `.get("comments", {})` a secas no cubre ese
|
|
395
|
+
# caso -el valor por defecto de `.get` solo se usa cuando la
|
|
396
|
+
# clave FALTA, no cuando está y vale `None`-, así que sin el
|
|
397
|
+
# `or {}` de aquí un `None` explícito reventaría con
|
|
398
|
+
# `AttributeError` al llamar a `.get("summary")` sobre él.
|
|
399
|
+
comentarios=((post.get("comments") or {}).get("summary") or {}).get(
|
|
400
|
+
"total_count"
|
|
401
|
+
),
|
|
402
|
+
compartidos=(post.get("shares") or {}).get("count"),
|
|
403
|
+
),
|
|
404
|
+
especificas={
|
|
405
|
+
# No hay `alcance`: en v26.0 Facebook no da ninguna métrica de
|
|
406
|
+
# alcance por publicación (ver `METRICAS_MUERTAS`). El hueco es
|
|
407
|
+
# deliberado; no se rellena con otra métrica parecida.
|
|
408
|
+
"reacciones": sum(reacciones.values()) if isinstance(reacciones, dict) else None,
|
|
409
|
+
# Los dos en segundos, no en los milisegundos que manda Meta.
|
|
410
|
+
"tiempo_visto_seg": segundos(
|
|
411
|
+
valor_insight(insights, "post_video_view_time") if es_video else None
|
|
412
|
+
),
|
|
413
|
+
# Retención: lo que de verdad mide "que vean el contenido".
|
|
414
|
+
"retencion_media_seg": segundos(
|
|
415
|
+
valor_insight(insights, "post_video_avg_time_watched") if es_video else None
|
|
416
|
+
),
|
|
417
|
+
},
|
|
418
|
+
)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Deterministic offline insights; absent evidence is never a zero or a promise."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections import Counter
|
|
5
|
+
from datetime import date, timedelta
|
|
6
|
+
|
|
7
|
+
from socialctl.brands import Brand
|
|
8
|
+
from socialctl.metricas.almacen import _fechas, ruta_snapshot
|
|
9
|
+
from socialctl.metricas.modelos import EstadoLectura, LecturaRed, Snapshot
|
|
10
|
+
from socialctl.models import Platform
|
|
11
|
+
from socialctl.read_reports import ReadReport
|
|
12
|
+
|
|
13
|
+
ACCOUNT_FIELDS = {'followers':'seguidores','content_count':'total_piezas','views':'total_vistas'}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _error(code, action='inspect_snapshot', **fields):
|
|
17
|
+
return {'code':code,'action':action,'retryable':False,**fields}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _load(brand, day, errors):
|
|
21
|
+
path=ruta_snapshot(brand,day)
|
|
22
|
+
if not path.exists():
|
|
23
|
+
return None
|
|
24
|
+
try:
|
|
25
|
+
snapshot=Snapshot.model_validate_json(path.read_text(encoding='utf-8'))
|
|
26
|
+
if snapshot.marca!=brand.nombre or snapshot.fecha!=day:
|
|
27
|
+
errors.append(_error('snapshot_identity_mismatch',snapshot_date=day.isoformat()))
|
|
28
|
+
return None
|
|
29
|
+
return snapshot
|
|
30
|
+
except (OSError,ValueError):
|
|
31
|
+
errors.append(_error('snapshot_unreadable',snapshot_date=day.isoformat()))
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _number(value):
|
|
36
|
+
return value if isinstance(value,int) and value>=0 else None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _comparison(current, baseline, current_day, baseline_day):
|
|
40
|
+
result={'status':'unavailable','reason':None,'from_observed_at':None,
|
|
41
|
+
'to_observed_at':current.observed_at.isoformat() if current.observed_at else None,
|
|
42
|
+
'elapsed_seconds':None}
|
|
43
|
+
if baseline is None or baseline.estado!=EstadoLectura.OK:
|
|
44
|
+
result['reason']='baseline_unavailable'
|
|
45
|
+
elif not (current.account_id or '').strip() or not (baseline.account_id or '').strip():
|
|
46
|
+
result['reason']='account_identity_unknown'
|
|
47
|
+
elif current.account_id!=baseline.account_id:
|
|
48
|
+
result['reason']='account_changed'
|
|
49
|
+
else:
|
|
50
|
+
start,end=baseline.observed_at,current.observed_at
|
|
51
|
+
result['from_observed_at']=start.isoformat() if start else None
|
|
52
|
+
if (not start or not end or start.utcoffset() is None or end.utcoffset() is None
|
|
53
|
+
or end<=start):
|
|
54
|
+
result['reason']='observation_interval_unavailable'
|
|
55
|
+
elif end.date()!=current_day or start.date()!=baseline_day:
|
|
56
|
+
# Old snapshots do not record the collector's timezone. Keep the
|
|
57
|
+
# observations, but never guess that a different date is fresh.
|
|
58
|
+
result['reason']='observation_date_mismatch'
|
|
59
|
+
else:
|
|
60
|
+
result.update(status='available',elapsed_seconds=(end-start).total_seconds())
|
|
61
|
+
return result
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _accounts(current, baseline, comparable):
|
|
65
|
+
values={}
|
|
66
|
+
for name,field in ACCOUNT_FIELDS.items():
|
|
67
|
+
end=_number(getattr(current.cuenta,field,None))
|
|
68
|
+
start=_number(getattr(baseline.cuenta,field,None)) if baseline and comparable else None
|
|
69
|
+
delta=end-start if end is not None and start is not None else None
|
|
70
|
+
values[name]={'current':end,'baseline':start,'change':delta,
|
|
71
|
+
'percent_change':round(delta/start*100,2) if delta is not None and start else None}
|
|
72
|
+
if name=='views' and delta is not None and delta<0:
|
|
73
|
+
values[name].update(change=None,percent_change=None,
|
|
74
|
+
counter_correction=True,observed_difference=delta)
|
|
75
|
+
return values
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _unique(pieces):
|
|
79
|
+
counts=Counter(piece.id for piece in pieces)
|
|
80
|
+
return {p.id:p for p in pieces if counts[p.id]==1},sorted(k for k,v in counts.items() if v>1)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _rank(current, baseline, comparable, top):
|
|
84
|
+
latest,duplicates=_unique(current.piezas)
|
|
85
|
+
previous,baseline_duplicates=_unique(baseline.piezas if baseline else [])
|
|
86
|
+
lifetime,changes,corrections=[],[],[]
|
|
87
|
+
without_baseline=0
|
|
88
|
+
unknown=0;unknown_baseline=0
|
|
89
|
+
for identifier,piece in latest.items():
|
|
90
|
+
end=_number(piece.acumulado.vistas)
|
|
91
|
+
if end is None:
|
|
92
|
+
unknown+=1
|
|
93
|
+
continue
|
|
94
|
+
item={'id':identifier,'title':piece.titulo,'url':piece.url,'value':end}
|
|
95
|
+
lifetime.append(item)
|
|
96
|
+
start=_number(previous[identifier].acumulado.vistas) if identifier in previous else None
|
|
97
|
+
if identifier in previous and start is None:
|
|
98
|
+
unknown_baseline+=1
|
|
99
|
+
if start is None:
|
|
100
|
+
without_baseline+=1
|
|
101
|
+
elif comparable:
|
|
102
|
+
delta=end-start
|
|
103
|
+
if delta<0:
|
|
104
|
+
corrections.append(identifier)
|
|
105
|
+
else:
|
|
106
|
+
changes.append({**item,'value':delta})
|
|
107
|
+
sort=lambda rows:sorted(rows,key=lambda p:(-p['value'],p['id']))[:top]
|
|
108
|
+
return {'scope':'observed_items_only','lifetime_views':sort(lifetime),
|
|
109
|
+
'view_change':sort(changes),'without_baseline':without_baseline,
|
|
110
|
+
'unknown_views':unknown,'counter_corrections':sorted(corrections),
|
|
111
|
+
'unknown_baseline_views':unknown_baseline,
|
|
112
|
+
'duplicate_ids':duplicates,'baseline_duplicate_ids':baseline_duplicates}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def build_report(brand: Brand, days: int=7, as_of: date|None=None,
|
|
116
|
+
top: int=5, only: Platform|None=None) -> ReadReport:
|
|
117
|
+
if not 1<=days<=365 or not 1<=top<=50:
|
|
118
|
+
raise ValueError('days must be 1..365 and top must be 1..50')
|
|
119
|
+
from socialctl.youtube_data import enforce_youtube_data, MAX_AGE_DAYS, YouTubeDataCleanupError
|
|
120
|
+
as_of=as_of or date.today()
|
|
121
|
+
data={'brand':brand.nombre,'requested_as_of':as_of.isoformat(),'days':days,
|
|
122
|
+
'source':'saved_snapshots','coverage_scope':'platforms_in_latest_snapshot',
|
|
123
|
+
'youtube_cache_max_days':MAX_AGE_DAYS,
|
|
124
|
+
'latest_snapshot':None,'platforms':{}}
|
|
125
|
+
try:
|
|
126
|
+
enforce_youtube_data(brand.raiz)
|
|
127
|
+
except YouTubeDataCleanupError:
|
|
128
|
+
return ReadReport(status='error',data=data,errors=[_error('local_data_cleanup_required','run_data_cleanup')])
|
|
129
|
+
errors=[]
|
|
130
|
+
dates=[day for day in _fechas(brand) if day<=as_of]
|
|
131
|
+
if not dates:
|
|
132
|
+
return ReadReport(status='error',data=data,errors=[_error('snapshots_unavailable','collect_metrics')])
|
|
133
|
+
latest_day=dates[-1]
|
|
134
|
+
data['latest_snapshot']=latest_day.isoformat()
|
|
135
|
+
latest=_load(brand,latest_day,errors)
|
|
136
|
+
if latest is None:
|
|
137
|
+
return ReadReport(status='error',data=data,errors=errors)
|
|
138
|
+
baseline_day=latest_day-timedelta(days=days)
|
|
139
|
+
previous_day=baseline_day-timedelta(days=days)
|
|
140
|
+
baseline=_load(brand,baseline_day,errors)
|
|
141
|
+
previous=_load(brand,previous_day,errors)
|
|
142
|
+
data['baseline_snapshot']=baseline_day.isoformat()
|
|
143
|
+
data['previous_baseline_snapshot']=previous_day.isoformat()
|
|
144
|
+
platforms=[only] if only else sorted(latest.redes,key=lambda p:p.value)
|
|
145
|
+
coverage=[];usable=0
|
|
146
|
+
for platform in platforms:
|
|
147
|
+
current=latest.redes.get(platform)
|
|
148
|
+
old=baseline.redes.get(platform) if baseline else None
|
|
149
|
+
before=previous.redes.get(platform) if previous else None
|
|
150
|
+
covered={'platform':platform.value,'complete':False,'stale':latest_day<as_of,
|
|
151
|
+
'source_partial':False,'state':current.estado.value if current else 'unavailable'}
|
|
152
|
+
coverage.append(covered)
|
|
153
|
+
if current is None or current.estado!=EstadoLectura.OK:
|
|
154
|
+
errors.append(_error('platform_read_unavailable','collect_metrics',platform=platform.value))
|
|
155
|
+
continue
|
|
156
|
+
usable+=1
|
|
157
|
+
comparison=_comparison(current,old,latest_day,baseline_day)
|
|
158
|
+
comparable=comparison['status']=='available'
|
|
159
|
+
accounts=_accounts(current,old,comparable)
|
|
160
|
+
rankings=_rank(current,old,comparable,top)
|
|
161
|
+
partial=bool(current.warnings or any('enriquecimiento_fallido' in p.especificas for p in current.piezas))
|
|
162
|
+
partial=partial or bool(old and (old.warnings or any('enriquecimiento_fallido' in p.especificas for p in old.piezas)))
|
|
163
|
+
covered['source_partial']=partial
|
|
164
|
+
covered['observed_at']=comparison['to_observed_at']
|
|
165
|
+
covered['temporal_provenance']=comparison['reason'] if comparison['reason'] in {
|
|
166
|
+
'observation_date_mismatch','observation_interval_unavailable'} else ('observed_interval' if comparable else 'unverified')
|
|
167
|
+
covered['complete']=(comparable and not partial and not covered['stale']
|
|
168
|
+
and not rankings['duplicate_ids'] and not rankings['baseline_duplicate_ids']
|
|
169
|
+
and not rankings['unknown_views'] and not rankings['unknown_baseline_views']
|
|
170
|
+
and not rankings['counter_corrections']
|
|
171
|
+
and not any(v.get('counter_correction') for v in accounts.values())
|
|
172
|
+
and any(v['change'] is not None for v in accounts.values()))
|
|
173
|
+
prior=_comparison(old,before,baseline_day,previous_day) if old and old.estado==EstadoLectura.OK else {'status':'unavailable','reason':'baseline_unavailable'}
|
|
174
|
+
if old and old.account_id!=current.account_id:
|
|
175
|
+
prior.update(status='unavailable',reason='account_changed')
|
|
176
|
+
prior['account']=_accounts(old,before,prior['status']=='available') if old and old.estado==EstadoLectura.OK else {}
|
|
177
|
+
data['platforms'][platform.value]={'account_id':current.account_id,'account':accounts,
|
|
178
|
+
'comparison':comparison,'previous_comparison':prior,'top_content':rankings,
|
|
179
|
+
'best_posting_time':{'status':'unavailable','reason':'audience_online_hours_not_observed'}}
|
|
180
|
+
status='error' if not usable else ('ok' if not errors and all(r['complete'] for r in coverage) else 'partial')
|
|
181
|
+
return ReadReport(status=status,data=data,coverage=coverage,errors=errors)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _plain(value):
|
|
185
|
+
return ''.join(c if c.isprintable() else ' ' for c in str(value))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def render_report(report: ReadReport) -> str:
|
|
189
|
+
data=report.data
|
|
190
|
+
lines=[f"SocialCli report — {_plain(data['brand'])}: {report.status}",
|
|
191
|
+
f"Saved observations: {data['latest_snapshot'] or 'unavailable'}; requested daily window: {data['days']} days."]
|
|
192
|
+
for platform,row in data['platforms'].items():
|
|
193
|
+
lines.append(platform)
|
|
194
|
+
for metric,value in row['account'].items():
|
|
195
|
+
current=value['current'] if value['current'] is not None else 'unknown'
|
|
196
|
+
delta=f"{value['change']:+d}" if value['change'] is not None else 'unavailable'
|
|
197
|
+
lines.append(f" {metric}: {current}; observed change: {delta}")
|
|
198
|
+
if value.get('counter_correction'):
|
|
199
|
+
lines.append(f" {metric} counter correction: {value['observed_difference']:+d}; growth unavailable")
|
|
200
|
+
comparison=row['comparison']
|
|
201
|
+
if comparison['status']=='available':
|
|
202
|
+
lines.append(f" Observed interval: {comparison['from_observed_at']} → {comparison['to_observed_at']}")
|
|
203
|
+
else:
|
|
204
|
+
lines.append(f" Comparison: {comparison['reason']}")
|
|
205
|
+
prior=row['previous_comparison']
|
|
206
|
+
if prior['status']=='available':
|
|
207
|
+
lines.append(f" Previous observed interval: {prior['from_observed_at']} → {prior['to_observed_at']}")
|
|
208
|
+
for metric,value in prior['account'].items():
|
|
209
|
+
delta=f"{value['change']:+d}" if value['change'] is not None else 'unavailable'
|
|
210
|
+
lines.append(f" {metric} observed change: {delta}")
|
|
211
|
+
else:
|
|
212
|
+
lines.append(f" Previous comparison: {prior['reason']}")
|
|
213
|
+
for name,label in [('view_change','Top observed view changes'),('lifetime_views','Top observed lifetime views')]:
|
|
214
|
+
lines.append(f" {label}:")
|
|
215
|
+
for item in row['top_content'][name]:
|
|
216
|
+
lines.append(f" {item['value']} — {_plain(item['title'])} — {_plain(item['url'])}")
|
|
217
|
+
ranking=row['top_content']
|
|
218
|
+
lines.append(f" Content coverage: without baseline: {ranking['without_baseline']}; unknown views: {ranking['unknown_views']}; unknown baseline views: {ranking['unknown_baseline_views']}; counter corrections: {len(ranking['counter_corrections'])}; ambiguous IDs: {len(ranking['duplicate_ids'])+len(ranking['baseline_duplicate_ids'])}")
|
|
219
|
+
lines.append(' Best posting time: unavailable; audience online hours were not observed.')
|
|
220
|
+
for covered in report.coverage:
|
|
221
|
+
if not covered['complete']:
|
|
222
|
+
lines.append(f"Coverage {covered['platform']}: incomplete; stale={covered['stale']}, source_partial={covered['source_partial']}")
|
|
223
|
+
for error in report.errors:
|
|
224
|
+
lines.append(f"{error['code']}: {error['action']}")
|
|
225
|
+
lines.append(f"YouTube API cache expires after {data.get('youtube_cache_max_days', 6)} days; older comparisons may be unavailable.")
|
|
226
|
+
lines.append('Rankings cover observed content only. Missing data is not zero; platforms are not combined.')
|
|
227
|
+
return '\n'.join(lines)
|