A sixth paid-tool group, 'meta', off by default: a guest connects their own Meta business portfolio with a system-user key (Settings → Meta Business), the hub refuses a key that could write, keeps it (0600) and only sends GETs to an allowlist of Graph paths, scrubbing the key out of every answer. Ops: status, days (ads day × ad × age × gender, Instagram and Page per day), media, audience, history, get. The owner reads any guest's with --as. A daily snapshot saves the last 7 days every morning (Instagram keeps 30 days of followers); a connect backfills 28. A dead key is marked and pushed once. Hub edition cli/skills/meta, guest page business/meta (French), the owner's status line + Disconnect under the switch, mock, tests (fake Graph). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
100 lines
3.3 KiB
Python
100 lines
3.3 KiB
Python
"""
|
|
The free daily Meta snapshot (``meta.snapshot``): every morning, for each
|
|
guest whose Meta group is on and whose key works, the hub saves the last
|
|
:data:`meta.REFRESH_DAYS` days again (an ad's numbers keep moving for a week)
|
|
plus that morning's posts / reels and follower audience — one JSON file per
|
|
day under ``META_SNAPSHOT_DIR/<uid>/``. Instagram answers only the last 30
|
|
days of followers, so these files are what keeps the longer story; the runs
|
|
read them with ``meta history``.
|
|
|
|
No Claude run, no cost: a ledger row ``via: snapshot`` counts the Graph calls.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import datetime as dt
|
|
import logging
|
|
import os
|
|
import threading
|
|
import time
|
|
|
|
import httpx
|
|
|
|
from . import access, meta
|
|
from .ledger import LEDGER
|
|
|
|
log = logging.getLogger("toolproxy.snapshots")
|
|
|
|
HOUR = int(os.environ.get("META_SNAPSHOT_HOUR", "7")) # local (META_TZ)
|
|
CHECK_EVERY_S = int(os.environ.get("META_SNAPSHOT_CHECK_S", "1200"))
|
|
RETRY_AFTER_S = 2 * 3600
|
|
|
|
|
|
def _ts(iso: str | None) -> float:
|
|
try:
|
|
return dt.datetime.strptime(iso or "", "%Y-%m-%dT%H:%M:%SZ").replace(
|
|
tzinfo=dt.timezone.utc).timestamp()
|
|
except ValueError:
|
|
return 0.0
|
|
|
|
|
|
def due(deps, uid: str, now: dt.datetime | None = None) -> bool:
|
|
"""Whether this guest's snapshot should be taken now."""
|
|
now = now or dt.datetime.now(meta.TZ)
|
|
if now.hour < HOUR:
|
|
return False
|
|
rec = meta.STORE.get(uid)
|
|
if not rec.get("token") or rec.get("error"):
|
|
return False
|
|
if not deps.users.active(uid) or deps.security_state.guests_locked():
|
|
return False
|
|
if "meta" not in access.config(deps, access.Who(uid))["groups"]:
|
|
return False
|
|
snap = rec.get("snapshot") or {}
|
|
yesterday = (now.date() - dt.timedelta(days=1)).isoformat()
|
|
if snap.get("ok") and snap.get("day") == yesterday:
|
|
return False
|
|
if snap.get("ok") is False and time.time() - _ts(snap.get("at")) < RETRY_AFTER_S:
|
|
return False
|
|
return True
|
|
|
|
|
|
def take(deps, uid: str) -> dict:
|
|
async def go():
|
|
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=120.0)) as c:
|
|
return await meta.snapshot(c, uid)
|
|
try:
|
|
out = asyncio.run(go())
|
|
except meta.MetaError as e:
|
|
if e.kind == "meta-token":
|
|
from .routes import meta_key_died
|
|
meta.STORE.update(uid, {"error": None}) # let meta_key_died push once
|
|
meta_key_died(deps, uid, e.message)
|
|
log.warning("meta snapshot for %s failed: %s", uid, e.message)
|
|
return {"ok": False, "message": e.message}
|
|
LEDGER.record({"tool": "meta", "who": uid, "guest": uid, "via": "snapshot", "usd": 0,
|
|
"units": {"calls": out.get("calls", 0)}, "op": "snapshot"})
|
|
return out
|
|
|
|
|
|
class MetaSnapshots(threading.Thread):
|
|
def __init__(self, deps):
|
|
super().__init__(name="meta-snapshots", daemon=True)
|
|
self.deps = deps
|
|
|
|
def run(self) -> None:
|
|
time.sleep(90)
|
|
while True:
|
|
try:
|
|
for uid in meta.STORE.uids():
|
|
if due(self.deps, uid):
|
|
take(self.deps, uid)
|
|
except Exception:
|
|
log.exception("meta snapshots")
|
|
time.sleep(CHECK_EVERY_S)
|
|
|
|
|
|
def start(deps) -> None:
|
|
MetaSnapshots(deps).start()
|