ask-form's createReq.meta is map[string]string, so the bridge's ownerOnly/noPush booleans made every owner-only form a 400 (Approvals, New project). create_form() now sends true as "true", drops false/null, stringifies the rest; the hub reads both spellings of a switch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
435 lines
18 KiB
Python
435 lines
18 KiB
Python
"""What the hub does with an ask-form form: the push when one opens, the
|
|
events webhook, revoke / close back to its machine, the field spec on demand,
|
|
and the per-caller view the routes return."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import time
|
|
from urllib.parse import urlsplit
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from askform.store import ID_RE, parse_iso
|
|
from conversations.catalog import _conv_ids_by_session
|
|
from core.config import SIDECAR_TOKEN, SIDECAR_URL
|
|
from core.i18n import localized, tr
|
|
from core.state import AppState
|
|
from notifications.service import VIEW_URL, _conversation_url, _create_notify
|
|
from users import access
|
|
from users.caller import Caller
|
|
from workers.store import sidecar_request
|
|
|
|
log = logging.getLogger("askform")
|
|
LAB = "lab"
|
|
# A form older than this when first seen is history (a hub restart, a machine
|
|
# paired later): mirrored, never pushed.
|
|
FRESH_S = 15 * 60
|
|
|
|
|
|
def _form_session(form: dict) -> str | None:
|
|
meta = form.get("meta") if isinstance(form.get("meta"), dict) else {}
|
|
return str(meta["session"]) if meta.get("session") else None
|
|
|
|
|
|
def machines(deps: AppState) -> list[dict]:
|
|
"""Where forms live: the host sidecar (when configured) and every online
|
|
worker — ``{id, url, token, label}`` each. A guest's own computer also
|
|
carries ``vet``: what it reports is its word alone, so a form is taken
|
|
only for a session that runs on it (``guests.session_belongs`` — the
|
|
rule its outbox items already pass)."""
|
|
from workers import guests
|
|
out = []
|
|
if SIDECAR_TOKEN:
|
|
out.append({"id": LAB, "url": SIDECAR_URL, "token": SIDECAR_TOKEN, "label": "sidecar"})
|
|
for w in deps.worker_store.list():
|
|
if deps.worker_store.online(w["id"]):
|
|
m = {"id": w["id"], "url": w["url"], "token": w["token"],
|
|
"label": f"worker {w.get('name') or w['id']}"}
|
|
if guests.is_guest(w):
|
|
m["vet"] = lambda form, w=w: guests.session_belongs(
|
|
deps, w, _form_session(form))
|
|
out.append(m)
|
|
return out
|
|
|
|
|
|
def take(deps: AppState, m: dict, form: dict) -> tuple[dict, bool, bool]:
|
|
"""Mirror one form machine ``m`` handed over (a reply to a read, a
|
|
revoke, a close) — under the same rule as the poll: a guest's computer
|
|
only for its own sessions. :class:`HTTPException` 502 when refused."""
|
|
vet = m.get("vet")
|
|
try:
|
|
if vet and not vet(form):
|
|
raise ValueError("not one of that computer's sessions")
|
|
return deps.askform_store.upsert(m["id"], form, trusted=not vet)
|
|
except ValueError as e:
|
|
raise HTTPException(502, {"message": f"{m.get('label') or m['id']} sent a form "
|
|
f"the hub won't take: {e}",
|
|
"kind": "askform_refused"})
|
|
|
|
|
|
def _trusted(deps: AppState, machine: str) -> bool:
|
|
"""Is ``machine`` the lab or one of the owner's workers (not a guest's)?"""
|
|
from workers import guests
|
|
return machine == LAB or not guests.is_guest(deps.worker_store.get(machine))
|
|
|
|
|
|
def _machine(deps: AppState, mid: str) -> dict:
|
|
for m in machines(deps):
|
|
if m["id"] == mid:
|
|
return m
|
|
raise HTTPException(409, {"message": f"the machine holding this form ({mid or 'unknown'}) "
|
|
"isn't reachable", "kind": "askform_offline"})
|
|
|
|
|
|
def link_of(rec: dict) -> str:
|
|
"""The respondent link that works from anywhere, when the hub knows one."""
|
|
return rec.get("publicUrl") or rec.get("url") or ""
|
|
|
|
|
|
def _origin(url: str) -> str:
|
|
p = urlsplit(url or "")
|
|
return f"{p.scheme}://{p.netloc}".lower() if p.scheme and p.netloc else ""
|
|
|
|
|
|
def hub_origins() -> list[str]:
|
|
"""The hub's own sites — the owner's app and the guests' — which every
|
|
machine is asked to let frame its forms (the mirror's ``check_embed``)."""
|
|
from users.deliver import GUEST_PUBLIC_URL
|
|
return [o for o in dict.fromkeys((_origin(VIEW_URL), _origin(GUEST_PUBLIC_URL))) if o]
|
|
|
|
|
|
def embed_origins(deps: AppState, rec: dict) -> list[str]:
|
|
"""Who may frame this form's pages: its machine's ask-form, as last read."""
|
|
mirror = getattr(deps, "askform_mirror", None)
|
|
return mirror.embed_origins(rec.get("machine") or "") if mirror else []
|
|
|
|
|
|
def is_owner_only(rec: dict | None) -> bool:
|
|
"""True when a form is marked owner-only in its metadata (e.g. an approval
|
|
form triggered by a guest's request — only the owner sees or answers it)."""
|
|
if not isinstance(rec, dict):
|
|
return False
|
|
meta = rec.get("meta")
|
|
return bool(isinstance(meta, dict) and _flag(meta.get("ownerOnly")))
|
|
|
|
|
|
def _flag(v) -> bool:
|
|
"""A meta switch: ask-form keeps meta as strings (``"true"``); a record
|
|
mirrored before that may hold a real boolean."""
|
|
return v is True or (isinstance(v, str) and v.strip().lower() in ("true", "1", "yes"))
|
|
|
|
|
|
def meta_strings(meta: dict | None) -> dict[str, str]:
|
|
"""``meta`` as the ask-form server takes it — every value a string (its
|
|
``createReq.meta`` is ``map[string]string``, anything else is a 400): a
|
|
true switch → ``"true"``, a false or empty one left out (absent = off),
|
|
numbers as text, lists and objects as JSON."""
|
|
out: dict[str, str] = {}
|
|
for k, v in (meta or {}).items():
|
|
if v is None or v is False:
|
|
continue
|
|
if v is True:
|
|
out[str(k)] = "true"
|
|
elif isinstance(v, str):
|
|
out[str(k)] = v
|
|
elif isinstance(v, (dict, list)):
|
|
out[str(k)] = json.dumps(v, ensure_ascii=False, separators=(",", ":"))
|
|
else:
|
|
out[str(k)] = str(v)
|
|
return out
|
|
|
|
|
|
def _event_payload(rec: dict) -> dict:
|
|
"""Payload dispatched to dependent plugins subscribing to
|
|
``plugin:ask-form:form.{created,submitted,cancelled}``."""
|
|
return {
|
|
"id": rec.get("id") or "",
|
|
"formId": rec.get("id") or "",
|
|
"title": rec.get("title") or "",
|
|
"description": rec.get("description") or "",
|
|
"status": rec.get("status") or "",
|
|
"sessionId": rec.get("sessionId") or "",
|
|
"answers": rec.get("answers") if isinstance(rec.get("answers"), dict) else {},
|
|
"reason": rec.get("reason") or "",
|
|
"meta": rec.get("meta") if isinstance(rec.get("meta"), dict) else {},
|
|
"url": rec.get("url") or "",
|
|
"publicUrl": rec.get("publicUrl") or "",
|
|
"createdAt": rec.get("createdAt") or "",
|
|
"closedAt": rec.get("closedAt") or "",
|
|
"ownerOnly": is_owner_only(rec),
|
|
}
|
|
|
|
|
|
def _emit_created(deps: AppState, rec: dict) -> None:
|
|
fid = rec.get("id") or ""
|
|
if not fid or not deps.askform_store.claim_event(fid, "evCreated"):
|
|
return
|
|
try:
|
|
from plugins.scheduler import dispatch_event
|
|
from plugins.store import OWNER_UID
|
|
dispatch_event(deps, "plugin:ask-form:form.created", _event_payload(rec),
|
|
owner_uid=OWNER_UID, source_plugin="ask-form")
|
|
except Exception:
|
|
log.exception("askform: emit created for %s", fid)
|
|
|
|
|
|
def _emit_closed(deps: AppState, rec: dict) -> None:
|
|
fid = rec.get("id") or ""
|
|
status = rec.get("status") or ""
|
|
if not fid or status in ("", "pending"):
|
|
return
|
|
if not deps.askform_store.claim_event(fid, "evClosed"):
|
|
return
|
|
ev = "plugin:ask-form:form.submitted" if status in ("submitted", "answered") else "plugin:ask-form:form.cancelled"
|
|
try:
|
|
from plugins.scheduler import dispatch_event
|
|
from plugins.store import OWNER_UID
|
|
dispatch_event(deps, ev, _event_payload(rec),
|
|
owner_uid=OWNER_UID, source_plugin="ask-form")
|
|
except Exception:
|
|
log.exception("askform: emit %s for %s", ev, fid)
|
|
|
|
|
|
def on_mirror_new(deps: AppState, rec: dict) -> None:
|
|
"""Mirror callback when a newly seen pending form is discovered."""
|
|
push_new(deps, rec)
|
|
_emit_created(deps, rec)
|
|
|
|
|
|
def on_mirror_closed(deps: AppState, rec: dict) -> None:
|
|
"""Mirror callback when a form is seen in a non-pending status."""
|
|
from users import deliver
|
|
sid = "" if is_owner_only(rec) else (rec.get("sessionId") or "")
|
|
deliver.clear(deps, sid, rec["id"], "form")
|
|
_emit_closed(deps, rec)
|
|
|
|
|
|
def push_new(deps: AppState, rec: dict) -> None:
|
|
"""The "📋 title" push for a form that just opened — once per form, and
|
|
only for a fresh one. It opens the app on the form's conversation with the
|
|
form over it (``?form=<id>``) when the form's machine lets the app frame
|
|
its pages; else the form's own page (ask-form.xyz), answerable from the
|
|
phone with no login; without a known link, the conversation (its card
|
|
shows the link)."""
|
|
if rec.get("status") != "pending":
|
|
return
|
|
meta = rec.get("meta") if isinstance(rec.get("meta"), dict) else {}
|
|
if _flag(meta.get("noPush")):
|
|
return
|
|
created = parse_iso(rec.get("createdAt"))
|
|
if created is not None and time.time() - created > FRESH_S:
|
|
return
|
|
if not deps.askform_store.claim_push(rec["id"]):
|
|
return
|
|
owner_only = is_owner_only(rec)
|
|
sid = rec.get("sessionId") or ""
|
|
conv, link = _conversation_url(deps, sid), link_of(rec)
|
|
if link and "/conversation/" in conv and _origin(VIEW_URL) in embed_origins(deps, rec):
|
|
# Its machine lets the app frame it: the app, the form open over its
|
|
# conversation (FormModal → AskFormFrame); a guest's push gets the
|
|
# same path on their host (deliver.guest_url).
|
|
url = f"{conv}?form={rec['id']}"
|
|
else:
|
|
url = link or conv
|
|
def note(lang: str) -> dict:
|
|
return {"title": "📋 " + (rec.get("title") or rec["id"]),
|
|
"message": rec.get("description") or (
|
|
tr(lang, "Share the link, then the answers come in")
|
|
if rec.get("multi") else tr(lang, "Tap to answer"))}
|
|
try:
|
|
from users.caller import OWNER_ID
|
|
payload = {
|
|
**note("en"), "type": "ai", "url": url,
|
|
# An owner-only form (e.g. approval for a guest's request) must
|
|
# NEVER stamp onto the guest's conversation feed or push to them.
|
|
"sessionId": "" if owner_only else sid,
|
|
"pushKind": "form",
|
|
"tag": rec["id"],
|
|
**({"recipients": [OWNER_ID]} if owner_only else {}),
|
|
# The fallback line is the app's: per guest.
|
|
**({} if rec.get("description") or owner_only
|
|
else {"i18n": localized(note)}),
|
|
}
|
|
_create_notify(deps, payload)
|
|
except Exception:
|
|
log.exception("askform: push for %s", rec["id"])
|
|
|
|
|
|
def create_form(deps: AppState, body: dict, *, machine: str = LAB) -> dict:
|
|
"""Create a form on ``machine`` (default: the lab's ``ask-form serve``)
|
|
via its sidecar ``POST /ask-form/forms``, mirror it immediately, push if
|
|
not suppressed by ``meta.noPush``, and emit ``form.created``."""
|
|
m = _machine(deps, machine)
|
|
if isinstance(body.get("meta"), dict):
|
|
body = {**body, "meta": meta_strings(body["meta"])}
|
|
out = sidecar_request(m["url"], m["token"], "/ask-form/forms", body,
|
|
method="POST", timeout=12, label=m["label"])
|
|
rec, new, changed = take(deps, m, out)
|
|
if rec.get("status") == "pending":
|
|
push_new(deps, rec)
|
|
_emit_created(deps, rec)
|
|
if new or changed:
|
|
_publish(deps, rec)
|
|
return rec
|
|
|
|
|
|
def ingest_event(deps: AppState, machine: str, event: str, form: dict) -> dict:
|
|
"""An `ask-form serve` event (the webhook, or a worker's outbox item):
|
|
mirror the form, push on its creation, tell the viewer."""
|
|
# A guest's computer's events come through its outbox, which only lets
|
|
# its own sessions' through (guests.outbox_allowed) — the store still
|
|
# refuses it another machine's record (ValueError).
|
|
rec, new, changed = deps.askform_store.upsert(machine, form,
|
|
trusted=_trusted(deps, machine))
|
|
if event == "created" or (new and rec.get("status") == "pending"):
|
|
push_new(deps, rec)
|
|
_emit_created(deps, rec)
|
|
elif rec.get("status") not in (None, "", "pending"):
|
|
# Answered, closed or revoked: off the devices it was pushed to (once).
|
|
if changed:
|
|
from users import deliver
|
|
sid = "" if is_owner_only(rec) else (rec.get("sessionId") or "")
|
|
deliver.clear(deps, sid, rec["id"], "form")
|
|
_emit_closed(deps, rec)
|
|
if changed or new:
|
|
deps.hub.publish({"type": "askform", "id": rec["id"],
|
|
"sessionId": rec.get("sessionId") or "",
|
|
"status": rec.get("status")})
|
|
return rec
|
|
|
|
|
|
def ingest_outbox(deps: AppState, d: dict) -> dict:
|
|
"""The outbox mirror's create hook for a worker's ``askform`` item."""
|
|
form = d.get("form") if isinstance(d.get("form"), dict) else None
|
|
if not form:
|
|
raise HTTPException(400, "askform event without a form")
|
|
try:
|
|
rec = ingest_event(deps, str(d.get("worker") or ""), str(d.get("event") or ""), form)
|
|
except ValueError as e: # not an id, or a record this machine may not touch
|
|
raise HTTPException(400, str(e))
|
|
return {"id": d.get("id"), "ok": True, "form": rec["id"]}
|
|
|
|
|
|
def refresh(deps: AppState, fid: str, *, fields: bool = False) -> dict:
|
|
"""Re-read one form from its machine (``fields``: with its spec)."""
|
|
rec = _known(deps, fid)
|
|
m = _machine(deps, rec.get("machine") or "")
|
|
qs = "?fields=1" if fields else ""
|
|
out = sidecar_request(m["url"], m["token"], f"/ask-form/forms/{fid}{qs}", None,
|
|
method="GET", timeout=8, label=m["label"])
|
|
rec, _, changed = take(deps, m, out)
|
|
if changed:
|
|
_publish(deps, rec)
|
|
return rec
|
|
|
|
|
|
def recheck(deps: AppState, fid: str) -> dict:
|
|
"""Re-read one form from its machine *now*, for a viewer that knows it
|
|
just moved: the app heard its framed page say the answers went through,
|
|
or came back from the form's own tab. The events webhook would say the
|
|
same, but it waits behind the hub's queue (seconds when the box is busy).
|
|
A form that left ``pending`` here does what ``ingest_event`` does for
|
|
one: its push comes off the devices (whichever of the two sees the
|
|
change first does it; the other sees nothing new)."""
|
|
was = _known(deps, fid).get("status")
|
|
rec = refresh(deps, fid)
|
|
if was == "pending" and rec.get("status") not in (None, "", "pending"):
|
|
from users import deliver
|
|
sid = "" if is_owner_only(rec) else (rec.get("sessionId") or "")
|
|
deliver.clear(deps, sid, rec["id"], "form")
|
|
_emit_closed(deps, rec)
|
|
return rec
|
|
|
|
|
|
def with_fields(deps: AppState, fid: str) -> dict:
|
|
rec = _known(deps, fid)
|
|
if rec.get("fields") or not rec.get("machine"):
|
|
return rec
|
|
try:
|
|
return refresh(deps, fid, fields=True)
|
|
except HTTPException:
|
|
return rec # offline machine: the record as mirrored, no spec
|
|
|
|
|
|
def end(deps: AppState, fid: str, *, close: bool = False) -> dict:
|
|
"""Revoke a form (or close a multi one) on the machine that holds it."""
|
|
rec = _known(deps, fid)
|
|
m = _machine(deps, rec.get("machine") or "")
|
|
verb = "close" if close else "revoke"
|
|
out = sidecar_request(m["url"], m["token"], f"/ask-form/forms/{fid}/{verb}", {},
|
|
timeout=8, label=m["label"])
|
|
rec, _, changed = take(deps, m, out)
|
|
if changed:
|
|
_publish(deps, rec)
|
|
if rec.get("status") not in (None, "", "pending"):
|
|
from users import deliver
|
|
sid = "" if is_owner_only(rec) else (rec.get("sessionId") or "")
|
|
deliver.clear(deps, sid, rec["id"], "form")
|
|
_emit_closed(deps, rec)
|
|
deps.askform_mirror.poke(m["id"])
|
|
return rec
|
|
|
|
|
|
def _known(deps: AppState, fid: str) -> dict:
|
|
if not ID_RE.match(fid or ""):
|
|
raise HTTPException(400, f"not an ask-form id: {fid!r}")
|
|
rec = deps.askform_store.get(fid)
|
|
if not rec:
|
|
raise HTTPException(404, f"unknown form {fid}")
|
|
return rec
|
|
|
|
|
|
def _publish(deps: AppState, rec: dict) -> None:
|
|
deps.hub.publish({"type": "askform", "id": rec["id"],
|
|
"sessionId": rec.get("sessionId") or "",
|
|
"status": rec.get("status")})
|
|
|
|
|
|
# ── the view ─────────────────────────────────────────────────────────────────
|
|
def visible(deps: AppState, caller: Caller, rec: dict | None) -> dict:
|
|
"""404 (never 403) for a guest outside the form's conversation or on an
|
|
owner-only form."""
|
|
if not rec:
|
|
raise HTTPException(404, "unknown form")
|
|
if not caller.is_owner:
|
|
if is_owner_only(rec):
|
|
raise HTTPException(404, "unknown form")
|
|
sid = rec.get("sessionId") or ""
|
|
if not sid or not access.visible(deps, caller, sid):
|
|
raise HTTPException(404, "unknown form")
|
|
return rec
|
|
|
|
|
|
def public(deps: AppState, caller: Caller, recs: list[dict], *,
|
|
lite: bool = True) -> list[dict]:
|
|
"""The records as the API serves them: ``conversationId`` (the way back),
|
|
``forYou`` (the caller is in its conversation's audience), ``fieldCount``;
|
|
``lite`` drops the field specs."""
|
|
by_sid = _conv_ids_by_session(deps) if any(r.get("sessionId") for r in recs) else {}
|
|
out = []
|
|
for r in recs:
|
|
r = dict(r)
|
|
sid = r.get("sessionId") or ""
|
|
if is_owner_only(r):
|
|
r["forYou"] = caller.is_owner
|
|
r["ownerOnly"] = True
|
|
else:
|
|
r["forYou"] = access.hears(caller, deps.meta_store.peek(sid)) if sid else caller.is_owner
|
|
cid = by_sid.get(sid) if sid else None
|
|
if cid:
|
|
r["conversationId"] = cid
|
|
if r.get("fields") is not None:
|
|
r["fieldCount"] = len(r["fields"])
|
|
frame = embed_origins(deps, r)
|
|
if frame:
|
|
r["embedOrigins"] = frame
|
|
if lite:
|
|
r.pop("fields", None)
|
|
r.pop("placeholder", None)
|
|
r.pop("evCreated", None)
|
|
r.pop("evClosed", None)
|
|
out.append(r)
|
|
return out
|