55 lines
2.7 KiB
Python
55 lines
2.7 KiB
Python
"""Single-occurrence schedules, persisted in UTC; explicit fixed UTC+08:00 zone."""
|
||
from datetime import date, datetime, time, timedelta, timezone
|
||
|
||
CONTACT_ZONE = timezone(timedelta(hours=8), "UTC+08:00")
|
||
|
||
|
||
def normalize_schedule(value, now):
|
||
value = dict(value or {})
|
||
kind = value.get("kind", "immediate")
|
||
interval = int(value.get("interval", 30))
|
||
if not 20 <= interval <= 3600:
|
||
raise ValueError("客户间隔须为 20–3600 秒")
|
||
result = {"kind": kind, "interval": interval, "timezone": "UTC+08:00"}
|
||
if kind == "immediate":
|
||
result["start_at"] = now
|
||
elif kind == "fixed":
|
||
stamp = datetime.fromisoformat(str(value.get("at", "")))
|
||
if stamp.tzinfo is not None:
|
||
raise ValueError("指定时间请按页面显示的 UTC+08:00 填写")
|
||
result["start_at"] = stamp.replace(tzinfo=CONTACT_ZONE).timestamp()
|
||
if result["start_at"] < now:
|
||
raise ValueError("指定时间不能早于当前时间")
|
||
elif kind == "window":
|
||
start = date.fromisoformat(str(value.get("start_date", "")))
|
||
end = date.fromisoformat(str(value.get("end_date", "")))
|
||
begin, finish = time.fromisoformat(str(value.get("start", ""))), time.fromisoformat(str(value.get("end", "")))
|
||
if begin.tzinfo or finish.tzinfo or begin >= finish:
|
||
raise ValueError("结束时间须晚于开始时间;第一版时间段不跨午夜")
|
||
days = sorted(set(int(d) for d in value.get("weekdays", [0, 1, 2, 3, 4])))
|
||
if not days or any(d not in range(7) for d in days) or not 0 <= (end - start).days <= 366:
|
||
raise ValueError("请选择执行日及一年以内的有效日期范围")
|
||
result.update(start_date=start.isoformat(), end_date=end.isoformat(), start=begin.isoformat(),
|
||
end=finish.isoformat(), weekdays=days)
|
||
else:
|
||
raise ValueError("不支持的发送方式")
|
||
if next_slot(result, now) is None:
|
||
raise ValueError("日期范围内已没有可发送的时间段")
|
||
return result
|
||
|
||
|
||
def next_slot(schedule, now):
|
||
if schedule["kind"] != "window":
|
||
return max(now, float(schedule["start_at"]))
|
||
local = datetime.fromtimestamp(now, CONTACT_ZONE)
|
||
day = max(local.date(), date.fromisoformat(schedule["start_date"]))
|
||
end_day = date.fromisoformat(schedule["end_date"])
|
||
while day <= end_day:
|
||
if day.weekday() in schedule["weekdays"]:
|
||
start = datetime.combine(day, time.fromisoformat(schedule["start"]), CONTACT_ZONE).timestamp()
|
||
end = datetime.combine(day, time.fromisoformat(schedule["end"]), CONTACT_ZONE).timestamp()
|
||
if max(start, now) < end:
|
||
return max(start, now)
|
||
day += timedelta(days=1)
|
||
return None
|