From 70c480a7cd524f2bf4e55f0a871536cfde667b9f Mon Sep 17 00:00:00 2001 From: Jef Roosens Date: Thu, 30 Dec 2021 21:08:28 +0100 Subject: [PATCH] Wrote basic upload folder --- .gitignore | 1 + app.py | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 .gitignore create mode 100644 app.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/app.py b/app.py new file mode 100644 index 0000000..9d6a38c --- /dev/null +++ b/app.py @@ -0,0 +1,68 @@ +import os +from flask import Flask, request +from pathlib import Path +from werkzeug.utils import secure_filename +import subprocess + +UPLOAD_FOLDER = './data' +API_KEY = 'yeet' +ALLOWED_EXTENSIONS = {'pkg.tar.zst', 'pkg.tar.gz'} + +app = Flask(__name__) +app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER + + +def require_api_key(func): + def inner(*args, **kwargs): + print(request.headers) + if request.headers.get('x-api-key') and request.headers.get('x-api-key') == API_KEY: + return func(*args, **kwargs) + + return {'message': 'Unauthorized.'}, 401 + + return inner + + +def allowed_file(filename): + return any(filename.endswith(ext) for ext in ALLOWED_EXTENSIONS) + + +@app.route('/publish', methods=['POST']) +@require_api_key +def upload_file(): + # check if the post request has the file part + if 'file' not in request.files or not request.files['file']: + return {'message': 'No file.'}, 400 + + file = request.files['file'] + + # Check wether a filename was provided + if file.filename == '': + return {'message': 'No filename.'}, 400 + + # Check wether the filename has an allowed file extension + if not allowed_file(file.filename): + return {'message': 'Invalid extension.'}, 400 + + # Create path for file & check if it already exists + filename = secure_filename(file.filename) + path = Path(app.config['UPLOAD_FOLDER']) / 'pkgs' / filename + + if path.exists(): + return {'message': 'File already exists.'}, 400 + + path.parent.mkdir(parents=True, exist_ok=True) + + # Store the file + file.save(path) + + # Run repo-add on the file + res = subprocess.run(["repo-add", path.parent.parent / "repo.db.tar.gz", path]) + + if res.returncode != 0: + path.unlink() + + return {'message': 'Failed to add file to repository.'}, 500 + + return {'message': 'Success.'}, 200 +