914 lines
41 KiB
Python
914 lines
41 KiB
Python
"""
|
||
The ``meta`` tool group: a guest's own Meta Business — their ad account's
|
||
insights, their Instagram account and their Facebook Page — **read-only**,
|
||
with the key they connect kept on the hub.
|
||
|
||
Gabriel's picks (form ``meta-business-read-only-for-cel_qbacrq``, 2026-11-25,
|
||
after Cel asked to stop exporting CALAMITE's numbers by hand):
|
||
|
||
* **The key** is a **system-user token** the guest makes in their own Meta
|
||
business portfolio (an Employee system user, their ad account / Page /
|
||
Instagram account assigned with view-only rights, expiry *Never*) and
|
||
pastes on their own page (Settings → Meta Business, ``metaroutes.py``).
|
||
It never leaves the hub: their runs and computers call the proxy with
|
||
their run token, the proxy calls Meta.
|
||
* **Read-only, three times over**: the token is refused at connect when it
|
||
carries any permission outside :data:`READ_SCOPES` (``ads_management``,
|
||
``business_management``, anything that publishes or messages); the proxy
|
||
only ever sends ``GET`` to an allowlist of Graph paths (:func:`path_ok`),
|
||
with Graph's ``method=`` override and the batch API out of reach; and Meta
|
||
itself holds the system user to view-only rights on each asset.
|
||
* **Who** — the group is off by default (Settings → Users → <guest> →
|
||
Access → Paid tools). The guest's own runs use their connection; the
|
||
owner's runs may use any guest's (``as``, or the only one there is).
|
||
* **Data** — ad insights (day × ad × age × gender, with the ad set), the
|
||
Instagram account per day (followers, reach, views, profile visits, link
|
||
taps, interactions, follows / unfollows), each post or reel's insights,
|
||
the follower audience, and the Page per day.
|
||
* **A free daily snapshot** (``snapshots.py``): Instagram only answers the
|
||
last 30 days of followers, and an ad's numbers keep moving for a week (its
|
||
attribution window), so every morning the hub saves the last 7 days again
|
||
— one file per day under ``META_SNAPSHOT_DIR/<uid>/`` — and the runs read
|
||
them back with ``history``.
|
||
|
||
Free, counted in the tool ledger (``units.calls`` = Graph calls).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import datetime as dt
|
||
import json
|
||
import logging
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import threading
|
||
import time
|
||
from zoneinfo import ZoneInfo
|
||
|
||
import httpx
|
||
|
||
log = logging.getLogger("toolproxy.meta")
|
||
|
||
GRAPH_URL = (os.environ.get("META_GRAPH_URL") or "https://graph.facebook.com").rstrip("/")
|
||
GRAPH_VERSION = os.environ.get("META_GRAPH_VERSION") or "v27.0"
|
||
PATH = pathlib.Path(os.environ.get("TOOLS_META_PATH", "/data/tools-meta.json"))
|
||
SNAP_DIR = pathlib.Path(os.environ.get("META_SNAPSHOT_DIR", "/data/meta-snapshots"))
|
||
TZ = ZoneInfo(os.environ.get("META_TZ", "Europe/Paris"))
|
||
|
||
# What the guest is told to tick when they make the token.
|
||
SCOPES_ASKED = ("ads_read", "read_insights", "pages_show_list", "pages_read_engagement",
|
||
"instagram_basic", "instagram_manage_insights")
|
||
# Every permission a connected token may carry: reading only. Anything else
|
||
# (ads_management, business_management, pages_manage_*, *_publish,
|
||
# *_messaging, catalog_management…) and the key is refused.
|
||
READ_SCOPES = frozenset(SCOPES_ASKED) | {
|
||
"public_profile", "pages_read_user_content", "read_audience_network_insights",
|
||
"instagram_business_basic", "instagram_business_manage_insights", "attribution_read",
|
||
}
|
||
# What each kind of data needs (a token without them still connects; the
|
||
# page says what it won't see).
|
||
NEEDS = {"ads": ("ads_read",),
|
||
"instagram": ("instagram_basic", "instagram_manage_insights", "pages_show_list"),
|
||
"page": ("read_insights", "pages_read_engagement", "pages_show_list")}
|
||
|
||
MAX_PAGES = 40 # pages of a Graph listing followed for ``all``
|
||
MAX_ROWS = 20_000
|
||
MAX_DAYS = 92 # one ``days`` call
|
||
MAX_HISTORY_DAYS = 400 # one ``history`` read
|
||
IG_FOLLOWER_DAYS = 30 # Instagram's follower_count goes back that far, no more
|
||
REFRESH_DAYS = 7 # the snapshot saves the last week again (ad attribution)
|
||
|
||
ADS_FIELDS = ("campaign_id,campaign_name,adset_id,adset_name,ad_id,ad_name,spend,impressions,"
|
||
"reach,frequency,clicks,inline_link_clicks,cpm,ctr,actions,cost_per_action_type,"
|
||
"video_play_actions,video_thruplay_watched_actions,video_p25_watched_actions,"
|
||
"video_p50_watched_actions,video_p75_watched_actions,video_p100_watched_actions,"
|
||
"video_avg_time_watched_actions")
|
||
ADS_FIELDS_MIN = ("campaign_id,campaign_name,adset_id,adset_name,ad_id,ad_name,spend,"
|
||
"impressions,reach,clicks,inline_link_clicks,actions")
|
||
# Instagram account, one value per day (``metric_type=total_value``).
|
||
IG_DAY_METRICS = ("views", "reach", "accounts_engaged", "total_interactions", "likes",
|
||
"comments", "shares", "saves", "replies", "profile_links_taps",
|
||
"website_clicks", "profile_views")
|
||
# Facebook Page, per day (Meta retired a batch of these in 2025: each one that
|
||
# answers "invalid metric" is dropped for the rest of the process).
|
||
PAGE_DAY_METRICS = ("page_follows", "page_daily_follows_unique", "page_daily_unfollows_unique",
|
||
"page_media_view", "page_total_media_view_unique", "page_post_engagements",
|
||
"page_impressions_unique", "page_views_total")
|
||
MEDIA_METRICS = {
|
||
"REELS": ("reach", "views", "likes", "comments", "shares", "saved", "total_interactions",
|
||
"ig_reels_avg_watch_time", "ig_reels_video_view_total_time"),
|
||
"FEED": ("reach", "views", "likes", "comments", "shares", "saved", "total_interactions",
|
||
"profile_visits", "follows"),
|
||
"STORY": ("reach", "views", "replies", "shares", "total_interactions"),
|
||
}
|
||
MEDIA_FIELDS = ("id,caption,media_type,media_product_type,permalink,timestamp,like_count,"
|
||
"comments_count")
|
||
|
||
# Metrics Meta refused here, by (where, metric) — skipped until the next start.
|
||
_BAD: set[tuple[str, str]] = set()
|
||
|
||
_ID = r"\d{1,25}"
|
||
_PATHS = [re.compile(p) for p in (
|
||
r"^me$", r"^me/(adaccounts|accounts|permissions)$",
|
||
rf"^act_{_ID}(/(insights|campaigns|adsets|ads|adcreatives))?$",
|
||
rf"^{_ID}(/(insights|media|stories|children|comments|published_posts|posts|video_reels"
|
||
r"|ads|adsets|adcreatives))?$",
|
||
rf"^{_ID}_{_ID}(/(insights|comments))?$",
|
||
)]
|
||
# Graph parameters a caller never sets: the key, its proof, Graph's own
|
||
# method override (``?method=post`` turns a GET into a write) and the rest of
|
||
# its request plumbing.
|
||
_FORBIDDEN = {"access_token", "appsecret_proof", "appsecret_time", "method", "batch",
|
||
"callback", "jsonp", "suppress_http_code", "transport", "include_headers",
|
||
"debug", "_method", "redirect", "pretty"}
|
||
_PARAM_RE = re.compile(r"^[a-z][a-z0-9_]{0,40}$")
|
||
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||
_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
|
||
_TOKEN_RE = re.compile(r"(access_token=)[^&\s\"']+")
|
||
|
||
|
||
# Errors that stop a whole call (the others drop one metric and go on).
|
||
FATAL = ("meta-token", "meta-rate", "upstream")
|
||
|
||
|
||
class MetaError(Exception):
|
||
def __init__(self, status: int, message: str, kind: str = "meta", code: int | None = None):
|
||
super().__init__(message)
|
||
self.status, self.message, self.kind, self.code = status, message, kind, code
|
||
|
||
|
||
def graph_error(err: dict, http_status: int = 400) -> MetaError:
|
||
"""A Graph ``{"error": …}`` in our words: a dead key, a rate limit, a
|
||
missing permission, a bad request — or Meta's own trouble."""
|
||
code = err.get("code")
|
||
sub = err.get("error_subcode")
|
||
msg = str(err.get("error_user_msg") or err.get("message") or "Meta refused the call")[:400]
|
||
if code == 190 or code in (102, 2500) and "token" in msg.lower():
|
||
return MetaError(403, f"the Meta key no longer works ({msg}) — reconnect it in "
|
||
"Settings → Meta Business", "meta-token", code)
|
||
if code in (4, 17, 32, 613) or (isinstance(code, int) and 80000 <= code <= 80014):
|
||
return MetaError(429, f"Meta's rate limit: {msg} — try again in a few minutes",
|
||
"meta-rate", code)
|
||
if code == 10 or (isinstance(code, int) and 200 <= code <= 299):
|
||
return MetaError(403, f"the Meta key may not read this: {msg}", "meta-permission", code)
|
||
if sub == 1504018 or "reduce the amount of data" in msg.lower():
|
||
return MetaError(400, f"{msg} — ask for fewer days or fewer breakdowns", "meta-size", code)
|
||
if http_status >= 500 or code in (1, 2):
|
||
return MetaError(502, f"Meta is having trouble: {msg}", "upstream", code)
|
||
return MetaError(400, f"Meta: {msg}", "meta", code)
|
||
|
||
|
||
# ── scrubbing what Meta answers ──────────────────────────────────────────────
|
||
def scrub(obj, secrets: tuple[str, ...] = ()):
|
||
"""Meta's answer without a key in it: ``access_token`` fields (a Page's
|
||
own token in ``me/accounts``) dropped, ``paging.next`` / ``previous`` (full
|
||
URLs carrying the key) replaced by ``more``, and any key string that is
|
||
left masked."""
|
||
if isinstance(obj, dict):
|
||
out = {}
|
||
for k, v in obj.items():
|
||
if k == "access_token":
|
||
continue
|
||
if k == "paging" and isinstance(v, dict):
|
||
p = {kk: scrub(vv, secrets) for kk, vv in v.items() if kk not in ("next", "previous")}
|
||
p["more"] = bool(v.get("next"))
|
||
out[k] = p
|
||
continue
|
||
out[k] = scrub(v, secrets)
|
||
return out
|
||
if isinstance(obj, list):
|
||
return [scrub(v, secrets) for v in obj]
|
||
if isinstance(obj, str):
|
||
s = obj
|
||
for sec in secrets:
|
||
if sec and sec in s:
|
||
s = s.replace(sec, "***")
|
||
return _TOKEN_RE.sub(r"\1***", s) if "access_token=" in s else s
|
||
return obj
|
||
|
||
|
||
def path_ok(path: str) -> bool:
|
||
return any(p.match(path or "") for p in _PATHS)
|
||
|
||
|
||
def clean_params(raw) -> dict:
|
||
"""A caller's Graph parameters, as strings — the key, ``method`` and
|
||
Graph's plumbing refused."""
|
||
if raw is None:
|
||
return {}
|
||
if not isinstance(raw, dict):
|
||
raise MetaError(400, "params must be an object", "body")
|
||
if len(raw) > 30:
|
||
raise MetaError(400, "at most 30 params", "body")
|
||
out = {}
|
||
for k, v in raw.items():
|
||
k = str(k)
|
||
if k.lower() in _FORBIDDEN or not _PARAM_RE.match(k):
|
||
raise MetaError(400, f"the parameter {k!r} isn't allowed here", "param")
|
||
if isinstance(v, bool):
|
||
v = "true" if v else "false"
|
||
elif isinstance(v, (dict, list)):
|
||
v = json.dumps(v, separators=(",", ":"))
|
||
elif v is None:
|
||
continue
|
||
v = str(v)
|
||
if len(v) > 4000:
|
||
raise MetaError(400, f"the parameter {k!r} is too long", "param")
|
||
out[k] = v
|
||
return out
|
||
|
||
|
||
# ── the store: each guest's connection ───────────────────────────────────────
|
||
class Store:
|
||
"""``{uid: {token, pageTokens, user, scopes, adAccounts, pages, instagram,
|
||
connectedAt, checkedAt, error, snapshot}}`` in one 0600 file."""
|
||
|
||
def __init__(self, path: pathlib.Path = PATH):
|
||
self.path = pathlib.Path(path)
|
||
self._lock = threading.Lock()
|
||
|
||
def _read(self) -> dict:
|
||
try:
|
||
d = json.loads(self.path.read_text())
|
||
return d if isinstance(d, dict) else {}
|
||
except (OSError, ValueError):
|
||
return {}
|
||
|
||
def _write(self, d: dict) -> None:
|
||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||
tmp = self.path.with_suffix(".tmp")
|
||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
with os.fdopen(fd, "w") as f:
|
||
json.dump(d, f)
|
||
os.replace(tmp, self.path)
|
||
|
||
def get(self, uid: str) -> dict:
|
||
with self._lock:
|
||
return dict(self._read().get(uid) or {})
|
||
|
||
def uids(self) -> list[str]:
|
||
with self._lock:
|
||
return [u for u, r in self._read().items() if isinstance(r, dict) and r.get("token")]
|
||
|
||
def put(self, uid: str, rec: dict) -> None:
|
||
with self._lock:
|
||
d = self._read()
|
||
d[uid] = rec
|
||
self._write(d)
|
||
|
||
def update(self, uid: str, patch: dict) -> dict:
|
||
with self._lock:
|
||
d = self._read()
|
||
rec = dict(d.get(uid) or {})
|
||
if not rec.get("token"):
|
||
return rec
|
||
rec.update(patch)
|
||
d[uid] = rec
|
||
self._write(d)
|
||
return rec
|
||
|
||
def drop(self, uid: str) -> bool:
|
||
with self._lock:
|
||
d = self._read()
|
||
if uid not in d:
|
||
return False
|
||
d.pop(uid)
|
||
self._write(d)
|
||
return True
|
||
|
||
|
||
STORE = Store()
|
||
|
||
|
||
def _now_iso() -> str:
|
||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||
|
||
|
||
def public(rec: dict) -> dict:
|
||
"""A connection as the pages and the runs see it: never a key."""
|
||
if not rec or not rec.get("token"):
|
||
return {"connected": False}
|
||
scopes = list(rec.get("scopes") or [])
|
||
return {
|
||
"connected": True,
|
||
"user": rec.get("user") or {},
|
||
"scopes": scopes,
|
||
"missing": [s for s in SCOPES_ASKED if s not in scopes],
|
||
"sees": {k: all(s in scopes for s in need) for k, need in NEEDS.items()},
|
||
"adAccounts": rec.get("adAccounts") or [],
|
||
"pages": rec.get("pages") or [],
|
||
"instagram": rec.get("instagram") or [],
|
||
"connectedAt": rec.get("connectedAt"),
|
||
"checkedAt": rec.get("checkedAt"),
|
||
"error": rec.get("error"),
|
||
"snapshot": rec.get("snapshot") or {},
|
||
"expiresAt": rec.get("expiresAt"),
|
||
}
|
||
|
||
|
||
# ── talking to Meta ──────────────────────────────────────────────────────────
|
||
class Graph:
|
||
"""GETs on the Graph API with one connection's key (a Page's own key for
|
||
that Page's paths). Counts its calls for the ledger."""
|
||
|
||
def __init__(self, client: httpx.AsyncClient, rec: dict):
|
||
self.client = client
|
||
self.token = rec.get("token") or ""
|
||
self.page_tokens = dict(rec.get("pageTokens") or {})
|
||
self.calls = 0
|
||
|
||
def secrets(self) -> tuple[str, ...]:
|
||
return (self.token, *self.page_tokens.values())
|
||
|
||
def _token_for(self, path: str) -> str:
|
||
head = path.split("/", 1)[0].split("_", 1)[0]
|
||
return self.page_tokens.get(head) or self.token
|
||
|
||
async def get(self, path: str, params: dict | None = None, *, token: str | None = None) -> dict:
|
||
q = {**(params or {}), "access_token": token or self._token_for(path)}
|
||
self.calls += 1
|
||
try:
|
||
r = await self.client.get(f"{GRAPH_URL}/{GRAPH_VERSION}/{path}", params=q,
|
||
timeout=httpx.Timeout(20.0, read=90.0))
|
||
except httpx.HTTPError as e:
|
||
raise MetaError(502, f"Meta is unreachable ({type(e).__name__})", "upstream")
|
||
try:
|
||
out = r.json()
|
||
except ValueError:
|
||
raise MetaError(502, f"Meta answered {r.status_code} without JSON", "upstream")
|
||
if isinstance(out, dict) and isinstance(out.get("error"), dict):
|
||
raise graph_error(out["error"], r.status_code)
|
||
if r.status_code >= 400:
|
||
raise MetaError(502, f"Meta answered {r.status_code}", "upstream")
|
||
return out if isinstance(out, dict) else {"data": out}
|
||
|
||
async def all(self, path: str, params: dict | None = None, *,
|
||
max_pages: int = MAX_PAGES, max_rows: int = MAX_ROWS) -> dict:
|
||
"""Every page of a listing (``data``) merged, up to the caps."""
|
||
p = dict(params or {})
|
||
rows: list = []
|
||
out: dict = {}
|
||
for _ in range(max_pages):
|
||
out = await self.get(path, p)
|
||
rows += list(out.get("data") or [])
|
||
paging = out.get("paging") or {}
|
||
after = (paging.get("cursors") or {}).get("after")
|
||
if not paging.get("next") or not after or len(rows) >= max_rows:
|
||
break
|
||
p["after"] = after
|
||
more = bool((out.get("paging") or {}).get("next"))
|
||
return {"data": rows[:max_rows], "paging": {"more": more or len(rows) > max_rows}}
|
||
|
||
|
||
async def inspect(client: httpx.AsyncClient, token: str) -> dict:
|
||
"""Check a key and find what it reaches. Raises ``MetaError`` for a key
|
||
that doesn't work or may write; returns the record's fields."""
|
||
token = (token or "").strip()
|
||
if not re.match(r"^[A-Za-z0-9_\-|.]{40,1024}$", token):
|
||
raise MetaError(400, "that doesn't look like a Meta access token — copy the whole "
|
||
"key Meta showed (it starts with EAA)", "token-format")
|
||
g = Graph(client, {"token": token})
|
||
me = await g.get("me", {"fields": "id,name"})
|
||
scopes: list[str] = []
|
||
try:
|
||
perms = await g.get("me/permissions")
|
||
scopes = sorted({p.get("permission") for p in perms.get("data") or []
|
||
if p.get("status") == "granted" and p.get("permission")})
|
||
except MetaError:
|
||
scopes = []
|
||
expires = None
|
||
if not scopes:
|
||
# A system user's token may not list /me/permissions: ask debug_token.
|
||
try:
|
||
d = (await g.get("debug_token", {"input_token": token})).get("data") or {}
|
||
scopes = sorted(set(d.get("scopes") or []))
|
||
expires = d.get("expires_at") or None
|
||
except MetaError:
|
||
pass
|
||
if not scopes:
|
||
raise MetaError(400, "Meta didn't say what this key may do — make a new one with the "
|
||
f"permissions {', '.join(SCOPES_ASKED)}", "scopes")
|
||
extra = [s for s in scopes if s not in READ_SCOPES]
|
||
if extra:
|
||
raise MetaError(400, "this key can do more than read (" + ", ".join(extra) + "). Make a "
|
||
"new one with only: " + ", ".join(SCOPES_ASKED), "scopes")
|
||
ads: list[dict] = []
|
||
if "ads_read" in scopes:
|
||
try:
|
||
got = await g.all("me/adaccounts", {"fields": "id,account_id,name,currency,"
|
||
"timezone_name,account_status",
|
||
"limit": "100"}, max_pages=5)
|
||
ads = [{"id": a.get("id"), "name": a.get("name") or a.get("account_id"),
|
||
"currency": a.get("currency"), "timezone": a.get("timezone_name"),
|
||
"status": a.get("account_status")}
|
||
for a in got["data"] if str(a.get("id") or "").startswith("act_")]
|
||
except MetaError as e:
|
||
if e.kind == "meta-token":
|
||
raise
|
||
pages: list[dict] = []
|
||
page_tokens: dict[str, str] = {}
|
||
instagram: list[dict] = []
|
||
if "pages_show_list" in scopes:
|
||
try:
|
||
got = await g.all("me/accounts", {
|
||
"fields": "id,name,access_token,instagram_business_account"
|
||
"{id,username,name,followers_count}", "limit": "100"}, max_pages=5)
|
||
for p in got["data"]:
|
||
pid = str(p.get("id") or "")
|
||
if not pid.isdigit():
|
||
continue
|
||
pages.append({"id": pid, "name": p.get("name") or pid})
|
||
if p.get("access_token"):
|
||
page_tokens[pid] = p["access_token"]
|
||
ig = p.get("instagram_business_account") or {}
|
||
if str(ig.get("id") or "").isdigit():
|
||
instagram.append({"id": str(ig["id"]), "username": ig.get("username") or "",
|
||
"followers": ig.get("followers_count"), "page": pid})
|
||
except MetaError as e:
|
||
if e.kind == "meta-token":
|
||
raise
|
||
if not (ads or pages or instagram):
|
||
raise MetaError(400, "the key works, but it reaches no ad account, Page or Instagram "
|
||
"account — assign them to the system user (Business settings → "
|
||
"System users → Assign assets), then make the key again",
|
||
"no-assets")
|
||
return {"token": token, "pageTokens": page_tokens,
|
||
"user": {"id": str(me.get("id") or ""), "name": me.get("name") or ""},
|
||
"scopes": scopes, "adAccounts": ads, "pages": pages, "instagram": instagram,
|
||
"expiresAt": expires, "checkedAt": _now_iso(), "error": None}
|
||
|
||
|
||
# ── days ─────────────────────────────────────────────────────────────────────
|
||
def _date(s: str, what: str) -> dt.date:
|
||
if not isinstance(s, str) or not _DATE_RE.match(s):
|
||
raise MetaError(400, f"{what} must be a date YYYY-MM-DD", "body")
|
||
try:
|
||
return dt.date.fromisoformat(s)
|
||
except ValueError:
|
||
raise MetaError(400, f"{what} isn't a real date", "body")
|
||
|
||
|
||
def today() -> dt.date:
|
||
return dt.datetime.now(TZ).date()
|
||
|
||
|
||
def date_range(body: dict, *, default_days: int = 7, cap: int = MAX_DAYS) -> tuple[dt.date, dt.date]:
|
||
"""``since`` / ``until`` (inclusive) — by default the last ``default_days``
|
||
full days; never today or later (a day Meta hasn't finished)."""
|
||
yesterday = today() - dt.timedelta(days=1)
|
||
until = _date(body["until"], "until") if body.get("until") else yesterday
|
||
since = (_date(body["since"], "since") if body.get("since")
|
||
else until - dt.timedelta(days=default_days - 1))
|
||
until = min(until, yesterday)
|
||
if since > until:
|
||
raise MetaError(400, f"since must be on or before until (and Meta's last full day is "
|
||
f"{yesterday})", "body")
|
||
if (until - since).days + 1 > cap:
|
||
raise MetaError(400, f"at most {cap} days at once", "body")
|
||
return since, until
|
||
|
||
|
||
def _days(since: dt.date, until: dt.date) -> list[dt.date]:
|
||
return [since + dt.timedelta(days=i) for i in range((until - since).days + 1)]
|
||
|
||
|
||
def _unix(d: dt.date) -> int:
|
||
return int(dt.datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp())
|
||
|
||
|
||
def _end_day(end_time: str) -> str | None:
|
||
"""Meta's daily ``end_time`` (the end of the day it counts) → that day."""
|
||
try:
|
||
t = dt.datetime.fromisoformat(str(end_time).replace("+0000", "+00:00"))
|
||
except ValueError:
|
||
return None
|
||
return (t - dt.timedelta(days=1)).date().isoformat()
|
||
|
||
|
||
def _pick(rec: dict, key: str, want: str | None) -> list[dict]:
|
||
items = list(rec.get(key) or [])
|
||
if want:
|
||
items = [i for i in items if i.get("id") == want or i.get("username") == want]
|
||
if not items:
|
||
raise MetaError(404, f"{want!r} isn't one of this connection's {key}", "asset")
|
||
return items
|
||
|
||
|
||
async def _ads_days(g: Graph, acct: str, since: dt.date, until: dt.date,
|
||
errors: list) -> dict[str, list]:
|
||
params = {"level": "ad", "time_increment": "1", "breakdowns": "age,gender",
|
||
"time_range": json.dumps({"since": since.isoformat(), "until": until.isoformat()}),
|
||
"limit": "500", "fields": ADS_FIELDS}
|
||
try:
|
||
got = await g.all(f"{acct}/insights", params)
|
||
except MetaError as e:
|
||
if e.kind != "meta": # a bad field name: try again with the core ones
|
||
raise
|
||
params["fields"] = ADS_FIELDS_MIN
|
||
errors.append({"part": "ads", "account": acct, "message": f"{e.message} (fewer fields)"})
|
||
got = await g.all(f"{acct}/insights", params)
|
||
out: dict[str, list] = {}
|
||
for row in got["data"]:
|
||
day = row.pop("date_start", None)
|
||
row.pop("date_stop", None)
|
||
if day:
|
||
out.setdefault(day, []).append(row)
|
||
if got["paging"].get("more"):
|
||
errors.append({"part": "ads", "account": acct,
|
||
"message": f"cut at {MAX_ROWS} rows — ask for fewer days"})
|
||
return out
|
||
|
||
|
||
async def _metrics(g: Graph, where: str, path: str, metrics: tuple, params: dict,
|
||
errors: list, part: str) -> list[dict]:
|
||
"""``path/insights`` for these metrics: all at once, or one by one when
|
||
one of them is refused (and that one is skipped from then on)."""
|
||
want = [m for m in metrics if (where, m) not in _BAD]
|
||
if not want:
|
||
return []
|
||
try:
|
||
return list((await g.get(path, {**params, "metric": ",".join(want)})).get("data") or [])
|
||
except MetaError as e:
|
||
# Only "invalid metric" drops a metric; a missing permission, a
|
||
# dead key or a rate limit stops the part (``days`` notes it).
|
||
if e.kind != "meta":
|
||
raise
|
||
if len(want) == 1:
|
||
_BAD.add((where, want[0]))
|
||
errors.append({"part": part, "metric": want[0], "message": e.message})
|
||
return []
|
||
data: list[dict] = []
|
||
for m in want:
|
||
try:
|
||
data += list((await g.get(path, {**params, "metric": m})).get("data") or [])
|
||
except MetaError as e:
|
||
if e.kind != "meta":
|
||
raise
|
||
_BAD.add((where, m))
|
||
errors.append({"part": part, "metric": m, "message": e.message})
|
||
return data
|
||
|
||
|
||
async def _ig_days(g: Graph, ig: str, since: dt.date, until: dt.date,
|
||
errors: list) -> dict[str, dict]:
|
||
out: dict[str, dict] = {d.isoformat(): {} for d in _days(since, until)}
|
||
# follower_count: a series, the last 30 days only (not today).
|
||
floor = today() - dt.timedelta(days=IG_FOLLOWER_DAYS)
|
||
fs = max(since, floor)
|
||
if fs <= until:
|
||
rows = await _metrics(g, "ig-series", f"{ig}/insights", ("follower_count",),
|
||
{"period": "day", "since": str(_unix(fs)),
|
||
"until": str(_unix(until + dt.timedelta(days=1)))},
|
||
errors, "instagram")
|
||
for m in rows:
|
||
for v in m.get("values") or []:
|
||
day = _end_day(v.get("end_time"))
|
||
if day in out:
|
||
out[day][m.get("name") or "follower_count"] = v.get("value")
|
||
for d in _days(since, until):
|
||
day = d.isoformat()
|
||
window = {"period": "day", "metric_type": "total_value", "since": str(_unix(d)),
|
||
"until": str(_unix(d + dt.timedelta(days=1)))}
|
||
for m in await _metrics(g, "ig-day", f"{ig}/insights", IG_DAY_METRICS, window,
|
||
errors, "instagram"):
|
||
out[day][m.get("name")] = (m.get("total_value") or {}).get("value")
|
||
for m in await _metrics(g, "ig-follows", f"{ig}/insights", ("follows_and_unfollows",),
|
||
{**window, "breakdown": "follow_type"}, errors, "instagram"):
|
||
for b in (m.get("total_value") or {}).get("breakdowns") or []:
|
||
for r in b.get("results") or []:
|
||
kind = (r.get("dimension_values") or [""])[0]
|
||
if kind == "FOLLOWER":
|
||
out[day]["follows"] = r.get("value")
|
||
elif kind == "NON_FOLLOWER":
|
||
out[day]["unfollows"] = r.get("value")
|
||
return out
|
||
|
||
|
||
async def _page_days(g: Graph, page: str, since: dt.date, until: dt.date,
|
||
errors: list) -> dict[str, dict]:
|
||
out: dict[str, dict] = {d.isoformat(): {} for d in _days(since, until)}
|
||
rows = await _metrics(g, "page", f"{page}/insights", PAGE_DAY_METRICS,
|
||
{"period": "day", "since": since.isoformat(),
|
||
"until": (until + dt.timedelta(days=1)).isoformat()},
|
||
errors, "page")
|
||
for m in rows:
|
||
for v in m.get("values") or []:
|
||
day = _end_day(v.get("end_time"))
|
||
if day in out:
|
||
out[day][m.get("name")] = v.get("value")
|
||
return out
|
||
|
||
|
||
PARTS = ("ads", "instagram", "page")
|
||
# A stored day also holds that morning's media and audience.
|
||
HISTORY_PARTS = PARTS + ("media", "audience")
|
||
|
||
|
||
def _parts(body: dict, allowed: tuple[str, ...] = PARTS) -> tuple[str, ...]:
|
||
raw = body.get("parts")
|
||
if not raw:
|
||
return allowed
|
||
raw = raw.split(",") if isinstance(raw, str) else raw
|
||
if not isinstance(raw, (list, tuple)):
|
||
raise MetaError(400, f"parts: any of {', '.join(allowed)}", "body")
|
||
parts = tuple(p for p in allowed if p in {str(x).strip() for x in raw})
|
||
if not parts:
|
||
raise MetaError(400, f"parts: any of {', '.join(allowed)}", "body")
|
||
return parts
|
||
|
||
|
||
def _int(v, default: int, lo: int, hi: int) -> int:
|
||
try:
|
||
return max(lo, min(hi, int(v)))
|
||
except (TypeError, ValueError):
|
||
return default
|
||
|
||
|
||
async def days(g: Graph, rec: dict, since: dt.date, until: dt.date,
|
||
parts: tuple[str, ...] = PARTS, *, account: str | None = None,
|
||
instagram: str | None = None, page: str | None = None) -> dict:
|
||
"""``{days: {date: {ads: {act: [rows]}, instagram: {ig: {...}}, page: {pid:
|
||
{...}}}}, errors: [...]}`` — the per-day numbers, live from Meta."""
|
||
errors: list = []
|
||
by_day: dict[str, dict] = {d.isoformat(): {} for d in _days(since, until)}
|
||
sees = public(rec)["sees"]
|
||
|
||
def put(part: str, asset: str, per_day: dict) -> None:
|
||
for day, v in per_day.items():
|
||
if day in by_day:
|
||
by_day[day].setdefault(part, {})[asset] = v
|
||
|
||
async def part(name: str, asset: str, job) -> None:
|
||
try:
|
||
put(name, asset, await job)
|
||
except MetaError as e:
|
||
if e.kind in ("meta-token", "meta-rate"):
|
||
raise
|
||
errors.append({"part": name, "asset": asset, "message": e.message})
|
||
|
||
if "ads" in parts and sees["ads"]:
|
||
for a in _pick(rec, "adAccounts", account):
|
||
async def ads_job(acct=a["id"]):
|
||
rows = await _ads_days(g, acct, since, until, errors)
|
||
return {d: rows.get(d, []) for d in by_day}
|
||
await part("ads", a["id"], ads_job())
|
||
if "instagram" in parts and sees["instagram"]:
|
||
for ig in _pick(rec, "instagram", instagram):
|
||
await part("instagram", ig["id"], _ig_days(g, ig["id"], since, until, errors))
|
||
if "page" in parts and sees["page"]:
|
||
for p in _pick(rec, "pages", page):
|
||
await part("page", p["id"], _page_days(g, p["id"], since, until, errors))
|
||
return {"since": since.isoformat(), "until": until.isoformat(), "days": by_day,
|
||
"errors": errors}
|
||
|
||
|
||
async def media(g: Graph, rec: dict, *, since: dt.date | None = None, limit: int = 30,
|
||
instagram: str | None = None) -> dict:
|
||
"""Each recent post / reel with its insights so far (cumulative)."""
|
||
since = since or (today() - dt.timedelta(days=30))
|
||
floor = dt.datetime(since.year, since.month, since.day, tzinfo=TZ)
|
||
errors: list = []
|
||
out: dict[str, list] = {}
|
||
for ig in _pick(rec, "instagram", instagram):
|
||
got = await g.all(f"{ig['id']}/media", {"fields": MEDIA_FIELDS, "limit": "50"},
|
||
max_pages=4, max_rows=200)
|
||
items = []
|
||
for m in got["data"]:
|
||
try:
|
||
ts = dt.datetime.fromisoformat(str(m.get("timestamp")).replace("+0000", "+00:00"))
|
||
except ValueError:
|
||
continue
|
||
if ts >= floor:
|
||
items.append(m)
|
||
items = items[:_int(limit, 30, 1, 100)]
|
||
sem = asyncio.Semaphore(4)
|
||
|
||
async def one(m: dict) -> None:
|
||
kind = m.get("media_product_type") or "FEED"
|
||
metrics = MEDIA_METRICS.get(kind, MEDIA_METRICS["FEED"])
|
||
async with sem:
|
||
rows = await _metrics(g, f"media-{kind}", f"{m['id']}/insights", metrics, {},
|
||
errors, "media")
|
||
m["insights"] = {r.get("name"): ((r.get("values") or [{}])[0].get("value")
|
||
if r.get("values") else
|
||
(r.get("total_value") or {}).get("value"))
|
||
for r in rows}
|
||
|
||
await asyncio.gather(*(one(m) for m in items))
|
||
out[ig["id"]] = items
|
||
return {"asOf": _now_iso(), "since": since.isoformat(), "media": out, "errors": errors}
|
||
|
||
|
||
async def audience(g: Graph, rec: dict, *, instagram: str | None = None) -> dict:
|
||
"""The followers' age × gender, countries and cities, and the profile's
|
||
counters — as of now."""
|
||
errors: list = []
|
||
out: dict[str, dict] = {}
|
||
for ig in _pick(rec, "instagram", instagram):
|
||
res: dict = {}
|
||
try:
|
||
prof = await g.get(ig["id"], {"fields": "username,followers_count,follows_count,"
|
||
"media_count"})
|
||
res["profile"] = {k: prof.get(k) for k in ("username", "followers_count",
|
||
"follows_count", "media_count")}
|
||
except MetaError as e:
|
||
if e.kind == "meta-token":
|
||
raise
|
||
errors.append({"part": "audience", "metric": "profile", "message": e.message})
|
||
todo = ["age,gender", "country", "city"]
|
||
while todo:
|
||
bd = todo.pop(0)
|
||
key = bd.replace(",", "_")
|
||
if ("audience", key) in _BAD:
|
||
if bd == "age,gender": # refused together: ask one at a time
|
||
todo[:0] = ["age", "gender"]
|
||
continue
|
||
try:
|
||
got = await g.get(f"{ig['id']}/insights", {
|
||
"metric": "follower_demographics", "period": "lifetime",
|
||
"metric_type": "total_value", "breakdown": bd})
|
||
except MetaError as e:
|
||
if e.kind in FATAL:
|
||
raise
|
||
_BAD.add(("audience", key))
|
||
if bd == "age,gender":
|
||
todo[:0] = ["age", "gender"]
|
||
else:
|
||
errors.append({"part": "audience", "metric": key, "message": e.message})
|
||
continue
|
||
rows = []
|
||
for m in got.get("data") or []:
|
||
for b in (m.get("total_value") or {}).get("breakdowns") or []:
|
||
for r in b.get("results") or []:
|
||
rows.append({"key": r.get("dimension_values") or [],
|
||
"value": r.get("value")})
|
||
res[key] = rows
|
||
out[ig["id"]] = res
|
||
return {"asOf": _now_iso(), "instagram": out, "errors": errors}
|
||
|
||
|
||
# ── snapshots on disk ────────────────────────────────────────────────────────
|
||
def snap_dir(uid: str) -> pathlib.Path:
|
||
if not _UID_RE.match(uid or ""):
|
||
raise MetaError(400, "bad user", "body")
|
||
return SNAP_DIR / uid
|
||
|
||
|
||
def save_day(uid: str, day: str, bundle: dict) -> None:
|
||
d = snap_dir(uid)
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
path = d / f"{day}.json"
|
||
cur: dict = {}
|
||
try:
|
||
cur = json.loads(path.read_text())
|
||
except (OSError, ValueError):
|
||
pass
|
||
# A refresh of the day's numbers keeps the point-in-time parts it took
|
||
# that morning (media, audience) unless it brings new ones.
|
||
merged = {**cur, **bundle, "date": day, "takenAt": _now_iso()}
|
||
tmp = path.with_suffix(".tmp")
|
||
tmp.write_text(json.dumps(merged, separators=(",", ":")))
|
||
os.replace(tmp, path)
|
||
|
||
|
||
def stored_days(uid: str) -> list[str]:
|
||
try:
|
||
return sorted(p.stem for p in snap_dir(uid).glob("*.json") if _DATE_RE.match(p.stem))
|
||
except OSError:
|
||
return []
|
||
|
||
|
||
def history(uid: str, since: dt.date, until: dt.date, parts: tuple[str, ...] | None = None,
|
||
max_bytes: int = 8 * 1024 ** 2) -> dict:
|
||
out: dict[str, dict] = {}
|
||
size = 0
|
||
keep = (set(parts) | {"date", "takenAt"}) if parts else None
|
||
for day in stored_days(uid):
|
||
if not (since.isoformat() <= day <= until.isoformat()):
|
||
continue
|
||
try:
|
||
raw = (snap_dir(uid) / f"{day}.json").read_text()
|
||
except OSError:
|
||
continue
|
||
size += len(raw)
|
||
if size > max_bytes:
|
||
return {"days": out, "cut": day, "message": "over 8 MB — ask for fewer days"}
|
||
rec = json.loads(raw)
|
||
out[day] = {k: v for k, v in rec.items() if keep is None or k in keep}
|
||
return {"days": out, "stored": _span(uid)}
|
||
|
||
|
||
def _span(uid: str) -> dict:
|
||
ds = stored_days(uid)
|
||
return {"days": len(ds), "first": ds[0] if ds else None, "last": ds[-1] if ds else None}
|
||
|
||
|
||
async def snapshot(client: httpx.AsyncClient, uid: str, *, backfill: bool = False) -> dict:
|
||
"""Save the last :data:`REFRESH_DAYS` days (``backfill``: the last 28) for
|
||
one guest, plus today's media and audience in yesterday's file."""
|
||
rec = STORE.get(uid)
|
||
if not rec.get("token"):
|
||
return {"calls": 0}
|
||
g = Graph(client, rec)
|
||
yesterday = today() - dt.timedelta(days=1)
|
||
since = yesterday - dt.timedelta(days=(28 if backfill else REFRESH_DAYS) - 1)
|
||
status: dict = {"at": _now_iso()}
|
||
try:
|
||
got = await days(g, rec, since, yesterday)
|
||
extra: dict = {}
|
||
if public(rec)["sees"]["instagram"] and rec.get("instagram"):
|
||
m = await media(g, rec)
|
||
a = await audience(g, rec)
|
||
extra = {"media": m["media"], "audience": a["instagram"]}
|
||
got["errors"] += m["errors"] + a["errors"]
|
||
for day, bundle in got["days"].items():
|
||
save_day(uid, day, {**bundle, **(extra if day == yesterday.isoformat() else {})})
|
||
status.update({"day": yesterday.isoformat(), "ok": True,
|
||
"errors": got["errors"][:20], **_span(uid)})
|
||
STORE.update(uid, {"snapshot": status})
|
||
except MetaError as e:
|
||
status.update({"ok": False, "message": e.message, "kind": e.kind})
|
||
patch: dict = {"snapshot": {**(rec.get("snapshot") or {}), **status}}
|
||
if e.kind == "meta-token":
|
||
patch["error"] = {"at": _now_iso(), "message": e.message, "kind": e.kind}
|
||
STORE.update(uid, patch)
|
||
raise
|
||
return {"calls": g.calls, **status}
|
||
|
||
|
||
# ── who a call reads for ─────────────────────────────────────────────────────
|
||
def connection_for(who_uid: str | None, body: dict) -> tuple[str, dict]:
|
||
"""A guest reads their own connection; the owner names one (``as``) or
|
||
gets the only one there is."""
|
||
if who_uid is not None:
|
||
rec = STORE.get(who_uid)
|
||
if not rec.get("token"):
|
||
raise MetaError(404, "Meta isn't connected yet — connect it in Settings → Meta "
|
||
"Business (ai-agent.gabvdl.xyz/settings/meta)", "not-connected")
|
||
return who_uid, rec
|
||
want = str(body.get("as") or "").strip().lower()
|
||
uids = STORE.uids()
|
||
if want:
|
||
if want not in uids:
|
||
raise MetaError(404, f"{want!r} has no Meta connection (connected: "
|
||
f"{', '.join(uids) or 'nobody'})", "not-connected")
|
||
return want, STORE.get(want)
|
||
if len(uids) == 1:
|
||
return uids[0], STORE.get(uids[0])
|
||
raise MetaError(400 if uids else 404,
|
||
f"say whose Meta to read: --as {' | '.join(uids)}" if uids
|
||
else "nobody has connected Meta yet", "not-connected")
|
||
|
||
|
||
# ── the proxy's operations ───────────────────────────────────────────────────
|
||
async def op_status(g: Graph, uid: str, rec: dict, body: dict) -> dict:
|
||
return {"as": uid, **public(rec), "stored": _span(uid)}
|
||
|
||
|
||
async def op_get(g: Graph, uid: str, rec: dict, body: dict) -> dict:
|
||
path = str(body.get("path") or "").strip().strip("/")
|
||
if path.startswith(f"{GRAPH_VERSION}/"):
|
||
path = path[len(GRAPH_VERSION) + 1:]
|
||
if not path_ok(path):
|
||
raise MetaError(403, f"{path!r} isn't a path this read-only tool reads — me, "
|
||
"me/adaccounts|accounts|permissions, act_<id>[/insights|campaigns|"
|
||
"adsets|ads|adcreatives], <id>[/insights|media|stories|children|"
|
||
"comments|published_posts|posts|video_reels|ads|adsets|adcreatives]",
|
||
"path")
|
||
if path.startswith("act_") and path.split("/", 1)[0] not in {
|
||
a["id"] for a in rec.get("adAccounts") or []}:
|
||
raise MetaError(404, f"{path.split('/', 1)[0]} isn't this connection's ad account", "asset")
|
||
params = clean_params(body.get("params"))
|
||
out = await (g.all(path, params) if body.get("all") else g.get(path, params))
|
||
return scrub(out, g.secrets())
|
||
|
||
|
||
async def op_days(g: Graph, uid: str, rec: dict, body: dict) -> dict:
|
||
since, until = date_range(body)
|
||
return scrub(await days(g, rec, since, until, _parts(body), account=body.get("account"),
|
||
instagram=body.get("instagram"), page=body.get("page")), g.secrets())
|
||
|
||
|
||
async def op_media(g: Graph, uid: str, rec: dict, body: dict) -> dict:
|
||
since = _date(body["since"], "since") if body.get("since") else None
|
||
return scrub(await media(g, rec, since=since, limit=_int(body.get("limit"), 30, 1, 100),
|
||
instagram=body.get("instagram")), g.secrets())
|
||
|
||
|
||
async def op_audience(g: Graph, uid: str, rec: dict, body: dict) -> dict:
|
||
return scrub(await audience(g, rec, instagram=body.get("instagram")), g.secrets())
|
||
|
||
|
||
async def op_history(g: Graph, uid: str, rec: dict, body: dict) -> dict:
|
||
since, until = date_range(body, default_days=30, cap=MAX_HISTORY_DAYS)
|
||
parts = _parts(body, HISTORY_PARTS) if body.get("parts") else None
|
||
return history(uid, since, until, parts)
|
||
|
||
|
||
OPS = {"status": op_status, "get": op_get, "days": op_days, "media": op_media,
|
||
"audience": op_audience, "history": op_history}
|
||
# The ones that never call Meta.
|
||
OFFLINE = {"status", "history"}
|