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 0000000..a67a2c5 Binary files /dev/null and b/scripts/lib/__pycache__/proxer_utils.cpython-311.pyc differ 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 0000000..4b14dff Binary files /dev/null and b/scripts/lib/__pycache__/proxer_utils.cpython-313.pyc differ 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 0000000..c0161dd Binary files /dev/null and b/scripts/lib/__pycache__/proxer_utils.cpython-38.pyc differ diff --git a/scripts/lib/__pycache__/script_utils.cpython-313.pyc b/scripts/lib/__pycache__/script_utils.cpython-313.pyc new file mode 100644 index 0000000..0f76d97 Binary files /dev/null and b/scripts/lib/__pycache__/script_utils.cpython-313.pyc differ 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 0000000..163e0cf Binary files /dev/null and b/scripts/lib/__pycache__/script_utils.cpython-38.pyc differ diff --git a/scripts/lib/proxer_utils.py b/scripts/lib/proxer_utils.py index 66768b2..3973325 100644 --- a/scripts/lib/proxer_utils.py +++ b/scripts/lib/proxer_utils.py @@ -35,7 +35,7 @@ class NetworkError(ProxerError): def get_embed_url(episode_url: str, auth_cookie: tuple[str, str]) -> 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
  • <% } %>