2021-12-30 21:08:28 +01:00
|
|
|
import os
|
|
|
|
from flask import Flask, request
|
|
|
|
from pathlib import Path
|
|
|
|
from werkzeug.utils import secure_filename
|
|
|
|
import subprocess
|
|
|
|
|
2021-12-30 21:18:12 +01:00
|
|
|
UPLOAD_FOLDER = Path(os.environ['REPO_DIR']) / "pkgs"
|
|
|
|
API_KEY = os.environ['API_KEY']
|
2021-12-30 21:08:28 +01:00
|
|
|
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)
|
2021-12-30 21:18:12 +01:00
|
|
|
path = Path(app.config['UPLOAD_FOLDER']) / filename
|
2021-12-30 21:08:28 +01:00
|
|
|
|
|
|
|
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
|
2021-12-30 22:28:24 +01:00
|
|
|
res = subprocess.run(["repo-add", path.parent.parent / "repo.db.tar.gz", path])
|
2021-12-30 21:08:28 +01:00
|
|
|
|
|
|
|
if res.returncode != 0:
|
|
|
|
path.unlink()
|
|
|
|
|
|
|
|
return {'message': 'Failed to add file to repository.'}, 500
|
|
|
|
|
|
|
|
return {'message': 'Success.'}, 200
|