cauldron/cauldron/server.py
Kayos d649b99aef v0.3 step 5: lean shopping list — claude on-demand foods + game strip
Two changes:

1. foods catalog grows organically. Switch the canonical seed from the
   noisy USDA dump (2462 rows of "'s, classic chicken noodle soup")
   to the Sonnet-curated cut (229 clean rows). search_food() is now
   exact + case-insensitive — Mealie's parser already canonicalizes
   food names household-side, so cauldron just needs to look them up
   verbatim. On miss, the /list view calls forge.fetch_food_info() to
   ask Sonnet for {density_g_per_ml, default_unit_class, common_size_g,
   category}, persists the row with source='claude', and the household's
   actual kitchen catalog builds itself out as Abby uses it.

   Killer case verified end-to-end: "2 cups + 50g + 1.25 lb rice"
   collapses to a single "2.25 lb rice" line on the shopping list once
   rice has a density row.

2. Game system stripped from /plan. Scoreboard panel, streak banner,
   "first to lock takes the week" / "🏆 you locked this one in" copy
   all gone. award_pick_points calls in /api/plan/generate +
   /api/plan/regenerate stopped firing. household_scoreboard /
   household_streak DB methods kept as dead code; cauldron_pick_points
   table left in place — non-destructive, easy to revive later if
   gamification comes back. Goal: get the base flow (pick → plan →
   list) working for Abby first, layer features on after.
2026-04-29 22:02:20 -07:00

1001 lines
36 KiB
Python

