#!/usr/bin/python3 """Update GWR advance ticket date cache.""" import os.path import smtplib import sys from email.message import EmailMessage from email.utils import formatdate, make_msgid import requests from agenda import gwr config = __import__("config.default", fromlist=[""]) def send_mail(subject: str, body: str) -> None: """Send an e-mail.""" msg = EmailMessage() msg["Subject"] = subject msg["To"] = f"{config.NAME} <{config.MAIL_TO}>" msg["From"] = f"{config.NAME} <{config.MAIL_FROM}>" msg["Date"] = formatdate() msg["Message-ID"] = make_msgid() msg.set_content(body) s = smtplib.SMTP(config.SMTP_HOST) s.sendmail(config.MAIL_TO, [config.MAIL_TO], msg.as_string()) s.quit() def main() -> None: """Get date from web page and compare with existing.""" filename = os.path.join(config.DATA_DIR, "advance-tickets.html") existing_html = open(filename).read() existing_date = gwr.extract_weekday_date(existing_html) new_html = requests.get(gwr.url).text open(filename, "w").write(new_html) new_date = gwr.extract_weekday_date(new_html) if existing_date == new_date: if sys.stdin.isatty(): print("date has't changed:", existing_date) return subject = f"New GWR advance ticket booking date: {new_date}" body = f"""Old date: {existing_date} New date: {new_date} {gwr.url} Agenda: https://edwardbetts.com/agenda/ """ send_mail(subject, body) if __name__ == "__main__": main()