Add headless watcher and mark-watched features; update Dockerfile and docs

- Add app/headless_watcher.py and app/mark_watched.py
- Update main.py, ytdl.py, Dockerfile, docker-compose.yml
- Update DEPLOY.md, README.md, pyproject.toml, uv.lock
- Ignore /downloads and /metube-config/cookies in .gitignore
This commit is contained in:
tigeren 2026-08-07 05:39:28 +00:00
parent 159bf3b6e6
commit f3be397a96
11 changed files with 2200 additions and 1780 deletions

6
.gitignore vendored
View File

@ -51,3 +51,9 @@ pending*
__pycache__ __pycache__
.venv .venv
# Downloaded media
/downloads
# Cookies (sensitive)
/metube-config/cookies

View File

@ -1,5 +1,5 @@
docker build -t 192.168.2.212:3000/tigeren/metube:1.8 . docker build -t 192.168.2.212:3000/tigeren/metube:1.9 .
docker push 192.168.2.212:3000/tigeren/metube:1.8 docker push 192.168.2.212:3000/tigeren/metube:1.9
docker compose up -d --build --force-recreate docker compose up -d --build --force-recreate

View File

@ -1,43 +1,47 @@
FROM node:lts-alpine AS builder FROM node:lts-alpine AS builder
WORKDIR /metube WORKDIR /metube
COPY ui ./ COPY ui ./
RUN npm ci && \ RUN npm ci && \
node_modules/.bin/ng build --configuration production node_modules/.bin/ng build --configuration production
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 chromium nss freetype harfbuzz ca-certificates && \
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 --extra headless && \
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=0 ENV UID=0
ENV GID=0 ENV GID=0
ENV UMASK=022 ENV UMASK=022
ENV DOWNLOAD_DIR /downloads # Playwright settings for Alpine Chromium
ENV STATE_DIR /downloads/.metube ENV PLAYWRIGHT_BROWSERS_PATH=0
ENV TEMP_DIR /downloads ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser
VOLUME /downloads
EXPOSE 8081 ENV DOWNLOAD_DIR /downloads
ENV STATE_DIR /downloads/.metube
# Add build-time argument for version ENV TEMP_DIR /downloads
ARG VERSION=dev VOLUME /downloads
ENV METUBE_VERSION=$VERSION EXPOSE 8081
ENTRYPOINT ["/sbin/tini", "-g", "--", "./docker-entrypoint.sh"] # Add build-time argument for version
ARG VERSION=dev
ENV METUBE_VERSION=$VERSION
ENTRYPOINT ["/sbin/tini", "-g", "--", "./docker-entrypoint.sh"]

583
README.md
View File

