The web server now runs a scheduler over schedules kept in SQLite
(~/.local/share/receipt-maker, outside the clone). A schedule is a
trigger, a receipt made of blocks, and options:
- Triggers: once, recurring (rrule-based, DST-safe), sun times,
reminders before calendar (ICS) events, RSS/JSON watchers, webhooks
with per-schedule secrets.
- Blocks, rendered fresh as one job: templated notes ({date},
{days_until:..}, rotating {choice}, trigger vars), QR, saved images,
random image, calendar agenda, feed headlines, dividers.
- Rules: quiet hours (hold/skip/ignore), daily cap, pause, catch-up
window for missed runs (never replayed), retries on connect failure
only; a mid-job drop (new PrinterDropped) is never resent.
receipt.py renders through composable Blocks (render_note/image/qr are
wrappers, output unchanged). Print history persists, with Print again.
The page moves to web/ with Print (note/image/QR + paper preview),
Schedules (presets, editor with live preview and next runs), History
and Settings tabs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
296 lines
11 KiB
Python
296 lines
11 KiB
Python
"""When schedules fire: next fire times, calendar reminders and plain-English summaries.
|
|
|
|
Recurrences are evaluated as wall-clock times in the settings timezone and
|
|
then made aware: a time in a spring-forward gap fires an hour later, and one
|
|
in a fall-back overlap fires on its first pass only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
from collections.abc import Callable
|
|
from urllib.parse import urlparse
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from dateutil import rrule as du
|
|
|
|
from receipt_models import (
|
|
WEEKDAYS,
|
|
CalendarTrigger,
|
|
OnceTrigger,
|
|
RecurringTrigger,
|
|
Settings,
|
|
SunTrigger,
|
|
WatchTrigger,
|
|
WebhookTrigger,
|
|
)
|
|
from receipt_sources import Event
|
|
from receipt_store import UTC
|
|
|
|
FREQS = {"daily": du.DAILY, "weekly": du.WEEKLY, "monthly": du.MONTHLY, "yearly": du.YEARLY}
|
|
DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
|
POSITIONS = {1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", -1: "last"}
|
|
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
|
CALENDAR_LOOKAHEAD = dt.timedelta(days=2)
|
|
|
|
|
|
class TriggerError(ValueError):
|
|
"""The trigger can't produce fire times (bad custom rule, no location for sun times)."""
|
|
|
|
|
|
def localize(naive: dt.datetime, tz: ZoneInfo) -> dt.datetime:
|
|
"""A wall-clock time as aware UTC; fold=0, so gaps shift forward and overlaps fire once."""
|
|
return naive.replace(tzinfo=tz).astimezone(UTC)
|
|
|
|
|
|
def ruleset(trigger: RecurringTrigger) -> du.rruleset:
|
|
start = trigger.start or dt.date(2000, 1, 3) # a Monday; only matters for intervals > 1
|
|
common = {
|
|
"dtstart": dt.datetime.combine(start, dt.time()),
|
|
"until": dt.datetime.combine(trigger.until, dt.time(23, 59, 59)) if trigger.until else None,
|
|
}
|
|
rules = du.rruleset()
|
|
if trigger.rrule:
|
|
text = trigger.rrule.strip().removeprefix("RRULE:")
|
|
try:
|
|
base = du.rrulestr(text, dtstart=common["dtstart"])
|
|
except (ValueError, TypeError) as e:
|
|
raise TriggerError(f"custom rule: {e}") from None
|
|
if not isinstance(base, du.rrule):
|
|
raise TriggerError("custom rule: give a single RRULE")
|
|
if "BYHOUR" in text.upper():
|
|
rules.rrule(base)
|
|
else:
|
|
for t in trigger.times:
|
|
rules.rrule(base.replace(byhour=t.hour, byminute=t.minute, bysecond=0))
|
|
return rules
|
|
|
|
kw: dict = {"freq": FREQS[trigger.freq], "interval": trigger.interval, **common}
|
|
days = trigger.weekdays
|
|
if trigger.freq in ("daily", "weekly"):
|
|
if days:
|
|
kw["byweekday"] = days
|
|
else:
|
|
if trigger.freq == "yearly":
|
|
kw["bymonth"] = trigger.month or start.month
|
|
if days:
|
|
kw["byweekday"] = days
|
|
if trigger.setpos is not None:
|
|
kw["bysetpos"] = trigger.setpos
|
|
else:
|
|
kw["bymonthday"] = trigger.monthday or start.day
|
|
# One rule per time: byhour x byminute would be a cross product (07:30 + 18:00 -> 07:00 too).
|
|
for t in trigger.times:
|
|
rules.rrule(du.rrule(byhour=t.hour, byminute=t.minute, bysecond=0, **kw))
|
|
return rules
|
|
|
|
|
|
def _sun_time(trigger: SunTrigger, day: dt.date, settings: Settings) -> dt.datetime | None:
|
|
from astral import Observer, sun
|
|
|
|
location = settings.location
|
|
observer = Observer(location.latitude, location.longitude)
|
|
try:
|
|
at = getattr(sun, trigger.event)(observer, date=day, tzinfo=settings.tz)
|
|
except ValueError: # the sun never reaches that angle that day (high latitudes)
|
|
return None
|
|
at += dt.timedelta(minutes=trigger.offset_minutes)
|
|
return at.replace(microsecond=0).astimezone(UTC)
|
|
|
|
|
|
def next_fire(trigger, after: dt.datetime, settings: Settings) -> dt.datetime | None:
|
|
"""The first fire time strictly after `after` for a timed trigger; None if there are no more."""
|
|
tz = settings.tz
|
|
if isinstance(trigger, OnceTrigger):
|
|
at = localize(trigger.at, tz)
|
|
return at if at > after else None
|
|
if isinstance(trigger, RecurringTrigger):
|
|
rules = ruleset(trigger)
|
|
# Search from a little earlier in wall-clock terms: around a DST change the
|
|
# naive local time of `after` can be an hour off the aware comparison below.
|
|
candidate = rules.after(after.astimezone(tz).replace(tzinfo=None) - dt.timedelta(hours=2))
|
|
for _ in range(500):
|
|
if candidate is None:
|
|
return None
|
|
at = localize(candidate, tz)
|
|
if at > after:
|
|
return at
|
|
candidate = rules.after(candidate)
|
|
return None
|
|
if isinstance(trigger, SunTrigger):
|
|
if settings.location is None:
|
|
raise TriggerError("sun times need a location in Settings")
|
|
first = after.astimezone(tz).date() - dt.timedelta(days=1)
|
|
for offset in range(400): # covers polar night/day stretches
|
|
day = first + dt.timedelta(days=offset)
|
|
if day.weekday() not in trigger.weekdays:
|
|
continue
|
|
at = _sun_time(trigger, day, settings)
|
|
if at is not None and at > after:
|
|
return at
|
|
return None
|
|
return None
|
|
|
|
|
|
def upcoming(trigger, after: dt.datetime, settings: Settings, count: int) -> list[dt.datetime]:
|
|
times = []
|
|
at = after
|
|
while len(times) < count:
|
|
at = next_fire(trigger, at, settings)
|
|
if at is None:
|
|
break
|
|
times.append(at)
|
|
return times
|
|
|
|
|
|
def calendar_fires(
|
|
trigger: CalendarTrigger, events: list[Event]
|
|
) -> list[tuple[dt.datetime, Event]]:
|
|
"""(fire time in UTC, event) for each event the trigger reminds about, soonest first."""
|
|
needle = trigger.contains.strip().lower()
|
|
fires = []
|
|
for event in events:
|
|
if event.all_day and not trigger.include_all_day:
|
|
continue
|
|
if needle and needle not in event.title.lower():
|
|
continue
|
|
at = event.start - dt.timedelta(minutes=trigger.minutes_before)
|
|
fires.append((at.astimezone(UTC), event))
|
|
fires.sort(key=lambda f: f[0])
|
|
return fires
|
|
|
|
|
|
# --- summaries ---
|
|
|
|
|
|
def _join(words: list[str]) -> str:
|
|
if len(words) <= 1:
|
|
return "".join(words)
|
|
return f"{', '.join(words[:-1])} and {words[-1]}"
|
|
|
|
|
|
def _days(days: list[int]) -> str:
|
|
if not days or sorted(days) == WEEKDAYS:
|
|
return "every day"
|
|
if sorted(days) == [0, 1, 2, 3, 4]:
|
|
return "weekdays"
|
|
if sorted(days) == [5, 6]:
|
|
return "weekends"
|
|
return _join([DAY_NAMES[d] for d in sorted(days)])
|
|
|
|
|
|
def _date(day: dt.date) -> str:
|
|
return f"{day.day} {MONTHS[day.month - 1]} {day.year}"
|
|
|
|
|
|
def _ordinal(n: int) -> str:
|
|
suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
|
|
return f"{n}{suffix}"
|
|
|
|
|
|
def _times(times: list[dt.time]) -> str:
|
|
return _join([t.strftime("%H:%M") for t in times])
|
|
|
|
|
|
def _every(unit: str, interval: int) -> str:
|
|
return f"every {unit}" if interval == 1 else f"every {interval} {unit}s"
|
|
|
|
|
|
def _day_of_month(trigger: RecurringTrigger) -> str:
|
|
if trigger.weekdays:
|
|
if trigger.setpos is None:
|
|
return f"every {_join([DAY_NAMES[d] for d in trigger.weekdays])}"
|
|
days = trigger.weekdays
|
|
what = "weekday" if days == [0, 1, 2, 3, 4] else _join([DAY_NAMES[d] for d in days])
|
|
return f"the {POSITIONS[trigger.setpos]} {what}"
|
|
if trigger.monthday == -1:
|
|
return "the last day"
|
|
day = trigger.monthday or (trigger.start.day if trigger.start else 1)
|
|
return f"the {_ordinal(day)}"
|
|
|
|
|
|
def _recurring(trigger: RecurringTrigger) -> str:
|
|
if trigger.rrule:
|
|
rule = trigger.rrule.strip().removeprefix("RRULE:")
|
|
return f"Custom rule {rule} at {_times(trigger.times)}"
|
|
n = trigger.interval
|
|
if trigger.freq == "daily":
|
|
when = _days(trigger.weekdays) if n == 1 else f"{_every('day', n)}"
|
|
if n > 1 and trigger.weekdays:
|
|
when += f" ({_days(trigger.weekdays)})"
|
|
elif trigger.freq == "weekly":
|
|
on = _join([DAY_NAMES[d] for d in trigger.weekdays]) if trigger.weekdays else None
|
|
if on is None and trigger.start:
|
|
on = DAY_NAMES[trigger.start.weekday()]
|
|
when = _every("week", n) + (f" on {on}" if on else "")
|
|
elif trigger.freq == "monthly":
|
|
when = f"{_every('month', n)} on {_day_of_month(trigger)}"
|
|
else:
|
|
month = trigger.month or (trigger.start.month if trigger.start else 1)
|
|
if trigger.weekdays:
|
|
when = f"{_every('year', n)} on {_day_of_month(trigger)} of {MONTHS[month - 1]}"
|
|
elif trigger.monthday == -1:
|
|
when = f"{_every('year', n)} on the last day of {MONTHS[month - 1]}"
|
|
else:
|
|
day = trigger.monthday or (trigger.start.day if trigger.start else 1)
|
|
when = f"{_every('year', n)} on {day} {MONTHS[month - 1]}"
|
|
text = f"{when[0].upper()}{when[1:]} at {_times(trigger.times)}"
|
|
if trigger.until:
|
|
text += f", until {_date(trigger.until)}"
|
|
return text
|
|
|
|
|
|
def _minutes(n: int) -> str:
|
|
if n and n % (24 * 60) == 0:
|
|
days = n // (24 * 60)
|
|
return f"{days} day{'s' if days > 1 else ''}"
|
|
if n and n % 60 == 0:
|
|
return f"{n // 60} h"
|
|
if n > 60:
|
|
return f"{n // 60} h {n % 60} min"
|
|
return f"{n} min"
|
|
|
|
|
|
def describe(
|
|
trigger, settings: Settings, source_name: Callable[[str], str] = lambda _id: "a calendar"
|
|
) -> str:
|
|
if isinstance(trigger, OnceTrigger):
|
|
at = trigger.at
|
|
return f"Once, {DAY_NAMES[at.weekday()]} {_date(at)} at {at:%H:%M}"
|
|
if isinstance(trigger, RecurringTrigger):
|
|
return _recurring(trigger)
|
|
if isinstance(trigger, SunTrigger):
|
|
offset = trigger.offset_minutes
|
|
if offset == 0:
|
|
when = f"At {trigger.event}"
|
|
else:
|
|
when = f"{_minutes(abs(offset))} {'before' if offset < 0 else 'after'} {trigger.event}"
|
|
if sorted(trigger.weekdays) != WEEKDAYS:
|
|
when += f", {_days(trigger.weekdays)}"
|
|
if settings.location is None:
|
|
when += " (set a location in Settings)"
|
|
return when
|
|
if isinstance(trigger, CalendarTrigger):
|
|
name = source_name(trigger.source_id)
|
|
if trigger.minutes_before == 0:
|
|
text = f"When events in {name} start"
|
|
else:
|
|
text = f"{_minutes(trigger.minutes_before)} before events in {name}"
|
|
if trigger.contains.strip():
|
|
text += f' matching "{trigger.contains.strip()}"'
|
|
if trigger.include_all_day:
|
|
text += ", incl. all-day"
|
|
return text
|
|
if isinstance(trigger, WatchTrigger):
|
|
host = urlparse(trigger.url).netloc
|
|
every = f"checked every {_minutes(trigger.every_minutes)}"
|
|
if trigger.kind == "rss":
|
|
return f"New items in {host}, {every}"
|
|
path = trigger.path or "the value"
|
|
if trigger.condition == "changed":
|
|
return f"When {path} at {host} changes, {every}"
|
|
return f"When {path} at {host} goes {trigger.condition} {trigger.threshold:g}, {every}"
|
|
if isinstance(trigger, WebhookTrigger):
|
|
return f"When its webhook is called (up to {trigger.per_hour} an hour)"
|
|
return "Unknown trigger"
|