add micropub to gitea stuff

This commit is contained in:
James Ravenscroft 2021-12-23 21:39:21 +00:00
parent 897c75848c
commit 8b19417d14
1 changed files with 97 additions and 4 deletions

View File

@ -1,13 +1,105 @@
from flask import Flask, request, url_for import requests
from flask.ext.micropub import MicropubClient import os
import functools
import dotenv
import giteapy
import time
import base64
import yaml
from slugify import slugify
from datetime import datetime
from flask import Flask, request, url_for, Response
from requests import api
from flask_micropub import MicropubClient
dotenv.load_dotenv()
PERMITTED_DOMAIN = os.environ.get(
'PERMITTED_DOMAINS', 'https://brainsteam.co.uk/').split(';')
app = Flask(__name__) app = Flask(__name__)
app.config['SECRET_KEY'] = 'my super secret key' app.config['SECRET_KEY'] = 'my super secret key'
micropub = MicropubClient(app) micropub = MicropubClient(app, client_id='https://brainsteam.co.uk')
@app.route('/') def authed_endpoint(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
authtok = request.headers.get('Authorization')
if authtok is None:
return {"error": "No token provided"}, 401
auth = requests.get("https://tokens.indieauth.com/token", headers={
"Authorization": authtok, "Accept": "application/json"}).json()
if auth['me'] not in PERMITTED_DOMAIN:
return {"error": f"User {auth['me']} not permitted to post here"}, 403
return f(*args, *kwargs)
return wrapper
_api_client = None
def get_api_client():
global _api_client
if _api_client is None:
config = giteapy.Configuration()
config.host = os.environ.get('GITEA_URL')
config.api_key['access_token'] = os.environ.get('GITEA_API_KEY')
_api_client = giteapy.RepositoryApi(giteapy.ApiClient(config))
return _api_client
@app.route('/', methods=['POST'])
@authed_endpoint
def req():
doc = request.form.to_dict()
if 'name' in doc:
entry_type = "posts"
else:
entry_type = "micros"
now = datetime.now()
now_ts = int(time.mktime(now.timetuple()))
url = os.path.join("/",entry_type,now.strftime("%Y/%m/%d"), str(now_ts))
file_path = os.path.join(os.environ.get('CONTENT_PREFIX'), entry_type, now.strftime("%Y/%m/%d"), str(now_ts) + ".md")
frontmatter = yaml.dump({"url":url, "type": entry_type, "date": now.isoformat(sep='T')})
content = base64.encodestring(f"---\n{frontmatter}\n---\n\n{doc['content']}".encode("utf8")).decode("utf8")
api = get_api_client()
body = giteapy.CreateFileOptions(content=content)
try:
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})
except Exception as e:
return {"error": str(e)}, 500
print(r)
return {"hello": "world"}
@app.route('/', methods=['GET'])
def index(): def index():
return """ return """
<!DOCTYPE html> <!DOCTYPE html>
@ -65,6 +157,7 @@ def indieauth_callback(resp):
@app.route('/micropub-callback') @app.route('/micropub-callback')
@micropub.authorized_handler @micropub.authorized_handler
def micropub_callback(resp): def micropub_callback(resp):
return """ return """
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>