Files

907 lines
39 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
The Meta Business plugin's shared logic (stdlib only): the Graph reads, their
shaping and the snapshot files. Used by the ``meta`` CLI (skill), the
``inspect`` / ``status`` actions (``handlers/``) and the daily snapshot job
(``jobs/snapshot.py``).
Ported from the ai-agent's former built-in ``backend/toolproxy/meta.py``. The
difference: nothing here ever holds the Meta key. Every Graph read goes to the
hub's allowlisted plugin proxy, ``<AIA_TOOLS_URL>/plugins/meta/proxy/<path>``,
which adds the key, allows only ``GET`` on the read-only Graph paths, refuses
``access_token`` / ``method`` / ``batch``… parameters and scrubs the key out of
the answer. Per-user files live in the plugin data dir (``…/data/…`` over the
hub, ``AIA_PLUGIN_DATA_DIR`` for jobs and actions):
* ``connection.json`` — what the key reaches (no key): user, scopes, ad
accounts, Pages, Instagram accounts, connectedAt / checkedAt, error;
* ``snapshot.json`` — the last snapshot run's status;
* ``YYYY-MM-DD.json`` — one saved day (ads / instagram / page, plus that
morning's media and audience on the newest day).
"""
from __future__ import annotations
import datetime as dt
import json
import os
import pathlib
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from zoneinfo import ZoneInfo
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import hubclient as hub # noqa: E402
PLUGIN_ID = "meta"
GRAPH_VERSION = "v27.0"
DEFAULT_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.
READ_SCOPES = frozenset(SCOPES_ASKED) | {
"public_profile", "pages_read_user_content", "read_audience_network_insights",
"instagram_business_basic", "instagram_business_manage_insights", "attribution_read",
}
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
MAX_ROWS = 20_000
MAX_DAYS = 92
MAX_HISTORY_DAYS = 400
IG_FOLLOWER_DAYS = 30
REFRESH_DAYS = 7
BACKFILL_DAYS = 28
HISTORY_MAX_BYTES = 8 * 1024 ** 2
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")
IG_DAY_METRICS = ("views", "reach", "accounts_engaged", "total_interactions", "likes",
"comments", "shares", "saves", "replies", "profile_links_taps",
"website_clicks", "profile_views")
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")
PARTS = ("ads", "instagram", "page")
HISTORY_PARTS = PARTS + ("media", "audience")
# Metrics Meta refused here, by (where, metric) — skipped for this process.
_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))?$",
)]
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}$")
DAY_FILE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}\.json$")
_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", "hub")
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."""
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 and "page access token" in msg.lower():
# A Page's insights want the Page's own key, which the hub strips from
# every answer (stripResponseKeys): the key is fine, this part is out.
return MetaError(403, "Meta wants a Page key for the Facebook Page's numbers, which the "
"hub doesn't hand out — the Page part is skipped (ads and "
"Instagram are unaffected)", "meta-page-key", code)
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 → Plugins → 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):
"""Meta's answer without a key in it: ``access_token`` fields (a Page's
own key in ``me/accounts``) dropped, ``paging.next`` / ``previous``
replaced by ``more``, and ``access_token=…`` in strings masked. (The hub
proxy already masks the stored key itself.)"""
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) for kk, vv in v.items() if kk not in ("next", "previous")}
p["more"] = bool(v.get("next") or v.get("more"))
out[k] = p
continue
out[k] = scrub(v)
return out
if isinstance(obj, list):
return [scrub(v) for v in obj]
if isinstance(obj, str) and "access_token=" in obj:
return _TOKEN_RE.sub(r"\1***", obj)
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 (the hub refuses them too)."""
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
def now_iso() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# ── talking to the hub ───────────────────────────────────────────────────────
class Hub:
"""The plugin's runtime endpoints on the hub, as one user (``as_uid``:
the owner reading a guest's, via ``X-Plugin-As``)."""
def __init__(self, as_uid: str | None = None, timeout: float = 120.0):
self.as_uid = (as_uid or "").strip().lower() or None
self.timeout = timeout
self.calls = 0
def _request(self, method: str, path: str, *, params: dict | None = None,
body: bytes | None = None, content_type: str | None = None):
url, token = hub.config()
full = f"{url}/plugins/{PLUGIN_ID}/{path.lstrip('/')}"
if params:
full += "?" + urllib.parse.urlencode(params)
headers = hub._headers(token)
if self.as_uid:
headers["X-Plugin-As"] = self.as_uid
if content_type:
headers["Content-Type"] = content_type
req = urllib.request.Request(full, data=body, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
try:
raw = e.read()
except OSError:
raw = b""
return e.code, raw
except urllib.error.URLError as e:
raise MetaError(502, f"couldn't reach the hub at {url}: {e.reason}", "hub") from None
@staticmethod
def _hub_error(status: int, raw: bytes) -> MetaError:
msg = ""
try:
d = json.loads(raw)
err = d.get("error") if isinstance(d, dict) else None
if isinstance(err, dict):
msg = str(err.get("message") or "")
elif isinstance(d, dict) and d.get("detail"):
msg = str(d["detail"])
except ValueError:
msg = raw.decode("utf-8", "replace")[:300]
if status == 412:
msg = (msg or "no Meta key yet") + " — connect it in Settings → Plugins → Meta Business"
elif status == 404 and "not active" in msg:
msg += " — install and enable the Meta Business plugin (Settings → Plugins)"
return MetaError(status, msg or f"the hub answered HTTP {status}", "hub")
# Graph, through the plugin proxy
def graph(self, path: str, params: dict | None = None) -> dict:
self.calls += 1
status, raw = self._request("GET", f"proxy/{path}", params=params)
try:
out = json.loads(raw) if raw else {}
except ValueError:
raise MetaError(502, f"Meta answered {status} without JSON", "upstream") from None
if isinstance(out, dict) and isinstance(out.get("error"), dict):
err = out["error"]
# Graph errors carry a ``code`` / ``type``; the hub's own carry ``kind``.
if "code" in err or "type" in err or "fbtrace_id" in err:
raise graph_error(err, status)
raise self._hub_error(status, raw)
if status >= 400:
raise self._hub_error(status, raw)
return out if isinstance(out, dict) else {"data": out}
def graph_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 = self.graph(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 paging.get("more")) or not after or len(rows) >= max_rows:
break
p["after"] = after
paging = out.get("paging") or {}
more = bool(paging.get("next") or paging.get("more"))
return {"data": rows[:max_rows], "paging": {"more": more or len(rows) > max_rows}}
# per-user data dir
def data_list(self) -> list[dict]:
status, raw = self._request("GET", "data")
if status >= 400:
raise self._hub_error(status, raw)
return list((json.loads(raw) or {}).get("files") or [])
def data_get(self, rel: str) -> bytes | None:
status, raw = self._request("GET", f"data/{rel}")
if status == 404:
return None
if status >= 400:
raise self._hub_error(status, raw)
return raw
def data_get_json(self, rel: str):
raw = self.data_get(rel)
if raw is None:
return None
try:
return json.loads(raw)
except ValueError:
return None
def data_put_json(self, rel: str, obj) -> None:
if self.as_uid:
return # the hub writes only the caller's own data dir
status, raw = self._request("PUT", f"data/{rel}",
body=json.dumps(obj, separators=(",", ":")).encode(),
content_type="application/octet-stream")
if status >= 400:
raise self._hub_error(status, raw)
def config(self) -> dict:
status, raw = self._request("GET", "config")
if status >= 400:
return {}
try:
return dict((json.loads(raw) or {}).get("config") or {})
except (ValueError, TypeError):
return {}
# ── storage: the hub's data API, or the data dir itself (jobs / actions) ─────
class HubStore:
"""Plugin data through the hub (the CLI)."""
def __init__(self, h: Hub):
self.h = h
def read(self, name: str):
return self.h.data_get_json(name)
def write(self, name: str, obj) -> None:
self.h.data_put_json(name, obj)
def days(self) -> list[str]:
return sorted(f["path"][:-5] for f in self.h.data_list()
if DAY_FILE_RE.match(str(f.get("path") or "")))
def read_raw(self, name: str) -> bytes | None:
return self.h.data_get(name)
class DirStore:
"""Plugin data in ``AIA_PLUGIN_DATA_DIR`` (jobs, actions, tests)."""
def __init__(self, root: str | os.PathLike):
self.root = pathlib.Path(root)
def read(self, name: str):
try:
return json.loads((self.root / name).read_text())
except (OSError, ValueError):
return None
def read_raw(self, name: str) -> bytes | None:
try:
return (self.root / name).read_bytes()
except OSError:
return None
def write(self, name: str, obj) -> None:
self.root.mkdir(parents=True, exist_ok=True)
path = self.root / name
tmp = path.with_name(f".{path.name}.tmp")
tmp.write_text(json.dumps(obj, separators=(",", ":"), ensure_ascii=False))
os.replace(tmp, path)
def days(self) -> list[str]:
try:
return sorted(p.name[:-5] for p in self.root.iterdir() if DAY_FILE_RE.match(p.name))
except OSError:
return []
def save_day(self, day: str, bundle: dict) -> None:
"""A refresh of a day keeps the point-in-time parts it took that
morning (media, audience) unless it brings new ones."""
cur = self.read(f"{day}.json") or {}
self.write(f"{day}.json", {**cur, **bundle, "date": day, "takenAt": now_iso()})
def plugin_data_dir() -> pathlib.Path:
d = os.environ.get("AIA_PLUGIN_DATA_DIR", "").strip()
if not d:
raise MetaError(500, "AIA_PLUGIN_DATA_DIR isn't set (this runs as a plugin job/action)",
"config")
return pathlib.Path(d)
def plugin_config() -> dict:
try:
c = json.loads(os.environ.get("AIA_PLUGIN_CONFIG") or "{}")
return c if isinstance(c, dict) else {}
except ValueError:
return {}
# ── days ─────────────────────────────────────────────────────────────────────
class Clock:
"""Days in the connection's time zone (setting ``timezone``)."""
def __init__(self, tz: str | None = None):
try:
self.tz = ZoneInfo((tz or "").strip() or DEFAULT_TZ)
except Exception:
self.tz = ZoneInfo(DEFAULT_TZ)
def today(self) -> dt.date:
return dt.datetime.now(self.tz).date()
def unix(self, d: dt.date) -> int:
return int(dt.datetime(d.year, d.month, d.day, tzinfo=self.tz).timestamp())
def floor(self, d: dt.date) -> dt.datetime:
return dt.datetime(d.year, d.month, d.day, tzinfo=self.tz)
def parse_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") from None
def date_range(clock: Clock, since: str | None, until: str | None, *, 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."""
yesterday = clock.today() - dt.timedelta(days=1)
u = parse_date(until, "until") if until else yesterday
s = parse_date(since, "since") if since else u - dt.timedelta(days=default_days - 1)
u = min(u, yesterday)
if s > u:
raise MetaError(400, f"since must be on or before until (and Meta's last full day is "
f"{yesterday})", "body")
if (u - s).days + 1 > cap:
raise MetaError(400, f"at most {cap} days at once", "body")
return s, u
def day_list(since: dt.date, until: dt.date) -> list[dt.date]:
return [since + dt.timedelta(days=i) for i in range((until - since).days + 1)]
def end_day(end_time) -> 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 parse_parts(raw, allowed: tuple[str, ...] = PARTS) -> tuple[str, ...]:
if not raw:
return allowed
raw = raw.split(",") if isinstance(raw, str) else raw
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
# ── the connection ───────────────────────────────────────────────────────────
def public(rec: dict | None) -> dict:
"""A connection as the pages and the runs see it (it never holds a key)."""
if not rec or not rec.get("user"):
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"),
}
def inspect(h: Hub) -> dict:
"""Check the stored key and find what it reaches. Raises ``MetaError``
for a key that doesn't work, may write, or reaches nothing."""
me = h.graph("me", {"fields": "id,name"})
perms = h.graph("me/permissions")
scopes = sorted({p.get("permission") for p in perms.get("data") or []
if isinstance(p, dict) and p.get("status") == "granted"
and p.get("permission")})
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 = h.graph_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 in ("meta-token", "hub"):
raise
pages: list[dict] = []
instagram: list[dict] = []
if "pages_show_list" in scopes:
try:
got = h.graph_all("me/accounts", {
"fields": "id,name,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})
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 in ("meta-token", "hub"):
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 {"user": {"id": str(me.get("id") or ""), "name": me.get("name") or ""},
"scopes": scopes, "adAccounts": ads, "pages": pages, "instagram": instagram,
"checkedAt": now_iso(), "error": None}
def refresh_connection(h: Hub, store) -> dict:
"""Inspect and save ``connection.json`` (keeping ``connectedAt``); a dead
key, extra scopes or no assets are written as its ``error``."""
cur = store.read("connection.json") or {}
try:
rec = inspect(h)
except MetaError as e:
if e.kind in ("meta-token", "scopes", "no-assets") and cur:
cur["error"] = {"at": now_iso(), "message": e.message, "kind": e.kind}
store.write("connection.json", cur)
raise
rec["connectedAt"] = cur.get("connectedAt") or rec["checkedAt"]
store.write("connection.json", rec)
return rec
def connection(h: Hub, store) -> dict:
"""The saved connection, or a live check when none is saved yet."""
rec = store.read("connection.json")
if isinstance(rec, dict) and rec.get("user"):
return rec
return refresh_connection(h, store)
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
# ── reading Meta ─────────────────────────────────────────────────────────────
def ads_days(h: Hub, 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 = h.graph_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 = h.graph_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
def metrics(h: Hub, where: str, path: str, names: 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 names if (where, m) not in _BAD]
if not want:
return []
try:
return list(h.graph(path, {**params, "metric": ",".join(want)}).get("data") or [])
except MetaError as e:
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(h.graph(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
def ig_days(h: Hub, clock: Clock, ig: str, since: dt.date, until: dt.date,
errors: list) -> dict[str, dict]:
out: dict[str, dict] = {d.isoformat(): {} for d in day_list(since, until)}
floor = clock.today() - dt.timedelta(days=IG_FOLLOWER_DAYS)
fs = max(since, floor)
if fs <= until:
rows = metrics(h, "ig-series", f"{ig}/insights", ("follower_count",),
{"period": "day", "since": str(clock.unix(fs)),
"until": str(clock.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 day_list(since, until):
day = d.isoformat()
window = {"period": "day", "metric_type": "total_value", "since": str(clock.unix(d)),
"until": str(clock.unix(d + dt.timedelta(days=1)))}
for m in metrics(h, "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 metrics(h, "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
def page_days(h: Hub, page: str, since: dt.date, until: dt.date, errors: list) -> dict[str, dict]:
out: dict[str, dict] = {d.isoformat(): {} for d in day_list(since, until)}
rows = metrics(h, "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
def days(h: Hub, clock: Clock, 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 day_list(since, until)}
sees = public(rec).get("sees") or {}
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
def run(name: str, asset: str, job) -> None:
try:
put(name, asset, job())
except MetaError as e:
if e.kind in ("meta-token", "meta-rate", "hub"):
raise
errors.append({"part": name, "asset": asset, "message": e.message})
if "ads" in parts and sees.get("ads"):
for a in pick(rec, "adAccounts", account):
def ads_job(acct=a["id"]):
rows = ads_days(h, acct, since, until, errors)
return {d: rows.get(d, []) for d in by_day}
run("ads", a["id"], ads_job)
if "instagram" in parts and sees.get("instagram"):
for ig in pick(rec, "instagram", instagram):
run("instagram", ig["id"], lambda i=ig["id"]: ig_days(h, clock, i, since, until, errors))
if "page" in parts and sees.get("page"):
for p in pick(rec, "pages", page):
run("page", p["id"], lambda i=p["id"]: page_days(h, i, since, until, errors))
return scrub({"since": since.isoformat(), "until": until.isoformat(), "days": by_day,
"errors": errors})
def _int(v, default: int, lo: int, hi: int) -> int:
try:
return max(lo, min(hi, int(v)))
except (TypeError, ValueError):
return default
def media(h: Hub, clock: Clock, 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 (clock.today() - dt.timedelta(days=30))
floor = clock.floor(since)
errors: list = []
out: dict[str, list] = {}
for ig in pick(rec, "instagram", instagram):
got = h.graph_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)]
def one(m: dict) -> None:
kind = m.get("media_product_type") or "FEED"
names = MEDIA_METRICS.get(kind, MEDIA_METRICS["FEED"])
rows = metrics(h, f"media-{kind}", f"{m['id']}/insights", names, {}, 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}
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(one, items))
out[ig["id"]] = items
return scrub({"asOf": now_iso(), "since": since.isoformat(), "media": out, "errors": errors})
def audience(h: Hub, 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 = h.graph(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 in ("meta-token", "hub"):
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":
todo[:0] = ["age", "gender"]
continue
try:
got = h.graph(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 scrub({"asOf": now_iso(), "instagram": out, "errors": errors})
def get(h: Hub, rec: dict, path: str, params: dict | None = None, *, all_pages: bool = False) -> dict:
"""One allowlisted Graph read (the hub allows the same paths)."""
path = str(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")
p = clean_params(params)
return scrub(h.graph_all(path, p) if all_pages else h.graph(path, p))
# ── saved days ───────────────────────────────────────────────────────────────
def span(day_names: list[str]) -> dict:
return {"days": len(day_names), "first": day_names[0] if day_names else None,
"last": day_names[-1] if day_names else None}
def history(store, since: dt.date, until: dt.date, parts: tuple[str, ...] | None = None,
max_bytes: int = HISTORY_MAX_BYTES) -> dict:
out: dict[str, dict] = {}
size = 0
keep = (set(parts) | {"date", "takenAt"}) if parts else None
names = store.days()
for day in names:
if not (since.isoformat() <= day <= until.isoformat()):
continue
raw = store.read_raw(f"{day}.json")
if raw is None:
continue
size += len(raw)
if size > max_bytes:
return {"days": out, "cut": day, "message": "over 8 MB — ask for fewer days",
"stored": span(names)}
try:
rec = json.loads(raw)
except ValueError:
continue
out[day] = {k: v for k, v in rec.items() if keep is None or k in keep}
return {"days": out, "stored": span(names)}
def status(store) -> dict:
"""What the key reaches (as last checked) + the saved days + the last
snapshot — offline, nothing asked of Meta."""
rec = store.read("connection.json")
out = public(rec if isinstance(rec, dict) else None)
out["stored"] = span(store.days())
out["snapshot"] = store.read("snapshot.json") or {}
return out
def snapshot(h: Hub, store: DirStore, clock: Clock, *, backfill: bool | None = None) -> dict:
"""Save the last :data:`REFRESH_DAYS` days (``backfill``: the last 28;
by default when fewer than a week is saved) plus this morning's media
and audience in yesterday's file. Writes ``snapshot.json``."""
yesterday = clock.today() - dt.timedelta(days=1)
if backfill is None:
backfill = len(store.days()) < REFRESH_DAYS
since = yesterday - dt.timedelta(days=(BACKFILL_DAYS if backfill else REFRESH_DAYS) - 1)
st: dict = {"at": now_iso()}
try:
rec = refresh_connection(h, store)
got = days(h, clock, rec, since, yesterday)
extra: dict = {}
if public(rec)["sees"]["instagram"] and rec.get("instagram"):
m = media(h, clock, rec)
a = audience(h, rec)
extra = {"media": m["media"], "audience": a["instagram"]}
got["errors"] += m["errors"] + a["errors"]
for day, bundle in got["days"].items():
store.save_day(day, {**bundle, **(extra if day == yesterday.isoformat() else {})})
st.update({"day": yesterday.isoformat(), "ok": True, "backfill": bool(backfill),
"errors": got["errors"][:20], **span(store.days())})
except MetaError as e:
prev = store.read("snapshot.json") or {}
st = {**prev, **st, "ok": False, "message": e.message, "kind": e.kind}
store.write("snapshot.json", st)
raise
store.write("snapshot.json", st)
return {"calls": h.calls, **st}