1
0
personal-data/personal_data_calendar/__main__.py

76 lines
2.0 KiB
Python
Raw Normal View History

2024-08-25 18:08:41 +00:00
import argparse
import datetime
2024-08-25 18:50:03 +00:00
import urllib.parse
import icalendar
2024-08-25 18:08:41 +00:00
from personal_data.util import load_csv_file
2024-08-25 18:50:03 +00:00
NOW = datetime.datetime.now(tz=datetime.UTC)
2024-08-25 18:08:41 +00:00
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('data_folder')
parser.add_argument('output_file')
return parser.parse_args()
2024-08-25 18:50:03 +00:00
2024-08-25 18:08:41 +00:00
def generate_calendar(rows: list[dict]) -> icalendar.Calendar:
2024-08-25 20:15:13 +00:00
max_title_parts = 2
2024-08-25 18:08:41 +00:00
cal = icalendar.Calendar()
cal.add('prodid', '-//personal_data_calendar//example.org//')
cal.add('version', '2.0')
for event_data in rows:
2024-08-25 18:38:16 +00:00
# Select data
2024-08-25 18:50:03 +00:00
possible_time_keys = [
k for k, v in event_data.items() if isinstance(v, datetime.date)
]
possible_name_keys = [k for k, v in event_data.items() if isinstance(v, str)]
possible_image_keys = [
k for k, v in event_data.items() if isinstance(v, urllib.parse.ParseResult)
]
2024-08-25 18:38:16 +00:00
date = event_data[possible_time_keys[0]] if possible_time_keys else None
image = event_data[possible_image_keys[0]] if possible_image_keys else None
if date is None:
continue
2024-08-25 20:15:13 +00:00
title = ': '.join(event_data[k] for k in possible_name_keys[:max_title_parts])
2024-10-03 21:24:12 +00:00
description = '\n\n'.join(
event_data[k] for k in possible_name_keys[max_title_parts:]
)
2024-08-25 18:49:49 +00:00
2024-08-25 18:08:41 +00:00
# Create event
event = icalendar.Event()
2024-08-25 18:38:16 +00:00
event.add('summary', title)
2024-08-25 18:49:49 +00:00
event.add('description', description)
2024-08-25 18:38:16 +00:00
event.add('dtstart', date)
2024-08-25 20:15:13 +00:00
event.add('dtend', date + datetime.timedelta(minutes=30))
2024-08-25 18:08:41 +00:00
event.add('created', NOW)
event.add('dtstamp', NOW)
2024-08-25 18:38:16 +00:00
if image:
event.add('image', image.geturl())
2024-08-25 18:08:41 +00:00
cal.add_component(event)
del event
return cal
def main():
args = parse_arguments()
dicts = load_csv_file(args.data_folder + '/games_played_playstation.csv')
calendar = generate_calendar(dicts)
with open(args.output_file, 'wb') as f:
f.write(calendar.to_ical())
2024-08-25 18:50:03 +00:00
2024-08-25 18:08:41 +00:00
if __name__ == '__main__':
main()