Files

162 lines
6.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""One-shot, idempotent move of the ai-agent's former built-in Meta Business
tool into the ``meta`` live plugin's storage. Run it on the hub's data dir
(the host side of the container's ``/data``) **once the plugin is installed**
for each guest — nothing here installs it.
For each guest in ``<data>/tools-meta.json`` that has a key:
* the key → ``<data>/plugins/secrets/<uid>/meta.json`` as ``{"token": …}``
(mode 0600, other keys in that file kept). A different key already there
is left alone (the guest pasted a new one) unless ``--overwrite-secret``;
* what the key reaches (no key, no Page keys) →
``<data>/plugins/data/<uid>/meta/connection.json`` when it isn't there yet;
* the saved days ``<data>/meta-snapshots/<uid>/YYYY-MM-DD.json`` →
``<data>/plugins/data/<uid>/meta/YYYY-MM-DD.json`` (a day already there is
kept unless ``--overwrite-days``), and the last snapshot status →
``snapshot.json``.
It never prints, logs or returns a key: only counts and paths. ``--dry-run``
shows what it would do. The legacy files are only read, never changed.
migrate_legacy.py [--data-dir DIR] [--uid carol] [--dry-run]
"""
from __future__ import annotations
import argparse
import json
import os
import pathlib
import re
import shutil
import sys
DEFAULT_DATA = os.environ.get("AIA_DATA_DIR", "/data") # the hub's /data, or its host-side copy
PLUGIN_ID = "meta"
_UID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
_DAY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}\.json$")
_PUBLIC = ("user", "scopes", "adAccounts", "pages", "instagram", "connectedAt", "checkedAt",
"error", "expiresAt")
def _read_json(p: pathlib.Path):
try:
return json.loads(p.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
def _write_0600(p: pathlib.Path, obj) -> None:
p.parent.mkdir(parents=True, exist_ok=True)
os.chmod(p.parent, 0o700)
tmp = p.with_suffix(".tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=1, sort_keys=True)
os.chmod(tmp, 0o600)
os.replace(tmp, p)
def _write_json(p: pathlib.Path, obj) -> None:
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_name(f".{p.name}.tmp")
tmp.write_text(json.dumps(obj, separators=(",", ":"), ensure_ascii=False), encoding="utf-8")
os.replace(tmp, p)
def migrate(data_dir: str | os.PathLike, *, only: str | None = None, dry_run: bool = False,
overwrite_secret: bool = False, overwrite_days: bool = False) -> dict:
"""Returns ``{uid: {secret, connection, days_copied, days_kept}}`` — never a key."""
data = pathlib.Path(data_dir)
legacy = _read_json(data / "tools-meta.json")
if not isinstance(legacy, dict):
raise SystemExit(f"no legacy Meta store at {data / 'tools-meta.json'}")
plugins = data / "plugins"
report: dict[str, dict] = {}
for uid, rec in sorted(legacy.items()):
if only and uid != only:
continue
if not _UID_RE.match(str(uid)) or not isinstance(rec, dict):
report[str(uid)[:64]] = {"skipped": "bad user id or record"}
continue
token = rec.get("token")
out: dict = {"secret": "none", "connection": "none", "days_copied": 0, "days_kept": 0}
# the key
if isinstance(token, str) and token.strip():
sec_path = plugins / "secrets" / uid / f"{PLUGIN_ID}.json"
cur = _read_json(sec_path)
cur = cur if isinstance(cur, dict) else {}
if cur.get("token") == token:
out["secret"] = "already there"
elif cur.get("token") and not overwrite_secret:
out["secret"] = "kept the newer key already there"
else:
out["secret"] = "would copy" if dry_run else "copied"
if not dry_run:
_write_0600(sec_path, {**cur, "token": token})
if sec_path.exists() and not dry_run:
os.chmod(sec_path, 0o600)
dest = plugins / "data" / uid / PLUGIN_ID
# what it reaches (never a key)
conn_path = dest / "connection.json"
if conn_path.exists():
out["connection"] = "already there"
elif rec.get("user") or rec.get("adAccounts") or rec.get("instagram") or rec.get("pages"):
conn = {k: rec.get(k) for k in _PUBLIC if k in rec}
out["connection"] = "would write" if dry_run else "written"
if not dry_run:
_write_json(conn_path, conn)
# the saved days
src = data / "meta-snapshots" / uid
if src.is_dir():
for f in sorted(src.iterdir()):
if not (f.is_file() and _DAY_RE.match(f.name)):
continue
target = dest / f.name
if target.exists() and not overwrite_days:
out["days_kept"] += 1
continue
out["days_copied"] += 1
if not dry_run:
dest.mkdir(parents=True, exist_ok=True)
tmp = dest / f".{f.name}.tmp"
shutil.copy2(f, tmp)
os.replace(tmp, target)
snap = rec.get("snapshot")
if isinstance(snap, dict) and snap and not (dest / "snapshot.json").exists():
out["snapshot_status"] = "would write" if dry_run else "written"
if not dry_run:
_write_json(dest / "snapshot.json", snap)
report[uid] = out
return report
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--data-dir", default=DEFAULT_DATA,
help=f"the hub's data dir (default {DEFAULT_DATA})")
ap.add_argument("--uid", help="only this guest")
ap.add_argument("--dry-run", action="store_true", help="say what it would do, change nothing")
ap.add_argument("--overwrite-secret", action="store_true",
help="replace a different key already stored for the plugin")
ap.add_argument("--overwrite-days", action="store_true",
help="replace saved days already in the plugin's data dir")
a = ap.parse_args(argv)
report = migrate(a.data_dir, only=a.uid, dry_run=a.dry_run,
overwrite_secret=a.overwrite_secret, overwrite_days=a.overwrite_days)
for uid, r in report.items():
print(f"{uid}: " + ", ".join(f"{k}={v}" for k, v in r.items()))
if not report:
print("nothing to migrate")
return 0
if __name__ == "__main__":
sys.exit(main())