From 97aa3cd19d0d988aec696c31a07651a867d2c4a5 Mon Sep 17 00:00:00 2001 From: craig Date: Thu, 26 Feb 2026 23:58:19 +1100 Subject: [PATCH] Initial commit --- .env | 2 + backend/Dockerfile | 28 +++ backend/__pycache__/main.cpython-312.pyc | Bin 0 -> 5007 bytes backend/__pycache__/worker.cpython-312.pyc | Bin 0 -> 8988 bytes backend/cookies.txt | 15 ++ .../__pycache__/downloader.cpython-312.pyc | Bin 0 -> 2962 bytes backend/core/downloader.py | 80 ++++++ .../f59b35cd-8c0f-4fdc-85d0-d1f45177444d.txt | 24 ++ backend/main.py | 101 ++++++++ backend/requirements.txt | 9 + backend/test_info_dict.py | 26 ++ backend/test_playlist.py | 12 + backend/test_poster.jpg | Bin 0 -> 14279 bytes backend/test_poster.py | 26 ++ backend/test_yt.py | 24 ++ backend/test_yt_dlp_progress.py | 31 +++ backend/worker.py | 231 ++++++++++++++++++ docker-compose.yml | 55 +++++ docs/plans/2026-02-21-yt-downloader-design.md | 37 +++ frontend/.gitignore | 24 ++ frontend/Dockerfile | 18 ++ frontend/README.md | 50 ++++ frontend/eslint.config.js | 28 +++ frontend/index.html | 13 + frontend/nginx.conf | 30 +++ frontend/package.json | 34 +++ frontend/postcss.config.js | 6 + frontend/public/vite.svg | 1 + frontend/src/App.css | 42 ++++ frontend/src/App.tsx | 153 ++++++++++++ frontend/src/assets/react.svg | 1 + .../src/components/ActiveDownloadsPanel.tsx | 169 +++++++++++++ frontend/src/components/HeroInput.tsx | 47 ++++ frontend/src/components/MetadataCard.tsx | 102 ++++++++ frontend/src/index.css | 83 +++++++ frontend/src/main.tsx | 10 + frontend/src/vite-env.d.ts | 1 + frontend/tailwind.config.js | 79 ++++++ frontend/tsconfig.app.json | 26 ++ frontend/tsconfig.json | 7 + frontend/tsconfig.node.json | 29 +++ frontend/vite.config.ts | 21 ++ test_playlist.py | 10 + 43 files changed, 1685 insertions(+) create mode 100644 .env create mode 100644 backend/Dockerfile create mode 100644 backend/__pycache__/main.cpython-312.pyc create mode 100644 backend/__pycache__/worker.cpython-312.pyc create mode 100644 backend/cookies.txt create mode 100644 backend/core/__pycache__/downloader.cpython-312.pyc create mode 100644 backend/core/downloader.py create mode 100644 backend/f59b35cd-8c0f-4fdc-85d0-d1f45177444d.txt create mode 100644 backend/main.py create mode 100644 backend/requirements.txt create mode 100644 backend/test_info_dict.py create mode 100644 backend/test_playlist.py create mode 100644 backend/test_poster.jpg create mode 100644 backend/test_poster.py create mode 100644 backend/test_yt.py create mode 100644 backend/test_yt_dlp_progress.py create mode 100644 backend/worker.py create mode 100644 docker-compose.yml create mode 100644 docs/plans/2026-02-21-yt-downloader-design.md create mode 100644 frontend/.gitignore create mode 100644 frontend/Dockerfile create mode 100644 frontend/README.md create mode 100644 frontend/eslint.config.js create mode 100644 frontend/index.html create mode 100644 frontend/nginx.conf create mode 100644 frontend/package.json create mode 100644 frontend/postcss.config.js create mode 100644 frontend/public/vite.svg create mode 100644 frontend/src/App.css create mode 100644 frontend/src/App.tsx create mode 100644 frontend/src/assets/react.svg create mode 100644 frontend/src/components/ActiveDownloadsPanel.tsx create mode 100644 frontend/src/components/HeroInput.tsx create mode 100644 frontend/src/components/MetadataCard.tsx create mode 100644 frontend/src/index.css create mode 100644 frontend/src/main.tsx create mode 100644 frontend/src/vite-env.d.ts create mode 100644 frontend/tailwind.config.js create mode 100644 frontend/tsconfig.app.json create mode 100644 frontend/tsconfig.json create mode 100644 frontend/tsconfig.node.json create mode 100644 frontend/vite.config.ts create mode 100644 test_playlist.py diff --git a/.env b/.env new file mode 100644 index 0000000..5411bae --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +# Path to the NAS share where YouTube videos will be downloaded +NAS_SHARE_PATH=/home/craig/Beast/Media/TV-Shows/youtube-tv-shows2/ diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..cdf2af1 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,28 @@ +FROM python:3.12-slim + +# Create a non-root user +RUN addgroup --gid 1000 appgroup && \ + adduser --uid 1000 --gid 1000 --disabled-password --gecos "" appuser + +WORKDIR /app + +# Install system dependencies, primarily ffmpeg which is crucial for yt-dlp to merge formats +# nodejs is required for yt-dlp to solve the YouTube 'n' challenge bot-detection +RUN apt-get update && apt-get install -y \ + ffmpeg \ + aria2 \ + nodejs \ + && rm -rf /var/lib/apt/lists/* + +# Install python dependencies first (caching) +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +# Copy application code +COPY --chown=appuser:appgroup . . + +# Switch to non-root user +USER appuser + +# Command will be overridden by docker-compose for either web or worker +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/backend/__pycache__/main.cpython-312.pyc b/backend/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22f41082a947b349e54bd7ea68de9cf709a7febe GIT binary patch literal 5007 zcmcf^ZA=`;b!I>AljHF5bvD>67);I|V1u0x?AXSb#HkySfYXF?mCJHFz~Q~y%j}*B z7+U<18dp(cS8Bjbs?e%ZZP}3`wUwg&X_LSGbLcFAHnvLCRBHZR45}QrQu}82_8Yt3XGjHF#H}k&c&6~dl0zL%oo#brdzazF14xt&OAO))^iK95lMY$v& zvQTOE}urTP~5f;Gi|JM6&G+DFK>xhU5bvK8d2StHlBNAT3HKY?r^}XkZLdg0o)F;`CZC|xuiV$6`0pGLzw9NvoVrwumOg5`V5 z7e5EU_Qk3vHu3{_r)YU#DKx;k9C&pEtY`Jlft=ffd2+$KP&K_!Oe62MaM2}?XW3o6GSrLY1uVvb4Z zUYKiwPd^Bq<&hN^DyduWH_rPT=U(~U>0h7zsCl8SYrd`PFRv_gN9VhvIsfUYXl}9Rp`UFl$5|HZFhy%`)2(OXaiZ%tIm+^o>9Xfng>PSo#CU3V3SKOC8lY-%Q=r}Y{tXG{|q>z<7<5zr;+ois~Zi%Fnw3bL2 zlA%dZ2M{?a8N&oXc85sXp!GK($IlE=Et66tmWx^}?p`QWbZL-kNvW6R2WfPeP-4+{ z5tYy}X;h)S@9XQfn>jV0=@k+_)fv+wJt1Q&v<}kP{&yvraK8flZVLo_Hzw( zR5Wx*4Nz>urPi=pYH%n4yLS?9Igzkpo3h05CG(HvU@Py!q&Kc5(<(6t+=7Epmk?#h zR&41=#BBx>dJF<7uBB2W&S>1jP(_Ef)#6a1A8uJk zbOP4U{|Ma!>lRol4J}pHE>!NGuiTxhY*`4lWP>e>WtDjs3U8hnyEZoW^hZ@6d9w9S z<*GZTPkdfpvm`~b?XS*P_2^yeER^lYmhD(93opA+AiT7>VKH3$ zf$zF+?#Wzu_g5lcUb>981;;O;Tq~(K_^|hb4d*yf!GSV4Sw&u8UJvFw&P;*UuP&z)M=3I*m}P3O8MLVzkRY9^O}GsjMim)h+FJ7JHGH zLRy2g%t~&n%A;$IswM{LX*Tmi)x6tZJcMtYfzueVKL4w(DL}vyAp*APPr|=RM*p^veV-7dvIS%ii?YfU(VC(I$5P45w&#bR0 zhb`QJ**->efDtt_q67a2QT6%ithX+Qr99V++h&LI2!%U@n>oxj6*Nu6U literal 0 HcmV?d00001 diff --git a/backend/__pycache__/worker.cpython-312.pyc b/backend/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b968e94aa47ff5f2fde4166dc42dfc7a081bc7b GIT binary patch literal 8988 zcmb_iYfu|kmhRT0^?nN^UP6E|$UJTQz&63bv56gQ^01RhuoJD&Z9qauN_WeErZq*T zQe{YG3b|&t5IdeluKf`*_78sS5AQ!`Ypar7SE__X7NyNrxoW&WQu_x#W|DG#?4H|F z3x!}iNlnY{zW4UI=bm%!x#xWMHn$B1EdiIOFCF-=dV=^fu1J@vPa{6UmsG@WYE0zPAUa$Qfcc+ ztB~>rRqUw+{tBd`;deuQU7n{K(#eRI38eXuKw4T~Y&FojV9gdMsRaCV*U5Yh>1h)( zz<(oc8ljNsL&fz1*^qgf^q9ZFwLuRlP%qITnwb_fZ=5`F`keR8H_pWE42=Tpk&cf1 z^I+GZ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Oy)nA_#wWjC!T*XjtiHP@ zeRjGOYJL)l-l8|?>gXr>iu9yDvT7FU`=NhZMxpTPxrg=2lkT34OY4_%M~mHqrJkRy zUC80J;Zj>?sk3XNf4x5!xHDL*-rZg7JXnf%Z;Y;w=H9%k7UKv09rm|IR!(g0?chHx$-TNITXi2^%&*OQtAYDfDxECEn7M=$tyNob= z*=m2H?fk_b1b1;@0YbSyYi8`s1YPV%>uQ#=WJ=elVINlw!ho#@fKC!J4_h-@I_WYT z_g&3szytM$nVeUd0qkw@dSR~vR|6UF`e`f4GKQ_qQn>X%PfShOCQGVp(pqe&a;7<> zQER`wVDq|^DH?*1P64|HYJvPP6$Yp>MX^pXZJ({#I$aE3GG+{5T;-x@@}NDHnVm3z zb~pn23{%C6#RHjig_60yiciRF5Ztf>LLCz7uu!`|@x~f&xeT=!$=dsfo>nMhCi|t5 z2yu^Tac^3+r?^ZPV7V5Tvvv|NJb1a1%8_$CR9$jXGk_Eo5ur?$K6prVi-$+5Z^fu^ z%Y&l}DVi=%Sh8%E@K>f2$PztirXfOoB|ph>SP8nhx9qr_5KJv`U(0;?f-$L`no7=6 zTP3QkvQYpGz;Eq?tzSk@I=V}ZEv2@uQd@hey(i~cbxK`*`91IDcc096jsRmd$jfK8 zn^3HO`B#tq!H?%Zn*aFPN7q(o9{GP>+BL8eSdA9~J>LhTTfvS(uw(6wN5S5lwe4vM z4wquBTe03ktT%UZvp*l}Eymtn838hF=vW&mL=~vD$JgHf^tZXIg|@`1_xskq+{HhR z{bB5`_El4{|5&m0_{wPjb@ptuueay++)7ll#*YeS?jL|PG)I2wKy`hEVDEpPy@?uHZ#g%dt!SbUP5g*(aQJak z*P3zv!e-;W5AUAI$A^kdNAjT~|J{~g?DKVx`&W(kHLwE0F9f5OLp0T%3tP>N9R2qiY)PpC}ul{YPLY}O{|9%E)>{Ao literal 0 HcmV?d00001 diff --git a/backend/core/downloader.py b/backend/core/downloader.py new file mode 100644 index 0000000..90b2cfb --- /dev/null +++ b/backend/core/downloader.py @@ -0,0 +1,80 @@ +import yt_dlp +import os + +def filter_formats(formats): + """ + Filters formats to return only resolutions >= 720p. + Provides video+audio formats whenever possible to avoid complex post-processing, + but also provides distinct video lines if they're high quality. + """ + available = [] + seen_heights = set() + + # Sort formats from highest resolution to lowest + sorted_formats = sorted(formats, key=lambda f: f.get('height', 0) or 0, reverse=True) + + for f in sorted_formats: + h = f.get('height') + # Skip audio-only or very low res + if not h or h < 720: + continue + + ext = f.get('ext') + # Prefer mp4/webm. + if ext not in ['mp4', 'webm']: + continue + + # Optional: We want to deduplicate mostly matching resolutions. + if h not in seen_heights: + parsed = { + "format_id": f.get("format_id"), + "quality": f"{h}p", + "ext": ext, + "vcodec": f.get("vcodec"), + "acodec": f.get("acodec", "none"), + "filesize": f.get("filesize", 0) + } + available.append(parsed) + # Temporarily disabled so users can choose codecs + # seen_heights.add(h) + + # If no 720p+ available, we must fail gracefully on the frontend. + return available + +def fetch_metadata(url: str): + ydl_opts = { + 'skip_download': True, + 'quiet': True, + 'no_warnings': True, + 'playlistend': 1, # Only parse the first video of a playlist to save API timeout + 'js_runtimes': {'node': {}}, + 'extractor_args': {'youtube': ['player_client=android,web']} + } + + cookie_path = '/app/cookies.txt' + if os.path.exists(cookie_path): + ydl_opts['cookiefile'] = cookie_path + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + try: + info = ydl.extract_info(url, download=False) + + # If playlist, handle differently. For MVP, assuming single video first. + if 'entries' in info: + # It's a playlist. Grab the first entry just to prove metadata. + # In full implementation, we'd list the playlist videos. + info = info['entries'][0] + + formats = filter_formats(info.get('formats', [])) + + return { + "title": info.get('title', 'Unknown Title'), + "thumbnail": info.get('thumbnail', ''), + "duration": info.get('duration') or 0, + "uploader": info.get('uploader', 'Unknown'), + "url": url, + "available_formats": formats + } + + except yt_dlp.utils.DownloadError as e: + raise Exception(f"yt-dlp error: {str(e)}") diff --git a/backend/f59b35cd-8c0f-4fdc-85d0-d1f45177444d.txt b/backend/f59b35cd-8c0f-4fdc-85d0-d1f45177444d.txt new file mode 100644 index 0000000..e065e14 --- /dev/null +++ b/backend/f59b35cd-8c0f-4fdc-85d0-d1f45177444d.txt @@ -0,0 +1,24 @@ +# Netscape HTTP Cookie File +# https://curl.haxx.se/rfc/cookie_spec.html +# This is a generated file! Do not edit. + +.youtube.com TRUE / FALSE 1806598005 HSID AccGVW1xKFLINfQyi +.youtube.com TRUE / TRUE 1806598005 SSID Ayw03m65e2vprL9UQ +.youtube.com TRUE / FALSE 1806598005 APISID NOABkz_rb4J9SAw6/AgZl7xC2ERW_sIuZW +.youtube.com TRUE / TRUE 1806598005 SAPISID BDs3lGsjhCQuIGaT/ADTEkszuyOZQ9L4d6 +.youtube.com TRUE / TRUE 1806598005 __Secure-1PAPISID BDs3lGsjhCQuIGaT/ADTEkszuyOZQ9L4d6 +.youtube.com TRUE / TRUE 1806598005 __Secure-3PAPISID BDs3lGsjhCQuIGaT/ADTEkszuyOZQ9L4d6 +.youtube.com TRUE / FALSE 1806598005 SID g.a0007AhWJ01Qg8r-UBg0khapmaapywuFL8nnYKAf00GbI1BzaPB1Q__leKyRpUChC_d7-ffrGQACgYKAZMSARcSFQHGX2MiaFgVwOAk9dh8d4R5W2lKShoVAUF8yKp7X8adLX1ykkKhBabDH6su0076 +.youtube.com TRUE / TRUE 1806598005 __Secure-1PSID g.a0007AhWJ01Qg8r-UBg0khapmaapywuFL8nnYKAf00GbI1BzaPB1VhASMTE5NAo_S6e9ks4-yQACgYKAYMSARcSFQHGX2MikqzHkuuosq6jQTelwjWv2RoVAUF8yKpGgNCx3plyDAnbwmOGNLea0076 +.youtube.com TRUE / TRUE 1806598005 __Secure-3PSID g.a0007AhWJ01Qg8r-UBg0khapmaapywuFL8nnYKAf00GbI1BzaPB10bDSSdBR4obfdM_9rnfqDwACgYKAZQSARcSFQHGX2MiqhIVjSOwm-OE4al6Z8l62RoVAUF8yKrms16bga3L6NBa9irra9EP0076 +.youtube.com TRUE / TRUE 1806598686 LOGIN_INFO AFmmF2swRgIhAPSQ0Hm3uAexLzGGkCfbf6Yn9X0PL9uqreEoYFVYHXUkAiEApgadvRoGRr6Uk2ZEGeeV0nw-35LyKFyDwSH6PTG01vQ:QUQ3MjNmd0RUajdVbW5GczFPOWE0elVOcTJUMnpjTkc4dmlFUFZSYy1FbFZkbjg3Ny1QTmNQSnB1cXYtVTRtU3QySUF4WHN6VG1kYVl1M3c2T2JsdDhxdy0tU09TU25qZDdNb0xYUUVaZ1JDUHlQR3A0dFo4TmRxSnhLbWpZMVRhMVFtT0tHNUZCcjFHSEtWNzJ4TXRZMkgwZEFBbTZCYVJn +.youtube.com TRUE / TRUE 1806668784 PREF f6=40000000&tz=Australia.Melbourne&f5=30000&f7=100 +.youtube.com TRUE / TRUE 1803644786 __Secure-1PSIDTS sidts-CjQBBj1CYo8uMLJfiULir34CcgemulGBczKbcse4XA0OkQHdwL4Z75A4moTHNdDHxyU9hN5-EAA +.youtube.com TRUE / TRUE 1803644786 __Secure-3PSIDTS sidts-CjQBBj1CYo8uMLJfiULir34CcgemulGBczKbcse4XA0OkQHdwL4Z75A4moTHNdDHxyU9hN5-EAA +.youtube.com TRUE / FALSE 1803644790 SIDCC AKEyXzXRlLg1D4QoKlTkKdsL9cbrT9-9Sr0qsdbe-YFWuXMU4Vg8EBqL02Z5F9aPPoWSdUJIww +.youtube.com TRUE / TRUE 1803644790 __Secure-1PSIDCC AKEyXzVQh8kpCwz9rVNKBCpWo1js4wlnt2eu947q21TeYp9t9Xx_4D9M6HHfevxq6dwvnmsjiw +.youtube.com TRUE / TRUE 1803644790 __Secure-3PSIDCC AKEyXzU8510GMZTECI4xxHVsGgXjpugsyTwtq2IQ0HrylpEy-fNkYbI-yZXREomVYPEPfxoN6w +.youtube.com TRUE / TRUE 1787660781 VISITOR_INFO1_LIVE IHTXSywYQLs +.youtube.com TRUE / TRUE 1787660781 VISITOR_PRIVACY_METADATA CgJBVRIEGgAgLA%3D%3D +.youtube.com TRUE / TRUE 1787590686 __Secure-ROLLOUT_TOKEN CI6N0JOw9POGbhDq4OvCjvWSAxizlq3DjvWSAw%3D%3D +.youtube.com TRUE / TRUE 0 YSC siFhDeuqlq0 diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000..9a4cf40 --- /dev/null +++ b/backend/main.py @@ -0,0 +1,101 @@ +from fastapi import FastAPI, HTTPException, Request +from fastapi.middleware.cors import CORSMiddleware +from sse_starlette.sse import EventSourceResponse +from pydantic import BaseModel +import asyncio +import os + +from core.downloader import fetch_metadata +from worker import download_video_task + +app = FastAPI(title="YouTube Downloader API") + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # In production, restrict to frontend URL + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +class URLRequest(BaseModel): + url: str + +class DownloadRequest(BaseModel): + url: str + format_id: str + quality_label: str + +@app.post("/api/metadata") +async def get_metadata(request: URLRequest): + try: + data = fetch_metadata(request.url) + return data + except Exception as e: + raise HTTPException(status_code=400, detail=str(e)) + +@app.post("/api/download") +async def start_download(request: DownloadRequest): + # Queue the task in celery + task = download_video_task.delay(request.url, request.format_id, request.quality_label) + return {"job_id": task.id, "status": "Queued"} + +import redis as redis_lib +r = redis_lib.Redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0"), decode_responses=True) + +@app.post("/api/jobs/{job_id}/pause") +async def pause_job(job_id: str): + r.set(f"job_action:{job_id}", "pause") + return {"status": "success", "action": "pause"} + +@app.post("/api/jobs/{job_id}/resume") +async def resume_job(job_id: str): + r.set(f"job_action:{job_id}", "resume") + return {"status": "success", "action": "resume"} + +@app.post("/api/jobs/{job_id}/cancel") +async def cancel_job(job_id: str): + r.set(f"job_action:{job_id}", "cancel") + return {"status": "success", "action": "cancel"} + +@app.get("/api/status/{job_id}") +async def job_status(request: Request, job_id: str): + """ + SSE endpoint to stream the status of the background task. + Reads from Redis where the Celery worker pushes progress updates. + """ + # Import redis here to avoid circular imports / initialization issues + import redis + redis_url = os.getenv("REDIS_URL", "redis://redis:6379/0") + r = redis.Redis.from_url(redis_url, decode_responses=True) + + async def event_publisher(): + # Loop infinitely and yield SSE events to the frontend + while True: + # If client disconnects, stop + if await request.is_disconnected(): + break + + # Poll for the latest progress from Redis utilizing the job ID + progress = r.hgetall(f"job_progress:{job_id}") + + if not progress: + # Setup phase or job not started + yield {"event": "message", "data": '{"status": "queued", "progress": 0}'} + await asyncio.sleep(1) + continue + + # Formatting event data + import json + yield { + "event": "message", + "data": json.dumps(progress) + } + + # If the job is marked complete or failed, we can terminate the stream + if progress.get("status") in ["completed", "failed"]: + break + + await asyncio.sleep(0.5) + + return EventSourceResponse(event_publisher()) diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..5eb263f --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,9 @@ +fastapi>=0.111.0 +uvicorn[standard]>=0.30.1 +celery[redis]>=5.4.0 +redis>=5.0.4 +yt-dlp[default]>=2025.1.0 +pydantic>=2.7.1 +pydantic-settings>=2.2.1 +python-multipart>=0.0.9 +sse-starlette>=2.1.0 diff --git a/backend/test_info_dict.py b/backend/test_info_dict.py new file mode 100644 index 0000000..e954c61 --- /dev/null +++ b/backend/test_info_dict.py @@ -0,0 +1,26 @@ +import yt_dlp +import json + +ydl_opts = { + 'playlistend': 1, + 'simulate': True, + 'quiet': True, +} + +info_dict_dump = {} + +def progress_hook(d): + global info_dict_dump + if d['status'] == 'downloading': + # Grab info_dict on first hook call + if not info_dict_dump: + info_dict_dump = d.get('info_dict', {}) + +ydl_opts['progress_hooks'] = [progress_hook] + +with yt_dlp.YoutubeDL(ydl_opts) as ydl: + ydl.download(["https://www.youtube.com/playlist?list=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-"]) + +# Print out keys related to playlist +res = {k: v for k, v in info_dict_dump.items() if 'playlist' in k or 'thumb' in k} +print(json.dumps(res, indent=2)) diff --git a/backend/test_playlist.py b/backend/test_playlist.py new file mode 100644 index 0000000..9cc29d5 --- /dev/null +++ b/backend/test_playlist.py @@ -0,0 +1,12 @@ +import yt_dlp +import json + +ydl_opts = { + 'extract_flat': True, + 'playlistend': 1, +} +with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info("https://www.youtube.com/playlist?list=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-", download=False) + # Remove entries to avoid huge output, just keep the playlist info + filtered = {k: v for k, v in info.items() if k != 'entries'} + print(json.dumps(filtered, indent=2)) diff --git a/backend/test_poster.jpg b/backend/test_poster.jpg new file mode 100644 index 0000000000000000000000000000000000000000..392985d6e12c094897671640c3a22a4efd49307b GIT binary patch literal 14279 zcmb8VWmFtZ6EM0g?y%_M4!gL!yTjrV2);-No)8G`&a$|>CukrL+}%mA;6Z{z2qX|b zp7(tBocrhgxZN|;Q&TmiJ1+W8h$5;NaswZ~wo`Q!juR3-AR+4;6(N z03=31B}RD~1keHiKp-m0f4ctPf{F%2N5R0v0$@L*)rkNoKr~b|OjK-ibS%_o5)>dY z02Pf9#4nGIp>Kmp!sHp6IxkS%hefUcGe~QkyC7volx&kx3fg*MQ?Mx7d52vZF6=zB zqDBGyC+Ghq>6sTQ8af8%Gm__7rT+>F+JF0ha{dzpVnpR9(U(Vq*`%T~VF-jOcs6d6 zGP69b0`O2#o^3!S2FL=g-xC~+>jhO9#o)0_bmr?&V@#DE-dY2`9}<`ri#OVg)$YI)K7p&$bA@J8`7oS=Jw-kvmK(1D$9vUJ@}76 zH&*hpB1(|^ z1W0B+WBJ4MMJm|kky&d0q=A-Z{xKrCJ?$`jVC44WJl_5ZzOIVT$x&sBPLX=r*@+d& z*6v@EBPz(mw@6jhE0F1e8k+S3SSBVJPiE^PCW(ZigRp z-bCeEGeX;7`QoD~*o-~ioIEmvPTOHmfbyXDnJaGsgh;wj3m9fU`cpHKn8%=qRyx_W zlcP_CqNPVIs-j!luJj1h(Vsq^;Ta&75*~!o_c?Ksg8G@S6L|c1y1MDNt-KzFR$)ha z;l;3Pl<52;t;odCnSCfS7A<%s{V?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D*b2p3~!&h z-bvT5ESZG=`F!GnR6XDcAabjUc=RY-)V$!*5ARvf6qCO&>9Zv{NV{=1XUTue5zxR4 zd-U+%djyLWLpl%m5Ne8fCq0&mKTd__z|q zpbES+-e=@Tp=cGAf7*Ylb`jTqN9l!nfTib!%|SKKIz|4-+~ROiRa*#ea=7RHihZql XArz_dZwjN2PV-m)v;U0fpH}`40c9Mm literal 0 HcmV?d00001 diff --git a/backend/test_poster.py b/backend/test_poster.py new file mode 100644 index 0000000..3827580 --- /dev/null +++ b/backend/test_poster.py @@ -0,0 +1,26 @@ +import yt_dlp +import json +import os +import urllib.request + +url = "https://www.youtube.com/playlist?list=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-" + +ydl_opts = { + 'extract_flat': True, + 'quiet': True, +} + +with yt_dlp.YoutubeDL(ydl_opts) as ydl: + meta = ydl.extract_info(url, download=False, process=False) + thumbs = meta.get('thumbnails', []) + show_name = meta.get('playlist_title') or meta.get('uploader') or 'Unknown' + + print(f"Show Name: {show_name}") + if thumbs: + best_thumb = thumbs[-1]['url'] + print(f"Best Thumb: {best_thumb}") + # Verify download + urllib.request.urlretrieve(best_thumb, 'test_poster.jpg') + print(f"File size: {os.path.getsize('test_poster.jpg')} bytes") + else: + print("No thumbnails found at top level.") diff --git a/backend/test_yt.py b/backend/test_yt.py new file mode 100644 index 0000000..e565491 --- /dev/null +++ b/backend/test_yt.py @@ -0,0 +1,24 @@ +import yt_dlp +import sys +import json + +url = sys.argv[1] + +ydl_opts = { + 'skip_download': True, + 'quiet': True, + 'no_warnings': True, + 'extract_flat': True, +} + +try: + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=False) + print("Success!") + if 'entries' in info: + print("Is Playlist. Number of entries:", len(list(info['entries']))) + print("First item title:", list(info['entries'])[0].get('title', 'Unknown')) + else: + print("Single Video:", info.get('title')) +except Exception as e: + print(f"Error: {e}") diff --git a/backend/test_yt_dlp_progress.py b/backend/test_yt_dlp_progress.py new file mode 100644 index 0000000..28f91a6 --- /dev/null +++ b/backend/test_yt_dlp_progress.py @@ -0,0 +1,31 @@ +import yt_dlp +import json + +def progress_hook(d): + print("--- PROGRESS UPDATE ---") + + # Let's print the dict but omit 'info_dict' since it's huge + d_copy = {k: v for k, v in d.items() if k != 'info_dict'} + print(json.dumps(d_copy, indent=2)) + + # Also print the specific fields we try to parse + if d['status'] == 'downloading': + percent_str = d.get('_percent_str', '0%').strip() + print(f"Origin percent_str: {repr(percent_str)}") + try: + percent_clean = percent_str.replace('\x1b[0;94m', '').replace('\x1b[0m', '').replace('%', '') + percent_val = float(percent_clean) + print(f"Cleaned percent: {percent_val}") + except Exception as e: + print(f"Failed to parse percent: {e}") + +ydl_opts = { + 'format': 'worst', + 'progress_hooks': [progress_hook], + 'quiet': True, + 'outtmpl': '/tmp/test_vid.%(ext)s' +} + +with yt_dlp.YoutubeDL(ydl_opts) as ydl: + # A lightweight test video URL + ydl.download(['https://www.youtube.com/watch?v=jNQXAC9IVRw']) diff --git a/backend/worker.py b/backend/worker.py new file mode 100644 index 0000000..ee2e396 --- /dev/null +++ b/backend/worker.py @@ -0,0 +1,231 @@ +import os +import redis +import json +from celery import Celery +import yt_dlp + +# Redis Setup +redis_url = os.getenv("REDIS_URL", "redis://redis:6379/0") +r = redis.Redis.from_url(redis_url, decode_responses=True) + +# Celery Setup +celery_app = Celery( + "worker", + broker=redis_url, + backend=redis_url +) + +class MyLogger(object): + def debug(self, msg): + pass + + def warning(self, msg): + pass + + def error(self, msg): + print(msg) + +@celery_app.task(bind=True) +def download_video_task(self, url: str, format_id: str, quality_label: str): + """ + Background job to download a Youtube Video. + Reports progress natively back to Redis for the web server to SSE. + """ + job_id = self.request.id + nas_dir = os.getenv("NAS_PATH", "/mnt/nas/downloads") + + # Ensure destination directory exists + os.makedirs(nas_dir, exist_ok=True) + + # Redis key to store this job's progress + progress_key = f"job_progress:{job_id}" + + r.hset(progress_key, mapping={ + "status": "starting", + "progress": 0, + "eta": "Calculating...", + "speed": "0MiB/s", + "quality": quality_label + }) + + last_update = {"time": 0} + + def progress_hook(d): + import time + current_time = time.time() + + # Throttle Redis calls to max 10 times per second during active downloads + if d.setdefault('status', 'downloading') == 'downloading' and current_time - last_update["time"] < 0.1: + return + + last_update["time"] = current_time + + # 1. Check for action commands from the user (Pause / Cancel) + action_key = f"job_action:{job_id}" + action = r.get(action_key) + + if action == "cancel": + r.delete(action_key) + raise Exception("Job cancelled by user") + + if action == "pause": + r.hset(progress_key, "status", "paused") + while r.get(action_key) == "pause": + time.sleep(1) # Block the download loop + # Exited pause, resume processing + r.hset(progress_key, "status", "downloading") + if r.get(action_key) == "cancel": + r.delete(action_key) + raise Exception("Job cancelled by user") + + # 2. Extract Progress and Playlist Info + if d['status'] == 'downloading': + try: + import re + + percent_str = d.get('_percent_str', '0%').strip() + match = re.search(r'([\d\.]+)%', percent_str) + percent_val = float(match.group(1)) if match else 0.0 + + speed_str = d.get('_speed_str', '0MiB/s').strip() + speed = re.sub(r'\x1b\[[0-9;]*[mK]', '', speed_str).strip() + if "DL:" in percent_str: + speed_match = re.search(r'DL:([^\s]+)', percent_str) + if speed_match: + speed = speed_match.group(1) + '/s' + + eta_str = d.get('_eta_str', 'Unknown').strip() + eta = re.sub(r'\x1b\[[0-9;]*[mK]', '', eta_str).strip() + + info = d.get('info_dict', {}) + video_title = info.get('title', 'Unknown Title') + playlist_index = info.get('playlist_index', 1) or 1 + playlist_count = info.get('n_entries', 1) or 1 + + # If downloading a playlist, prefix the status + progress_status = "downloading" + if playlist_count > 1: + r.hset(progress_key, "playlist_mode", "true") + r.hset(progress_key, "current_video", playlist_index) + r.hset(progress_key, "total_videos", playlist_count) + r.hset(progress_key, "video_title", video_title) + + r.hset(progress_key, mapping={ + "status": r.hget(progress_key, "status") or "downloading", # Retain 'paused' if just waking up + "progress": percent_val, + "eta": eta, + "speed": speed + }) + except Exception as e: + import traceback + print(f"Failed to parse progress: {e}\n{traceback.format_exc()}") + pass + + elif d['status'] == 'finished': + r.hset(progress_key, mapping={ + "status": "processing", + "progress": 100, + "eta": "Finalizing/Merging Video...", + "speed": "Done" + }) + + try: + is_playlist = False + + # Pre-flight: Download Show Poster (Playlist/Channel Thumbnail) + try: + meta_opts = { + 'quiet': True, + 'extract_flat': True, + 'ignoreerrors': True, + 'js_runtimes': {'node': {}} + } + cookie_path = '/app/cookies.txt' + if os.path.exists(cookie_path): + meta_opts['cookiefile'] = cookie_path + + with yt_dlp.YoutubeDL(meta_opts) as ydl_meta: + meta = ydl_meta.extract_info(url, download=False, process=False) + # Determine Plex "Show" Name to match output_template + is_playlist = meta.get('_type') == 'playlist' + show_name = meta.get('title') if is_playlist else meta.get('uploader') + + # Sanitize the show_name to match OS folder naming exactly as yt-dlp does + from yt_dlp.utils import sanitize_filename + show_name_clean = sanitize_filename(show_name, restricted=False) if show_name else 'Unknown' + + thumbs = meta.get('thumbnails', []) + if thumbs: + best_thumb_url = thumbs[-1]['url'] + show_dir = os.path.join(nas_dir, show_name_clean) + os.makedirs(show_dir, exist_ok=True) + + import urllib.request + poster_path = os.path.join(show_dir, 'poster.jpg') + if not os.path.exists(poster_path): + urllib.request.urlretrieve(best_thumb_url, poster_path) + except Exception as e: + # Silently fail poster fetch so main download isn't impacted + pass + + # Dynamically define directory grouping based on media type + if is_playlist: + # Flat folder for playlists, no seasons folder, numbered locally + output_template = os.path.join(nas_dir, + '%(playlist_title,uploader)s', + '%(playlist_autonumber)02d - %(title)s.%(ext)s' + ) + else: + # Plex TV Shows naming convention for individual channel videos + # Structure: Show Name/Season YYYY/Show Name - SYYYYEmmdd - Title.ext + output_template = os.path.join(nas_dir, + '%(uploader)s', + 'Season %(upload_date>%Y|Unknown)s', + '%(uploader)s - S%(upload_date>%Y|00)sE%(upload_date>%m%d|00)s - %(title)s.%(ext)s' + ) + + ydl_opts = { + 'format': f"{format_id}+bestaudio/best", + 'outtmpl': output_template, + 'progress_hooks': [progress_hook], + 'logger': MyLogger(), + 'ignoreerrors': True, + # 'cookiesfrombrowser': ('chrome',), # Fails in docker without host mount mapping + 'merge_output_format': 'mp4', # Ensures ffmpeg merges audio + video into single mp4 + + # Speed optimizations: Use native concurrent fragments rather than aria2c + # as aria2c is heavily throttled by YouTube + 'concurrent_fragment_downloads': 8, + 'http_chunk_size': 10485760, # 10MB chunks to bypass speed throttling + + # Impersonate iOS client to bypass YouTube throttling + 'extractor_args': {'youtube': ['player_client=ios,android,web']}, + + # Save Metadata + 'writeinfojson': True, + 'writethumbnail': True, + 'writedescription': True, + + # Use NodeJS for JS Challenge Solving (Bot detection bypass) + 'js_runtimes': {'node': {}} + } + + cookie_path = '/app/cookies.txt' + if os.path.exists(cookie_path): + ydl_opts['cookiefile'] = cookie_path + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + ydl.download([url]) + + # Mark as 100% completed in redis + r.hset(progress_key, "status", "completed") + # Cleanup redis cache after 24 hrs + r.expire(progress_key, 86400) + + return {"status": "success", "job_id": job_id} + + except Exception as e: + r.hset(progress_key, "status", "failed") + r.hset(progress_key, "error_detail", str(e)) + r.expire(progress_key, 86400) + raise e diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e23ef31 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,55 @@ +services: + frontend: + build: + context: ./frontend + dockerfile: Dockerfile + restart: unless-stopped + ports: + - "8002:80" + depends_on: + - backend + + backend: + build: + context: ./backend + dockerfile: Dockerfile + restart: unless-stopped + command: uvicorn main:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips="*" + expose: + - "8000" + dns: + - 8.8.8.8 + - 8.8.4.4 + volumes: + - ./backend:/app + - ${NAS_SHARE_PATH}:/mnt/nas/downloads + environment: + - REDIS_URL=redis://redis:6379/0 + - NAS_PATH=/mnt/nas/downloads + depends_on: + - redis + + worker: + build: + context: ./backend + dockerfile: Dockerfile + restart: unless-stopped + command: celery -A worker.celery_app worker --loglevel=info + dns: + - 8.8.8.8 + - 8.8.4.4 + volumes: + - ./backend:/app + - ${NAS_SHARE_PATH}:/mnt/nas/downloads + environment: + - REDIS_URL=redis://redis:6379/0 + - NAS_PATH=/mnt/nas/downloads + depends_on: + - redis + - backend + + redis: + image: redis:7-alpine + restart: unless-stopped + ports: + - "6379:6379" diff --git a/docs/plans/2026-02-21-yt-downloader-design.md b/docs/plans/2026-02-21-yt-downloader-design.md new file mode 100644 index 0000000..fda90ec --- /dev/null +++ b/docs/plans/2026-02-21-yt-downloader-design.md @@ -0,0 +1,37 @@ +# YouTube Downloader Web App Design + +## MVP Requirements +- Web app running inside a Docker Container. +- Core engine: `yt-dlp` for downloading individually linked videos and entire playlists. +- User input: Paste URL into a React dashboard. +- Destination: Videos are downloaded directly to a configured NAS location on the backend. +- Quality Constraint: Videos are always downloaded to a minimum quality of 720p. If the user explicitly selects a resolution on the dashboard (e.g., 1080p, 4K) and it is available, it honors that up to the selected limit. + +## Architecture +**Tech Stack:** +- **Backend**: FastAPI (Python 3.12+). Excellent async capabilities for handling heavy `yt-dlp` tasks. +- **Frontend**: React 19 / Vite. Snappy SPA dashboard built using modern UI/UX principles (e.g., shadcn/ui). +- **Task Queue**: Celery + Redis (or FastAPI BackgroundTasks for v1 if Redis is overkill). Manages long-running downloads asynchronously. + +**Data Flow:** +1. User pastes a YouTube URL into the React dashboard. +2. Frontend calls a FastAPI `/api/metadata` endpoint. +3. Backend runs `yt-dlp -F` (with `--cookies-from-browser` for YouTube) to fetch metadata without downloading. +4. Frontend displays thumbnail, title, and a dropdown of qualities >= 720p. +5. User selects a quality and triggers download. +6. Backend creates a background task with celery/Redis, generates a Job ID, and returns it. +7. Frontend polls or subscribes (SSE) to `/api/status/{job_id}` for progress. +8. Backend runs `yt-dlp -f [quality]` and saves the output to the NAS directory. + +## Core Features +- **URL Parsing & Validation Engine**: Validates inputs, fetches metadata. Use browser cookies to overcome 403 Forbidden errors on YouTube. +- **Quality Selector**: Dropdown showing available formats that pass the >= 720p check. +- **Background Task Runner**: Handles queueing multiple jobs (e.g., playlist support) so the API doesn't hang. +- **Progress Emitter**: Streams stdout of `yt-dlp` (via SSE) to update a sleek progress bar on the dashboard. +- **NAS Destination Display**: Visual indicator of the current download directory path. + +## Error Handling & Edge Cases +- **Resolution unavailable**: Fall back horizontally to closest format that is still >= 720p. Fail gracefully if only 480p is available. +- **Network Interruptions**: Ensure `yt-dlp` can resume downloads (`yt-dlp --continue`) without starting from scratch. +- **YouTube 403 Forbidden**: Always inject `--cookies-from-browser chrome` (or relevant setup) to bypass age restrictions or bot checks. +- **Stale Jobs**: Implement timeout/retry mechanics in Celery to ensure the queue doesn't get blocked by frozen connections. diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..a547bf3 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000..afe9d89 --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,18 @@ +# Build stage +FROM node:20-alpine AS build +WORKDIR /app +COPY package*.json ./ +RUN npm install +RUN npm install -D @types/node +COPY . . +RUN npm run build + +# Production runtime stage +FROM nginx:alpine +# Copy built assets +COPY --from=build /app/dist /usr/share/nginx/html +# Copy nginx config +COPY nginx.conf /etc/nginx/conf.d/default.conf + +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..74872fd --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,50 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: + +- Configure the top-level `parserOptions` property like this: + +```js +export default tseslint.config({ + languageOptions: { + // other options... + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + }, +}) +``` + +- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` +- Optionally add `...tseslint.configs.stylisticTypeChecked` +- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: + +```js +// eslint.config.js +import react from 'eslint-plugin-react' + +export default tseslint.config({ + // Set the react version + settings: { react: { version: '18.3' } }, + plugins: { + // Add the react plugin + react, + }, + rules: { + // other rules... + // Enable its recommended rules + ...react.configs.recommended.rules, + ...react.configs['jsx-runtime'].rules, + }, +}) +``` diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js new file mode 100644 index 0000000..092408a --- /dev/null +++ b/frontend/eslint.config.js @@ -0,0 +1,28 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { ignores: ['dist'] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ['**/*.{ts,tsx}'], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + plugins: { + 'react-hooks': reactHooks, + 'react-refresh': reactRefresh, + }, + rules: { + ...reactHooks.configs.recommended.rules, + 'react-refresh/only-export-components': [ + 'warn', + { allowConstantExport: true }, + ], + }, + }, +) diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..ff26ef8 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + Craigs Youtube Downloader + + +
+ + + diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000..a721a8f --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,30 @@ +server { + listen 80; + + # Enable gzip compression + gzip on; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; + + location / { + root /usr/share/nginx/html; + index index.html index.htm; + try_files $uri $uri/ /index.html; + } + + location /api/ { + proxy_pass http://backend:8000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Disable buffering for SSE (Server-Sent Events) + proxy_buffering off; + proxy_cache off; + chunked_transfer_encoding off; + proxy_read_timeout 24h; + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..d90fa00 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,34 @@ +{ + "name": "-frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@tailwindcss/postcss": "^4.2.0", + "lucide-react": "^0.575.0", + "react": "^18.3.1", + "react-dom": "^18.3.1" + }, + "devDependencies": { + "@eslint/js": "^9.13.0", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "^4.3.3", + "autoprefixer": "^10.4.24", + "eslint": "^9.13.0", + "eslint-plugin-react-hooks": "^5.0.0", + "eslint-plugin-react-refresh": "^0.4.14", + "globals": "^15.11.0", + "postcss": "^8.5.6", + "tailwindcss": "^4.2.0", + "typescript": "~5.6.2", + "typescript-eslint": "^8.11.0", + "vite": "^5.4.10" + } +} diff --git a/frontend/postcss.config.js b/frontend/postcss.config.js new file mode 100644 index 0000000..d0ec925 --- /dev/null +++ b/frontend/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + '@tailwindcss/postcss': {}, + autoprefixer: {}, + }, +} diff --git a/frontend/public/vite.svg b/frontend/public/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/frontend/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/App.css b/frontend/src/App.css new file mode 100644 index 0000000..b9d355d --- /dev/null +++ b/frontend/src/App.css @@ -0,0 +1,42 @@ +#root { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; +} + +.logo { + height: 6em; + padding: 1.5em; + will-change: filter; + transition: filter 300ms; +} +.logo:hover { + filter: drop-shadow(0 0 2em #646cffaa); +} +.logo.react:hover { + filter: drop-shadow(0 0 2em #61dafbaa); +} + +@keyframes logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: no-preference) { + a:nth-of-type(2) .logo { + animation: logo-spin infinite 20s linear; + } +} + +.card { + padding: 2em; +} + +.read-the-docs { + color: #888; +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 0000000..ca8edab --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,153 @@ +import { useState } from 'react'; +import HeroInput from './components/HeroInput'; +import MetadataCard from './components/MetadataCard'; +import ActiveDownloadsPanel from './components/ActiveDownloadsPanel'; + +export type VideoFormat = { + format_id: string; + quality: string; + ext: string; + vcodec?: string; + filesize?: number; +}; + +export type VideoMetadata = { + title: string; + thumbnail: string; + duration: number; + uploader: string; + url: string; + available_formats: VideoFormat[]; +}; + +export type DownloadJob = { + job_id: string; + status: string; + progress: number; + eta: string; + speed: string; + title: string; + playlist_mode?: string; + current_video?: number; + total_videos?: number; + video_title?: string; +}; + +function App() { + const [metadata, setMetadata] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [activeJobs, setActiveJobs] = useState>({}); + + const handleFetchMetadata = async (url: string) => { + setLoading(true); + setError(null); + setMetadata(null); + + try { + const apiUrl = import.meta.env.VITE_API_URL ?? ''; + const response = await fetch(`${apiUrl}/api/metadata`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ url }), + }); + + if (!response.ok) { + const errData = await response.json(); + throw new Error(errData.detail || 'Failed to fetch metadata'); + } + + const data = await response.json(); + setMetadata(data); + } catch (err: any) { + setError(err.message); + } finally { + setLoading(false); + } + }; + + const handleStartDownload = async (formatId: string, qualityLabel: string) => { + if (!metadata) return; + + try { + const apiUrl = import.meta.env.VITE_API_URL ?? ''; + const response = await fetch(`${apiUrl}/api/download`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + url: metadata.url, + format_id: formatId, + quality_label: qualityLabel, + }), + }); + + if (!response.ok) throw new Error('Failed to start download'); + + const data = await response.json(); + const jobId = data.job_id; + + // Add to active jobs + setActiveJobs(prev => ({ + ...prev, + [jobId]: { + job_id: jobId, + status: 'Starting...', + progress: 0, + eta: '--', + speed: '--', + title: metadata.title, + } + })); + + // In a real app we'd connect to SSE here. For MVP, the ActiveDownloadsPanel handles it. + + } catch (err: any) { + alert(err.message); + } + }; + + return ( +
+ {/* Background Decor */} +
+
+ +
+
+

+ Craigs Youtube Downloader +

+

+ Paste a link to download videos in stunning 720p+ quality straight to your NAS. +

+
+ + + + {error && ( +
+ {error} +
+ )} + + {metadata && !loading && ( + + )} + + {Object.keys(activeJobs).length > 0 && ( + + )} +
+
+ ); +} + +export default App; diff --git a/frontend/src/assets/react.svg b/frontend/src/assets/react.svg new file mode 100644 index 0000000..6c87de9 --- /dev/null +++ b/frontend/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/components/ActiveDownloadsPanel.tsx b/frontend/src/components/ActiveDownloadsPanel.tsx new file mode 100644 index 0000000..f7df0d8 --- /dev/null +++ b/frontend/src/components/ActiveDownloadsPanel.tsx @@ -0,0 +1,169 @@ +import { useEffect } from 'react'; +import type { DownloadJob } from '../App'; +import { Video, CheckCircle, AlertOctagon, Loader, Pause, Play, X } from 'lucide-react'; + +interface PanelProps { + activeJobs: Record; + setActiveJobs: React.Dispatch>>; +} + +export default function ActiveDownloadsPanel({ activeJobs, setActiveJobs }: PanelProps) { + + useEffect(() => { + const EventSources: Record = {}; + const apiUrl = import.meta.env.VITE_API_URL ?? ''; + + Object.keys(activeJobs).forEach(jobId => { + const job = activeJobs[jobId]; + // Only open connections for active jobs + if (job.status === 'completed' || job.status === 'failed' || EventSources[jobId]) { + return; + } + + console.log("Connecting to SSE for:", jobId); + const url = `${apiUrl}/api/status/${jobId}`; + const source = new EventSource(url); + + source.onmessage = (event) => { + const data = JSON.parse(event.data); + + setActiveJobs(prev => ({ + ...prev, + [jobId]: { + ...prev[jobId], + status: data.status, + progress: Number(data.progress || 0), + eta: data.eta || '--', + speed: data.speed || '--', + playlist_mode: data.playlist_mode, + current_video: data.current_video ? Number(data.current_video) : undefined, + total_videos: data.total_videos ? Number(data.total_videos) : undefined, + video_title: data.video_title + } + })); + + if (data.status === 'completed' || data.status === 'failed') { + source.close(); + delete EventSources[jobId]; + } + }; + + source.onerror = (e) => { + console.error("SSE Error for", jobId, e); + source.close(); + delete EventSources[jobId]; + }; + + EventSources[jobId] = source; + }); + + return () => { + // Cleanup all open event sources on unmount + Object.values(EventSources).forEach(source => source.close()); + }; + }, [Object.keys(activeJobs).join(',')]); + + const handleAction = async (jobId: string, action: 'pause' | 'resume' | 'cancel') => { + try { + const apiUrl = import.meta.env.VITE_API_URL ?? ''; + await fetch(`${apiUrl}/api/jobs/${jobId}/${action}`, { method: 'POST' }); + } catch (e) { + console.error(e); + } + }; + + const handleGlobalAction = async (action: 'pause' | 'resume' | 'cancel') => { + const promises = Object.values(activeJobs) + .filter(job => job.status !== 'completed' && job.status !== 'failed') + .map(job => handleAction(job.job_id, action)); + await Promise.all(promises); + }; + + const hasActiveJobs = Object.values(activeJobs).some(job => job.status !== 'completed' && job.status !== 'failed'); + + return ( +
+
+

+ Active Jobs +

+ {hasActiveJobs && ( +
+ + + +
+ )} +
+ +
+ {Object.values(activeJobs).map((job) => ( +
+
+
+
+ {job.status === 'completed' ? : + job.status === 'failed' ? : +
+
+
{job.title}
+ {job.playlist_mode && job.current_video && job.total_videos && ( +

+ Downloading {job.current_video} of {job.total_videos}: {job.video_title} +

+ )} +

+ {(job.status === 'starting' || job.status === 'downloading') && } + {job.status === 'paused' && } + {job.status} + {job.status === 'downloading' && ` • ${job.speed} • ETA: ${job.eta}`} +

+
+
+ +
+ {/* Control Buttons */} + {job.status !== 'completed' && job.status !== 'failed' && ( +
+ {job.status === 'paused' ? ( + + ) : ( + + )} + +
+ )} + + + {typeof job.progress === 'number' ? job.progress.toFixed(1) : job.progress}% + +
+
+ +
+
+ {/* Shine effect on progress bar */} + {(job.status === 'downloading' || job.status === 'processing') && ( +
+ )} +
+
+
+ ))} +
+
+ ); +} diff --git a/frontend/src/components/HeroInput.tsx b/frontend/src/components/HeroInput.tsx new file mode 100644 index 0000000..f552a05 --- /dev/null +++ b/frontend/src/components/HeroInput.tsx @@ -0,0 +1,47 @@ +import { useState } from 'react'; +import { Search, Loader2 } from 'lucide-react'; + +interface HeroInputProps { + onFetch: (url: string) => void; + isLoading: boolean; +} + +export default function HeroInput({ onFetch, isLoading }: HeroInputProps) { + const [url, setUrl] = useState(''); + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (url.trim()) { + onFetch(url.trim()); + } + }; + + return ( +
+
+
+ +
+ {isLoading ? : } +
+ + setUrl(e.target.value)} + placeholder="Paste YouTube or Playlist URL here..." + className="flex-1 bg-transparent border-none outline-none text-foreground placeholder:text-muted-foreground/50 text-lg py-3 px-2" + disabled={isLoading} + /> + + +
+
+ ); +} diff --git a/frontend/src/components/MetadataCard.tsx b/frontend/src/components/MetadataCard.tsx new file mode 100644 index 0000000..07acce4 --- /dev/null +++ b/frontend/src/components/MetadataCard.tsx @@ -0,0 +1,102 @@ +import { useState } from 'react'; +import { DownloadCloud, Clock, User, AlertCircle } from 'lucide-react'; +import type { VideoMetadata } from '../App'; + +interface MetadataCardProps { + metadata: VideoMetadata; + onDownload: (formatId: string, qualityLabel: string) => void; +} + +export default function MetadataCard({ metadata, onDownload }: MetadataCardProps) { + const formatSeconds = (sec: number) => { + const min = Math.floor(sec / 60); + const s = Math.floor(sec % 60); + return `${min}:${s < 10 ? '0' : ''}${s}`; + }; + + const [selectedFormat, setSelectedFormat] = useState( + metadata.available_formats[0]?.format_id || '' + ); + + const handleDownloadClick = () => { + const fmt = metadata.available_formats.find((f) => f.format_id === selectedFormat); + if (fmt) { + onDownload(fmt.format_id, fmt.quality); + } + }; + + return ( +
+
+ + {/* Decorative corner glow */} +
+ +
+
+ Video Thumbnail +
+
+ + {formatSeconds(metadata.duration)} +
+
+ +
+
+

+ {metadata.title} +

+
+ + {metadata.uploader} +
+
+ +
+ {metadata.available_formats.length > 0 ? ( + <> + +
+ + + +
+ + ) : ( +
+ + No high-resolution streams available (720p+ required). +
+ )} +
+ +
+
+
+
+ ); +} diff --git a/frontend/src/index.css b/frontend/src/index.css new file mode 100644 index 0000000..016b0b0 --- /dev/null +++ b/frontend/src/index.css @@ -0,0 +1,83 @@ +@import "tailwindcss"; + +@theme { + --color-background: hsl(224 71.4% 4.1%); + --color-foreground: hsl(210 20% 98%); + + --color-card: hsl(224 71.4% 4.1%); + --color-card-foreground: hsl(210 20% 98%); + + --color-popover: hsl(224 71.4% 4.1%); + --color-popover-foreground: hsl(210 20% 98%); + + --color-primary: hsl(262.1 83.3% 57.8%); + --color-primary-foreground: hsl(210 20% 98%); + + --color-secondary: hsl(215 27.9% 16.9%); + --color-secondary-foreground: hsl(210 20% 98%); + + --color-muted: hsl(215 27.9% 16.9%); + --color-muted-foreground: hsl(217.9 10.6% 64.9%); + + --color-accent: hsl(215 27.9% 16.9%); + --color-accent-foreground: hsl(210 20% 98%); + + --color-destructive: hsl(0 62.8% 30.6%); + --color-destructive-foreground: hsl(210 20% 98%); + + --color-border: hsl(215 27.9% 16.9%); + --color-input: hsl(215 27.9% 16.9%); + --color-ring: hsl(262.1 83.3% 57.8%); + + --radius: 0.75rem; +} + +/* Base styles using the new theme variables */ +@layer base { + + *, + ::before, + ::after { + border-color: var(--color-border); + } + + body { + background-color: var(--color-background); + color: var(--color-foreground); + font-feature-settings: "rlig" 1, "calt" 1; + } +} + +/* Glassmorphism Utilities */ +.glass { + background: rgba(17, 24, 39, 0.7); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + border: 1px solid rgba(255, 255, 255, 0.08); +} + +.glass-card { + background: linear-gradient(145deg, rgba(30, 41, 59, 0.6) 0%, rgba(15, 23, 42, 0.8) 100%); + backdrop-filter: blur(20px); + border: 1px solid rgba(255, 255, 255, 0.05); + box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37); +} + +.animate-gradient { + background-size: 300%; + animation: animatedgradient 6s ease infinite alternate; +} + +@keyframes animatedgradient { + 0% { + background-position: 0% 50%; + } + + 50% { + background-position: 100% 50%; + } + + 100% { + background-position: 0% 50%; + } +} \ No newline at end of file diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx new file mode 100644 index 0000000..bef5202 --- /dev/null +++ b/frontend/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import './index.css' +import App from './App.tsx' + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/frontend/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/frontend/tailwind.config.js b/frontend/tailwind.config.js new file mode 100644 index 0000000..de2e563 --- /dev/null +++ b/frontend/tailwind.config.js @@ -0,0 +1,79 @@ +/** @type {import('tailwindcss').Config} */ +export default { + darkMode: ["class"], + content: [ + "./index.html", + "./src/**/*.{ts,tsx,js,jsx}", + ], + theme: { + container: { + center: true, + padding: "2rem", + screens: { + "2xl": "1400px", + }, + }, + extend: { + colors: { + border: "hsl(var(--border))", + input: "hsl(var(--input))", + ring: "hsl(var(--ring))", + background: "hsl(var(--background))", + foreground: "hsl(var(--foreground))", + primary: { + DEFAULT: "hsl(var(--primary))", + foreground: "hsl(var(--primary-foreground))", + }, + secondary: { + DEFAULT: "hsl(var(--secondary))", + foreground: "hsl(var(--secondary-foreground))", + }, + destructive: { + DEFAULT: "hsl(var(--destructive))", + foreground: "hsl(var(--destructive-foreground))", + }, + muted: { + DEFAULT: "hsl(var(--muted))", + foreground: "hsl(var(--muted-foreground))", + }, + accent: { + DEFAULT: "hsl(var(--accent))", + foreground: "hsl(var(--accent-foreground))", + }, + popover: { + DEFAULT: "hsl(var(--popover))", + foreground: "hsl(var(--popover-foreground))", + }, + card: { + DEFAULT: "hsl(var(--card))", + foreground: "hsl(var(--card-foreground))", + }, + }, + borderRadius: { + lg: "var(--radius)", + md: "calc(var(--radius) - 2px)", + sm: "calc(var(--radius) - 4px)", + }, + keyframes: { + "accordion-down": { + from: { height: 0 }, + to: { height: "var(--radix-accordion-content-height)" }, + }, + "accordion-up": { + from: { height: "var(--radix-accordion-content-height)" }, + to: { height: 0 }, + }, + "pulse-slow": { + "0%, 100%": { opacity: 1 }, + "50%": { opacity: .5 }, + } + }, + animation: { + "accordion-down": "accordion-down 0.2s ease-out", + "accordion-up": "accordion-up 0.2s ease-out", + "pulse-slow": "pulse-slow 3s cubic-bezier(0.4, 0, 0.6, 1) infinite", + }, + }, + }, + plugins: [], +} diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json new file mode 100644 index 0000000..f867de0 --- /dev/null +++ b/frontend/tsconfig.app.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src"] +} diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000..1ffef60 --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,7 @@ +{ + "files": [], + "references": [ + { "path": "./tsconfig.app.json" }, + { "path": "./tsconfig.node.json" } + ] +} diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.json new file mode 100644 index 0000000..254bfe7 --- /dev/null +++ b/frontend/tsconfig.node.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "target": "ES2022", + "lib": [ + "ES2023" + ], + "module": "ESNext", + "skipLibCheck": true, + /* Bundler mode */ + "moduleResolution": "Bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true, + "types": [ + "node" + ] + }, + "include": [ + "vite.config.ts" + ] +} \ No newline at end of file diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts new file mode 100644 index 0000000..9447692 --- /dev/null +++ b/frontend/vite.config.ts @@ -0,0 +1,21 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import path from "path" + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [react()], + resolve: { + alias: { + "@": path.resolve(__dirname, "./src"), + }, + }, + server: { + proxy: { + '/api': { + target: 'http://localhost:8002', + changeOrigin: true, + } + } + } +}) diff --git a/test_playlist.py b/test_playlist.py new file mode 100644 index 0000000..e6e3728 --- /dev/null +++ b/test_playlist.py @@ -0,0 +1,10 @@ +import yt_dlp +import json + +ydl_opts = { + 'extract_flat': True, + 'playlistend': 1, +} +with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info("https://www.youtube.com/playlist?list=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-", download=False) + print(json.dumps({k: v for k, v in info.items() if k != 'entries'}, indent=2))