Compare commits

..

1 Commits

Author SHA1 Message Date
maxid
f5761bc661 run the container as the user configured if not starting as root 2026-02-04 18:50:52 +01:00
125 changed files with 4734 additions and 3852 deletions

View File

@@ -53,5 +53,5 @@ YOUR CONFIG HERE
```
- [ ] I understand, that without logs and/or screenshots and a detailed description of the problem, it is very hard to fix bugs.
- [ ] I have checked the [documentation](https://maxdorninger.github.io/MediaManager/) for help.
- [ ] I have checked the [documentation](https://maximilian-dorninger.gitbook.io/mediamanager) for help.
- [ ] I have searched the [issues](https://github.com/maxdorninger/MediaManager/issues) for similar issues and found none.

View File

@@ -1,31 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
- package-ecosystem: "npm"
directory: "/web"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
- package-ecosystem: "uv"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
- package-ecosystem: "uv"
directory: "/metadata_relay"
schedule:
interval: "weekly"
open-pull-requests-limit: 5

View File

@@ -85,7 +85,7 @@ jobs:
run: echo "name=$(echo '${{ github.event.repository.name }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
with:
install: true
driver-opts: image=moby/buildkit:rootless
@@ -171,7 +171,7 @@ jobs:
run: echo "name=$(echo '${{ github.event.repository.name }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3

View File

@@ -50,7 +50,7 @@ jobs:
run: echo "name=$(echo '${{ github.event.repository.name }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
with:
install: true
driver-opts: image=moby/buildkit:rootless
@@ -135,7 +135,7 @@ jobs:
run: echo "name=$(echo '${{ github.event.repository.name }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3

View File

@@ -1,62 +0,0 @@
name: Publish docs via GitHub Pages
on:
push:
branches:
- master
tags:
- v*
workflow_dispatch:
inputs:
set_default_alias:
description: 'Alias to set as default (e.g. latest, master)'
required: false
default: 'latest'
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Configure Git Credentials
run: |
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
- uses: actions/setup-python@v6
with:
python-version: 3.x
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- uses: actions/cache@v4
with:
key: mkdocs-material-${{ env.cache_id }}
path: .cache
restore-keys: |
mkdocs-material-
- name: Install dependencies
run: pip install mkdocs-material mike
- name: Deploy (master)
if: github.ref == 'refs/heads/master'
run: |
mike deploy --push --update-aliases master
- name: Deploy (tag)
if: startsWith(github.ref, 'refs/tags/v')
run: |
version=${GITHUB_REF#refs/tags/}
mike deploy --push --update-aliases $version latest --title "$version"
mike set-default --push latest
- name: Set Default (Manual)
if: github.event_name == 'workflow_dispatch' && github.event.inputs.set_default_alias != ''
run: |
mike set-default --push ${{ github.event.inputs.set_default_alias }}

4
.gitignore vendored
View File

@@ -49,5 +49,5 @@ __pycache__
# Postgres
/postgres
# MkDocs
site/
# Node modules
/node_modules/*

View File

@@ -18,7 +18,7 @@ Generally, if you have any questions or need help on the implementation side of
just ask in the issue, or in a draft PR.
Also, see the contribution guide in the docs for information on how to setup the dev environment:
https://maxdorninger.github.io/MediaManager/
https://maximilian-dorninger.gitbook.io/mediamanager
### For something that is a one or two line fix:

View File

@@ -1,7 +1,7 @@
<br />
<div align="center">
<a href="https://maxdorninger.github.io/MediaManager/">
<img src="https://raw.githubusercontent.com/maxdorninger/MediaManager/refs/heads/master/docs/assets/logo-with-text.svg" alt="Logo" width="800">
<a href="https://maximilian-dorninger.gitbook.io/mediamanager">
<img src="https://github.com/maxdorninger/MediaManager/blob/master/web/static/logo.svg" alt="Logo" width="260" height="260">
</a>
<h3 align="center">MediaManager</h3>
@@ -9,7 +9,7 @@
<p align="center">
Modern management system for your media library
<br />
<a href="https://maxdorninger.github.io/MediaManager/"><strong>Explore the docs »</strong></a>
<a href="https://maximilian-dorninger.gitbook.io/mediamanager"><strong>Explore the docs »</strong></a>
<br />
<a href="https://github.com/maxdorninger/MediaManager/issues/new?labels=bug&template=bug_report.md">Report Bug</a>
&middot;
@@ -35,7 +35,7 @@ wget -O ./config/config.toml https://github.com/maxdorninger/MediaManager/releas
docker compose up -d
```
### [View the docs for installation instructions and more](https://maxdorninger.github.io/MediaManager/)
### [View the docs for installation instructions and more](https://maximilian-dorninger.gitbook.io/mediamanager)
## Support MediaManager
@@ -60,7 +60,6 @@ docker compose up -d
<a href="https://buymeacoffee.com/maxdorninger"><img src="https://cdn.buymeacoffee.com/uploads/profile_pictures/default/v2/DEBBB9/JO.png" width="80px" alt="Josh" /></a>&nbsp;&nbsp;
<a href="https://buymeacoffee.com/maxdorninger"><img src="https://cdn.buymeacoffee.com/uploads/profile_pictures/2025/11/2VeQ8sTGPhj4tiLy.jpg" width="80px" alt="PuppiestDoggo" /></a>&nbsp;&nbsp;
<a href="https://github.com/seferino-fernandez"><img src="https://avatars.githubusercontent.com/u/5546622" width="80px" alt="Seferino" /></a>&nbsp;&nbsp;
<a href="https://buymeacoffee.com/maxdorninger"><img src="https://cdn.buymeacoffee.com/uploads/profile_pictures/default/v2/EC9689/SY.png" width="80px" alt="syn" /></a>&nbsp;&nbsp;
## Star History
@@ -81,7 +80,7 @@ docker compose up -d
## Developer Quick Start
For the developer guide see the [Developer Guide](https://maxdorninger.github.io/MediaManager/).
For the developer guide see the [Developer Guide](https://maximilian-dorninger.gitbook.io/mediamanager).
<!-- LICENSE -->

View File

@@ -30,13 +30,14 @@ from media_manager.auth.db import OAuthAccount, User # noqa: E402
from media_manager.config import MediaManagerConfig # noqa: E402
from media_manager.database import Base # noqa: E402
from media_manager.indexer.models import IndexerQueryResult # noqa: E402
from media_manager.movies.models import Movie, MovieFile # noqa: E402
from media_manager.movies.models import Movie, MovieFile, MovieRequest # noqa: E402
from media_manager.notification.models import Notification # noqa: E402
from media_manager.torrent.models import Torrent # noqa: E402
from media_manager.tv.models import ( # noqa: E402
Episode,
EpisodeFile,
Season,
SeasonFile,
SeasonRequest,
Show,
)
@@ -46,13 +47,15 @@ target_metadata = Base.metadata
# noinspection PyStatementEffect
__all__ = [
"Episode",
"EpisodeFile",
"IndexerQueryResult",
"Movie",
"MovieFile",
"MovieRequest",
"Notification",
"OAuthAccount",
"Season",
"SeasonFile",
"SeasonRequest",
"Show",
"Torrent",
"User",

View File

@@ -1,46 +0,0 @@
"""create episode file table and add episode column to indexerqueryresult
Revision ID: 3a8fbd71e2c2
Revises: 9f3c1b2a4d8e
Create Date: 2026-01-08 13:43:00
"""
from typing import Sequence, Union
from alembic import op
from sqlalchemy.dialects import postgresql
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "3a8fbd71e2c2"
down_revision: Union[str, None] = "9f3c1b2a4d8e"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
quality_enum = postgresql.ENUM("uhd", "fullhd", "hd", "sd", "unknown", name="quality",
create_type=False,
)
# Create episode file table
op.create_table(
"episode_file",
sa.Column("episode_id", sa.UUID(), nullable=False),
sa.Column("torrent_id", sa.UUID(), nullable=True),
sa.Column("file_path_suffix", sa.String(), nullable=False),
sa.Column("quality", quality_enum, nullable=False),
sa.ForeignKeyConstraint(["episode_id"], ["episode.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["torrent_id"], ["torrent.id"], ondelete="SET NULL"),
sa.PrimaryKeyConstraint("episode_id", "file_path_suffix"),
)
# Add episode column to indexerqueryresult
op.add_column(
"indexer_query_result", sa.Column("episode", postgresql.ARRAY(sa.Integer()), nullable=True),
)
def downgrade() -> None:
op.drop_table("episode_file")
op.drop_column("indexer_query_result", "episode")

View File

@@ -1,31 +0,0 @@
"""add overview column to episode table
Revision ID: 9f3c1b2a4d8e
Revises: 2c61f662ca9e
Create Date: 2025-12-29 21:45:00
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "9f3c1b2a4d8e"
down_revision: Union[str, None] = "2c61f662ca9e"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# Add overview to episode table
op.add_column(
"episode",
sa.Column("overview", sa.Text(), nullable=True),
)
def downgrade() -> None:
op.drop_column("episode", "overview")

View File

@@ -1,71 +0,0 @@
"""migrate season files to episode files and drop the legacy table
Revision ID: a6f714d3c8b9
Revises: 16e78af9e5bf
Create Date: 2026-02-22 16:30:00
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = "a6f714d3c8b9"
down_revision: Union[str, None] = "3a8fbd71e2c2"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Copy season_file records into episode_file and remove the legacy table."""
op.execute(
"""
INSERT INTO episode_file (episode_id, torrent_id, file_path_suffix, quality)
SELECT episode.id, season_file.torrent_id, season_file.file_path_suffix, season_file.quality
FROM season_file
JOIN season ON season.id = season_file.season_id
JOIN episode ON episode.season_id = season.id
LEFT JOIN episode_file ON
episode_file.episode_id = episode.id
AND episode_file.file_path_suffix = season_file.file_path_suffix
WHERE episode_file.episode_id IS NULL
"""
)
op.drop_table("season_file")
def downgrade() -> None:
"""Recreate season_file, repopulate it from episode_file, and keep both tables."""
quality_enum = postgresql.ENUM(
"uhd", "fullhd", "hd", "sd", "unknown", name="quality", create_type=False
)
op.create_table(
"season_file",
sa.Column("season_id", sa.UUID(), nullable=False),
sa.Column("torrent_id", sa.UUID(), nullable=True),
sa.Column("file_path_suffix", sa.String(), nullable=False),
sa.Column("quality", quality_enum, nullable=False),
sa.ForeignKeyConstraint(["season_id"], ["season.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["torrent_id"], ["torrent.id"], ondelete="SET NULL"),
sa.PrimaryKeyConstraint("season_id", "file_path_suffix"),
)
op.execute(
"""
INSERT INTO season_file (season_id, torrent_id, file_path_suffix, quality)
SELECT DISTINCT ON (episode.season_id, episode_file.file_path_suffix)
episode.season_id,
episode_file.torrent_id,
episode_file.file_path_suffix,
episode_file.quality
FROM episode_file
JOIN episode ON episode.id = episode_file.episode_id
ORDER BY episode.season_id, episode_file.file_path_suffix, episode_file.torrent_id, episode_file.quality
"""
)

View File

@@ -1,65 +0,0 @@
"""remove requests
Revision ID: e60ae827ed98
Revises: a6f714d3c8b9
Create Date: 2026-02-22 18:07:12.866130
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = 'e60ae827ed98'
down_revision: Union[str, None] = 'a6f714d3c8b9'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('movie_request')
op.drop_table('season_request')
op.alter_column('episode', 'overview',
existing_type=sa.TEXT(),
type_=sa.String(),
existing_nullable=True)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('season_request',
sa.Column('id', sa.UUID(), autoincrement=False, nullable=False),
sa.Column('season_id', sa.UUID(), autoincrement=False, nullable=False),
sa.Column('wanted_quality', postgresql.ENUM('uhd', 'fullhd', 'hd', 'sd', 'unknown', name='quality'), autoincrement=False, nullable=False),
sa.Column('min_quality', postgresql.ENUM('uhd', 'fullhd', 'hd', 'sd', 'unknown', name='quality'), autoincrement=False, nullable=False),
sa.Column('requested_by_id', sa.UUID(), autoincrement=False, nullable=True),
sa.Column('authorized', sa.BOOLEAN(), autoincrement=False, nullable=False),
sa.Column('authorized_by_id', sa.UUID(), autoincrement=False, nullable=True),
sa.ForeignKeyConstraint(['authorized_by_id'], ['user.id'], name=op.f('season_request_authorized_by_id_fkey'), ondelete='SET NULL'),
sa.ForeignKeyConstraint(['requested_by_id'], ['user.id'], name=op.f('season_request_requested_by_id_fkey'), ondelete='SET NULL'),
sa.ForeignKeyConstraint(['season_id'], ['season.id'], name=op.f('season_request_season_id_fkey'), ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id', name=op.f('season_request_pkey')),
sa.UniqueConstraint('season_id', 'wanted_quality', name=op.f('season_request_season_id_wanted_quality_key'), postgresql_include=[], postgresql_nulls_not_distinct=False)
)
op.create_table('movie_request',
sa.Column('id', sa.UUID(), autoincrement=False, nullable=False),
sa.Column('movie_id', sa.UUID(), autoincrement=False, nullable=False),
sa.Column('wanted_quality', postgresql.ENUM('uhd', 'fullhd', 'hd', 'sd', 'unknown', name='quality'), autoincrement=False, nullable=False),
sa.Column('min_quality', postgresql.ENUM('uhd', 'fullhd', 'hd', 'sd', 'unknown', name='quality'), autoincrement=False, nullable=False),
sa.Column('authorized', sa.BOOLEAN(), autoincrement=False, nullable=False),
sa.Column('requested_by_id', sa.UUID(), autoincrement=False, nullable=True),
sa.Column('authorized_by_id', sa.UUID(), autoincrement=False, nullable=True),
sa.ForeignKeyConstraint(['authorized_by_id'], ['user.id'], name=op.f('movie_request_authorized_by_id_fkey'), ondelete='SET NULL'),
sa.ForeignKeyConstraint(['movie_id'], ['movie.id'], name=op.f('movie_request_movie_id_fkey'), ondelete='CASCADE'),
sa.ForeignKeyConstraint(['requested_by_id'], ['user.id'], name=op.f('movie_request_requested_by_id_fkey'), ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id', name=op.f('movie_request_pkey')),
sa.UniqueConstraint('movie_id', 'wanted_quality', name=op.f('movie_request_movie_id_wanted_quality_key'), postgresql_include=[], postgresql_nulls_not_distinct=False)
)
# ### end Alembic commands ###

View File

@@ -1,6 +1,6 @@
# MediaManager Dev Configuration File
# This file contains all available configuration options for MediaManager
# Documentation: https://maxdorninger.github.io/MediaManager/
# Documentation: https://maximilian-dorninger.gitbook.io/mediamanager
#
# This is an example configuration file that gets copied to your config folder
# on first boot. You should modify the values below to match your setup.
@@ -138,7 +138,7 @@ negate = false
[[indexers.title_scoring_rules]]
name = "avoid_cam"
keywords = ["cam", "camrip", "bdscr", "ddc", "dvdscreener","dvdscr", "hdcam", "hdtc", "hdts", "scr", "screener","telesync", "ts", "webscreener", "tc", "telecine", "tvrip"]
keywords = ["cam", "ts"]
score_modifier = -10000
negate = false

View File

@@ -1,6 +1,6 @@
# MediaManager Example Configuration File
# This file contains all available configuration options for MediaManager
# Documentation: https://maxdorninger.github.io/MediaManager/
# Documentation: https://maximilian-dorninger.gitbook.io/mediamanager
#
# This is an example configuration file that gets copied to your config folder
# on first boot. You should modify the values below to match your setup.
@@ -138,7 +138,7 @@ negate = false
[[indexers.title_scoring_rules]]
name = "avoid_cam"
keywords = ["cam", "camrip", "bdscr", "ddc", "dvdscreener","dvdscr", "hdcam", "hdtc", "hdts", "scr", "screener","telesync", "ts", "webscreener", "tc", "telecine", "tvrip"]
keywords = ["cam", "ts"]
score_modifier = -10000
negate = false

View File

@@ -56,15 +56,6 @@ services:
- ./web:/app
depends_on:
- mediamanager
docs:
image: squidfunk/mkdocs-material:9
container_name: mediamanager-docs
volumes:
- .:/docs
ports:
- "9000:9000"
command: serve -w /docs -a 0.0.0.0:9000
# ----------------------------
# Additional services can be uncommented and configured as needed
@@ -139,17 +130,17 @@ services:
# ports:
# - 8081:8080
# restart: unless-stopped
jackett:
image: lscr.io/linuxserver/jackett:latest
container_name: jackett
environment:
- PUID=1000
- PGID=1000
- TZ=Etc/UTC
- AUTO_UPDATE=true
volumes:
- ./res/jackett/data:/config
- ./res/jackett/torrents:/downloads
ports:
- 9117:9117
restart: unless-stopped
# jackett:
# image: lscr.io/linuxserver/jackett:latest
# container_name: jackett
# environment:
# - PUID=1000
# - PGID=1000
# - TZ=Etc/UTC
# - AUTO_UPDATE=true
# volumes:
# - ./res/jackett/data:/config
# - ./res/jackett/torrents:/downloads
# ports:
# - 9117:9117
# restart: unless-stopped

View File

Before

Width:  |  Height:  |  Size: 3.1 MiB

After

Width:  |  Height:  |  Size: 3.1 MiB

View File

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

View File

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 9.0 KiB

View File

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

View File

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 62 KiB

View File

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

View File

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

View File

Before

Width:  |  Height:  |  Size: 244 KiB

After

Width:  |  Height:  |  Size: 244 KiB

View File

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 24 KiB

View File

Before

Width:  |  Height:  |  Size: 113 KiB

After

Width:  |  Height:  |  Size: 113 KiB

View File

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 72 KiB

View File

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

Before

Width:  |  Height:  |  Size: 8.9 MiB

After

Width:  |  Height:  |  Size: 8.9 MiB

View File

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

View File

Before

Width:  |  Height:  |  Size: 5.5 MiB

After

Width:  |  Height:  |  Size: 5.5 MiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

View File

Before

Width:  |  Height:  |  Size: 7.6 MiB

After

Width:  |  Height:  |  Size: 7.6 MiB

View File

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 123 KiB

34
docs/README.md Normal file
View File

@@ -0,0 +1,34 @@
---
layout:
width: default
title:
visible: true
description:
visible: true
tableOfContents:
visible: true
outline:
visible: false
pagination:
visible: true
metadata:
visible: true
---
# MediaManager
MediaManager is the modern, easy-to-use successor to the fragmented "Arr" stack. Manage, discover, and automate your TV and movie collection in a single, simple interface.
_Replaces Sonarr, Radarr, Seerr, and more._
### Quick Links
<table data-view="cards" data-full-width="false"><thead><tr><th align="center"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td align="center">Installation Guide</td><td><a href="installation/">installation</a></td></tr><tr><td align="center">Configuration</td><td><a href="configuration/">configuration</a></td></tr><tr><td align="center">Developer Guide</td><td><a href="contributing-to-mediamanager/developer-guide.md">developer-guide.md</a></td></tr><tr><td align="center">Troubleshooting</td><td><a href="troubleshooting.md">troubleshooting.md</a></td></tr><tr><td align="center">Advanced Features</td><td><a href="advanced-features/">advanced-features</a></td></tr><tr><td align="center">Import Existing Media</td><td><a href="importing-existing-media.md">importing-existing-media.md</a></td></tr></tbody></table>
## Support MediaManager & Maximilian Dorninger
<table data-card-size="large" data-view="cards" data-full-width="false"><thead><tr><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="image">Cover image</th></tr></thead><tbody><tr><td>Sponsor me on GitHub Sponsors :)</td><td><a href="https://github.com/sponsors/maxdorninger">https://github.com/sponsors/maxdorninger</a></td><td></td></tr><tr><td>Buy me a coffee :)</td><td><a href="https://buymeacoffee.com/maxdorninger">https://buymeacoffee.com/maxdorninger</a></td><td></td></tr></tbody></table>
### MediaManager Sponsors
<table data-view="cards" data-full-width="false"><thead><tr><th>Sponsor</th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="image">Cover image</th></tr></thead><tbody><tr><td>Aljaž Mur Eržen</td><td><a href="https://fosstodon.org/@aljazmerzen">https://fosstodon.org/@aljazmerzen</a></td><td><a href="https://github.com/aljazerzen.png">https://github.com/aljazerzen.png</a></td></tr><tr><td>Luis Rodriguez</td><td><a href="https://github.com/ldrrp">https://github.com/ldrrp</a></td><td><a href="https://github.com/ldrrp.png">https://github.com/ldrrp.png</a></td></tr><tr><td>Brandon P.</td><td><a href="https://github.com/brandon-dacrib">https://github.com/brandon-dacrib</a></td><td><a href="https://github.com/brandon-dacrib.png">https://github.com/brandon-dacrib.png</a></td></tr><tr><td>SeimusS</td><td><a href="https://github.com/SeimusS">https://github.com/SeimusS</a></td><td><a href="https://github.com/SeimusS.png">https://github.com/SeimusS.png</a></td></tr><tr><td>HadrienKerlero</td><td><a href="https://github.com/HadrienKerlero">https://github.com/HadrienKerlero</a></td><td><a href="https://github.com/HadrienKerlero.png">https://github.com/HadrienKerlero.png</a></td></tr><tr><td>keyxmakerx</td><td><a href="https://github.com/keyxmakerx">https://github.com/keyxmakerx</a></td><td><a href="https://github.com/keyxmakerx.png">https://github.com/keyxmakerx.png</a></td></tr><tr><td>LITUATUI</td><td><a href="https://github.com/LITUATUI">https://github.com/LITUATUI</a></td><td><a href="https://github.com/LITUATUI.png">https://github.com/LITUATUI.png</a></td></tr><tr><td>Nicolas</td><td><a href="https://buymeacoffee.com/maxdorninger">https://buymeacoffee.com/maxdorninger</a></td><td><a href="https://cdn.buymeacoffee.com/uploads/profile_pictures/default/v2/B6CDBD/NI.png">https://cdn.buymeacoffee.com/uploads/profile_pictures/default/v2/B6CDBD/NI.png</a></td></tr><tr><td>Josh</td><td><a href="https://buymeacoffee.com/maxdorninger">https://buymeacoffee.com/maxdorninger</a></td><td><a href="https://cdn.buymeacoffee.com/uploads/profile_pictures/default/v2/DEBBB9/JO.png">https://cdn.buymeacoffee.com/uploads/profile_pictures/default/v2/DEBBB9/JO.png</a></td></tr><tr><td>PuppiestDoggo</td><td><a href="https://buymeacoffee.com/maxdorninger">https://buymeacoffee.com/maxdorninger</a></td><td><a href="https://cdn.buymeacoffee.com/uploads/profile_pictures/2025/11/2VeQ8sTGPhj4tiLy.jpg">https://cdn.buymeacoffee.com/uploads/profile_pictures/2025/11/2VeQ8sTGPhj4tiLy.jpg</a></td></tr><tr><td>Seferino</td><td><a href="https://github.com/seferino-fernandez">https://github.com/seferino-fernandez</a></td><td><a href="https://avatars.githubusercontent.com/u/5546622">https://avatars.githubusercontent.com/u/5546622</a></td></tr><tr><td>Powered by DigitalOcean</td><td><a href="https://m.do.co/c/4edf05429dca">https://m.do.co/c/4edf05429dca</a></td><td data-object-fit="contain"><a href="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_vertical_blue.svg">https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_vertical_blue.svg</a></td></tr></tbody></table>

33
docs/SUMMARY.md Normal file
View File

@@ -0,0 +1,33 @@
# Table of contents
* [MediaManager](README.md)
* [Installation Guide](installation/README.md)
* [Docker Compose](installation/docker.md)
* [Nix Flakes \[Community\]](installation/flakes.md)
* [Importing existing media](importing-existing-media.md)
* [Usage](usage.md)
* [Configuration](configuration/README.md)
* [Backend](configuration/backend.md)
* [Authentication](configuration/authentication.md)
* [Database](configuration/database.md)
* [Download Clients](configuration/download-clients.md)
* [Indexers](configuration/indexers.md)
* [Scoring Rulesets](configuration/scoring-rulesets.md)
* [Notifications](configuration/notifications.md)
* [Custom Libraries](configuration/custom-libraries.md)
* [Logging](configuration/logging.md)
* [Advanced Features](advanced-features/README.md)
* [qBittorrent Category](advanced-features/qbittorrent-category.md)
* [URL Prefix](advanced-features/url-prefix.md)
* [Metadata Provider Configuration](advanced-features/metadata-provider-configuration.md)
* [Custom port](advanced-features/custom-port.md)
* [Follow symlinks in frontend files](advanced-features/follow-symlinks-in-frontend-files.md)
* [Disable startup ascii art](advanced-features/disable-startup-ascii-art.md)
* [Troubleshooting](troubleshooting.md)
* [API Reference](api-reference.md)
* [Screenshots](screenshots.md)
## Contributing to MediaManager
* [Developer Guide](contributing-to-mediamanager/developer-guide.md)
* [Documentation](contributing-to-mediamanager/documentation.md)

View File

@@ -0,0 +1,9 @@
---
description: >-
The features in this section are not required to run MediaManager and serve
their purpose in very specific environments, but they can enhance your
experience and provide additional functionality.
---
# Advanced Features

View File

@@ -7,6 +7,8 @@ MediaManager can be configured to follow symlinks when serving frontend files. T
* `FRONTEND_FOLLOW_SYMLINKS`\
Set this environment variable to `true` to follow symlinks when serving frontend files. Default is `false`.
```bash title=".env"
{% code title=".env" %}
```bash
FRONTEND_FOLLOW_SYMLINKS=true
```
{% endcode %}

View File

@@ -8,8 +8,9 @@ Metadata provider settings are configured in the `[metadata]` section of your `c
TMDB (The Movie Database) is the primary metadata provider for MediaManager. It provides detailed information about movies and TV shows.
!!! info
Other software like Jellyfin use TMDB as well, so there won't be any metadata discrepancies.
{% hint style="info" %}
Other software like Jellyfin use TMDB as well, so there won't be any metadata discrepancies.
{% endhint %}
* `tmdb_relay_url`\
URL of the TMDB relay (MetadataRelay). Default is `https://metadata-relay.dorninger.co/tmdb`. Example: `https://your-own-relay.example.com/tmdb`.
@@ -18,21 +19,24 @@ TMDB (The Movie Database) is the primary metadata provider for MediaManager. It
* `default_language`\
TMDB language parameter used when searching and adding. Default is `en`. Format: ISO 639-1 (2 letters).
!!! warning
`default_language` sets the TMDB `language` parameter when searching and adding TV shows and movies. If TMDB does not find a matching translation, metadata in the original language will be fetched with no option for a fallback language. It is therefore highly advised to only use "broad" languages. For most use cases, the default setting is safest.
{% hint style="warning" %}
`default_language` sets the TMDB `language` parameter when searching and adding TV shows and movies. If TMDB does not find a matching translation, metadata in the original language will be fetched with no option for a fallback language. It is therefore highly advised to only use "broad" languages. For most use cases, the default setting is safest.
{% endhint %}
### TVDB Settings (`[metadata.tvdb]`)
!!! warning
The TVDB might provide false metadata and doesn't support some features of MediaManager like showing overviews. Therefore, TMDB is the preferred metadata provider.
{% hint style="warning" %}
The TVDB might provide false metadata and doesn't support some features of MediaManager like showing overviews. Therefore, TMDB is the preferred metadata provider.
{% endhint %}
* `tvdb_relay_url`\
URL of the TVDB relay (MetadataRelay). Default is `https://metadata-relay.dorninger.co/tvdb`. Example: `https://your-own-relay.example.com/tvdb`.
### MetadataRelay
!!! info
To use MediaManager you don't need to set up your own MetadataRelay, as the default relay hosted by the developer should be sufficient for most purposes.
{% hint style="info" %}
To use MediaManager you don't need to set up your own MetadataRelay, as the default relay hosted by the developer should be sufficient for most purposes.
{% endhint %}
The MetadataRelay is a service that provides metadata for MediaManager. It acts as a proxy for TMDB and TVDB, allowing you to use your own API keys if needed, but the default relay means you don't need to create accounts for API keys yourself.
@@ -43,14 +47,16 @@ You might want to use your own relay if you want to avoid rate limits, protect y
* Get a TMDB API key from [The Movie Database](https://www.themoviedb.org/settings/api)
* Get a TVDB API key from [The TVDB](https://thetvdb.com/auth/register)
!!! info
If you want to use your own MetadataRelay, you can set the `tmdb_relay_url` and/or `tvdb_relay_url` to your own relay service.
{% hint style="info" %}
If you want to use your own MetadataRelay, you can set the `tmdb_relay_url` and/or `tvdb_relay_url` to your own relay service.
{% endhint %}
### Example Configuration
Here's a complete example of the metadata section in your `config.toml`:
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[metadata]
# TMDB configuration
[metadata.tmdb]
@@ -60,6 +66,8 @@ Here's a complete example of the metadata section in your `config.toml`:
[metadata.tvdb]
tvdb_relay_url = "https://metadata-relay.dorninger.co/tvdb"
```
{% endcode %}
!!! info
In most cases, you can simply use the default values and don't need to specify these settings in your config file at all.
{% hint style="info" %}
In most cases, you can simply use the default values and don't need to specify these settings in your config file at all.
{% endhint %}

View File

@@ -9,8 +9,10 @@ Use the following variables to customize behavior:
* `torrents.qbittorrent.category_save_path`\
Save path for the category in qBittorrent. By default, no subdirectory is used. Example: `/data/torrents/MediaManager`.
!!! info
qBittorrent saves torrents to the path specified by `torrents.qbittorrent.category_save_path`, so it must be a valid path that qBittorrent can write to.
{% hint style="info" %}
qBittorrent saves torrents to the path specified by `torrents.qbittorrent.category_save_path`, so it must be a valid path that qBittorrent can write to.
{% endhint %}
!!! warning
For MediaManager to successfully import torrents, you must add the subdirectory to the `misc.torrent_directory` variable.
{% hint style="warning" %}
For MediaManager to successfully import torrents, you must add the subdirectory to the `misc.torrent_directory` variable.
{% endhint %}

View File

@@ -6,20 +6,23 @@ In order to run it on a prefixed path, like `maxdorninger.github.io/media`, the
In short, clone the repository, then run:
```none title="Build Docker image"
{% code title="Build Docker image" %}
```none
docker build \
--build-arg BASE_PATH=/media \
--build-arg VERSION=my-custom-version \
-t MediaManager:my-custom-version \
-f Dockerfile .
```
{% endcode %}
You also need to set the `BASE_PATH` environment variable at runtime in `docker-compose.yaml`:
* `BASE_PATH`\
Base path prefix MediaManager is served under. Example: `/media`. This must match the `BASE_PATH` build arg.
```yaml title="docker-compose.yaml (excerpt)"
{% code title="docker-compose.yaml (excerpt)" %}
```yaml
services:
mediamanager:
image: MediaManager:my-custom-version
@@ -29,8 +32,10 @@ services:
BASE_PATH: /media
...
```
{% endcode %}
!!! info
Make sure to include the base path in the `frontend_url` field in the config file. See [Backend](../configuration/backend.md).
{% hint style="info" %}
Make sure to include the base path in the `frontend_url` field in the config file. See [Backend](../configuration/backend.md).
{% endhint %}
Finally, ensure that whatever reverse proxy you're using leaves the incoming path unchanged; that is, you should not strip the `/media` from `/media/web/`.

View File

@@ -1,7 +1,8 @@
# API Reference
!!! info
Media Manager's backend is built with FastAPI, which automatically generates interactive API documentation.
{% hint style="info" %}
Media Manager's backend is built with FastAPI, which automatically generates interactive API documentation.
{% endhint %}
* Swagger UI (typically available at `http://localhost:8000/docs`)
* ReDoc (typically available at `http://localhost:8000/redoc`)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 108 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 110 KiB

View File

@@ -6,8 +6,9 @@ Frontend settings are configured through environment variables in your `docker-c
## Configuration File Location
!!! warning
Note that MediaManager may need to be restarted for changes in the config file to take effect.
{% hint style="warning" %}
Note that MediaManager may need to be restarted for changes in the config file to take effect.
{% endhint %}
Your `config.toml` file should be in the directory that's mounted to `/app/config/config.toml` inside the container:
@@ -65,5 +66,6 @@ MEDIAMANAGER_AUTH__OPENID_CONNECT__CLIENT_SECRET = "your_client_secret_from_prov
So for every config "level", you basically have to take the name of the value and prepend it with the section names in uppercase with 2 underscores as delimiters and `MEDIAMANAGER_` as the prefix.
!!! warning
Note that not every env variable starts with `MEDIAMANAGER_`; this prefix only applies to env variables which replace/overwrite values in the config file. Variables like the `CONFIG_DIR` env variable must not be prefixed.
{% hint style="warning" %}
Note that not every env variable starts with `MEDIAMANAGER_`; this prefix only applies to env variables which replace/overwrite values in the config file. Variables like the `CONFIG_DIR` env variable must not be prefixed.
{% endhint %}

View File

@@ -20,11 +20,13 @@ All authentication settings are configured in the `[auth]` section of your `conf
* `email_password_resets`\
Enables password resets via email. Default is `false`.
!!! info
To use email password resets, you must also configure SMTP settings in the `[notifications.smtp_config]` section.
{% hint style="info" %}
To use email password resets, you must also configure SMTP settings in the `[notifications.smtp_config]` section.
{% endhint %}
!!! info
When setting up MediaManager for the first time, you should add your email to `admin_emails` in the `[auth]` config section. MediaManager will then use this email instead of the default admin email. Your account will automatically be created as an admin account, allowing you to manage other users, media and settings.
{% hint style="info" %}
When setting up MediaManager for the first time, you should add your email to `admin_emails` in the `[auth]` config section. MediaManager will then use this email instead of the default admin email. Your account will automatically be created as an admin account, allowing you to manage other users, media and settings.
{% endhint %}
## OpenID Connect Settings (`[auth.openid_connect]`)
@@ -51,20 +53,22 @@ The OpenID server will likely require a redirect URI. This URL will usually look
{MEDIAMANAGER_URL}/api/v1/auth/oauth/callback
```
!!! warning
It is very important that you set the correct callback URI, otherwise it won't work!
{% hint style="warning" %}
It is very important that you set the correct callback URI, otherwise it won't work!
{% endhint %}
#### Authentik Example
Here is an example configuration for the OpenID Connect provider for Authentik.
![authentik-redirect-url-example](<../assets/assets/authentik redirect url example.png>)
![authentik-redirect-url-example](<../.gitbook/assets/authentik redirect url example.png>)
## Example Configuration
Here's a complete example of the authentication section in your `config.toml`:
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[auth]
token_secret = "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6"
session_lifetime = 604800 # 1 week
@@ -78,4 +82,4 @@ client_secret = "your-secret-key-here"
configuration_endpoint = "https://auth.example.com/.well-known/openid-configuration"
name = "Authentik"
```
{% endcode %}

View File

@@ -26,7 +26,8 @@ description: >-
Here's a complete example of the general settings section in your `config.toml`:
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[misc]
# REQUIRED: Change this to match your actual frontend domain.
@@ -37,6 +38,8 @@ cors_urls = ["http://localhost:8000"]
# Optional: Development mode (set to true for debugging)
development = false
```
{% endcode %}
!!! info
The `frontend_url` is the most important setting to configure correctly. Make sure it matches your actual deployment URLs.
{% hint style="info" %}
The `frontend_url` is the most important setting to configure correctly. Make sure it matches your actual deployment URLs.
{% endhint %}

View File

@@ -6,8 +6,9 @@ MediaManager supports custom libraries, allowing you to add multiple folders for
Custom libraries are configured in the `misc` section in the `config.toml` file. You can add as many libraries as you need.
!!! info
You are not limited to `/data/tv` or `/data/movies`, you can choose the entire path freely!
{% hint style="info" %}
You are not limited to `/data/tv` or `/data/movies`, you can choose the entire path freely!
{% endhint %}
### Movie Libraries

View File

@@ -19,7 +19,8 @@ Database settings are configured in the `[database]` section of your `config.tom
Here's a complete example of the database section in your `config.toml`:
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[database]
host = "db"
port = 5432
@@ -27,6 +28,8 @@ user = "MediaManager"
password = "your_secure_password"
dbname = "MediaManager"
```
{% endcode %}
!!! info
In docker-compose deployments the container name is simultaneously its hostname, so you can use "db" or "postgres" as host.
{% hint style="info" %}
In docker-compose deployments the container name is simultaneously its hostname, so you can use "db" or "postgres" as host.
{% endhint %}

View File

@@ -19,8 +19,9 @@ qBittorrent is a popular BitTorrent client that MediaManager can integrate with
## Transmission Settings (`[torrents.transmission]`)
!!! info
The downloads path in Transmission and MediaManager must be the same, i.e. the path `/data/torrents` must link to the same volume for both containers.
{% hint style="info" %}
The downloads path in Transmission and MediaManager must be the same, i.e. the path `/data/torrents` must link to the same volume for both containers.
{% endhint %}
Transmission is a BitTorrent client that MediaManager can integrate with for downloading torrents.
@@ -58,7 +59,8 @@ SABnzbd is a Usenet newsreader that MediaManager can integrate with for download
Here's a complete example of the download clients section in your `config.toml`:
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[torrents]
# qBittorrent configuration
[torrents.qbittorrent]
@@ -85,12 +87,14 @@ Here's a complete example of the download clients section in your `config.toml`:
port = 8080
api_key = "your_sabnzbd_api_key"
```
{% endcode %}
## Docker Compose Integration
When using Docker Compose, make sure your download clients are accessible from the MediaManager backend:
```yaml title="docker-compose.yml"
{% code title="docker-compose.yml" %}
```yaml
services:
# MediaManager backend
backend:
@@ -117,9 +121,12 @@ services:
- ./data/usenet:/downloads
# ... other configuration ...
```
{% endcode %}
!!! warning
You should enable only one BitTorrent and only one Usenet Download Client at any time.
{% hint style="warning" %}
You should enable only one BitTorrent and only one Usenet Download Client at any time.
{% endhint %}
!!! info
Make sure the download directories in your download clients are accessible to MediaManager for proper file management and organization.
{% hint style="info" %}
Make sure the download directories in your download clients are accessible to MediaManager for proper file management and organization.
{% endhint %}

View File

@@ -13,8 +13,9 @@ Indexer settings are configured in the `[indexers]` section of your `config.toml
* `timeout_seconds`\
Timeout in seconds for requests to Prowlarr. Default is `60`.
!!! warning
Symptoms of timeouts are typically no search results ("No torrents found!") in conjunction with logs showing read timeouts.
{% hint style="warning" %}
Symptoms of timeouts are typically no search results ("No torrents found!") in conjunction with logs showing read timeouts.
{% endhint %}
<details>
@@ -49,7 +50,8 @@ DEBUG - media_manager.indexer.utils -
## Example Configuration
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[indexers]
[indexers.prowlarr]
enabled = true
@@ -64,4 +66,4 @@ api_key = "your_jackett_api_key"
indexers = ["1337x", "rarbg"]
timeout_seconds = 60
```
{% endcode %}

View File

@@ -57,7 +57,8 @@ Controls which emails receive notifications.
Here's a complete example of the notifications section in your `config.toml`:
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[notifications]
# SMTP settings for email notifications and password resets
[notifications.smtp_config]
@@ -90,7 +91,8 @@ Here's a complete example of the notifications section in your `config.toml`:
api_key = "your_pushover_api_key"
user = "your_pushover_user_key"
```
{% endcode %}
!!! info
You can enable multiple notification methods simultaneously. For example, you could have both email and Gotify notifications enabled at the same time.
{% hint style="info" %}
You can enable multiple notification methods simultaneously. For example, you could have both email and Gotify notifications enabled at the same time.
{% endhint %}

View File

@@ -17,8 +17,9 @@ Rules define how MediaManager scores releases based on their titles or indexer f
* Reject releases that do not meet certain criteria (e.g., non-freeleech releases).
* and more.
!!! info
The keywords and flags are compared case-insensitively.
{% hint style="info" %}
The keywords and flags are compared case-insensitively.
{% endhint %}
### Title Rules
@@ -37,7 +38,8 @@ Each title rule consists of:
Examples for Title Rules
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[[indexers.title_scoring_rules]]
name = "prefer_h265"
keywords = ["h265", "hevc", "x265"]
@@ -50,6 +52,7 @@ keywords = ["cam", "ts"]
score_modifier = -10000
negate = false
```
{% endcode %}
* The first rule increases the score for releases containing "h265", "hevc", or "x265".
* The second rule heavily penalizes releases containing "cam" or "ts".
@@ -73,7 +76,8 @@ Each indexer flag rule consists of:
Examples for Indexer Flag Rules
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[[indexers.indexer_flag_scoring_rules]]
name = "reject_non_freeleech"
flags = ["freeleech", "freeleech75"]
@@ -86,6 +90,7 @@ flags = ["nuked"]
score_modifier = -10000
negate = false
```
{% endcode %}
* The first rule penalizes releases that do not have the "freeleech" or "freeleech75" flag.
* The second rule penalizes releases that are marked as "nuked".
@@ -94,7 +99,8 @@ If `negate` is set to `true`, the `score_modifier` is applied only if none of th
## Example
```toml title="config.toml"
{% code title="config.toml" %}
```toml
[[indexers.scoring_rule_sets]]
name = "default"
libraries = ["ALL_TV", "ALL_MOVIES"]
@@ -105,6 +111,7 @@ name = "strict_quality"
libraries = ["ALL_MOVIES"]
rule_names = ["prefer_h265", "avoid_cam", "reject_non_freeleech"]
```
{% endcode %}
## Libraries
@@ -120,8 +127,9 @@ You can use special library names in your rulesets:
This allows you to set global rules for all TV or movie content, or provide fallback rules for uncategorized media.
!!! info
You don't need to create lots of libraries with different directories, multiple libraries can share the same directory. You can set multiple (unlimited) libraries to the default directory `/data/movies` or `/data/tv` and use different rulesets with them.
{% hint style="info" %}
You don't need to create lots of libraries with different directories, multiple libraries can share the same directory. You can set multiple (unlimited) libraries to the default directory `/data/movies` or `/data/tv` and use different rulesets with them.
{% endhint %}
## Relation to Sonarr/Radarr Profiles

View File

@@ -10,7 +10,7 @@ description: >-
* `media_manager/`: Backend FastAPI application
* `web/`: Frontend SvelteKit application
* `docs/`: Documentation (MkDocs)
* `docs/`: Documentation (GitBook)
* `metadata_relay/`: Metadata relay service, also FastAPI
## Special Dev Configuration
@@ -44,8 +44,9 @@ MediaManager uses various environment variables for configuration. In the Docker
* `DISABLE_FRONTEND_MOUNT`\
When `TRUE`, disables mounting built frontend files (allows separate frontend container).
!!! info
This is automatically set in `docker-compose.dev.yaml` to enable the separate frontend development container
{% hint style="info" %}
This is automatically set in `docker-compose.dev.yaml` to enable the separate frontend development container
{% endhint %}
#### Configuration Files
@@ -104,9 +105,10 @@ This means when your browser makes a request to `http://localhost:5173/api/v1/tv
### Setting up the full development environment with Docker (Recommended)
This is the easiest and recommended way to get started. Everything runs in Docker with hot-reloading enabled.
{% stepper %}
{% step %}
### Prepare config files
Create config directory (only needed on first run) and copy example config files:
@@ -116,9 +118,9 @@ mkdir -p res/config # Only needed on first run
cp config.dev.toml res/config/config.toml
cp web/.env.example web/.env
```
{% endstep %}
{% step %}
### Start all services
Recommended: Use make commands for easy development
@@ -133,9 +135,9 @@ Alternative: Use docker compose directly (if make is not available)
```bash
docker compose -f docker-compose.dev.yaml up
```
{% endstep %}
{% step %}
### Access the application
* Frontend (with HMR): http://localhost:5173
@@ -149,10 +151,12 @@ Now you can edit code and see changes instantly:
* Edit Python files → Backend auto-reloads
* Edit Svelte/TypeScript files → Frontend HMR updates in browser
* Edit config.toml → Changes apply immediately
{% endstep %}
{% endstepper %}
!!! info
Run `make help` to see all available development commands including `make down`, `make logs`, `make app` (shell into backend), and more.
{% hint style="info" %}
Run `make help` to see all available development commands including `make down`, `make logs`, `make app` (shell into backend), and more.
{% endhint %}
## Setting up the backend development environment (Local)
@@ -213,17 +217,18 @@ ruff check .
## Setting up the frontend development environment (Local, Optional)
Using the Docker setup above is recommended. This section is for those who prefer to run the frontend locally outside of Docker.
{% stepper %}
{% step %}
### Clone & change dir
1. Clone the repository
2. cd into repo root
3. cd into `web` directory
{% endstep %}
{% step %}
### Install Node.js (example using nvm-windows)
I used nvm-windows:
@@ -238,9 +243,9 @@ If using PowerShell you may need:
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
```
{% endstep %}
{% step %}
### Create .env for frontend
```bash
@@ -248,18 +253,18 @@ cp .env.example .env
```
Update `PUBLIC_API_URL` if your backend is not at `http://localhost:8000`
{% endstep %}
{% step %}
### Install dependencies and run dev server
```bash
npm install
npm run dev
```
{% endstep %}
{% step %}
### Format & lint
* Format:
@@ -273,10 +278,12 @@ npm run format
```bash
npm run lint
```
{% endstep %}
{% endstepper %}
!!! info
If running frontend locally, make sure to add `http://localhost:5173` to the `cors_urls` in your backend config file.
{% hint style="info" %}
If running frontend locally, make sure to add `http://localhost:5173` to the `cors_urls` in your backend config file.
{% endhint %}
## Troubleshooting

View File

@@ -1,14 +1,11 @@
# Documentation
MediaManager uses [MkDocs](https://www.mkdocs.org/) with
the [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) theme for documentation.
MediaManager currently uses GitBook for documentation.
The files for the documentation are in the `/docs` directory.
The files for the documentation are in the \`/docs\` directory. They are \_mostly\_ standard markdown.
To preview the documentation locally, you need to have mkdocs or Docker installed.
Unfortunately GitBook doesn't provide a way to locally preview the documentation. Instead you can submit a PR with your proposed changes and a GitBook workflow will run which will provide a link to the preview.
## How to preview the documentation locally with docker
To access the preview just open the \`Details\` link.
1. Run the mkdocs container in `docker-compose.dev.yaml`
2. Open `http://127.0.0.1:9000/` in your browser.
<figure><img src="../.gitbook/assets/image.png" alt=""><figcaption></figcaption></figure>

View File

@@ -1,22 +0,0 @@
/*.md-header__button.md-logo {*/
/* margin-top: 0;*/
/* margin-bottom: 0;*/
/* padding-top: 0;*/
/* padding-bottom: 0;*/
/*}*/
/*.md-header__button.md-logo img,*/
/*.md-header__button.md-logo svg {*/
/* height: 70%;*/
/* width: 70%;*/
/*}*/
/* Increase logo size */
.md-header__button.md-logo svg, .md-header__button.md-logo img {
height: 2.5rem; /* Increase height (default is usually ~1.2rem to 1.5rem) */
width: auto;
}
/* Adjust header height if necessary to fit the larger logo */
.md-header {
height: 4rem; /* Match or exceed your new logo height */
}

View File

@@ -23,8 +23,9 @@ Here is an example, using these rules:
If your folder structure is in the correct format, you can start importing. To do this, log in as an administrator and go to the TV/movie dashboard.
!!! info
After importing, MediaManager will automatically prefix the old root TV show/movie folders with a dot to mark them as "imported".
{% hint style="info" %}
After importing, MediaManager will automatically prefix the old root TV show/movie folders with a dot to mark them as "imported".
{% endhint %}
So after importing, the directory would look like this (using the above directory structure):

View File

@@ -1,2 +0,0 @@
--8<-- "README.md"

View File

@@ -2,5 +2,4 @@
The recommended way to install and run Media Manager is using Docker and Docker Compose. Other installation methods are not officially supported, but listed here for convenience.
[Docker Compose (recommended)](docker.md){ .md-button .md-button--primary }
[Nix Flakes [Community]](flakes.md){ .md-button }
<table data-view="cards" data-full-width="false"><thead><tr><th align="center"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td align="center">Docker Compose (recommended)</td><td><a href="docker.md">docker.md</a></td></tr><tr><td align="center">Nix Flakes [Community]</td><td><a href="flakes.md">flakes.md</a></td></tr></tbody></table>

View File

@@ -9,8 +9,8 @@
Follow these steps to get MediaManager running with Docker Compose:
{% stepper %}
{% step %}
#### Get the docker-compose file
Download the `docker-compose.yaml` from the MediaManager repo:
@@ -18,9 +18,9 @@ Download the `docker-compose.yaml` from the MediaManager repo:
```bash
wget -O docker-compose.yaml https://github.com/maxdorninger/MediaManager/releases/latest/download/docker-compose.yaml
```
{% endstep %}
{% step %}
#### Prepare configuration directory and example config
Create a config directory and download the example configuration:
@@ -29,15 +29,15 @@ Create a config directory and download the example configuration:
mkdir config
wget -O ./config/config.toml https://github.com/maxdorninger/MediaManager/releases/latest/download/config.example.toml
```
{% endstep %}
{% step %}
#### Edit configuration
You probably need to edit the `config.toml` file in the `./config` directory to suit your environment and preferences. [How to configure MediaManager.](../configuration/README.md)
You probably need to edit the `config.toml` file in the `./config` directory to suit your environment and preferences. [How to configure MediaManager.](configuration/)
{% endstep %}
{% step %}
#### Start MediaManager
Bring up the stack:
@@ -45,15 +45,16 @@ Bring up the stack:
```bash
docker compose up -d
```
{% endstep %}
{% endstepper %}
* Upon first run, MediaManager will create a default `config.toml` file in the `./config` directory (if not already present).
* Upon first run, MediaManager will also create a default admin user. The credentials of the default admin user will be printed in the logs of the container — it's recommended to change the password of this user after the first login.
* [For more information on the available configuration options, see the Configuration section of the documentation.](../configuration/README.md)
* [For more information on the available configuration options, see the Configuration section of the documentation.](configuration/)
!!! info
When setting up MediaManager for the first time, you should add your email to `admin_emails` in the `[auth]` config section. MediaManager will then use this email instead of the default admin email. Your account will automatically be created as an admin account, allowing you to manage other users, media, and settings.
{% hint style="info" %}
When setting up MediaManager for the first time, you should add your email to `admin_emails` in the `[auth]` config section. MediaManager will then use this email instead of the default admin email. Your account will automatically be created as an admin account, allowing you to manage other users, media, and settings.
{% endhint %}
## Docker Images
@@ -69,8 +70,9 @@ MetadataRelay images are also available on both registries:
From v1.12.1 onwards, both MediaManager and MetadataRelay images are available on both Quay.io and GHCR. The reason for the switch to Quay.io as the primary image registry is due to [GHCR's continued slow performance.](https://github.com/orgs/community/discussions/173607)
!!! info
You can use either the Quay.io or GHCR images interchangeably, as they are built from the same source and the tags are the same across both registries.
{% hint style="info" %}
You can use either the Quay.io or GHCR images interchangeably, as they are built from the same source and the tags are the same across both registries.
{% endhint %}
### Tags

View File

@@ -1,9 +1,11 @@
# Nix Flakes
!!! note
This is a community contribution and not officially supported by the MediaManager team, but included here for convenience.
{% hint style="note" %}
This is a community contribution and not officially supported by the MediaManager team, but included here for convenience.
{% endhint %}
*Please report issues with this method at the [corresponding GitHub repository](https://github.com/strangeglyph/mediamanager-nix).*
*Please report issues with this method at the [corresponding GitHub repository](https://github.com/strangeglyph/mediamanager-nix).*
</note>
## Prerequisites
@@ -62,11 +64,12 @@ The host and port that MediaManager listens on can be set using `services.media-
To configure MediaManager, use `services.media-manager.settings`, which follows the same structure as the MediaManager
`config.toml`. To provision secrets, set `services.media-manager.environmentFile` to a protected file, for example one
provided by [agenix](https://github.com/ryantm/agenix) or [sops-nix](https://github.com/Mic92/sops-nix).
See [Configuration](../configuration/README.md#configuring-secrets) for guidance on using environment variables.
See [Configuration](Configuration.md#configuring-secrets) for guidance on using environment variables.
!!! warning
Do not place secrets in the nix store, as it is world-readable.
{% hint style="warning" %}
Do not place secrets in the nix store, as it is world-readable.
{% endhint %}
## Automatic Postgres Setup

View File

@@ -1,6 +1,7 @@
# Screenshots
!!! info
MediaManager also supports darkmode!
{% hint style="info" %}
MediaManager also supports darkmode!
{% endhint %}
![screenshot-dashboard.png](<assets/assets/screenshot dashboard.png>) ![screenshot-tv-dashboard.png](<assets/assets/screenshot tv dashboard.png>) ![screenshot-download-season.png](<assets/assets/screenshot download season.png>) ![screenshot-request-season.png](<assets/assets/screenshot request season.png>) ![screenshot-tv-torrents.png](<assets/assets/screenshot tv torrents.png>) ![screenshot-settings.png](<assets/assets/screenshot settings.png>) ![screenshot-login.png](<assets/assets/screenshot login.png>)
![screenshot-dashboard.png](<.gitbook/assets/screenshot dashboard.png>) ![screenshot-tv-dashboard.png](<.gitbook/assets/screenshot tv dashboard.png>) ![screenshot-download-season.png](<.gitbook/assets/screenshot download season.png>) ![screenshot-request-season.png](<.gitbook/assets/screenshot request season.png>) ![screenshot-tv-torrents.png](<.gitbook/assets/screenshot tv torrents.png>) ![screenshot-settings.png](<.gitbook/assets/screenshot settings.png>) ![screenshot-login.png](<.gitbook/assets/screenshot login.png>)

View File

@@ -1,7 +1,8 @@
# Troubleshooting
!!! info
Always check the container and browser logs for more specific error messages
{% hint style="info" %}
Always check the container and browser logs for more specific error messages
{% endhint %}
<details>
@@ -59,9 +60,10 @@ Switch to advanced tabTry switching to the advanced tab when searching for torre
#### Possible Fixes:
* [Unable to pull image from GitHub Container Registry (Stack Overflow)](https://stackoverflow.com/questions/74656167/unable-to-pull-image-from-github-container-registry-ghcr)
* [Try pulling the image from Quay.io](installation/docker.md#docker-images)
* [Try pulling the image from Quay.io](/broken/pages/09241b2fcda5d337e8878e4052f4634fe2902d10#mediamanager-and-metadatarelay-docker-images)
</details>
!!! info
If it still doesn't work, [please open an Issue.](https://github.com/maxdorninger/MediaManager/issues) It is possible that a bug is causing the issue.
{% hint style="info" %}
If it still doesn't work, [please open an Issue.](https://github.com/maxdorninger/MediaManager/issues) It is possible that a bug is causing the issue.
{% endhint %}

133
docs/usage.md Normal file
View File

@@ -0,0 +1,133 @@
# Usage
If you are coming from Radarr or Sonarr you will find that MediaManager does things a bit differently. Instead of completely automatically downloading and managing your media, MediaManager focuses on providing an easy-to-use interface to guide you through the process of finding and downloading media. Advanced features like multiple qualities of a show/movie necessitate such a paradigm shift. So here is a quick step-by-step guide to get you started:
#### Downloading/Requesting a show
{% stepper %}
{% step %}
### Add the show
Add a show on the "Add Show" page. After adding the show you will be redirected to the show's page.
{% endstep %}
{% step %}
### Request season(s)
Click the "Request Season" button on the show's page. Select one or more seasons that you want to download.
{% endstep %}
{% step %}
### Select qualities
Select the "Min Quality" — the minimum resolution of the content to download.\
Select the "Wanted Quality" — the **maximum** resolution of the content to download.
{% endstep %}
{% step %}
### Submit request
Click "Submit request". This is not the last step: an administrator must first approve your request for download. Only after approval will the requested content be downloaded.
{% endstep %}
{% step %}
### Finished
Congratulation! You've downloaded a show (after admin approval).
{% endstep %}
{% endstepper %}
#### Requesting a show (as an admin)
{% stepper %}
{% step %}
### Add the show
Add a show on the "Add Show" page. After adding the show you will be redirected to the show's page.
{% endstep %}
{% step %}
### Request season(s)
Click the "Request Season" button on the show's page. Select one or more seasons that you want to download.
{% endstep %}
{% step %}
### Select qualities
Select the "Min Quality" — the minimum resolution of the content to download.\
Select the "Wanted Quality" — the **maximum** resolution of the content to download.
{% endstep %}
{% step %}
### Submit request (auto-approved)
Click "Submit request". As an admin, your request will be automatically approved.
{% endstep %}
{% step %}
### Finished
Congratulation! You've downloaded a show.
{% endstep %}
{% endstepper %}
#### Downloading a show (admin-only)
You can only directly download a show if you are an admin!
{% stepper %}
{% step %}
### Go to the show's page
Open the show's page that contains the season you wish to download.
{% endstep %}
{% step %}
### Start download
Click the "Download Season" button.
{% endstep %}
{% step %}
### Enter season number
Enter the season number that you want to download.
{% endstep %}
{% step %}
### Optional file path suffix
Optionally select the "File Path Suffix". Note: **it needs to be unique per season per show!**
{% endstep %}
{% step %}
### Choose torrent and download
Click "Download" on the torrent that you want to download.
{% endstep %}
{% step %}
### Finished
Congratulation! You've downloaded a show.
{% endstep %}
{% endstepper %}
#### Managing requests
Users need their requests to be approved by an admin. To manage requests:
{% stepper %}
{% step %}
### Open Requests page
Go to the "Requests" page.
{% endstep %}
{% step %}
### Approve, delete or modify
From the Requests page you can approve, delete, or modify a user's request.
{% endstep %}
{% endstepper %}

View File

@@ -1,9 +1,7 @@
import concurrent
import concurrent.futures
import logging
import xml.etree.ElementTree as ET
from concurrent.futures.thread import ThreadPoolExecutor
from dataclasses import dataclass
import requests
@@ -17,21 +15,6 @@ from media_manager.tv.schemas import Show
log = logging.getLogger(__name__)
@dataclass
class IndexerInfo:
supports_tv_search: bool
supports_tv_search_tmdb: bool
supports_tv_search_imdb: bool
supports_tv_search_tvdb: bool
supports_tv_search_season: bool
supports_tv_search_episode: bool
supports_movie_search: bool
supports_movie_search_tmdb: bool
supports_movie_search_imdb: bool
supports_movie_search_tvdb: bool
class Jackett(GenericIndexer, TorznabMixin):
def __init__(self) -> None:
"""
@@ -48,16 +31,11 @@ class Jackett(GenericIndexer, TorznabMixin):
def search(self, query: str, is_tv: bool) -> list[IndexerQueryResult]:
log.debug("Searching for " + query)
params = {"q": query, "t": "tvsearch" if is_tv else "movie"}
return self.__search_jackett(params)
def __search_jackett(self, params: dict) -> list[IndexerQueryResult]:
futures = []
with ThreadPoolExecutor() as executor, requests.Session() as session:
for indexer in self.indexers:
future = executor.submit(
self.get_torrents_by_indexer, indexer, params, session
self.get_torrents_by_indexer, indexer, query, is_tv, session
)
futures.append(future)
@@ -73,103 +51,14 @@ class Jackett(GenericIndexer, TorznabMixin):
return responses
def __get_search_capabilities(
self, indexer: str, session: requests.Session
) -> IndexerInfo:
def get_torrents_by_indexer(
self, indexer: str, query: str, is_tv: bool, session: requests.Session
) -> list[IndexerQueryResult]:
url = (
self.url
+ f"/api/v2.0/indexers/{indexer}/results/torznab/api?apikey={self.api_key}&t=caps"
+ f"/api/v2.0/indexers/{indexer}/results/torznab/api?apikey={self.api_key}&t={'tvsearch' if is_tv else 'movie'}&q={query}"
)
response = session.get(url, timeout=self.timeout_seconds)
if response.status_code != 200:
msg = f"Cannot get search capabilities for Indexer {indexer}"
log.error(msg)
raise RuntimeError(msg)
xml = response.text
xml_tree = ET.fromstring(xml) # noqa: S314 # trusted source, since it is user controlled
tv_search = xml_tree.find("./*/tv-search")
movie_search = xml_tree.find("./*/movie-search")
log.debug(tv_search.attrib)
log.debug(movie_search.attrib)
tv_search_capabilities = []
movie_search_capabilities = []
tv_search_available = (tv_search is not None) and (
tv_search.attrib["available"] == "yes"
)
movie_search_available = (movie_search is not None) and (
movie_search.attrib["available"] == "yes"
)
if tv_search_available:
tv_search_capabilities = tv_search.attrib["supportedParams"].split(",")
if movie_search_available:
movie_search_capabilities = movie_search.attrib["supportedParams"].split(
","
)
return IndexerInfo(
supports_tv_search=tv_search_available,
supports_tv_search_imdb="tmdbid" in tv_search_capabilities,
supports_tv_search_tmdb="tmdbid" in tv_search_capabilities,
supports_tv_search_tvdb="tvdbid" in tv_search_capabilities,
supports_tv_search_season="season" in tv_search_capabilities,
supports_tv_search_episode="ep" in tv_search_capabilities,
supports_movie_search=movie_search_available,
supports_movie_search_imdb="imdbid" in movie_search_capabilities,
supports_movie_search_tmdb="tmdbid" in movie_search_capabilities,
supports_movie_search_tvdb="tvdbid" in movie_search_capabilities,
)
def __get_optimal_query_parameters(
self, indexer: str, session: requests.Session, params: dict
) -> dict[str, str]:
query_params = {"apikey": self.api_key, "t": params["t"]}
search_capabilities = self.__get_search_capabilities(
indexer=indexer, session=session
)
if params["t"] == "tvsearch":
if not search_capabilities.supports_tv_search:
msg = f"Indexer {indexer} does not support TV search"
raise RuntimeError(msg)
if search_capabilities.supports_tv_search_season and "season" in params:
query_params["season"] = params["season"]
if search_capabilities.supports_tv_search_episode and "ep" in params:
query_params["ep"] = params["ep"]
if search_capabilities.supports_tv_search_imdb and "imdbid" in params:
query_params["imdbid"] = params["imdbid"]
elif search_capabilities.supports_tv_search_tvdb and "tvdbid" in params:
query_params["tvdbid"] = params["tvdbid"]
elif search_capabilities.supports_tv_search_tmdb and "tmdbid" in params:
query_params["tmdbid"] = params["tmdbid"]
else:
query_params["q"] = params["q"]
if params["t"] == "movie":
if not search_capabilities.supports_movie_search:
msg = f"Indexer {indexer} does not support Movie search"
raise RuntimeError(msg)
if search_capabilities.supports_movie_search_imdb and "imdbid" in params:
query_params["imdbid"] = params["imdbid"]
elif search_capabilities.supports_tv_search_tvdb and "tvdbid" in params:
query_params["tvdbid"] = params["tvdbid"]
elif search_capabilities.supports_tv_search_tmdb and "tmdbid" in params:
query_params["tmdbid"] = params["tmdbid"]
else:
query_params["q"] = params["q"]
return query_params
def get_torrents_by_indexer(
self, indexer: str, params: dict, session: requests.Session
) -> list[IndexerQueryResult]:
url = f"{self.url}/api/v2.0/indexers/{indexer}/results/torznab/api"
query_params = self.__get_optimal_query_parameters(
indexer=indexer, session=session, params=params
)
response = session.get(url, timeout=self.timeout_seconds, params=query_params)
log.debug(f"Indexer {indexer} url: {response.url}")
if response.status_code != 200:
log.error(
@@ -186,23 +75,8 @@ class Jackett(GenericIndexer, TorznabMixin):
self, query: str, show: Show, season_number: int
) -> list[IndexerQueryResult]:
log.debug(f"Searching for season {season_number} of show {show.name}")
params = {
"t": "tvsearch",
"season": season_number,
"q": query,
}
if show.imdb_id:
params["imdbid"] = show.imdb_id
params[show.metadata_provider + "id"] = show.external_id
return self.__search_jackett(params=params)
return self.search(query=query, is_tv=True)
def search_movie(self, query: str, movie: Movie) -> list[IndexerQueryResult]:
log.debug(f"Searching for movie {movie.name}")
params = {
"t": "movie",
"q": query,
}
if movie.imdb_id:
params["imdbid"] = movie.imdb_id
params[movie.metadata_provider + "id"] = movie.external_id
return self.__search_jackett(params=params)
return self.search(query=query, is_tv=False)

View File

@@ -64,12 +64,16 @@ class TorznabMixin:
title = item.find("title").text
size_str = item.find("size")
if size_str is None or size_str.text is None:
log.warning(f"Torznab item {title} has no size, skipping.")
log.warning(
f"Torznab item {title} has no size, skipping."
)
continue
try:
size = int(size_str.text or "0")
except ValueError:
log.warning(f"Torznab item {title} has invalid size, skipping.")
log.warning(
f"Torznab item {title} has invalid size, skipping."
)
continue
result = IndexerQueryResult(

View File

@@ -18,7 +18,6 @@ class IndexerQueryResult(Base):
flags = mapped_column(ARRAY(String))
quality: Mapped[Quality]
season = mapped_column(ARRAY(Integer))
episode = mapped_column(ARRAY(Integer))
size = mapped_column(BigInteger)
usenet: Mapped[bool]
age: Mapped[int]

View File

@@ -35,10 +35,10 @@ class IndexerQueryResult(BaseModel):
@computed_field
@property
def quality(self) -> Quality:
high_quality_pattern = r"\b(4k|2160p|uhd)\b"
medium_quality_pattern = r"\b(1080p|full[ ._-]?hd)\b"
low_quality_pattern = r"\b(720p|(?<!full[ ._-])hd(?![a-z]))\b"
very_low_quality_pattern = r"\b(480p|360p|sd)\b"
high_quality_pattern = r"\b(4k)\b"
medium_quality_pattern = r"\b(1080p)\b"
low_quality_pattern = r"\b(720p)\b"
very_low_quality_pattern = r"\b(480p|360p)\b"
if re.search(high_quality_pattern, self.title, re.IGNORECASE):
return Quality.uhd
@@ -54,55 +54,14 @@ class IndexerQueryResult(BaseModel):
@computed_field
@property
def season(self) -> list[int]:
title = self.title.lower()
# 1) S01E01 / S1E2
m = re.search(r"s(\d{1,2})e\d{1,3}", title)
if m:
return [int(m.group(1))]
# 2) Range S01-S03 / S1-S3
m = re.search(r"s(\d{1,2})\s*(?:-|\u2013)\s*s?(\d{1,2})", title)
if m:
start, end = int(m.group(1)), int(m.group(2))
if start <= end:
return list(range(start, end + 1))
return []
# 3) Pack S01 / S1
m = re.search(r"\bs(\d{1,2})\b", title)
if m:
return [int(m.group(1))]
# 4) Season 01 / Season 1
m = re.search(r"\bseason\s*(\d{1,2})\b", title)
if m:
return [int(m.group(1))]
return []
@computed_field(return_type=list[int])
@property
def episode(self) -> list[int]:
title = self.title.lower()
result: list[int] = []
pattern = r"s\d{1,2}e(\d{1,3})(?:\s*-\s*(?:s?\d{1,2}e)?(\d{1,3}))?"
match = re.search(pattern, title)
if not match:
return result
start = int(match.group(1))
end = match.group(2)
if end:
end = int(end)
if end >= start:
result = list(range(start, end + 1))
pattern = r"\bS(\d+)\b"
matches = re.findall(pattern, self.title, re.IGNORECASE)
if matches.__len__() == 2:
result = list(range(int(matches[0]), int(matches[1]) + 1))
elif matches.__len__() == 1:
result = [int(matches[0])]
else:
result = [start]
result = []
return result
def __gt__(self, other: "IndexerQueryResult") -> bool:

View File

@@ -1,5 +1,4 @@
import logging
import re
from urllib.parse import urljoin
import requests
@@ -24,11 +23,7 @@ def evaluate_indexer_query_result(
log.debug(f"Applying rule {rule.name} to {query_result.title}")
if (
any(
re.search(
rf"\b{re.escape(keyword)}\b",
query_result.title,
re.IGNORECASE,
)
keyword.lower() in query_result.title.lower()
for keyword in rule.keywords
)
and not rule.negate
@@ -39,11 +34,7 @@ def evaluate_indexer_query_result(
query_result.score += rule.score_modifier
elif (
not any(
re.search(
rf"\b{re.escape(keyword)}\b",
query_result.title,
re.IGNORECASE,
)
keyword.lower() in query_result.title.lower()
for keyword in rule.keywords
)
and rule.negate
@@ -164,3 +155,5 @@ def follow_redirects_to_final_torrent_url(
)
msg = "An error occurred during the request"
raise RuntimeError(msg) from e
return current_url

View File

@@ -83,4 +83,3 @@ def setup_logging() -> None:
logging.getLogger("transmission_rpc").setLevel(logging.WARNING)
logging.getLogger("qbittorrentapi").setLevel(logging.WARNING)
logging.getLogger("sabnzbd_api").setLevel(logging.WARNING)
logging.getLogger("taskiq").setLevel(logging.WARNING)

View File

@@ -1,8 +1,5 @@
import asyncio
import logging
import os
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
import uvicorn
from asgi_correlation_id import CorrelationIdMiddleware
@@ -12,8 +9,6 @@ from fastapi.staticfiles import StaticFiles
from psycopg.errors import UniqueViolation
from sqlalchemy.exc import IntegrityError
from starlette.responses import FileResponse, RedirectResponse
from taskiq.receiver import Receiver
from taskiq_fastapi import populate_dependency_context
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
import media_manager.movies.router as movies_router
@@ -33,7 +28,6 @@ from media_manager.auth.users import (
fastapi_users,
)
from media_manager.config import MediaManagerConfig
from media_manager.database import init_engine
from media_manager.exceptions import (
ConflictError,
InvalidConfigError,
@@ -48,24 +42,18 @@ from media_manager.exceptions import (
from media_manager.filesystem_checks import run_filesystem_checks
from media_manager.logging import LOGGING_CONFIG, setup_logging
from media_manager.notification.router import router as notification_router
from media_manager.scheduler import (
broker,
build_scheduler_loop,
import_all_movie_torrents_task,
import_all_show_torrents_task,
update_all_movies_metadata_task,
update_all_non_ended_shows_metadata_task,
)
from media_manager.scheduler import setup_scheduler
setup_logging()
config = MediaManagerConfig()
log = logging.getLogger(__name__)
if config.misc.development:
log.warning("Development Mode activated!")
scheduler = setup_scheduler(config)
run_filesystem_checks(config, log)
BASE_PATH = os.getenv("BASE_PATH", "")
@@ -74,57 +62,7 @@ DISABLE_FRONTEND_MOUNT = os.getenv("DISABLE_FRONTEND_MOUNT", "").lower() == "tru
FRONTEND_FOLLOW_SYMLINKS = os.getenv("FRONTEND_FOLLOW_SYMLINKS", "").lower() == "true"
log.info("Hello World!")
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator:
init_engine(config.database)
broker_started = False
started_sources: list = []
finish_event: asyncio.Event | None = None
receiver_task: asyncio.Task | None = None
loop_task: asyncio.Task | None = None
try:
if not broker.is_worker_process:
await broker.startup()
broker_started = True
populate_dependency_context(broker, app)
scheduler_loop = build_scheduler_loop()
for source in scheduler_loop.scheduler.sources:
await source.startup()
started_sources.append(source)
finish_event = asyncio.Event()
receiver = Receiver(broker, run_startup=False, max_async_tasks=10)
receiver_task = asyncio.create_task(receiver.listen(finish_event))
loop_task = asyncio.create_task(scheduler_loop.run(skip_first_run=True))
try:
await asyncio.gather(
import_all_movie_torrents_task.kiq(),
import_all_show_torrents_task.kiq(),
update_all_movies_metadata_task.kiq(),
update_all_non_ended_shows_metadata_task.kiq(),
)
except Exception:
log.exception("Failed to submit initial background tasks during startup.")
raise
yield
finally:
if loop_task is not None:
loop_task.cancel()
try:
await loop_task
except asyncio.CancelledError:
pass
if finish_event is not None and receiver_task is not None:
finish_event.set()
await receiver_task
for source in started_sources:
await source.shutdown()
if broker_started:
await broker.shutdown()
app = FastAPI(root_path=BASE_PATH, lifespan=lifespan)
app = FastAPI(root_path=BASE_PATH)
app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
origins = config.misc.cors_urls
log.info(f"CORS URLs activated for following origins: {origins}")

View File

@@ -15,7 +15,7 @@ def download_poster_image(storage_path: Path, poster_url: str, uuid: UUID) -> bo
res = requests.get(poster_url, stream=True, timeout=60)
if res.status_code == 200:
image_file_path = storage_path.joinpath(str(uuid)).with_suffix(".jpg")
image_file_path = storage_path.joinpath(str(uuid)).with_suffix("jpg")
image_file_path.write_bytes(res.content)
original_image = Image.open(image_file_path)

View File

@@ -3,6 +3,7 @@ from uuid import UUID
from sqlalchemy import ForeignKey, PrimaryKeyConstraint, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from media_manager.auth.db import User
from media_manager.database import Base
from media_manager.torrent.models import Quality
@@ -21,6 +22,10 @@ class Movie(Base):
original_language: Mapped[str | None] = mapped_column(default=None)
imdb_id: Mapped[str | None] = mapped_column(default=None)
movie_requests: Mapped[list["MovieRequest"]] = relationship(
"MovieRequest", back_populates="movie", cascade="all, delete-orphan"
)
class MovieFile(Base):
__tablename__ = "movie_file"
@@ -37,3 +42,31 @@ class MovieFile(Base):
)
torrent = relationship("Torrent", back_populates="movie_files", uselist=False)
class MovieRequest(Base):
__tablename__ = "movie_request"
__table_args__ = (UniqueConstraint("movie_id", "wanted_quality"),)
id: Mapped[UUID] = mapped_column(primary_key=True)
movie_id: Mapped[UUID] = mapped_column(
ForeignKey(column="movie.id", ondelete="CASCADE"),
)
wanted_quality: Mapped[Quality]
min_quality: Mapped[Quality]
authorized: Mapped[bool] = mapped_column(default=False)
requested_by_id: Mapped[UUID | None] = mapped_column(
ForeignKey(column="user.id", ondelete="SET NULL"),
)
authorized_by_id: Mapped[UUID | None] = mapped_column(
ForeignKey(column="user.id", ondelete="SET NULL"),
)
requested_by: Mapped["User|None"] = relationship(
foreign_keys=[requested_by_id], uselist=False
)
authorized_by: Mapped["User|None"] = relationship(
foreign_keys=[authorized_by_id], uselist=False
)
movie = relationship("Movie", back_populates="movie_requests", uselist=False)

View File

@@ -5,10 +5,10 @@ from sqlalchemy.exc import (
IntegrityError,
SQLAlchemyError,
)
from sqlalchemy.orm import Session
from sqlalchemy.orm import Session, joinedload
from media_manager.exceptions import ConflictError, NotFoundError
from media_manager.movies.models import Movie, MovieFile
from media_manager.movies.models import Movie, MovieFile, MovieRequest
from media_manager.movies.schemas import (
Movie as MovieSchema,
)
@@ -17,10 +17,17 @@ from media_manager.movies.schemas import (
)
from media_manager.movies.schemas import (
MovieId,
MovieRequestId,
)
from media_manager.movies.schemas import (
MovieRequest as MovieRequestSchema,
)
from media_manager.movies.schemas import (
MovieTorrent as MovieTorrentSchema,
)
from media_manager.movies.schemas import (
RichMovieRequest as RichMovieRequestSchema,
)
from media_manager.torrent.models import Torrent
from media_manager.torrent.schemas import TorrentId
@@ -166,6 +173,46 @@ class MovieRepository:
log.exception(f"Database error while deleting movie {movie_id}")
raise
def add_movie_request(
self, movie_request: MovieRequestSchema
) -> MovieRequestSchema:
"""
Adds a Movie to the MovieRequest table, which marks it as requested.
:param movie_request: The MovieRequest object to add.
:return: The added MovieRequest object.
:raises IntegrityError: If a similar request already exists or violates constraints.
:raises SQLAlchemyError: If a database error occurs.
"""
log.debug(f"Adding movie request: {movie_request.model_dump_json()}")
db_model = MovieRequest(
id=movie_request.id,
movie_id=movie_request.movie_id,
requested_by_id=movie_request.requested_by.id
if movie_request.requested_by
else None,
authorized_by_id=movie_request.authorized_by.id
if movie_request.authorized_by
else None,
wanted_quality=movie_request.wanted_quality,
min_quality=movie_request.min_quality,
authorized=movie_request.authorized,
)
try:
self.db.add(db_model)
self.db.commit()
self.db.refresh(db_model)
log.info(f"Successfully added movie request with id: {db_model.id}")
return MovieRequestSchema.model_validate(db_model)
except IntegrityError:
self.db.rollback()
log.exception("Integrity error while adding movie request")
raise
except SQLAlchemyError:
self.db.rollback()
log.exception("Database error while adding movie request")
raise
def set_movie_library(self, movie_id: MovieId, library: str) -> None:
"""
Sets the library for a movie.
@@ -187,6 +234,49 @@ class MovieRepository:
log.exception(f"Database error setting library for movie {movie_id}")
raise
def delete_movie_request(self, movie_request_id: MovieRequestId) -> None:
"""
Removes a MovieRequest by its ID.
:param movie_request_id: The ID of the movie request to delete.
:raises NotFoundError: If the movie request is not found.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = delete(MovieRequest).where(MovieRequest.id == movie_request_id)
result = self.db.execute(stmt)
if result.rowcount == 0:
self.db.rollback()
msg = f"movie request with id {movie_request_id} not found."
raise NotFoundError(msg)
self.db.commit()
# Successfully deleted movie request with id: {movie_request_id}
except SQLAlchemyError:
self.db.rollback()
log.exception(
f"Database error while deleting movie request {movie_request_id}"
)
raise
def get_movie_requests(self) -> list[RichMovieRequestSchema]:
"""
Retrieve all movie requests.
:return: A list of RichMovieRequest objects.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = select(MovieRequest).options(
joinedload(MovieRequest.requested_by),
joinedload(MovieRequest.authorized_by),
joinedload(MovieRequest.movie),
)
results = self.db.execute(stmt).scalars().unique().all()
return [RichMovieRequestSchema.model_validate(x) for x in results]
except SQLAlchemyError:
log.exception("Database error while retrieving movie requests")
raise
def add_movie_file(self, movie_file: MovieFileSchema) -> MovieFileSchema:
"""
Adds a movie file record to the database.
@@ -306,6 +396,25 @@ class MovieRepository:
log.exception("Database error retrieving all movies with torrents")
raise
def get_movie_request(self, movie_request_id: MovieRequestId) -> MovieRequestSchema:
"""
Retrieve a movie request by its ID.
:param movie_request_id: The ID of the movie request.
:return: A MovieRequest object.
:raises NotFoundError: If the movie request is not found.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
request = self.db.get(MovieRequest, movie_request_id)
if not request:
msg = f"Movie request with id {movie_request_id} not found."
raise NotFoundError(msg)
return MovieRequestSchema.model_validate(request)
except SQLAlchemyError:
log.exception(f"Database error retrieving movie request {movie_request_id}")
raise
def get_movie_by_torrent_id(self, torrent_id: TorrentId) -> MovieSchema:
"""
Retrieve a movie by a torrent ID.

View File

@@ -1,7 +1,9 @@
from pathlib import Path
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from media_manager.auth.schemas import UserRead
from media_manager.auth.users import current_active_user, current_superuser
from media_manager.config import LibraryItem, MediaManagerConfig
from media_manager.exceptions import ConflictError, NotFoundError
@@ -11,14 +13,20 @@ from media_manager.indexer.schemas import (
)
from media_manager.metadataProvider.dependencies import metadata_provider_dep
from media_manager.metadataProvider.schemas import MetaDataProviderSearchResult
from media_manager.movies import log
from media_manager.movies.dependencies import (
movie_dep,
movie_service_dep,
)
from media_manager.movies.schemas import (
CreateMovieRequest,
Movie,
MovieRequest,
MovieRequestBase,
MovieRequestId,
PublicMovie,
PublicMovieFile,
RichMovieRequest,
RichMovieTorrent,
)
from media_manager.schemas import MediaImportSuggestion
@@ -180,6 +188,103 @@ def get_available_libraries() -> list[LibraryItem]:
return MediaManagerConfig().misc.movie_libraries
# -----------------------------------------------------------------------------
# MOVIE REQUESTS
# -----------------------------------------------------------------------------
@router.get(
"/requests",
dependencies=[Depends(current_active_user)],
)
def get_all_movie_requests(movie_service: movie_service_dep) -> list[RichMovieRequest]:
"""
Get all movie requests.
"""
return movie_service.get_all_movie_requests()
@router.post(
"/requests",
status_code=status.HTTP_201_CREATED,
)
def create_movie_request(
movie_service: movie_service_dep,
movie_request: CreateMovieRequest,
user: Annotated[UserRead, Depends(current_active_user)],
) -> MovieRequest:
"""
Create a new movie request.
"""
log.info(
f"User {user.email} is creating a movie request for {movie_request.movie_id}"
)
movie_request: MovieRequest = MovieRequest.model_validate(movie_request)
movie_request.requested_by = user
if user.is_superuser:
movie_request.authorized = True
movie_request.authorized_by = user
return movie_service.add_movie_request(movie_request=movie_request)
@router.put(
"/requests/{movie_request_id}",
)
def update_movie_request(
movie_service: movie_service_dep,
movie_request_id: MovieRequestId,
update_movie_request: MovieRequestBase,
user: Annotated[UserRead, Depends(current_active_user)],
) -> MovieRequest:
"""
Update an existing movie request.
"""
movie_request = movie_service.get_movie_request_by_id(
movie_request_id=movie_request_id
)
if movie_request.requested_by.id != user.id or user.is_superuser:
movie_request.min_quality = update_movie_request.min_quality
movie_request.wanted_quality = update_movie_request.wanted_quality
return movie_service.update_movie_request(movie_request=movie_request)
@router.patch("/requests/{movie_request_id}", status_code=status.HTTP_204_NO_CONTENT)
def authorize_request(
movie_service: movie_service_dep,
movie_request_id: MovieRequestId,
user: Annotated[UserRead, Depends(current_superuser)],
authorized_status: bool = False,
) -> None:
"""
Authorize or de-authorize a movie request.
"""
movie_request = movie_service.get_movie_request_by_id(
movie_request_id=movie_request_id
)
movie_request.authorized = authorized_status
if authorized_status:
movie_request.authorized_by = user
else:
movie_request.authorized_by = None
movie_service.update_movie_request(movie_request=movie_request)
@router.delete(
"/requests/{movie_request_id}",
status_code=status.HTTP_204_NO_CONTENT,
dependencies=[Depends(current_superuser)],
)
def delete_movie_request(
movie_service: movie_service_dep, movie_request_id: MovieRequestId
) -> None:
"""
Delete a movie request.
"""
movie_service.delete_movie_request(movie_request_id=movie_request_id)
# -----------------------------------------------------------------------------
# MOVIES - SINGLE RESOURCE
# -----------------------------------------------------------------------------

View File

@@ -2,12 +2,14 @@ import typing
import uuid
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, model_validator
from media_manager.auth.schemas import UserRead
from media_manager.torrent.models import Quality
from media_manager.torrent.schemas import TorrentId, TorrentStatus
MovieId = typing.NewType("MovieId", UUID)
MovieRequestId = typing.NewType("MovieRequestId", UUID)
class Movie(BaseModel):
@@ -38,6 +40,38 @@ class PublicMovieFile(MovieFile):
imported: bool = False
class MovieRequestBase(BaseModel):
min_quality: Quality
wanted_quality: Quality
@model_validator(mode="after")
def ensure_wanted_quality_is_eq_or_gt_min_quality(self) -> "MovieRequestBase":
if self.min_quality.value < self.wanted_quality.value:
msg = "wanted_quality must be equal to or lower than minimum_quality."
raise ValueError(msg)
return self
class CreateMovieRequest(MovieRequestBase):
movie_id: MovieId
class MovieRequest(MovieRequestBase):
model_config = ConfigDict(from_attributes=True)
id: MovieRequestId = Field(default_factory=lambda: MovieRequestId(uuid.uuid4()))
movie_id: MovieId
requested_by: UserRead | None = None
authorized: bool = False
authorized_by: UserRead | None = None
class RichMovieRequest(MovieRequest):
movie: Movie
class MovieTorrent(BaseModel):
model_config = ConfigDict(from_attributes=True)

View File

@@ -4,9 +4,12 @@ from pathlib import Path
from typing import overload
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from media_manager.config import MediaManagerConfig
from media_manager.database import SessionLocal, get_session
from media_manager.exceptions import InvalidConfigError, NotFoundError, RenameError
from media_manager.indexer.repository import IndexerRepository
from media_manager.indexer.schemas import IndexerQueryResult, IndexerQueryResultId
from media_manager.indexer.service import IndexerService
from media_manager.indexer.utils import evaluate_indexer_query_results
@@ -22,14 +25,20 @@ from media_manager.movies.schemas import (
Movie,
MovieFile,
MovieId,
MovieRequest,
MovieRequestId,
PublicMovie,
PublicMovieFile,
RichMovieRequest,
RichMovieTorrent,
)
from media_manager.notification.repository import NotificationRepository
from media_manager.notification.service import NotificationService
from media_manager.schemas import MediaImportSuggestion
from media_manager.torrent.repository import TorrentRepository
from media_manager.torrent.schemas import (
Quality,
QualityStrings,
Torrent,
TorrentStatus,
)
@@ -80,6 +89,44 @@ class MovieService:
metadata_provider.download_movie_poster_image(movie=saved_movie)
return saved_movie
def add_movie_request(self, movie_request: MovieRequest) -> MovieRequest:
"""
Add a new movie request.
:param movie_request: The movie request to add.
:return: The added movie request.
"""
return self.movie_repository.add_movie_request(movie_request=movie_request)
def get_movie_request_by_id(self, movie_request_id: MovieRequestId) -> MovieRequest:
"""
Get a movie request by its ID.
:param movie_request_id: The ID of the movie request.
:return: The movie request or None if not found.
"""
return self.movie_repository.get_movie_request(
movie_request_id=movie_request_id
)
def update_movie_request(self, movie_request: MovieRequest) -> MovieRequest:
"""
Update an existing movie request.
:param movie_request: The movie request to update.
:return: The updated movie request.
"""
self.movie_repository.delete_movie_request(movie_request_id=movie_request.id)
return self.movie_repository.add_movie_request(movie_request=movie_request)
def delete_movie_request(self, movie_request_id: MovieRequestId) -> None:
"""
Delete a movie request by its ID.
:param movie_request_id: The ID of the movie request to delete.
"""
self.movie_repository.delete_movie_request(movie_request_id=movie_request_id)
def delete_movie(
self,
movie: Movie,
@@ -344,6 +391,14 @@ class MovieService:
external_id=external_id, metadata_provider=metadata_provider
)
def get_all_movie_requests(self) -> list[RichMovieRequest]:
"""
Get all movie requests.
:return: A list of rich movie requests.
"""
return self.movie_repository.get_movie_requests()
def set_movie_library(self, movie: Movie, library: str) -> None:
self.movie_repository.set_movie_library(movie_id=movie.id, library=library)
@@ -416,6 +471,65 @@ class MovieService:
self.torrent_service.resume_download(torrent=movie_torrent)
return movie_torrent
def download_approved_movie_request(
self, movie_request: MovieRequest, movie: Movie
) -> bool:
"""
Download an approved movie request.
:param movie_request: The movie request to download.
:param movie: The Movie object.
:return: True if the download was successful, False otherwise.
:raises ValueError: If the movie request is not authorized.
"""
if not movie_request.authorized:
msg = "Movie request is not authorized"
raise ValueError(msg)
log.info(f"Downloading approved movie request {movie_request.id}")
torrents = self.get_all_available_torrents_for_movie(movie=movie)
available_torrents: list[IndexerQueryResult] = []
for torrent in torrents:
if (
(torrent.quality.value < movie_request.wanted_quality.value)
or (torrent.quality.value > movie_request.min_quality.value)
or (torrent.seeders < 3)
):
log.debug(
f"Skipping torrent {torrent.title} with quality {torrent.quality} for movie {movie.id}, because it does not match the requested quality {movie_request.wanted_quality}"
)
else:
available_torrents.append(torrent)
log.debug(
f"Taking torrent {torrent.title} with quality {torrent.quality} for movie {movie.id} into consideration"
)
if len(available_torrents) == 0:
log.warning(
f"No torrents found for movie request {movie_request.id} with quality between {QualityStrings[movie_request.min_quality.name]} and {QualityStrings[movie_request.wanted_quality.name]}"
)
return False
available_torrents.sort()
torrent = self.torrent_service.download(indexer_result=available_torrents[0])
movie_file = MovieFile(
movie_id=movie.id,
quality=torrent.quality,
torrent_id=torrent.id,
file_path_suffix=QualityStrings[torrent.quality.name].value.upper(),
)
try:
self.movie_repository.add_movie_file(movie_file=movie_file)
except IntegrityError:
log.warning(
f"Movie file for movie {movie.name} and torrent {torrent.title} already exists"
)
self.delete_movie_request(movie_request.id)
return True
def get_movie_root_path(self, movie: Movie) -> Path:
misc_config = MediaManagerConfig().misc
movie_file_path = (
@@ -609,7 +723,7 @@ class MovieService:
)
if not fresh_movie_data:
log.warning(
f"Could not fetch fresh metadata for movie: {db_movie.name} ({db_movie.year})"
f"Could not fetch fresh metadata for movie: {db_movie.name} (ID: {db_movie.external_id})"
)
return None
log.debug(f"Fetched fresh metadata for movie: {fresh_movie_data.name}")
@@ -624,9 +738,7 @@ class MovieService:
updated_movie = self.movie_repository.get_movie_by_id(movie_id=db_movie.id)
log.info(
f"Successfully updated metadata for movie: {db_movie.name} ({db_movie.year})"
)
log.info(f"Successfully updated metadata for movie ID: {db_movie.id}")
metadata_provider.download_movie_poster_image(movie=updated_movie)
return updated_movie
@@ -661,29 +773,102 @@ class MovieService:
log.debug(f"Found {len(importable_movies)} importable movies.")
return importable_movies
def import_all_torrents(self) -> None:
def auto_download_all_approved_movie_requests() -> None:
"""
Auto download all approved movie requests.
This is a standalone function as it creates its own DB session.
"""
db: Session = SessionLocal() if SessionLocal else next(get_session())
movie_repository = MovieRepository(db=db)
torrent_service = TorrentService(torrent_repository=TorrentRepository(db=db))
indexer_service = IndexerService(indexer_repository=IndexerRepository(db=db))
notification_service = NotificationService(
notification_repository=NotificationRepository(db=db)
)
movie_service = MovieService(
movie_repository=movie_repository,
torrent_service=torrent_service,
indexer_service=indexer_service,
notification_service=notification_service,
)
log.info("Auto downloading all approved movie requests")
movie_requests = movie_repository.get_movie_requests()
log.info(f"Found {len(movie_requests)} movie requests to process")
count = 0
for movie_request in movie_requests:
if movie_request.authorized:
movie = movie_repository.get_movie_by_id(movie_id=movie_request.movie_id)
if movie_service.download_approved_movie_request(
movie_request=movie_request, movie=movie
):
count += 1
else:
log.info(
f"Could not download movie request {movie_request.id} for movie {movie.name}"
)
log.info(f"Auto downloaded {count} approved movie requests")
db.commit()
db.close()
def import_all_movie_torrents() -> None:
with next(get_session()) as db:
movie_repository = MovieRepository(db=db)
torrent_service = TorrentService(torrent_repository=TorrentRepository(db=db))
indexer_service = IndexerService(indexer_repository=IndexerRepository(db=db))
notification_service = NotificationService(
notification_repository=NotificationRepository(db=db)
)
movie_service = MovieService(
movie_repository=movie_repository,
torrent_service=torrent_service,
indexer_service=indexer_service,
notification_service=notification_service,
)
log.info("Importing all torrents")
torrents = self.torrent_service.get_all_torrents()
torrents = torrent_service.get_all_torrents()
log.info("Found %d torrents to import", len(torrents))
for t in torrents:
try:
if not t.imported and t.status == TorrentStatus.finished:
movie = self.torrent_service.get_movie_of_torrent(torrent=t)
movie = torrent_service.get_movie_of_torrent(torrent=t)
if movie is None:
log.warning(
f"torrent {t.title} is not a movie torrent, skipping import."
)
continue
self.import_torrent_files(torrent=t, movie=movie)
movie_service.import_torrent_files(torrent=t, movie=movie)
except RuntimeError:
log.exception(f"Failed to import torrent {t.title}")
log.info("Finished importing all torrents")
db.commit()
def update_all_movies_metadata() -> None:
"""
Updates the metadata of all movies.
"""
with next(get_session()) as db:
movie_repository = MovieRepository(db=db)
movie_service = MovieService(
movie_repository=movie_repository,
torrent_service=TorrentService(torrent_repository=TorrentRepository(db=db)),
indexer_service=IndexerService(indexer_repository=IndexerRepository(db=db)),
notification_service=NotificationService(
notification_repository=NotificationRepository(db=db)
),
)
def update_all_metadata(self) -> None:
"""Updates the metadata of all movies."""
log.info("Updating metadata for all movies")
movies = self.movie_repository.get_movies()
movies = movie_repository.get_movies()
log.info(f"Found {len(movies)} movies to update")
for movie in movies:
try:
if movie.metadata_provider == "tmdb":
@@ -700,6 +885,7 @@ class MovieService:
f"Error initializing metadata provider {movie.metadata_provider} for movie {movie.name}",
)
continue
self.update_movie_metadata(
movie_service.update_movie_metadata(
db_movie=movie, metadata_provider=metadata_provider
)
db.commit()

View File

@@ -1,91 +1,67 @@
import asyncio
import logging
from urllib.parse import quote
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
import taskiq_fastapi
from taskiq import TaskiqDepends, TaskiqScheduler
from taskiq.cli.scheduler.run import SchedulerLoop
from taskiq_postgresql import PostgresqlBroker
from taskiq_postgresql.scheduler_source import PostgresqlSchedulerSource
from media_manager.movies.dependencies import get_movie_service
from media_manager.movies.service import MovieService
from media_manager.tv.dependencies import get_tv_service
from media_manager.tv.service import TvService
def _build_db_connection_string_for_taskiq() -> str:
from media_manager.config import MediaManagerConfig
db_config = MediaManagerConfig().database
user = quote(db_config.user, safe="")
password = quote(db_config.password, safe="")
dbname = quote(db_config.dbname, safe="")
host = quote(str(db_config.host), safe="")
port = quote(str(db_config.port), safe="")
return f"postgresql://{user}:{password}@{host}:{port}/{dbname}"
broker = PostgresqlBroker(
dsn=_build_db_connection_string_for_taskiq,
driver="psycopg",
run_migrations=True,
import media_manager.database
from media_manager.config import MediaManagerConfig
from media_manager.movies.service import (
auto_download_all_approved_movie_requests,
import_all_movie_torrents,
update_all_movies_metadata,
)
from media_manager.tv.service import (
auto_download_all_approved_season_requests,
import_all_show_torrents,
update_all_non_ended_shows_metadata,
)
# Register FastAPI app with the broker so worker processes can resolve FastAPI
# dependencies. Using a string reference avoids circular imports.
taskiq_fastapi.init(broker, "media_manager.main:app")
log = logging.getLogger(__name__)
def setup_scheduler(config: MediaManagerConfig) -> BackgroundScheduler:
from media_manager.database import init_engine
@broker.task
async def import_all_movie_torrents_task(
movie_service: MovieService = TaskiqDepends(get_movie_service),
) -> None:
log.info("Importing all Movie torrents")
await asyncio.to_thread(movie_service.import_all_torrents)
@broker.task
async def import_all_show_torrents_task(
tv_service: TvService = TaskiqDepends(get_tv_service),
) -> None:
log.info("Importing all Show torrents")
await asyncio.to_thread(tv_service.import_all_torrents)
@broker.task
async def update_all_movies_metadata_task(
movie_service: MovieService = TaskiqDepends(get_movie_service),
) -> None:
await asyncio.to_thread(movie_service.update_all_metadata)
@broker.task
async def update_all_non_ended_shows_metadata_task(
tv_service: TvService = TaskiqDepends(get_tv_service),
) -> None:
await asyncio.to_thread(tv_service.update_all_non_ended_shows_metadata)
# Maps each task to its cron schedule so PostgresqlSchedulerSource can seed
# the taskiq_schedulers table on first startup.
_STARTUP_SCHEDULES: dict[str, list[dict[str, str]]] = {
import_all_movie_torrents_task.task_name: [{"cron": "*/2 * * * *"}],
import_all_show_torrents_task.task_name: [{"cron": "*/2 * * * *"}],
update_all_movies_metadata_task.task_name: [{"cron": "0 0 * * 1"}],
update_all_non_ended_shows_metadata_task.task_name: [{"cron": "0 0 * * 1"}],
}
def build_scheduler_loop() -> SchedulerLoop:
source = PostgresqlSchedulerSource(
dsn=_build_db_connection_string_for_taskiq,
driver="psycopg",
broker=broker,
run_migrations=True,
startup_schedule=_STARTUP_SCHEDULES,
init_engine(config.database)
jobstores = {"default": SQLAlchemyJobStore(engine=media_manager.database.engine)}
scheduler = BackgroundScheduler(jobstores=jobstores)
every_15_minutes_trigger = CronTrigger(minute="*/15", hour="*")
daily_trigger = CronTrigger(hour=0, minute=0, jitter=60 * 60 * 24 * 2)
weekly_trigger = CronTrigger(
day_of_week="mon", hour=0, minute=0, jitter=60 * 60 * 24 * 2
)
scheduler = TaskiqScheduler(broker=broker, sources=[source])
return SchedulerLoop(scheduler)
scheduler.add_job(
import_all_movie_torrents,
every_15_minutes_trigger,
id="import_all_movie_torrents",
replace_existing=True,
)
scheduler.add_job(
import_all_show_torrents,
every_15_minutes_trigger,
id="import_all_show_torrents",
replace_existing=True,
)
scheduler.add_job(
auto_download_all_approved_season_requests,
daily_trigger,
id="auto_download_all_approved_season_requests",
replace_existing=True,
)
scheduler.add_job(
auto_download_all_approved_movie_requests,
daily_trigger,
id="auto_download_all_approved_movie_requests",
replace_existing=True,
)
scheduler.add_job(
update_all_movies_metadata,
weekly_trigger,
id="update_all_movies_metadata",
replace_existing=True,
)
scheduler.add_job(
update_all_non_ended_shows_metadata,
weekly_trigger,
id="update_all_non_ended_shows_metadata",
replace_existing=True,
)
scheduler.start()
return scheduler

View File

@@ -1,7 +1,8 @@
from pydantic_settings import BaseSettings
from pydantic_settings import BaseSettings, SettingsConfigDict
class QbittorrentConfig(BaseSettings):
model_config = SettingsConfigDict(env_prefix="QBITTORRENT_")
host: str = "localhost"
port: int = 8080
username: str = "admin"
@@ -13,6 +14,7 @@ class QbittorrentConfig(BaseSettings):
class TransmissionConfig(BaseSettings):
model_config = SettingsConfigDict(env_prefix="TRANSMISSION_")
path: str = "/transmission/rpc"
https_enabled: bool = True
host: str = "localhost"
@@ -23,6 +25,7 @@ class TransmissionConfig(BaseSettings):
class SabnzbdConfig(BaseSettings):
model_config = SettingsConfigDict(env_prefix="SABNZBD_")
host: str = "localhost"
port: int = 8080
api_key: str = ""

View File

@@ -57,45 +57,23 @@ class QbittorrentDownloadClient(AbstractDownloadClient):
log.exception("Failed to log into qbittorrent")
raise
categories = self.api_client.torrents_categories()
log.debug(f"Found following categories in qBittorrent: {categories}")
if self.config.category_name in categories:
category = categories.get(self.config.category_name)
if category.get("savePath") == self.config.category_save_path:
log.debug(
f"Category '{self.config.category_name}' already exists in qBittorrent with the correct save path."
)
return
# category exists but with a different save path, attempt to update it
log.debug(
f"Category '{self.config.category_name}' already exists in qBittorrent but with a different save path. Attempting to update it."
try:
self.api_client.torrents_create_category(
name=self.config.category_name,
save_path=self.config.category_save_path
if self.config.category_save_path != ""
else None,
)
except Conflict409Error:
try:
self.api_client.torrents_edit_category(
name=self.config.category_name,
save_path=self.config.category_save_path,
)
except Conflict409Error:
log.exception(
f"Attempt to update category '{self.config.category_name}' in qBittorrent with a different save"
f" path failed. The configured save path and the save path saved in Qbittorrent differ,"
f" manually update it in the qBittorrent WebUI or change the save path in the MediaManager"
f" config to match the one in qBittorrent."
)
else:
# create category if it doesn't exist
log.debug(
f"Category '{self.config.category_name}' does not exist in qBittorrent. Attempting to create it."
)
try:
self.api_client.torrents_create_category(
name=self.config.category_name,
save_path=self.config.category_save_path,
)
except Conflict409Error:
log.exception(
f"Attempt to create category '{self.config.category_name}' in qBittorrent failed. The category already exists but was not found in the initial category list, manually check if the category exists in the qBittorrent WebUI or change the category name in the MediaManager config."
save_path=self.config.category_save_path
if self.config.category_save_path != ""
else None,
)
except Exception:
log.exception("Error on updating MediaManager category in qBittorrent")
def download_torrent(self, indexer_result: IndexerQueryResult) -> Torrent:
"""

View File

@@ -16,5 +16,5 @@ class Torrent(Base):
hash: Mapped[str]
usenet: Mapped[bool]
episode_files = relationship("EpisodeFile", back_populates="torrent")
season_files = relationship("SeasonFile", back_populates="torrent")
movie_files = relationship("MovieFile", back_populates="torrent")

View File

@@ -3,13 +3,17 @@ from sqlalchemy import delete, select
from media_manager.database import DbSessionDependency
from media_manager.exceptions import NotFoundError
from media_manager.movies.models import Movie, MovieFile
from media_manager.movies.schemas import Movie as MovieSchema
from media_manager.movies.schemas import MovieFile as MovieFileSchema
from media_manager.movies.schemas import (
Movie as MovieSchema,
)
from media_manager.movies.schemas import (
MovieFile as MovieFileSchema,
)
from media_manager.torrent.models import Torrent
from media_manager.torrent.schemas import Torrent as TorrentSchema
from media_manager.torrent.schemas import TorrentId
from media_manager.tv.models import Episode, EpisodeFile, Season, Show
from media_manager.tv.schemas import EpisodeFile as EpisodeFileSchema
from media_manager.tv.models import Season, SeasonFile, Show
from media_manager.tv.schemas import SeasonFile as SeasonFileSchema
from media_manager.tv.schemas import Show as ShowSchema
@@ -17,22 +21,19 @@ class TorrentRepository:
def __init__(self, db: DbSessionDependency) -> None:
self.db = db
def get_episode_files_of_torrent(
def get_seasons_files_of_torrent(
self, torrent_id: TorrentId
) -> list[EpisodeFileSchema]:
stmt = select(EpisodeFile).where(EpisodeFile.torrent_id == torrent_id)
) -> list[SeasonFileSchema]:
stmt = select(SeasonFile).where(SeasonFile.torrent_id == torrent_id)
result = self.db.execute(stmt).scalars().all()
return [
EpisodeFileSchema.model_validate(episode_file) for episode_file in result
]
return [SeasonFileSchema.model_validate(season_file) for season_file in result]
def get_show_of_torrent(self, torrent_id: TorrentId) -> ShowSchema | None:
stmt = (
select(Show)
.join(Show.seasons)
.join(Season.episodes)
.join(Episode.episode_files)
.where(EpisodeFile.torrent_id == torrent_id)
.join(SeasonFile.season)
.join(Season.show)
.where(SeasonFile.torrent_id == torrent_id)
)
result = self.db.execute(stmt).unique().scalar_one_or_none()
if result is None:
@@ -68,10 +69,10 @@ class TorrentRepository:
)
self.db.execute(movie_files_stmt)
episode_files_stmt = delete(EpisodeFile).where(
EpisodeFile.torrent_id == torrent_id
season_files_stmt = delete(SeasonFile).where(
SeasonFile.torrent_id == torrent_id
)
self.db.execute(episode_files_stmt)
self.db.execute(season_files_stmt)
self.db.delete(self.db.get(Torrent, torrent_id))

View File

@@ -5,7 +5,7 @@ from media_manager.movies.schemas import Movie, MovieFile
from media_manager.torrent.manager import DownloadManager
from media_manager.torrent.repository import TorrentRepository
from media_manager.torrent.schemas import Torrent, TorrentId
from media_manager.tv.schemas import EpisodeFile, Show
from media_manager.tv.schemas import SeasonFile, Show
log = logging.getLogger(__name__)
@@ -19,13 +19,13 @@ class TorrentService:
self.torrent_repository = torrent_repository
self.download_manager = download_manager or DownloadManager()
def get_episode_files_of_torrent(self, torrent: Torrent) -> list[EpisodeFile]:
def get_season_files_of_torrent(self, torrent: Torrent) -> list[SeasonFile]:
"""
Returns all episode files of a torrent
:param torrent: the torrent to get the episode files of
:return: list of episode files
Returns all season files of a torrent
:param torrent: the torrent to get the season files of
:return: list of season files
"""
return self.torrent_repository.get_episode_files_of_torrent(
return self.torrent_repository.get_seasons_files_of_torrent(
torrent_id=torrent.id
)

View File

@@ -133,8 +133,7 @@ def get_torrent_hash(torrent: IndexerQueryResult) -> str:
:return: The hash of the torrent.
"""
torrent_filepath = (
MediaManagerConfig().misc.torrent_directory
/ f"{sanitize_filename(torrent.title)}.torrent"
MediaManagerConfig().misc.torrent_directory / f"{sanitize_filename(torrent.title)}.torrent"
)
if torrent_filepath.exists():
log.warning(f"Torrent file already exists at: {torrent_filepath}")

View File

@@ -3,6 +3,7 @@ from uuid import UUID
from sqlalchemy import ForeignKey, PrimaryKeyConstraint, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from media_manager.auth.db import User
from media_manager.database import Base
from media_manager.torrent.models import Quality
@@ -47,6 +48,13 @@ class Season(Base):
back_populates="season", cascade="all, delete"
)
season_files = relationship(
"SeasonFile", back_populates="season", cascade="all, delete"
)
season_requests = relationship(
"SeasonRequest", back_populates="season", cascade="all, delete"
)
class Episode(Base):
__tablename__ = "episode"
@@ -58,19 +66,15 @@ class Episode(Base):
number: Mapped[int]
external_id: Mapped[int]
title: Mapped[str]
overview: Mapped[str | None] = mapped_column(nullable=True)
season: Mapped["Season"] = relationship(back_populates="episodes")
episode_files = relationship(
"EpisodeFile", back_populates="episode", cascade="all, delete"
)
class EpisodeFile(Base):
__tablename__ = "episode_file"
__table_args__ = (PrimaryKeyConstraint("episode_id", "file_path_suffix"),)
episode_id: Mapped[UUID] = mapped_column(
ForeignKey(column="episode.id", ondelete="CASCADE"),
class SeasonFile(Base):
__tablename__ = "season_file"
__table_args__ = (PrimaryKeyConstraint("season_id", "file_path_suffix"),)
season_id: Mapped[UUID] = mapped_column(
ForeignKey(column="season.id", ondelete="CASCADE"),
)
torrent_id: Mapped[UUID | None] = mapped_column(
ForeignKey(column="torrent.id", ondelete="SET NULL"),
@@ -78,5 +82,31 @@ class EpisodeFile(Base):
file_path_suffix: Mapped[str]
quality: Mapped[Quality]
torrent = relationship("Torrent", back_populates="episode_files", uselist=False)
episode = relationship("Episode", back_populates="episode_files", uselist=False)
torrent = relationship("Torrent", back_populates="season_files", uselist=False)
season = relationship("Season", back_populates="season_files", uselist=False)
class SeasonRequest(Base):
__tablename__ = "season_request"
__table_args__ = (UniqueConstraint("season_id", "wanted_quality"),)
id: Mapped[UUID] = mapped_column(primary_key=True)
season_id: Mapped[UUID] = mapped_column(
ForeignKey(column="season.id", ondelete="CASCADE"),
)
wanted_quality: Mapped[Quality]
min_quality: Mapped[Quality]
requested_by_id: Mapped[UUID | None] = mapped_column(
ForeignKey(column="user.id", ondelete="SET NULL"),
)
authorized: Mapped[bool] = mapped_column(default=False)
authorized_by_id: Mapped[UUID | None] = mapped_column(
ForeignKey(column="user.id", ondelete="SET NULL"),
)
requested_by: Mapped["User|None"] = relationship(
foreign_keys=[requested_by_id], uselist=False
)
authorized_by: Mapped["User|None"] = relationship(
foreign_keys=[authorized_by_id], uselist=False
)
season = relationship("Season", back_populates="season_requests", uselist=False)

View File

@@ -1,5 +1,8 @@
from sqlalchemy import delete, func, select
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from sqlalchemy.exc import (
IntegrityError,
SQLAlchemyError,
)
from sqlalchemy.orm import Session, joinedload
from media_manager.exceptions import ConflictError, NotFoundError
@@ -7,18 +10,32 @@ from media_manager.torrent.models import Torrent
from media_manager.torrent.schemas import Torrent as TorrentSchema
from media_manager.torrent.schemas import TorrentId
from media_manager.tv import log
from media_manager.tv.models import Episode, EpisodeFile, Season, Show
from media_manager.tv.schemas import Episode as EpisodeSchema
from media_manager.tv.schemas import EpisodeFile as EpisodeFileSchema
from media_manager.tv.models import Episode, Season, SeasonFile, SeasonRequest, Show
from media_manager.tv.schemas import (
Episode as EpisodeSchema,
)
from media_manager.tv.schemas import (
EpisodeId,
EpisodeNumber,
SeasonId,
SeasonNumber,
SeasonRequestId,
ShowId,
)
from media_manager.tv.schemas import Season as SeasonSchema
from media_manager.tv.schemas import Show as ShowSchema
from media_manager.tv.schemas import (
RichSeasonRequest as RichSeasonRequestSchema,
)
from media_manager.tv.schemas import (
Season as SeasonSchema,
)
from media_manager.tv.schemas import (
SeasonFile as SeasonFileSchema,
)
from media_manager.tv.schemas import (
SeasonRequest as SeasonRequestSchema,
)
from media_manager.tv.schemas import (
Show as ShowSchema,
)
class TvRepository:
@@ -103,7 +120,9 @@ class TvRepository:
def get_total_downloaded_episodes_count(self) -> int:
try:
stmt = select(func.count(Episode.id)).select_from(Episode).join(EpisodeFile)
stmt = (
select(func.count()).select_from(Episode).join(Season).join(SeasonFile)
)
return self.db.execute(stmt).scalar_one_or_none()
except SQLAlchemyError:
log.exception("Database error while calculating downloaded episodes count")
@@ -154,7 +173,6 @@ class TvRepository:
number=episode.number,
external_id=episode.external_id,
title=episode.title,
overview=episode.overview,
)
for episode in season.episodes
],
@@ -216,40 +234,64 @@ class TvRepository:
log.exception(f"Database error while retrieving season {season_id}")
raise
def get_episode(self, episode_id: EpisodeId) -> EpisodeSchema:
def add_season_request(
self, season_request: SeasonRequestSchema
) -> SeasonRequestSchema:
"""
Retrieve an episode by its ID.
Adds a Season to the SeasonRequest table, which marks it as requested.
:param episode_id: The ID of the episode to get.
:return: An Episode object.
:raises NotFoundError: If the episode with the given ID is not found.
:param season_request: The SeasonRequest object to add.
:return: The added SeasonRequest object.
:raises IntegrityError: If a similar request already exists or violates constraints.
:raises SQLAlchemyError: If a database error occurs.
"""
db_model = SeasonRequest(
id=season_request.id,
season_id=season_request.season_id,
wanted_quality=season_request.wanted_quality,
min_quality=season_request.min_quality,
requested_by_id=season_request.requested_by.id
if season_request.requested_by
else None,
authorized=season_request.authorized,
authorized_by_id=season_request.authorized_by.id
if season_request.authorized_by
else None,
)
try:
self.db.add(db_model)
self.db.commit()
self.db.refresh(db_model)
return SeasonRequestSchema.model_validate(db_model)
except IntegrityError:
self.db.rollback()
log.exception("Integrity error while adding season request")
raise
except SQLAlchemyError:
self.db.rollback()
log.exception("Database error while adding season request")
raise
def delete_season_request(self, season_request_id: SeasonRequestId) -> None:
"""
Removes a SeasonRequest by its ID.
:param season_request_id: The ID of the season request to delete.
:raises NotFoundError: If the season request is not found.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
episode = self.db.get(Episode, episode_id)
if not episode:
msg = f"Episode with id {episode_id} not found."
stmt = delete(SeasonRequest).where(SeasonRequest.id == season_request_id)
result = self.db.execute(stmt)
if result.rowcount == 0:
self.db.rollback()
msg = f"SeasonRequest with id {season_request_id} not found."
raise NotFoundError(msg)
return EpisodeSchema.model_validate(episode)
except SQLAlchemyError as e:
log.error(f"Database error while retrieving episode {episode_id}: {e}")
raise
def get_season_by_episode(self, episode_id: EpisodeId) -> SeasonSchema:
try:
stmt = select(Season).join(Season.episodes).where(Episode.id == episode_id)
season = self.db.scalar(stmt)
if not season:
msg = f"Season not found for episode {episode_id}"
raise NotFoundError(msg)
return SeasonSchema.model_validate(season)
except SQLAlchemyError as e:
log.error(
f"Database error while retrieving season for episode {episode_id}: {e}"
self.db.commit()
except SQLAlchemyError:
self.db.rollback()
log.exception(
f"Database error while deleting season request {season_request_id}"
)
raise
@@ -281,46 +323,78 @@ class TvRepository:
)
raise
def add_episode_file(self, episode_file: EpisodeFileSchema) -> EpisodeFileSchema:
def get_season_requests(self) -> list[RichSeasonRequestSchema]:
"""
Adds an episode file record to the database.
Retrieve all season requests.
:param episode_file: The EpisodeFile object to add.
:return: The added EpisodeFile object.
:return: A list of RichSeasonRequest objects.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = select(SeasonRequest).options(
joinedload(SeasonRequest.requested_by),
joinedload(SeasonRequest.authorized_by),
joinedload(SeasonRequest.season).joinedload(Season.show),
)
results = self.db.execute(stmt).scalars().unique().all()
return [
RichSeasonRequestSchema(
id=SeasonRequestId(x.id),
min_quality=x.min_quality,
wanted_quality=x.wanted_quality,
season_id=SeasonId(x.season_id),
show=x.season.show,
season=x.season,
requested_by=x.requested_by,
authorized_by=x.authorized_by,
authorized=x.authorized,
)
for x in results
]
except SQLAlchemyError:
log.exception("Database error while retrieving season requests")
raise
def add_season_file(self, season_file: SeasonFileSchema) -> SeasonFileSchema:
"""
Adds a season file record to the database.
:param season_file: The SeasonFile object to add.
:return: The added SeasonFile object.
:raises IntegrityError: If the record violates constraints.
:raises SQLAlchemyError: If a database error occurs.
"""
db_model = EpisodeFile(**episode_file.model_dump())
db_model = SeasonFile(**season_file.model_dump())
try:
self.db.add(db_model)
self.db.commit()
self.db.refresh(db_model)
return EpisodeFileSchema.model_validate(db_model)
except IntegrityError as e:
return SeasonFileSchema.model_validate(db_model)
except IntegrityError:
self.db.rollback()
log.error(f"Integrity error while adding episode file: {e}")
log.exception("Integrity error while adding season file")
raise
except SQLAlchemyError as e:
except SQLAlchemyError:
self.db.rollback()
log.error(f"Database error while adding episode file: {e}")
log.exception("Database error while adding season file")
raise
def remove_episode_files_by_torrent_id(self, torrent_id: TorrentId) -> int:
def remove_season_files_by_torrent_id(self, torrent_id: TorrentId) -> int:
"""
Removes episode file records associated with a given torrent ID.
Removes season file records associated with a given torrent ID.
:param torrent_id: The ID of the torrent whose episode files are to be removed.
:return: The number of episode files removed.
:param torrent_id: The ID of the torrent whose season files are to be removed.
:return: The number of season files removed.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = delete(EpisodeFile).where(EpisodeFile.torrent_id == torrent_id)
stmt = delete(SeasonFile).where(SeasonFile.torrent_id == torrent_id)
result = self.db.execute(stmt)
self.db.commit()
except SQLAlchemyError:
self.db.rollback()
log.exception(
f"Database error removing episode files for torrent_id {torrent_id}"
f"Database error removing season files for torrent_id {torrent_id}"
)
raise
return result.rowcount
@@ -346,45 +420,23 @@ class TvRepository:
log.exception(f"Database error setting library for show {show_id}")
raise
def get_episode_files_by_season_id(
def get_season_files_by_season_id(
self, season_id: SeasonId
) -> list[EpisodeFileSchema]:
) -> list[SeasonFileSchema]:
"""
Retrieve all episode files for a given season ID.
Retrieve all season files for a given season ID.
:param season_id: The ID of the season.
:return: A list of EpisodeFile objects.
:return: A list of SeasonFile objects.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = (
select(EpisodeFile).join(Episode).where(Episode.season_id == season_id)
)
stmt = select(SeasonFile).where(SeasonFile.season_id == season_id)
results = self.db.execute(stmt).scalars().all()
return [EpisodeFileSchema.model_validate(ef) for ef in results]
return [SeasonFileSchema.model_validate(sf) for sf in results]
except SQLAlchemyError:
log.exception(
f"Database error retrieving episode files for season_id {season_id}"
)
raise
def get_episode_files_by_episode_id(
self, episode_id: EpisodeId
) -> list[EpisodeFileSchema]:
"""
Retrieve all episode files for a given episode ID.
:param episode_id: The ID of the episode.
:return: A list of EpisodeFile objects.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = select(EpisodeFile).where(EpisodeFile.episode_id == episode_id)
results = self.db.execute(stmt).scalars().all()
return [EpisodeFileSchema.model_validate(sf) for sf in results]
except SQLAlchemyError as e:
log.error(
f"Database error retrieving episode files for episode_id {episode_id}: {e}"
f"Database error retrieving season files for season_id {season_id}"
)
raise
@@ -400,9 +452,8 @@ class TvRepository:
stmt = (
select(Torrent)
.distinct()
.join(EpisodeFile, EpisodeFile.torrent_id == Torrent.id)
.join(Episode, Episode.id == EpisodeFile.episode_id)
.join(Season, Season.id == Episode.season_id)
.join(SeasonFile, SeasonFile.torrent_id == Torrent.id)
.join(Season, Season.id == SeasonFile.season_id)
.where(Season.show_id == show_id)
)
results = self.db.execute(stmt).scalars().unique().all()
@@ -423,9 +474,8 @@ class TvRepository:
select(Show)
.distinct()
.join(Season, Show.id == Season.show_id)
.join(Episode, Season.id == Episode.season_id)
.join(EpisodeFile, Episode.id == EpisodeFile.episode_id)
.join(Torrent, EpisodeFile.torrent_id == Torrent.id)
.join(SeasonFile, Season.id == SeasonFile.season_id)
.join(Torrent, SeasonFile.torrent_id == Torrent.id)
.options(joinedload(Show.seasons).joinedload(Season.episodes))
.order_by(Show.name)
)
@@ -447,9 +497,8 @@ class TvRepository:
stmt = (
select(Season.number)
.distinct()
.join(Episode, Episode.season_id == Season.id)
.join(EpisodeFile, EpisodeFile.episode_id == Episode.id)
.where(EpisodeFile.torrent_id == torrent_id)
.join(SeasonFile, Season.id == SeasonFile.season_id)
.where(SeasonFile.torrent_id == torrent_id)
)
results = self.db.execute(stmt).scalars().unique().all()
return [SeasonNumber(x) for x in results]
@@ -459,29 +508,27 @@ class TvRepository:
)
raise
def get_episodes_by_torrent_id(self, torrent_id: TorrentId) -> list[EpisodeNumber]:
def get_season_request(
self, season_request_id: SeasonRequestId
) -> SeasonRequestSchema:
"""
Retrieve episode numbers associated with a given torrent ID.
Retrieve a season request by its ID.
:param torrent_id: The ID of the torrent.
:return: A list of EpisodeNumber objects.
:param season_request_id: The ID of the season request.
:return: A SeasonRequest object.
:raises NotFoundError: If the season request is not found.
:raises SQLAlchemyError: If a database error occurs.
"""
try:
stmt = (
select(Episode.number)
.join(EpisodeFile, EpisodeFile.episode_id == Episode.id)
.where(EpisodeFile.torrent_id == torrent_id)
.order_by(Episode.number)
)
episode_numbers = self.db.execute(stmt).scalars().all()
return [EpisodeNumber(n) for n in sorted(set(episode_numbers))]
except SQLAlchemyError as e:
log.error(
f"Database error retrieving episodes for torrent_id {torrent_id}: {e}"
request = self.db.get(SeasonRequest, season_request_id)
if not request:
log.warning(f"Season request with id {season_request_id} not found.")
msg = f"Season request with id {season_request_id} not found."
raise NotFoundError(msg)
return SeasonRequestSchema.model_validate(request)
except SQLAlchemyError:
log.exception(
f"Database error retrieving season request {season_request_id}"
)
raise
@@ -684,21 +731,14 @@ class TvRepository:
if updated:
self.db.commit()
self.db.refresh(db_season)
log.debug(
f"Updating existing season {db_season.number} for show {db_season.show.name}"
)
return SeasonSchema.model_validate(db_season)
def update_episode_attributes(
self,
episode_id: EpisodeId,
title: str | None = None,
overview: str | None = None,
self, episode_id: EpisodeId, title: str | None = None
) -> EpisodeSchema:
"""
Update attributes of an existing episode.
:param overview: Tje new overview for the episode.
:param episode_id: The ID of the episode to update.
:param title: The new title for the episode.
:param external_id: The new external ID for the episode.
@@ -715,12 +755,8 @@ class TvRepository:
if title is not None and db_episode.title != title:
db_episode.title = title
updated = True
if overview is not None and db_episode.overview != overview:
db_episode.overview = overview
updated = True
if updated:
self.db.commit()
self.db.refresh(db_episode)
log.info(f"Updating existing episode {db_episode.number}")
return EpisodeSchema.model_validate(db_episode)

View File

@@ -1,7 +1,10 @@
from pathlib import Path
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from media_manager.auth.db import User
from media_manager.auth.schemas import UserRead
from media_manager.auth.users import current_active_user, current_superuser
from media_manager.config import LibraryItem, MediaManagerConfig
from media_manager.exceptions import MediaAlreadyExistsError, NotFoundError
@@ -14,18 +17,24 @@ from media_manager.metadataProvider.schemas import MetaDataProviderSearchResult
from media_manager.schemas import MediaImportSuggestion
from media_manager.torrent.schemas import Torrent
from media_manager.torrent.utils import get_importable_media_directories
from media_manager.tv import log
from media_manager.tv.dependencies import (
season_dep,
show_dep,
tv_service_dep,
)
from media_manager.tv.schemas import (
PublicEpisodeFile,
CreateSeasonRequest,
PublicSeasonFile,
PublicShow,
RichSeasonRequest,
RichShowTorrent,
Season,
SeasonRequest,
SeasonRequestId,
Show,
ShowId,
UpdateSeasonRequest,
)
router = APIRouter()
@@ -269,6 +278,110 @@ def get_a_shows_torrents(show: show_dep, tv_service: tv_service_dep) -> RichShow
return tv_service.get_torrents_for_show(show=show)
# -----------------------------------------------------------------------------
# SEASONS - REQUESTS
# -----------------------------------------------------------------------------
@router.get(
"/seasons/requests",
status_code=status.HTTP_200_OK,
dependencies=[Depends(current_active_user)],
)
def get_season_requests(tv_service: tv_service_dep) -> list[RichSeasonRequest]:
"""
Get all season requests.
"""
return tv_service.get_all_season_requests()
@router.post("/seasons/requests", status_code=status.HTTP_204_NO_CONTENT)
def request_a_season(
user: Annotated[User, Depends(current_active_user)],
season_request: CreateSeasonRequest,
tv_service: tv_service_dep,
) -> None:
"""
Create a new season request.
"""
request: SeasonRequest = SeasonRequest.model_validate(season_request)
request.requested_by = UserRead.model_validate(user)
if user.is_superuser:
request.authorized = True
request.authorized_by = UserRead.model_validate(user)
tv_service.add_season_request(request)
return
@router.put("/seasons/requests", status_code=status.HTTP_204_NO_CONTENT)
def update_request(
tv_service: tv_service_dep,
user: Annotated[User, Depends(current_active_user)],
season_request: UpdateSeasonRequest,
) -> None:
"""
Update an existing season request.
"""
updated_season_request: SeasonRequest = SeasonRequest.model_validate(season_request)
request = tv_service.get_season_request_by_id(
season_request_id=updated_season_request.id
)
if request.requested_by.id == user.id or user.is_superuser:
updated_season_request.requested_by = UserRead.model_validate(user)
tv_service.update_season_request(season_request=updated_season_request)
return
@router.patch(
"/seasons/requests/{season_request_id}", status_code=status.HTTP_204_NO_CONTENT
)
def authorize_request(
tv_service: tv_service_dep,
user: Annotated[User, Depends(current_superuser)],
season_request_id: SeasonRequestId,
authorized_status: bool = False,
) -> None:
"""
Authorize or de-authorize a season request.
"""
season_request = tv_service.get_season_request_by_id(
season_request_id=season_request_id
)
if not season_request:
raise NotFoundError
season_request.authorized_by = UserRead.model_validate(user)
season_request.authorized = authorized_status
if not authorized_status:
season_request.authorized_by = None
tv_service.update_season_request(season_request=season_request)
@router.delete(
"/seasons/requests/{request_id}",
status_code=status.HTTP_204_NO_CONTENT,
)
def delete_season_request(
tv_service: tv_service_dep,
user: Annotated[User, Depends(current_active_user)],
request_id: SeasonRequestId,
) -> None:
"""
Delete a season request.
"""
request = tv_service.get_season_request_by_id(season_request_id=request_id)
if user.is_superuser or request.requested_by.id == user.id:
tv_service.delete_season_request(season_request_id=request_id)
log.info(f"User {user.id} deleted season request {request_id}.")
return
log.warning(
f"User {user.id} tried to delete season request {request_id} but is not authorized."
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to delete this request",
)
# -----------------------------------------------------------------------------
# SEASONS
# -----------------------------------------------------------------------------
@@ -289,13 +402,13 @@ def get_season(season: season_dep) -> Season:
"/seasons/{season_id}/files",
dependencies=[Depends(current_active_user)],
)
def get_episode_files(
def get_season_files(
season: season_dep, tv_service: tv_service_dep
) -> list[PublicEpisodeFile]:
) -> list[PublicSeasonFile]:
"""
Get episode files associated with a specific season.
Get files associated with a specific season.
"""
return tv_service.get_public_episode_files_by_season_id(season=season)
return tv_service.get_public_season_files_by_season_id(season=season)
# -----------------------------------------------------------------------------

View File

@@ -2,8 +2,9 @@ import typing
import uuid
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, model_validator
from media_manager.auth.schemas import UserRead
from media_manager.torrent.models import Quality
from media_manager.torrent.schemas import TorrentId, TorrentStatus
@@ -13,6 +14,7 @@ EpisodeId = typing.NewType("EpisodeId", UUID)
SeasonNumber = typing.NewType("SeasonNumber", int)
EpisodeNumber = typing.NewType("EpisodeNumber", int)
SeasonRequestId = typing.NewType("SeasonRequestId", UUID)
class Episode(BaseModel):
@@ -22,7 +24,6 @@ class Episode(BaseModel):
number: EpisodeNumber
external_id: int
title: str
overview: str | None = None
class Season(BaseModel):
@@ -61,16 +62,52 @@ class Show(BaseModel):
seasons: list[Season]
class EpisodeFile(BaseModel):
class SeasonRequestBase(BaseModel):
min_quality: Quality
wanted_quality: Quality
@model_validator(mode="after")
def ensure_wanted_quality_is_eq_or_gt_min_quality(self) -> "SeasonRequestBase":
if self.min_quality.value < self.wanted_quality.value:
msg = "wanted_quality must be equal to or lower than minimum_quality."
raise ValueError(msg)
return self
class CreateSeasonRequest(SeasonRequestBase):
season_id: SeasonId
class UpdateSeasonRequest(SeasonRequestBase):
id: SeasonRequestId
class SeasonRequest(SeasonRequestBase):
model_config = ConfigDict(from_attributes=True)
episode_id: EpisodeId
id: SeasonRequestId = Field(default_factory=lambda: SeasonRequestId(uuid.uuid4()))
season_id: SeasonId
requested_by: UserRead | None = None
authorized: bool = False
authorized_by: UserRead | None = None
class RichSeasonRequest(SeasonRequest):
show: Show
season: Season
class SeasonFile(BaseModel):
model_config = ConfigDict(from_attributes=True)
season_id: SeasonId
quality: Quality
torrent_id: TorrentId | None
file_path_suffix: str
class PublicEpisodeFile(EpisodeFile):
class PublicSeasonFile(SeasonFile):
downloaded: bool = False
@@ -86,7 +123,6 @@ class RichSeasonTorrent(BaseModel):
file_path_suffix: str
seasons: list[SeasonNumber]
episodes: list[EpisodeNumber]
class RichShowTorrent(BaseModel):
@@ -99,18 +135,6 @@ class RichShowTorrent(BaseModel):
torrents: list[RichSeasonTorrent]
class PublicEpisode(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: EpisodeId
number: EpisodeNumber
downloaded: bool = False
title: str
overview: str | None = None
external_id: int
class PublicSeason(BaseModel):
model_config = ConfigDict(from_attributes=True)
@@ -123,7 +147,7 @@ class PublicSeason(BaseModel):
external_id: int
episodes: list[PublicEpisode]
episodes: list[Episode]
class PublicShow(BaseModel):

View File

@@ -7,7 +7,9 @@ from typing import overload
from sqlalchemy.exc import IntegrityError
from media_manager.config import MediaManagerConfig
from media_manager.database import get_session
from media_manager.exceptions import InvalidConfigError, NotFoundError, RenameError
from media_manager.indexer.repository import IndexerRepository
from media_manager.indexer.schemas import IndexerQueryResult, IndexerQueryResultId
from media_manager.indexer.service import IndexerService
from media_manager.indexer.utils import evaluate_indexer_query_results
@@ -17,10 +19,13 @@ from media_manager.metadataProvider.abstract_metadata_provider import (
from media_manager.metadataProvider.schemas import MetaDataProviderSearchResult
from media_manager.metadataProvider.tmdb import TmdbMetadataProvider
from media_manager.metadataProvider.tvdb import TvdbMetadataProvider
from media_manager.notification.repository import NotificationRepository
from media_manager.notification.service import NotificationService
from media_manager.schemas import MediaImportSuggestion
from media_manager.torrent.repository import TorrentRepository
from media_manager.torrent.schemas import (
Quality,
QualityStrings,
Torrent,
TorrentStatus,
)
@@ -36,17 +41,21 @@ from media_manager.torrent.utils import (
from media_manager.tv import log
from media_manager.tv.repository import TvRepository
from media_manager.tv.schemas import (
Episode,
EpisodeFile,
Episode as EpisodeSchema,
)
from media_manager.tv.schemas import (
EpisodeId,
EpisodeNumber,
PublicEpisodeFile,
PublicSeason,
PublicSeasonFile,
PublicShow,
RichSeasonRequest,
RichSeasonTorrent,
RichShowTorrent,
Season,
SeasonFile,
SeasonId,
SeasonRequest,
SeasonRequestId,
Show,
ShowId,
)
@@ -85,6 +94,28 @@ class TvService:
metadata_provider.download_show_poster_image(show=saved_show)
return saved_show
def add_season_request(self, season_request: SeasonRequest) -> SeasonRequest:
"""
Add a new season request.
:param season_request: The season request to add.
:return: The added season request.
"""
return self.tv_repository.add_season_request(season_request=season_request)
def get_season_request_by_id(
self, season_request_id: SeasonRequestId
) -> SeasonRequest | None:
"""
Get a season request by its ID.
:param season_request_id: The ID of the season request.
:return: The season request or None if not found.
"""
return self.tv_repository.get_season_request(
season_request_id=season_request_id
)
def get_total_downloaded_episoded_count(self) -> int:
"""
Get total number of downloaded episodes.
@@ -92,9 +123,27 @@ class TvService:
return self.tv_repository.get_total_downloaded_episodes_count()
def update_season_request(self, season_request: SeasonRequest) -> SeasonRequest:
"""
Update an existing season request.
:param season_request: The season request to update.
:return: The updated season request.
"""
self.tv_repository.delete_season_request(season_request_id=season_request.id)
return self.tv_repository.add_season_request(season_request=season_request)
def set_show_library(self, show: Show, library: str) -> None:
self.tv_repository.set_show_library(show_id=show.id, library=library)
def delete_season_request(self, season_request_id: SeasonRequestId) -> None:
"""
Delete a season request by its ID.
:param season_request_id: The ID of the season request to delete.
"""
self.tv_repository.delete_season_request(season_request_id=season_request_id)
def delete_show(
self,
show: Show,
@@ -124,7 +173,6 @@ class TvService:
for torrent in torrents:
try:
self.torrent_service.cancel_download(torrent, delete_files=True)
self.torrent_service.delete_torrent(torrent_id=torrent.id)
log.info(f"Deleted torrent: {torrent.hash}")
except Exception:
log.warning(
@@ -133,26 +181,24 @@ class TvService:
self.tv_repository.delete_show(show_id=show.id)
def get_public_episode_files_by_season_id(
def get_public_season_files_by_season_id(
self, season: Season
) -> list[PublicEpisodeFile]:
) -> list[PublicSeasonFile]:
"""
Get all public episode files for a given season.
Get all public season files for a given season.
:param season: The season object.
:return: A list of public episode files.
:return: A list of public season files.
"""
episode_files = self.tv_repository.get_episode_files_by_season_id(
season_files = self.tv_repository.get_season_files_by_season_id(
season_id=season.id
)
public_episode_files = [
PublicEpisodeFile.model_validate(x) for x in episode_files
]
public_season_files = [PublicSeasonFile.model_validate(x) for x in season_files]
result = []
for episode_file in public_episode_files:
if self.episode_file_exists_on_file(episode_file=episode_file):
episode_file.downloaded = True
result.append(episode_file)
for season_file in public_season_files:
if self.season_file_exists_on_file(season_file=season_file):
season_file.downloaded = True
result.append(season_file)
return result
@overload
@@ -288,27 +334,11 @@ class TvService:
:param show: The show object.
:return: A public show.
"""
seasons = [PublicSeason.model_validate(season) for season in show.seasons]
for season in seasons:
season.downloaded = self.is_season_downloaded(season_id=season.id)
public_show = PublicShow.model_validate(show)
public_seasons: list[PublicSeason] = []
for season in show.seasons:
public_season = PublicSeason.model_validate(season)
for episode in public_season.episodes:
episode.downloaded = self.is_episode_downloaded(
episode=episode,
season=season,
show=show,
)
# A season is considered downloaded if it has episodes and all of them are downloaded,
# matching the behavior of is_season_downloaded.
public_season.downloaded = bool(public_season.episodes) and all(
episode.downloaded for episode in public_season.episodes
)
public_seasons.append(public_season)
public_show.seasons = public_seasons
public_show.seasons = seasons
return public_show
def get_show_by_id(self, show_id: ShowId) -> Show:
@@ -320,85 +350,33 @@ class TvService:
"""
return self.tv_repository.get_show_by_id(show_id=show_id)
def is_season_downloaded(self, season: Season, show: Show) -> bool:
def is_season_downloaded(self, season_id: SeasonId) -> bool:
"""
Check if a season is downloaded.
:param season: The season object.
:param show: The show object.
:param season_id: The ID of the season.
:return: True if the season is downloaded, False otherwise.
"""
episodes = season.episodes
if not episodes:
return False
for episode in episodes:
if not self.is_episode_downloaded(
episode=episode, season=season, show=show
):
return False
return True
def is_episode_downloaded(
self, episode: Episode, season: Season, show: Show
) -> bool:
"""
Check if an episode is downloaded and imported (file exists on disk).
An episode is considered downloaded if:
- There is at least one EpisodeFile in the database AND
- A matching episode file exists in the season directory on disk.
:param episode: The episode object.
:param season: The season object.
:param show: The show object.
:return: True if the episode is downloaded and imported, False otherwise.
"""
episode_files = self.tv_repository.get_episode_files_by_episode_id(
episode_id=episode.id
season_files = self.tv_repository.get_season_files_by_season_id(
season_id=season_id
)
if not episode_files:
return False
season_dir = self.get_root_season_directory(show, season.number)
if not season_dir.exists():
return False
episode_token = f"S{season.number:02d}E{episode.number:02d}"
video_extensions = {".mkv", ".mp4", ".avi", ".mov"}
try:
for file in season_dir.iterdir():
if (
file.is_file()
and episode_token.lower() in file.name.lower()
and file.suffix.lower() in video_extensions
):
return True
except OSError as e:
log.error(
f"Disk check failed for episode {episode.id} in {season_dir}: {e}"
)
for season_file in season_files:
if self.season_file_exists_on_file(season_file=season_file):
return True
return False
def episode_file_exists_on_file(self, episode_file: EpisodeFile) -> bool:
def season_file_exists_on_file(self, season_file: SeasonFile) -> bool:
"""
Check if an episode file exists on the filesystem.
Check if a season file exists on the filesystem.
:param episode_file: The episode file to check.
:param season_file: The season file to check.
:return: True if the file exists, False otherwise.
"""
if episode_file.torrent_id is None:
if season_file.torrent_id is None:
return True
try:
torrent_file = self.torrent_service.get_torrent_by_id(
torrent_id=episode_file.torrent_id
torrent_id=season_file.torrent_id
)
if torrent_file.imported:
@@ -431,23 +409,13 @@ class TvService:
"""
return self.tv_repository.get_season(season_id=season_id)
def get_episode(self, episode_id: EpisodeId) -> Episode:
def get_all_season_requests(self) -> list[RichSeasonRequest]:
"""
Get an episode by its ID.
Get all season requests.
:param episode_id: The ID of the episode.
:return: The episode.
:return: A list of rich season requests.
"""
return self.tv_repository.get_episode(episode_id=episode_id)
def get_season_by_episode(self, episode_id: EpisodeId) -> Season:
"""
Get a season by the episode ID.
:param episode_id: The ID of the episode.
:return: The season.
"""
return self.tv_repository.get_season_by_episode(episode_id=episode_id)
return self.tv_repository.get_season_requests()
def get_torrents_for_show(self, show: Show) -> RichShowTorrent:
"""
@@ -462,16 +430,10 @@ class TvService:
seasons = self.tv_repository.get_seasons_by_torrent_id(
torrent_id=show_torrent.id
)
episodes = self.tv_repository.get_episodes_by_torrent_id(
torrent_id=show_torrent.id
)
episode_files = self.torrent_service.get_episode_files_of_torrent(
season_files = self.torrent_service.get_season_files_of_torrent(
torrent=show_torrent
)
file_path_suffix = (
episode_files[0].file_path_suffix if episode_files else ""
)
file_path_suffix = season_files[0].file_path_suffix if season_files else ""
season_torrent = RichSeasonTorrent(
torrent_id=show_torrent.id,
torrent_title=show_torrent.title,
@@ -479,12 +441,10 @@ class TvService:
quality=show_torrent.quality,
imported=show_torrent.imported,
seasons=seasons,
episodes=episodes if len(seasons) == 1 else [],
file_path_suffix=file_path_suffix,
usenet=show_torrent.usenet,
)
rich_season_torrents.append(season_torrent)
return RichShowTorrent(
show_id=show.id,
name=show.name,
@@ -527,54 +487,95 @@ class TvService:
season = self.tv_repository.get_season_by_number(
season_number=season_number, show_id=show_id
)
episodes = {episode.number: episode.id for episode in season.episodes}
if indexer_result.episode:
episode_ids = []
missing_episodes = []
for ep_number in indexer_result.episode:
ep_id = episodes.get(EpisodeNumber(ep_number))
if ep_id is None:
missing_episodes.append(ep_number)
continue
episode_ids.append(ep_id)
if missing_episodes:
log.warning(
"Some episodes from indexer result were not found in season %s "
"for show %s and will be skipped: %s",
season.id,
show_id,
", ".join(str(ep) for ep in missing_episodes),
)
else:
episode_ids = [episode.id for episode in season.episodes]
for episode_id in episode_ids:
episode_file = EpisodeFile(
episode_id=episode_id,
quality=indexer_result.quality,
torrent_id=show_torrent.id,
file_path_suffix=override_show_file_path_suffix,
)
self.tv_repository.add_episode_file(episode_file=episode_file)
season_file = SeasonFile(
season_id=season.id,
quality=indexer_result.quality,
torrent_id=show_torrent.id,
file_path_suffix=override_show_file_path_suffix,
)
self.tv_repository.add_season_file(season_file=season_file)
except IntegrityError:
log.error(
f"Episode file for episode {episode_id} of season {season.id} and quality {indexer_result.quality} already exists, skipping."
f"Season file for season {season.id} and quality {indexer_result.quality} already exists, skipping."
)
self.tv_repository.remove_episode_files_by_torrent_id(show_torrent.id)
self.torrent_service.cancel_download(
torrent=show_torrent, delete_files=True
)
raise
else:
log.info(
f"Successfully added episode files for torrent {show_torrent.title} and show ID {show_id}"
f"Successfully added season files for torrent {show_torrent.title} and show ID {show_id}"
)
self.torrent_service.resume_download(torrent=show_torrent)
return show_torrent
def download_approved_season_request(
self, season_request: SeasonRequest, show: Show
) -> bool:
"""
Download an approved season request.
:param season_request: The season request to download.
:param show: The Show object.
:return: True if the download was successful, False otherwise.
:raises ValueError: If the season request is not authorized.
"""
if not season_request.authorized:
msg = f"Season request {season_request.id} is not authorized for download"
raise ValueError(msg)
log.info(f"Downloading approved season request {season_request.id}")
season = self.get_season(season_id=season_request.season_id)
torrents = self.get_all_available_torrents_for_a_season(
season_number=season.number, show_id=show.id
)
available_torrents: list[IndexerQueryResult] = []
for torrent in torrents:
if (
(torrent.quality.value < season_request.wanted_quality.value)
or (torrent.quality.value > season_request.min_quality.value)
or (torrent.seeders < 3)
):
log.info(
f"Skipping torrent {torrent.title} with quality {torrent.quality} for season {season.id}, because it does not match the requested quality {season_request.wanted_quality}"
)
elif torrent.season != [season.number]:
log.info(
f"Skipping torrent {torrent.title} with quality {torrent.quality} for season {season.id}, because it contains to many/wrong seasons {torrent.season} (wanted: {season.number})"
)
else:
available_torrents.append(torrent)
log.info(
f"Taking torrent {torrent.title} with quality {torrent.quality} for season {season.id} into consideration"
)
if len(available_torrents) == 0:
log.warning(
f"No torrents matching criteria were found (wanted quality: {season_request.wanted_quality}, min_quality: {season_request.min_quality} for season {season.id})"
)
return False
available_torrents.sort()
torrent = self.torrent_service.download(indexer_result=available_torrents[0])
season_file = SeasonFile(
season_id=season.id,
quality=torrent.quality,
torrent_id=torrent.id,
file_path_suffix=QualityStrings[torrent.quality.name].value.upper(),
)
try:
self.tv_repository.add_season_file(season_file=season_file)
except IntegrityError:
log.warning(
f"Season file for season {season.id} and quality {torrent.quality} already exists, skipping."
)
self.delete_season_request(season_request.id)
return True
def get_root_show_directory(self, show: Show) -> Path:
misc_config = MediaManagerConfig().misc
show_directory_name = f"{remove_special_characters(show.name)} ({show.year}) [{show.metadata_provider}id-{show.external_id}]"
@@ -652,12 +653,12 @@ class TvService:
video_files: list[Path],
subtitle_files: list[Path],
file_path_suffix: str = "",
) -> tuple[bool, list[Episode]]:
) -> tuple[bool, int]:
season_path = self.get_root_season_directory(
show=show, season_number=season.number
)
success = True
imported_episodes = []
imported_episodes_count = 0
try:
season_path.mkdir(parents=True, exist_ok=True)
except Exception as e:
@@ -676,7 +677,7 @@ class TvService:
file_path_suffix=file_path_suffix,
)
if imported:
imported_episodes.append(episode)
imported_episodes_count += 1
except Exception:
# Send notification about missing episode file
@@ -689,72 +690,11 @@ class TvService:
log.warning(
f"S{season.number}E{episode.number} not found when trying to import episode for show {show.name}."
)
return success, imported_episodes
return success, imported_episodes_count
def import_episode_files(
self,
show: Show,
season: Season,
episode: Episode,
video_files: list[Path],
subtitle_files: list[Path],
file_path_suffix: str = "",
) -> bool:
episode_file_name = f"{remove_special_characters(show.name)} S{season.number:02d}E{episode.number:02d}"
if file_path_suffix != "":
episode_file_name += f" - {file_path_suffix}"
pattern = (
r".*[. ]S0?" + str(season.number) + r"E0?" + str(episode.number) + r"[. ].*"
)
subtitle_pattern = pattern + r"[. ]([A-Za-z]{2})[. ]srt"
target_file_name = (
self.get_root_season_directory(show=show, season_number=season.number)
/ episode_file_name
)
# import subtitle
for subtitle_file in subtitle_files:
regex_result = re.search(
subtitle_pattern, subtitle_file.name, re.IGNORECASE
)
if regex_result:
language_code = regex_result.group(1)
target_subtitle_file = target_file_name.with_suffix(
f".{language_code}.srt"
)
import_file(target_file=target_subtitle_file, source_file=subtitle_file)
else:
log.debug(
f"Didn't find any pattern {subtitle_pattern} in subtitle file: {subtitle_file.name}"
)
found_video = False
# import episode videos
for file in video_files:
if re.search(pattern, file.name, re.IGNORECASE):
target_video_file = target_file_name.with_suffix(file.suffix)
import_file(target_file=target_video_file, source_file=file)
found_video = True
break
if not found_video:
# Send notification about missing episode file
if self.notification_service:
self.notification_service.send_notification_to_all_providers(
title="Missing Episode File",
message=f"No video file found for S{season.number:02d}E{episode.number:02d} for show {show.name}. Manual intervention may be required.",
)
log.warning(
f"File for S{season.number}E{episode.number} not found when trying to import episode for show {show.name}."
)
return False
return True
def import_episode_files_from_torrent(self, torrent: Torrent, show: Show) -> None:
def import_torrent_files(self, torrent: Torrent, show: Show) -> None:
"""
Organizes episodes files from a torrent into the TV directory structure, mapping them to seasons and episodes.
Organizes files from a torrent into the TV directory structure, mapping them to seasons and episodes.
:param torrent: The Torrent object
:param show: The Show object
"""
@@ -767,68 +707,33 @@ class TvService:
f"Importing these {len(video_files)} files:\n" + pprint.pformat(video_files)
)
episode_files = self.torrent_service.get_episode_files_of_torrent(
torrent=torrent
)
if not episode_files:
log.warning(
f"No episode files associated with torrent {torrent.title}, skipping import."
)
return
season_files = self.torrent_service.get_season_files_of_torrent(torrent=torrent)
log.info(
f"Found {len(episode_files)} episode files associated with torrent {torrent.title}"
f"Found {len(season_files)} season files associated with torrent {torrent.title}"
)
imported_episodes_by_season: dict[int, list[int]] = {}
for episode_file in episode_files:
season = self.get_season_by_episode(episode_id=episode_file.episode_id)
episode = self.get_episode(episode_file.episode_id)
season_path = self.get_root_season_directory(
show=show, season_number=season.number
)
if not season_path.exists():
try:
season_path.mkdir(parents=True)
except Exception as e:
log.warning(f"Could not create path {season_path}: {e}")
msg = f"Could not create path {season_path}"
raise Exception(msg) from e # noqa: TRY002
episoded_import_success = self.import_episode_files(
for season_file in season_files:
season = self.get_season(season_id=season_file.season_id)
season_import_success, _imported_episodes_count = self.import_season(
show=show,
season=season,
episode=episode,
video_files=video_files,
subtitle_files=subtitle_files,
file_path_suffix=episode_file.file_path_suffix,
file_path_suffix=season_file.file_path_suffix,
)
success.append(episoded_import_success)
if episoded_import_success:
imported_episodes_by_season.setdefault(season.number, []).append(
episode.number
)
success.append(season_import_success)
if season_import_success:
log.info(
f"Episode {episode.number} from Season {season.number} successfully imported from torrent {torrent.title}"
f"Season {season.number} successfully imported from torrent {torrent.title}"
)
else:
log.warning(
f"Episode {episode.number} from Season {season.number} failed to import from torrent {torrent.title}"
f"Season {season.number} failed to import from torrent {torrent.title}"
)
success_messages: list[str] = []
for season_number, episodes in imported_episodes_by_season.items():
episode_list = ",".join(str(e) for e in sorted(episodes))
success_messages.append(
f"Episode(s): {episode_list} from Season {season_number}"
)
episodes_summary = "; ".join(success_messages)
log.info(
f"Finished importing files for torrent {torrent.title} {'without' if all(success) else 'with'} errors"
)
if all(success):
torrent.imported = True
@@ -838,11 +743,7 @@ class TvService:
if self.notification_service:
self.notification_service.send_notification_to_all_providers(
title="TV Show imported successfully",
message=(
f"Successfully imported {episodes_summary} "
f"of {show.name} ({show.year}) "
f"from torrent {torrent.title}."
),
message=f"Successfully imported {show.name} ({show.year}) from torrent {torrent.title}.",
)
else:
if self.notification_service:
@@ -851,10 +752,6 @@ class TvService:
message=f"Importing {show.name} ({show.year}) from torrent {torrent.title} completed with errors. Please check the logs for details.",
)
log.info(
f"Finished importing files for torrent {torrent.title} {'without' if all(success) else 'with'} errors"
)
def update_show_metadata(
self, db_show: Show, metadata_provider: AbstractMetadataProvider
) -> Show | None:
@@ -901,7 +798,9 @@ class TvService:
existing_season = existing_season_external_ids[
fresh_season_data.external_id
]
log.debug(
f"Updating existing season {existing_season.number} for show {db_show.name}"
)
self.tv_repository.update_season_attributes(
season_id=existing_season.id,
name=fresh_season_data.name,
@@ -913,28 +812,28 @@ class TvService:
ep.external_id: ep for ep in existing_season.episodes
}
for fresh_episode_data in fresh_season_data.episodes:
if fresh_episode_data.external_id in existing_episode_external_ids:
if fresh_episode_data.number in existing_episode_external_ids:
# Update existing episode
existing_episode = existing_episode_external_ids[
fresh_episode_data.external_id
]
log.debug(
f"Updating existing episode {existing_episode.number} for season {existing_season.number}"
)
self.tv_repository.update_episode_attributes(
episode_id=existing_episode.id,
title=fresh_episode_data.title,
overview=fresh_episode_data.overview,
)
else:
# Add new episode
log.debug(
f"Adding new episode {fresh_episode_data.number} to season {existing_season.number}"
)
episode_schema = Episode(
episode_schema = EpisodeSchema(
id=EpisodeId(fresh_episode_data.id),
number=fresh_episode_data.number,
external_id=fresh_episode_data.external_id,
title=fresh_episode_data.title,
overview=fresh_episode_data.overview,
)
self.tv_repository.add_episode_to_season(
season_id=existing_season.id, episode_data=episode_schema
@@ -945,12 +844,11 @@ class TvService:
f"Adding new season {fresh_season_data.number} to show {db_show.name}"
)
episodes_for_schema = [
Episode(
EpisodeSchema(
id=EpisodeId(ep_data.id),
number=ep_data.number,
external_id=ep_data.external_id,
title=ep_data.title,
overview=ep_data.overview,
)
for ep_data in fresh_season_data.episodes
]
@@ -969,7 +867,7 @@ class TvService:
updated_show = self.tv_repository.get_show_by_id(show_id=db_show.id)
log.info(f"Successfully updated metadata for show: {updated_show.name}")
log.info(f"Successfully updated metadata for show ID: {db_show.id}")
metadata_provider.download_show_poster_image(show=updated_show)
return updated_show
@@ -1013,22 +911,21 @@ class TvService:
directory=new_source_path
)
for season in tv_show.seasons:
_success, imported_episodes = self.import_season(
success, imported_episode_count = self.import_season(
show=tv_show,
season=season,
video_files=video_files,
subtitle_files=subtitle_files,
file_path_suffix="IMPORTED",
)
for episode in imported_episodes:
episode_file = EpisodeFile(
episode_id=episode.id,
quality=Quality.unknown,
file_path_suffix="IMPORTED",
torrent_id=None,
)
self.tv_repository.add_episode_file(episode_file=episode_file)
season_file = SeasonFile(
season_id=season.id,
quality=Quality.unknown,
file_path_suffix="IMPORTED",
torrent_id=None,
)
if success or imported_episode_count > (len(season.episodes) / 2):
self.tv_repository.add_season_file(season_file=season_file)
def get_importable_tv_shows(
self, metadata_provider: AbstractMetadataProvider
@@ -1062,34 +959,104 @@ class TvService:
log.debug(f"Detected {len(import_suggestions)} importable TV shows.")
return import_suggestions
def import_all_torrents(self) -> None:
def auto_download_all_approved_season_requests() -> None:
"""
Auto download all approved season requests.
This is a standalone function as it creates its own DB session.
"""
with next(get_session()) as db:
tv_repository = TvRepository(db=db)
torrent_service = TorrentService(torrent_repository=TorrentRepository(db=db))
indexer_service = IndexerService(indexer_repository=IndexerRepository(db=db))
notification_service = NotificationService(
notification_repository=NotificationRepository(db=db)
)
tv_service = TvService(
tv_repository=tv_repository,
torrent_service=torrent_service,
indexer_service=indexer_service,
notification_service=notification_service,
)
log.info("Auto downloading all approved season requests")
season_requests = tv_repository.get_season_requests()
log.info(f"Found {len(season_requests)} season requests to process")
count = 0
for season_request in season_requests:
if season_request.authorized:
log.info(f"Processing season request {season_request.id} for download")
show = tv_repository.get_show_by_season_id(
season_id=season_request.season_id
)
if tv_service.download_approved_season_request(
season_request=season_request, show=show
):
count += 1
else:
log.warning(
f"Failed to download season request {season_request.id} for show {show.name}"
)
log.info(f"Auto downloaded {count} approved season requests")
db.commit()
def import_all_show_torrents() -> None:
with next(get_session()) as db:
tv_repository = TvRepository(db=db)
torrent_service = TorrentService(torrent_repository=TorrentRepository(db=db))
indexer_service = IndexerService(indexer_repository=IndexerRepository(db=db))
notification_service = NotificationService(
notification_repository=NotificationRepository(db=db)
)
tv_service = TvService(
tv_repository=tv_repository,
torrent_service=torrent_service,
indexer_service=indexer_service,
notification_service=notification_service,
)
log.info("Importing all torrents")
torrents = self.torrent_service.get_all_torrents()
torrents = torrent_service.get_all_torrents()
log.info("Found %d torrents to import", len(torrents))
for t in torrents:
show = None
try:
if not t.imported and t.status == TorrentStatus.finished:
show = self.torrent_service.get_show_of_torrent(torrent=t)
show = torrent_service.get_show_of_torrent(torrent=t)
if show is None:
log.warning(
f"torrent {t.title} is not a tv torrent, skipping import."
)
continue
self.import_episode_files_from_torrent(torrent=t, show=show)
except RuntimeError as e:
show_name = show.name if show is not None else "<unknown>"
log.error(
f"Error importing torrent {t.title} for show {show_name}: {e}",
exc_info=True,
)
tv_service.import_torrent_files(torrent=t, show=show)
except RuntimeError:
log.exception(f"Error importing torrent {t.title} for show {show.name}")
log.info("Finished importing all torrents")
db.commit()
def update_all_non_ended_shows_metadata() -> None:
"""
Updates the metadata of all non-ended shows.
"""
with next(get_session()) as db:
tv_repository = TvRepository(db=db)
tv_service = TvService(
tv_repository=tv_repository,
torrent_service=TorrentService(torrent_repository=TorrentRepository(db=db)),
indexer_service=IndexerService(indexer_repository=IndexerRepository(db=db)),
notification_service=NotificationService(
notification_repository=NotificationRepository(db=db)
),
)
def update_all_non_ended_shows_metadata(self) -> None:
"""Updates the metadata of all non-ended shows."""
log.info("Updating metadata for all non-ended shows")
shows = [show for show in self.tv_repository.get_shows() if not show.ended]
shows = [show for show in tv_repository.get_shows() if not show.ended]
log.info(f"Found {len(shows)} non-ended shows to update")
for show in shows:
try:
if show.metadata_provider == "tmdb":
@@ -1106,10 +1073,34 @@ class TvService:
f"Error initializing metadata provider {show.metadata_provider} for show {show.name}"
)
continue
updated_show = self.update_show_metadata(
updated_show = tv_service.update_show_metadata(
db_show=show, metadata_provider=metadata_provider
)
# Automatically add season requests for new seasons
existing_seasons = [x.id for x in show.seasons]
new_seasons = [
x for x in updated_show.seasons if x.id not in existing_seasons
]
if show.continuous_download:
for new_season in new_seasons:
log.info(
f"Automatically adding season request for new season {new_season.number} of show {updated_show.name}"
)
tv_service.add_season_request(
SeasonRequest(
min_quality=Quality.sd,
wanted_quality=Quality.uhd,
season_id=new_season.id,
authorized=True,
)
)
if updated_show:
log.debug("Updated show metadata", extra={"show": updated_show.name})
log.debug(
f"Added new seasons: {len(new_seasons)} to show: {updated_show.name}"
)
else:
log.warning(f"Failed to update metadata for show: {show.name}")
db.commit()

18
metadata_relay/uv.lock generated
View File

@@ -547,11 +547,11 @@ wheels = [
[[package]]
name = "python-multipart"
version = "0.0.22"
version = "0.0.21"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/94/01/979e98d542a70714b0cb2b6728ed0b7c46792b695e3eaec3e20711271ca3/python_multipart-0.0.22.tar.gz", hash = "sha256:7340bef99a7e0032613f56dc36027b959fd3b30a787ed62d310e951f7c3a3a58", size = 37612, upload-time = "2026-01-25T10:15:56.219Z" }
sdist = { url = "https://files.pythonhosted.org/packages/78/96/804520d0850c7db98e5ccb70282e29208723f0964e88ffd9d0da2f52ea09/python_multipart-0.0.21.tar.gz", hash = "sha256:7137ebd4d3bbf70ea1622998f902b97a29434a9e8dc40eb203bbcf7c2a2cba92", size = 37196, upload-time = "2025-12-17T09:24:22.446Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/1b/d0/397f9626e711ff749a95d96b7af99b9c566a9bb5129b8e4c10fc4d100304/python_multipart-0.0.22-py3-none-any.whl", hash = "sha256:2b2cd894c83d21bf49d702499531c7bafd057d730c201782048f7945d82de155", size = 24579, upload-time = "2026-01-25T10:15:54.811Z" },
{ url = "https://files.pythonhosted.org/packages/aa/76/03af049af4dcee5d27442f71b6924f01f3efb5d2bd34f23fcd563f2cc5f5/python_multipart-0.0.21-py3-none-any.whl", hash = "sha256:cf7a6713e01c87aa35387f4774e812c4361150938d20d232800f75ffcf266090", size = 24541, upload-time = "2025-12-17T09:24:21.153Z" },
]
[[package]]
@@ -791,24 +791,24 @@ wheels = [
[[package]]
name = "urllib3"
version = "2.6.3"
version = "2.6.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c7/24/5f1b3bdffd70275f6661c76461e25f024d5a38a46f04aaca912426a2b1d3/urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed", size = 435556, upload-time = "2026-01-07T16:24:43.925Z" }
sdist = { url = "https://files.pythonhosted.org/packages/1e/24/a2a2ed9addd907787d7aa0355ba36a6cadf1768b934c652ea78acbd59dcd/urllib3-2.6.2.tar.gz", hash = "sha256:016f9c98bb7e98085cb2b4b17b87d2c702975664e4f060c6532e64d1c1a5e797", size = 432930, upload-time = "2025-12-11T15:56:40.252Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/39/08/aaaad47bc4e9dc8c725e68f9d04865dbcb2052843ff09c97b08904852d84/urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4", size = 131584, upload-time = "2026-01-07T16:24:42.685Z" },
{ url = "https://files.pythonhosted.org/packages/6d/b9/4095b668ea3678bf6a0af005527f39de12fb026516fb3df17495a733b7f8/urllib3-2.6.2-py3-none-any.whl", hash = "sha256:ec21cddfe7724fc7cb4ba4bea7aa8e2ef36f607a4bab81aa6ce42a13dc3f03dd", size = 131182, upload-time = "2025-12-11T15:56:38.584Z" },
]
[[package]]
name = "uvicorn"
version = "0.41.0"
version = "0.40.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click" },
{ name = "h11" },
]
sdist = { url = "https://files.pythonhosted.org/packages/32/ce/eeb58ae4ac36fe09e3842eb02e0eb676bf2c53ae062b98f1b2531673efdd/uvicorn-0.41.0.tar.gz", hash = "sha256:09d11cf7008da33113824ee5a1c6422d89fbc2ff476540d69a34c87fab8b571a", size = 82633, upload-time = "2026-02-16T23:07:24.1Z" }
sdist = { url = "https://files.pythonhosted.org/packages/c3/d1/8f3c683c9561a4e6689dd3b1d345c815f10f86acd044ee1fb9a4dcd0b8c5/uvicorn-0.40.0.tar.gz", hash = "sha256:839676675e87e73694518b5574fd0f24c9d97b46bea16df7b8c05ea1a51071ea", size = 81761, upload-time = "2025-12-21T14:16:22.45Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/83/e4/d04a086285c20886c0daad0e026f250869201013d18f81d9ff5eada73a88/uvicorn-0.41.0-py3-none-any.whl", hash = "sha256:29e35b1d2c36a04b9e180d4007ede3bcb32a85fbdfd6c6aeb3f26839de088187", size = 68783, upload-time = "2026-02-16T23:07:22.357Z" },
{ url = "https://files.pythonhosted.org/packages/3d/d8/2083a1daa7439a66f3a48589a57d576aa117726762618f6bb09fe3798796/uvicorn-0.40.0-py3-none-any.whl", hash = "sha256:c6c8f55bc8bf13eb6fa9ff87ad62308bbbc33d0b67f84293151efe87e0d5f2ee", size = 68502, upload-time = "2025-12-21T14:16:21.041Z" },
]
[package.optional-dependencies]

View File

@@ -1,72 +0,0 @@
site_name: "MediaManager Documentation"
theme:
name: "material"
logo: "assets/logo.svg"
favicon: "assets/favicon.ico"
features:
- navigation.sections
- navigation.expand
- navigation.indexes
- content.code.copy
- navigation.footer
palette:
- scheme: default
primary: indigo
accent: indigo
toggle:
icon: material/brightness-7
name: Switch to dark mode
- scheme: slate
primary: black
accent: black
toggle:
icon: material/brightness-4
name: Switch to light mode
markdown_extensions:
- admonition
- pymdownx.details
- pymdownx.superfences
- attr_list
- md_in_html
- pymdownx.snippets:
base_path: ["."]
nav:
- Welcome: index.md
- Installation:
- installation/README.md
- Docker Compose: installation/docker.md
- Nix Flakes [Community]: installation/flakes.md
- Usage:
- Importing existing media: importing-existing-media.md
- Configuration:
- configuration/README.md
- Backend: configuration/backend.md
- Authentication: configuration/authentication.md
- Database: configuration/database.md
- Download Clients: configuration/download-clients.md
- Indexers: configuration/indexers.md
- Scoring Rulesets: configuration/scoring-rulesets.md
- Notifications: configuration/notifications.md
- Custom Libraries: configuration/custom-libraries.md
- Logging: configuration/logging.md
- Advanced Features:
- qBittorrent Category: advanced-features/qbittorrent-category.md
- URL Prefix: advanced-features/url-prefix.md
- Metadata Provider Configuration: advanced-features/metadata-provider-configuration.md
- Custom port: advanced-features/custom-port.md
- Follow symlinks in frontend files: advanced-features/follow-symlinks-in-frontend-files.md
- Disable startup ascii art: advanced-features/disable-startup-ascii-art.md
- Troubleshooting: troubleshooting.md
- API Reference: api-reference.md
- Screenshots: screenshots.md
- Contributing to MediaManager:
- Developer Guide: contributing-to-mediamanager/developer-guide.md
- Documentation: contributing-to-mediamanager/documentation.md
extra:
version:
provider: mike
extra_css:
- custom.css

View File

@@ -13,7 +13,7 @@ dependencies = [
"httpx-oauth>=0.16.1",
"jsonschema>=4.24.0",
"patool>=4.0.1",
"psycopg[binary,pool]>=3.2.9",
"psycopg[binary]>=3.2.9",
"pydantic>=2.11.5",
"pydantic-settings[toml]>=2.9.1",
"python-json-logger>=3.3.0",
@@ -26,9 +26,7 @@ dependencies = [
"typing-inspect>=0.9.0",
"uvicorn>=0.34.2",
"fastapi-utils>=0.8.0",
"taskiq>=0.12.0",
"taskiq-fastapi>=0.4.0",
"taskiq-postgresql[psycopg]>=0.4.0",
"apscheduler>=3.11.0",
"alembic>=1.16.1",
"pytest>=8.4.0",
"pillow>=11.3.0",

View File

@@ -41,4 +41,4 @@ ignore = [
]
[lint.flake8-bugbear]
extend-immutable-calls = ["fastapi.Depends", "fastapi.Path", "taskiq.TaskiqDepends"]
extend-immutable-calls = ["fastapi.Depends", "fastapi.Path"]

892
uv.lock generated

File diff suppressed because it is too large Load Diff

2091
web/package-lock.json generated

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More