From cb61ad08c78b72411c6f4e6e2eafc0d0b61239e1 Mon Sep 17 00:00:00 2001 From: DeSqBlocki Date: Sat, 6 Dec 2025 15:31:13 +0100 Subject: [PATCH] REVAMP --- .env.example | 11 - .gitignore | 201 +----------------- controllers/queueController.js | 19 +- queue_worker.js | 100 +++++---- .../__pycache__/proxer_utils.cpython-311.pyc | Bin 0 -> 6770 bytes .../__pycache__/proxer_utils.cpython-313.pyc | Bin 0 -> 5985 bytes .../__pycache__/proxer_utils.cpython-38.pyc | Bin 0 -> 2969 bytes .../__pycache__/script_utils.cpython-313.pyc | Bin 0 -> 1866 bytes .../__pycache__/script_utils.cpython-38.pyc | Bin 0 -> 1367 bytes scripts/lib/proxer_utils.py | 77 +++---- scripts/proxer-dl.py | 59 ----- views/status.ejs | 52 ++++- 12 files changed, 145 insertions(+), 374 deletions(-) delete mode 100644 .env.example create mode 100644 scripts/lib/__pycache__/proxer_utils.cpython-311.pyc create mode 100644 scripts/lib/__pycache__/proxer_utils.cpython-313.pyc create mode 100644 scripts/lib/__pycache__/proxer_utils.cpython-38.pyc create mode 100644 scripts/lib/__pycache__/script_utils.cpython-313.pyc create mode 100644 scripts/lib/__pycache__/script_utils.cpython-38.pyc delete mode 100644 scripts/proxer-dl.py diff --git a/.env.example b/.env.example deleted file mode 100644 index a05906a..0000000 --- a/.env.example +++ /dev/null @@ -1,11 +0,0 @@ -# .env.example — copy to .env and fill values -MONGO_URI=mongodb://username:password@192.168.20.21:27023 -MONGO_DB=downloads -TOKEN_PREFIX=prefix= -WORKERS=4 -OUTPUT_DIR=/mnt/media/WIP/ -PORT=3000 - - -# Optional -LOG_LEVEL=info \ No newline at end of file diff --git a/.gitignore b/.gitignore index 84307af..30b61dc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,202 +1,3 @@ -# ---> Java -node_modules -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -replay_pid* - -# ---> Python -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# UV -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -#uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -#poetry.lock - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -#pdm.lock -# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it -# in version control. -# https://pdm.fming.dev/latest/usage/project/#working-with-version-control -.pdm.toml -.pdm-python -.pdm-build/ - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments .env +node_modules .venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ - -# Ruff stuff: -.ruff_cache/ - -# PyPI configuration file -.pypirc - diff --git a/controllers/queueController.js b/controllers/queueController.js index bac3059..72ea8b4 100644 --- a/controllers/queueController.js +++ b/controllers/queueController.js @@ -102,18 +102,31 @@ exports.status = async (req, res) => { const db = await getDb(); const queued = await db.collection("queue") - .find({}).sort({ created_at: 1 }).toArray(); + .find({ $or: [ { processing: { $exists: false } }, { processing: false } ] }) + .sort({ created_at: 1 }) + .toArray(); + + const processing = await db.collection("queue") + .find({ processing: true }) + .sort({ created_at: 1 }) + .toArray(); const done = await db.collection("done") - .find({}).sort({ finished_at: -1 }).toArray(); + .find({}) + .sort({ finished_at: -1 }) + .toArray(); const failed = await db.collection("failed") - .find({}).sort({ failed_at: -1 }).toArray(); + .find({}) + .sort({ failed_at: -1 }) + .toArray(); res.render("status", { title: "Queue Status", queued, + processing, finished: done, failed }); }; + diff --git a/queue_worker.js b/queue_worker.js index 99ba740..fd2fbd6 100644 --- a/queue_worker.js +++ b/queue_worker.js @@ -17,45 +17,52 @@ let queueCol, doneCol, failedCol; // ======================== // RUN A JOB // ======================== -async function runJob(job) { - const venvPython = "/home/pm2/Proxer-Downloader/.venv/bin/python"; +function runJob(job) { + return new Promise((resolve) => { + const venvPython = "F:/Nextcloud/DeSq-Gaming/Documents/Coding/Proxer-Downloader-v2/Proxer-Downloader/.venv/Scripts/python"; - const cleanName = job.filename.replace(".mp4", ""); - const safeToken = token.replace(/^"+|"+$/g, ''); // strip extra quotes - const command = `${venvPython} ${scriptPath} -u "${url}" -f "${cleanName}" -t "${safeToken}" -o "${OUTPUT_DIR}"`; + const cleanName = job.filename.replace(".mp4", ""); + const safeToken = job.token.replace(/^"+|"+$/g, ''); + const scriptPath = 'scripts/proxer-dl-video.py' + const command = `${venvPython} ${scriptPath} -u "${job.url}" -f "${cleanName}" -t "${safeToken}" -o "${OUTPUT_DIR}"`; + console.log("Running:", command); - console.log("Running:", command); + exec(command, async (error, stdout, stderr) => { + const outputLog = `${stdout}\n${stderr}`.trim(); - exec(command, async (error, stdout, stderr) => { - const outputLog = `${stdout}\n${stderr}`.trim(); - - if (error) { - console.error(`FAILED: ${cleanName}`); - await failedCol.insertOne({ - filename: job.filename, - url: job.url, - failed_at: new Date(), - output_log: outputLog, - return_code: error.code, - }); - - await queueCol.deleteOne({ _id: job._id }); - } else { - console.log(`SUCCESS: ${cleanName}`); - await doneCol.insertOne({ - filename: job.filename, - url: job.url, - finished_at: new Date(), - output_log: outputLog, - result: "success", - }); - - await queueCol.deleteOne({ _id: job._id }); - } + try { + if (error) { + console.error(`FAILED: ${cleanName}`); + await failedCol.insertOne({ + filename: job.filename, + url: job.url, + failed_at: new Date(), + output_log: outputLog, + return_code: error.code, + }); + } else { + console.log(`SUCCESS: ${cleanName}`); + await doneCol.insertOne({ + filename: job.filename, + url: job.url, + finished_at: new Date(), + output_log: outputLog, + result: "success", + }); + } + // Remove from queue in both cases + await queueCol.deleteOne({ _id: job._id }); + } catch (dbErr) { + console.error("DB error:", dbErr); + } finally { + resolve(); // resolve promise when done + } + }); }); } + // ======================== // MAIN LOOP // ======================== @@ -64,24 +71,36 @@ async function main() { try { await client.connect(); - const db = client.db(DB_NAME); + const db = client.db(DB_NAME); queueCol = db.collection("queue"); doneCol = db.collection("done"); failedCol = db.collection("failed"); while (true) { const job = await queueCol.findOneAndUpdate( - {}, - { $set: { processing: true } }, - { sort: { created_at: 1 }, returnDocument: "after" } + { + // Only pick jobs NOT being processed + $or: [ + { processing: { $exists: false } }, + { processing: false } + ] + }, + { + // Atomically claim job + $set: { processing: true, started_at: new Date() } + }, + { + sort: { created_at: 1 }, + returnDocument: "after" + } ); - if (job && job.value) { - await runJob(job.value); + if (job && job.token) { + await runJob(job); } else { - // Queue empty, wait 1 second - await new Promise((resolve) => setTimeout(resolve, 1000)); + // No available job, wait a bit + await new Promise(resolve => setTimeout(resolve, 1000)); } } } catch (err) { @@ -90,3 +109,4 @@ async function main() { } main(); + diff --git a/scripts/lib/__pycache__/proxer_utils.cpython-311.pyc b/scripts/lib/__pycache__/proxer_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a67a2c51e289c8cacd2e9e2c0e3d7372e901c686 GIT binary patch literal 6770 zcmbtYZ)_V!cAw?$lFPpqCE1cC*ICJyY{n9KagRmzyEsqe-9DzUzn)}cP;Vts~jPp z5tYP=%BhYt7v~`6(~b-u=Q%7B(n3aziy3F!nQ_HktV~Qx8F$>x5eLz@TkK!3KS+D) zf1o-axb8U!`2t=$VC{E^Dt$^+x5nS&K?koL;y$MHfX=J=+jIe@^MTH<1=@6nm@WXi zL;G|cYKIn7gIcE+)PjqSqxC-{DwHfb)viy4c$eA@bucfehaums_NzTm(hKiV)ToX{ zN$vYoj2~7V*GTACQT50W(y4_=p5|6HnkX2lv>wji^)N+L#(c`Si&dyX@5+lgD(gwA zGC4YW#kW8f8mT4_B=;h=R%w%#Il7|T1cOehfZg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TenhOh2hPoZtLU>r92kTd%y;VB2sR|4lv>3p5TrXcYLiFg7Vsjcp^ z`*_8Dyh@y6X#3=@x2H-(cj(#CfnOZkUVb_}`DA$VQPCWpEDz6DhUd+NtoiXL<%Lhc z|DSPOaX{2}6^{WR;TQn2N*w-SCN{<0u3oSyIK124``Oi>UEM0!Ub@*m^leqdY7+4W z|NiPvuWqhZdQO#nrz^hGrtfss54JFanD`1!`v%2c*+D5J<^yW|p@WFNPiM{G+3mX^ z;3*5QSA^Hi`lF-2@|Z;Z7X#$WfahX_|FXC9;;a0ZuZocVH%D}MW{m&sm@qT$`t2kK z5_a81Xc9VN-v?fUv?XY8KTC0E;+c)z9_tio)ZQOR#g;D#o{ka5^I{=o?+NdMqNkFV za@oZcEc`2Tmp@?lo0hwA^=#iS;`N(-yyRiaS)zgW2kb0I(J5l>G&>b*dd zPzBaA(SHRJPF5UObqJhLB`AD^JG36a-!3_9wm!RL%zXK?O9sr=2et^;z3!@zuB}tQ z7%?O7nPj$1W-DYC5>=YEceLPvGhTL-Dv(loW7kp literal 0 HcmV?d00001 diff --git a/scripts/lib/__pycache__/proxer_utils.cpython-313.pyc b/scripts/lib/__pycache__/proxer_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b14dff2aaebb825474f92f99f1ffafebdbc4453 GIT binary patch literal 5985 zcmb_gOK=;>dG5gsfWealNr^A5G^Cc2P~t-psa**a#U%ykK~dBOBiO1CS$GHxKEhx>EZe1|D*68& zJV-7#uG&hY(2u_#^LO|EfBkj84u$*#!oOS^EB<#2A^(AedhpdUuX{K`eoSOSiOk8a z+Z^Q}?;#%wv|a9idXxzA5hm%7d*q`a>x6$7*2%6hQSQdN4>@|I;EMKE z(*9C$VPu)=D=N*D&0@(IUVh~FPf3_BnvW!?rV4!|<#j3obu2n4}5pI-xF^qrB{*g3MF5EKrZ^re4`YMcGSz1u^Qg#aTrwl;H!fTA^d5 z3zcT`X48{OwOYgW6jYikFR;|WRMiTs3@Ma9g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Qcwh4_p?ISb^afdfs_lM-S-a;QxTPylF`Fa%e7fyi#$^SiAn*J1vj66#*XPy-!{ zg%oiv;*7YVP6tAhxHUZvC>(oC*xxkS7_%vtMcH=|4F^Kw`=0p*?E(rJsMouY%6S^I z2h*6xn+FSrKP-SA2&V@^ikE|zx%=56IEr9}LYMh=aubdr&6o1kN6&#ycY;taCh_)l zAf$YCT_th{?koW!k-NR$(AJ&oInW)7&Hg~3;a8udMCS2=!9wzQJ=aX(DI}cY_M(|Y z3OtZY(A5bIa@nM{UniIResbAI21#S)U{QIOL{7k*Br2!-PDL zo;vj`6d%Af3%MwJ%_tfOdU$aG_QW0_qy>dG$!N_7_7PD8IvldjJ{#^4limj>L3V{A zMq2C7B|y6Nc42N5lkT$T52dv47d zJVw>2nfoEdGJ>(~E$M{BMYi79LIR-DIF{2Tk2nN}1XsFmwlUSyF8`o2Y>}aFFc<>zju#Pd|Vb--Ev~3YNzp zzU>Imu+DBv==g(&h@qF4#y1nc@LP%0)}_>%+d6vI>OB3luiAOmY8`x9{-Slvn*ZMR ze7-uLw+aup=2srOksD6nvGDMTS#2NOe=xl4>{-9G-Fvp$dv?2bq}n@ToqO+D-&SvY zt26O9xa%kW@Z;io$Ctk2Pu~9bKgJVPggrn ze;GXU#}M(K*li{5;16g2X4Yyy_2ki$kF3arUkjs6syM-pn0Gh14a4dk-wI!`#4GHG znRxR@5&Hkycl?ckRDE+Y-a?-97vm%R^DE~e{=CH>ALKvp4#!XPpPzPPe#9T2@PY}F z=uzi+=DX0*7F2kaqiEkqCv5i*ytUZk73Y2LDqVyoU=_sp zIYhvaIqoZ$zzMH|glqW?Ir3XFRwZM`*+nB$C`FGdGG5_w4c$~YuZtM_9HjZokUVvgjVvoY8~Xza*_+G%0;x~AdH?_b literal 0 HcmV?d00001 diff --git a/scripts/lib/__pycache__/proxer_utils.cpython-38.pyc b/scripts/lib/__pycache__/proxer_utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0161dd22a9d71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}d=XjOtU|)0s!AI$MJa?yc+aiU66t2=(b_ zLY+pg2R2X__0_7y0lE#{^%e2Zh~s1e8#W?@s3_1k2Fi~J`lx#fy@_Yg3*xd2%n%=6 z2O;Q-g^TTU=6mh#XmkB1`$zk}*1B-HHI;9r3%e0P;^x1 z(7)MfB}qFqahSgJF!lD)nepAB0LG$(vG6E1FJLS_;qXYHTZ`k1X>^btUwlJ3xQIdK zVt%w-HXWl}_7%RvGT}@lHg+$%fKFpqlDmLUmGcJl6yhsC_Vj>ZB96*fcr_)V}#xC>iM=oyoMT literal 0 HcmV?d00001 diff --git a/scripts/lib/__pycache__/script_utils.cpython-38.pyc b/scripts/lib/__pycache__/script_utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..163e0cfa28dff8fa9ef316cd2db587d124840b95 GIT binary patch literal 1367 zcmb7@&2G~`5XX0I$4S$)6sUko1?>f-NChM=NENiG4HBoSQU!%5B67Xk){3)h?XGER zg-g@703@nNVWo#2Ajf=)98^6WGK*W%vWc>_!BTZTc zVvyLardNhqL`F%x+g!_-V!~wM9{*|+F7p74g?}27Z{&wJqLf%VB9w3sI`s>-tD`Iv z+EukK6Iv@>+{TjZD6xm*z$(M~l}snnY7f5Nq#CRJCOU-M`F3lyvn2*LPF2o3 z?^IuOS}M-_LR!<=R6LOfoo%fKP_w0uWU3-AbZ1=Jbb#4pf5EJroj}A!P)h?c65`EM zU4uI|V^vQ`jp1t`uscj~AUd!qR)^##!1zVKQcH&*^b#3??NPJhe1Gce7uGwWG91!f zvO{)>Tn>o!dUgGQ0z7~SV}UR~5$Sy-yaF)8Vjcb~7RCs}Tt_UCS#DV*Ig1ZP+%qh( zhJA_BgoErWpfCE#KIFOJIeo2ByfZY#qbLXF;}69uPdSsyvOU4FNE^Yonn77H84OVA zr$Ux9ZwIl+a9So<^bCBZJp(D-F&~u2X{4*LD;Hf)-Dx}Hqy>0l=D`rpqjkz?=+!BZ zz6B8=T@zVi6c^?nusNg`8y05GdVt(V! zV8`GAdIg|=onqWoe`jU{LL01jhkn zoKz?t-zarmpUD(}MAb4#69WqMqpbAt#5AzZ92%rNl?t)9LzGHnV~LztPN(}fbefi4 zhIh;zFeud`ZP0)&&>9U str: """ - Extracts the embed URL from a Proxer episode page using iframe parsing. + Extracts the embed URL from a Proxer episode page. :param episode_url: URL of the Proxer episode page :param auth_cookie: Tuple containing (cookie_name, cookie_value) @@ -43,48 +43,32 @@ def get_embed_url(episode_url: str, auth_cookie: tuple[str, str]) -> str: :raises NotFoundError: If embed URL is not found :raises NetworkError: If a request fails """ - import re - from requests import get, RequestException - - HEADERS = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' - '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' - } - - # Strip URL fragment - episode_url = episode_url.split("#")[0] - - cookies = {auth_cookie[0]: auth_cookie[1], 'stream_choose': 'proxer-stream'} + SEARCH_TOKEN = '"code":"' + SEARCH_SERVER = "stream-service.proxer.me" + HEADERS = {'User-Agent': 'Mozilla/5.0'} try: - logging.info(f"[DEBUG] Fetching episode URL: {episode_url} with cookies: {cookies}") - response = get(episode_url, headers=HEADERS, cookies=cookies, timeout=15) + response = get(episode_url, cookies={auth_cookie[0]: auth_cookie[1], 'stream_choose': 'proxer-stream'}, headers=HEADERS) response.raise_for_status() - logging.info(f"[DEBUG] HTTP status: {response.status_code}") - content = response.text - logging.debug(f"[DEBUG] Page snippet: {content[:500].replace(chr(10), ' ')}") - - # Optional: dump full page to file for debugging - with open("/tmp/proxer_debug.html", "w", encoding="utf-8") as f: - f.write(content) - except RequestException as e: raise NetworkError(f"Failed to fetch episode page: {e}") - # Extract iframe src - match = re.search(r']+src="([^"]+)"', content) - if match: - embed_url = match.group(1) - logging.info(f"[DEBUG] Found embed URL: {embed_url}") - return embed_url - else: - raise NotFoundError("Embed code not found in page content. Check /tmp/proxer_debug.html for details.") + # Extract the embed code + code_index = content.find(SEARCH_TOKEN) + len(SEARCH_TOKEN) + if code_index < len(SEARCH_TOKEN): + raise NotFoundError("Embed code not found in page content.") + + code : str = content[code_index:].partition('"')[0] + + # Detect the correct streaming service + host : str = "stream-service" if SEARCH_SERVER in content else "stream" + return f"https://{host}.proxer.me/embed-{code}.html" def get_mp4_url(embed_url: str) -> str: """ - Extracts the direct MP4 URL from an embed page with enhanced logging. + Extracts the direct MP4 URL from an embed page. :param embed_url: URL of the Proxer embed player :returns: Direct MP4 URL @@ -92,33 +76,26 @@ def get_mp4_url(embed_url: str) -> str: :raises NetworkError: If a request fails """ SEARCH_TOKEN = 'video/mp4" src="' - HEADERS = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' - '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' - } + HEADERS = {'User-Agent': 'Mozilla/5.0'} try: - logging.info(f"[DEBUG] Fetching embed URL: {embed_url}") - response = get(embed_url, headers=HEADERS, timeout=15) + response = get(embed_url, headers=HEADERS) response.raise_for_status() - logging.info(f"[DEBUG] HTTP status: {response.status_code}") content = response.text - logging.debug(f"[DEBUG] Embed snippet: {content[:500].replace(chr(10), ' ')}") except RequestException as e: raise NetworkError(f"Failed to fetch embed page: {e}") + # Extract the MP4 URL link_index = content.find(SEARCH_TOKEN) + len(SEARCH_TOKEN) if link_index < len(SEARCH_TOKEN): raise NotFoundError("MP4 URL not found in embed page.") - mp4_url = content[link_index:].partition('"')[0] - logging.info(f"[DEBUG] Found MP4 URL: {mp4_url}") - return mp4_url + return content[link_index:].partition('"')[0] def download_mp4(mp4_url: str, save_path: str, label: str = "") -> None: """ - Downloads an MP4 file from a given URL with enhanced logging. + Downloads an MP4 file from a given URL and displays a progress bar. :param mp4_url: URL of the MP4 file :param save_path: Path to save the downloaded file @@ -128,25 +105,21 @@ def download_mp4(mp4_url: str, save_path: str, label: str = "") -> None: CHUNK_SIZE = 255 MAX_LABEL_LENGTH = 32 + # Adjust label for progress bar if label: label = label[:MAX_LABEL_LENGTH - 3] + "..." if len(label) > MAX_LABEL_LENGTH else label.ljust(MAX_LABEL_LENGTH) - logging.info(f"[DEBUG] Starting download: {mp4_url} -> {save_path}") - try: - response = get(mp4_url, stream=True, timeout=30) + response = get(mp4_url, stream=True) response.raise_for_status() total_length = int(response.headers.get('content-length', 0)) except RequestException as e: raise NetworkError(f"Failed to start download: {e}") + # Download file with progress bar with open(save_path, "wb") as file: if total_length: - for chunk in progress.bar( - response.iter_content(chunk_size=CHUNK_SIZE), - expected_size=total_length / CHUNK_SIZE, - label=label - ): + for chunk in progress.bar(response.iter_content(chunk_size=CHUNK_SIZE), expected_size=total_length / CHUNK_SIZE, label=label): if chunk: file.write(chunk) else: diff --git a/scripts/proxer-dl.py b/scripts/proxer-dl.py deleted file mode 100644 index 7111461..0000000 --- a/scripts/proxer-dl.py +++ /dev/null @@ -1,59 +0,0 @@ -import sys -import argparse -from time import sleep -from lib.proxer_utils import get_embed_url, get_mp4_url, download_mp4 - -def download_series(serie_id, pretty_name, episode_range, language, auth_token, output_dir): - """ - Downloads all episodes in a specified range of a series. - If the range is 'x-x', only a single episode is downloaded. - """ - start, end = map(int, episode_range.split("-")) - for episode_number in range(start, end + 1): - episode_url = f"https://proxer.me/watch/{serie_id}/{episode_number}/{language}" - try: - print(f"Fetching embed URL for episode {episode_number} for {episode_url}...") - embed_url = get_embed_url(episode_url, auth_token) - print(f"Embed URL fetched for episode {episode_number}: {embed_url}") - - print(f"Fetching MP4 URL for episode {episode_number}...") - mp4_url = get_mp4_url(embed_url) - print(f"MP4 URL fetched for episode {episode_number}: {mp4_url}") - - # Prepare the output file path - output_file = f"{output_dir}/{pretty_name}_Episode_{episode_number}_{language}.mp4" - - # Download the episode - print(f"Downloading episode {episode_number}...") - download_mp4(mp4_url, output_file, label=f"Episode {episode_number} ({language})") - print(f"Episode {episode_number} downloaded successfully!") - - except Exception as e: - print(f"Error downloading episode {episode_number}: {e}") - - # Optional: Sleep between downloads to avoid being rate-limited - sleep(1) - -def parse_args(): - """Parse command-line arguments""" - parser = argparse.ArgumentParser(description="Download a series or a single episode from Proxer.me") - parser.add_argument('-i', '--id', required=True, type=str, help="The series ID on Proxer.me") - parser.add_argument('-n', '--name', required=True, type=str, help="The pretty name of the series") - parser.add_argument('-e', '--episodes', required=True, type=str, help="Episode range (start-end), e.g. 1-10 or 5-5 for a single episode") - parser.add_argument('-l', '--language', required=True, - choices=['engsub', 'engdub', 'gersub', 'gerdub'], - help="Language of the subtitles/audio") - parser.add_argument('-t', '--token', required=True, type=str, help="Proxer authentication token (cookie)") - parser.add_argument('-o', '--output', required=True, type=str, help="Directory to store downloaded videos") - - return parser.parse_args() - -if __name__ == "__main__": - # Parse command-line arguments - args = parse_args() - - # Assuming the Proxer authentication token comes as a cookie string (name=value) - auth_token = tuple(args.token.split("=")) - - # Call the function to download episodes (single or multiple) - download_series(args.id, args.name, args.episodes, args.language, auth_token, args.output) diff --git a/views/status.ejs b/views/status.ejs index f6119b2..a0e4612 100644 --- a/views/status.ejs +++ b/views/status.ejs @@ -5,7 +5,7 @@ -
+