@ -1,291 +1,292 @@
# 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).
* __MARK_WATCHED_ON_COMPLETE__: if `true`, videos will be marked as "watched" on the source website after successful download. Requires cookies to be configured for the website. Currently supported: PornHub. Defaults to `false`. Uses headless browser technique for sites where API is not available.
### 📁 Storage & Directories
### 📁 Storage & Directories
* __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`. * __DOWNLOAD_DIR__: Path to where the downloads will be saved. Defaults to `/downloads` in the Docker image, and `.` otherwise.
* __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`. * __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`.
* __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__: 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_EXCLUDE_REGEX__: Regular expression to exclude some custom directories from the dropdown. Empty regex disables exclusion. Defaults to `(^|/)[.@].*$`, which means directories starting with `.` or `@`. * __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`.
* __DOWNLOAD_DIRS_INDEXABLE__: If `true`, the download directories (__DOWNLOAD_DIR__ and __AUDIO_DOWNLOAD_DIR__) are indexable on the web server. Defaults to `false`. * __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 `@`.
* __STATE_DIR__: Path to where the queue persistence files will be saved. Defaults to `/downloads/.metube` in the Docker image, and `.` otherwise. * __DOWNLOAD_DIRS_INDEXABLE__: If `true`, the download directories (__DOWNLOAD_DIR__ and __AUDIO_DOWNLOAD_DIR__) are indexable on the web server. Defaults to `false`.
* __TEMP_DIR__: Path where intermediary download files will be saved. Defaults to `/downloads` 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.
* Set this to an SSD or RAM filesystem (e.g., `tmpfs`) for better performance. * __TEMP_DIR__: Path where intermediary download files will be saved. Defaults to `/downloads` in the Docker image, and `.` otherwise.
* __Note__: Using a RAM filesystem may prevent downloads from being resumed. * 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.
### 📝 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_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__: 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_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_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`.
* __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`. * __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_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__: 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.
### 🌐 Web Server & URLs
### 🌐 Web Server & URLs
* __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. * __URL_PREFIX__: Base path for the web server (for use when hosting behind a reverse proxy). Defaults to `/`.
* __PUBLIC_HOST_AUDIO_URL__: Same as PUBLIC_HOST_URL but for audio downloads. * __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.
* __HTTPS__: Use `https` instead of `http` (__CERTFILE__ and __KEYFILE__ required). Defaults to `false`. * __PUBLIC_HOST_AUDIO_URL__: Same as PUBLIC_HOST_URL but for audio downloads.
* __CERTFILE__: HTTPS certificate file path. * __HTTPS__: Use `https` instead of `http` (__CERTFILE__ and __KEYFILE__ required). Defaults to `false`.
* __KEYFILE__: HTTPS key file path. * __CERTFILE__: HTTPS certificate file path.
* __ROBOTS_TXT__: A path to a `robots.txt` file mounted in the container. * __KEYFILE__: HTTPS key file path.
* __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`.
* __GID__: Group under which MeTube will run. Defaults to `1000`. * __UID__: User under which MeTube will run. Defaults to `1000`.
* __UMASK__: Umask value used by MeTube. Defaults to `022`. * __GID__: Group under which MeTube will run. Defaults to `1000`.
* __DEFAULT_THEME__: Default theme to use for the UI, can be set to `light`, `dark`, or `auto`. Defaults to `auto`. * __UMASK__: Umask value used by MeTube. Defaults to `022`.
* __LOGLEVEL__: Log level, can be set to `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`, or `NONE`. Defaults to `INFO`. * __DEFAULT_THEME__: Default theme to use for the UI, can be set to `light`, `dark`, or `auto`. Defaults to `auto`.
* __ENABLE_ACCESSLOG__: Whether to enable access log. Defaults to `false`. * __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`.
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) The project's Wiki contains examples of useful configurations contributed by users of MeTube:
* [OUTPUT_TEMPLATE Cookbook](https://github.com/alexta69/metube/wiki/OUTPUT_TEMPLATE-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)
## 🍪 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
volumes: ```yaml
- /path/to/cookies:/cookies volumes:
environment: - /path/to/cookies:/cookies
- YTDL_OPTIONS={"cookiefile":"/cookies/cookies.txt"} environment:
``` - YTDL_OPTIONS={"cookiefile":"/cookies/cookies.txt"}
```
* Install in your browser an extension to extract cookies:
* [Firefox](https://addons.mozilla.org/en-US/firefox/addon/export-cookies-txt/) * Install in your browser an extension to extract cookies:
* [Chrome](https://chrome.google.com/webstore/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc) * [Firefox](https://addons.mozilla.org/en-US/firefox/addon/export-cookies-txt/)
* Extract the cookies you need with the extension and rename the file `cookies.txt` * [Chrome](https://chrome.google.com/webstore/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc)
* Drop the file in the folder you configured in the docker-compose.yml above * Extract the cookies you need with the extension and rename the file `cookies.txt`
* Restart the container * Drop the file in the folder you configured in the docker-compose.yml above
* 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
environment: ```yaml
- 'YTDL_OPTIONS={"format": "best", "exec": "ffmpeg -i %(filepath)q -c:v libx264 -c:a aac %(filepath)q.h264.mp4"}' environment:
``` - '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:!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
``` 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:(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
``` 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:!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
``` 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:(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
``` 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
services: ```yaml
metube: services:
image: ghcr.io/alexta69/metube metube:
container_name: metube image: ghcr.io/alexta69/metube
restart: unless-stopped container_name: metube
ports: restart: unless-stopped
- "8081:8081" ports:
volumes: - "8081:8081"
- /path/to/downloads:/downloads volumes:
- /path/to/ssl/crt:/ssl/crt.pem - /path/to/downloads:/downloads
- /path/to/ssl/key:/ssl/key.pem - /path/to/ssl/crt:/ssl/crt.pem
environment: - /path/to/ssl/key:/ssl/key.pem
- HTTPS=true environment:
- CERTFILE=/ssl/crt.pem - HTTPS=true
- KEYFILE=/ssl/key.pem - CERTFILE=/ssl/crt.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
location /metube/ { ```nginx
proxy_pass http://metube:8081; location /metube/ {
proxy_http_version 1.1; proxy_pass http://metube:8081;
proxy_set_header Upgrade $http_upgrade; proxy_http_version 1.1;
proxy_set_header Connection "upgrade"; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host; proxy_set_header Connection "upgrade";
} 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
# For putting in your Apache sites site.conf ```apache
# Serves MeTube under a /metube/ subdir (http://yourdomain.com/metube/) # For putting in your Apache sites site.conf
<Location /metube/> # Serves MeTube under a /metube/ subdir (http://yourdomain.com/metube/)
ProxyPass http://localhost:8081/ retry=0 timeout=30 <Location /metube/>
ProxyPassReverse http://localhost:8081/ ProxyPass http://localhost:8081/ retry=0 timeout=30
</Location> ProxyPassReverse http://localhost:8081/
</Location>
<Location /metube/socket.io>
RewriteEngine On <Location /metube/socket.io>
RewriteCond %{QUERY_STRING} transport=websocket [NC] RewriteEngine On
RewriteRule /(.*) ws://localhost:8081/socket.io/$1 [P,L] RewriteCond %{QUERY_STRING} transport=websocket [NC]
ProxyPass http://localhost:8081/socket.io retry=0 timeout=30 RewriteRule /(.*) ws://localhost:8081/socket.io/$1 [P,L]
ProxyPassReverse http://localhost:8081/socket.io ProxyPass http://localhost:8081/socket.io retry=0 timeout=30
</Location> ProxyPassReverse http://localhost:8081/socket.io
``` </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
example.com { ```caddyfile
route /metube/* { example.com {
uri strip_prefix metube route /metube/* {
reverse_proxy metube:8081 uri strip_prefix metube
} 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/containrrr/watchtower) for this purpose.
I recommend installing and setting up [watchtower](https://github.com/containrrr/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
docker exec -ti metube sh ```bash
cd /downloads docker exec -ti metube sh
``` 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 and Python 3.13 installed.
Make sure you have Node.js and Python 3.13 installed.
```bash
cd metube/ui ```bash
# install Angular and build the UI cd metube/ui
npm install # install Angular and build the UI
node_modules/.bin/ng build npm install
# install python dependencies node_modules/.bin/ng build
cd .. # install python dependencies
curl -LsSf https://astral.sh/uv/install.sh | sh cd ..
uv sync curl -LsSf https://astral.sh/uv/install.sh | sh
# run uv sync
uv run python3 app/main.py # run
``` 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
docker build -t metube . ```bash
``` 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`).

144
app/headless_watcher.py Normal file
View File

@ -0,0 +1,144 @@
"""
Mark videos as watched using a headless browser.
Visiting the page with authenticated cookies triggers the watch tracking JavaScript.
"""
import os
import re
import logging
import asyncio
from urllib.parse import urlparse, parse_qs
from typing import Optional, Dict
log = logging.getLogger("headless_watcher")
# Try to import playwright
try:
from playwright.async_api import async_playwright
HAS_PLAYWRIGHT = True
except ImportError:
HAS_PLAYWRIGHT = False
log.warning("Playwright not installed, headless watching will not work")
class HeadlessWatcher:
"""Uses headless browser to visit pages and trigger watch tracking."""
def __init__(self, cookie_file: str):
self.cookie_file = cookie_file
self.domain_cookies = self._parse_cookie_file()
def _parse_cookie_file(self) -> Dict[str, list]:
"""Parse Netscape cookie file and group by domain."""
cookies_by_domain = {}
if not os.path.exists(self.cookie_file):
log.warning(f"Cookie file not found: {self.cookie_file}")
return cookies_by_domain
try:
with open(self.cookie_file, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("\t")
if len(parts) >= 7:
domain = parts[0].lstrip(".")
path = parts[2]
secure = parts[3] == "TRUE"
name = parts[5]
value = parts[6]
if domain not in cookies_by_domain:
cookies_by_domain[domain] = []
cookies_by_domain[domain].append({
"name": name,
"value": value,
"domain": parts[0],
"path": path,
"secure": secure,
"httpOnly": False,
})
log.debug(f"Parsed cookies for {len(cookies_by_domain)} domains")
except Exception as e:
log.error(f"Error parsing cookie file: {e}")
return cookies_by_domain
async def visit_page(self, url: str, wait_seconds: int = 5) -> bool:
"""Visit a page with cookies to trigger watch tracking."""
if not HAS_PLAYWRIGHT:
log.error("Playwright not installed")
return False
parsed_url = urlparse(url)
domain = parsed_url.netloc.lower()
cookies = []
for cookie_domain, domain_cookies in self.domain_cookies.items():
if domain in cookie_domain or cookie_domain in domain:
cookies.extend(domain_cookies)
if not cookies:
log.warning(f"No cookies found for domain: {domain}")
return False
log.info(f"Visiting {url} with {len(cookies)} cookies")
try:
async with async_playwright() as p:
# Use system Chromium if available (for Alpine/Docker)
chromium_path = os.environ.get("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")
if chromium_path and os.path.exists(chromium_path):
log.debug(f"Using system Chromium: {chromium_path}")
browser = await p.chromium.launch(headless=True, executable_path=chromium_path)
else:
browser = await p.chromium.launch(headless=True)
try:
context = await browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
)
await context.add_cookies(cookies)
page = await context.new_page()
response = await page.goto(url, wait_until="networkidle", timeout=30000)
if response and response.status == 200:
log.debug(f"Page loaded, waiting {wait_seconds}s")
await asyncio.sleep(wait_seconds)
log.info("Successfully triggered watch tracking")
return True
else:
status = response.status if response else "no response"
log.warning(f"Failed to load page, status: {status}")
return False
finally:
await browser.close()
except Exception as e:
log.error(f"Error in headless browser: {e}")
return False
class PHEadlessWatcher(HeadlessWatcher):
"""PornHub specific headless watcher."""
DOMAINS = ["pornhub.com", "www.pornhub.com", "de.pornhub.com", "fr.pornhub.com", "es.pornhub.com", "it.pornhub.com", "rt.pornhub.com"]
def can_handle(self, url: str) -> bool:
parsed = urlparse(url)
domain = parsed.netloc.lower()
return any(d in domain for d in self.DOMAINS)
async def mark_watched(self, url: str, wait_seconds: int = 5) -> bool:
return await self.visit_page(url, wait_seconds=wait_seconds)
async def headless_mark_watched(url: str, cookie_file: str, wait_seconds: int = 5) -> bool:
"""Mark a video as watched using headless browser."""
if not HAS_PLAYWRIGHT:
log.error("Playwright is not installed")
return False
# Try PH handler first
ph_handler = PHHeadlessWatcher(cookie_file)
if ph_handler.can_handle(url):
return await ph_handler.mark_watched(url, wait_seconds)
# Fallback to generic handler
generic_handler = HeadlessWatcher(cookie_file)
return await generic_handler.visit_page(url, wait_seconds)

File diff suppressed because it is too large Load Diff

228
app/mark_watched.py Normal file
View File

@ -0,0 +1,228 @@
"""
Mark videos as watched on various websites after successful download.
Uses the same cookies that were used for downloading.
"""
import os
import re
import logging
from urllib.parse import urlparse, parse_qs
from typing import Optional, Dict, Callable
from headless_watcher import headless_mark_watched, HAS_PLAYWRIGHT
log = logging.getLogger("mark_watched")
# Try to import curl_cffi for better impersonation, fallback to requests
try:
from curl_cffi import requests as curl_requests
HAS_CURL_CFFI = True
except ImportError:
HAS_CURL_CFFI = False
import requests
class MarkWatchedHandler:
"""Base class for mark-as-watched handlers."""
def __init__(self, cookie_file: str):
self.cookie_file = cookie_file
def can_handle(self, url: str) -> bool:
"""Check if this handler can handle the given URL."""
raise NotImplementedError
async def mark_watched(self, url: str) -> bool:
"""Mark the video as watched. Returns True on success."""
raise NotImplementedError
def _load_cookies(self) -> Dict[str, str]:
"""Load cookies from the Netscape cookie file."""
cookies = {}
if not os.path.exists(self.cookie_file):
log.warning(f"Cookie file not found: {self.cookie_file}")
return cookies
try:
with open(self.cookie_file, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
# Netscape format: domain flag path secure expiration name value
parts = line.split("\t")
if len(parts) >= 7:
name = parts[5]
value = parts[6]
cookies[name] = value
log.debug(f"Loaded {len(cookies)} cookies from {self.cookie_file}")
except Exception as e:
log.error(f"Error loading cookies: {e}")
return cookies
def _make_request(self, method: str, url: str, **kwargs) -> Optional[object]:
"""Make HTTP request using curl_cffi if available, else requests."""
try:
if HAS_CURL_CFFI:
# Use curl_cffi for better impersonation
session = curl_requests.Session()
# Set browser impersonation
session.impersonate = "chrome124"
response = session.request(method, url, **kwargs)
return response
else:
return requests.request(method, url, **kwargs)
except Exception as e:
log.error(f"Request failed: {e}")
return None
class PHHandler(MarkWatchedHandler):
"""Handler for PornHub."""
DOMAINS = ["pornhub.com", "www.pornhub.com", "de.pornhub.com", "fr.pornhub.com", "es.pornhub.com", "it.pornhub.com", "rt.pornhub.com"]
def can_handle(self, url):
parsed = urlparse(url)
domain = parsed.netloc.lower()
return any(d in domain for d in self.DOMAINS)
async def mark_watched(self, url):
# Extract viewkey from URL
parsed = urlparse(url)
params = parse_qs(parsed.query)
viewkey = params.get("viewkey", [None])[0]
if not viewkey:
# Try to extract from path
match = re.search(r"viewkey=([^&]+)", url)
if match:
viewkey = match.group(1)
if not viewkey:
log.warning(f"Could not extract viewkey from URL: {url}")
return False
log.info(f"Marking video as watched, viewkey: {viewkey}")
# Load cookies
cookies = self._load_cookies()
if not cookies:
log.warning("No cookies available, cannot mark as watched")
return False
# Try multiple endpoints as PH may use different URLs
# First try the AJAX endpoint which is most commonly used
endpoints = [
# AJAX endpoint (most common)
("POST", f"https://www.pornhub.com/user/watched/add/video/{viewkey}"),
# Alternative format
("GET", f"https://www.pornhub.com/user/watched/add/video/{viewkey}"),
# Legacy endpoint
("POST", f"https://www.pornhub.com/user/watched/video/viewkey/{viewkey}"),
]
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "en-US,en;q=0.9",
"X-Requested-With": "XMLHttpRequest",
"Referer": url,
}
for method, api_url in endpoints:
log.debug(f"Trying {method} {api_url}")
response = self._make_request(method, api_url, headers=headers, cookies=cookies, allow_redirects=True)
if response is None:
continue
log.debug(f"Response status: {response.status_code}")
if response.status_code == 200:
log.info(f"Successfully marked video as watched using {api_url}")
return True
elif response.status_code == 302:
# Redirect often means success on PH
log.info(f"Successfully marked video as watched (redirect from {api_url})")
return True
# API methods failed, try headless browser as fallback
log.info("API methods failed, trying headless browser approach")
if HAS_PLAYWRIGHT:
return await headless_mark_watched(url, self.cookie_file, wait_seconds=5)
else:
log.warning("Playwright not available for headless browser fallback")
return False
class YouTubeHandler(MarkWatchedHandler):
"""Handler for YouTube - uses YouTube API or internal endpoints."""
DOMAINS = ["youtube.com", "www.youtube.com", "youtu.be", "m.youtube.com"]
def can_handle(self, url):
parsed = urlparse(url)
domain = parsed.netloc.lower()
return any(d in domain for d in self.DOMAINS)
async def mark_watched(self, url):
# YouTube marking as watched requires more complex handling
# typically done through the browse endpoint with protobuf
# This is a simplified implementation
log.info("YouTube mark-as-watched not yet fully implemented")
return False
# Registry of all handlers
HANDLERS = [
PHHandler,
YouTubeHandler,
]
def get_handler(url: str, cookie_file: str) -> Optional[MarkWatchedHandler]:
"""
Get the appropriate handler for a URL.
Args:
url: The video URL
cookie_file: Path to the Netscape cookie file
Returns:
Handler instance if found, None otherwise
"""
if not cookie_file or not os.path.exists(cookie_file):
return None
for handler_class in HANDLERS:
handler = handler_class(cookie_file)
if handler.can_handle(url):
return handler
return None
async def mark_watched(url: str, cookie_file: str) -> bool:
"""
Mark a video as watched on its respective site.
Args:
url: The video URL
cookie_file: Path to the Netscape cookie file
Returns:
True if successfully marked as watched, False otherwise
"""
handler = get_handler(url, cookie_file)
if not handler:
log.debug(f"No mark-watched handler available for URL: {url}")
return False
try:
return await handler.mark_watched(url)
except Exception as e:
log.error(f"Error marking video as watched: {e}")
return False

File diff suppressed because it is too large Load Diff

View File

@ -73,6 +73,9 @@ services:
# Optional: robots.txt # Optional: robots.txt
# - ROBOTS_TXT=/app/robots.txt # - ROBOTS_TXT=/app/robots.txt
# MARK_WATCHED_ON_COMPLETE
- MARK_WATCHED_ON_COMPLETE=true
# Optional: health check # Optional: health check
healthcheck: healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8081/version"] test: ["CMD", "curl", "-f", "http://localhost:8081/version"]

View File

@ -16,3 +16,8 @@ dependencies = [
dev = [ dev = [
"pylint", "pylint",
] ]
[project.optional-dependencies]
headless = [
"playwright",
]

12
uv.lock
View File

@ -744,11 +744,11 @@ wheels = [
[[package]] [[package]]
name = "yt-dlp" name = "yt-dlp"
version = "2025.12.8" version = "2026.2.21"
source = { registry = "https://pypi.org/simple" } source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/14/77/db924ebbd99d0b2b571c184cb08ed232cf4906c6f9b76eed763cd2c84170/yt_dlp-2025.12.8.tar.gz", hash = "sha256:b773c81bb6b71cb2c111cfb859f453c7a71cf2ef44eff234ff155877184c3e4f", size = 3088947, upload-time = "2025-12-08T00:16:01.649Z" } sdist = { url = "https://files.pythonhosted.org/packages/58/d9/55ffff25204733e94a507552ad984d5a8a8e4f9d1f0d91763e6b1a41c79b/yt_dlp-2026.2.21.tar.gz", hash = "sha256:4407dfc1a71fec0dee5ef916a8d4b66057812939b509ae45451fa8fb4376b539", size = 3116630, upload-time = "2026-02-21T20:40:53.522Z" }
wheels = [ wheels = [
{ url = "https://files.pythonhosted.org/packages/6e/2f/98c3596ad923f8efd32c90dca62e241e8ad9efcebf20831173c357042ba0/yt_dlp-2025.12.8-py3-none-any.whl", hash = "sha256:36e2584342e409cfbfa0b5e61448a1c5189e345cf4564294456ee509e7d3e065", size = 3291464, upload-time = "2025-12-08T00:15:58.556Z" }, { url = "https://files.pythonhosted.org/packages/5a/40/664c99ee36d80d84ce7a96cd98aebcb3d16c19e6c3ad3461d2cf5424040e/yt_dlp-2026.2.21-py3-none-any.whl", hash = "sha256:0d8408f5b6d20487f5caeb946dfd04f9bcd2f1a3a125b744a0a982b590e449f7", size = 3313392, upload-time = "2026-02-21T20:40:51.514Z" },
] ]
[package.optional-dependencies] [package.optional-dependencies]
@ -769,9 +769,9 @@ default = [
[[package]] [[package]]
name = "yt-dlp-ejs" name = "yt-dlp-ejs"
version = "0.3.2" version = "0.5.0"
source = { registry = "https://pypi.org/simple" } source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/de/72/57d02cf78eb45126bd171298d6a58a5bd48ce1a398b6b7ff00fc904f1f0c/yt_dlp_ejs-0.3.2.tar.gz", hash = "sha256:31a41292799992bdc913e03c9fac2a8c90c82a5cbbc792b2e3373b01da841e3e", size = 34678, upload-time = "2025-12-07T23:44:48.258Z" } sdist = { url = "https://files.pythonhosted.org/packages/6b/0d/b9e4ab1b47cdeba0842df634b74b3c0144307640ad5b632a5e189c4ab7ce/yt_dlp_ejs-0.5.0.tar.gz", hash = "sha256:8dfae59e418232f485253dcf8e197fefa232423c3af7824fe19e4517b173293b", size = 98925, upload-time = "2026-02-21T19:29:16.844Z" }
wheels = [ wheels = [
{ url = "https://files.pythonhosted.org/packages/9d/0d/1f0d7a735ca60b87953271b15d00eff5eef05f6118390ddf6f81982526ed/yt_dlp_ejs-0.3.2-py3-none-any.whl", hash = "sha256:f2dc6b3d1b909af1f13e021621b0af048056fca5fb07c4db6aa9bbb37a4f66a9", size = 53252, upload-time = "2025-12-07T23:44:46.605Z" }, { url = "https://files.pythonhosted.org/packages/7e/5b/1283356b70d4893a8a050cee15092e1b08ea15310b94365f88067146721b/yt_dlp_ejs-0.5.0-py3-none-any.whl", hash = "sha256:674fc0efea741d3100cdf3f0f9e123150715ee41edf47ea7a62fbdeda204bdec", size = 54032, upload-time = "2026-02-21T19:29:15.408Z" },
] ]