From ddb0bdeda389f1548e11fe39e6bf20d8cf07a11c Mon Sep 17 00:00:00 2001 From: rra Date: Fri, 3 Sep 2021 15:58:20 +0200 Subject: [PATCH] images in calendar events now properly supported, fix #4 --- event_feed.py | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/event_feed.py b/event_feed.py index d662b5a..d11fb1c 100644 --- a/event_feed.py +++ b/event_feed.py @@ -76,13 +76,13 @@ def create_metadata(event): def localize_time(date): """ Turn a given date into various timezones + Takes arrow objects """ - # Dates need to be displayed for the various TZs - # takes arrow objects # 3 PM Kassel, Germany, 4 PM Ramallah/Jerusalem, Palestina (QoF), # 8 AM Bogota, Colombia (MaMa), 8 PM Jakarta, Indonesia (Gudskul), # 1 PM (+1day) Wellington, New Zealand (Fafswag), 9 AM Havana, Cuba (Instar). + tzs = [ ('Kassel','Europe/Berlin'), @@ -105,24 +105,51 @@ def localize_time(date): return localized_begins def create_event_post(post_dir, event): + """ + Create HUGO post based on calendar event metadata + Searches for image URLS in description and downloads them + Function is also called when post is in need of updating + In that case it will also delete images no longer in metadata + TODO: split this up into more functions for legibility + """ if not os.path.exists(post_dir): os.mkdir(post_dir) event_metadata = create_metadata(event) + #list already existing images + #so we can later delete them if we dont find them in the event metadata anymore + existing_images = os.listdir(post_dir) + try: + existing_images.remove('index.md') + existing_images.remove('.timestamp') + except: + pass + for img in event_metadata['images']: + + #parse img url to safe local image name img_name = img.split('/')[-1] + fn, ext = img_name.split('.') + img_name = slugify(fn) + '.' + ext + local_image = os.path.join(post_dir, img_name) - #TODO: handle the fact that someone might update a post - #and delete / replace an image + if not os.path.exists(local_image): #download preview image response = requests.get(img, stream=True) with open(local_image, 'wb') as img_file: shutil.copyfileobj(response.raw, img_file) - print('Downloaded event image for event "{}"'.format(event.name)) + print('Downloaded image for event "{}"'.format(event.name)) event_metadata['description'] = event_metadata['description'].replace(img, '![]({})'.format(img_name)) + if img_name in existing_images: + existing_images.remove(img_name) + + for left_over_image in existing_images: + #remove images we found, but which are no longer in remote event + os.remove(os.path.join(post_dir,left_over_image)) + print('deleted image', left_over_image) with open(os.path.join(post_dir,'index.md'),'w') as f: post = template.render(event = event_metadata)