20 Commits

Author SHA1 Message Date
Alex
a002af9bf2 Merge pull request #864 from alexta69/dependabot/github_actions/github-actions-151e9c363d
Bump the github-actions group with 5 updates
2026-01-02 08:21:27 +02:00
dependabot[bot]
37aaa29efb Bump the github-actions group with 5 updates
Bumps the github-actions group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [actions/checkout](https://github.com/actions/checkout) | `4` | `6` |
| [docker/build-push-action](https://github.com/docker/build-push-action) | `5` | `6` |
| [softprops/action-gh-release](https://github.com/softprops/action-gh-release) | `1` | `2` |
| [actions/setup-python](https://github.com/actions/setup-python) | `4` | `6` |
| [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) | `6` | `7` |


Updates `actions/checkout` from 4 to 6
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

Updates `docker/build-push-action` from 5 to 6
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v5...v6)

Updates `softprops/action-gh-release` from 1 to 2
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

Updates `actions/setup-python` from 4 to 6
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v4...v6)

Updates `astral-sh/setup-uv` from 6 to 7
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: docker/build-push-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: softprops/action-gh-release
  dependency-version: '2'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/setup-python
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: astral-sh/setup-uv
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-02 06:15:39 +00:00
Alex
d10f2a0358 Merge pull request #863 from cclauss/patch-1
Keep GitHub Actions up to date with GitHub's Dependabot
2026-01-02 08:14:46 +02:00
Alex
c7008763d7 Merge pull request #861 from ikatkov/split-chapters-in-ui
Add video/audio chapter splitting with UI controls
2026-01-01 23:22:57 +02:00
Christian Clauss
351058e9f4 Keep GitHub Actions up to date with GitHub's Dependabot
* [Keeping your software supply chain secure with Dependabot](https://docs.github.com/en/code-security/dependabot)
* [Keeping your actions up to date with Dependabot](https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot)
* [Configuration options for the `dependabot.yml` file - package-ecosystem](https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem)

To see all GitHub Actions dependencies, run the command:
% `git grep 'uses: ' .github/workflows/`
2025-12-31 13:05:26 +01:00
ikatkov
df87a1aa2b Merge branch 'alexta69:master' into split-chapters-in-ui 2025-12-31 00:16:52 -08:00
Igor Katkov
02480afddf feat: Use OUTPUT_TEMPLATE_CHAPTER default setting 2025-12-31 00:13:55 -08:00
Igor Katkov
d51f2ce628 feat: Undo bogus formatting changes 2025-12-30 23:33:01 -08:00
Igor Katkov
962929d42d feat: Implement chapter splitting functionality with UI controls, yt-dlp integration, and chapter file tracking. 2025-12-30 22:07:49 -08:00
Alex
179452b4f4 Merge pull request #858 from ikatkov/master
Improves logging, helpful when debugging yt-dlp options
2025-12-30 22:40:16 +02:00
ikatkov
4fce74d1ed Merge pull request #1 from ikatkov/logging-fix
Logging fix
2025-12-30 10:22:31 -08:00
Igor Katkov
09a2e95515 fix: Root logger aligns with config.LOGLEVEL 2025-12-30 10:19:30 -08:00
Igor Katkov
d947876a71 fix: pass DEBUG log level to ytdl 2025-12-30 10:01:43 -08:00
Igor Katkov
6ba681a3cd fix: Moved code to respect loggin level in main.py 2025-12-30 08:45:54 -08:00
Alex
1f8fa7744e Merge pull request #857 from mercury233/patch-1
fix completed result tooltip
2025-12-27 12:17:40 +02:00
mercury233
092765535f fix completed result tooltip 2025-12-27 10:48:57 +08:00
Alex
90299b227e Merge pull request #855 from alemonmk/suppress-dl-progress-logs
Suppress download progress update in logs
2025-12-26 17:43:36 +02:00
Alex
6445517751 Merge pull request #848 from alemonmk/fix-crlf
Convert files to LF line ending
2025-12-26 14:21:17 +02:00
Lemon Lam
dae710a339 Suppress download progress update
...by sending them to debug
2025-12-26 19:42:09 +08:00
Lemon Lam
318f4f9f21 Convert to LF 2025-12-26 19:30:26 +08:00
12 changed files with 1645 additions and 1461 deletions

13
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,13 @@
# Keep GitHub Actions up to date with GitHub's Dependabot...
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot
# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference#package-ecosystem
version: 2
updates:
- package-ecosystem: github-actions
directory: /
groups:
github-actions:
patterns:
- "*" # Group all Actions updates into a single larger pull request
schedule:
interval: weekly

View File

@@ -15,7 +15,7 @@ jobs:
run: echo "::set-output name=date::$(date +'%Y.%m.%d')" run: echo "::set-output name=date::$(date +'%Y.%m.%d')"
- -
name: Checkout name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
- -
name: Set up QEMU name: Set up QEMU
uses: docker/setup-qemu-action@v3 uses: docker/setup-qemu-action@v3
@@ -37,7 +37,7 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- -
name: Build and push name: Build and push
uses: docker/build-push-action@v5 uses: docker/build-push-action@v6
with: with:
context: . context: .
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
@@ -74,7 +74,7 @@ jobs:
id: date id: date
run: echo "date=$(date +'%Y.%m.%d')" >> $GITHUB_OUTPUT run: echo "date=$(date +'%Y.%m.%d')" >> $GITHUB_OUTPUT
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get commits since last release - name: Get commits since last release
@@ -167,7 +167,7 @@ jobs:
git push origin ":refs/tags/$TAG_NAME" || true git push origin ":refs/tags/$TAG_NAME" || true
fi fi
- name: Create GitHub Release - name: Create GitHub Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v2
with: with:
tag_name: ${{ steps.date.outputs.date }} tag_name: ${{ steps.date.outputs.date }}
name: Release ${{ steps.date.outputs.date }} name: Release ${{ steps.date.outputs.date }}

View File

@@ -10,17 +10,17 @@ jobs:
steps: steps:
- -
name: Checkout name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v6
with: with:
token: ${{ secrets.AUTOUPDATE_PAT }} token: ${{ secrets.AUTOUPDATE_PAT }}
- -
name: Set up Python name: Set up Python
uses: actions/setup-python@v4 uses: actions/setup-python@v6
with: with:
python-version: '3.13' python-version: '3.13'
- -
name: Install uv name: Install uv
uses: astral-sh/setup-uv@v6 uses: astral-sh/setup-uv@v7
- -
name: Update yt-dlp name: Update yt-dlp
run: | run: |

View File

@@ -1,43 +1,43 @@
FROM node:lts-alpine AS builder FROM node:lts-alpine AS builder
WORKDIR /metube WORKDIR /metube
COPY ui ./ COPY ui ./
RUN corepack enable && corepack prepare pnpm --activate RUN corepack enable && corepack prepare pnpm --activate
RUN pnpm install && pnpm run build RUN pnpm install && pnpm run build
FROM python:3.13-alpine FROM python:3.13-alpine
WORKDIR /app WORKDIR /app
COPY pyproject.toml uv.lock docker-entrypoint.sh ./ COPY pyproject.toml uv.lock docker-entrypoint.sh ./
# Use sed to strip carriage-return characters from the entrypoint script (in case building on Windows) # Use sed to strip carriage-return characters from the entrypoint script (in case building on Windows)
# Install dependencies # Install dependencies
RUN sed -i 's/\r$//g' docker-entrypoint.sh && \ RUN sed -i 's/\r$//g' docker-entrypoint.sh && \
chmod +x docker-entrypoint.sh && \ chmod +x docker-entrypoint.sh && \
apk add --update ffmpeg aria2 coreutils shadow su-exec curl tini deno && \ apk add --update ffmpeg aria2 coreutils shadow su-exec curl tini deno && \
apk add --update --virtual .build-deps gcc g++ musl-dev uv && \ apk add --update --virtual .build-deps gcc g++ musl-dev uv && \
UV_PROJECT_ENVIRONMENT=/usr/local uv sync --frozen --no-dev --compile-bytecode && \ UV_PROJECT_ENVIRONMENT=/usr/local uv sync --frozen --no-dev --compile-bytecode && \
apk del .build-deps && \ apk del .build-deps && \
rm -rf /var/cache/apk/* && \ rm -rf /var/cache/apk/* && \
mkdir /.cache && chmod 777 /.cache mkdir /.cache && chmod 777 /.cache
COPY app ./app COPY app ./app
COPY --from=builder /metube/dist/metube ./ui/dist/metube COPY --from=builder /metube/dist/metube ./ui/dist/metube
ENV UID=1000 ENV UID=1000
ENV GID=1000 ENV GID=1000
ENV UMASK=022 ENV UMASK=022
ENV DOWNLOAD_DIR /downloads ENV DOWNLOAD_DIR /downloads
ENV STATE_DIR /downloads/.metube ENV STATE_DIR /downloads/.metube
ENV TEMP_DIR /downloads ENV TEMP_DIR /downloads
VOLUME /downloads VOLUME /downloads
EXPOSE 8081 EXPOSE 8081
# Add build-time argument for version # Add build-time argument for version
ARG VERSION=dev ARG VERSION=dev
ENV METUBE_VERSION=$VERSION ENV METUBE_VERSION=$VERSION
ENTRYPOINT ["/sbin/tini", "-g", "--", "./docker-entrypoint.sh"] ENTRYPOINT ["/sbin/tini", "-g", "--", "./docker-entrypoint.sh"]

582
README.md
View File

@@ -1,291 +1,291 @@
# MeTube # MeTube
![Build Status](https://github.com/alexta69/metube/actions/workflows/main.yml/badge.svg) ![Build Status](https://github.com/alexta69/metube/actions/workflows/main.yml/badge.svg)
![Docker Pulls](https://img.shields.io/docker/pulls/alexta69/metube.svg) ![Docker Pulls](https://img.shields.io/docker/pulls/alexta69/metube.svg)
Web GUI for youtube-dl (using the [yt-dlp](https://github.com/yt-dlp/yt-dlp) fork) with playlist support. Allows you to download videos from YouTube and [dozens of other sites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md). Web GUI for youtube-dl (using the [yt-dlp](https://github.com/yt-dlp/yt-dlp) fork) with playlist support. Allows you to download videos from YouTube and [dozens of other sites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md).
![screenshot1](https://github.com/alexta69/metube/raw/master/screenshot.gif) ![screenshot1](https://github.com/alexta69/metube/raw/master/screenshot.gif)
## 🐳 Run using Docker ## 🐳 Run using Docker
```bash ```bash
docker run -d -p 8081:8081 -v /path/to/downloads:/downloads ghcr.io/alexta69/metube docker run -d -p 8081:8081 -v /path/to/downloads:/downloads ghcr.io/alexta69/metube
``` ```
## 🐳 Run using docker-compose ## 🐳 Run using docker-compose
```yaml ```yaml
services: services:
metube: metube:
image: ghcr.io/alexta69/metube image: ghcr.io/alexta69/metube
container_name: metube container_name: metube
restart: unless-stopped restart: unless-stopped
ports: ports:
- "8081:8081" - "8081:8081"
volumes: volumes:
- /path/to/downloads:/downloads - /path/to/downloads:/downloads
``` ```
## ⚙️ Configuration via environment variables ## ⚙️ Configuration via environment variables
Certain values can be set via environment variables, using the `-e` parameter on the docker command line, or the `environment:` section in docker-compose. Certain values can be set via environment variables, using the `-e` parameter on the docker command line, or the `environment:` section in docker-compose.
### ⬇️ Download Behavior ### ⬇️ Download Behavior
* __DOWNLOAD_MODE__: This flag controls how downloads are scheduled and executed. Options are `sequential`, `concurrent`, and `limited`. Defaults to `limited`: * __DOWNLOAD_MODE__: This flag controls how downloads are scheduled and executed. Options are `sequential`, `concurrent`, and `limited`. Defaults to `limited`:
* `sequential`: Downloads are processed one at a time. A new download won't start until the previous one has finished. This mode is useful for conserving system resources or ensuring downloads occur in strict order. * `sequential`: Downloads are processed one at a time. A new download won't start until the previous one has finished. This mode is useful for conserving system resources or ensuring downloads occur in strict order.
* `concurrent`: Downloads are started immediately as they are added, with no built-in limit on how many run simultaneously. This mode may overwhelm your system if too many downloads start at once. * `concurrent`: Downloads are started immediately as they are added, with no built-in limit on how many run simultaneously. This mode may overwhelm your system if too many downloads start at once.
* `limited`: Downloads are started concurrently but are capped by a concurrency limit. In this mode, a semaphore is used so that at most a fixed number of downloads run at any given time. * `limited`: Downloads are started concurrently but are capped by a concurrency limit. In this mode, a semaphore is used so that at most a fixed number of downloads run at any given time.
* __MAX_CONCURRENT_DOWNLOADS__: This flag is used only when `DOWNLOAD_MODE` is set to `limited`. * __MAX_CONCURRENT_DOWNLOADS__: This flag is used only when `DOWNLOAD_MODE` is set to `limited`.
It specifies the maximum number of simultaneous downloads allowed. For example, if set to `5`, then at most five downloads will run concurrently, and any additional downloads will wait until one of the active downloads completes. Defaults to `3`. It specifies the maximum number of simultaneous downloads allowed. For example, if set to `5`, then at most five downloads will run concurrently, and any additional downloads will wait until one of the active downloads completes. Defaults to `3`.
* __DELETE_FILE_ON_TRASHCAN__: if `true`, downloaded files are deleted on the server, when they are trashed from the "Completed" section of the UI. Defaults to `false`. * __DELETE_FILE_ON_TRASHCAN__: if `true`, downloaded files are deleted on the server, when they are trashed from the "Completed" section of the UI. Defaults to `false`.
* __DEFAULT_OPTION_PLAYLIST_STRICT_MODE__: if `true`, the "Strict Playlist mode" switch will be enabled by default. In this mode the playlists will be downloaded only if the URL strictly points to a playlist. URLs to videos inside a playlist will be treated same as direct video URL. Defaults to `false` . * __DEFAULT_OPTION_PLAYLIST_STRICT_MODE__: if `true`, the "Strict Playlist mode" switch will be enabled by default. In this mode the playlists will be downloaded only if the URL strictly points to a playlist. URLs to videos inside a playlist will be treated same as direct video URL. Defaults to `false` .
* __DEFAULT_OPTION_PLAYLIST_ITEM_LIMIT__: Maximum number of playlist items that can be downloaded. Defaults to `0` (no limit). * __DEFAULT_OPTION_PLAYLIST_ITEM_LIMIT__: Maximum number of playlist items that can be downloaded. Defaults to `0` (no limit).
### 📁 Storage & Directories ### 📁 Storage & Directories
* __DOWNLOAD_DIR__: Path to where the downloads will be saved. Defaults to `/downloads` in the Docker image, and `.` otherwise. * __DOWNLOAD_DIR__: Path to where the downloads will be saved. Defaults to `/downloads` in the Docker image, and `.` otherwise.
* __AUDIO_DOWNLOAD_DIR__: Path to where audio-only downloads will be saved, if you wish to separate them from the video downloads. Defaults to the value of `DOWNLOAD_DIR`. * __AUDIO_DOWNLOAD_DIR__: Path to where audio-only downloads will be saved, if you wish to separate them from the video downloads. Defaults to the value of `DOWNLOAD_DIR`.
* __CUSTOM_DIRS__: Whether to enable downloading videos into custom directories within the __DOWNLOAD_DIR__ (or __AUDIO_DOWNLOAD_DIR__). When enabled, a dropdown appears next to the Add button to specify the download directory. Defaults to `true`. * __CUSTOM_DIRS__: Whether to enable downloading videos into custom directories within the __DOWNLOAD_DIR__ (or __AUDIO_DOWNLOAD_DIR__). When enabled, a dropdown appears next to the Add button to specify the download directory. Defaults to `true`.
* __CREATE_CUSTOM_DIRS__: Whether to support automatically creating directories within the __DOWNLOAD_DIR__ (or __AUDIO_DOWNLOAD_DIR__) if they do not exist. When enabled, the download directory selector supports free-text input, and the specified directory will be created recursively. Defaults to `true`. * __CREATE_CUSTOM_DIRS__: Whether to support automatically creating directories within the __DOWNLOAD_DIR__ (or __AUDIO_DOWNLOAD_DIR__) if they do not exist. When enabled, the download directory selector supports free-text input, and the specified directory will be created recursively. Defaults to `true`.
* __CUSTOM_DIRS_EXCLUDE_REGEX__: Regular expression to exclude some custom directories from the dropdown. Empty regex disables exclusion. Defaults to `(^|/)[.@].*$`, which means directories starting with `.` or `@`. * __CUSTOM_DIRS_EXCLUDE_REGEX__: Regular expression to exclude some custom directories from the dropdown. Empty regex disables exclusion. Defaults to `(^|/)[.@].*$`, which means directories starting with `.` or `@`.
* __DOWNLOAD_DIRS_INDEXABLE__: If `true`, the download directories (__DOWNLOAD_DIR__ and __AUDIO_DOWNLOAD_DIR__) are indexable on the web server. Defaults to `false`. * __DOWNLOAD_DIRS_INDEXABLE__: If `true`, the download directories (__DOWNLOAD_DIR__ and __AUDIO_DOWNLOAD_DIR__) are indexable on the web server. Defaults to `false`.
* __STATE_DIR__: Path to where the queue persistence files will be saved. Defaults to `/downloads/.metube` in the Docker image, and `.` otherwise. * __STATE_DIR__: Path to where the queue persistence files will be saved. Defaults to `/downloads/.metube` in the Docker image, and `.` otherwise.
* __TEMP_DIR__: Path where intermediary download files will be saved. Defaults to `/downloads` in the Docker image, and `.` otherwise. * __TEMP_DIR__: Path where intermediary download files will be saved. Defaults to `/downloads` in the Docker image, and `.` otherwise.
* Set this to an SSD or RAM filesystem (e.g., `tmpfs`) for better performance. * Set this to an SSD or RAM filesystem (e.g., `tmpfs`) for better performance.
* __Note__: Using a RAM filesystem may prevent downloads from being resumed. * __Note__: Using a RAM filesystem may prevent downloads from being resumed.
### 📝 File Naming & yt-dlp ### 📝 File Naming & yt-dlp
* __OUTPUT_TEMPLATE__: The template for the filenames of the downloaded videos, formatted according to [this spec](https://github.com/yt-dlp/yt-dlp/blob/master/README.md#output-template). Defaults to `%(title)s.%(ext)s`. * __OUTPUT_TEMPLATE__: The template for the filenames of the downloaded videos, formatted according to [this spec](https://github.com/yt-dlp/yt-dlp/blob/master/README.md#output-template). Defaults to `%(title)s.%(ext)s`.
* __OUTPUT_TEMPLATE_CHAPTER__: The template for the filenames of the downloaded videos when split into chapters via postprocessors. Defaults to `%(title)s - %(section_number)s %(section_title)s.%(ext)s`. * __OUTPUT_TEMPLATE_CHAPTER__: The template for the filenames of the downloaded videos when split into chapters via postprocessors. Defaults to `%(title)s - %(section_number)s %(section_title)s.%(ext)s`.
* __OUTPUT_TEMPLATE_PLAYLIST__: The template for the filenames of the downloaded videos when downloaded as a playlist. Defaults to `%(playlist_title)s/%(title)s.%(ext)s`. When empty, then `OUTPUT_TEMPLATE` is used. * __OUTPUT_TEMPLATE_PLAYLIST__: The template for the filenames of the downloaded videos when downloaded as a playlist. Defaults to `%(playlist_title)s/%(title)s.%(ext)s`. When empty, then `OUTPUT_TEMPLATE` is used.
* __YTDL_OPTIONS__: Additional options to pass to yt-dlp in JSON format. [See available options here](https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/YoutubeDL.py#L222). They roughly correspond to command-line options, though some do not have exact equivalents here. For example, `--recode-video` has to be specified via `postprocessors`. Also note that dashes are replaced with underscores. You may find [this script](https://github.com/yt-dlp/yt-dlp/blob/master/devscripts/cli_to_api.py) helpful for converting from command-line options to `YTDL_OPTIONS`. * __YTDL_OPTIONS__: Additional options to pass to yt-dlp in JSON format. [See available options here](https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/YoutubeDL.py#L222). They roughly correspond to command-line options, though some do not have exact equivalents here. For example, `--recode-video` has to be specified via `postprocessors`. Also note that dashes are replaced with underscores. You may find [this script](https://github.com/yt-dlp/yt-dlp/blob/master/devscripts/cli_to_api.py) helpful for converting from command-line options to `YTDL_OPTIONS`.
* __YTDL_OPTIONS_FILE__: A path to a JSON file that will be loaded and used for populating `YTDL_OPTIONS` above. Please note that if both `YTDL_OPTIONS_FILE` and `YTDL_OPTIONS` are specified, the options in `YTDL_OPTIONS` take precedence. The file will be monitored for changes and reloaded automatically when changes are detected. * __YTDL_OPTIONS_FILE__: A path to a JSON file that will be loaded and used for populating `YTDL_OPTIONS` above. Please note that if both `YTDL_OPTIONS_FILE` and `YTDL_OPTIONS` are specified, the options in `YTDL_OPTIONS` take precedence. The file will be monitored for changes and reloaded automatically when changes are detected.
### 🌐 Web Server & URLs ### 🌐 Web Server & URLs
* __URL_PREFIX__: Base path for the web server (for use when hosting behind a reverse proxy). Defaults to `/`. * __URL_PREFIX__: Base path for the web server (for use when hosting behind a reverse proxy). Defaults to `/`.
* __PUBLIC_HOST_URL__: Base URL for the download links shown in the UI for completed files. By default, MeTube serves them under its own URL. If your download directory is accessible on another URL and you want the download links to be based there, use this variable to set it. * __PUBLIC_HOST_URL__: Base URL for the download links shown in the UI for completed files. By default, MeTube serves them under its own URL. If your download directory is accessible on another URL and you want the download links to be based there, use this variable to set it.
* __PUBLIC_HOST_AUDIO_URL__: Same as PUBLIC_HOST_URL but for audio downloads. * __PUBLIC_HOST_AUDIO_URL__: Same as PUBLIC_HOST_URL but for audio downloads.
* __HTTPS__: Use `https` instead of `http` (__CERTFILE__ and __KEYFILE__ required). Defaults to `false`. * __HTTPS__: Use `https` instead of `http` (__CERTFILE__ and __KEYFILE__ required). Defaults to `false`.
* __CERTFILE__: HTTPS certificate file path. * __CERTFILE__: HTTPS certificate file path.
* __KEYFILE__: HTTPS key file path. * __KEYFILE__: HTTPS key file path.
* __ROBOTS_TXT__: A path to a `robots.txt` file mounted in the container. * __ROBOTS_TXT__: A path to a `robots.txt` file mounted in the container.
### 🏠 Basic Setup ### 🏠 Basic Setup
* __UID__: User under which MeTube will run. Defaults to `1000`. * __UID__: User under which MeTube will run. Defaults to `1000`.
* __GID__: Group under which MeTube will run. Defaults to `1000`. * __GID__: Group under which MeTube will run. Defaults to `1000`.
* __UMASK__: Umask value used by MeTube. Defaults to `022`. * __UMASK__: Umask value used by MeTube. Defaults to `022`.
* __DEFAULT_THEME__: Default theme to use for the UI, can be set to `light`, `dark`, or `auto`. Defaults to `auto`. * __DEFAULT_THEME__: Default theme to use for the UI, can be set to `light`, `dark`, or `auto`. Defaults to `auto`.
* __LOGLEVEL__: Log level, can be set to `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`, or `NONE`. Defaults to `INFO`. * __LOGLEVEL__: Log level, can be set to `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`, or `NONE`. Defaults to `INFO`.
* __ENABLE_ACCESSLOG__: Whether to enable access log. Defaults to `false`. * __ENABLE_ACCESSLOG__: Whether to enable access log. Defaults to `false`.
The project's Wiki contains examples of useful configurations contributed by users of MeTube: The project's Wiki contains examples of useful configurations contributed by users of MeTube:
* [YTDL_OPTIONS Cookbook](https://github.com/alexta69/metube/wiki/YTDL_OPTIONS-Cookbook) * [YTDL_OPTIONS Cookbook](https://github.com/alexta69/metube/wiki/YTDL_OPTIONS-Cookbook)
* [OUTPUT_TEMPLATE Cookbook](https://github.com/alexta69/metube/wiki/OUTPUT_TEMPLATE-Cookbook) * [OUTPUT_TEMPLATE Cookbook](https://github.com/alexta69/metube/wiki/OUTPUT_TEMPLATE-Cookbook)
## 🍪 Using browser cookies ## 🍪 Using browser cookies
In case you need to use your browser's cookies with MeTube, for example to download restricted or private videos: In case you need to use your browser's cookies with MeTube, for example to download restricted or private videos:
* Add the following to your docker-compose.yml: * Add the following to your docker-compose.yml:
```yaml ```yaml
volumes: volumes:
- /path/to/cookies:/cookies - /path/to/cookies:/cookies
environment: environment:
- YTDL_OPTIONS={"cookiefile":"/cookies/cookies.txt"} - YTDL_OPTIONS={"cookiefile":"/cookies/cookies.txt"}
``` ```
* Install in your browser an extension to extract cookies: * Install in your browser an extension to extract cookies:
* [Firefox](https://addons.mozilla.org/en-US/firefox/addon/export-cookies-txt/) * [Firefox](https://addons.mozilla.org/en-US/firefox/addon/export-cookies-txt/)
* [Chrome](https://chrome.google.com/webstore/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc) * [Chrome](https://chrome.google.com/webstore/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc)
* Extract the cookies you need with the extension and rename the file `cookies.txt` * Extract the cookies you need with the extension and rename the file `cookies.txt`
* Drop the file in the folder you configured in the docker-compose.yml above * Drop the file in the folder you configured in the docker-compose.yml above
* Restart the container * Restart the container
## 🔌 Browser extensions ## 🔌 Browser extensions
Browser extensions allow right-clicking videos and sending them directly to MeTube. Please note that if you're on an HTTPS page, your MeTube instance must be behind an HTTPS reverse proxy (see below) for the extensions to work. Browser extensions allow right-clicking videos and sending them directly to MeTube. Please note that if you're on an HTTPS page, your MeTube instance must be behind an HTTPS reverse proxy (see below) for the extensions to work.
__Chrome:__ contributed by [Rpsl](https://github.com/rpsl). You can install it from [Google Chrome Webstore](https://chrome.google.com/webstore/detail/metube-downloader/fbmkmdnlhacefjljljlbhkodfmfkijdh) or use developer mode and install [from sources](https://github.com/Rpsl/metube-browser-extension). __Chrome:__ contributed by [Rpsl](https://github.com/rpsl). You can install it from [Google Chrome Webstore](https://chrome.google.com/webstore/detail/metube-downloader/fbmkmdnlhacefjljljlbhkodfmfkijdh) or use developer mode and install [from sources](https://github.com/Rpsl/metube-browser-extension).
__Firefox:__ contributed by [nanocortex](https://github.com/nanocortex). You can install it from [Firefox Addons](https://addons.mozilla.org/en-US/firefox/addon/metube-downloader) or get sources from [here](https://github.com/nanocortex/metube-firefox-addon). __Firefox:__ contributed by [nanocortex](https://github.com/nanocortex). You can install it from [Firefox Addons](https://addons.mozilla.org/en-US/firefox/addon/metube-downloader) or get sources from [here](https://github.com/nanocortex/metube-firefox-addon).
## 📱 iOS Shortcut ## 📱 iOS Shortcut
[rithask](https://github.com/rithask) created an iOS shortcut to send URLs to MeTube from Safari. Enter the MeTube instance address when prompted which will be saved for later use. You can run the shortcut from Safaris share menu. The shortcut can be downloaded from [this iCloud link](https://www.icloud.com/shortcuts/66627a9f334c467baabdb2769763a1a6). [rithask](https://github.com/rithask) created an iOS shortcut to send URLs to MeTube from Safari. Enter the MeTube instance address when prompted which will be saved for later use. You can run the shortcut from Safaris share menu. The shortcut can be downloaded from [this iCloud link](https://www.icloud.com/shortcuts/66627a9f334c467baabdb2769763a1a6).
## 📱 iOS Compatibility ## 📱 iOS Compatibility
iOS has strict requirements for video files, requiring h264 or h265 video codec and aac audio codec in MP4 container. This can sometimes be a lower quality than the best quality available. To accommodate iOS requirements, when downloading a MP4 format you can choose "Best (iOS)" to get the best quality formats as compatible as possible with iOS requirements. iOS has strict requirements for video files, requiring h264 or h265 video codec and aac audio codec in MP4 container. This can sometimes be a lower quality than the best quality available. To accommodate iOS requirements, when downloading a MP4 format you can choose "Best (iOS)" to get the best quality formats as compatible as possible with iOS requirements.
To force all downloads to be converted to an iOS-compatible codec, insert this as an environment variable: To force all downloads to be converted to an iOS-compatible codec, insert this as an environment variable:
```yaml ```yaml
environment: environment:
- 'YTDL_OPTIONS={"format": "best", "exec": "ffmpeg -i %(filepath)q -c:v libx264 -c:a aac %(filepath)q.h264.mp4"}' - 'YTDL_OPTIONS={"format": "best", "exec": "ffmpeg -i %(filepath)q -c:v libx264 -c:a aac %(filepath)q.h264.mp4"}'
``` ```
## 🔖 Bookmarklet ## 🔖 Bookmarklet
[kushfest](https://github.com/kushfest) has created a Chrome bookmarklet for sending the currently open webpage to MeTube. Please note that if you're on an HTTPS page, your MeTube instance must be configured with `HTTPS` as `true` in the environment, or be behind an HTTPS reverse proxy (see below) for the bookmarklet to work. [kushfest](https://github.com/kushfest) has created a Chrome bookmarklet for sending the currently open webpage to MeTube. Please note that if you're on an HTTPS page, your MeTube instance must be configured with `HTTPS` as `true` in the environment, or be behind an HTTPS reverse proxy (see below) for the bookmarklet to work.
GitHub doesn't allow embedding JavaScript as a link, so the bookmarklet has to be created manually by copying the following code to a new bookmark you create on your bookmarks bar. Change the hostname in the URL below to point to your MeTube instance. GitHub doesn't allow embedding JavaScript as a link, so the bookmarklet has to be created manually by copying the following code to a new bookmark you create on your bookmarks bar. Change the hostname in the URL below to point to your MeTube instance.
```javascript ```javascript
javascript:!function(){xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.withCredentials=true;xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function(){if(xhr.status==200){alert("Sent to metube!")}else{alert("Send to metube failed. Check the javascript console for clues.")}}}(); javascript:!function(){xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.withCredentials=true;xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function(){if(xhr.status==200){alert("Sent to metube!")}else{alert("Send to metube failed. Check the javascript console for clues.")}}}();
``` ```
[shoonya75](https://github.com/shoonya75) has contributed a Firefox version: [shoonya75](https://github.com/shoonya75) has contributed a Firefox version:
```javascript ```javascript
javascript:(function(){xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function(){if(xhr.status==200){alert("Sent to metube!")}else{alert("Send to metube failed. Check the javascript console for clues.")}}})(); javascript:(function(){xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function(){if(xhr.status==200){alert("Sent to metube!")}else{alert("Send to metube failed. Check the javascript console for clues.")}}})();
``` ```
The above bookmarklets use `alert()` as a success/failure notification. The following will show a toast message instead: The above bookmarklets use `alert()` as a success/failure notification. The following will show a toast message instead:
Chrome: Chrome:
```javascript ```javascript
javascript:!function(){function notify(msg) {var sc = document.scrollingElement.scrollTop; var text = document.createElement('span');text.innerHTML=msg;var ts = text.style;ts.all = 'revert';ts.color = '#000';ts.fontFamily = 'Verdana, sans-serif';ts.fontSize = '15px';ts.backgroundColor = 'white';ts.padding = '15px';ts.border = '1px solid gainsboro';ts.boxShadow = '3px 3px 10px';ts.zIndex = '100';document.body.appendChild(text);ts.position = 'absolute'; ts.top = 50 + sc + 'px'; ts.left = (window.innerWidth / 2)-(text.offsetWidth / 2) + 'px'; setTimeout(function () { text.style.visibility = "hidden"; }, 1500);}xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function() { if(xhr.status==200){notify("Sent to metube!")}else {notify("Send to metube failed. Check the javascript console for clues.")}}}(); javascript:!function(){function notify(msg) {var sc = document.scrollingElement.scrollTop; var text = document.createElement('span');text.innerHTML=msg;var ts = text.style;ts.all = 'revert';ts.color = '#000';ts.fontFamily = 'Verdana, sans-serif';ts.fontSize = '15px';ts.backgroundColor = 'white';ts.padding = '15px';ts.border = '1px solid gainsboro';ts.boxShadow = '3px 3px 10px';ts.zIndex = '100';document.body.appendChild(text);ts.position = 'absolute'; ts.top = 50 + sc + 'px'; ts.left = (window.innerWidth / 2)-(text.offsetWidth / 2) + 'px'; setTimeout(function () { text.style.visibility = "hidden"; }, 1500);}xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function() { if(xhr.status==200){notify("Sent to metube!")}else {notify("Send to metube failed. Check the javascript console for clues.")}}}();
``` ```
Firefox: Firefox:
```javascript ```javascript
javascript:(function(){function notify(msg) {var sc = document.scrollingElement.scrollTop; var text = document.createElement('span');text.innerHTML=msg;var ts = text.style;ts.all = 'revert';ts.color = '#000';ts.fontFamily = 'Verdana, sans-serif';ts.fontSize = '15px';ts.backgroundColor = 'white';ts.padding = '15px';ts.border = '1px solid gainsboro';ts.boxShadow = '3px 3px 10px';ts.zIndex = '100';document.body.appendChild(text);ts.position = 'absolute'; ts.top = 50 + sc + 'px'; ts.left = (window.innerWidth / 2)-(text.offsetWidth / 2) + 'px'; setTimeout(function () { text.style.visibility = "hidden"; }, 1500);}xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function() { if(xhr.status==200){notify("Sent to metube!")}else {notify("Send to metube failed. Check the javascript console for clues.")}}})(); javascript:(function(){function notify(msg) {var sc = document.scrollingElement.scrollTop; var text = document.createElement('span');text.innerHTML=msg;var ts = text.style;ts.all = 'revert';ts.color = '#000';ts.fontFamily = 'Verdana, sans-serif';ts.fontSize = '15px';ts.backgroundColor = 'white';ts.padding = '15px';ts.border = '1px solid gainsboro';ts.boxShadow = '3px 3px 10px';ts.zIndex = '100';document.body.appendChild(text);ts.position = 'absolute'; ts.top = 50 + sc + 'px'; ts.left = (window.innerWidth / 2)-(text.offsetWidth / 2) + 'px'; setTimeout(function () { text.style.visibility = "hidden"; }, 1500);}xhr=new XMLHttpRequest();xhr.open("POST","https://metube.domain.com/add");xhr.send(JSON.stringify({"url":document.location.href,"quality":"best"}));xhr.onload=function() { if(xhr.status==200){notify("Sent to metube!")}else {notify("Send to metube failed. Check the javascript console for clues.")}}})();
``` ```
## ⚡ Raycast extension ## ⚡ Raycast extension
[dotvhs](https://github.com/dotvhs) has created an [extension for Raycast](https://www.raycast.com/dot/metube) that allows adding videos to MeTube directly from Raycast. [dotvhs](https://github.com/dotvhs) has created an [extension for Raycast](https://www.raycast.com/dot/metube) that allows adding videos to MeTube directly from Raycast.
## 🔒 HTTPS support, and running behind a reverse proxy ## 🔒 HTTPS support, and running behind a reverse proxy
It's possible to configure MeTube to listen in HTTPS mode. `docker-compose` example: It's possible to configure MeTube to listen in HTTPS mode. `docker-compose` example:
```yaml ```yaml
services: services:
metube: metube:
image: ghcr.io/alexta69/metube image: ghcr.io/alexta69/metube
container_name: metube container_name: metube
restart: unless-stopped restart: unless-stopped
ports: ports:
- "8081:8081" - "8081:8081"
volumes: volumes:
- /path/to/downloads:/downloads - /path/to/downloads:/downloads
- /path/to/ssl/crt:/ssl/crt.pem - /path/to/ssl/crt:/ssl/crt.pem
- /path/to/ssl/key:/ssl/key.pem - /path/to/ssl/key:/ssl/key.pem
environment: environment:
- HTTPS=true - HTTPS=true
- CERTFILE=/ssl/crt.pem - CERTFILE=/ssl/crt.pem
- KEYFILE=/ssl/key.pem - KEYFILE=/ssl/key.pem
``` ```
It's also possible to run MeTube behind a reverse proxy, in order to support authentication. HTTPS support can also be added in this way. It's also possible to run MeTube behind a reverse proxy, in order to support authentication. HTTPS support can also be added in this way.
When running behind a reverse proxy which remaps the URL (i.e. serves MeTube under a subdirectory and not under root), don't forget to set the URL_PREFIX environment variable to the correct value. When running behind a reverse proxy which remaps the URL (i.e. serves MeTube under a subdirectory and not under root), don't forget to set the URL_PREFIX environment variable to the correct value.
If you're using the [linuxserver/swag](https://docs.linuxserver.io/general/swag) image for your reverse proxying needs (which I can heartily recommend), it already includes ready snippets for proxying MeTube both in [subfolder](https://github.com/linuxserver/reverse-proxy-confs/blob/master/metube.subfolder.conf.sample) and [subdomain](https://github.com/linuxserver/reverse-proxy-confs/blob/master/metube.subdomain.conf.sample) modes under the `nginx/proxy-confs` directory in the configuration volume. It also includes Authelia which can be used for authentication. If you're using the [linuxserver/swag](https://docs.linuxserver.io/general/swag) image for your reverse proxying needs (which I can heartily recommend), it already includes ready snippets for proxying MeTube both in [subfolder](https://github.com/linuxserver/reverse-proxy-confs/blob/master/metube.subfolder.conf.sample) and [subdomain](https://github.com/linuxserver/reverse-proxy-confs/blob/master/metube.subdomain.conf.sample) modes under the `nginx/proxy-confs` directory in the configuration volume. It also includes Authelia which can be used for authentication.
### 🌐 NGINX ### 🌐 NGINX
```nginx ```nginx
location /metube/ { location /metube/ {
proxy_pass http://metube:8081; proxy_pass http://metube:8081;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
proxy_set_header Host $host; proxy_set_header Host $host;
} }
``` ```
Note: the extra `proxy_set_header` directives are there to make WebSocket work. Note: the extra `proxy_set_header` directives are there to make WebSocket work.
### 🌐 Apache ### 🌐 Apache
Contributed by [PIE-yt](https://github.com/PIE-yt). Source [here](https://gist.github.com/PIE-yt/29e7116588379032427f5bd446b2cac4). Contributed by [PIE-yt](https://github.com/PIE-yt). Source [here](https://gist.github.com/PIE-yt/29e7116588379032427f5bd446b2cac4).
```apache ```apache
# For putting in your Apache sites site.conf # For putting in your Apache sites site.conf
# Serves MeTube under a /metube/ subdir (http://yourdomain.com/metube/) # Serves MeTube under a /metube/ subdir (http://yourdomain.com/metube/)
<Location /metube/> <Location /metube/>
ProxyPass http://localhost:8081/ retry=0 timeout=30 ProxyPass http://localhost:8081/ retry=0 timeout=30
ProxyPassReverse http://localhost:8081/ ProxyPassReverse http://localhost:8081/
</Location> </Location>
<Location /metube/socket.io> <Location /metube/socket.io>
RewriteEngine On RewriteEngine On
RewriteCond %{QUERY_STRING} transport=websocket [NC] RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:8081/socket.io/$1 [P,L] RewriteRule /(.*) ws://localhost:8081/socket.io/$1 [P,L]
ProxyPass http://localhost:8081/socket.io retry=0 timeout=30 ProxyPass http://localhost:8081/socket.io retry=0 timeout=30
ProxyPassReverse http://localhost:8081/socket.io ProxyPassReverse http://localhost:8081/socket.io
</Location> </Location>
``` ```
### 🌐 Caddy ### 🌐 Caddy
The following example Caddyfile gets a reverse proxy going behind [caddy](https://caddyserver.com). The following example Caddyfile gets a reverse proxy going behind [caddy](https://caddyserver.com).
```caddyfile ```caddyfile
example.com { example.com {
route /metube/* { route /metube/* {
uri strip_prefix metube uri strip_prefix metube
reverse_proxy metube:8081 reverse_proxy metube:8081
} }
} }
``` ```
## 🔄 Updating yt-dlp ## 🔄 Updating yt-dlp
The engine which powers the actual video downloads in MeTube is [yt-dlp](https://github.com/yt-dlp/yt-dlp). Since video sites regularly change their layouts, frequent updates of yt-dlp are required to keep up. The engine which powers the actual video downloads in MeTube is [yt-dlp](https://github.com/yt-dlp/yt-dlp). Since video sites regularly change their layouts, frequent updates of yt-dlp are required to keep up.
There's an automatic nightly build of MeTube which looks for a new version of yt-dlp, and if one exists, the build pulls it and publishes an updated docker image. Therefore, in order to keep up with the changes, it's recommended that you update your MeTube container regularly with the latest image. There's an automatic nightly build of MeTube which looks for a new version of yt-dlp, and if one exists, the build pulls it and publishes an updated docker image. Therefore, in order to keep up with the changes, it's recommended that you update your MeTube container regularly with the latest image.
I recommend installing and setting up [watchtower](https://github.com/nicholas-fedor/watchtower) for this purpose. I recommend installing and setting up [watchtower](https://github.com/nicholas-fedor/watchtower) for this purpose.
## 🔧 Troubleshooting and submitting issues ## 🔧 Troubleshooting and submitting issues
Before asking a question or submitting an issue for MeTube, please remember that MeTube is only a UI for [yt-dlp](https://github.com/yt-dlp/yt-dlp). Any issues you might be experiencing with authentication to video websites, postprocessing, permissions, other `YTDL_OPTIONS` configurations which seem not to work, or anything else that concerns the workings of the underlying yt-dlp library, need not be opened on the MeTube project. In order to debug and troubleshoot them, it's advised to try using the yt-dlp binary directly first, bypassing the UI, and once that is working, importing the options that worked for you into `YTDL_OPTIONS`. Before asking a question or submitting an issue for MeTube, please remember that MeTube is only a UI for [yt-dlp](https://github.com/yt-dlp/yt-dlp). Any issues you might be experiencing with authentication to video websites, postprocessing, permissions, other `YTDL_OPTIONS` configurations which seem not to work, or anything else that concerns the workings of the underlying yt-dlp library, need not be opened on the MeTube project. In order to debug and troubleshoot them, it's advised to try using the yt-dlp binary directly first, bypassing the UI, and once that is working, importing the options that worked for you into `YTDL_OPTIONS`.
In order to test with the yt-dlp command directly, you can either download it and run it locally, or for a better simulation of its actual conditions, you can run it within the MeTube container itself. Assuming your MeTube container is called `metube`, run the following on your Docker host to get a shell inside the container: In order to test with the yt-dlp command directly, you can either download it and run it locally, or for a better simulation of its actual conditions, you can run it within the MeTube container itself. Assuming your MeTube container is called `metube`, run the following on your Docker host to get a shell inside the container:
```bash ```bash
docker exec -ti metube sh docker exec -ti metube sh
cd /downloads cd /downloads
``` ```
Once there, you can use the yt-dlp command freely. Once there, you can use the yt-dlp command freely.
## 💡 Submitting feature requests ## 💡 Submitting feature requests
MeTube development relies on code contributions by the community. The program as it currently stands fits my own use cases, and is therefore feature-complete as far as I'm concerned. If your use cases are different and require additional features, please feel free to submit PRs that implement those features. It's advisable to create an issue first to discuss the planned implementation, because in an effort to reduce bloat, some PRs may not be accepted. However, note that opening a feature request when you don't intend to implement the feature will rarely result in the request being fulfilled. MeTube development relies on code contributions by the community. The program as it currently stands fits my own use cases, and is therefore feature-complete as far as I'm concerned. If your use cases are different and require additional features, please feel free to submit PRs that implement those features. It's advisable to create an issue first to discuss the planned implementation, because in an effort to reduce bloat, some PRs may not be accepted. However, note that opening a feature request when you don't intend to implement the feature will rarely result in the request being fulfilled.
## 🛠️ Building and running locally ## 🛠️ Building and running locally
Make sure you have Node.js 22+ and Python 3.13 installed. Make sure you have Node.js 22+ and Python 3.13 installed.
```bash ```bash
cd metube/ui cd metube/ui
# install Angular and build the UI # install Angular and build the UI
pnpm install pnpm install
pnpm run build pnpm run build
# install python dependencies # install python dependencies
cd .. cd ..
curl -LsSf https://astral.sh/uv/install.sh | sh curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync uv sync
# run # run
uv run python3 app/main.py uv run python3 app/main.py
``` ```
A Docker image can be built locally (it will build the UI too): A Docker image can be built locally (it will build the UI too):
```bash ```bash
docker build -t metube . docker build -t metube .
``` ```
Note that if you're running the server in VSCode, your downloads will go to your user's Downloads folder (this is configured via the environment in `.vscode/launch.json`). Note that if you're running the server in VSCode, your downloads will go to your user's Downloads folder (this is configured via the environment in `.vscode/launch.json`).

View File

@@ -1,419 +1,434 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# pylint: disable=no-member,method-hidden # pylint: disable=no-member,method-hidden
import os import os
import sys import sys
import asyncio import asyncio
from pathlib import Path from pathlib import Path
from aiohttp import web from aiohttp import web
from aiohttp.log import access_logger from aiohttp.log import access_logger
import ssl import ssl
import socket import socket
import socketio import socketio
import logging import logging
import json import json
import pathlib import pathlib
import re import re
from watchfiles import DefaultFilter, Change, awatch from watchfiles import DefaultFilter, Change, awatch
from ytdl import DownloadQueueNotifier, DownloadQueue from ytdl import DownloadQueueNotifier, DownloadQueue
from yt_dlp.version import __version__ as yt_dlp_version from yt_dlp.version import __version__ as yt_dlp_version
log = logging.getLogger('main') log = logging.getLogger('main')
class Config: def parseLogLevel(logLevel):
_DEFAULTS = { match logLevel:
'DOWNLOAD_DIR': '.', case 'DEBUG':
'AUDIO_DOWNLOAD_DIR': '%%DOWNLOAD_DIR', return logging.DEBUG
'TEMP_DIR': '%%DOWNLOAD_DIR', case 'INFO':
'DOWNLOAD_DIRS_INDEXABLE': 'false', return logging.INFO
'CUSTOM_DIRS': 'true', case 'WARNING':
'CREATE_CUSTOM_DIRS': 'true', return logging.WARNING
'CUSTOM_DIRS_EXCLUDE_REGEX': r'(^|/)[.@].*$', case 'ERROR':
'DELETE_FILE_ON_TRASHCAN': 'false', return logging.ERROR
'STATE_DIR': '.', case 'CRITICAL':
'URL_PREFIX': '', return logging.CRITICAL
'PUBLIC_HOST_URL': 'download/', case _:
'PUBLIC_HOST_AUDIO_URL': 'audio_download/', return None
'OUTPUT_TEMPLATE': '%(title)s.%(ext)s',
'OUTPUT_TEMPLATE_CHAPTER': '%(title)s - %(section_number)s %(section_title)s.%(ext)s', # Configure logging before Config() uses it so early messages are not dropped.
'OUTPUT_TEMPLATE_PLAYLIST': '%(playlist_title)s/%(title)s.%(ext)s', # Only configure if no handlers are set (avoid clobbering hosting app settings).
'DEFAULT_OPTION_PLAYLIST_STRICT_MODE' : 'false', if not logging.getLogger().hasHandlers():
'DEFAULT_OPTION_PLAYLIST_ITEM_LIMIT' : '0', logging.basicConfig(level=parseLogLevel(os.environ.get('LOGLEVEL', 'INFO')) or logging.INFO)
'YTDL_OPTIONS': '{}',
'YTDL_OPTIONS_FILE': '', class Config:
'ROBOTS_TXT': '', _DEFAULTS = {
'HOST': '0.0.0.0', 'DOWNLOAD_DIR': '.',
'PORT': '8081', 'AUDIO_DOWNLOAD_DIR': '%%DOWNLOAD_DIR',
'HTTPS': 'false', 'TEMP_DIR': '%%DOWNLOAD_DIR',
'CERTFILE': '', 'DOWNLOAD_DIRS_INDEXABLE': 'false',
'KEYFILE': '', 'CUSTOM_DIRS': 'true',
'BASE_DIR': '', 'CREATE_CUSTOM_DIRS': 'true',
'DEFAULT_THEME': 'auto', 'CUSTOM_DIRS_EXCLUDE_REGEX': r'(^|/)[.@].*$',
'DOWNLOAD_MODE': 'limited', 'DELETE_FILE_ON_TRASHCAN': 'false',
'MAX_CONCURRENT_DOWNLOADS': 3, 'STATE_DIR': '.',
'LOGLEVEL': 'INFO', 'URL_PREFIX': '',
'ENABLE_ACCESSLOG': 'false', 'PUBLIC_HOST_URL': 'download/',
} 'PUBLIC_HOST_AUDIO_URL': 'audio_download/',
'OUTPUT_TEMPLATE': '%(title)s.%(ext)s',
_BOOLEAN = ('DOWNLOAD_DIRS_INDEXABLE', 'CUSTOM_DIRS', 'CREATE_CUSTOM_DIRS', 'DELETE_FILE_ON_TRASHCAN', 'DEFAULT_OPTION_PLAYLIST_STRICT_MODE', 'HTTPS', 'ENABLE_ACCESSLOG') 'OUTPUT_TEMPLATE_CHAPTER': '%(title)s - %(section_number)02d - %(section_title)s.%(ext)s',
'OUTPUT_TEMPLATE_PLAYLIST': '%(playlist_title)s/%(title)s.%(ext)s',
def __init__(self): 'DEFAULT_OPTION_PLAYLIST_STRICT_MODE' : 'false',
for k, v in self._DEFAULTS.items(): 'DEFAULT_OPTION_PLAYLIST_ITEM_LIMIT' : '0',
setattr(self, k, os.environ.get(k, v)) 'YTDL_OPTIONS': '{}',
'YTDL_OPTIONS_FILE': '',
for k, v in self.__dict__.items(): 'ROBOTS_TXT': '',
if isinstance(v, str) and v.startswith('%%'): 'HOST': '0.0.0.0',
setattr(self, k, getattr(self, v[2:])) 'PORT': '8081',
if k in self._BOOLEAN: 'HTTPS': 'false',
if v not in ('true', 'false', 'True', 'False', 'on', 'off', '1', '0'): 'CERTFILE': '',
log.error(f'Environment variable "{k}" is set to a non-boolean value "{v}"') 'KEYFILE': '',
sys.exit(1) 'BASE_DIR': '',
setattr(self, k, v in ('true', 'True', 'on', '1')) 'DEFAULT_THEME': 'auto',
'DOWNLOAD_MODE': 'limited',
if not self.URL_PREFIX.endswith('/'): 'MAX_CONCURRENT_DOWNLOADS': 3,
self.URL_PREFIX += '/' 'LOGLEVEL': 'INFO',
'ENABLE_ACCESSLOG': 'false',
# Convert relative addresses to absolute addresses to prevent the failure of file address comparison }
if self.YTDL_OPTIONS_FILE and self.YTDL_OPTIONS_FILE.startswith('.'):
self.YTDL_OPTIONS_FILE = str(Path(self.YTDL_OPTIONS_FILE).resolve()) _BOOLEAN = ('DOWNLOAD_DIRS_INDEXABLE', 'CUSTOM_DIRS', 'CREATE_CUSTOM_DIRS', 'DELETE_FILE_ON_TRASHCAN', 'DEFAULT_OPTION_PLAYLIST_STRICT_MODE', 'HTTPS', 'ENABLE_ACCESSLOG')
success,_ = self.load_ytdl_options() def __init__(self):
if not success: for k, v in self._DEFAULTS.items():
sys.exit(1) setattr(self, k, os.environ.get(k, v))
def load_ytdl_options(self) -> tuple[bool, str]: for k, v in self.__dict__.items():
try: if isinstance(v, str) and v.startswith('%%'):
self.YTDL_OPTIONS = json.loads(os.environ.get('YTDL_OPTIONS', '{}')) setattr(self, k, getattr(self, v[2:]))
assert isinstance(self.YTDL_OPTIONS, dict) if k in self._BOOLEAN:
except (json.decoder.JSONDecodeError, AssertionError): if v not in ('true', 'false', 'True', 'False', 'on', 'off', '1', '0'):
msg = 'Environment variable YTDL_OPTIONS is invalid' log.error(f'Environment variable "{k}" is set to a non-boolean value "{v}"')
log.error(msg) sys.exit(1)
return (False, msg) setattr(self, k, v in ('true', 'True', 'on', '1'))
if not self.YTDL_OPTIONS_FILE: if not self.URL_PREFIX.endswith('/'):
return (True, '') self.URL_PREFIX += '/'
log.info(f'Loading yt-dlp custom options from "{self.YTDL_OPTIONS_FILE}"') # Convert relative addresses to absolute addresses to prevent the failure of file address comparison
if not os.path.exists(self.YTDL_OPTIONS_FILE): if self.YTDL_OPTIONS_FILE and self.YTDL_OPTIONS_FILE.startswith('.'):
msg = f'File "{self.YTDL_OPTIONS_FILE}" not found' self.YTDL_OPTIONS_FILE = str(Path(self.YTDL_OPTIONS_FILE).resolve())
log.error(msg)
return (False, msg) success,_ = self.load_ytdl_options()
try: if not success:
with open(self.YTDL_OPTIONS_FILE) as json_data: sys.exit(1)
opts = json.load(json_data)
assert isinstance(opts, dict) def load_ytdl_options(self) -> tuple[bool, str]:
except (json.decoder.JSONDecodeError, AssertionError): try:
msg = 'YTDL_OPTIONS_FILE contents is invalid' self.YTDL_OPTIONS = json.loads(os.environ.get('YTDL_OPTIONS', '{}'))
log.error(msg) assert isinstance(self.YTDL_OPTIONS, dict)
return (False, msg) except (json.decoder.JSONDecodeError, AssertionError):
msg = 'Environment variable YTDL_OPTIONS is invalid'
self.YTDL_OPTIONS.update(opts) log.error(msg)
return (True, '') return (False, msg)
config = Config() if not self.YTDL_OPTIONS_FILE:
return (True, '')
class ObjectSerializer(json.JSONEncoder):
def default(self, obj): log.info(f'Loading yt-dlp custom options from "{self.YTDL_OPTIONS_FILE}"')
# First try to use __dict__ for custom objects if not os.path.exists(self.YTDL_OPTIONS_FILE):
if hasattr(obj, '__dict__'): msg = f'File "{self.YTDL_OPTIONS_FILE}" not found'
return obj.__dict__ log.error(msg)
# Convert iterables (generators, dict_items, etc.) to lists return (False, msg)
# Exclude strings and bytes which are also iterable try:
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes)): with open(self.YTDL_OPTIONS_FILE) as json_data:
try: opts = json.load(json_data)
return list(obj) assert isinstance(opts, dict)
except: except (json.decoder.JSONDecodeError, AssertionError):
pass msg = 'YTDL_OPTIONS_FILE contents is invalid'
# Fall back to default behavior log.error(msg)
return json.JSONEncoder.default(self, obj) return (False, msg)
serializer = ObjectSerializer() self.YTDL_OPTIONS.update(opts)
app = web.Application() return (True, '')
sio = socketio.AsyncServer(cors_allowed_origins='*')
sio.attach(app, socketio_path=config.URL_PREFIX + 'socket.io') config = Config()
routes = web.RouteTableDef() # Align root logger level with Config (keeps a single source of truth).
# This re-applies the log level after Config loads, in case LOGLEVEL was
class Notifier(DownloadQueueNotifier): # overridden by config file settings or differs from the environment variable.
async def added(self, dl): logging.getLogger().setLevel(parseLogLevel(str(config.LOGLEVEL)) or logging.INFO)
log.info(f"Notifier: Download added - {dl.title}")
await sio.emit('added', serializer.encode(dl)) class ObjectSerializer(json.JSONEncoder):
def default(self, obj):
async def updated(self, dl): # First try to use __dict__ for custom objects
log.info(f"Notifier: Download updated - {dl.title}") if hasattr(obj, '__dict__'):
await sio.emit('updated', serializer.encode(dl)) return obj.__dict__
# Convert iterables (generators, dict_items, etc.) to lists
async def completed(self, dl): # Exclude strings and bytes which are also iterable
log.info(f"Notifier: Download completed - {dl.title}") elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes)):
await sio.emit('completed', serializer.encode(dl)) try:
return list(obj)
async def canceled(self, id): except:
log.info(f"Notifier: Download canceled - {id}") pass
await sio.emit('canceled', serializer.encode(id)) # Fall back to default behavior
return json.JSONEncoder.default(self, obj)
async def cleared(self, id):
log.info(f"Notifier: Download cleared - {id}") serializer = ObjectSerializer()
await sio.emit('cleared', serializer.encode(id)) app = web.Application()
sio = socketio.AsyncServer(cors_allowed_origins='*')
dqueue = DownloadQueue(config, Notifier()) sio.attach(app, socketio_path=config.URL_PREFIX + 'socket.io')
app.on_startup.append(lambda app: dqueue.initialize()) routes = web.RouteTableDef()
class FileOpsFilter(DefaultFilter): class Notifier(DownloadQueueNotifier):
def __call__(self, change_type: int, path: str) -> bool: async def added(self, dl):
# Check if this path matches our YTDL_OPTIONS_FILE log.info(f"Notifier: Download added - {dl.title}")
if path != config.YTDL_OPTIONS_FILE: await sio.emit('added', serializer.encode(dl))
return False
async def updated(self, dl):
# For existing files, use samefile comparison to handle symlinks correctly log.debug(f"Notifier: Download updated - {dl.title}")
if os.path.exists(config.YTDL_OPTIONS_FILE): await sio.emit('updated', serializer.encode(dl))
try:
if not os.path.samefile(path, config.YTDL_OPTIONS_FILE): async def completed(self, dl):
return False log.info(f"Notifier: Download completed - {dl.title}")
except (OSError, IOError): await sio.emit('completed', serializer.encode(dl))
# If samefile fails, fall back to string comparison
if path != config.YTDL_OPTIONS_FILE: async def canceled(self, id):
return False log.info(f"Notifier: Download canceled - {id}")
await sio.emit('canceled', serializer.encode(id))
# Accept all change types for our file: modified, added, deleted
return change_type in (Change.modified, Change.added, Change.deleted) async def cleared(self, id):
log.info(f"Notifier: Download cleared - {id}")
def get_options_update_time(success=True, msg=''): await sio.emit('cleared', serializer.encode(id))
result = {
'success': success, dqueue = DownloadQueue(config, Notifier())
'msg': msg, app.on_startup.append(lambda app: dqueue.initialize())
'update_time': None
} class FileOpsFilter(DefaultFilter):
def __call__(self, change_type: int, path: str) -> bool:
# Only try to get file modification time if YTDL_OPTIONS_FILE is set and file exists # Check if this path matches our YTDL_OPTIONS_FILE
if config.YTDL_OPTIONS_FILE and os.path.exists(config.YTDL_OPTIONS_FILE): if path != config.YTDL_OPTIONS_FILE:
try: return False
result['update_time'] = os.path.getmtime(config.YTDL_OPTIONS_FILE)
except (OSError, IOError) as e: # For existing files, use samefile comparison to handle symlinks correctly
log.warning(f"Could not get modification time for {config.YTDL_OPTIONS_FILE}: {e}") if os.path.exists(config.YTDL_OPTIONS_FILE):
result['update_time'] = None try:
if not os.path.samefile(path, config.YTDL_OPTIONS_FILE):
return result return False
except (OSError, IOError):
async def watch_files(): # If samefile fails, fall back to string comparison
async def _watch_files(): if path != config.YTDL_OPTIONS_FILE:
async for changes in awatch(config.YTDL_OPTIONS_FILE, watch_filter=FileOpsFilter()): return False
success, msg = config.load_ytdl_options()
result = get_options_update_time(success, msg) # Accept all change types for our file: modified, added, deleted
await sio.emit('ytdl_options_changed', serializer.encode(result)) return change_type in (Change.modified, Change.added, Change.deleted)
log.info(f'Starting Watch File: {config.YTDL_OPTIONS_FILE}') def get_options_update_time(success=True, msg=''):
asyncio.create_task(_watch_files()) result = {
'success': success,
if config.YTDL_OPTIONS_FILE: 'msg': msg,
app.on_startup.append(lambda app: watch_files()) 'update_time': None
}
@routes.post(config.URL_PREFIX + 'add')
async def add(request): # Only try to get file modification time if YTDL_OPTIONS_FILE is set and file exists
log.info("Received request to add download") if config.YTDL_OPTIONS_FILE and os.path.exists(config.YTDL_OPTIONS_FILE):
post = await request.json() try:
log.info(f"Request data: {post}") result['update_time'] = os.path.getmtime(config.YTDL_OPTIONS_FILE)
url = post.get('url') except (OSError, IOError) as e:
quality = post.get('quality') log.warning(f"Could not get modification time for {config.YTDL_OPTIONS_FILE}: {e}")
if not url or not quality: result['update_time'] = None
log.error("Bad request: missing 'url' or 'quality'")
raise web.HTTPBadRequest() return result
format = post.get('format')
folder = post.get('folder') async def watch_files():
custom_name_prefix = post.get('custom_name_prefix') async def _watch_files():
playlist_strict_mode = post.get('playlist_strict_mode') async for changes in awatch(config.YTDL_OPTIONS_FILE, watch_filter=FileOpsFilter()):
playlist_item_limit = post.get('playlist_item_limit') success, msg = config.load_ytdl_options()
auto_start = post.get('auto_start') result = get_options_update_time(success, msg)
await sio.emit('ytdl_options_changed', serializer.encode(result))
if custom_name_prefix is None:
custom_name_prefix = '' log.info(f'Starting Watch File: {config.YTDL_OPTIONS_FILE}')
if auto_start is None: asyncio.create_task(_watch_files())
auto_start = True
if playlist_strict_mode is None: if config.YTDL_OPTIONS_FILE:
playlist_strict_mode = config.DEFAULT_OPTION_PLAYLIST_STRICT_MODE app.on_startup.append(lambda app: watch_files())
if playlist_item_limit is None:
playlist_item_limit = config.DEFAULT_OPTION_PLAYLIST_ITEM_LIMIT @routes.post(config.URL_PREFIX + 'add')
async def add(request):
playlist_item_limit = int(playlist_item_limit) log.info("Received request to add download")
post = await request.json()
status = await dqueue.add(url, quality, format, folder, custom_name_prefix, playlist_strict_mode, playlist_item_limit, auto_start) log.info(f"Request data: {post}")
return web.Response(text=serializer.encode(status)) url = post.get('url')
quality = post.get('quality')
@routes.post(config.URL_PREFIX + 'delete') if not url or not quality:
async def delete(request): log.error("Bad request: missing 'url' or 'quality'")
post = await request.json() raise web.HTTPBadRequest()
ids = post.get('ids') format = post.get('format')
where = post.get('where') folder = post.get('folder')
if not ids or where not in ['queue', 'done']: custom_name_prefix = post.get('custom_name_prefix')
log.error("Bad request: missing 'ids' or incorrect 'where' value") playlist_strict_mode = post.get('playlist_strict_mode')
raise web.HTTPBadRequest() playlist_item_limit = post.get('playlist_item_limit')
status = await (dqueue.cancel(ids) if where == 'queue' else dqueue.clear(ids)) auto_start = post.get('auto_start')
log.info(f"Download delete request processed for ids: {ids}, where: {where}") split_by_chapters = post.get('split_by_chapters')
return web.Response(text=serializer.encode(status)) chapter_template = post.get('chapter_template')
@routes.post(config.URL_PREFIX + 'start') if custom_name_prefix is None:
async def start(request): custom_name_prefix = ''
post = await request.json() if auto_start is None:
ids = post.get('ids') auto_start = True
log.info(f"Received request to start pending downloads for ids: {ids}") if playlist_strict_mode is None:
status = await dqueue.start_pending(ids) playlist_strict_mode = config.DEFAULT_OPTION_PLAYLIST_STRICT_MODE
return web.Response(text=serializer.encode(status)) if playlist_item_limit is None:
playlist_item_limit = config.DEFAULT_OPTION_PLAYLIST_ITEM_LIMIT
@routes.get(config.URL_PREFIX + 'history') if split_by_chapters is None:
async def history(request): split_by_chapters = False
history = { 'done': [], 'queue': [], 'pending': []} if chapter_template is None:
chapter_template = config.OUTPUT_TEMPLATE_CHAPTER
for _, v in dqueue.queue.saved_items():
history['queue'].append(v) playlist_item_limit = int(playlist_item_limit)
for _, v in dqueue.done.saved_items():
history['done'].append(v) status = await dqueue.add(url, quality, format, folder, custom_name_prefix, playlist_strict_mode, playlist_item_limit, auto_start, split_by_chapters, chapter_template)
for _, v in dqueue.pending.saved_items(): return web.Response(text=serializer.encode(status))
history['pending'].append(v)
@routes.post(config.URL_PREFIX + 'delete')
log.info("Sending download history") async def delete(request):
return web.Response(text=serializer.encode(history)) post = await request.json()
ids = post.get('ids')
@sio.event where = post.get('where')
async def connect(sid, environ): if not ids or where not in ['queue', 'done']:
log.info(f"Client connected: {sid}") log.error("Bad request: missing 'ids' or incorrect 'where' value")
await sio.emit('all', serializer.encode(dqueue.get()), to=sid) raise web.HTTPBadRequest()
await sio.emit('configuration', serializer.encode(config), to=sid) status = await (dqueue.cancel(ids) if where == 'queue' else dqueue.clear(ids))
if config.CUSTOM_DIRS: log.info(f"Download delete request processed for ids: {ids}, where: {where}")
await sio.emit('custom_dirs', serializer.encode(get_custom_dirs()), to=sid) return web.Response(text=serializer.encode(status))
if config.YTDL_OPTIONS_FILE:
await sio.emit('ytdl_options_changed', serializer.encode(get_options_update_time()), to=sid) @routes.post(config.URL_PREFIX + 'start')
async def start(request):
def get_custom_dirs(): post = await request.json()
def recursive_dirs(base): ids = post.get('ids')
path = pathlib.Path(base) log.info(f"Received request to start pending downloads for ids: {ids}")
status = await dqueue.start_pending(ids)
# Converts PosixPath object to string, and remove base/ prefix return web.Response(text=serializer.encode(status))
def convert(p):
s = str(p) @routes.get(config.URL_PREFIX + 'history')
if s.startswith(base): async def history(request):
s = s[len(base):] history = { 'done': [], 'queue': [], 'pending': []}
if s.startswith('/'): for _, v in dqueue.queue.saved_items():
s = s[1:] history['queue'].append(v)
for _, v in dqueue.done.saved_items():
return s history['done'].append(v)
for _, v in dqueue.pending.saved_items():
# Include only directories which do not match the exclude filter history['pending'].append(v)
def include_dir(d):
if len(config.CUSTOM_DIRS_EXCLUDE_REGEX) == 0: log.info("Sending download history")
return True return web.Response(text=serializer.encode(history))
else:
return re.search(config.CUSTOM_DIRS_EXCLUDE_REGEX, d) is None @sio.event
async def connect(sid, environ):
# Recursively lists all subdirectories of DOWNLOAD_DIR log.info(f"Client connected: {sid}")
dirs = list(filter(include_dir, map(convert, path.glob('**/')))) await sio.emit('all', serializer.encode(dqueue.get()), to=sid)
await sio.emit('configuration', serializer.encode(config), to=sid)
return dirs if config.CUSTOM_DIRS:
await sio.emit('custom_dirs', serializer.encode(get_custom_dirs()), to=sid)
download_dir = recursive_dirs(config.DOWNLOAD_DIR) if config.YTDL_OPTIONS_FILE:
await sio.emit('ytdl_options_changed', serializer.encode(get_options_update_time()), to=sid)
audio_download_dir = download_dir
if config.DOWNLOAD_DIR != config.AUDIO_DOWNLOAD_DIR: def get_custom_dirs():
audio_download_dir = recursive_dirs(config.AUDIO_DOWNLOAD_DIR) def recursive_dirs(base):
path = pathlib.Path(base)
return {
"download_dir": download_dir, # Converts PosixPath object to string, and remove base/ prefix
"audio_download_dir": audio_download_dir def convert(p):
} s = str(p)
if s.startswith(base):
@routes.get(config.URL_PREFIX) s = s[len(base):]
def index(request):
response = web.FileResponse(os.path.join(config.BASE_DIR, 'ui/dist/metube/browser/index.html')) if s.startswith('/'):
if 'metube_theme' not in request.cookies: s = s[1:]
response.set_cookie('metube_theme', config.DEFAULT_THEME)
return response return s
@routes.get(config.URL_PREFIX + 'robots.txt') # Include only directories which do not match the exclude filter
def robots(request): def include_dir(d):
if config.ROBOTS_TXT: if len(config.CUSTOM_DIRS_EXCLUDE_REGEX) == 0:
response = web.FileResponse(os.path.join(config.BASE_DIR, config.ROBOTS_TXT)) return True
else: else:
response = web.Response( return re.search(config.CUSTOM_DIRS_EXCLUDE_REGEX, d) is None
text="User-agent: *\nDisallow: /download/\nDisallow: /audio_download/\n"
) # Recursively lists all subdirectories of DOWNLOAD_DIR
return response dirs = list(filter(include_dir, map(convert, path.glob('**/'))))
@routes.get(config.URL_PREFIX + 'version') return dirs
def version(request):
return web.json_response({ download_dir = recursive_dirs(config.DOWNLOAD_DIR)
"yt-dlp": yt_dlp_version,
"version": os.getenv("METUBE_VERSION", "dev") audio_download_dir = download_dir
}) if config.DOWNLOAD_DIR != config.AUDIO_DOWNLOAD_DIR:
audio_download_dir = recursive_dirs(config.AUDIO_DOWNLOAD_DIR)
if config.URL_PREFIX != '/':
@routes.get('/') return {
def index_redirect_root(request): "download_dir": download_dir,
return web.HTTPFound(config.URL_PREFIX) "audio_download_dir": audio_download_dir
}
@routes.get(config.URL_PREFIX[:-1])
def index_redirect_dir(request): @routes.get(config.URL_PREFIX)
return web.HTTPFound(config.URL_PREFIX) def index(request):
response = web.FileResponse(os.path.join(config.BASE_DIR, 'ui/dist/metube/browser/index.html'))
routes.static(config.URL_PREFIX + 'download/', config.DOWNLOAD_DIR, show_index=config.DOWNLOAD_DIRS_INDEXABLE) if 'metube_theme' not in request.cookies:
routes.static(config.URL_PREFIX + 'audio_download/', config.AUDIO_DOWNLOAD_DIR, show_index=config.DOWNLOAD_DIRS_INDEXABLE) response.set_cookie('metube_theme', config.DEFAULT_THEME)
routes.static(config.URL_PREFIX, os.path.join(config.BASE_DIR, 'ui/dist/metube/browser')) return response
try:
app.add_routes(routes) @routes.get(config.URL_PREFIX + 'robots.txt')
except ValueError as e: def robots(request):
if 'ui/dist/metube/browser' in str(e): if config.ROBOTS_TXT:
raise RuntimeError('Could not find the frontend UI static assets. Please run `node_modules/.bin/ng build` inside the ui folder') from e response = web.FileResponse(os.path.join(config.BASE_DIR, config.ROBOTS_TXT))
raise e else:
response = web.Response(
# https://github.com/aio-libs/aiohttp/pull/4615 waiting for release text="User-agent: *\nDisallow: /download/\nDisallow: /audio_download/\n"
# @routes.options(config.URL_PREFIX + 'add') )
async def add_cors(request): return response
return web.Response(text=serializer.encode({"status": "ok"}))
@routes.get(config.URL_PREFIX + 'version')
app.router.add_route('OPTIONS', config.URL_PREFIX + 'add', add_cors) def version(request):
return web.json_response({
async def on_prepare(request, response): "yt-dlp": yt_dlp_version,
if 'Origin' in request.headers: "version": os.getenv("METUBE_VERSION", "dev")
response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] })
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
if config.URL_PREFIX != '/':
app.on_response_prepare.append(on_prepare) @routes.get('/')
def index_redirect_root(request):
def supports_reuse_port(): return web.HTTPFound(config.URL_PREFIX)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @routes.get(config.URL_PREFIX[:-1])
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) def index_redirect_dir(request):
sock.close() return web.HTTPFound(config.URL_PREFIX)
return True
except (AttributeError, OSError): routes.static(config.URL_PREFIX + 'download/', config.DOWNLOAD_DIR, show_index=config.DOWNLOAD_DIRS_INDEXABLE)
return False routes.static(config.URL_PREFIX + 'audio_download/', config.AUDIO_DOWNLOAD_DIR, show_index=config.DOWNLOAD_DIRS_INDEXABLE)
routes.static(config.URL_PREFIX, os.path.join(config.BASE_DIR, 'ui/dist/metube/browser'))
def parseLogLevel(logLevel): try:
match logLevel: app.add_routes(routes)
case 'DEBUG': except ValueError as e:
return logging.DEBUG if 'ui/dist/metube/browser' in str(e):
case 'INFO': raise RuntimeError('Could not find the frontend UI static assets. Please run `node_modules/.bin/ng build` inside the ui folder') from e
return logging.INFO raise e
case 'WARNING':
return logging.WARNING # https://github.com/aio-libs/aiohttp/pull/4615 waiting for release
case 'ERROR': # @routes.options(config.URL_PREFIX + 'add')
return logging.ERROR async def add_cors(request):
case 'CRITICAL': return web.Response(text=serializer.encode({"status": "ok"}))
return logging.CRITICAL
case _: app.router.add_route('OPTIONS', config.URL_PREFIX + 'add', add_cors)
return None
async def on_prepare(request, response):
def isAccessLogEnabled(): if 'Origin' in request.headers:
if config.ENABLE_ACCESSLOG: response.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
return access_logger response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
else:
return None app.on_response_prepare.append(on_prepare)
if __name__ == '__main__': def supports_reuse_port():
logging.basicConfig(level=parseLogLevel(config.LOGLEVEL)) try:
log.info(f"Listening on {config.HOST}:{config.PORT}") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
if config.HTTPS: sock.close()
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) return True
ssl_context.load_cert_chain(certfile=config.CERTFILE, keyfile=config.KEYFILE) except (AttributeError, OSError):
web.run_app(app, host=config.HOST, port=int(config.PORT), reuse_port=supports_reuse_port(), ssl_context=ssl_context, access_log=isAccessLogEnabled()) return False
else:
web.run_app(app, host=config.HOST, port=int(config.PORT), reuse_port=supports_reuse_port(), access_log=isAccessLogEnabled()) def isAccessLogEnabled():
if config.ENABLE_ACCESSLOG:
return access_logger
else:
return None
if __name__ == '__main__':
logging.getLogger().setLevel(parseLogLevel(config.LOGLEVEL) or logging.INFO)
log.info(f"Listening on {config.HOST}:{config.PORT}")
if config.HTTPS:
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(certfile=config.CERTFILE, keyfile=config.KEYFILE)
web.run_app(app, host=config.HOST, port=int(config.PORT), reuse_port=supports_reuse_port(), ssl_context=ssl_context, access_log=isAccessLogEnabled())
else:
web.run_app(app, host=config.HOST, port=int(config.PORT), reuse_port=supports_reuse_port(), access_log=isAccessLogEnabled())

File diff suppressed because it is too large Load Diff

View File

@@ -231,6 +231,29 @@
<label class="form-check-label" for="checkbox-strict-mode">Strict Playlist Mode</label> <label class="form-check-label" for="checkbox-strict-mode">Strict Playlist Mode</label>
</div> </div>
</div> </div>
<div class="col-12">
<div class="row g-2 align-items-center">
<div class="col-auto">
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" role="switch" id="checkbox-split-chapters"
name="splitByChapters" [(ngModel)]="splitByChapters" (change)="splitByChaptersChanged()"
[disabled]="addInProgress || downloads.loading"
ngbTooltip="Split video into separate files by chapters">
<label class="form-check-label" for="checkbox-split-chapters">Split by chapters</label>
</div>
</div>
@if (splitByChapters) {
<div class="col">
<div class="input-group">
<span class="input-group-text">Template</span>
<input type="text" class="form-control" name="chapterTemplate" [(ngModel)]="chapterTemplate"
(change)="chapterTemplateChanged()" [disabled]="addInProgress || downloads.loading"
ngbTooltip="Output template for chapter files">
</div>
</div>
}
</div>
</div>
</div> </div>
<!-- Advanced Actions --> <!-- Advanced Actions -->
@@ -395,7 +418,7 @@
<fa-icon [icon]="faTimesCircle" class="text-danger" /> <fa-icon [icon]="faTimesCircle" class="text-danger" />
} }
</div> </div>
<span ngbTooltip="{{download.value.msg}} | {{download.value.error}}">@if (!!download.value.filename) { <span ngbTooltip="{{buildResultItemTooltip(download.value)}}">@if (!!download.value.filename) {
<a href="{{buildDownloadLink(download.value)}}" target="_blank">{{ download.value.title }}</a> <a href="{{buildDownloadLink(download.value)}}" target="_blank">{{ download.value.title }}</a>
} @else { } @else {
{{download.value.title}} {{download.value.title}}
@@ -425,7 +448,32 @@
</div> </div>
</td> </td>
</tr> </tr>
@if (download.value.chapter_files && download.value.chapter_files.length > 0) {
@for (chapterFile of download.value.chapter_files; track chapterFile.filename) {
<tr [class.disabled]='download.value.deleting'>
<td></td>
<td>
<div style="padding-left: 2rem;">
<fa-icon [icon]="faCheckCircle" class="text-success me-2" />
<a href="{{buildChapterDownloadLink(download.value, chapterFile.filename)}}" target="_blank">{{
getChapterFileName(chapterFile.filename) }}</a>
</div>
</td>
<td>
@if (chapterFile.size) {
<span>{{ chapterFile.size | fileSize }}</span>
}
</td>
<td>
<div class="d-flex">
<a href="{{buildChapterDownloadLink(download.value, chapterFile.filename)}}" download
class="btn btn-link"><fa-icon [icon]="faDownload" /></a>
</div>
</td>
</tr>
} }
}
}
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@@ -1,211 +1,211 @@
.button-toggle-theme:focus, .button-toggle-theme:active .button-toggle-theme:focus, .button-toggle-theme:active
box-shadow: none box-shadow: none
outline: 0px outline: 0px
.add-url-box .add-url-box
max-width: 960px max-width: 960px
margin: 4rem auto margin: 4rem auto
.add-url-component .add-url-component
margin: 0.5rem auto margin: 0.5rem auto
.add-url-group .add-url-group
width: 100% width: 100%
button.add-url button.add-url
width: 100% width: 100%
.folder-dropdown-menu .folder-dropdown-menu
width: 500px width: 500px
max-width: calc(100vw - 3rem) max-width: calc(100vw - 3rem)
.folder-dropdown-menu .input-group .folder-dropdown-menu .input-group
display: flex display: flex
padding-left: 5px padding-left: 5px
padding-right: 5px padding-right: 5px
.metube-section-header .metube-section-header
font-size: 1.8rem font-size: 1.8rem
font-weight: 300 font-weight: 300
position: relative position: relative
background: var(--bs-secondary-bg) background: var(--bs-secondary-bg)
padding: 0.5rem 0 padding: 0.5rem 0
margin-top: 3.5rem margin-top: 3.5rem
.metube-section-header:before .metube-section-header:before
content: "" content: ""
position: absolute position: absolute
top: 0 top: 0
bottom: 0 bottom: 0
left: -9999px left: -9999px
right: 0 right: 0
border-left: 9999px solid var(--bs-secondary-bg) border-left: 9999px solid var(--bs-secondary-bg)
box-shadow: 9999px 0 0 var(--bs-secondary-bg) box-shadow: 9999px 0 0 var(--bs-secondary-bg)
button:hover button:hover
text-decoration: none text-decoration: none
th th
border-top: 0 border-top: 0
border-bottom-width: 3px !important border-bottom-width: 3px !important
vertical-align: middle !important vertical-align: middle !important
white-space: nowrap white-space: nowrap
td td
vertical-align: middle vertical-align: middle
.disabled .disabled
opacity: 0.5 opacity: 0.5
pointer-events: none pointer-events: none
.form-switch .form-switch
input input
margin-top: 5px margin-top: 5px
.download-progressbar .download-progressbar
width: 12rem width: 12rem
margin-left: auto margin-left: auto
.batch-panel .batch-panel
margin-top: 15px margin-top: 15px
border: 1px solid #ccc border: 1px solid #ccc
border-radius: 8px border-radius: 8px
padding: 15px padding: 15px
background-color: #fff background-color: #fff
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1)
.batch-panel-header .batch-panel-header
border-bottom: 1px solid #eee border-bottom: 1px solid #eee
padding-bottom: 8px padding-bottom: 8px
margin-bottom: 15px margin-bottom: 15px
h4 h4
font-size: 1.5rem font-size: 1.5rem
margin: 0 margin: 0
.batch-panel-body .batch-panel-body
textarea.form-control textarea.form-control
resize: vertical resize: vertical
.batch-status .batch-status
font-size: 0.9rem font-size: 0.9rem
color: #555 color: #555
.d-flex.my-3 .d-flex.my-3
margin-top: 1rem margin-top: 1rem
margin-bottom: 1rem margin-bottom: 1rem
.modal.fade.show .modal.fade.show
background-color: rgba(0, 0, 0, 0.5) background-color: rgba(0, 0, 0, 0.5)
.modal-header .modal-header
border-bottom: 1px solid #eee border-bottom: 1px solid #eee
.modal-body .modal-body
textarea.form-control textarea.form-control
resize: vertical resize: vertical
.add-url .add-url
display: inline-flex display: inline-flex
align-items: center align-items: center
justify-content: center justify-content: center
.spinner-border .spinner-border
margin-right: 0.5rem margin-right: 0.5rem
::ng-deep .ng-select ::ng-deep .ng-select
flex: 1 flex: 1
.ng-select-container .ng-select-container
min-height: 38px min-height: 38px
.ng-value .ng-value
white-space: nowrap white-space: nowrap
overflow: visible overflow: visible
.ng-dropdown-panel .ng-dropdown-panel
.ng-dropdown-panel-items .ng-dropdown-panel-items
max-height: 300px max-height: 300px
.ng-option .ng-option
white-space: nowrap white-space: nowrap
overflow: visible overflow: visible
text-overflow: ellipsis text-overflow: ellipsis
:host :host
display: flex display: flex
flex-direction: column flex-direction: column
min-height: 100vh min-height: 100vh
main main
flex-grow: 1 flex-grow: 1
.footer .footer
width: 100% width: 100%
padding: 10px 0 padding: 10px 0
background: linear-gradient(to bottom, rgba(0,0,0,0.2), rgba(0,0,0,0.1)) background: linear-gradient(to bottom, rgba(0,0,0,0.2), rgba(0,0,0,0.1))
.footer-content .footer-content
display: flex display: flex
justify-content: center justify-content: center
align-items: center align-items: center
gap: 20px gap: 20px
color: #fff color: #fff
font-size: 0.9rem font-size: 0.9rem
.version-item .version-item
display: flex display: flex
align-items: center align-items: center
gap: 8px gap: 8px
.version-label .version-label
font-size: 0.75rem font-size: 0.75rem
text-transform: uppercase text-transform: uppercase
letter-spacing: 0.5px letter-spacing: 0.5px
opacity: 0.7 opacity: 0.7
.version-value .version-value
font-family: monospace font-family: monospace
font-size: 0.85rem font-size: 0.85rem
padding: 2px 6px padding: 2px 6px
background: rgba(255,255,255,0.1) background: rgba(255,255,255,0.1)
border-radius: 4px border-radius: 4px
.version-separator .version-separator
width: 1px width: 1px
height: 16px height: 16px
background: rgba(255,255,255,0.2) background: rgba(255,255,255,0.2)
margin: 0 4px margin: 0 4px
.github-link .github-link
display: flex display: flex
align-items: center align-items: center
gap: 6px gap: 6px
color: #fff color: #fff
text-decoration: none text-decoration: none
font-size: 0.85rem font-size: 0.85rem
padding: 2px 8px padding: 2px 8px
border-radius: 4px border-radius: 4px
transition: background-color 0.2s ease transition: background-color 0.2s ease
&:hover &:hover
background: rgba(255,255,255,0.1) background: rgba(255,255,255,0.1)
color: #fff color: #fff
text-decoration: none text-decoration: none
i i
font-size: 1rem font-size: 1rem
.download-metrics .download-metrics
display: flex display: flex
align-items: center align-items: center
gap: 16px gap: 16px
margin-left: 24px margin-left: 24px
.metric .metric
display: flex display: flex
align-items: center align-items: center
gap: 6px gap: 6px
font-size: 0.9rem font-size: 0.9rem
color: #adb5bd color: #adb5bd
fa-icon fa-icon
font-size: 1rem font-size: 1rem
span span
white-space: nowrap white-space: nowrap

