add support for copying photos

This commit is contained in:
James Ravenscroft 2021-12-24 10:49:31 +00:00
parent efb4019c82
commit e7ae240555
1 changed files with 97 additions and 19 deletions

View File

@ -32,13 +32,16 @@ def authed_endpoint(f):
authtok = request.headers.get('Authorization') authtok = request.headers.get('Authorization')
if authtok is None: if authtok is None:
return {"error": "No token provided"}, 401 return {
"error": "unauthorized",
"error_description": "An auth token was not provided"
}, 401
auth = requests.get("https://tokens.indieauth.com/token", headers={ auth = requests.get("https://tokens.indieauth.com/token", headers={
"Authorization": authtok, "Accept": "application/json"}).json() "Authorization": authtok, "Accept": "application/json"}).json()
if auth['me'] not in PERMITTED_DOMAIN: if auth['me'] not in PERMITTED_DOMAIN:
return {"error": f"User {auth['me']} not permitted to post here"}, 403 return {"error": "forbidden", "error_description": f"User {auth['me']} not permitted to post here"}, 403
return f(*args, *kwargs) return f(*args, *kwargs)
@ -67,18 +70,23 @@ def req():
doc = request.form.to_dict(flat=True) doc = request.form.to_dict(flat=True)
if 'name' in doc: if 'name' in doc:
entry_type = "posts" entry_type = "post"
else: else:
entry_type = "micros" entry_type = "note"
now = datetime.now() now = datetime.now()
now_ts = int(time.mktime(now.timetuple())) now_ts = int(time.mktime(now.timetuple()))
url = os.path.join("/",entry_type,now.strftime("%Y/%m/%d"), str(now_ts)) url = os.path.join("/", entry_type + "s",
file_path = os.path.join(os.environ.get('CONTENT_PREFIX'), entry_type, now.strftime("%Y/%m/%d"), str(now_ts) + ".md") now.strftime("%Y/%m/%d"), str(now_ts))
if 'name' in doc:
slug = slugify(doc['name']) + str(now_ts)
else:
slug = str(now_ts)
file_path = os.path.join(os.environ.get(
'CONTENT_PREFIX'), entry_type + "s", now.strftime("%Y/%m/%d"), slug + ".md")
frontmatter = { frontmatter = {
"url": url, "url": url,
@ -86,23 +94,55 @@ def req():
"date": now.isoformat(sep='T'), "date": now.isoformat(sep='T'),
} }
if 'category' in doc:
categories = [doc['category']]
else:
categories = request.form.getlist('category[]') categories = request.form.getlist('category[]')
if 'name' in doc:
frontmatter['title'] = doc['name']
if len(categories) > 0: if len(categories) > 0:
frontmatter['categories'] = categories frontmatter['tags'] = categories
frontmatter_str = yaml.dump(frontmatter) frontmatter_str = yaml.dump(frontmatter)
content = base64.encodestring(f"---\n{frontmatter_str}\n---\n\n{doc['content']}".encode("utf8")).decode("utf8") if 'photo' in doc:
if os.environ.get('MICROPUB_IMAGE_STRATEGY') == 'copy':
# download the photo
r = requests.get(doc['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")
# make directory if needed
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']
docstr = f"![image]({photo_url}) \n\n {doc['content']}"
else:
docstr = doc['content']
content = base64.encodestring(
f"---\n{frontmatter_str}\n---\n\n{docstr}".encode("utf8")).decode("utf8")
api = get_api_client() api = get_api_client()
body = giteapy.CreateFileOptions(content=content) body = giteapy.CreateFileOptions(content=content)
try: try:
r = api.repo_create_file(os.environ.get('GITEA_REPO_OWNER'), os.environ.get('GITEA_REPO_NAME'), file_path, body) r = api.repo_create_file(os.environ.get(
'GITEA_REPO_OWNER'), os.environ.get('GITEA_REPO_NAME'), file_path, body)
return Response(status=202, headers={"Location": url}) return Response(status=202, headers={"Location": url})
@ -114,8 +154,46 @@ def req():
# return {"hello": "world"} # return {"hello": "world"}
@app.route('/', methods=['GET']) @app.route("/", methods=['GET'])
@authed_endpoint
def index(): def index():
if request.args.get('q') == 'config':
return {
"media-endpoint": "/micropub/media",
"syndicate-to": [
{
"uid": "mastodon",
"name": "Mastodon"
}
],
"post-types": [
{
"type": "note",
"name": "Note"
},
{
"type": "article",
"name": "Blog Post"
},
{
"type": "photo",
"name": "Photo"
},
{
"type": "reply",
"name": "Reply"
},
{
"type": "bookmark",
"name": "Bookmark"
}
]
}
@app.route('/form', methods=['GET'])
def authform():
return """ return """
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>