nikhilyadavtemp1 commited on
Commit
76a638f
Β·
1 Parent(s): 41ff2c2

feat: integrate Telegram bot for file management and high-speed local hosting

Browse files
Files changed (2) hide show
  1. main.py +105 -64
  2. requirements.txt +2 -0
main.py CHANGED
@@ -1,37 +1,112 @@
1
  import os
2
  import shutil
3
  import time
4
- from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Header, Request
5
- from fastapi.responses import FileResponse, JSONResponse
6
- from fastapi.staticfiles import StaticFiles
7
- from typing import List, Optional
8
  import uuid
9
  import threading
 
 
 
 
 
 
 
10
 
11
- app = FastAPI(title="Advanced File Sharing API")
12
-
 
13
  UPLOAD_DIR = "uploads"
14
  os.makedirs(UPLOAD_DIR, exist_ok=True)
15
 
16
- # Background task to cleanup old files (older than 24 hours)
 
 
17
  def cleanup_old_files():
18
  while True:
19
  now = time.time()
20
  for filename in os.listdir(UPLOAD_DIR):
21
  file_path = os.path.join(UPLOAD_DIR, filename)
22
  if os.path.isfile(file_path):
23
- # 24 hours = 86400 seconds
24
- if now - os.path.getmtime(file_path) > 86400:
25
  try:
26
  os.remove(file_path)
27
- print(f"Deleted old file: {filename}")
28
- except Exception as e:
29
- print(f"Error deleting {filename}: {e}")
30
- time.sleep(3600) # Check every hour
31
 
32
- # Start cleanup thread
33
  threading.Thread(target=cleanup_old_files, daemon=True).start()
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  app.mount("/static", StaticFiles(directory="static"), name="static")
36
 
37
  @app.get("/")
