Dalsi vlna cisteni /remind od Claude
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/env -S uv run --script
|
||||
# /// script
|
||||
# requires-python = ">=3.11"
|
||||
# dependencies = ["croniter"]
|
||||
@@ -21,7 +21,7 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
from croniter import croniter
|
||||
from db import get_db, init_db, log_operation
|
||||
from random_times import compute_fire_times
|
||||
from random_times import compute_fire_times, parse_window
|
||||
|
||||
WORKSPACE = Path(__file__).resolve().parent.parent.parent.parent
|
||||
DEFAULT_DB_PATH = WORKSPACE / "db" / "reminders.sqlite"
|
||||
@@ -57,19 +57,7 @@ def _build_random(args: argparse.Namespace) -> dict | None:
|
||||
return cfg
|
||||
|
||||
|
||||
def _parse_window(window: str) -> tuple[int, int]:
|
||||
start_str, end_str = window.split("-", 1)
|
||||
start = _hhmm_to_minutes(start_str.strip())
|
||||
end = _hhmm_to_minutes(end_str.strip())
|
||||
return start, end
|
||||
|
||||
|
||||
def _hhmm_to_minutes(value: str) -> int:
|
||||
h, m = value.split(":")
|
||||
return int(h) * 60 + int(m)
|
||||
|
||||
|
||||
def _insert_schedules(conn, reminder_id: int, args: argparse.Namespace) -> None:
|
||||
def _insert_schedules(conn, reminder_id: int, args: argparse.Namespace, random_cfg: dict | None) -> None:
|
||||
if args.at:
|
||||
for at_str in args.at:
|
||||
conn.execute(
|
||||
@@ -82,9 +70,8 @@ def _insert_schedules(conn, reminder_id: int, args: argparse.Namespace) -> None:
|
||||
"INSERT INTO schedule_cron (reminder_id, cron_expr) VALUES (?, ?)",
|
||||
(reminder_id, expr),
|
||||
)
|
||||
random_cfg = _build_random(args)
|
||||
if random_cfg:
|
||||
start, end = _parse_window(random_cfg["window"])
|
||||
start, end = parse_window(random_cfg["window"])
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO schedule_random
|
||||
@@ -131,9 +118,11 @@ def _fetch_reminder(conn, reminder_id: int) -> dict:
|
||||
|
||||
|
||||
def _find_by_keyword(conn, keyword: str) -> list[dict]:
|
||||
escaped = keyword.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
rows = conn.execute(
|
||||
"SELECT id, text, enabled, timezone, created_at, updated_at, deleted_at FROM reminders WHERE text LIKE ? AND deleted_at IS NULL",
|
||||
(f"%{keyword}%",),
|
||||
"SELECT id, text, enabled, timezone, created_at, updated_at, deleted_at "
|
||||
"FROM reminders WHERE text LIKE ? ESCAPE '\\' AND deleted_at IS NULL",
|
||||
(f"%{escaped}%",),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
@@ -181,48 +170,52 @@ def cmd_list(_args: argparse.Namespace) -> int:
|
||||
conn = get_db(DB_PATH)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT id, text, enabled, timezone, created_at, updated_at, deleted_at FROM reminders WHERE deleted_at IS NULL ORDER BY id"
|
||||
"SELECT id, text, enabled FROM reminders WHERE deleted_at IS NULL ORDER BY id"
|
||||
).fetchall()
|
||||
if not rows:
|
||||
print("(no active reminders)")
|
||||
return 0
|
||||
|
||||
for idx, row in enumerate(rows, start=1):
|
||||
reminder = dict(row)
|
||||
rid = reminder["id"]
|
||||
status = "enabled" if reminder["enabled"] else "disabled"
|
||||
print(f"{idx}. {reminder['text']} ({status})")
|
||||
|
||||
at_rows = conn.execute(
|
||||
"SELECT at_datetime FROM schedule_at WHERE reminder_id = ?", (rid,)
|
||||
).fetchall()
|
||||
for r in at_rows:
|
||||
print(f" - at: {r['at_datetime']}")
|
||||
|
||||
cron_rows = conn.execute(
|
||||
"SELECT cron_expr FROM schedule_cron WHERE reminder_id = ?", (rid,)
|
||||
).fetchall()
|
||||
for r in cron_rows:
|
||||
print(f" - cron: {r['cron_expr']}")
|
||||
|
||||
random_rows = conn.execute(
|
||||
"SELECT times_per_day, window_start, window_end, days_filter, from_date, until_date FROM schedule_random WHERE reminder_id = ?",
|
||||
(rid,),
|
||||
).fetchall()
|
||||
for r in random_rows:
|
||||
parts = [f"random: {r['times_per_day']}× daily {r['window_start']}–{r['window_end']}"]
|
||||
if r["days_filter"]:
|
||||
parts.append(f"({r['days_filter']})")
|
||||
if r["from_date"]:
|
||||
parts.append(f"from {r['from_date']}")
|
||||
if r["until_date"]:
|
||||
parts.append(f"until {r['until_date']}")
|
||||
print(f" - {' '.join(parts)}")
|
||||
|
||||
for row in rows:
|
||||
rid = row["id"]
|
||||
status = "enabled" if row["enabled"] else "disabled"
|
||||
print(f"#{rid} {row['text']} [{status}]")
|
||||
for line in _schedule_lines(conn, rid):
|
||||
print(f" {line}")
|
||||
return 0
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _schedule_lines(conn, reminder_id: int) -> list[str]:
|
||||
"""Human-readable schedule descriptions for one reminder, in at/cron/random order."""
|
||||
lines = []
|
||||
for r in conn.execute("SELECT at_datetime FROM schedule_at WHERE reminder_id = ?", (reminder_id,)):
|
||||
lines.append(f"at: {r['at_datetime']}")
|
||||
for r in conn.execute("SELECT cron_expr FROM schedule_cron WHERE reminder_id = ?", (reminder_id,)):
|
||||
lines.append(f"cron: {r['cron_expr']}")
|
||||
random_rows = conn.execute(
|
||||
"SELECT times_per_day, window_start, window_end, days_filter, from_date, until_date "
|
||||
"FROM schedule_random WHERE reminder_id = ?",
|
||||
(reminder_id,),
|
||||
)
|
||||
for r in random_rows:
|
||||
window = f"{_minutes_to_hhmm(r['window_start'])}–{_minutes_to_hhmm(r['window_end'])}"
|
||||
parts = [f"random: {r['times_per_day']}× daily {window}"]
|
||||
if r["days_filter"]:
|
||||
parts.append(f"({r['days_filter']})")
|
||||
if r["from_date"]:
|
||||
parts.append(f"from {r['from_date']}")
|
||||
if r["until_date"]:
|
||||
parts.append(f"until {r['until_date']}")
|
||||
lines.append(" ".join(parts))
|
||||
return lines
|
||||
|
||||
|
||||
def _minutes_to_hhmm(total: int) -> str:
|
||||
return f"{total // 60:02d}:{total % 60:02d}"
|
||||
|
||||
|
||||
def cmd_add(args: argparse.Namespace) -> int:
|
||||
text = (args.text or "").strip()
|
||||
if not text:
|
||||
@@ -263,7 +256,7 @@ def cmd_add(args: argparse.Namespace) -> int:
|
||||
(text, now, now),
|
||||
)
|
||||
reminder_id = cur.lastrowid
|
||||
_insert_schedules(conn, reminder_id, args)
|
||||
_insert_schedules(conn, reminder_id, args, random_cfg)
|
||||
conn.execute("COMMIT")
|
||||
reminder = _fetch_reminder(conn, reminder_id)
|
||||
log_operation("ADD", reminder_id, f'text="{text}"')
|
||||
@@ -306,6 +299,19 @@ def cmd_edit(args: argparse.Namespace) -> int:
|
||||
print(json.dumps({"error": "--replace-schedules requires at least one --cron/--at/--random-* option"}), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
new_text = None
|
||||
if args.text:
|
||||
new_text = args.text.strip()
|
||||
if not new_text:
|
||||
print(json.dumps({"error": "text must not be empty"}), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
random_cfg = _build_random(args)
|
||||
except ValueError as exc:
|
||||
print(json.dumps({"error": str(exc)}), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
_ensure_db()
|
||||
conn = get_db(DB_PATH)
|
||||
try:
|
||||
@@ -317,11 +323,7 @@ def cmd_edit(args: argparse.Namespace) -> int:
|
||||
conn.execute("BEGIN")
|
||||
now = _now()
|
||||
|
||||
if args.text:
|
||||
new_text = args.text.strip()
|
||||
if not new_text:
|
||||
print(json.dumps({"error": "text must not be empty"}), file=sys.stderr)
|
||||
return 1
|
||||
if new_text is not None:
|
||||
conn.execute("UPDATE reminders SET text = ?, updated_at = ? WHERE id = ?", (new_text, now, rid))
|
||||
log_operation("EDIT", rid, f'text="{new_text}"')
|
||||
|
||||
@@ -329,7 +331,7 @@ def cmd_edit(args: argparse.Namespace) -> int:
|
||||
conn.execute("DELETE FROM schedule_at WHERE reminder_id = ?", (rid,))
|
||||
conn.execute("DELETE FROM schedule_cron WHERE reminder_id = ?", (rid,))
|
||||
conn.execute("DELETE FROM schedule_random WHERE reminder_id = ?", (rid,))
|
||||
_insert_schedules(conn, rid, args)
|
||||
_insert_schedules(conn, rid, args, random_cfg)
|
||||
conn.execute("UPDATE reminders SET updated_at = ? WHERE id = ?", (now, rid))
|
||||
log_operation("EDIT", rid, "schedules replaced")
|
||||
|
||||
@@ -403,21 +405,28 @@ def cmd_delivered(args: argparse.Namespace) -> int:
|
||||
except ValueError as exc:
|
||||
print(json.dumps({"error": f"invalid --since date: {exc}"}), file=sys.stderr)
|
||||
return 1
|
||||
where, params = "f.fire_time >= ?", (since,)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT f.delivered_at, r.text
|
||||
FROM reminder_fires f
|
||||
JOIN reminders r ON r.id = f.reminder_id
|
||||
WHERE f.status = 'delivered' AND f.fire_time >= ?
|
||||
ORDER BY f.delivered_at
|
||||
""",
|
||||
(since,),
|
||||
).fetchall()
|
||||
else:
|
||||
today = datetime.now(PRAGUE).date().isoformat()
|
||||
where, params = "substr(f.fire_time, 1, 10) = ?", (today,)
|
||||
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT f.delivered_at, r.text
|
||||
FROM reminder_fires f
|
||||
JOIN reminders r ON r.id = f.reminder_id
|
||||
WHERE f.status = 'delivered' AND {where}
|
||||
ORDER BY f.delivered_at
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT f.delivered_at, r.text
|
||||
FROM reminder_fires f
|
||||
JOIN reminders r ON r.id = f.reminder_id
|
||||
WHERE f.status = 'delivered' AND substr(f.fire_time, 1, 10) = ?
|
||||
ORDER BY f.delivered_at
|
||||
""",
|
||||
(today,),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
print(f"{row['delivered_at']} {row['text']}")
|
||||
return 0
|
||||
|
||||
Reference in New Issue
Block a user