From 07d59395ce212e612711719ab0f29908eb446f85 Mon Sep 17 00:00:00 2001 From: TheErrorExe <161362055+TheErrorExe@users.noreply.github.com> Date: Tue, 1 Apr 2025 21:21:31 +0200 Subject: [PATCH] Update helper.py --- helper.py | 64 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 27 deletions(-) diff --git a/helper.py b/helper.py index a4a5d25..af27c49 100644 --- a/helper.py +++ b/helper.py @@ -1,57 +1,67 @@ import json import os import subprocess +import aiofiles +import aiohttp - -def read_file(path): +async def read_file(path): assert isinstance(path, str), "Path must be a string" try: - with open(path, 'r', encoding='utf-8') as file: - content = file.read() + async with aiofiles.open(path, 'r', encoding='utf-8') as file: + content = await file.read() return content except FileNotFoundError: return "Error: File not found." except Exception as e: return f"Error: {str(e)}" - -def get_video_duration_from_file(video_path): +async def get_video_duration_from_file(video_path): try: - result = subprocess.run( - ['ffprobe', '-v', 'error', '-show_format', '-show_streams', '-of', 'json', video_path], - stdout=subprocess.PIPE, stderr=subprocess.PIPE + result = await asyncio.create_subprocess_exec( + 'ffprobe', '-v', 'error', '-show_format', '-show_streams', '-of', 'json', video_path, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE ) - video_info = json.loads(result.stdout) + stdout, stderr = await result.communicate() + if result.returncode != 0: + raise Exception(stderr.decode()) + + video_info = json.loads(stdout.decode()) duration = float(video_info['format']['duration']) - return duration except Exception as e: print(f"Can't fetch Video-Duration: {str(e)}") return 0 - -def format_duration(seconds): +async def format_duration(seconds): minutes = seconds // 60 seconds = seconds % 60 return f"{minutes}:{str(seconds).zfill(2)}" - -def get_file_size(file_path): - return os.path.getsize(file_path) - - -def get_range(file_path, byte_range): - with open(file_path, 'rb') as f: - f.seek(byte_range[0]) - return f.read(byte_range[1] - byte_range[0] + 1) - - -def get_api_key(): +async def get_file_size(file_path): try: - with open("token.txt", "r") as f: - return f.read().strip() + stat = os.stat(file_path) + return stat.st_size + except Exception as e: + print(f"Error getting file size: {str(e)}") + return 0 + +async def get_range(file_path, byte_range): + try: + async with aiofiles.open(file_path, 'rb') as f: + await f.seek(byte_range[0]) + data = await f.read(byte_range[1] - byte_range[0] + 1) + return data + except Exception as e: + print(f"Error reading file range: {str(e)}") + return b'' + +async def get_api_key(): + try: + async with aiofiles.open("token.txt", "r") as f: + return (await f.read()).strip() except FileNotFoundError: raise FileNotFoundError("Missing token.txt. Please go to README.md")