Files
buryan-infra/ops/home/mealie2grocy.py
T

131 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Mealie (БД) → Grocy (API): рецепт превращается в список покупок."""
import json
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
PG = ("PGPASSWORD='Buryan20261016mrAzbQ5SWdxwYg' psql -h 192.168.1.151 -U postgres "
"-d mealie_db -t -A -F '|'")
GROCY = "http://192.168.1.110:9283"
EMAIL = "roman@buryans.ru"
TOKENS = "/root/.mealie-grocy.json"
def sh(cmd):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60)
return (r.stdout or "").strip()
def grocy(method, path, key, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(GROCY + path, data=data, method=method,
headers={"GROCY-API-KEY": key,
"X-Auth-Request-Email": EMAIL,
"Content-Type": "application/json",
"Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=25) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw else {})
except urllib.error.HTTPError as e:
return e.code, e.read()[:200].decode("utf-8", "replace")
def find_recipe(name):
q = name.replace("'", "''")
out = sh(f"{PG} -c \"select slug||'~'||name from recipes where name ilike '%{q}%' limit 5\"")
rows = [r.split("~", 1) for r in out.splitlines() if "~" in r]
if not rows:
return None, []
exact = [r for r in rows if r[1].lower() == name.lower()]
slug, title = (exact or rows)[0]
return title, ingredient_rows(slug)
def ingredient_rows(slug):
q = slug.replace("'", "''")
sql = ("select coalesce(ri.quantity::text,''), coalesce(u.name,''), "
"coalesce(f.name,''), coalesce(ri.note,''), coalesce(ri.original_text,'') "
"from recipes_ingredients ri "
"left join ingredient_units u on u.id = ri.unit_id "
"left join ingredient_foods f on f.id = ri.food_id "
f"join recipes r on r.id = ri.recipe_id where r.slug = '{q}'")
out = sh(f"{PG} -c \"{sql}\"")
items = []
for line in out.splitlines():
parts = line.split("|")
if len(parts) < 4:
continue
qty, unit, food, note = parts[0], parts[1], parts[2], parts[3]
label = " ".join(x for x in [qty, unit, food or note] if x).strip()
if not label:
continue
items.append({"label": label, "product": (food or note or label)[:60],
"amount": float(qty) if qty else 1})
return items
def ensure_list(key, title="Покупки"):
st, data = grocy("GET", "/api/objects/shopping_lists", key)
if st == 200 and isinstance(data, list):
for l in data:
if l.get("name") == title:
return l["id"]
if data:
return data[0]["id"]
st, created = grocy("POST", "/api/objects/shopping_lists", key, {"name": title})
return created.get("id") if st in (200, 201) else None
def ensure_product(key, name):
q = "/api/objects/products?query%5B%5D=" + urllib.parse.quote("name=" + name)
st, data = grocy("GET", q, key)
if st == 200 and isinstance(data, list) and data:
return data[0]["id"]
st, created = grocy("POST", "/api/objects/products", key, {
"name": name, "location_id": 2,
"qu_id_purchase": 2, "qu_id_stock": 2, "qu_id_consume": 2,
"min_stock_amount": 0,
})
return created.get("id") if st in (200, 201) else None
def main():
if len(sys.argv) < 2:
print(__doc__)
return
name = sys.argv[1]
tok = json.load(open(TOKENS))
key = tok["grocy_key"]
title, items = find_recipe(name)
if not title:
print(f"рецепт «{name}» не найден в Mealie")
return
print(f"рецепт: {title}")
if not items:
print("ингредиентов нет")
return
list_id = ensure_list(key)
if not list_id:
print("не удалось получить список Grocy")
return
added = 0
for it in items:
pid = ensure_product(key, it["product"])
if not pid:
continue
st, _ = grocy("POST", "/api/objects/shopping_list", key, {
"shopping_list_id": list_id, "product_id": pid,
"amount": it["amount"] or 1})
if st in (200, 201):
added += 1
print(" +", it["label"])
print(f"итого добавлено: {added}")
if __name__ == "__main__":
main()