File size: 2,275 Bytes
f1354ed
 
894989c
 
d459a7d
c42d5ea
894989c
c42d5ea
 
894989c
1f5e81c
c42d5ea
 
f1354ed
 
 
0ecff8c
1f5e81c
c42d5ea
 
f1354ed
 
 
 
 
 
 
 
 
 
 
 
894989c
f1354ed
 
 
 
0ecff8c
f1354ed
 
1f5e81c
f1354ed
 
 
 
 
1f5e81c
f1354ed
1f5e81c
f1354ed
 
 
 
 
 
 
 
 
 
 
 
 
0ecff8c
1f5e81c
f1354ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from fastapi import FastAPI, Request, UploadFile, File
from fastapi.responses import JSONResponse
import os
from datetime import datetime

app = FastAPI()

SAVE_DIR = "files"
os.makedirs(SAVE_DIR, exist_ok=True)


@app.get("/")
def home():
    """Health check endpoint"""
    print("✅ Health check")
    return {"status": "running", "service": "Telegram File Storage"}


@app.post("/upload")
async def upload(request: Request):
    """
    دریافت فایل از تلگرام بات (از طریق Koyeb)
    """
    try:
        # خواندن محتوای فایل
        data = await request.body()
        
        if not data:
            return JSONResponse(
                {"error": "No file data received"}, 
                status_code=400
            )

        # گرفتن نام فایل از header
        filename = request.headers.get("X-Filename")
        if not filename:
            filename = f"file_{datetime.now().strftime('%Y%m%d_%H%M%S')}.bin"

        size_kb = round(len(data) / 1024, 2)
        print(f"📥 File received: {filename} | {size_kb} KB")

        # ذخیره فایل
        file_path = os.path.join(SAVE_DIR, filename)
        
        with open(file_path, "wb") as f:
            f.write(data)

        print(f"💾 Saved to: {file_path}")

        return {
            "status": "success",
            "saved": filename,
            "size_kb": size_kb,
            "path": file_path
        }
        
    except Exception as e:
        print(f"❌ Error: {e}")
        return JSONResponse(
            {"error": str(e)}, 
            status_code=500
        )


@app.get("/files")
def list_files():
    """لیست فایل‌های ذخیره شده"""
    try:
        files = os.listdir(SAVE_DIR)
        file_info = []
        
        for f in files:
            path = os.path.join(SAVE_DIR, f)
            size = os.path.getsize(path)
            file_info.append({
                "name": f,
                "size_kb": round(size / 1024, 2)
            })
        
        return {
            "total": len(files),
            "files": file_info
        }
    except Exception as e:
        return {"error": str(e)}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)