61 lines
1.6 KiB
Python
61 lines
1.6 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
|
|
from datetime import datetime
|
|
|
|
from flask import Blueprint, g, request, jsonify
|
|
from werkzeug.utils import secure_filename
|
|
|
|
from pyles.db import db, File, Tag, FileTag
|
|
from pyles.files import upload_file
|
|
from pyles.user import token_required
|
|
from pyles.settings import BASE_URL
|
|
|
|
bp = Blueprint("files_api", __name__)
|
|
|
|
|
|
@bp.post("/api/upload")
|
|
@token_required
|
|
def upload():
|
|
file = request.files.get("file")
|
|
if not file:
|
|
return jsonify({"error": "Missing file"}), 400
|
|
expires = None
|
|
tags = []
|
|
try:
|
|
exp = request.args.get("expires", type=int)
|
|
expires = datetime.fromtimestamp(exp) if exp else None
|
|
except:
|
|
pass
|
|
|
|
if raw_tags := request.args.get("tags"):
|
|
tags = [int(raw) for raw in raw_tags.split(",")]
|
|
tags: list[Tag] = Tag.select().where(Tag.id.in_(tags), Tag.user_id == g.user.id)
|
|
|
|
hash, content_type = upload_file(file)
|
|
|
|
with db.atomic():
|
|
db_file: File = File.create(
|
|
user=g.user,
|
|
filename=secure_filename(file.filename),
|
|
hash=hash,
|
|
content_type=content_type,
|
|
expires=expires,
|
|
)
|
|
|
|
if len(tags) > 0:
|
|
FileTag.bulk_create(FileTag(file=db_file, tag=tag) for tag in tags)
|
|
|
|
return jsonify(
|
|
{
|
|
"id": db_file.id,
|
|
"hash": db_file.hash,
|
|
"url": f"{BASE_URL}/{db_file.path}",
|
|
"tags": [{"id": tag.id, "name": tag.name} for tag in tags],
|
|
}
|
|
)
|
|
|
|
|
|
@bp.patch("/api/files/<url_id>")
|
|
@token_required
|
|
def update_file():
|
|
...
|