From fe6b396dfa0b45ffa2d89de3da7cdb4b0604e797 Mon Sep 17 00:00:00 2001 From: James Ravenscroft Date: Fri, 24 Dec 2021 11:56:12 +0000 Subject: [PATCH] implement handling of multiple photos --- example.py | 95 ++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 75 insertions(+), 20 deletions(-) diff --git a/example.py b/example.py index 0bd73f6..0772753 100644 --- a/example.py +++ b/example.py @@ -1,3 +1,4 @@ +from typing import Dict, List import requests import os import functools @@ -5,6 +6,7 @@ import dotenv import giteapy import time import base64 +from werkzeug.datastructures import FileStorage import yaml from slugify import slugify @@ -62,6 +64,64 @@ def get_api_client(): return _api_client +def process_photo_url(now: datetime, doc: Dict[str, List[str]], suffix: str = ""): + """Process photo submitted via URL""" + + now_ts = int(time.mktime(now.timetuple())) + + if os.environ.get('MICROPUB_IMAGE_STRATEGY') == 'copy': + # download the photo + r = requests.get(doc['photo']) + + ext = os.path.splitext(doc['photo'])[1] + + # generate local filename + filename = os.path.join(os.environ.get( + 'MICROPUB_MEDIA_PATH'), now.strftime("%Y/%m/%d"), str(now_ts) + f"{now_ts}_{suffix}{ext}") + photo_url = os.path.join(os.environ.get( + 'MICROPUB_MEDIA_URL_PREFIX'), now.strftime("%Y/%m/%d"), str(now_ts) + f"{now_ts}_{suffix}{ext}") + + # make directory if needed + if not os.path.exists(os.path.dirname(filename)): + os.makedirs(os.path.dirname(filename)) + + with open(filename, 'wb') as f: + f.write(r.content) + + # elif os.environ.get('MICROPUB_IMAGE_STRATEGY') == 'gitea': + + else: + photo_url = doc['photo'] + + return photo_url + +def process_photo_upload(now: datetime, file: FileStorage, suffix: str=""): + """Process photo directly uploaded to micropub""" + + now_ts = int(time.mktime(now.timetuple())) + + if os.environ.get('MICROPUB_IMAGE_STRATEGY') == 'copy': + + ext = os.path.splitext(file.filename)[1] + + # generate local filename + filename = os.path.join(os.environ.get( + 'MICROPUB_MEDIA_PATH'), now.strftime("%Y/%m/%d"), f"{now_ts}_{suffix}{ext}") + photo_url = os.path.join(os.environ.get( + 'MICROPUB_MEDIA_URL_PREFIX'), now.strftime("%Y/%m/%d"), f"{now_ts}_{suffix}{ext}") + + # make directory if needed + if not os.path.exists(os.path.dirname(filename)): + os.makedirs(os.path.dirname(filename)) + + file.save(filename) + + return photo_url + + else: + return None + + @app.route('/', methods=['POST']) @authed_endpoint @@ -107,31 +167,29 @@ def req(): frontmatter_str = yaml.dump(frontmatter) - if 'photo' in doc: + if ('photo' in doc) or ('photo' in request.files) or ('photo[]' in request.files): - if os.environ.get('MICROPUB_IMAGE_STRATEGY') == 'copy': - # download the photo - r = requests.get(doc['photo']) + if 'photo[]' in request.files: + photos = request.files.getlist('photo[]') - # generate local filename - filename = os.path.join(os.environ.get( - 'MICROPUB_MEDIA_PATH'), now.strftime("%Y/%m/%d"), str(now_ts) + ".jpg") - photo_url = os.path.join(os.environ.get( - 'MICROPUB_MEDIA_URL_PREFIX'), now.strftime("%Y/%m/%d"), str(now_ts) + ".jpg") + docstr = "" - # make directory if needed - if not os.path.exists(os.path.dirname(filename)): - os.makedirs(os.path.dirname(filename)) + for i, photo in enumerate(photos): + photo_url = process_photo_upload(now, photo, suffix=i) - with open(filename, 'wb') as f: - f.write(r.content) + docstr += f"\n\n![image]({photo_url})" - # elif os.environ.get('MICROPUB_IMAGE_STRATEGY') == 'gitea': + docstr += f"\n\n {doc['content']}" else: - photo_url = doc['photo'] - docstr = f"![image]({photo_url}) \n\n {doc['content']}" + if 'photo' in doc: + photo_url = process_photo_url(now, doc) + else: + photo_url = process_photo_upload(now, request.files['photo']) + + + docstr = f"![image]({photo_url}) \n\n {doc['content']}" else: docstr = doc['content'] @@ -151,9 +209,6 @@ def req(): except Exception as e: return {"error": str(e)}, 500 - # print(r) - - # return {"hello": "world"} def parse_categories():