Queued

    @@ -18,7 +18,41 @@ <% }) %> <% if (queued.length === 0) { %> -
  • No pending downloads
  • +
  • No queued jobs
  • + <% } %> + +
+
+ + + + +
+

Processing

+
    + + <% processing.forEach(job => { %> +
  • + <%= job.filename %> + +
    + <%= job.url %>
    + Started: <%= new Date(job.created_at).toLocaleString() %> + + <% if (job.output_log) { %> +
    + Live Log +
    +<%= job.output_log %>
    +              
    +
    + <% } %> + +
  • + <% }) %> + + <% if (processing.length === 0) { %> +
  • Nothing processing
  • <% } %>
@@ -27,7 +61,7 @@ -
+

Done

    @@ -49,7 +83,7 @@ <% }) %> <% if (finished.length === 0) { %> -
  • No completed downloads
  • +
  • No completed jobs
  • <% } %>
@@ -58,11 +92,11 @@ -
+

Failed

    - <% failed && failed.forEach(job => { %> + <% failed.forEach(job => { %>
  • <%= job.filename %>
    <%= new Date(job.failed_at).toLocaleString() %>
    @@ -71,7 +105,7 @@
    Show Error Log
    -          <%= job.output_log %>
    +<%= job.output_log %>
                   
    <% } %> @@ -79,8 +113,8 @@
  • <% }) %> - <% if (!failed || failed.length === 0) { %> -
  • No failed jobs
  • + <% if (failed.length === 0) { %> +
  • No failed jobs
  • <% } %>