Update main.py
Browse files
main.py
CHANGED
|
@@ -2,9 +2,8 @@ import os
|
|
| 2 |
import asyncio
|
| 3 |
from telethon.sync import TelegramClient
|
| 4 |
from telethon.sessions import StringSession
|
| 5 |
-
from telethon.tl.functions.upload import GetFileRequest
|
| 6 |
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 7 |
-
from fastapi.responses import
|
| 8 |
import uvicorn
|
| 9 |
import tempfile
|
| 10 |
|
|
@@ -39,13 +38,13 @@ async def upload_file(file: UploadFile = File(...)):
|
|
| 39 |
doc = message.document
|
| 40 |
original_filename = next((attr.file_name for attr in doc.attributes if hasattr(attr, 'file_name')), file.filename)
|
| 41 |
|
|
|
|
| 42 |
return {
|
| 43 |
"message": "File uploaded successfully. Use the 'message_id' to download.",
|
| 44 |
"telegram_details": {
|
| 45 |
"message_id": message.id,
|
| 46 |
"filename": original_filename,
|
| 47 |
"size_bytes": doc.size,
|
| 48 |
-
"mime_type": doc.mime_type,
|
| 49 |
"date": message.date.isoformat()
|
| 50 |
}
|
| 51 |
}
|
|
@@ -58,42 +57,40 @@ async def upload_file(file: UploadFile = File(...)):
|
|
| 58 |
@app.get("/v1/download/{message_id}")
|
| 59 |
async def download_file(message_id: int):
|
| 60 |
"""
|
| 61 |
-
|
| 62 |
-
This is extremely fast and efficient.
|
| 63 |
"""
|
| 64 |
if not all([SESSION_STRING, API_ID, API_HASH]):
|
| 65 |
raise HTTPException(status_code=500, detail="Server is not configured for downloads.")
|
| 66 |
|
|
|
|
|
|
|
|
|
|
| 67 |
try:
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
location=location,
|
| 82 |
-
cdn_supported=True,
|
| 83 |
-
offset=0,
|
| 84 |
-
limit=0
|
| 85 |
-
)
|
| 86 |
-
result = await client(req)
|
| 87 |
-
|
| 88 |
-
# The result contains the temporary URL.
|
| 89 |
-
# Format: https://{cdn_redirect_ip}/.../{file_token}
|
| 90 |
-
cdn_url = f"https://{result.cdn_redirect}/file/{result.bytes.hex()}"
|
| 91 |
-
|
| 92 |
-
# Immediately redirect the user's client to this URL
|
| 93 |
-
return RedirectResponse(url=cdn_url, status_code=307)
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
if __name__ == "__main__":
|
| 99 |
if not all([SESSION_STRING, API_ID, API_HASH]):
|
|
|
|
| 2 |
import asyncio
|
| 3 |
from telethon.sync import TelegramClient
|
| 4 |
from telethon.sessions import StringSession
|
|
|
|
| 5 |
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 6 |
+
from fastapi.responses import StreamingResponse
|
| 7 |
import uvicorn
|
| 8 |
import tempfile
|
| 9 |
|
|
|
|
| 38 |
doc = message.document
|
| 39 |
original_filename = next((attr.file_name for attr in doc.attributes if hasattr(attr, 'file_name')), file.filename)
|
| 40 |
|
| 41 |
+
# Simplified response with only the essentials
|
| 42 |
return {
|
| 43 |
"message": "File uploaded successfully. Use the 'message_id' to download.",
|
| 44 |
"telegram_details": {
|
| 45 |
"message_id": message.id,
|
| 46 |
"filename": original_filename,
|
| 47 |
"size_bytes": doc.size,
|
|
|
|
| 48 |
"date": message.date.isoformat()
|
| 49 |
}
|
| 50 |
}
|
|
|
|
| 57 |
@app.get("/v1/download/{message_id}")
|
| 58 |
async def download_file(message_id: int):
|
| 59 |
"""
|
| 60 |
+
Streams a file directly from Telegram to the client, ensuring a fast download start.
|
|
|
|
| 61 |
"""
|
| 62 |
if not all([SESSION_STRING, API_ID, API_HASH]):
|
| 63 |
raise HTTPException(status_code=500, detail="Server is not configured for downloads.")
|
| 64 |
|
| 65 |
+
client = TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH)
|
| 66 |
+
await client.connect()
|
| 67 |
+
|
| 68 |
try:
|
| 69 |
+
message = await client.get_messages(TARGET_CHANNEL, ids=message_id)
|
| 70 |
+
if not message or not message.media:
|
| 71 |
+
raise HTTPException(status_code=404, detail=f"Message not found or has no media.")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
await client.disconnect()
|
| 74 |
+
raise HTTPException(status_code=500, detail=f"Could not retrieve file details: {e}")
|
| 75 |
|
| 76 |
+
original_filename = message.file.name if message.file and message.file.name else f"download_{message_id}"
|
| 77 |
+
mime_type = message.file.mime_type if message.file else 'application/octet-stream'
|
| 78 |
+
|
| 79 |
+
headers = {
|
| 80 |
+
'Content-Disposition': f'attachment; filename="{original_filename}"'
|
| 81 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
async def file_iterator():
|
| 84 |
+
"""This async generator streams the file and ensures the client disconnects."""
|
| 85 |
+
try:
|
| 86 |
+
# Stream the file chunk by chunk
|
| 87 |
+
async for chunk in client.iter_download(message):
|
| 88 |
+
yield chunk
|
| 89 |
+
finally:
|
| 90 |
+
# Crucially, disconnect after the download is complete or fails
|
| 91 |
+
await client.disconnect()
|
| 92 |
+
|
| 93 |
+
return StreamingResponse(file_iterator(), media_type=mime_type, headers=headers)
|
| 94 |
|
| 95 |
if __name__ == "__main__":
|
| 96 |
if not all([SESSION_STRING, API_ID, API_HASH]):
|