Files
gabrielvidalandClaude Opus 5.5 8f793bae88 feat(guests): Analytics · Matomo tool group — a guest's own sites through the tool proxy
A per-guest switch (Settings → Users → <guest> → Access → Paid tools): their
runs and computers get the matomo hub edition, which lists their Matomo sites
(the ones whose URLs are all on their address), adds one on their address with
its cookieless tracking tag, reads its reports (the report modules' get*
methods, idSite forced to that site) and mints a view-only key for a page of
theirs (one viewer user per guest, GET-capable app token, rotate = recreate).
Superuser token stays in the hub. Free, counted in the tool ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:20:18 +01:00

99 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
"""Web analytics for your own sites, on the lab's Matomo through the ai-agent hub.
matomo sites # your Matomo sites (id, name, URLs)
matomo add-site https://jeu.example.xyz # a site for one of your addresses + its tag
matomo tracking 10 # the <script> tag to paste in index.html
matomo report 10 VisitsSummary.get --period month --date today
matomo report 10 Actions.getPageUrls --period range --date 2026-10-01,today -p flat=1
matomo report 10 Events.getCategory -p segment=pageUrl=@/jeu/
matomo token # a view-only key for a page of yours
matomo token --rotate # a new key; the old one stops working
"""
from __future__ import annotations
import argparse
import json
import pathlib
import sys
sys.dont_write_bytecode = True # nothing written into the skill folder
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import hubclient as hub # noqa: E402
def op(name: str, body: dict) -> object:
return hub.call("POST", f"matomo/{name}", json_body=body, timeout=180)
def show(data: object) -> None:
print(json.dumps(data, indent=2, ensure_ascii=False))
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="matomo", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("sites", help="your Matomo sites")
s.add_argument("--json", action="store_true")
s = sub.add_parser("add-site", help="a Matomo site for one of your addresses")
s.add_argument("url")
s.add_argument("--name")
s = sub.add_parser("tracking", help="the tracking tag of a site")
s.add_argument("site")
s = sub.add_parser("report", help="a Reporting API call on one of your sites")
s.add_argument("site")
s.add_argument("method", help="e.g. VisitsSummary.get, Actions.getPageUrls, Events.getAction")
s.add_argument("--period", default=None, help="day | week | month | year | range")
s.add_argument("--date", default=None, help="today | yesterday | 2026-11-01 | last7 | A,B")
s.add_argument("-p", "--param", action="append", default=[], metavar="KEY=VALUE",
help="any other API parameter (repeatable): segment, flat, filter_limit…")
s = sub.add_parser("token", help="a view-only key for a page of yours")
s.add_argument("--rotate", action="store_true")
a = ap.parse_args(argv)
try:
if a.cmd == "sites":
d = op("sites", {})
if a.json:
show(d)
elif not d["sites"]:
print(f"no Matomo site of yours yet — `matomo add-site https://<name>."
f"{d.get('base') or '<your domain>'}`", file=sys.stderr)
else:
for st in d["sites"]:
print(f"{st['id']:>4} {st['name']:<24} {' '.join(st['urls'])}")
elif a.cmd == "add-site":
d = op("add-site", {"url": a.url, **({"name": a.name} if a.name else {})})
st = d["site"]
print(f"{'created' if d['created'] else 'already there'}: site {st['id']} · "
f"{st['name']} · {' '.join(st['urls'])}", file=sys.stderr)
print(d["tracking"])
elif a.cmd == "tracking":
print(op("tracking", {"site": a.site})["tracking"])
elif a.cmd == "report":
params = {}
for kv in a.param:
k, sep, v = kv.partition("=")
if not sep:
hub.die(f"-p wants KEY=VALUE, not {kv!r}", 2)
params[k] = v
if a.period:
params["period"] = a.period
if a.date:
params["date"] = a.date
show(op("report", {"site": a.site, "method": a.method, "params": params}))
elif a.cmd == "token":
d = op("token", {"rotate": a.rotate})
print(f"view-only key of {d['login']} — sites {', '.join(map(str, d['sites']))}"
f"{' (rotated: the old key no longer works)' if d['rotated'] else ''}",
file=sys.stderr)
print(d["token"])
except hub.HubError as e:
hub.die(str(e))
return 0
if __name__ == "__main__":
sys.exit(main())