dev@locazia: converting media

This commit is contained in:
user 2024-04-05 18:22:27 +03:00
parent f83855a296
commit 084ae0850d
2 changed files with 64 additions and 3 deletions

View File

@ -1,3 +1,4 @@
import asyncio
import hashlib import hashlib
import os import os
from datetime import datetime from datetime import datetime
@ -13,6 +14,9 @@ from app.core._config import UPLOADS_DIR
from app.core._utils.resolve_content import resolve_content from app.core._utils.resolve_content import resolve_content
from app.core.logger import make_log from app.core.logger import make_log
from app.core.models.node_storage import StoredContent from app.core.models.node_storage import StoredContent
from pydub import AudioSegment
from PIL import Image
from uuid import uuid4
async def s_api_v1_storage_post(request): async def s_api_v1_storage_post(request):
@ -89,6 +93,8 @@ async def s_api_v1_storage_post(request):
async def s_api_v1_storage_get(request, file_hash=None): async def s_api_v1_storage_get(request, file_hash=None):
seconds_limit = int(request.args.get("seconds_limit", 0))
content_id = file_hash content_id = file_hash
cid, errmsg = resolve_content(content_id) cid, errmsg = resolve_content(content_id)
if errmsg: if errmsg:
@ -108,12 +114,60 @@ async def s_api_v1_storage_get(request, file_hash=None):
async with aiofiles.open(file_path, "rb") as file: async with aiofiles.open(file_path, "rb") as file:
content_file_bin = await file.read() content_file_bin = await file.read()
query_id = str(uuid4().hex())
tempfile_path = os.path.join(UPLOADS_DIR, f"tmp_{content_sha256}")
# async def remove_temp_files():
# await asyncio.sleep(180)
# if os.path.exists(tempfile_path):
# os.remove(tempfile_path)
accept_type = cid.accept_type or content.meta.get("content_type") accept_type = cid.accept_type or content.meta.get("content_type")
if accept_type: if accept_type:
if accept_type == "application/json": if accept_type == "application/json":
return response.json( return response.json(
json.loads(content_file_bin.decode()) json.loads(content_file_bin.decode())
) )
content_type, content_encoding = accept_type.split("/")
if content_type == 'audio':
tempfile_path += "_mpeg" + (f"_{seconds_limit}" if seconds_limit else "")
if not os.path.exists(tempfile_path):
try:
audio = AudioSegment(content_file_bin)
audio = audio[:seconds_limit * 1000] if seconds_limit else audio
audio.export(tempfile_path, format="mp3")
except BaseException as e:
make_log("Storage", f"Error converting audio: {e}" + '\n' + traceback.format_exc(), level="error")
if os.path.exists(tempfile_path):
async with aiofiles.open(tempfile_path, "rb") as file:
content_file_bin = await file.read()
make_log(f"Storage", f"Audio {content_sha256} converted successfully")
else:
tempfile_path = tempfile_path[:-5]
elif content_type == 'image':
tempfile_path += "_jpeg"
if not os.path.exists(tempfile_path):
try:
image = Image.open(file_path)
image = image.convert('RGB')
quality = 95
while quality > 10:
image.save(tempfile_path, 'JPEG', quality=quality)
if os.path.getsize(tempfile_path) <= 200 * 1024: # Проверка размера файла в килобайтах
break
quality -= 5
except BaseException as e:
make_log("Storage", f"Error converting image: {e}" + '\n' + traceback.format_exc(), level="error")
if os.path.exists(tempfile_path):
async with aiofiles.open(tempfile_path, "rb") as file:
content_file_bin = await file.read()
make_log(f"Storage", f"Image {content_sha256} converted successfully")
else:
tempfile_path = tempfile_path[:-5]
return response.raw(body=content_file_bin, **({'content_type': accept_type} if accept_type else {})) return response.raw(body=content_file_bin, **({'content_type': accept_type} if accept_type else {}))

View File

@ -88,9 +88,16 @@ class PlayerTemplates:
inline_keyboard_array = [] inline_keyboard_array = []
extra_buttons = [] extra_buttons = []
else: else:
have_access = False user_wallet_address = self.user.wallet_address(self.db_session)
have_access = (
(content.owner_address == user_wallet_address)
or bool(self.db_session.query(UserContent).filter_by(owner_address=user_wallet_address, status='active', content_id=content.id).first())
)
if not have_access:
inline_keyboard_array.append([{
'text': self.user.translated('buyTrackListenLicense_button').format(price=round(0.15 , 3)),
'callback_data': f'PC_{content.id}'
}])
make_log("TG-Player", f"Send content {content_type} ({content_encoding}) to chat {self._chat_id}. {cd_log}") make_log("TG-Player", f"Send content {content_type} ({content_encoding}) to chat {self._chat_id}. {cd_log}")
for kmsg in self.db_session.query(KnownTelegramMessage).filter_by( for kmsg in self.db_session.query(KnownTelegramMessage).filter_by(