86 lines
2.9 KiB
Python
86 lines
2.9 KiB
Python
from sanic import response
|
|
from app.core._config import UPLOADS_DIR
|
|
from app.core.storage import db_session
|
|
from app.core.content.content_id import ContentId
|
|
from app.core._utils.resolve_content import resolve_content
|
|
from app.core.models.node_storage import StoredContent
|
|
from app.core.logger import make_log
|
|
from datetime import datetime
|
|
from base58 import b58encode, b58decode
|
|
from mimetypes import guess_type
|
|
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_param.name
|
|
else:
|
|
return response.json({"error": "No file provided"}, status=400)
|
|
|
|
file_meta = {}
|
|
file_mimetype, file_encoding = guess_type(file_name)
|
|
if file_mimetype:
|
|
file_meta["content_type"] = file_mimetype
|
|
|
|
if file_encoding:
|
|
file_meta["extension_encoding"] = file_encoding
|
|
|
|
try:
|
|
file_hash = b58encode(hashlib.sha256(file_content).digest()).decode()
|
|
new_content = StoredContent(
|
|
type="local/content_bin",
|
|
user_id=request.ctx.user.id,
|
|
hash=file_hash,
|
|
filename=file_name,
|
|
meta=file_meta,
|
|
created=datetime.now(),
|
|
key_id=None,
|
|
btfs_cid="",
|
|
ipfs_cid="",
|
|
telegram_cid="",
|
|
)
|
|
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)
|
|
|
|
new_content_id = new_content.cid
|
|
new_cid = new_content_id.serialize_v1()
|
|
|
|
return response.json({
|
|
"content_sha256": file_hash,
|
|
"content_id_v1": new_cid,
|
|
"content_url": f"dmy://storage?cid={new_cid}",
|
|
})
|
|
except BaseException as e:
|
|
return response.json({"error": f"Error: {e}"}, status=500)
|
|
|
|
|
|
async def s_api_v1_storage_get(request, file_hash=None):
|
|
content_id = file_hash
|
|
cid, errmsg = resolve_content(content_id)
|
|
if errmsg:
|
|
return response.json({"error": errmsg}, status=400)
|
|
|
|
content_sha256 = b58encode(cid.content_hash).decode()
|
|
content = request.ctx.db_session.query(StoredContent).filter(StoredContent.hash == content_sha256).first()
|
|
if not content:
|
|
return response.json({"error": "File not found"}, status=404)
|
|
|
|
make_log("Storage", f"File {content_sha256} requested by {request.ip}")
|
|
file_path = os.path.join(UPLOADS_DIR, content_sha256)
|
|
if not os.path.exists(file_path):
|
|
return response.json({"error": "File not found"}, status=404)
|
|
|
|
return await response.file(file_path)
|