Upload 2 files
Browse filesFiles changed (2)
- app.py+58-2
- requirements.txt+4-4
485 unmodified lines48648748848949049149256 unmodified lines5495505515525535541 unmodified line5565575585595605615625636 unmodified lines570571572573574575576577578579580581582583584585586587588485 unmodified lines# 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 a56 unmodified linestimestamp = 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,1 unmodified line'no_warnings': False,'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.6 unmodified lineslogger.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 videolowered = 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 cookiefileif cookie_path and os.path.exists(cookie_path):485 unmodified lines48648748848949049149249349449549649749849950050150250350450550650750850951056 unmodified lines5675685695705715725735745755765775785795805815821 unmodified line5845855865875885895905915925935945956 unmodified lines602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644485 unmodified lines# 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.## NOTE: cookies alone are not always enough. TikTok also rejects many# datacenter/cloud egress IPs (HF Spaces included) for private posts,# answering with statusCode 10216 ("You do not have permission to view# this post") even when a valid session cookie is supplied. Setting the# TIKTOK_PROXY env var (ideally a residential proxy,# e.g. http://user:pass@host:port) routes requests through a non-flagged# egress IP. The error responses below include a `diagnostics` block so a# failure can be attributed to the cookie vs. the network path.# =====================================================================TIKTOK_PROXY = os.getenv('TIKTOK_PROXY')try:import curl_cffi # noqa: F401 (yt-dlp uses it for browser impersonation)_IMPERSONATION_AVAILABLE = Trueexcept ImportError:_IMPERSONATION_AVAILABLE = Falsedef _build_netscape_cookiefile(cookie_header: str, domain: str = ".tiktok.com") -> str:"""Convert a raw Cookie header string ("name1=val1; name2=val2") into a56 unmodified linestimestamp = datetime.now().strftime('%Y%m%d%H%M%S')output_template = str(Path(global_download_dir) / f'%(title).70s_{timestamp}.%(ext)s')# Capture yt-dlp's own warnings/errors so a failure is attributable# (cookie problem vs. network/egress problem) instead of a bare message.messages: list = []class _YtdlLogger:def debug(self, msg): passdef info(self, msg): passdef warning(self, msg): messages.append(str(msg))def error(self, msg): messages.append(str(msg))ydl_opts = {'format': 'best','outtmpl': output_template,1 unmodified line'no_warnings': False,'noprogress': True,'merge_output_format': 'mp4','logger': _YtdlLogger(),}if TIKTOK_PROXY:ydl_opts['proxy'] = TIKTOK_PROXY# 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.6 unmodified lineslogger.error(f"failed to build cookiefile: {e}")return {"error": f"Invalid cookie data: {str(e)}", "url": "https://t.me/chrunoss"}def _diagnostics() -> dict:"""Environment facts that attribute a failure to cookie vs. network path."""return {"yt_dlp_version": yt_dlp.version.__version__,"cookiefile_passed": bool(cookie_path),"cookie_names": sorted(p.split("=", 1)[0].strip()for p in cookie_header.split(";") if "=" in p),"tiktok_proxy_configured": bool(TIKTOK_PROXY),"impersonation_available": _IMPERSONATION_AVAILABLE,# names only — never log proxy credentials"proxy_env_vars": sorted(k for k in os.environif k.lower() in ("http_proxy", "https_proxy", "all_proxy", "no_proxy")),"yt_dlp_messages": messages[-6:],}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 videolowered = msg.lower()if any(k in lowered for k in ("private", "permission", "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","diagnostics": _diagnostics(),}return {"error": f"Download failed: {msg}","url": "https://t.me/chrunoss","diagnostics": _diagnostics(),}finally:# Always remove the temporary cookiefileif cookie_path and os.path.exists(cookie_path):
123456789fastapiyt-dlp# yt-dlp only declares curl_cffi as an OPTIONAL extra. TikTok's extractor needs# browser impersonation to serve logged-in/private posts; without it the request# falls back to a non-browser fingerprint and private videos return# "You do not have permission to view this post".curl-cffi>=0.10,<0.17ffmpeg-pythonuvicorn123456789fastapiyt-dlp# yt-dlp declares curl_cffi only as an OPTIONAL extra. Installing it enables# browser TLS impersonation for the TikTok extractor, which lowers the chance# of the request being flagged by TikTok's bot protection. (Not required for# cookie-authenticated private posts -- verified working without it.)curl-cffi>=0.10,<0.17ffmpeg-pythonuvicorn
app.py+58-2
requirements.txt+4-4