|
| 1 | +import json |
| 2 | +from argparse import ArgumentParser |
| 3 | +from datetime import datetime, timezone |
| 4 | +from pathlib import Path |
| 5 | +from uuid import uuid4 |
| 6 | + |
| 7 | +from icalendar import Calendar, Event |
| 8 | + |
| 9 | + |
| 10 | +def convert_event(json_event: dict) -> Event: |
| 11 | + start = ( |
| 12 | + datetime.strptime(json_event["start"], "%Y-%m-%dT%H:%M:%S%z") |
| 13 | + .astimezone(timezone.utc) |
| 14 | + .strftime("%Y%m%dT%H%M%SZ") |
| 15 | + ) |
| 16 | + summary = json_event["title"] |
| 17 | + description = json_event.get("website_url", "") |
| 18 | + dtstart = start |
| 19 | + duration = f"PT{json_event['duration']}M" |
| 20 | + dtstamp = start |
| 21 | + uid = str(uuid4()) |
| 22 | + location = ", ".join(json_event["rooms"]) |
| 23 | + |
| 24 | + return Event( |
| 25 | + summary=summary, |
| 26 | + description=description, |
| 27 | + dtstart=dtstart, |
| 28 | + duration=duration, |
| 29 | + dtstamp=dtstamp, |
| 30 | + uid=uid, |
| 31 | + location=location, |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +def create_calendar() -> Calendar: |
| 36 | + cal = Calendar() |
| 37 | + cal.add("prodid", "-//Erik//Europython2024Calendar//EN") |
| 38 | + cal.add("version", "2.0") |
| 39 | + return cal |
| 40 | + |
| 41 | + |
| 42 | +def main(): |
| 43 | + parser = ArgumentParser() |
| 44 | + parser.add_argument( |
| 45 | + "-j", |
| 46 | + "--json-files", |
| 47 | + help="Path to the json file to process, supports globs in the filename", |
| 48 | + ) |
| 49 | + args = parser.parse_args() |
| 50 | + |
| 51 | + calendar = create_calendar() |
| 52 | + path = Path(args.json_files) |
| 53 | + json_files = Path(path.parent).expanduser().glob(path.name) |
| 54 | + |
| 55 | + for json_file in json_files: |
| 56 | + with open(json_file, "r") as fp: |
| 57 | + events = json.load(fp) |
| 58 | + |
| 59 | + for json_event in events["events"]: |
| 60 | + event = convert_event(json_event) |
| 61 | + calendar.add_component(event) |
| 62 | + |
| 63 | + with open("calendar.ics", "wb") as fp: |
| 64 | + fp.write(calendar.to_ical()) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + main() |
0 commit comments