mirror of
https://github.com/flibusta-apps/telegram_files_cache_server.git
synced 2025-12-08 09:30:40 +01:00
Add file downloading
This commit is contained in:
48
src/app/services/files_client.py
Normal file
48
src/app/services/files_client.py
Normal file
@@ -0,0 +1,48 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.config import env_config
|
||||
|
||||
|
||||
class UploadedFile(BaseModel):
|
||||
id: int
|
||||
backend: str
|
||||
data: dict
|
||||
upload_time: datetime
|
||||
|
||||
|
||||
async def upload_file(content: bytes, filename: str, caption: str) -> UploadedFile:
|
||||
headers = {"Authorization": env_config.FILES_SERVER_API_KEY}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
form = {"caption": caption}
|
||||
files = {"file": (filename, content)}
|
||||
|
||||
response = await client.post(
|
||||
f"{env_config.FILES_SERVER_URL}/api/v1/files/upload/",
|
||||
data=form,
|
||||
files=files,
|
||||
headers=headers,
|
||||
timeout=5 * 60,
|
||||
)
|
||||
|
||||
return UploadedFile.parse_obj(response.json())
|
||||
|
||||
|
||||
async def download_file(chat_id: int, message_id: int) -> Optional[bytes]:
|
||||
headers = {"Authorization": env_config.FILES_SERVER_API_KEY}
|
||||
|
||||
async with httpx.AsyncClient(timeout=60) as client:
|
||||
response = await client.get(
|
||||
f"{env_config.FILES_SERVER_URL}"
|
||||
f"/api/v1/files/download_by_message/{chat_id}/{message_id}",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
return None
|
||||
|
||||
return response.content
|
||||
Reference in New Issue
Block a user