1
0
personal-data/personal_data_calendar/__main__.py
2024-10-03 23:24:12 +02:00

76 lines
2.0 KiB
Python

import argparse
import datetime
import urllib.parse
import icalendar
from personal_data.util import load_csv_file
NOW = datetime.datetime.now(tz=datetime.UTC)
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('data_folder')
parser.add_argument('output_file')
return parser.parse_args()
def generate_calendar(rows: list[dict]) -> icalendar.Calendar:
max_title_parts = 2
cal = icalendar.Calendar()
cal.add('prodid', '-//personal_data_calendar//example.org//')
cal.add('version', '2.0')
for event_data in rows:
# Select data
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)
]
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
title = ': '.join(event_data[k] for k in possible_name_keys[:max_title_parts])
description = '\n\n'.join(
event_data[k] for k in possible_name_keys[max_title_parts:]
)
# Create event
event = icalendar.Event()
event.add('summary', title)
event.add('description', description)
event.add('dtstart', date)
event.add('dtend', date + datetime.timedelta(minutes=30))
event.add('created', NOW)
event.add('dtstamp', NOW)
if image:
event.add('image', image.geturl())
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())
if __name__ == '__main__':
main()