uploader-bot/app/api/routes/node_storage.py

59 lines
2.0 KiB
Python

from sanic import response
from app.core._config import UPLOADS_DIR
from app.core.storage import db_session
from app.core.models.node_storage import StoredContent
from app.core.logger import make_log
from datetime import datetime
from base58 import b58encode, b58decode
import os
import hashlib
async def s_api_v1_storage_post(request):
if not request.files and not request.json:
return response.json({"error": "No file provided"}, status=400)
file_param = list(request.files.values())[0][0] if request.files else None
file_name_json = request.json.get("filename") if request.json else None
if file_param:
file_content = file_param.body
file_name = file_name_json or file_param.name
else:
return response.json({"error": "No file provided"}, status=400)
try:
file_hash = b58encode(hashlib.sha256(file_content).digest()).decode()
new_content = StoredContent(
hash=file_hash,
filename=file_name,
user_id=None,
meta={},
created=datetime.now(),
key_id=None
)
request.ctx.db_session.add(new_content)
request.ctx.db_session.commit()
file_path = os.path.join(UPLOADS_DIR, file_hash)
with open(file_path, "wb") as file:
file.write(file_content)
return response.json({"content_sha256": file_hash})
except BaseException as e:
return response.json({"error": f"Error: {e}"}, status=500)
async def s_api_v1_storage_get(request, file_hash):
content = request.ctx.db_session.query(StoredContent).filter(StoredContent.hash == file_hash).first()
if not content:
return response.json({"error": "File not found"}, status=404)
make_log(f"File {file_hash} requested by {request.ip}")
file_path = os.path.join(UPLOADS_DIR, file_hash)
if not os.path.exists(file_path):
return response.json({"error": "File not found"}, status=404)
return await response.file(file_path)