Update app.py
Browse files475 unmodified lines476477478479479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604475 unmodified lines "total": total_seen, "has_next": has_next, "next_page": next_page, } }
# =====================================================================# /tiktok/download — TikTok video download (including private videos)## yt-dlp's TikTokIE reads auth cookies (sessionid / sid_tt) from its# cookiejar to access private videos. The client passes its raw Cookie# header string; we persist it to a temporary Netscape-format cookiefile# and hand the path to yt-dlp via the native `cookiefile` option.# =====================================================================def _build_netscape_cookiefile(cookie_header: str, domain: str = ".tiktok.com") -> str: """ Convert a raw Cookie header string ("name1=val1; name2=val2") into a temporary Netscape HTTP Cookie File for the given domain. Returns the path to the temp file. """ lines = ["# Netscape HTTP Cookie File", "# This is a generated file. Do not edit."] expiry = str(int((datetime.now() + timedelta(days=365)).timestamp())) for part in cookie_header.split(";"): part = part.strip() if not part or "=" not in part: continue name, value = part.split("=", 1) name = name.strip() value = value.strip() if not name: continue lines.append("\t".join([domain, "TRUE", "/", "FALSE", expiry, name, value]))
fd, path = tempfile.mkstemp(suffix=".txt", prefix="tiktok_cookies_") with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("\n".join(lines) + "\n") return path
@app.post("/tiktok/download")async def download_tiktok_video(request: Request): """ Download a TikTok video, including private ones.
Request body (JSON): url: TikTok video URL (required) cookie: Raw Cookie header string, e.g. "sessionid=xxx; sid_tt=yyy; tt_csrf_token=zzz". Required for private videos; optional for public ones. token: Access token (optional, bypasses rate limit when valid) """ data = await request.json()
has_valid_token = bool(ACCESS_TOKEN) and data.get('token') == ACCESS_TOKEN
user_ip = get_user_ip(request) if not has_valid_token and rate_limiter.is_rate_limited(user_ip): raise HTTPException( status_code=429, detail={ "error": "You have exceeded the maximum number of requests per day. Please try again tomorrow.", "url": "https://t.me/chrunoss" } )
video_url = data.get('url') if not video_url: raise HTTPException(status_code=400, detail="Missing 'url' in request body") if "tiktok.com" not in video_url: return {"error": f"{video_url} is not a TikTok URL", "url": "https://t.me/chrunoss"}
cookie_header = (data.get('cookie') or "").strip()
timestamp = datetime.now().strftime('%Y%m%d%H%M%S') output_template = str(Path(global_download_dir) / f'%(title).70s_{timestamp}.%(ext)s')
ydl_opts = { 'format': 'best', 'outtmpl': output_template, 'quiet': True, 'no_warnings': True, 'noprogress': True, 'merge_output_format': 'mp4', }
# If cookies are supplied, write them to a temp Netscape cookiefile. # yt-dlp's native `cookiefile` option populates its cookiejar, which # TikTokIE reads (sessionid / sid_tt) to access private videos. cookie_path = None if cookie_header: try: cookie_path = _build_netscape_cookiefile(cookie_header) ydl_opts['cookiefile'] = cookie_path except Exception as e: logger.error(f"failed to build cookiefile: {e}") return {"error": f"Invalid cookie data: {str(e)}", "url": "https://t.me/chrunoss"}
try: await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([video_url])) except Exception as e: msg = str(e) # Give a clear hint when the cookie is missing/invalid for a private video lowered = msg.lower() if any(k in lowered for k in ("private", "login", "sessionid", "sid_tt", "403", "forbidden")): return { "error": "Private video or auth required. Provide a valid 'cookie' containing sessionid/sid_tt.", "detail": msg[:200], "url": "https://t.me/chrunoss", } return {"error": f"Download failed: {msg}", "url": "https://t.me/chrunoss"} finally: # Always remove the temporary cookiefile if cookie_path and os.path.exists(cookie_path): try: os.remove(cookie_path) except OSError: pass
downloaded_files = list(Path(global_download_dir).glob(f"*_{timestamp}.mp4")) if not downloaded_files: return {"error": "Download failed. Report error on Telegram", "url": "https://t.me/chrunoss"}
downloaded_file = downloaded_files[0] encoded_filename = urllib.parse.quote(downloaded_file.name) base_url = str(request.base_url) download_url = f"{base_url}file/{encoded_filename}"
gc.collect() return {"url": download_url}app.py+126-1