Update main.py
Browse files
main.py
CHANGED
|
@@ -6,6 +6,7 @@ from fastapi import FastAPI, UploadFile, File, HTTPException
|
|
| 6 |
from fastapi.responses import FileResponse
|
| 7 |
import uvicorn
|
| 8 |
import tempfile
|
|
|
|
| 9 |
|
| 10 |
# --- Configuration from environment variables ---
|
| 11 |
SESSION_STRING = os.environ.get('SESSION_STRING')
|
|
@@ -20,20 +21,20 @@ UPLOAD_DIR = tempfile.gettempdir()
|
|
| 20 |
|
| 21 |
app = FastAPI()
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
async def upload_to_telegram(file_path: str):
|
| 24 |
-
"""
|
| 25 |
-
Uploads a file to the Telegram channel and returns the message object.
|
| 26 |
-
"""
|
| 27 |
if not all([SESSION_STRING, API_ID, API_HASH]):
|
| 28 |
-
raise ValueError("
|
| 29 |
-
|
| 30 |
async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
|
| 31 |
try:
|
| 32 |
-
|
| 33 |
-
message = await client.send_file(TARGET_CHANNEL, file_path)
|
| 34 |
-
# Check if the upload was successful and returned a message with media
|
| 35 |
if not message or not message.media:
|
| 36 |
-
raise HTTPException(status_code=500, detail="
|
| 37 |
return message
|
| 38 |
except Exception as e:
|
| 39 |
raise HTTPException(status_code=500, detail=f"Failed to upload to Telegram: {e}")
|
|
@@ -41,62 +42,62 @@ async def upload_to_telegram(file_path: str):
|
|
| 41 |
@app.post("/v1/upload")
|
| 42 |
async def upload_file(file: UploadFile = File(...)):
|
| 43 |
"""
|
| 44 |
-
|
| 45 |
"""
|
| 46 |
file_location = os.path.join(UPLOAD_DIR, file.filename)
|
| 47 |
try:
|
| 48 |
with open(file_location, "wb+") as file_object:
|
| 49 |
file_object.write(file.file.read())
|
| 50 |
|
| 51 |
-
# Upload the file and get the message object
|
| 52 |
message = await upload_to_telegram(file_location)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
|
| 56 |
-
original_filename = message.file.name if message.file and message.file.name else file.filename
|
| 57 |
|
|
|
|
| 58 |
return {
|
| 59 |
-
"message": "File uploaded successfully
|
| 60 |
-
"
|
| 61 |
-
"
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
}
|
| 64 |
finally:
|
| 65 |
-
# Clean up the local temporary file
|
| 66 |
if os.path.exists(file_location):
|
| 67 |
os.remove(file_location)
|
| 68 |
|
| 69 |
-
@app.get("/v1/download/{
|
| 70 |
-
async def download_file(
|
| 71 |
"""
|
| 72 |
-
Downloads a file from Telegram
|
| 73 |
"""
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
|
| 77 |
download_path = None
|
| 78 |
try:
|
| 79 |
async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
|
| 80 |
-
# Get the specific message from the channel using the message_id
|
| 81 |
message = await client.get_messages(TARGET_CHANNEL, ids=message_id)
|
| 82 |
-
|
| 83 |
if not message or not message.media:
|
| 84 |
-
raise HTTPException(status_code=404, detail="
|
| 85 |
|
| 86 |
-
# Download the media to the temporary directory
|
| 87 |
-
# Telethon will return the path where the file was saved
|
| 88 |
download_path = await client.download_media(message, file=UPLOAD_DIR)
|
| 89 |
-
|
| 90 |
-
# Determine the filename to send to the user
|
| 91 |
-
response_filename = message.file.name if message.file and message.file.name else "downloaded_file"
|
| 92 |
-
|
| 93 |
-
# Return the file as a response
|
| 94 |
-
return FileResponse(download_path, media_type='application/octet-stream', filename=response_filename)
|
| 95 |
-
|
| 96 |
except Exception as e:
|
| 97 |
-
raise HTTPException(status_code=500, detail=f"Failed to download
|
| 98 |
finally:
|
| 99 |
-
# Crucially, clean up the downloaded file from the server's temp storage
|
| 100 |
if download_path and os.path.exists(download_path):
|
| 101 |
os.remove(download_path)
|
| 102 |
|
|
|
|
| 6 |
from fastapi.responses import FileResponse
|
| 7 |
import uvicorn
|
| 8 |
import tempfile
|
| 9 |
+
from typing import Dict
|
| 10 |
|
| 11 |
# --- Configuration from environment variables ---
|
| 12 |
SESSION_STRING = os.environ.get('SESSION_STRING')
|
|
|
|
| 21 |
|
| 22 |
app = FastAPI()
|
| 23 |
|
| 24 |
+
# --- In-Memory Database for Filename to Message ID mapping ---
|
| 25 |
+
# NOTE: This dictionary is not persistent. It will be cleared if the server restarts.
|
| 26 |
+
# For production, replace this with a real database (e.g., Redis, SQLite).
|
| 27 |
+
file_map: Dict[str, int] = {}
|
| 28 |
+
|
| 29 |
async def upload_to_telegram(file_path: str):
|
| 30 |
+
"""Uploads a file and returns the full Telegram message object."""
|
|
|
|
|
|
|
| 31 |
if not all([SESSION_STRING, API_ID, API_HASH]):
|
| 32 |
+
raise ValueError("Server is not configured with Telegram credentials.")
|
|
|
|
| 33 |
async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
|
| 34 |
try:
|
| 35 |
+
message = await client.send_file(TARGET_CHANNEL, file_path, force_document=True)
|
|
|
|
|
|
|
| 36 |
if not message or not message.media:
|
| 37 |
+
raise HTTPException(status_code=500, detail="Upload failed to return a valid message.")
|
| 38 |
return message
|
| 39 |
except Exception as e:
|
| 40 |
raise HTTPException(status_code=500, detail=f"Failed to upload to Telegram: {e}")
|
|
|
|
| 42 |
@app.post("/v1/upload")
|
| 43 |
async def upload_file(file: UploadFile = File(...)):
|
| 44 |
"""
|
| 45 |
+
Uploads a file to Telegram, stores its mapping, and returns full API details.
|
| 46 |
"""
|
| 47 |
file_location = os.path.join(UPLOAD_DIR, file.filename)
|
| 48 |
try:
|
| 49 |
with open(file_location, "wb+") as file_object:
|
| 50 |
file_object.write(file.file.read())
|
| 51 |
|
|
|
|
| 52 |
message = await upload_to_telegram(file_location)
|
| 53 |
+
doc = message.document
|
| 54 |
+
|
| 55 |
+
# Extract the original filename from the document attributes
|
| 56 |
+
original_filename = next((attr.file_name for attr in doc.attributes if hasattr(attr, 'file_name')), file.filename)
|
| 57 |
|
| 58 |
+
# Store the mapping in our in-memory "database"
|
| 59 |
+
file_map[original_filename] = message.id
|
|
|
|
| 60 |
|
| 61 |
+
# Return a rich, detailed JSON response from the Telegram API
|
| 62 |
return {
|
| 63 |
+
"message": "File uploaded successfully.",
|
| 64 |
+
"channel": TARGET_CHANNEL,
|
| 65 |
+
"telegram_details": {
|
| 66 |
+
"message_id": message.id,
|
| 67 |
+
"file_id": doc.id,
|
| 68 |
+
"file_reference": doc.file_reference.hex() if doc.file_reference else None,
|
| 69 |
+
"filename": original_filename,
|
| 70 |
+
"size_bytes": doc.size,
|
| 71 |
+
"mime_type": doc.mime_type,
|
| 72 |
+
"date": message.date.isoformat()
|
| 73 |
+
}
|
| 74 |
}
|
| 75 |
finally:
|
|
|
|
| 76 |
if os.path.exists(file_location):
|
| 77 |
os.remove(file_location)
|
| 78 |
|
| 79 |
+
@app.get("/v1/download/{filename}")
|
| 80 |
+
async def download_file(filename: str):
|
| 81 |
"""
|
| 82 |
+
Downloads a file from Telegram by its filename using the stored mapping.
|
| 83 |
"""
|
| 84 |
+
# Look up the message_id from our in-memory map
|
| 85 |
+
message_id = file_map.get(filename)
|
| 86 |
+
if not message_id:
|
| 87 |
+
raise HTTPException(status_code=404, detail=f"File '{filename}' not found. The server may have restarted or the file was never uploaded.")
|
| 88 |
|
| 89 |
download_path = None
|
| 90 |
try:
|
| 91 |
async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
|
|
|
|
| 92 |
message = await client.get_messages(TARGET_CHANNEL, ids=message_id)
|
|
|
|
| 93 |
if not message or not message.media:
|
| 94 |
+
raise HTTPException(status_code=404, detail="File found in map, but message is missing or has no media in Telegram.")
|
| 95 |
|
|
|
|
|
|
|
| 96 |
download_path = await client.download_media(message, file=UPLOAD_DIR)
|
| 97 |
+
return FileResponse(download_path, media_type='application/octet-stream', filename=filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
+
raise HTTPException(status_code=500, detail=f"Failed to download from Telegram: {e}")
|
| 100 |
finally:
|
|
|
|
| 101 |
if download_path and os.path.exists(download_path):
|
| 102 |
os.remove(download_path)
|
| 103 |
|