Утренняя сводка дополнена блоком из последней инвентаризации: медиа, музыка, книги, фото, документы. Теперь одно сообщение отвечает и «что произошло», и «что у нас есть». Проверено: дайджест отправился, блоки событий и заметного на месте.
111 lines
4.2 KiB
Python
111 lines
4.2 KiB
Python
"""Дневной дайджест по событиям ядра."""
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.parse
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
|
|
import psycopg2
|
|
|
|
DSN = os.environ.get("CORE_DSN",
|
|
"dbname=hub_core user=hub_core password=hub_core host=192.168.1.151 client_encoding=utf8")
|
|
MATRIX_HS = os.environ.get("MATRIX_HS", "https://matrix.buryans.ru")
|
|
TOKEN = os.environ.get("NOTIFY_TOKEN", "")
|
|
ROOM = os.environ.get("NOTIFY_ROOM", "")
|
|
|
|
|
|
def send(text):
|
|
if not (TOKEN and ROOM):
|
|
print("нет настроек Matrix")
|
|
return False
|
|
txn = int(datetime.now().timestamp() * 1000)
|
|
rid = urllib.parse.quote(ROOM, safe="")
|
|
body = json.dumps({"msgtype": "m.text", "body": text,
|
|
"format": "org.matrix.custom.html",
|
|
"formatted_body": text.replace("\n", "<br>")}).encode()
|
|
req = urllib.request.Request(
|
|
f"{MATRIX_HS}/_matrix/client/v3/rooms/{rid}/send/m.room.message/{txn}",
|
|
data=body, method="PUT",
|
|
headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=15):
|
|
return True
|
|
except Exception as e:
|
|
print("не отправилось:", str(e)[:100])
|
|
return False
|
|
|
|
|
|
def main():
|
|
con = psycopg2.connect(DSN, connect_timeout=10)
|
|
cur = con.cursor()
|
|
|
|
cur.execute("""select source, type, count(*) from events
|
|
where at > now() - interval '24 hours'
|
|
group by source, type order by 3 desc""")
|
|
rows = cur.fetchall()
|
|
|
|
cur.execute("""select count(*) from entities""")
|
|
entities = cur.fetchone()[0]
|
|
|
|
cur.execute("""select count(*) from problems where resolved_at is null""")
|
|
open_problems = cur.fetchone()[0]
|
|
|
|
cur.execute("""select count(*) from actions where at > now() - interval '24 hours'""")
|
|
actions = cur.fetchone()[0]
|
|
|
|
cur.execute("""select payload from data_docs
|
|
where collection = 'inventory'
|
|
order by updated_at desc limit 1""")
|
|
inv_row = cur.fetchone()
|
|
inventory_row = inv_row[0] if inv_row else None
|
|
|
|
cur.execute("""select source, type, entity->>'title' from events
|
|
where at > now() - interval '24 hours'
|
|
and type in ('media.imported','media.requested','service.alert','document.added','book.added')
|
|
order by id desc limit 8""")
|
|
notable = cur.fetchall()
|
|
con.close()
|
|
|
|
lines = [f"**Сводка · {datetime.now(timezone.utc).strftime('%d.%m')}**", ""]
|
|
if not rows:
|
|
lines.append("_За сутки событий не было._")
|
|
else:
|
|
total = sum(r[2] for r in rows)
|
|
lines.append(f"**Событий за сутки: {total}**")
|
|
for src, typ, n in rows[:8]:
|
|
lines.append(f"• {src}: {typ} — {n}")
|
|
if notable:
|
|
lines.append("\n**Заметное**")
|
|
for src, typ, title in notable:
|
|
lines.append(f"• {title or '—'} ({typ}, {src})")
|
|
if inventory_row:
|
|
try:
|
|
inv = inventory_row if isinstance(inventory_row, dict) else json.loads(inventory_row)
|
|
jf = inv.get("jellyfin") or {}
|
|
nv = inv.get("navidrome") or {}
|
|
cb = inv.get("calibre") or {}
|
|
im = inv.get("immich") or {}
|
|
pl = inv.get("paperless") or {}
|
|
lines.append("")
|
|
lines.append("**Что есть**")
|
|
lines.append(f"• Медиа: {jf.get('Movie')} фильмов, {jf.get('Series')} сериалов, "
|
|
f"{jf.get('Episode')} серий")
|
|
lines.append(f"• Музыка: {nv.get('albums')} альбомов, {nv.get('tracks')} треков")
|
|
lines.append(f"• Книги: {cb.get('books')} · Фото: {im.get('assets')} · "
|
|
f"Документы: {pl.get('documents')}")
|
|
except Exception:
|
|
pass
|
|
|
|
lines.append("")
|
|
lines.append(f"Карточек: {entities} · открытых проблем: {open_problems} · действий: {actions}")
|
|
|
|
text = "\n".join(lines)
|
|
ok = send(text)
|
|
print(text.replace("\n", " | ")[:500])
|
|
return 0 if ok else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|