@@ -50,84 +125,50 @@ async def upload_files(
50
  user_id = x_user_id or "cli-anonymous"
51
  uploaded_files = []
52
 
53
- # Case 1: Direct Binary Upload (curl -T)
54
  if request.method == "PUT" or (not files and not file):
55
  content = await request.body()
56
- if not content:
57
- raise HTTPException(status_code=400, detail="Empty file")
58
-
59
- # Determine filename: from URL path, then header, then default
60
  final_name = filename or request.headers.get("x-filename") or f"upload_{int(time.time())}"
61
  file_id = str(uuid.uuid4())[:8]
62
  safe_name = f"{user_id}_{file_id}_{final_name}"
63
  file_path = os.path.join(UPLOAD_DIR, safe_name)
64
-
65
  with open(file_path, "wb") as buffer:
66
  buffer.write(content)
67
-
68
- url = f"https://ttnikal-filesharing.hf.space/download/{safe_name}"
69
- return f"{url}\n"
70
 
71
- # Case 2: Multipart Upload (Web/Standard Curl)
72
  target_files = []
73
  if files: target_files.extend(files)
74
  if file: target_files.append(file)
75
 
76
  for f in target_files:
77
  file_id = str(uuid.uuid4())[:8]
78
- filename = f"{user_id}_{file_id}_{f.filename}"
79
- file_path = os.path.join(UPLOAD_DIR, filename)
80
  with open(file_path, "wb") as buffer:
81
  shutil.copyfileobj(f.file, buffer)
82
- uploaded_files.append(f"https://ttnikal-filesharing.hf.space/download/{filename}")
83
 
84
- if len(target_files) == 1 and not x_user_id:
85
- return f"{uploaded_files[0]}\n"
86
- return {"message": "Upload successful", "urls": uploaded_files}
87
 
88
  @app.get("/files")
89
  async def list_files(x_user_id: str = Header(None)):
90
- if not x_user_id:
91
- return []
92
-
93
- files = []
94
- for filename in os.listdir(UPLOAD_DIR):
95
- if filename.startswith(f"{x_user_id}_"):
96
- file_path = os.path.join(UPLOAD_DIR, filename)
97
- if os.path.isfile(file_path):
98
- # Remove user_id and file_id from display name
99
- parts = filename.split("_")
100
- display_name = "_".join(parts[2:])
101
-
102
- files.append({
103
- "name": filename,
104
- "display_name": display_name,
105
- "size": os.path.getsize(file_path),
106
- "mtime": os.path.getmtime(file_path)
107
- })
108
- files.sort(key=lambda x: x['mtime'], reverse=True)
109
- return files
110
 
111
  @app.get("/download/{filename}")
112
  async def download_file(filename: str):
113
  file_path = os.path.join(UPLOAD_DIR, filename)
114
- if not os.path.exists(file_path):
115
- raise HTTPException(status_code=404, detail="File not found")
116
-
117
- parts = filename.split("_")
118
- original_name = "_".join(parts[2:])
119
- return FileResponse(file_path, filename=original_name)
120
 
121
  @app.delete("/delete/{filename}")
122
  async def delete_file(filename: str, x_user_id: str = Header(None)):
123
- if not x_user_id or not filename.startswith(f"{x_user_id}_"):
124
- raise HTTPException(status_code=403, detail="Not authorized to delete this file")
125
-
126
- file_path = os.path.join(UPLOAD_DIR, filename)
127
- if not os.path.exists(file_path):
128
- raise HTTPException(status_code=404, detail="File not found")
129
- os.remove(file_path)
130
- return {"message": "File deleted successfully"}
131
 
132
  if __name__ == "__main__":
133
  import uvicorn
 
1
  import os
2
  import shutil
3
  import time
 
 
 
 
4
  import uuid
5
  import threading
6
+ import asyncio
7
+ from typing import List, Optional
8
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Request
9
+ from fastapi.responses import FileResponse
10
+ from fastapi.staticfiles import StaticFiles
11
+ from telegram import Update, Bot
12
+ from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
13
 
14
+ # --- CONFIGURATION ---
15
+ TOKEN = os.getenv("TELEGRAM_TOKEN")
16
+ BASE_URL = "https://ttnikal-filesharing.hf.space"
17
  UPLOAD_DIR = "uploads"
18
  os.makedirs(UPLOAD_DIR, exist_ok=True)
19
 
20
+ app = FastAPI(title="Advanced File Sharing API with Telegram")
21
+
22
+ # --- CLEANUP TASK ---
23
  def cleanup_old_files():
24
  while True:
25
  now = time.time()
26
  for filename in os.listdir(UPLOAD_DIR):
27
  file_path = os.path.join(UPLOAD_DIR, filename)
28
  if os.path.isfile(file_path):
29
+ if now - os.path.getmtime(file_path) > 86400: # 24h
 
30
  try:
31
  os.remove(file_path)
32
+ except: pass
33
+ time.sleep(3600)
 
 
34
 
 
35
  threading.Thread(target=cleanup_old_files, daemon=True).start()
36
 
37
+ # --- TELEGRAM BOT LOGIC ---
38
+ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
39
+ await update.message.reply_text(
40
+ "πŸ‘‹ Welcome to NexusShare Bot!\n\n"
41
+ "Send me any file, and I'll host it for you.\n"
42
+ "Commands:\n"
43
+ "/files - List your uploaded files\n"
44
+ "/help - Show this message"
45
+ )
46
+
47
+ async def handle_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
48
+ file = update.message.document or update.message.video or update.message.audio or update.message.photo[-1]
49
+ file_id = file.file_id
50
+ file_name = getattr(file, 'file_name', f"file_{int(time.time())}")
51
+ if update.message.photo: file_name = f"photo_{int(time.time())}.jpg"
52
+
53
+ status_msg = await update.message.reply_text("πŸ“₯ Initializing download...")
54
+
55
+ # User ID for isolation (Tg ID)
56
+ user_id = f"tg{update.effective_user.id}"
57
+ unique_id = str(uuid.uuid4())[:8]
58
+ save_name = f"{user_id}_{unique_id}_{file_name}"
59
+ file_path = os.path.join(UPLOAD_DIR, save_name)
60
+
61
+ try:
62
+ new_file = await context.bot.get_file(file_id)
63
+
64
+ await status_msg.edit_text("⚑ Downloading and saving to disk for high-speed access...")
65
+
66
+ # Download the file
67
+ await new_file.download_to_drive(file_path)
68
+
69
+ download_url = f"{BASE_URL}/download/{save_name}"
70
+
71
+ await status_msg.edit_text(
72
+ f"βœ… *File Uploaded Successfully!*\n\n"
73
+ f"πŸ”— *URL:* {download_url}\n"
74
+ f"πŸ“‚ *Name:* {file_name}\n\n"
75
+ f"⚠️ *Note:* Valid for 24 hours. Links will reset if the server restarts.",
76
+ parse_mode='Markdown'
77
+ )
78
+ except Exception as e:
79
+ await status_msg.edit_text(f"❌ Error: {str(e)}")
80
+
81
+ async def list_user_files(update: Update, context: ContextTypes.DEFAULT_TYPE):
82
+ user_id = f"tg{update.effective_user.id}"
83
+ files = []
84
+ for filename in os.listdir(UPLOAD_DIR):
85
+ if filename.startswith(f"{user_id}_"):
86
+ parts = filename.split("_")
87
+ display_name = "_".join(parts[2:])
88
+ files.append(f"β€’ {display_name}\n β”” {BASE_URL}/download/{filename}")
89
+
90
+ if not files:
91
+ await update.message.reply_text("You haven't uploaded any files yet.")
92
+ else:
93
+ await update.message.reply_text("πŸ“‚ *Your Files (24h valid):*\n\n" + "\n".join(files), parse_mode='Markdown')
94
+
95
+ # Run Bot in Background
96
+ def run_bot():
97
+ if not TOKEN:
98
+ print("Telegram Token not found!")
99
+ return
100
+ application = ApplicationBuilder().token(TOKEN).build()
101
+ application.add_handler(CommandHandler("start", start))
102
+ application.add_handler(CommandHandler("files", list_user_files))
103
+ application.add_handler(MessageHandler(filters.ALL & ~filters.COMMAND, handle_document))
104
+ application.run_polling()
105
+
106
+ if TOKEN:
107
+ threading.Thread(target=run_bot, daemon=True).start()
108
+
109
+ # --- FASTAPI ENDPOINTS ---
110
  app.mount("/static", StaticFiles(directory="static"), name="static")
111
 
112
  @app.get("/")
 
125
  user_id = x_user_id or "cli-anonymous"
126
  uploaded_files = []
127
 
 
128
  if request.method == "PUT" or (not files and not file):
129
  content = await request.body()
 
 
 
 
130
  final_name = filename or request.headers.get("x-filename") or f"upload_{int(time.time())}"
131
  file_id = str(uuid.uuid4())[:8]
132
  safe_name = f"{user_id}_{file_id}_{final_name}"
133
  file_path = os.path.join(UPLOAD_DIR, safe_name)
 
134
  with open(file_path, "wb") as buffer:
135
  buffer.write(content)
136
+ return f"{BASE_URL}/download/{safe_name}\n"
 
 
137
 
 
138
  target_files = []
139
  if files: target_files.extend(files)
140
  if file: target_files.append(file)
141
 
142
  for f in target_files:
143
  file_id = str(uuid.uuid4())[:8]
144
+ name = f"{user_id}_{file_id}_{f.filename}"
145
+ file_path = os.path.join(UPLOAD_DIR, name)
146
  with open(file_path, "wb") as buffer:
147
  shutil.copyfileobj(f.file, buffer)
148
+ uploaded_files.append(f"{BASE_URL}/download/{name}")
149
 
150
+ return uploaded_files[0] if len(target_files) == 1 and not x_user_id else {"urls": uploaded_files}
 
 
151
 
152
  @app.get("/files")
153
  async def list_files(x_user_id: str = Header(None)):
154
+ if not x_user_id: return []
155
+ res = []
156
+ for f in os.listdir(UPLOAD_DIR):
157
+ if f.startswith(f"{x_user_id}_"):
158
+ res.append({"name": f, "display_name": "_".join(f.split("_")[2:]), "size": os.path.getsize(os.path.join(UPLOAD_DIR, f)), "mtime": os.path.getmtime(os.path.join(UPLOAD_DIR, f))})
159
+ return sorted(res, key=lambda x: x['mtime'], reverse=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
  @app.get("/download/{filename}")
162
  async def download_file(filename: str):
163
  file_path = os.path.join(UPLOAD_DIR, filename)
164
+ if not os.path.exists(file_path): raise HTTPException(status_code=404)
165
+ return FileResponse(file_path, filename="_".join(filename.split("_")[2:]))
 
 
 
 
166
 
167
  @app.delete("/delete/{filename}")
168
  async def delete_file(filename: str, x_user_id: str = Header(None)):
169
+ if not x_user_id or not filename.startswith(f"{x_user_id}_"): raise HTTPException(status_code=403)
170
+ if os.path.exists(os.path.join(UPLOAD_DIR, filename)): os.remove(os.path.join(UPLOAD_DIR, filename))
171
+ return {"status": "deleted"}
 
 
 
 
 
172
 
173
  if __name__ == "__main__":
174
  import uvicorn
requirements.txt CHANGED
@@ -2,3 +2,5 @@ fastapi
2
  uvicorn
3
  python-multipart
4
  aiofiles
 
 
 
2
  uvicorn
3
  python-multipart
4
  aiofiles
5
+ python-telegram-bot
6
+ aiohttp