View File

@@ -48,6 +48,8 @@ export class App implements AfterViewInit, OnInit {
autoStart: boolean; autoStart: boolean;
playlistStrictMode!: boolean; playlistStrictMode!: boolean;
playlistItemLimit!: number; playlistItemLimit!: number;
splitByChapters: boolean;
chapterTemplate: string;
addInProgress = false; addInProgress = false;
themes: Theme[] = Themes; themes: Theme[] = Themes;
activeTheme: Theme | undefined; activeTheme: Theme | undefined;
@@ -103,6 +105,9 @@ export class App implements AfterViewInit, OnInit {
this.setQualities() this.setQualities()
this.quality = this.cookieService.get('metube_quality') || 'best'; this.quality = this.cookieService.get('metube_quality') || 'best';
this.autoStart = this.cookieService.get('metube_auto_start') !== 'false'; this.autoStart = this.cookieService.get('metube_auto_start') !== 'false';
this.splitByChapters = this.cookieService.get('metube_split_chapters') === 'true';
// Will be set from backend configuration, use empty string as placeholder
this.chapterTemplate = this.cookieService.get('metube_chapter_template') || '';
this.activeTheme = this.getPreferredTheme(this.cookieService); this.activeTheme = this.getPreferredTheme(this.cookieService);
@@ -221,6 +226,10 @@ export class App implements AfterViewInit, OnInit {
if (playlistItemLimit !== '0') { if (playlistItemLimit !== '0') {
this.playlistItemLimit = playlistItemLimit; this.playlistItemLimit = playlistItemLimit;
} }
// Set chapter template from backend config if not already set by cookie
if (!this.chapterTemplate) {
this.chapterTemplate = config['OUTPUT_TEMPLATE_CHAPTER'];
}
} }
}); });
} }
@@ -260,6 +269,18 @@ export class App implements AfterViewInit, OnInit {
this.cookieService.set('metube_auto_start', this.autoStart ? 'true' : 'false', { expires: 3650 }); this.cookieService.set('metube_auto_start', this.autoStart ? 'true' : 'false', { expires: 3650 });
} }
splitByChaptersChanged() {
this.cookieService.set('metube_split_chapters', this.splitByChapters ? 'true' : 'false', { expires: 3650 });
}
chapterTemplateChanged() {
// Restore default if template is cleared - get from configuration
if (!this.chapterTemplate || this.chapterTemplate.trim() === '') {
this.chapterTemplate = this.downloads.configuration['OUTPUT_TEMPLATE_CHAPTER'];
}
this.cookieService.set('metube_chapter_template', this.chapterTemplate, { expires: 3650 });
}
queueSelectionChanged(checked: number) { queueSelectionChanged(checked: number) {
this.queueDelSelected().nativeElement.disabled = checked == 0; this.queueDelSelected().nativeElement.disabled = checked == 0;
this.queueDownloadSelected().nativeElement.disabled = checked == 0; this.queueDownloadSelected().nativeElement.disabled = checked == 0;
@@ -280,7 +301,7 @@ export class App implements AfterViewInit, OnInit {
} }
} }
addDownload(url?: string, quality?: string, format?: string, folder?: string, customNamePrefix?: string, playlistStrictMode?: boolean, playlistItemLimit?: number, autoStart?: boolean) { addDownload(url?: string, quality?: string, format?: string, folder?: string, customNamePrefix?: string, playlistStrictMode?: boolean, playlistItemLimit?: number, autoStart?: boolean, splitByChapters?: boolean, chapterTemplate?: string) {
url = url ?? this.addUrl url = url ?? this.addUrl
quality = quality ?? this.quality quality = quality ?? this.quality
format = format ?? this.format format = format ?? this.format
@@ -289,10 +310,18 @@ export class App implements AfterViewInit, OnInit {
playlistStrictMode = playlistStrictMode ?? this.playlistStrictMode playlistStrictMode = playlistStrictMode ?? this.playlistStrictMode
playlistItemLimit = playlistItemLimit ?? this.playlistItemLimit playlistItemLimit = playlistItemLimit ?? this.playlistItemLimit
autoStart = autoStart ?? this.autoStart autoStart = autoStart ?? this.autoStart
splitByChapters = splitByChapters ?? this.splitByChapters
chapterTemplate = chapterTemplate ?? this.chapterTemplate
console.debug('Downloading: url='+url+' quality='+quality+' format='+format+' folder='+folder+' customNamePrefix='+customNamePrefix+' playlistStrictMode='+playlistStrictMode+' playlistItemLimit='+playlistItemLimit+' autoStart='+autoStart); // Validate chapter template if chapter splitting is enabled
if (splitByChapters && !chapterTemplate.includes('%(section_number)')) {
alert('Chapter template must include %(section_number)');
return;
}
console.debug('Downloading: url=' + url + ' quality=' + quality + ' format=' + format + ' folder=' + folder + ' customNamePrefix=' + customNamePrefix + ' playlistStrictMode=' + playlistStrictMode + ' playlistItemLimit=' + playlistItemLimit + ' autoStart=' + autoStart + ' splitByChapters=' + splitByChapters + ' chapterTemplate=' + chapterTemplate);
this.addInProgress = true; this.addInProgress = true;
this.downloads.add(url, quality, format, folder, customNamePrefix, playlistStrictMode, playlistItemLimit, autoStart).subscribe((status: Status) => { this.downloads.add(url, quality, format, folder, customNamePrefix, playlistStrictMode, playlistItemLimit, autoStart, splitByChapters, chapterTemplate).subscribe((status: Status) => {
if (status.status === 'error') { if (status.status === 'error') {
alert(`Error adding URL: ${status.msg}`); alert(`Error adding URL: ${status.msg}`);
} else { } else {
@@ -307,7 +336,7 @@ export class App implements AfterViewInit, OnInit {
} }
retryDownload(key: string, download: Download) { retryDownload(key: string, download: Download) {
this.addDownload(download.url, download.quality, download.format, download.folder, download.custom_name_prefix, download.playlist_strict_mode, download.playlist_item_limit, true); this.addDownload(download.url, download.quality, download.format, download.folder, download.custom_name_prefix, download.playlist_strict_mode, download.playlist_item_limit, true, download.split_by_chapters, download.chapter_template);
this.downloads.delById('done', [key]).subscribe(); this.downloads.delById('done', [key]).subscribe();
} }
@@ -367,6 +396,35 @@ export class App implements AfterViewInit, OnInit {
return baseDir + encodeURIComponent(download.filename); return baseDir + encodeURIComponent(download.filename);
} }
buildResultItemTooltip(download: Download) {
const parts = [];
if (download.msg) {
parts.push(download.msg);
}
if (download.error) {
parts.push(download.error);
}
return parts.join(' | ');
}
buildChapterDownloadLink(download: Download, chapterFilename: string) {
let baseDir = this.downloads.configuration["PUBLIC_HOST_URL"];
if (download.quality == 'audio' || chapterFilename.endsWith('.mp3')) {
baseDir = this.downloads.configuration["PUBLIC_HOST_AUDIO_URL"];
}
if (download.folder) {
baseDir += download.folder + '/';
}
return baseDir + encodeURIComponent(chapterFilename);
}
getChapterFileName(filepath: string) {
// Extract just the filename from the path
const parts = filepath.split('/');
return parts[parts.length - 1];
}
isNumber(event: KeyboardEvent) { isNumber(event: KeyboardEvent) {
const charCode = +event.code || event.keyCode; const charCode = +event.code || event.keyCode;
@@ -424,7 +482,7 @@ export class App implements AfterViewInit, OnInit {
this.batchImportStatus = `Importing URL ${index + 1} of ${urls.length}: ${url}`; this.batchImportStatus = `Importing URL ${index + 1} of ${urls.length}: ${url}`;
// Now pass the selected quality, format, folder, etc. to the add() method // Now pass the selected quality, format, folder, etc. to the add() method
this.downloads.add(url, this.quality, this.format, this.folder, this.customNamePrefix, this.downloads.add(url, this.quality, this.format, this.folder, this.customNamePrefix,
this.playlistStrictMode, this.playlistItemLimit, this.autoStart) this.playlistStrictMode, this.playlistItemLimit, this.autoStart, this.splitByChapters, this.chapterTemplate)
.subscribe({ .subscribe({
next: (status: Status) => { next: (status: Status) => {
if (status.status === 'error') { if (status.status === 'error') {

View File

@@ -9,6 +9,8 @@ export interface Download {
custom_name_prefix: string; custom_name_prefix: string;
playlist_strict_mode: boolean; playlist_strict_mode: boolean;
playlist_item_limit: number; playlist_item_limit: number;
split_by_chapters?: boolean;
chapter_template?: string;
status: string; status: string;
msg: string; msg: string;
percent: number; percent: number;
@@ -19,4 +21,5 @@ export interface Download {
size?: number; size?: number;
error?: string; error?: string;
deleting?: boolean; deleting?: boolean;
chapter_files?: Array<{ filename: string, size: number }>;
} }

View File

@@ -107,8 +107,8 @@ export class DownloadsService {
return of({status: 'error', msg: msg}) return of({status: 'error', msg: msg})
} }
public add(url: string, quality: string, format: string, folder: string, customNamePrefix: string, playlistStrictMode: boolean, playlistItemLimit: number, autoStart: boolean) { public add(url: string, quality: string, format: string, folder: string, customNamePrefix: string, playlistStrictMode: boolean, playlistItemLimit: number, autoStart: boolean, splitByChapters: boolean, chapterTemplate: string) {
return this.http.post<Status>('add', {url: url, quality: quality, format: format, folder: folder, custom_name_prefix: customNamePrefix, playlist_strict_mode: playlistStrictMode, playlist_item_limit: playlistItemLimit, auto_start: autoStart}).pipe( return this.http.post<Status>('add', { url: url, quality: quality, format: format, folder: folder, custom_name_prefix: customNamePrefix, playlist_strict_mode: playlistStrictMode, playlist_item_limit: playlistItemLimit, auto_start: autoStart, split_by_chapters: splitByChapters, chapter_template: chapterTemplate }).pipe(
catchError(this.handleHTTPError) catchError(this.handleHTTPError)
); );
} }
@@ -150,9 +150,11 @@ export class DownloadsService {
const defaultPlaylistStrictMode = false; const defaultPlaylistStrictMode = false;
const defaultPlaylistItemLimit = 0; const defaultPlaylistItemLimit = 0;
const defaultAutoStart = true; const defaultAutoStart = true;
const defaultSplitByChapters = false;
const defaultChapterTemplate = this.configuration['OUTPUT_TEMPLATE_CHAPTER'];
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.add(url, defaultQuality, defaultFormat, defaultFolder, defaultCustomNamePrefix, defaultPlaylistStrictMode, defaultPlaylistItemLimit, defaultAutoStart) this.add(url, defaultQuality, defaultFormat, defaultFolder, defaultCustomNamePrefix, defaultPlaylistStrictMode, defaultPlaylistItemLimit, defaultAutoStart, defaultSplitByChapters, defaultChapterTemplate)
.subscribe({ .subscribe({
next: (response) => resolve(response), next: (response) => resolve(response),
error: (error) => reject(error) error: (error) => reject(error)