import os import sys import json import uuid import time import shutil import secrets import subprocess import threading from typing import Dict, List, Optional from datetime import datetime, timedelta from fastapi import FastAPI, HTTPException, Request, Response from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from starlette.middleware.base import BaseHTTPMiddleware from pydantic import BaseModel # ---------------------------------------------------- # 1. Environment & Folder Configurations # ---------------------------------------------------- if os.path.exists("/data") and os.access("/data", os.W_OK): DATA_DIR = "/data" else: current_dir = os.path.dirname(os.path.abspath(__file__)) workspace_root = os.path.dirname(current_dir) DATA_DIR = os.path.join(workspace_root, "data") os.makedirs(DATA_DIR, exist_ok=True) # ---------------------------------------------------- # 2. Authentication Manager # ---------------------------------------------------- class AuthManager: """ Manages session tokens, rate limiting, and IP lockouts. All state is in-memory; restarts invalidate all sessions (by design). """ # Tunable security constants SESSION_EXPIRE_SECONDS: int = 86400 # 24 hours MAX_FAIL_ATTEMPTS: int = 5 # per window FAIL_WINDOW_SECONDS: int = 60 # sliding window LOCKOUT_SECONDS: int = 900 # 15 minutes after threshold def __init__(self): self._lock = threading.Lock() # token -> expiry timestamp self._sessions: Dict[str, float] = {} # ip -> list of failure timestamps self._fail_log: Dict[str, List[float]] = {} # ip -> lockout-until timestamp self._lockouts: Dict[str, float] = {} # ------------------------------------------------------------------ # Internal helpers # ------------------------------------------------------------------ def _now(self) -> float: return time.monotonic() def _real_now(self) -> float: return time.time() def _is_locked_out(self, ip: str) -> bool: unlock_at = self._lockouts.get(ip, 0) return self._now() < unlock_at def _record_failure(self, ip: str) -> None: now = self._now() log = self._fail_log.setdefault(ip, []) # Prune old entries outside the window log[:] = [t for t in log if now - t < self.FAIL_WINDOW_SECONDS] log.append(now) if len(log) >= self.MAX_FAIL_ATTEMPTS: self._lockouts[ip] = now + self.LOCKOUT_SECONDS log.clear() # reset counter after locking def _lockout_remaining(self, ip: str) -> int: """Return seconds remaining in lockout, or 0.""" unlock_at = self._lockouts.get(ip, 0) remaining = unlock_at - self._now() return max(0, int(remaining)) # ------------------------------------------------------------------ # Public API # ------------------------------------------------------------------ def check_password(self) -> Optional[str]: """ Return the configured password from environment, or None if not set. """ return os.environ.get("ACCESS_PASSWORD") or None def verify(self, ip: str, password: str) -> dict: """ Attempt to authenticate. Returns a result dict: { "ok": bool, "token": str|None, "error": str|None, "lockout_remaining": int } """ configured = self.check_password() if configured is None: return {"ok": False, "token": None, "error": "ACCESS_PASSWORD environment variable is not configured.", "lockout_remaining": 0} with self._lock: if self._is_locked_out(ip): remaining = self._lockout_remaining(ip) return {"ok": False, "token": None, "error": f"Too many failed attempts. Try again in {remaining} seconds.", "lockout_remaining": remaining} if not secrets.compare_digest(password, configured): self._record_failure(ip) remaining = self._lockout_remaining(ip) return {"ok": False, "token": None, "error": "Incorrect password.", "lockout_remaining": remaining} # Success — issue a fresh session token token = secrets.token_urlsafe(32) expire_at = time.time() + self.SESSION_EXPIRE_SECONDS self._sessions[token] = expire_at return {"ok": True, "token": token, "error": None, "lockout_remaining": 0} def validate_token(self, token: str) -> bool: """Return True if the token is valid and not expired.""" if not token: return False with self._lock: expire_at = self._sessions.get(token) if expire_at is None: return False if time.time() > expire_at: del self._sessions[token] return False return True def revoke_token(self, token: str) -> None: """Invalidate a session token immediately.""" with self._lock: self._sessions.pop(token, None) def session_status(self, token: str) -> dict: """Return session info without side-effects.""" if not token: return {"authenticated": False} with self._lock: expire_at = self._sessions.get(token) if expire_at is None: return {"authenticated": False} if time.time() > expire_at: del self._sessions[token] return {"authenticated": False} return { "authenticated": True, "expires_at": datetime.fromtimestamp(expire_at).isoformat() } auth = AuthManager() # ---------------------------------------------------- # 3. Authentication Middleware # ---------------------------------------------------- # Routes that do NOT require authentication _PUBLIC_PATHS = { "/api/auth/login", "/api/auth/status", "/api/auth/logout", } # Cookie name for the session token SESSION_COOKIE = "hf_session" class AuthMiddleware(BaseHTTPMiddleware): """ Intercept every /api/* request (except public paths) and validate the session cookie. Returns 401 JSON for unauthenticated requests. Also enforces a hard 503 if ACCESS_PASSWORD is not configured, preventing the service from operating in an unsecured state. """ async def dispatch(self, request: Request, call_next): path = request.url.path # Only guard API routes; static files are served by the SPA lock screen if not path.startswith("/api/"): return await call_next(request) # ── Check password is configured ────────────────────────────── if auth.check_password() is None: return JSONResponse( status_code=503, content={ "detail": ( "Service unavailable: ACCESS_PASSWORD is not configured. " "Set it as a Secret/environment variable and restart." ) } ) # ── Allow public auth endpoints ─────────────────────────────── if path in _PUBLIC_PATHS: return await call_next(request) # ── Validate session cookie ─────────────────────────────────── token = request.cookies.get(SESSION_COOKIE, "") if not auth.validate_token(token): return JSONResponse( status_code=401, content={"detail": "Unauthorized. Please log in."} ) return await call_next(request) # ---------------------------------------------------- # 4. Thread-Safe Task Manager # ---------------------------------------------------- class TaskManager: def __init__(self, data_root: str): self.data_root = data_root self.tasks_file = os.path.join(data_root, "tasks.json") self.logs_dir = os.path.join(data_root, "logs") self.temp_dir = os.path.join(data_root, "temp_scripts") os.makedirs(self.data_root, exist_ok=True) os.makedirs(self.logs_dir, exist_ok=True) os.makedirs(self.temp_dir, exist_ok=True) self.lock = threading.Lock() self.tasks: Dict[str, dict] = {} self.active_processes: Dict[str, subprocess.Popen] = {} self._load_tasks() self._reset_stale_tasks() def _load_tasks(self): with self.lock: if os.path.exists(self.tasks_file): try: with open(self.tasks_file, 'r', encoding='utf-8') as f: self.tasks = json.load(f) except Exception as e: print(f"Error loading tasks: {e}", file=sys.stderr) self.tasks = {} else: self.tasks = {} def _save_tasks(self): with self.lock: try: with open(self.tasks_file, 'w', encoding='utf-8') as f: json.dump(self.tasks, f, indent=2, ensure_ascii=False) except Exception as e: print(f"Error saving tasks: {e}", file=sys.stderr) def _reset_stale_tasks(self): updated = False for task_id, task in self.tasks.items(): if task.get("status") in ["running", "pending"]: task["status"] = "failed" task["error_message"] = "Server restarted or task interrupted." task["updated_at"] = datetime.now().isoformat() updated = True if updated: self._save_tasks() def get_all_tasks(self) -> List[dict]: with self.lock: task_list = list(self.tasks.values()) task_list.sort(key=lambda x: x.get("created_at", ""), reverse=True) return task_list def get_task(self, task_id: str) -> Optional[dict]: with self.lock: return self.tasks.get(task_id) def get_task_logs(self, task_id: str) -> str: log_path = os.path.join(self.logs_dir, f"{task_id}.log") if os.path.exists(log_path): try: with open(log_path, 'r', encoding='utf-8', errors='replace') as f: return f.read() except Exception as e: return f"Error reading log: {str(e)}" return "Log file not found." def cancel_task(self, task_id: str) -> bool: process = None with self.lock: if task_id in self.active_processes: process = self.active_processes[task_id] task = self.tasks.get(task_id) if task and task["status"] in ["running", "pending"]: task["status"] = "cancelled" task["updated_at"] = datetime.now().isoformat() if process: try: process.terminate() try: process.wait(timeout=2) except subprocess.TimeoutExpired: process.kill() return True except Exception as e: print(f"Error terminating process for {task_id}: {e}", file=sys.stderr) return False if task and task["status"] == "cancelled": self._save_tasks() return True return False def delete_task(self, task_id: str, delete_files: bool = False) -> bool: self.cancel_task(task_id) with self.lock: task = self.tasks.pop(task_id, None) if not task: return False self._save_tasks() if delete_files and task: folder_name = task.get("folder_name") if folder_name: folder_path = os.path.join(self.data_root, folder_name) real_folder_path = os.path.abspath(folder_path) real_data_root = os.path.abspath(self.data_root) if real_folder_path.startswith(real_data_root) and os.path.exists(real_folder_path): try: shutil.rmtree(real_folder_path) except Exception as e: print(f"Error deleting folder {real_folder_path}: {e}", file=sys.stderr) log_path = os.path.join(self.logs_dir, f"{task_id}.log") if os.path.exists(log_path): try: os.remove(log_path) except Exception as e: print(f"Error deleting log {log_path}: {e}", file=sys.stderr) return True def create_task(self, folder_name: str, code: str) -> dict: task_id = str(uuid.uuid4()) safe_folder = "".join(c for c in folder_name if c.isalnum() or c in ('-', '_')).strip() if not safe_folder: safe_folder = "downloaded_files" task = { "id": task_id, "folder_name": safe_folder, "code": code, "status": "pending", "progress": 0, "error_message": None, "created_at": datetime.now().isoformat(), "updated_at": datetime.now().isoformat() } with self.lock: self.tasks[task_id] = task self._save_tasks() threading.Thread(target=self._run_task, args=(task_id,), daemon=True).start() return task def _run_task(self, task_id: str): with self.lock: task = self.tasks.get(task_id) if not task or task["status"] == "cancelled": return task["status"] = "running" task["updated_at"] = datetime.now().isoformat() self._save_tasks() folder_name = task["folder_name"] save_dir = os.path.join(self.data_root, folder_name) os.makedirs(save_dir, exist_ok=True) script_path = os.path.join(self.temp_dir, f"{task_id}.py") log_path = os.path.join(self.logs_dir, f"{task_id}.log") full_code = f"""# -*- coding: utf-8 -*- import os import sys import requests from huggingface_hub import hf_hub_download SAVE_DIR = {repr(save_dir)} os.makedirs(SAVE_DIR, exist_ok=True) def report_progress(percent): print(f"__PROGRESS__:{{percent}}", flush=True) def download_file(url, filename=None): if not filename: filename = url.split("/")[-1].split("?")[0] if not filename: filename = "file" filepath = os.path.join(SAVE_DIR, filename) print(f"Downloading {{url}} to {{filepath}}...", flush=True) response = requests.get(url, stream=True) response.raise_for_status() total_size = int(response.headers.get('content-length', 0)) block_size = 1024 * 1024 # 1MB chunks downloaded = 0 with open(filepath, 'wb') as f: for block in response.iter_content(block_size): if block: f.write(block) downloaded += len(block) if total_size > 0: percent = int((downloaded / total_size) * 100) report_progress(percent) print(f"Download complete: {{filepath}}", flush=True) report_progress(100) return filepath def download_torrent(torrent_path_or_magnet): import subprocess import re print(f"Starting torrent/magnet download for: {{torrent_path_or_magnet}}", flush=True) cmd = [ "aria2c", "-d", SAVE_DIR, "--summary-interval=1", "--bt-max-peers=50", "--seed-time=0", torrent_path_or_magnet ] process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) percent_re = re.compile(r'\\((\\d+)%\\)') while True: line = process.stdout.readline() if not line: break print(line, end='', flush=True) match = percent_re.search(line) if match: try: percent = int(match.group(1)) report_progress(percent) except ValueError: pass return_code = process.wait() if return_code != 0: raise Exception(f"aria2c execution failed with return code {{return_code}}") print("Torrent/magnet download completed successfully.", flush=True) report_progress(100) return SAVE_DIR def download_tg_channel(channel_username_or_id, bot_token=None, session_string=None, limit=20): import os import asyncio from telethon import TelegramClient from telethon.sessions import StringSession api_id = os.environ.get("TG_API_ID") or os.environ.get("TELEGRAM_API_ID") api_hash = os.environ.get("TG_API_HASH") or os.environ.get("TELEGRAM_API_HASH") bot_token = bot_token or os.environ.get("TG_BOT_TOKEN") or os.environ.get("TELEGRAM_BOT_TOKEN") session_string = session_string or os.environ.get("TG_SESSION_STRING") or os.environ.get("TELEGRAM_SESSION_STRING") if not api_id or not api_hash: raise Exception("Error: TG_API_ID or TG_API_HASH environment variables are not configured.") try: api_id = int(api_id) except ValueError: raise Exception("Error: TG_API_ID must be a valid integer.") print(f"Connecting to Telegram (App ID: {{api_id}})...", flush=True) async def run_download(): if session_string: client = TelegramClient(StringSession(session_string), api_id, api_hash) else: session_path = os.path.join(SAVE_DIR, "tg_user_session") client = TelegramClient(session_path, api_id, api_hash) if bot_token: print("Logging in using TG_BOT_TOKEN...", flush=True) await client.start(bot_token=bot_token) else: print("Logging in as a User client...", flush=True) await client.start() print("Telegram client connected successfully!", flush=True) try: channel = await client.get_entity(channel_username_or_id) except Exception as e: raise Exception(f"Failed to find channel entity '{{channel_username_or_id}}': {{str(e)}}") print(f"Reading messages from: {{channel_username_or_id}} (limit: {{limit}})...", flush=True) messages_with_media = [] async for msg in client.iter_messages(channel, limit=limit): if msg.media: messages_with_media.append(msg) total_files = len(messages_with_media) if total_files == 0: print("No media files found in the recent channel messages.", flush=True) report_progress(100) await client.disconnect() return print(f"Found {{total_files}} messages containing media. Starting downloads...", flush=True) for idx, msg in enumerate(messages_with_media): msg_id = msg.id file_name = getattr(msg.file, 'name', None) or f"tg_media_{{msg_id}}" print(f"Downloading file [{{idx+1}}/{{total_files}}]: {{file_name}}...", flush=True) def progress_callback(downloaded, total): if total: combined_pct = int(((idx + (downloaded / total)) / total_files) * 100) report_progress(combined_pct) filepath = await client.download_media( msg, file=SAVE_DIR, progress_callback=progress_callback ) if filepath: print(f"Saved: {{filepath}}", flush=True) report_progress(int(((idx + 1) / total_files) * 100)) print("Telegram channel download completed successfully.", flush=True) await client.disconnect() try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(run_download()) return SAVE_DIR # --- User Code Starts Here --- {task["code"]} # --- User Code Ends Here --- """ try: with open(script_path, 'w', encoding='utf-8') as f: f.write(full_code) except Exception as e: with self.lock: task = self.tasks.get(task_id) if task: task["status"] = "failed" task["error_message"] = f"Failed to initialize script file: {str(e)}" task["updated_at"] = datetime.now().isoformat() self._save_tasks() return log_file = None try: log_file = open(log_path, 'w', encoding='utf-8') log_file.write(f"=== Task {task_id} Started at {datetime.now().isoformat()} ===\n") log_file.write(f"Saving to: {save_dir}\n\n") log_file.flush() except Exception as e: print(f"Could not open log file: {e}", file=sys.stderr) try: env = os.environ.copy() env["SAVE_DIR"] = save_dir env["PYTHONUNBUFFERED"] = "1" process = subprocess.Popen( [sys.executable, script_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, env=env ) with self.lock: if self.tasks.get(task_id, {}).get("status") == "cancelled": process.terminate() if log_file: log_file.write("Task cancelled immediately.\n") return self.active_processes[task_id] = process while True: line = process.stdout.readline() if not line: break if line.startswith("__PROGRESS__:"): try: percent = int(line.split(":", 1)[1].strip()) with self.lock: if task_id in self.tasks and self.tasks[task_id]["status"] == "running": self.tasks[task_id]["progress"] = percent self.tasks[task_id]["updated_at"] = datetime.now().isoformat() self._save_tasks() except ValueError: pass else: if log_file: log_file.write(line) log_file.flush() return_code = process.wait() with self.lock: self.active_processes.pop(task_id, None) task = self.tasks.get(task_id) if task and task["status"] == "running": if return_code == 0: task["status"] = "completed" task["progress"] = 100 else: task["status"] = "failed" task["error_message"] = f"Script exited with error code {return_code}" task["updated_at"] = datetime.now().isoformat() if log_file: log_file.write(f"\n=== Task Finished with code {return_code} ===\n") except Exception as e: with self.lock: self.active_processes.pop(task_id, None) task = self.tasks.get(task_id) if task and task["status"] in ["running", "pending"]: task["status"] = "failed" task["error_message"] = str(e) task["updated_at"] = datetime.now().isoformat() if log_file: log_file.write(f"\n=== Execution Failed: {str(e)} ===\n") finally: if log_file: log_file.close() self._save_tasks() if os.path.exists(script_path): try: os.remove(script_path) except Exception: pass # Initialize managers manager = TaskManager(DATA_DIR) # ---------------------------------------------------- # 5. FastAPI Application # ---------------------------------------------------- app = FastAPI(title="HF Spaces Downloader Portal") # Register authentication middleware (runs before every request) app.add_middleware(AuthMiddleware) # ── API Models ──────────────────────────────────────────────────────── class TaskCreateRequest(BaseModel): folder_name: str code: str class LoginRequest(BaseModel): password: str # ── Auth Routes ─────────────────────────────────────────────────────── def _get_client_ip(request: Request) -> str: """Best-effort IP extraction, respecting common reverse-proxy headers.""" forwarded_for = request.headers.get("X-Forwarded-For") if forwarded_for: return forwarded_for.split(",")[0].strip() real_ip = request.headers.get("X-Real-IP") if real_ip: return real_ip.strip() if request.client: return request.client.host return "unknown" @app.post("/api/auth/login") async def login(req: LoginRequest, request: Request, response: Response): ip = _get_client_ip(request) result = auth.verify(ip, req.password) if not result["ok"]: status = 429 if result["lockout_remaining"] > 0 else 401 raise HTTPException(status_code=status, detail=result["error"]) # Set httpOnly, SameSite=Strict cookie — JS cannot read it response.set_cookie( key=SESSION_COOKIE, value=result["token"], max_age=AuthManager.SESSION_EXPIRE_SECONDS, httponly=True, samesite="strict", secure=False, # set True if you're certain HTTPS is always used ) return {"status": "ok", "message": "Authenticated successfully."} @app.post("/api/auth/logout") async def logout(request: Request, response: Response): token = request.cookies.get(SESSION_COOKIE, "") auth.revoke_token(token) response.delete_cookie(key=SESSION_COOKIE, samesite="strict") return {"status": "ok", "message": "Logged out."} @app.get("/api/auth/status") async def auth_status(request: Request): token = request.cookies.get(SESSION_COOKIE, "") return auth.session_status(token) # ── Task Routes ─────────────────────────────────────────────────────── @app.get("/api/tasks") def list_tasks(): return manager.get_all_tasks() @app.post("/api/tasks") def create_task(req: TaskCreateRequest): if not req.folder_name.strip(): raise HTTPException(status_code=400, detail="Folder name is required") if not req.code.strip(): raise HTTPException(status_code=400, detail="Python script content is required") task = manager.create_task(req.folder_name, req.code) return task @app.get("/api/tasks/{task_id}/logs") def get_task_logs(task_id: str): task = manager.get_task(task_id) if not task: raise HTTPException(status_code=404, detail="Task not found") logs = manager.get_task_logs(task_id) return {"logs": logs} @app.post("/api/tasks/{task_id}/cancel") def cancel_task(task_id: str): success = manager.cancel_task(task_id) if not success: raise HTTPException(status_code=400, detail="Failed to cancel task, or it was not running") return {"status": "cancelled"} @app.delete("/api/tasks/{task_id}") def delete_task(task_id: str, delete_files: bool = False): success = manager.delete_task(task_id, delete_files) if not success: raise HTTPException(status_code=404, detail="Task not found") return {"status": "deleted"} # ── File Routes ─────────────────────────────────────────────────────── @app.get("/api/files") def list_files(): files_tree = [] real_data_root = os.path.abspath(DATA_DIR) for root, dirs, files in os.walk(DATA_DIR): rel_root = os.path.relpath(root, DATA_DIR) if rel_root == ".": rel_root = "" parts = rel_root.split(os.sep) if "logs" in parts or "temp_scripts" in parts or (len(parts) > 0 and parts[0] in ["logs", "temp_scripts"]): continue for file in files: if rel_root == "" and file == "tasks.json": continue file_path = os.path.join(root, file) rel_path = os.path.join(rel_root, file).replace("\\", "/") stat = os.stat(file_path) files_tree.append({ "name": file, "path": rel_path, "size": stat.st_size, "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(), "is_dir": False }) return files_tree @app.get("/api/files/download/{file_path:path}") def download_file(file_path: str): target_path = os.path.abspath(os.path.join(DATA_DIR, file_path)) real_data_root = os.path.abspath(DATA_DIR) if not target_path.startswith(real_data_root): raise HTTPException(status_code=400, detail="Access denied") if not os.path.exists(target_path) or os.path.isdir(target_path): raise HTTPException(status_code=404, detail="File not found") return FileResponse(target_path, filename=os.path.basename(target_path)) @app.delete("/api/files/{file_path:path}") def delete_file(file_path: str): target_path = os.path.abspath(os.path.join(DATA_DIR, file_path)) real_data_root = os.path.abspath(DATA_DIR) if not target_path.startswith(real_data_root): raise HTTPException(status_code=400, detail="Access denied") parts = file_path.split("/") if parts[0] in ["logs", "temp_scripts", "tasks.json"] or not file_path: raise HTTPException(status_code=400, detail="Cannot delete system folders or metadata") if not os.path.exists(target_path): raise HTTPException(status_code=404, detail="File or folder not found") try: if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.remove(target_path) return {"status": "success"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # ── Static Files (SPA) ──────────────────────────────────────────────── # Mounted LAST so all API routes take precedence. # The SPA itself shows a lock screen on load; API calls are protected by middleware. static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") if os.path.exists(static_dir): app.mount("/", StaticFiles(directory=static_dir, html=True), name="static") else: @app.get("/") def index_fallback(): return JSONResponse({"status": "running", "msg": "Static files directory is being configured."})