"""Flask app — v0.2 foundation.
Adds Authentik OIDC + sulkta-mariadb DB + Fernet crypto for per-user Mealie
tokens. v0.1 admin endpoints stay (still bearer-gated for now); user-facing
routes start using OIDC sessions.
Routes (current):
GET /healthz liveness, no auth
GET / redirects to /login if no session,
else /me
GET /login start OIDC flow
GET /auth/callback OIDC callback
POST /logout clear session
GET /me "who am I" page (json for now)
GET /connect-mealie prompt for Mealie token
POST /connect-mealie store encrypted token
POST /disconnect-mealie delete encrypted token
GET /api/recipes (admin bearer) proxy Mealie list
POST /api/sterilize/preview/<slug> (admin bearer) v0.1 sterilizer
POST /api/sterilize/apply/<slug> (admin bearer) v0.1 sterilizer
"""
from datetime import date, datetime, timedelta
from functools import wraps
from flask import Flask, jsonify, redirect, render_template, request, session, url_for
from .config import load
from .crypto import TokenCrypto
from .db import DB
from .forge import Forge, ForgeError
from . import aggregator, foods
from .mealie import Mealie, MealieError
from .oidc import init_oauth
from .recipe_index import flatten_recipe, refresh_household_index, search_index
from .sterilizer import Sterilizer
cfg = load()
db = DB(host=cfg.db_host, port=cfg.db_port, name=cfg.db_name, user=cfg.db_user, password=cfg.db_password)
crypto = TokenCrypto(cfg.fernet_key)
forge = Forge(
base_url=cfg.clawdforge_url,
token=cfg.clawdforge_token,
default_model=cfg.default_model,
default_timeout=cfg.default_timeout_secs,
)
# System-tier Mealie client (Cobb's "Cauldron" token; admin batch ops only)
system_mealie = Mealie(base_url=cfg.mealie_api_url, api_token=cfg.mealie_api_token)
system_sterilizer = Sterilizer(mealie=system_mealie, forge=forge, model=cfg.default_model)
def create_app() -> Flask:
app = Flask(__name__)
app.secret_key = cfg.secret_key
app.config.update(
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
# NOT setting SESSION_COOKIE_SECURE=True — LAN is plain HTTP for now.
# If we ever front this with TLS, flip secure=True.
)
# Apply migrations on startup
applied = db.migrate()
if applied:
app.logger.info("applied migrations: %s", applied)
# Seed cauldron_foods from the USDA snapshot if empty
try:
loaded = foods.load_seed_if_empty(db)
if loaded:
app.logger.info("loaded %d foods from USDA seed", loaded)
except Exception as e:
app.logger.warning("foods seed load failed: %s", e)
oauth = init_oauth(
app,
issuer=cfg.oidc_issuer,
client_id=cfg.oidc_client_id,
client_secret=cfg.oidc_client_secret,
)
# ---------- helpers --------------------------------------------------
def require_bearer(fn):
@wraps(fn)
def w(*a, **kw):
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer "):
return jsonify({"error": "missing bearer"}), 401
tok = auth[7:].strip()
if not _const_eq(tok, cfg.admin_bearer):
return jsonify({"error": "forbidden"}), 403
return fn(*a, **kw)
return w
def require_session(fn):
@wraps(fn)
def w(*a, **kw):
if not session.get("user"):
return redirect(url_for("login", next=request.path))
return fn(*a, **kw)
return w
def current_user_mealie() -> Mealie | None:
u = session.get("user")
if not u:
return None
blob = db.get_user_mealie_token_blob(u["sub"])
if not blob:
return None
try:
tok = crypto.decrypt(blob)
except Exception:
return None
return Mealie(base_url=cfg.mealie_api_url, api_token=tok)
def sync_user_household(sub: str) -> int | None:
"""Pull the user's Mealie household, upsert into cauldron, ensure
membership. Idempotent. Returns local household_id or None.
Mealie's user-self response shape varies across versions — the
`household` field can be a dict (with id+name+slug), a plain
slug-string, or absent. We also accept top-level householdId /
householdSlug. If we can't resolve a real ID, fall back to slug.
"""
client = current_user_mealie()
if not client:
return None
try:
me = client.who_am_i()
except Exception:
return None
h = me.get("household")
h_id_mealie: str | None = None
h_name: str | None = None
if isinstance(h, dict):
h_id_mealie = h.get("id") or h.get("slug")
h_name = h.get("name") or h.get("slug")
elif isinstance(h, str) and h:
# newer Mealie versions return household as a slug string
h_id_mealie = h
h_name = h
# Fall back to top-level fields
h_id_mealie = h_id_mealie or me.get("householdId") or me.get("household_id") or me.get("householdSlug") or me.get("household_slug")
h_name = h_name or me.get("householdName") or h_id_mealie or "default"
if not h_id_mealie:
return None
local_id = db.upsert_household(mealie_household_id=str(h_id_mealie), name=str(h_name))
existing = db.list_household_member_subs(local_id)
role = "admin" if not existing else "member"
db.add_household_member(local_id, sub, role=role)
return local_id
def current_household_id() -> int | None:
u = session.get("user")
if not u:
return None
h = db.get_user_household_id(u["sub"])
if h is None:
h = sync_user_household(u["sub"])
return h
def monday_of(d: date) -> date:
return d - timedelta(days=d.weekday())
# ---------- public ---------------------------------------------------
@app.get("/healthz")
def healthz():
upstream = {}
try:
upstream["clawdforge"] = forge.healthz()
except Exception as e:
upstream["clawdforge_error"] = str(e)
try:
with db.conn() as c, c.cursor() as cur:
cur.execute("SELECT 1 AS ok")
cur.fetchone()
upstream["db"] = "ok"
except Exception as e:
upstream["db_error"] = str(e)
return jsonify({"ok": True, "upstream": upstream})
@app.get("/")
def index():
if not session.get("user"):
return redirect(url_for("login"))
return redirect(url_for("me"))
@app.get("/login")
def login():
# Stash where to go after login
nxt = request.args.get("next") or "/me"
session["post_login_next"] = nxt
return oauth.cauldron.authorize_redirect(cfg.oidc_redirect_uri)
@app.get("/auth/callback")
def auth_callback():
token = oauth.cauldron.authorize_access_token()
userinfo = token.get("userinfo") or oauth.cauldron.userinfo(token=token)
sub = userinfo.get("sub") or userinfo.get("email")
email = userinfo.get("email") or sub
name = userinfo.get("name") or userinfo.get("preferred_username")
if not sub or not email:
return ("missing sub/email in userinfo", 400)
db.upsert_user(sub=sub, email=email, display_name=name)
session["user"] = {"sub": sub, "email": email, "name": name}
return redirect(session.pop("post_login_next", "/me"))
@app.post("/logout")
def logout():
session.clear()
return redirect(url_for("login"))
@app.get("/me")
@require_session
def me():
u = session["user"]
connected = db.get_user_mealie_token_blob(u["sub"]) is not None
mealie_user = None
household_size = 0
if connected:
client = current_user_mealie()
if client:
try:
mealie_user = client.who_am_i()
except Exception:
mealie_user = None
# Lazy-sync household if not done yet
hid = current_household_id()
if hid:
household_size = len(db.list_household_member_subs(hid))
return render_template(
"me.html",
user=u, connected=connected, mealie_user=mealie_user,
household_size=household_size, active="me",
)
@app.get("/me.json")
@require_session
def me_json():
u = session["user"]
connected = db.get_user_mealie_token_blob(u["sub"]) is not None
return jsonify({"user": u, "mealie_connected": connected})
# ---------- mealie connect flow --------------------------------------
@app.get("/connect-mealie")
@require_session
def connect_mealie_get():
u = session["user"]
return render_template(
"connect.html",
user=u,
mealie_url=cfg.mealie_public_url,
active="me",
)
@app.post("/connect-mealie")
@require_session
def connect_mealie_post():
u = session["user"]
token = (request.form.get("mealie_token") or "").strip()
if not token:
return ("empty token", 400)
# Validate against Mealie before storing — don't persist a bad token
test = Mealie(base_url=cfg.mealie_api_url, api_token=token)
try:
test.who_am_i()
except MealieError as e:
return (f"token rejected by Mealie: {e}", 400)
blob = crypto.encrypt(token)
db.set_user_mealie_token_blob(u["sub"], blob)
# Sync household membership so the user immediately joins the shared
# picks pool + scoreboard (no manual admin step needed for first member).
sync_user_household(u["sub"])
return redirect(url_for("me"))
@app.post("/disconnect-mealie")
@require_session
def disconnect_mealie():
u = session["user"]
db.delete_user_mealie_token(u["sub"])
return redirect(url_for("me"))
# ---------- recipes (user-tier) --------------------------------------
@app.get("/recipes")
@require_session
def recipes_list():
client = current_user_mealie()
if not client:
return redirect(url_for("connect_mealie_get"))
u = session["user"]
sort = request.args.get("sort", "newest")
category = (request.args.get("cat") or "").strip()
per_page = 24
hid = current_household_id()
# Lazy refresh
state = db.get_index_state(hid) if hid else None
if hid and (not state or _index_stale(state)):
try:
refresh_household_index(mealie_client=client, db=db, household_id=hid)
state = db.get_index_state(hid)
except Exception as e:
app.logger.warning("recipe index refresh failed: %s", e)
# Categories for chips (still from Mealie — they're per-household)
categories: list[dict] = []
try:
cat_data = client.list_categories()
categories = cat_data.get("items") or []
except Exception:
pass
order_by_local, order_dir_local = _sort_to_local_order(sort)
items: list[dict] = []
total = 0
if hid:
rows = db.list_indexed_recipes(
hid, category=category or None,
order_by=order_by_local, order_dir=order_dir_local,
limit=per_page, offset=0,
)
pick_slugs = db.list_household_pick_slugs(hid)
items = [_index_row_to_card(r, pick_slugs) for r in rows]
total = (state or {}).get("recipe_count") or len(items)
pages = max(1, (total + per_page - 1) // per_page)
return render_template(
"recipes.html",
recipes=items, total=total, pages=pages,
sort=sort, category=category,
categories=categories,
active="recipes",
)
@app.get("/api/recipes.json")
@require_session
def recipes_json():
"""Recipes endpoint for the AJAX path. Two modes:
1. SEARCH (q given): hits the local cauldron_recipe_index, fuzzy-
ranks via rapidfuzz with multi-field weighting. Returns ranked
list, page=1 of however-many-matched. Refreshes index lazily
if stale (>5min) or empty.
2. BROWSE (no q): reads from local index ordered by sort key,
paginated. Falls back to Mealie if the index is empty (first
load before refresh completes).
"""
client = current_user_mealie()
if not client:
return jsonify({"error": "not connected"}), 409
u = session["user"]
page = max(1, int(request.args.get("page", "1")))
search = (request.args.get("q") or "").strip()
sort = request.args.get("sort", "newest")
category = (request.args.get("cat") or "").strip() or None
order_by_local, order_dir_local = _sort_to_local_order(sort)
per_page = 24
hid = current_household_id()
if not hid:
return jsonify({"items": [], "total": 0, "total_pages": 1, "next": None})
# Lazy index refresh
state = db.get_index_state(hid)
is_stale = (not state) or _index_stale(state)
if is_stale:
try:
refresh_household_index(mealie_client=client, db=db, household_id=hid)
except Exception as e:
app.logger.warning("recipe index refresh failed: %s", e)
pick_slugs = db.list_household_pick_slugs(hid)
if search:
# Pull all rows for the household, fuzzy-rank
rows = db.list_indexed_recipes(hid, category=category, limit=2000, offset=0)
ranked = search_index(rows, search, limit=80)
start = (page - 1) * per_page
slice_ = ranked[start:start + per_page]
items = [_index_row_to_card(r, pick_slugs) for r in slice_]
total = len(ranked)
total_pages = max(1, (total + per_page - 1) // per_page)
return jsonify({
"items": items,
"page": page,
"total": total,
"total_pages": total_pages,
"next": page + 1 if page < total_pages else None,
"scored": True,
})
# Browse mode
offset = (page - 1) * per_page
rows = db.list_indexed_recipes(
hid, category=category,
order_by=order_by_local, order_dir=order_dir_local,
limit=per_page + 1, offset=offset,
)
has_next = len(rows) > per_page
rows = rows[:per_page]
items = [_index_row_to_card(r, pick_slugs) for r in rows]
# total — cheap-ish: count only when we don't already know
total = (state or {}).get("recipe_count") or len(items)
total_pages = max(1, (total + per_page - 1) // per_page)
return jsonify({
"items": items,
"page": page,
"total": total,
"total_pages": total_pages,
"next": page + 1 if has_next else None,
"scored": False,
})
@app.post("/api/index/refresh")
@require_session
def index_refresh():
client = current_user_mealie()
hid = current_household_id()
if not client or not hid:
return jsonify({"error": "not ready"}), 409
try:
n = refresh_household_index(mealie_client=client, db=db, household_id=hid)
return jsonify({"ok": True, "count": n})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 502
@app.post("/api/picks/<slug>")
@require_session
def add_pick(slug: str):
u = session["user"]
name = (request.json or {}).get("name", "") if request.is_json else request.form.get("name", "")
if not name:
# Look it up from Mealie if missing
client = current_user_mealie()
if client:
try:
r = client.get_recipe(slug)
name = r.get("name") or slug
except Exception:
name = slug
else:
name = slug
added = db.add_meal_pick(u["sub"], slug, name)
return jsonify({"ok": True, "added": added, "slug": slug})
@app.delete("/api/picks/<slug>")
@require_session
def del_pick(slug: str):
u = session["user"]
removed = db.remove_meal_pick(u["sub"], slug)
return jsonify({"ok": True, "removed": removed, "slug": slug})
@app.get("/api/picks.json")
@require_session
def list_picks_json():
u = session["user"]
return jsonify({"picks": db.list_meal_picks(u["sub"])})
@app.get("/picks")
@require_session
def picks_view():
u = session["user"]
hid = current_household_id()
picks = db.list_household_picks_with_pickers(hid) if hid else []
my_picks = db.list_meal_pick_slugs(u["sub"])
for p in picks:
p["mine"] = p["slug"] in my_picks
return render_template(
"picks.html",
picks=picks,
active="picks",
household_size=len(db.list_household_member_subs(hid)) if hid else 0,
)
@app.get("/plan")
@require_session
def plan_view():
u = session["user"]
hid = current_household_id()
if not hid:
return redirect(url_for("connect_mealie_get"))
today = date.today()
this_monday = monday_of(today)
# Auto-lock any past unlocked weeks before reading
db.auto_lock_past_unlocked_plans(hid, this_monday)
plan = db.get_or_create_plan(hid, this_monday)
db.enrich_plan_with_slots(plan)
pick_count = len(db.list_household_pick_slugs(hid))
# Resolve display names for any subs we render — locked_by + every
# picker referenced by any slot. One round-trip; small set.
sub_display: dict[str, str] = _resolve_sub_displays(db, plan)
locked_by_display = None
if plan.get("locked_by_sub"):
locked_by_display = sub_display.get(plan["locked_by_sub"])
generated_by_display = None
if plan.get("generated_by_sub"):
generated_by_display = sub_display.get(plan["generated_by_sub"])
return render_template(
"plan.html",
week_start=plan["week_start"],
plan=plan,
locked_by_display=locked_by_display,
generated_by_display=generated_by_display,
sub_display=sub_display,
current_user_sub=u["sub"],
pick_count=pick_count,
active="plan",
)
@app.post("/api/plan/lock")
@require_session
def plan_lock():
u = session["user"]
hid = current_household_id()
if not hid:
return jsonify({"error": "no household"}), 409
today = date.today()
this_monday = monday_of(today)
plan = db.get_or_create_plan(hid, this_monday)
if plan.get("locked_at"):
return jsonify({"ok": False, "already_locked": True, "by": plan.get("locked_by_sub")})
updated = db.lock_plan(plan["id"], sub=u["sub"], reason="user")
return jsonify({"ok": True, "locked_at": updated["locked_at"].isoformat() if updated["locked_at"] else None})
@app.post("/api/plan/generate")
@require_session
def plan_generate():
u = session["user"]
hid = current_household_id()
if not hid:
return jsonify({"error": "no household"}), 409
today = date.today()
this_monday = monday_of(today)
plan = db.get_or_create_plan(hid, this_monday)
if plan.get("locked_at"):
return jsonify({
"error": "plan_locked",
"locked_by_sub": plan.get("locked_by_sub"),
"locked_at": plan["locked_at"].isoformat() if plan.get("locked_at") else None,
}), 409
# Idempotency / race: if slots already exist, return them. Two
# concurrent generators end up with the first writer's slots; the
# second sees them and returns 409 with the existing plan.
existing = db.list_plan_slots(plan["id"])
if existing:
db.enrich_plan_with_slots(plan)
return jsonify({
"error": "plan_already_generated",
"plan": _plan_payload(plan),
}), 409
# Pull picks (with picker_subs) + recipe pool (slug+name+tags only)
picks = db.list_household_picks_with_pickers(hid)
rows = db.list_indexed_recipes(hid, limit=2000, offset=0)
recipes = []
for r in rows:
tags = []
raw = r.get("raw_json")
if isinstance(raw, str):
try:
raw = _json_loads(raw)
except Exception:
raw = None
if isinstance(raw, dict):
tags = raw.get("tags") or []
recipes.append({"slug": r["slug"], "name": r["name"], "tags": tags})
if not recipes:
return jsonify({"error": "no_recipes_indexed"}), 409
try:
slots = forge.generate_plan(
picks=picks, recipes=recipes,
slots=7, week_start=this_monday.isoformat(),
)
except ForgeError as e:
return jsonify({"error": "forge_failed", "detail": str(e)}), 502
inserted = db.save_plan_slots(plan["id"], slots)
if inserted == 0:
# Race lost — re-read and return the winner's plan
db.enrich_plan_with_slots(plan)
return jsonify({
"error": "plan_already_generated",
"plan": _plan_payload(plan),
}), 409
plan = db.mark_plan_generated(plan["id"], u["sub"])
db.enrich_plan_with_slots(plan)
return jsonify({"ok": True, "plan": _plan_payload(plan)})
@app.post("/api/plan/regenerate")
@require_session
def plan_regenerate():
"""Re-roll: only the original generator can do this, only before
lock. Wipes slots + pick_points for this plan, then reuses the
generate path. Defensive — returns 409 on lock or wrong owner."""
u = session["user"]
hid = current_household_id()
if not hid:
return jsonify({"error": "no household"}), 409
today = date.today()
this_monday = monday_of(today)
plan = db.get_or_create_plan(hid, this_monday)
if plan.get("locked_at"):
return jsonify({"error": "plan_locked"}), 409
if not plan.get("generated_at"):
# Nothing to re-roll — caller probably wanted plain /generate
return jsonify({"error": "plan_not_generated"}), 409
if plan.get("generated_by_sub") != u["sub"]:
return jsonify({"error": "not_generator"}), 403
db.delete_plan_slots(plan["id"])
db.clear_plan_generated(plan["id"])
# Now fall through to the same logic as generate
picks = db.list_household_picks_with_pickers(hid)
rows = db.list_indexed_recipes(hid, limit=2000, offset=0)
recipes = []
for r in rows:
tags = []
raw = r.get("raw_json")
if isinstance(raw, str):
try:
raw = _json_loads(raw)
except Exception:
raw = None
if isinstance(raw, dict):
tags = raw.get("tags") or []
recipes.append({"slug": r["slug"], "name": r["name"], "tags": tags})
if not recipes:
return jsonify({"error": "no_recipes_indexed"}), 409
try:
slots = forge.generate_plan(
picks=picks, recipes=recipes,
slots=7, week_start=this_monday.isoformat(),
)
except ForgeError as e:
return jsonify({"error": "forge_failed", "detail": str(e)}), 502
db.save_plan_slots(plan["id"], slots)
plan = db.mark_plan_generated(plan["id"], u["sub"])
db.enrich_plan_with_slots(plan)
return jsonify({"ok": True, "plan": _plan_payload(plan)})
@app.get("/list")
@require_session
def list_view():
u = session["user"]
hid = current_household_id()
if not hid:
return redirect(url_for("connect_mealie_get"))
today = date.today()
this_monday = monday_of(today)
plan = db.get_or_create_plan(hid, this_monday)
db.enrich_plan_with_slots(plan)
if not plan.get("slots"):
return render_template(
"list.html",
plan=plan, lines=[], active="list",
empty_reason="no_plan",
missing_recipes=[],
)
client = current_user_mealie()
if not client:
return redirect(url_for("connect_mealie_get"))
raw_ings: list[aggregator.Ingredient] = []
missing: list[str] = []
for s in plan["slots"]:
try:
recipe = client.get_recipe(s["recipe_slug"])
except Exception:
missing.append(s["recipe_slug"])
continue
for ri in recipe.get("recipeIngredient", []) or []:
qty = ri.get("quantity")
unit_obj = ri.get("unit") or {}
unit = (unit_obj.get("name") if isinstance(unit_obj, dict) else "") or ""
food_obj = ri.get("food") or {}
food_name = (food_obj.get("name") if isinstance(food_obj, dict) else "") or ""
note = ri.get("note") or ""
if not food_name and not note:
continue
raw_ings.append(aggregator.Ingredient(
qty=float(qty) if qty not in (None, "") else None,
unit=unit,
food_name=food_name or note,
note=note if food_name else None,
source_recipe_slug=s["recipe_slug"],
original_text=ri.get("display") or _ing_render(qty, unit, food_name, note),
))
# foods_lookup: exact match → clawdforge fallback that persists.
# Per-request cache so the same food in multiple recipes isn't
# re-queried within one /list render.
lookup_cache: dict[str, dict | None] = {}
def foods_lookup(name: str):
key = (name or "").strip().lower()
if not key:
return None
if key in lookup_cache:
return lookup_cache[key]
hits = foods.search_food(db, key, limit=1)
if hits:
lookup_cache[key] = hits[0]
return hits[0]
# Miss — ask clawdforge, persist, return. On any failure, cache
# None for this request so we don't spam the model.
try:
info = forge.fetch_food_info(key)
row = foods.upsert_claude_food(
db,
canonical_name=key,
density_g_per_ml=info.get("density_g_per_ml"),
default_unit_class=info.get("default_unit_class") or "mass",
common_size_g=info.get("common_size_g"),
category=info.get("category"),
)
lookup_cache[key] = row
return row
except Exception as exc:
app.logger.warning("forge.fetch_food_info(%r) failed: %s", key, exc)
lookup_cache[key] = None
return None
lines = aggregator.aggregate(raw_ings, foods_lookup)
return render_template(
"list.html",
plan=plan, lines=lines, active="list",
empty_reason=None,
missing_recipes=missing,
)
@app.get("/api/recipes/<slug>.json")
@require_session
def recipe_detail_json(slug: str):
client = current_user_mealie()
if not client:
return jsonify({"error": "not connected"}), 409
u = session["user"]
try:
recipe = client.get_recipe(slug)
except Exception as e:
return jsonify({"error": str(e)}), 502
hid = current_household_id()
recipe["picked"] = slug in db.list_household_pick_slugs(hid) if hid else False
# Mealie's web URL: <public>/g/<group-slug>/r/<recipe-slug>
group_slug = _user_group_slug(client)
mealie_url = (
f"{cfg.mealie_public_url}/g/{group_slug}/r/{slug}"
if group_slug
else f"{cfg.mealie_public_url}/recipe/{slug}"
)
return jsonify({
"recipe": recipe,
"public_url": cfg.mealie_public_url,
"mealie_url": mealie_url,
})
@app.get("/recipes/<slug>")
@require_session
def recipe_detail(slug: str):
client = current_user_mealie()
if not client:
return redirect(url_for("connect_mealie_get"))
u = session["user"]
try:
recipe = client.get_recipe(slug)
except Exception as e:
return (f"recipe load failed: {e}", 502)
picked = slug in db.list_meal_pick_slugs(u["sub"])
group_slug = _user_group_slug(client)
mealie_url = (
f"{cfg.mealie_public_url}/g/{group_slug}/r/{slug}"
if group_slug else f"{cfg.mealie_public_url}/recipe/{slug}"
)
return render_template(
"recipe_detail.html",
recipe=recipe,
public_url=cfg.mealie_public_url,
mealie_url=mealie_url,
picked=picked,
active="recipes",
)
# ---------- v0.1 admin endpoints (carry over) ------------------------
@app.get("/api/recipes")
@require_bearer
def list_recipes_api():
page = int(request.args.get("page", "1"))
per_page = min(int(request.args.get("per_page", "50")), 200)
return jsonify(system_mealie.list_recipes(page=page, per_page=per_page))
@app.post("/api/sterilize/preview/<slug>")
@require_bearer
def sterilize_preview(slug: str):
try:
return jsonify(system_sterilizer.preview_recipe(slug))
except Exception as e:
return jsonify({"error": str(e)}), 502
@app.post("/api/sterilize/apply/<slug>")
@require_bearer
def sterilize_apply(slug: str):
create_missing = request.args.get("create_missing", "true").lower() == "true"
try:
return jsonify(system_sterilizer.apply_recipe(slug, create_missing=create_missing))
except Exception as e:
return jsonify({"error": str(e)}), 502
return app
def _user_group_slug(client) -> str | None:
"""Mealie's recipe permalink lives at /g/<group-slug>/r/<slug>. Pull
the group slug from /api/users/self. Cheap call (Mealie is on the
same docker bridge); could cache in session if it becomes hot."""
try:
me = client.who_am_i()
except Exception:
return None
g = me.get("group")
if isinstance(g, dict):
return g.get("slug") or g.get("name")
if isinstance(g, str) and g:
return g
return me.get("groupSlug") or me.get("group_slug") or me.get("groupName")
def _sort_to_order(sort: str) -> tuple[str, str]:
"""Map our sort keys to Mealie's orderBy + direction."""
return {
"newest": ("created_at", "desc"),
"oldest": ("created_at", "asc"),
"az": ("name", "asc"),
"za": ("name", "desc"),
"made": ("last_made", "desc"),
"updated": ("updated_at", "desc"),
}.get(sort, ("created_at", "desc"))
def _sort_to_local_order(sort: str) -> tuple[str, str]:
"""Same set, but mapped to our cauldron_recipe_index columns."""
return {
"newest": ("date_added", "desc"),
"oldest": ("date_added", "asc"),
"az": ("name", "asc"),
"za": ("name", "desc"),
"made": ("last_made", "desc"),
"updated": ("date_updated", "desc"),
}.get(sort, ("date_added", "desc"))
_INDEX_TTL_SECS = 5 * 60
def _index_stale(state: dict | None) -> bool:
if not state:
return True
last = state.get("last_refreshed_at")
if not last:
return True
from datetime import datetime
age = (datetime.utcnow() - last).total_seconds()
return age > _INDEX_TTL_SECS
def _index_row_to_card(row: dict, pick_slugs: set[str]) -> dict:
"""Index row → recipe card dict the JS frontend expects (matches the
Mealie recipe shape closely enough for renderCard)."""
import json as _json
raw = row.get("raw_json")
if isinstance(raw, str):
try:
raw = _json.loads(raw)
except Exception:
raw = {}
raw = raw or {}
return {
"slug": row["slug"],
"name": row["name"],
"totalTime": row.get("total_time") or raw.get("totalTime"),
"recipeYield": row.get("recipe_yield") or raw.get("recipeYield"),
"dateUpdated": (raw.get("dateUpdated") if raw else None) or (row["date_updated"].isoformat() if row.get("date_updated") else None),
"tags": raw.get("tags") or [],
"picked": row["slug"] in pick_slugs,
}
def _const_eq(a: str, b: str) -> bool:
if len(a) != len(b):
return False
diff = 0
for x, y in zip(a.encode(), b.encode()):
diff |= x ^ y
return diff == 0
def _json_loads(s):
import json as _j
return _j.loads(s)
def _resolve_sub_displays(db, plan: dict) -> dict[str, str]:
"""Return {sub: display_name} for every sub referenced by this plan's
slots + locked_by + generated_by. One DB round-trip; small set."""
subs: set[str] = set()
if plan.get("locked_by_sub"):
subs.add(plan["locked_by_sub"])
if plan.get("generated_by_sub"):
subs.add(plan["generated_by_sub"])
for s in plan.get("slots") or []:
for sub in s.get("picker_subs") or []:
if sub:
subs.add(sub)
if not subs:
return {}
placeholders = ", ".join(["%s"] * len(subs))
out: dict[str, str] = {}
with db.conn() as c, c.cursor() as cur:
cur.execute(
f"SELECT authentik_sub, display_name, email FROM cauldron_users "
f"WHERE authentik_sub IN ({placeholders})",
tuple(subs),
)
for r in cur.fetchall():
sub = r["authentik_sub"]
disp = r.get("display_name")
if not disp:
disp = (r.get("email") or "").split("@")[0]
out[sub] = disp or sub
return out
def _plan_payload(plan: dict) -> dict:
"""JSON-serializable view of a plan dict (datetimes → iso strings)."""
p = dict(plan)
for k in ("week_start", "generated_at", "locked_at"):
v = p.get(k)
if v is not None and hasattr(v, "isoformat"):
p[k] = v.isoformat()
slots = p.get("slots") or []
out_slots = []
for s in slots:
s2 = dict(s)
ca = s2.get("created_at")
if ca is not None and hasattr(ca, "isoformat"):
s2["created_at"] = ca.isoformat()
out_slots.append(s2)
p["slots"] = out_slots
return p
def _ing_render(qty, unit, food_name, note) -> str:
"""Tiny fallback for `display` when Mealie didn't render the line."""
parts: list[str] = []
if qty not in (None, ""):
parts.append(str(qty))
if unit:
parts.append(unit)
if food_name:
parts.append(food_name)
if note and not food_name:
parts.append(note)
return " ".join(parts).strip()
# gunicorn entrypoint
app = create_app()