Compare commits
85 Commits
test-gitbo
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8da2db42f1 | ||
|
|
f5253990e0 | ||
|
|
e529e0c0a3 | ||
|
|
46a9760376 | ||
|
|
8270d1d3ff | ||
|
|
6ef200c558 | ||
|
|
47d35d4bd7 | ||
|
|
cbd70bd6f3 | ||
|
|
d8405fd903 | ||
|
|
7824891557 | ||
|
|
a643c9426d | ||
|
|
c2645000e5 | ||
|
|
b16f2dce92 | ||
|
|
d8a0ec66c3 | ||
|
|
094d0e4eb7 | ||
|
|
4d7f596ffd | ||
|
|
300df14c8c | ||
|
|
2f102d6c5d | ||
|
|
3e696c463c | ||
|
|
5adb88f9e0 | ||
|
|
eb277dddac | ||
|
|
516d562bd8 | ||
|
|
dea75841b2 | ||
|
|
20e0dbf936 | ||
|
|
c8f2a4316e | ||
|
|
4836e3e188 | ||
|
|
7a6466ea9d | ||
|
|
b427aa5723 | ||
|
|
82aa01a650 | ||
|
|
bc3895ab40 | ||
|
|
b7ed529f77 | ||
|
|
370df4efa0 | ||
|
|
a3e85d6338 | ||
|
|
a2816f2dfb | ||
|
|
0026b891f5 | ||
|
|
b312d880b7 | ||
|
|
71e2a08535 | ||
|
|
f2bf1a2dae | ||
|
|
6b70980c2a | ||
|
|
e80a516c23 | ||
|
|
280e136209 | ||
|
|
5c62c9f5be | ||
|
|
1e46cdc03b | ||
|
|
18573fa7d9 | ||
|
|
6debd7a42d | ||
|
|
cd70ab8711 | ||
|
|
51b8794e4d | ||
|
|
0cfd1fa724 | ||
|
|
b5b297e99a | ||
|
|
58414cadae | ||
|
|
462794520e | ||
|
|
59afba007d | ||
|
|
cfa303e4f3 | ||
|
|
d3dde9c7eb | ||
|
|
9c94ef6de0 | ||
|
|
2665106847 | ||
|
|
d029177fc0 | ||
|
|
1698c404cd | ||
|
|
abac894a95 | ||
|
|
12854ff661 | ||
|
|
3d52a87302 | ||
|
|
9ee5cc6895 | ||
|
|
c45c9e5873 | ||
|
|
24fcba6bee | ||
|
|
d5994a9037 | ||
|
|
9e0d0c03c0 | ||
|
|
70ff8f6ace | ||
|
|
e347219721 | ||
|
|
72a626cb1a | ||
|
|
a1f3f92c10 | ||
|
|
caaa08fbf4 | ||
|
|
5db60141bb | ||
|
|
96b84d45db | ||
|
|
311e625eee | ||
|
|
e22e0394bd | ||
|
|
6377aa8b83 | ||
|
|
8855204930 | ||
|
|
7a13326d87 | ||
|
|
15e9cd001f | ||
|
|
e52b84c3c7 | ||
|
|
84a430651f | ||
|
|
463e6914e3 | ||
|
|
e5e85077ae | ||
|
|
a39e0d204a | ||
|
|
dd0b439bbe |
2
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -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://maximilian-dorninger.gitbook.io/mediamanager) for help.
|
||||
- [ ] I have checked the [documentation](https://maxdorninger.github.io/MediaManager/) for help.
|
||||
- [ ] I have searched the [issues](https://github.com/maxdorninger/MediaManager/issues) for similar issues and found none.
|
||||
|
||||
31
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
# 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
|
||||
|
||||
4
.github/workflows/build-push-backend.yml
vendored
@@ -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@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
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@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
|
||||
@@ -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@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
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@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
|
||||
62
.github/workflows/docs.yml
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
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
@@ -49,5 +49,5 @@ __pycache__
|
||||
# Postgres
|
||||
/postgres
|
||||
|
||||
# Node modules
|
||||
/node_modules/*
|
||||
# MkDocs
|
||||
site/
|
||||
|
||||
@@ -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://maximilian-dorninger.gitbook.io/mediamanager
|
||||
https://maxdorninger.github.io/MediaManager/
|
||||
|
||||
### For something that is a one or two line fix:
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ RUN env PUBLIC_VERSION=${VERSION} PUBLIC_API_URL=${BASE_PATH} BASE_PATH=${BASE_P
|
||||
FROM ghcr.io/astral-sh/uv:python3.13-trixie-slim AS base
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y ca-certificates bash libtorrent21 gcc bc locales postgresql media-types mailcap curl gzip unzip tar 7zip bzip2 unar && \
|
||||
apt-get install -y ca-certificates bash libtorrent21 gcc bc locales postgresql media-types mailcap curl gzip unzip tar 7zip bzip2 unar gosu && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -33,7 +33,6 @@ RUN chown -R mediamanager:mediamanager /app
|
||||
|
||||
USER mediamanager
|
||||
|
||||
# Set uv cache to a writable home directory and use copy mode for volume compatibility
|
||||
ENV UV_CACHE_DIR=/home/mediamanager/.cache/uv \
|
||||
UV_LINK_MODE=copy
|
||||
|
||||
@@ -47,6 +46,7 @@ ARG BASE_PATH=""
|
||||
LABEL author="github.com/maxdorninger"
|
||||
LABEL version=${VERSION}
|
||||
LABEL description="Docker image for MediaManager"
|
||||
USER root
|
||||
|
||||
ENV PUBLIC_VERSION=${VERSION} \
|
||||
CONFIG_DIR="/app/config" \
|
||||
|
||||
15
README.md
@@ -1,7 +1,7 @@
|
||||
<br />
|
||||
<div align="center">
|
||||
<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 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>
|
||||
|
||||
<h3 align="center">MediaManager</h3>
|
||||
@@ -9,7 +9,7 @@
|
||||
<p align="center">
|
||||
Modern management system for your media library
|
||||
<br />
|
||||
<a href="https://maximilian-dorninger.gitbook.io/mediamanager"><strong>Explore the docs »</strong></a>
|
||||
<a href="https://maxdorninger.github.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>
|
||||
·
|
||||
@@ -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://maximilian-dorninger.gitbook.io/mediamanager)
|
||||
### [View the docs for installation instructions and more](https://maxdorninger.github.io/MediaManager/)
|
||||
|
||||
## Support MediaManager
|
||||
|
||||
@@ -60,6 +60,7 @@ 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>
|
||||
<a href="https://buymeacoffee.com/maxdorninger"><img src="https://cdn.buymeacoffee.com/uploads/profile_pictures/2025/11/2VeQ8sTGPhj4tiLy.jpg" width="80px" alt="PuppiestDoggo" /></a>
|
||||
<a href="https://github.com/seferino-fernandez"><img src="https://avatars.githubusercontent.com/u/5546622" width="80px" alt="Seferino" /></a>
|
||||
<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>
|
||||
|
||||
## Star History
|
||||
|
||||
@@ -80,7 +81,7 @@ docker compose up -d
|
||||
|
||||
## Developer Quick Start
|
||||
|
||||
For the developer guide see the [Developer Guide](https://maximilian-dorninger.gitbook.io/mediamanager).
|
||||
For the developer guide see the [Developer Guide](https://maxdorninger.github.io/MediaManager/).
|
||||
|
||||
<!-- LICENSE -->
|
||||
|
||||
@@ -93,5 +94,9 @@ Distributed under the AGPL 3.0. See `LICENSE.txt` for more information.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Thanks to DigitalOcean for sponsoring the project!
|
||||
|
||||
[](https://www.digitalocean.com/?refcode=4edf05429dca&utm_campaign=Referral_Invite&utm_medium=Referral_Program&utm_source=badge)
|
||||
|
||||
* [Thanks to Pawel Czerwinski for the image on the login screen](https://unsplash.com/@pawel_czerwinski)
|
||||
|
||||
|
||||
@@ -30,14 +30,13 @@ 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, MovieRequest # noqa: E402
|
||||
from media_manager.movies.models import Movie, MovieFile # 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,
|
||||
)
|
||||
|
||||
@@ -47,15 +46,13 @@ target_metadata = Base.metadata
|
||||
# noinspection PyStatementEffect
|
||||
__all__ = [
|
||||
"Episode",
|
||||
"EpisodeFile",
|
||||
"IndexerQueryResult",
|
||||
"Movie",
|
||||
"MovieFile",
|
||||
"MovieRequest",
|
||||
"Notification",
|
||||
"OAuthAccount",
|
||||
"Season",
|
||||
"SeasonFile",
|
||||
"SeasonRequest",
|
||||
"Show",
|
||||
"Torrent",
|
||||
"User",
|
||||
@@ -106,7 +103,13 @@ def run_migrations_online() -> None:
|
||||
|
||||
"""
|
||||
|
||||
def include_object(_object, name, type_, _reflected, _compare_to):
|
||||
def include_object(
|
||||
_object: object | None,
|
||||
name: str | None,
|
||||
type_: str | None,
|
||||
_reflected: bool | None,
|
||||
_compare_to: object | None,
|
||||
) -> bool:
|
||||
if type_ == "table" and name == "apscheduler_jobs":
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,31 @@
|
||||
"""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")
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""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
|
||||
"""
|
||||
)
|
||||
|
||||
65
alembic/versions/e60ae827ed98_remove_requests.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""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 ###
|
||||
@@ -1,6 +1,6 @@
|
||||
# MediaManager Dev Configuration File
|
||||
# This file contains all available configuration options for MediaManager
|
||||
# Documentation: https://maximilian-dorninger.gitbook.io/mediamanager
|
||||
# Documentation: https://maxdorninger.github.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", "ts"]
|
||||
keywords = ["cam", "camrip", "bdscr", "ddc", "dvdscreener","dvdscr", "hdcam", "hdtc", "hdts", "scr", "screener","telesync", "ts", "webscreener", "tc", "telecine", "tvrip"]
|
||||
score_modifier = -10000
|
||||
negate = false
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# MediaManager Example Configuration File
|
||||
# This file contains all available configuration options for MediaManager
|
||||
# Documentation: https://maximilian-dorninger.gitbook.io/mediamanager
|
||||
# Documentation: https://maxdorninger.github.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", "ts"]
|
||||
keywords = ["cam", "camrip", "bdscr", "ddc", "dvdscreener","dvdscr", "hdcam", "hdtc", "hdts", "scr", "screener","telesync", "ts", "webscreener", "tc", "telecine", "tvrip"]
|
||||
score_modifier = -10000
|
||||
negate = false
|
||||
|
||||
|
||||
@@ -56,6 +56,15 @@ 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
|
||||
@@ -130,17 +139,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
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
layout:
|
||||
width: wide
|
||||
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="true"><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-guide.md">installation-guide.md</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="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="true"><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="true"><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></tbody></table>
|
||||
|
||||
### MediaManager Repository
|
||||
|
||||
https://github.com/maxdorninger/MediaManager
|
||||
@@ -1,26 +0,0 @@
|
||||
# Table of contents
|
||||
|
||||
* [MediaManager](README.md)
|
||||
* [Installation Guide](installation-guide.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)
|
||||
* [Troubleshooting](troubleshooting.md)
|
||||
* [Developer Guide](developer-guide.md)
|
||||
* [API Reference](api-reference.md)
|
||||
* [Screenshots](screenshots.md)
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
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
|
||||
|
||||
4
docs/advanced-features/disable-startup-ascii-art.md
Normal file
@@ -0,0 +1,4 @@
|
||||
# Disable Startup Ascii Art
|
||||
|
||||
* `MEDIAMANAGER_NO_STARTUP_ART`: Set this environment variable (to any value) \
|
||||
to disable the colorized startup splash screen. Unset to reenable.
|
||||
@@ -7,8 +7,6 @@ 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`.
|
||||
|
||||
{% code title=".env" %}
|
||||
```bash
|
||||
```bash title=".env"
|
||||
FRONTEND_FOLLOW_SYMLINKS=true
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
@@ -8,9 +8,8 @@ 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.
|
||||
|
||||
{% hint style="info" %}
|
||||
Other software like Jellyfin use TMDB as well, so there won't be any metadata discrepancies.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
Other software like Jellyfin use TMDB as well, so there won't be any metadata discrepancies.
|
||||
|
||||
* `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`.
|
||||
@@ -19,24 +18,21 @@ Other software like Jellyfin use TMDB as well, so there won't be any metadata di
|
||||
* `default_language`\
|
||||
TMDB language parameter used when searching and adding. Default is `en`. Format: ISO 639-1 (2 letters).
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
### TVDB Settings (`[metadata.tvdb]`)
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
* `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
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -47,16 +43,14 @@ 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)
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
### Example Configuration
|
||||
|
||||
Here's a complete example of the metadata section in your `config.toml`:
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[metadata]
|
||||
# TMDB configuration
|
||||
[metadata.tmdb]
|
||||
@@ -66,8 +60,6 @@ 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 %}
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
@@ -9,10 +9,8 @@ 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`.
|
||||
|
||||
{% 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 %}
|
||||
!!! 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="warning" %}
|
||||
For MediaManager to successfully import torrents, you must add the subdirectory to the `misc.torrent_directory` variable.
|
||||
{% endhint %}
|
||||
!!! warning
|
||||
For MediaManager to successfully import torrents, you must add the subdirectory to the `misc.torrent_directory` variable.
|
||||
|
||||
@@ -6,23 +6,20 @@ In order to run it on a prefixed path, like `maxdorninger.github.io/media`, the
|
||||
|
||||
In short, clone the repository, then run:
|
||||
|
||||
{% code title="Build Docker image" %}
|
||||
```none
|
||||
```none title="Build Docker image"
|
||||
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.
|
||||
|
||||
{% code title="docker-compose.yaml (excerpt)" %}
|
||||
```yaml
|
||||
```yaml title="docker-compose.yaml (excerpt)"
|
||||
services:
|
||||
mediamanager:
|
||||
image: MediaManager:my-custom-version
|
||||
@@ -32,10 +29,8 @@ services:
|
||||
BASE_PATH: /media
|
||||
...
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
{% 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 %}
|
||||
!!! info
|
||||
Make sure to include the base path in the `frontend_url` field in the config file. See [Backend](../configuration/backend.md).
|
||||
|
||||
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/`.
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# API Reference
|
||||
|
||||
{% hint style="info" %}
|
||||
Media Manager's backend is built with FastAPI, which automatically generates interactive API documentation.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
Media Manager's backend is built with FastAPI, which automatically generates interactive API documentation.
|
||||
|
||||
* Swagger UI (typically available at `http://localhost:8000/docs`)
|
||||
* ReDoc (typically available at `http://localhost:8000/redoc`)
|
||||
|
||||
|
Before Width: | Height: | Size: 3.1 MiB After Width: | Height: | Size: 3.1 MiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 9.0 KiB After Width: | Height: | Size: 9.0 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 62 KiB After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 244 KiB After Width: | Height: | Size: 244 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 113 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
BIN
docs/assets/assets/image.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 8.9 MiB After Width: | Height: | Size: 8.9 MiB |
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 5.5 MiB After Width: | Height: | Size: 5.5 MiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 7.6 MiB After Width: | Height: | Size: 7.6 MiB |
|
Before Width: | Height: | Size: 123 KiB After Width: | Height: | Size: 123 KiB |
BIN
docs/assets/favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
1
docs/assets/logo-with-text.svg
Normal file
|
After Width: | Height: | Size: 108 KiB |
1
docs/assets/logo.svg
Normal file
|
After Width: | Height: | Size: 110 KiB |
@@ -6,9 +6,8 @@ Frontend settings are configured through environment variables in your `docker-c
|
||||
|
||||
## Configuration File Location
|
||||
|
||||
{% hint style="warning" %}
|
||||
Note that MediaManager may need to be restarted for changes in the config file to take effect.
|
||||
{% endhint %}
|
||||
!!! warning
|
||||
Note that MediaManager may need to be restarted for changes in the config file to take effect.
|
||||
|
||||
Your `config.toml` file should be in the directory that's mounted to `/app/config/config.toml` inside the container:
|
||||
|
||||
@@ -66,6 +65,5 @@ 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.
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
@@ -20,13 +20,11 @@ All authentication settings are configured in the `[auth]` section of your `conf
|
||||
* `email_password_resets`\
|
||||
Enables password resets via email. Default is `false`.
|
||||
|
||||
{% hint style="info" %}
|
||||
To use email password resets, you must also configure SMTP settings in the `[notifications.smtp_config]` section.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
To use email password resets, you must also configure SMTP settings in the `[notifications.smtp_config]` section.
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
## OpenID Connect Settings (`[auth.openid_connect]`)
|
||||
|
||||
@@ -53,22 +51,20 @@ The OpenID server will likely require a redirect URI. This URL will usually look
|
||||
{MEDIAMANAGER_URL}/api/v1/auth/oauth/callback
|
||||
```
|
||||
|
||||
{% hint style="warning" %}
|
||||
It is very important that you set the correct callback URI, otherwise it won't work!
|
||||
{% endhint %}
|
||||
!!! warning
|
||||
It is very important that you set the correct callback URI, otherwise it won't work!
|
||||
|
||||
#### Authentik Example
|
||||
|
||||
Here is an example configuration for the OpenID Connect provider for Authentik.
|
||||
|
||||

|
||||

|
||||
|
||||
## Example Configuration
|
||||
|
||||
Here's a complete example of the authentication section in your `config.toml`:
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[auth]
|
||||
token_secret = "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6"
|
||||
session_lifetime = 604800 # 1 week
|
||||
@@ -82,4 +78,4 @@ client_secret = "your-secret-key-here"
|
||||
configuration_endpoint = "https://auth.example.com/.well-known/openid-configuration"
|
||||
name = "Authentik"
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
|
||||
@@ -26,8 +26,7 @@ description: >-
|
||||
|
||||
Here's a complete example of the general settings section in your `config.toml`:
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[misc]
|
||||
|
||||
# REQUIRED: Change this to match your actual frontend domain.
|
||||
@@ -38,8 +37,6 @@ cors_urls = ["http://localhost:8000"]
|
||||
# Optional: Development mode (set to true for debugging)
|
||||
development = false
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
{% hint style="info" %}
|
||||
The `frontend_url` is the most important setting to configure correctly. Make sure it matches your actual deployment URLs.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
The `frontend_url` is the most important setting to configure correctly. Make sure it matches your actual deployment URLs.
|
||||
|
||||
@@ -6,9 +6,8 @@ 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.
|
||||
|
||||
{% hint style="info" %}
|
||||
You are not limited to `/data/tv` or `/data/movies`, you can choose the entire path freely!
|
||||
{% endhint %}
|
||||
!!! info
|
||||
You are not limited to `/data/tv` or `/data/movies`, you can choose the entire path freely!
|
||||
|
||||
### Movie Libraries
|
||||
|
||||
|
||||
@@ -19,8 +19,7 @@ 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`:
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[database]
|
||||
host = "db"
|
||||
port = 5432
|
||||
@@ -28,8 +27,6 @@ user = "MediaManager"
|
||||
password = "your_secure_password"
|
||||
dbname = "MediaManager"
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
{% hint style="info" %}
|
||||
In docker-compose deployments the container name is simultaneously its hostname, so you can use "db" or "postgres" as host.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
In docker-compose deployments the container name is simultaneously its hostname, so you can use "db" or "postgres" as host.
|
||||
|
||||
@@ -19,9 +19,8 @@ qBittorrent is a popular BitTorrent client that MediaManager can integrate with
|
||||
|
||||
## Transmission Settings (`[torrents.transmission]`)
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
Transmission is a BitTorrent client that MediaManager can integrate with for downloading torrents.
|
||||
|
||||
@@ -59,8 +58,7 @@ 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`:
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[torrents]
|
||||
# qBittorrent configuration
|
||||
[torrents.qbittorrent]
|
||||
@@ -87,14 +85,12 @@ 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:
|
||||
|
||||
{% code title="docker-compose.yml" %}
|
||||
```yaml
|
||||
```yaml title="docker-compose.yml"
|
||||
services:
|
||||
# MediaManager backend
|
||||
backend:
|
||||
@@ -121,12 +117,9 @@ services:
|
||||
- ./data/usenet:/downloads
|
||||
# ... other configuration ...
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
{% hint style="warning" %}
|
||||
You should enable only one BitTorrent and only one Usenet Download Client at any time.
|
||||
{% endhint %}
|
||||
!!! warning
|
||||
You should enable only one BitTorrent and only one Usenet Download Client at any time.
|
||||
|
||||
{% hint style="info" %}
|
||||
Make sure the download directories in your download clients are accessible to MediaManager for proper file management and organization.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
Make sure the download directories in your download clients are accessible to MediaManager for proper file management and organization.
|
||||
|
||||
@@ -13,9 +13,8 @@ Indexer settings are configured in the `[indexers]` section of your `config.toml
|
||||
* `timeout_seconds`\
|
||||
Timeout in seconds for requests to Prowlarr. Default is `60`.
|
||||
|
||||
{% hint style="warning" %}
|
||||
Symptoms of timeouts are typically no search results ("No torrents found!") in conjunction with logs showing read timeouts.
|
||||
{% endhint %}
|
||||
!!! warning
|
||||
Symptoms of timeouts are typically no search results ("No torrents found!") in conjunction with logs showing read timeouts.
|
||||
|
||||
<details>
|
||||
|
||||
@@ -50,8 +49,7 @@ DEBUG - media_manager.indexer.utils -
|
||||
|
||||
## Example Configuration
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[indexers]
|
||||
[indexers.prowlarr]
|
||||
enabled = true
|
||||
@@ -66,4 +64,4 @@ api_key = "your_jackett_api_key"
|
||||
indexers = ["1337x", "rarbg"]
|
||||
timeout_seconds = 60
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
|
||||
@@ -57,8 +57,7 @@ Controls which emails receive notifications.
|
||||
|
||||
Here's a complete example of the notifications section in your `config.toml`:
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[notifications]
|
||||
# SMTP settings for email notifications and password resets
|
||||
[notifications.smtp_config]
|
||||
@@ -91,8 +90,7 @@ 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 %}
|
||||
|
||||
{% 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 %}
|
||||
|
||||
!!! info
|
||||
You can enable multiple notification methods simultaneously. For example, you could have both email and Gotify notifications enabled at the same time.
|
||||
|
||||
@@ -17,9 +17,8 @@ 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.
|
||||
|
||||
{% hint style="info" %}
|
||||
The keywords and flags are compared case-insensitively.
|
||||
{% endhint %}
|
||||
!!! info
|
||||
The keywords and flags are compared case-insensitively.
|
||||
|
||||
### Title Rules
|
||||
|
||||
@@ -38,8 +37,7 @@ Each title rule consists of:
|
||||
|
||||
Examples for Title Rules
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[[indexers.title_scoring_rules]]
|
||||
name = "prefer_h265"
|
||||
keywords = ["h265", "hevc", "x265"]
|
||||
@@ -52,7 +50,6 @@ 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".
|
||||
@@ -76,8 +73,7 @@ Each indexer flag rule consists of:
|
||||
|
||||
Examples for Indexer Flag Rules
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[[indexers.indexer_flag_scoring_rules]]
|
||||
name = "reject_non_freeleech"
|
||||
flags = ["freeleech", "freeleech75"]
|
||||
@@ -90,7 +86,6 @@ 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".
|
||||
@@ -99,8 +94,7 @@ If `negate` is set to `true`, the `score_modifier` is applied only if none of th
|
||||
|
||||
## Example
|
||||
|
||||
{% code title="config.toml" %}
|
||||
```toml
|
||||
```toml title="config.toml"
|
||||
[[indexers.scoring_rule_sets]]
|
||||
name = "default"
|
||||
libraries = ["ALL_TV", "ALL_MOVIES"]
|
||||
@@ -111,7 +105,6 @@ name = "strict_quality"
|
||||
libraries = ["ALL_MOVIES"]
|
||||
rule_names = ["prefer_h265", "avoid_cam", "reject_non_freeleech"]
|
||||
```
|
||||
{% endcode %}
|
||||
|
||||
## Libraries
|
||||
|
||||
@@ -127,9 +120,8 @@ 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.
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
## Relation to Sonarr/Radarr Profiles
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
# Developer Guide
|
||||
---
|
||||
description: >-
|
||||
This section is for those who want to contribute to Media Manager or
|
||||
understand its internals.
|
||||
---
|
||||
|
||||
This section is for those who want to contribute to Media Manager or understand its internals.
|
||||
# Developer Guide
|
||||
|
||||
## Source Code directory structure
|
||||
|
||||
* `media_manager/`: Backend FastAPI application
|
||||
* `web/`: Frontend SvelteKit application
|
||||
* `Writerside/`: Documentation
|
||||
* `docs/`: Documentation (MkDocs)
|
||||
* `metadata_relay/`: Metadata relay service, also FastAPI
|
||||
|
||||
## Special Dev Configuration
|
||||
@@ -40,9 +44,8 @@ MediaManager uses various environment variables for configuration. In the Docker
|
||||
* `DISABLE_FRONTEND_MOUNT`\
|
||||
When `TRUE`, disables mounting built frontend files (allows separate frontend container).
|
||||
|
||||
{% hint style="info" %}
|
||||
This is automatically set in `docker-compose.dev.yaml` to enable the separate frontend development container
|
||||
{% endhint %}
|
||||
!!! info
|
||||
This is automatically set in `docker-compose.dev.yaml` to enable the separate frontend development container
|
||||
|
||||
#### Configuration Files
|
||||
|
||||
@@ -69,7 +72,6 @@ I use IntellijIdea with the Pycharm and Webstorm plugins to develop this, but th
|
||||
* Pydantic
|
||||
* Ruff
|
||||
* VirtualKit
|
||||
* Writerside (for writing documentation)
|
||||
|
||||
### Recommended Development Workflow
|
||||
|
||||
@@ -102,10 +104,9 @@ 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:
|
||||
@@ -115,9 +116,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
|
||||
@@ -132,9 +133,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
|
||||
@@ -148,12 +149,10 @@ 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 %}
|
||||
|
||||
{% 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 %}
|
||||
|
||||
!!! info
|
||||
Run `make help` to see all available development commands including `make down`, `make logs`, `make app` (shell into backend), and more.
|
||||
|
||||
## Setting up the backend development environment (Local)
|
||||
|
||||
@@ -203,29 +202,28 @@ uv run fastapi run media_manager/main.py --reload --port 8000
|
||||
* Format code:
|
||||
|
||||
```bash
|
||||
uv run ruff format .
|
||||
ruff format .
|
||||
```
|
||||
|
||||
* Lint code:
|
||||
|
||||
```bash
|
||||
uv run ruff check .
|
||||
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:
|
||||
@@ -240,9 +238,9 @@ If using PowerShell you may need:
|
||||
```powershell
|
||||
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
|
||||
```
|
||||
{% endstep %}
|
||||
|
||||
{% step %}
|
||||
|
||||
|
||||
### Create .env for frontend
|
||||
|
||||
```bash
|
||||
@@ -250,18 +248,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:
|
||||
@@ -275,12 +273,10 @@ npm run format
|
||||
```bash
|
||||
npm run lint
|
||||
```
|
||||
{% endstep %}
|
||||
{% endstepper %}
|
||||
|
||||
{% hint style="info" %}
|
||||
If running frontend locally, make sure to add `http://localhost:5173` to the `cors_urls` in your backend config file.
|
||||
{% endhint %}
|
||||
|
||||
!!! info
|
||||
If running frontend locally, make sure to add `http://localhost:5173` to the `cors_urls` in your backend config file.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
14
docs/contributing-to-mediamanager/documentation.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Documentation
|
||||
|
||||
MediaManager uses [MkDocs](https://www.mkdocs.org/) with
|
||||
the [Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) theme for documentation.
|
||||
|
||||
The files for the documentation are in the `/docs` directory.
|
||||
|
||||
To preview the documentation locally, you need to have mkdocs or Docker installed.
|
||||
|
||||
## How to preview the documentation locally with docker
|
||||
|
||||
1. Run the mkdocs container in `docker-compose.dev.yaml`
|
||||
|
||||
2. Open `http://127.0.0.1:9000/` in your browser.
|
||||
22
docs/custom.css
Normal file
@@ -0,0 +1,22 @@
|
||||
/*.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 */
|
||||
}
|
||||
@@ -23,9 +23,8 @@ 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.
|
||||
|
||||
{% 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 %}
|
||||
!!! info
|
||||
After importing, MediaManager will automatically prefix the old root TV show/movie folders with a dot to mark them as "imported".
|
||||
|
||||
So after importing, the directory would look like this (using the above directory structure):
|
||||
|
||||
|
||||
2
docs/index.md
Normal file
@@ -0,0 +1,2 @@
|
||||
--8<-- "README.md"
|
||||
|
||||
6
docs/installation/README.md
Normal file
@@ -0,0 +1,6 @@
|
||||
# Installation Guide
|
||||
|
||||
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 }
|
||||
@@ -1,6 +1,4 @@
|
||||
# Installation Guide
|
||||
|
||||
The recommended way to install and run Media Manager is using Docker and Docker Compose.
|
||||
# Docker Compose
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -11,19 +9,19 @@ The recommended way to install and run Media Manager is using Docker and Docker
|
||||
|
||||
Follow these steps to get MediaManager running with Docker Compose:
|
||||
|
||||
{% stepper %}
|
||||
{% step %}
|
||||
### Get the docker-compose file
|
||||
|
||||
|
||||
#### Get the docker-compose file
|
||||
|
||||
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
|
||||
|
||||
|
||||
#### Prepare configuration directory and example config
|
||||
|
||||
Create a config directory and download the example configuration:
|
||||
|
||||
@@ -31,34 +29,33 @@ 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/)
|
||||
{% endstep %}
|
||||
|
||||
{% step %}
|
||||
### Start MediaManager
|
||||
#### 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)
|
||||
|
||||
|
||||
|
||||
#### Start MediaManager
|
||||
|
||||
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/)
|
||||
* [For more information on the available configuration options, see the Configuration section of the documentation.](../configuration/README.md)
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
## MediaManager and MetadataRelay Docker Images
|
||||
## Docker Images
|
||||
|
||||
MediaManager is available as a Docker image on both Red Hat Quay.io and GitHub Container Registry (GHCR):
|
||||
|
||||
@@ -70,11 +67,10 @@ MetadataRelay images are also available on both registries:
|
||||
* quay.io/maxdorninger/metadata\_relay
|
||||
* ghcr.io/maxdorninger/mediamanager/metadata\_relay
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
### Tags
|
||||
|
||||
@@ -85,4 +81,4 @@ Both registries support the following tags:
|
||||
* X.Y.Z: Specific version tags (e.g., `1.12.0`).
|
||||
* X.Y: Points to the latest release in the X.Y series (e.g., `1.12`).
|
||||
* X: Points to the latest release in the X series (e.g., `1`).
|
||||
* pr-: Points to the latest commit in the specified pull request (e.g., `pr-67`).
|
||||
* pr-\<number>: Points to the latest commit in the specified pull request (e.g., `pr-67`).
|
||||
124
docs/installation/flakes.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Nix Flakes
|
||||
|
||||
!!! note
|
||||
This is a community contribution and not officially supported by the MediaManager team, but included here for convenience.
|
||||
|
||||
*Please report issues with this method at the [corresponding GitHub repository](https://github.com/strangeglyph/mediamanager-nix).*
|
||||
|
||||
## Prerequisites
|
||||
|
||||
This guide assumes that your system is a flakes-based NixOS installation. Hosting MediaManager on a subpath (e.g. `yourdomain.com/mediamanager`) is currently not supported, though contributions to add support are welcome.
|
||||
|
||||
## Importing the community flake
|
||||
|
||||
To use the community-provided flake and module, first import it in your own flake, for example:
|
||||
|
||||
```nix
|
||||
{
|
||||
description = "An example NixOS configuration";
|
||||
|
||||
inputs = {
|
||||
nixpkgs = { url = "github:nixos/nixpkgs/nixos-unstable"; };
|
||||
|
||||
mediamanager-nix = {
|
||||
url = "github:strangeglyph/mediamanager-nix";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = inputs@{
|
||||
nixpkgs,
|
||||
mediamanager-nix,
|
||||
...
|
||||
}: {
|
||||
nixosConfigurations.your-system = nixpkgs.lib.nixosSystem {
|
||||
modules = [
|
||||
mediamanager-nix.nixosModules.default
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The flake provides a simple module to set up a MediaManager systemd service. To enable it, set
|
||||
|
||||
```nix
|
||||
{
|
||||
config = {
|
||||
services.media-manager = {
|
||||
enable = true;
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
You will either want to set `services.media-manager.dataDir`, which will provide sensible defaults for the settings
|
||||
`misc.{image,movie,tv,torrent}_directory`, or provide specific paths yourself.
|
||||
|
||||
The host and port that MediaManager listens on can be set using `services.media-manager.{host,port}`.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
!!! warning
|
||||
Do not place secrets in the nix store, as it is world-readable.
|
||||
|
||||
## Automatic Postgres Setup
|
||||
|
||||
As a convenience feature, the module provides a simple Postgres setup that can be enabled with `services.media-manager.postgres.enable`. This sets up a database user named `services.media-manager.postgres.user` and a database with the same name. Provided the user of the systemd service wasn't changed, authentication should work automatically for unix socket connections (the default mediamanager-nix settings).
|
||||
|
||||
For advanced setups, please refer to the NixOS manual.
|
||||
|
||||
## Example Configuration
|
||||
|
||||
Here is a minimal complete flake for a MediaManager setup:
|
||||
|
||||
```nix
|
||||
{
|
||||
description = "An example NixOS configuration";
|
||||
|
||||
inputs = {
|
||||
nixpkgs = { url = "github:nixos/nixpkgs/nixos-unstable"; };
|
||||
mediamanager-nix = {
|
||||
url = "github:strangeglyph/mediamanager-nix";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = inputs@{
|
||||
nixpkgs,
|
||||
mediamanager-nix,
|
||||
...
|
||||
}: {
|
||||
nixosConfigurations.your-system = nixpkgs.lib.nixosSystem {
|
||||
imports = [
|
||||
mediamanager-nix.nixosModules.default
|
||||
];
|
||||
|
||||
config = {
|
||||
services.media-manager = {
|
||||
enable = true;
|
||||
postgres.enable = true;
|
||||
port = 12345;
|
||||
dataDir = "/tmp";
|
||||
settings = {
|
||||
misc.frontend_url = "http://[::1]:12345";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.tmpfiles.settings."10-mediamanager" = {
|
||||
"/tmp/movies".d = { user = config.services.media-manager.user; };
|
||||
"/tmp/shows".d = { user = config.services.media-manager.user; };
|
||||
"/tmp/images".d = { user = config.services.media-manager.user; };
|
||||
"/tmp/torrents".d = { user = config.services.media-manager.user; };
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
@@ -1,7 +1,6 @@
|
||||
# Screenshots
|
||||
|
||||
{% hint style="info" %}
|
||||
MediaManager also supports darkmode!
|
||||
{% endhint %}
|
||||
!!! info
|
||||
MediaManager also supports darkmode!
|
||||
|
||||
      
|
||||
      
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# Troubleshooting
|
||||
|
||||
{% hint style="info" %}
|
||||
Always check the container and browser logs for more specific error messages
|
||||
{% endhint %}
|
||||
!!! info
|
||||
Always check the container and browser logs for more specific error messages
|
||||
|
||||
<details>
|
||||
|
||||
@@ -60,10 +59,9 @@ 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-guide.md#mediamanager-and-metadatarelay-docker-images)
|
||||
* [Try pulling the image from Quay.io](installation/docker.md#docker-images)
|
||||
|
||||
</details>
|
||||
|
||||
{% 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 %}
|
||||
!!! 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.
|
||||
|
||||
133
docs/usage.md
@@ -1,133 +0,0 @@
|
||||
# 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 %}
|
||||
@@ -20,7 +20,3 @@ class AuthConfig(BaseSettings):
|
||||
admin_emails: list[str] = []
|
||||
email_password_resets: bool = False
|
||||
openid_connect: OpenIdConfig = OpenIdConfig()
|
||||
|
||||
@property
|
||||
def jwt_signing_key(self):
|
||||
return self._jwt_signing_key
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi_users.db import (
|
||||
@@ -17,7 +16,7 @@ from media_manager.database import Base, build_db_url
|
||||
|
||||
class OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base):
|
||||
access_token: Mapped[str] = mapped_column(String(length=4096), nullable=False)
|
||||
refresh_token: Mapped[Optional[str]] = mapped_column(
|
||||
refresh_token: Mapped[str | None] = mapped_column(
|
||||
String(length=4096), nullable=True
|
||||
)
|
||||
|
||||
@@ -34,10 +33,12 @@ engine = create_async_engine(
|
||||
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
|
||||
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
async def get_async_session() -> AsyncGenerator[AsyncSession]:
|
||||
async with async_session_maker() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
||||
async def get_user_db(
|
||||
session: AsyncSession = Depends(get_async_session),
|
||||
) -> AsyncGenerator[SQLAlchemyUserDatabase]:
|
||||
yield SQLAlchemyUserDatabase(session, User, OAuthAccount)
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import APIRouter, Depends, FastAPI, status
|
||||
from fastapi_users.router import get_oauth_router
|
||||
from httpx_oauth.oauth2 import OAuth2
|
||||
from sqlalchemy import select
|
||||
@@ -7,6 +10,7 @@ from media_manager.auth.db import User
|
||||
from media_manager.auth.schemas import AuthMetadata, UserRead
|
||||
from media_manager.auth.users import (
|
||||
SECRET,
|
||||
create_default_admin_user,
|
||||
current_superuser,
|
||||
fastapi_users,
|
||||
openid_client,
|
||||
@@ -15,11 +19,18 @@ from media_manager.auth.users import (
|
||||
from media_manager.config import MediaManagerConfig
|
||||
from media_manager.database import DbSessionDependency
|
||||
|
||||
users_router = APIRouter()
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncGenerator:
|
||||
await create_default_admin_user()
|
||||
yield
|
||||
|
||||
|
||||
users_router = APIRouter(lifespan=lifespan)
|
||||
auth_metadata_router = APIRouter()
|
||||
|
||||
|
||||
def get_openid_router():
|
||||
def get_openid_router() -> APIRouter:
|
||||
if openid_client:
|
||||
return get_oauth_router(
|
||||
oauth_client=openid_client,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import contextlib
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Optional, override
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any, override
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
@@ -49,7 +50,7 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
self,
|
||||
user: models.UP,
|
||||
update_dict: dict[str, Any],
|
||||
request: Optional[Request] = None,
|
||||
request: Request | None = None,
|
||||
) -> None:
|
||||
log.info(f"User {user.id} has been updated.")
|
||||
if update_dict.get("is_superuser"):
|
||||
@@ -59,7 +60,9 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
await self.update(user=user, user_update=updated_user)
|
||||
|
||||
@override
|
||||
async def on_after_register(self, user: User, request: Optional[Request] = None):
|
||||
async def on_after_register(
|
||||
self, user: User, request: Request | None = None
|
||||
) -> None:
|
||||
log.info(f"User {user.id} has registered.")
|
||||
if user.email in config.admin_emails:
|
||||
updated_user = UserUpdate(is_superuser=True, is_verified=True)
|
||||
@@ -67,8 +70,8 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
|
||||
@override
|
||||
async def on_after_forgot_password(
|
||||
self, user: User, token: str, request: Optional[Request] = None
|
||||
):
|
||||
self, user: User, token: str, request: Request | None = None
|
||||
) -> None:
|
||||
link = f"{MediaManagerConfig().misc.frontend_url}web/login/reset-password?token={token}"
|
||||
log.info(f"User {user.id} has forgot their password. Reset Link: {link}")
|
||||
|
||||
@@ -83,7 +86,7 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
<p>Hi {user.email},
|
||||
<br>
|
||||
<br>
|
||||
if you forgot your password, <a href="{link}">reset you password here</a>.<br>
|
||||
if you forgot your password, <a href=\"{link}\">reset you password here</a>.<br>
|
||||
If you did not request a password reset, you can ignore this email.</p>
|
||||
<br>
|
||||
<br>
|
||||
@@ -98,24 +101,26 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
|
||||
@override
|
||||
async def on_after_reset_password(
|
||||
self, user: User, request: Optional[Request] = None
|
||||
):
|
||||
self, user: User, request: Request | None = None
|
||||
) -> None:
|
||||
log.info(f"User {user.id} has reset their password.")
|
||||
|
||||
@override
|
||||
async def on_after_request_verify(
|
||||
self, user: User, token: str, request: Optional[Request] = None
|
||||
):
|
||||
self, user: User, token: str, request: Request | None = None
|
||||
) -> None:
|
||||
log.info(
|
||||
f"Verification requested for user {user.id}. Verification token: {token}"
|
||||
)
|
||||
|
||||
@override
|
||||
async def on_after_verify(self, user: User, request: Optional[Request] = None):
|
||||
async def on_after_verify(self, user: User, request: Request | None = None) -> None:
|
||||
log.info(f"User {user.id} has been verified")
|
||||
|
||||
|
||||
async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
|
||||
async def get_user_manager(
|
||||
user_db: SQLAlchemyUserDatabase = Depends(get_user_db),
|
||||
) -> AsyncGenerator[UserManager]:
|
||||
yield UserManager(user_db)
|
||||
|
||||
|
||||
@@ -124,7 +129,7 @@ get_user_db_context = contextlib.asynccontextmanager(get_user_db)
|
||||
get_user_manager_context = contextlib.asynccontextmanager(get_user_manager)
|
||||
|
||||
|
||||
async def create_default_admin_user():
|
||||
async def create_default_admin_user() -> None:
|
||||
"""Create a default admin user if no users exist in the database"""
|
||||
try:
|
||||
async with get_async_session_context() as session:
|
||||
@@ -170,17 +175,13 @@ async def create_default_admin_user():
|
||||
log.info(
|
||||
f"Found {user_count} existing users. Skipping default user creation."
|
||||
)
|
||||
except Exception as e:
|
||||
log.error(f"Failed to create default admin user: {e}")
|
||||
except Exception:
|
||||
log.exception("Failed to create default admin user")
|
||||
log.info(
|
||||
"You can create an admin user manually by registering with an email from the admin_emails list in your config."
|
||||
)
|
||||
|
||||
|
||||
async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
|
||||
yield UserManager(user_db)
|
||||
|
||||
|
||||
def get_jwt_strategy() -> JWTStrategy[models.UP, models.ID]:
|
||||
return JWTStrategy(secret=SECRET, lifetime_seconds=LIFETIME)
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Tuple, Type
|
||||
|
||||
from pydantic import AnyHttpUrl
|
||||
from pydantic_settings import (
|
||||
@@ -41,7 +40,7 @@ class BasicConfig(BaseSettings):
|
||||
movie_directory: Path = Path(__file__).parent.parent / "data" / "movies"
|
||||
torrent_directory: Path = Path(__file__).parent.parent / "data" / "torrents"
|
||||
|
||||
frontend_url: AnyHttpUrl = "http://localhost:8000"
|
||||
frontend_url: AnyHttpUrl = AnyHttpUrl("http://localhost:8000")
|
||||
cors_urls: list[str] = []
|
||||
development: bool = False
|
||||
|
||||
@@ -71,12 +70,12 @@ class MediaManagerConfig(BaseSettings):
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
cls,
|
||||
settings_cls: Type[BaseSettings],
|
||||
settings_cls: type[BaseSettings],
|
||||
init_settings: PydanticBaseSettingsSource,
|
||||
env_settings: PydanticBaseSettingsSource,
|
||||
dotenv_settings: PydanticBaseSettingsSource,
|
||||
file_secret_settings: PydanticBaseSettingsSource,
|
||||
) -> Tuple[PydanticBaseSettingsSource, ...]:
|
||||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||||
return (
|
||||
init_settings,
|
||||
env_settings,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from contextvars import ContextVar
|
||||
from typing import Annotated, Any, Generator, Optional
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy import create_engine
|
||||
@@ -9,12 +10,14 @@ from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.engine.url import URL
|
||||
from sqlalchemy.orm import Session, declarative_base, sessionmaker
|
||||
|
||||
from media_manager.database.config import DbConfig
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
engine: Optional[Engine] = None
|
||||
SessionLocal: Optional[sessionmaker] = None
|
||||
engine: Engine | None = None
|
||||
SessionLocal: sessionmaker | None = None
|
||||
|
||||
|
||||
def build_db_url(
|
||||
@@ -35,7 +38,7 @@ def build_db_url(
|
||||
|
||||
|
||||
def init_engine(
|
||||
db_config: Any | None = None,
|
||||
db_config: DbConfig | None = None,
|
||||
url: str | URL | None = None,
|
||||
) -> Engine:
|
||||
"""
|
||||
@@ -81,7 +84,7 @@ def get_engine() -> Engine:
|
||||
return engine
|
||||
|
||||
|
||||
def get_session() -> Generator[Session, Any, None]:
|
||||
def get_session() -> Generator[Session]:
|
||||
if SessionLocal is None:
|
||||
msg = "Session factory not initialized. Call init_engine(...) first."
|
||||
raise RuntimeError(msg)
|
||||
@@ -89,9 +92,9 @@ def get_session() -> Generator[Session, Any, None]:
|
||||
try:
|
||||
yield db
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
db.rollback()
|
||||
log.critical(f"error occurred: {e}")
|
||||
log.critical("", exc_info=True)
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -4,10 +4,17 @@ from psycopg.errors import UniqueViolation
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
|
||||
class RenameError(Exception):
|
||||
"""Error when renaming something"""
|
||||
|
||||
def __init__(self, message: str = "Failed to rename source directory") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class MediaManagerError(Exception):
|
||||
"""Base exception for MediaManager errors."""
|
||||
|
||||
def __init__(self, message: str = "An error occurred."):
|
||||
def __init__(self, message: str = "An error occurred.") -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
@@ -17,76 +24,76 @@ class MediaAlreadyExistsError(MediaManagerError):
|
||||
|
||||
def __init__(
|
||||
self, message: str = "Entity with this ID or other identifier already exists"
|
||||
):
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class NotFoundError(MediaManagerError):
|
||||
"""Raised when an entity is not found (HTTP 404)."""
|
||||
|
||||
def __init__(self, message: str = "The requested entity was not found."):
|
||||
def __init__(self, message: str = "The requested entity was not found.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class InvalidConfigError(MediaManagerError):
|
||||
"""Raised when the server is improperly configured (HTTP 500)."""
|
||||
|
||||
def __init__(self, message: str = "The server is improperly configured."):
|
||||
def __init__(self, message: str = "The server is improperly configured.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class BadRequestError(MediaManagerError):
|
||||
"""Raised for invalid client requests (HTTP 400)."""
|
||||
|
||||
def __init__(self, message: str = "Bad request."):
|
||||
def __init__(self, message: str = "Bad request.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class UnauthorizedError(MediaManagerError):
|
||||
"""Raised for authentication failures (HTTP 401)."""
|
||||
|
||||
def __init__(self, message: str = "Unauthorized."):
|
||||
def __init__(self, message: str = "Unauthorized.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ForbiddenError(MediaManagerError):
|
||||
"""Raised for forbidden actions (HTTP 403)."""
|
||||
|
||||
def __init__(self, message: str = "Forbidden."):
|
||||
def __init__(self, message: str = "Forbidden.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ConflictError(MediaManagerError):
|
||||
"""Raised for resource conflicts (HTTP 409)."""
|
||||
|
||||
def __init__(self, message: str = "Conflict."):
|
||||
def __init__(self, message: str = "Conflict.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class UnprocessableEntityError(MediaManagerError):
|
||||
"""Raised for validation errors (HTTP 422)."""
|
||||
|
||||
def __init__(self, message: str = "Unprocessable entity."):
|
||||
def __init__(self, message: str = "Unprocessable entity.") -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
# Exception handlers
|
||||
async def media_already_exists_exception_handler(
|
||||
_request: Request, exc: MediaAlreadyExistsError
|
||||
_request: Request, _exc: Exception
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(status_code=409, content={"detail": exc.message})
|
||||
return JSONResponse(status_code=409, content={"detail": str(_exc)})
|
||||
|
||||
|
||||
async def not_found_error_exception_handler(
|
||||
_request: Request, exc: NotFoundError
|
||||
_request: Request, _exc: Exception
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(status_code=404, content={"detail": exc.message})
|
||||
return JSONResponse(status_code=404, content={"detail": str(_exc)})
|
||||
|
||||
|
||||
async def invalid_config_error_exception_handler(
|
||||
_request: Request, exc: InvalidConfigError
|
||||
_request: Request, _exc: Exception
|
||||
) -> JSONResponse:
|
||||
return JSONResponse(status_code=500, content={"detail": exc.message})
|
||||
return JSONResponse(status_code=500, content={"detail": str(_exc)})
|
||||
|
||||
|
||||
async def bad_request_error_handler(
|
||||
@@ -107,8 +114,8 @@ async def forbidden_error_handler(
|
||||
return JSONResponse(status_code=403, content={"detail": exc.message})
|
||||
|
||||
|
||||
async def conflict_error_handler(_request: Request, exc: ConflictError) -> JSONResponse:
|
||||
return JSONResponse(status_code=409, content={"detail": exc.message})
|
||||
async def conflict_error_handler(_request: Request, _exc: Exception) -> JSONResponse:
|
||||
return JSONResponse(status_code=409, content={"detail": str(_exc)})
|
||||
|
||||
|
||||
async def unprocessable_entity_error_handler(
|
||||
@@ -128,7 +135,7 @@ async def sqlalchemy_integrity_error_handler(
|
||||
)
|
||||
|
||||
|
||||
def register_exception_handlers(app: FastAPI):
|
||||
def register_exception_handlers(app: FastAPI) -> None:
|
||||
app.add_exception_handler(NotFoundError, not_found_error_exception_handler)
|
||||
app.add_exception_handler(
|
||||
MediaAlreadyExistsError, media_already_exists_exception_handler
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import shutil
|
||||
from logging import Logger
|
||||
from pathlib import Path
|
||||
|
||||
from media_manager.config import MediaManagerConfig
|
||||
|
||||
def run_filesystem_checks(config, log):
|
||||
|
||||
def run_filesystem_checks(config: MediaManagerConfig, log: Logger) -> None:
|
||||
log.info("Creating directories if they don't exist...")
|
||||
config.misc.tv_directory.mkdir(parents=True, exist_ok=True)
|
||||
config.misc.movie_directory.mkdir(parents=True, exist_ok=True)
|
||||
@@ -33,10 +36,8 @@ def run_filesystem_checks(config, log):
|
||||
if not test_hardlink.samefile(test_torrent_file):
|
||||
log.critical("Hardlink creation failed!")
|
||||
log.info("Successfully created test hardlink in TV directory")
|
||||
except OSError as e:
|
||||
log.error(
|
||||
f"Hardlink creation failed, falling back to copying files. Error: {e}"
|
||||
)
|
||||
except OSError:
|
||||
log.exception("Hardlink creation failed, falling back to copying files")
|
||||
shutil.copy(src=test_torrent_file, dst=test_hardlink)
|
||||
finally:
|
||||
test_hardlink.unlink()
|
||||
|
||||
@@ -5,7 +5,6 @@ from fastapi import Depends
|
||||
from media_manager.database import DbSessionDependency
|
||||
from media_manager.indexer.repository import IndexerRepository
|
||||
from media_manager.indexer.service import IndexerService
|
||||
from media_manager.tv.service import TvService
|
||||
|
||||
|
||||
def get_indexer_repository(db_session: DbSessionDependency) -> IndexerRepository:
|
||||
@@ -21,4 +20,4 @@ def get_indexer_service(
|
||||
return IndexerService(indexer_repository)
|
||||
|
||||
|
||||
indexer_service_dep = Annotated[TvService, Depends(get_indexer_service)]
|
||||
indexer_service_dep = Annotated[IndexerService, Depends(get_indexer_service)]
|
||||
|
||||
@@ -8,7 +8,7 @@ from media_manager.tv.schemas import Show
|
||||
class GenericIndexer(ABC):
|
||||
name: str
|
||||
|
||||
def __init__(self, name: str):
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
|
||||
@abstractmethod
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
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
|
||||
|
||||
@@ -14,8 +17,23 @@ 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):
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
A subclass of GenericIndexer for interacting with the Jacket API.
|
||||
|
||||
@@ -30,11 +48,16 @@ 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, query, is_tv, session
|
||||
self.get_torrents_by_indexer, indexer, params, session
|
||||
)
|
||||
futures.append(future)
|
||||
|
||||
@@ -45,19 +68,108 @@ class Jackett(GenericIndexer, TorznabMixin):
|
||||
result = future.result()
|
||||
if result is not None:
|
||||
responses.extend(result)
|
||||
except Exception as e:
|
||||
log.error(f"search result failed with: {e}")
|
||||
except Exception:
|
||||
log.exception("Searching failed")
|
||||
|
||||
return responses
|
||||
|
||||
def get_torrents_by_indexer(
|
||||
self, indexer: str, query: str, is_tv: bool, session: requests.Session
|
||||
) -> list[IndexerQueryResult]:
|
||||
def __get_search_capabilities(
|
||||
self, indexer: str, session: requests.Session
|
||||
) -> IndexerInfo:
|
||||
url = (
|
||||
self.url
|
||||
+ f"/api/v2.0/indexers/{indexer}/results/torznab/api?apikey={self.api_key}&t={'tvsearch' if is_tv else 'movie'}&q={query}"
|
||||
+ f"/api/v2.0/indexers/{indexer}/results/torznab/api?apikey={self.api_key}&t=caps"
|
||||
)
|
||||
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(
|
||||
@@ -67,13 +179,30 @@ class Jackett(GenericIndexer, TorznabMixin):
|
||||
|
||||
results = self.process_search_result(response.content)
|
||||
|
||||
log.info(f"Indexer {indexer.name} returned {len(results)} results")
|
||||
log.info(f"Indexer {indexer} returned {len(results)} results")
|
||||
return results
|
||||
|
||||
def search_season(
|
||||
self, query: str, show: Show, season_number: int
|
||||
) -> list[IndexerQueryResult]:
|
||||
pass
|
||||
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)
|
||||
|
||||
def search_movie(self, query: str, movie: Movie) -> list[IndexerQueryResult]:
|
||||
pass
|
||||
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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
from requests import Session
|
||||
from requests import Response, Session
|
||||
|
||||
from media_manager.config import MediaManagerConfig
|
||||
from media_manager.indexer.indexers.generic import GenericIndexer
|
||||
@@ -31,14 +31,14 @@ class IndexerInfo:
|
||||
|
||||
|
||||
class Prowlarr(GenericIndexer, TorznabMixin):
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
A subclass of GenericIndexer for interacting with the Prowlarr API.
|
||||
"""
|
||||
super().__init__(name="prowlarr")
|
||||
self.config = MediaManagerConfig().indexers.prowlarr
|
||||
|
||||
def _call_prowlarr_api(self, path: str, parameters: dict | None = None):
|
||||
def _call_prowlarr_api(self, path: str, parameters: dict | None = None) -> Response:
|
||||
url = f"{self.config.url}/api/v1{path}"
|
||||
headers = {"X-Api-Key": self.config.api_key}
|
||||
with Session() as session:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
from media_manager.indexer.schemas import IndexerQueryResult
|
||||
@@ -39,7 +39,7 @@ class TorznabMixin:
|
||||
posted_date = parsedate_to_datetime(
|
||||
attribute.attrib["value"]
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(datetime.UTC)
|
||||
age = int((now - posted_date).total_seconds())
|
||||
else:
|
||||
if attribute.attrib["name"] == "seeders":
|
||||
@@ -61,17 +61,28 @@ class TorznabMixin:
|
||||
if upload_volume_factor == 2:
|
||||
flags.append("doubleupload")
|
||||
|
||||
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.")
|
||||
continue
|
||||
try:
|
||||
size = int(size_str.text or "0")
|
||||
except ValueError:
|
||||
log.warning(f"Torznab item {title} has invalid size, skipping.")
|
||||
continue
|
||||
|
||||
result = IndexerQueryResult(
|
||||
title=item.find("title").text,
|
||||
title=title or "unknown",
|
||||
download_url=str(item.find("enclosure").attrib["url"]),
|
||||
seeders=seeders,
|
||||
flags=flags,
|
||||
size=int(item.find("size").text),
|
||||
size=size,
|
||||
usenet=is_usenet,
|
||||
age=age,
|
||||
indexer=indexer_name,
|
||||
)
|
||||
result_list.append(result)
|
||||
except Exception as e:
|
||||
log.error(f"1 Torznab search result errored with error: {e}")
|
||||
except Exception:
|
||||
log.exception("1 Torznab search result failed")
|
||||
return result_list
|
||||
|
||||
@@ -18,6 +18,7 @@ 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]
|
||||
|
||||
@@ -14,7 +14,7 @@ log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IndexerRepository:
|
||||
def __init__(self, db: Session):
|
||||
def __init__(self, db: Session) -> None:
|
||||
self.db = db
|
||||
|
||||
def get_result(self, result_id: IndexerQueryResultId) -> IndexerQueryResultSchema:
|
||||
|
||||
@@ -13,7 +13,9 @@ IndexerQueryResultId = typing.NewType("IndexerQueryResultId", UUID)
|
||||
class IndexerQueryResult(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: IndexerQueryResultId = pydantic.Field(default_factory=uuid4)
|
||||
id: IndexerQueryResultId = pydantic.Field(
|
||||
default_factory=lambda: IndexerQueryResultId(uuid4())
|
||||
)
|
||||
title: str
|
||||
download_url: str = pydantic.Field(
|
||||
exclude=True,
|
||||
@@ -33,10 +35,10 @@ class IndexerQueryResult(BaseModel):
|
||||
@computed_field
|
||||
@property
|
||||
def quality(self) -> Quality:
|
||||
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"
|
||||
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"
|
||||
|
||||
if re.search(high_quality_pattern, self.title, re.IGNORECASE):
|
||||
return Quality.uhd
|
||||
@@ -52,17 +54,58 @@ class IndexerQueryResult(BaseModel):
|
||||
@computed_field
|
||||
@property
|
||||
def season(self) -> list[int]:
|
||||
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])]
|
||||
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))
|
||||
else:
|
||||
result = []
|
||||
result = [start]
|
||||
|
||||
return result
|
||||
|
||||
def __gt__(self, other) -> bool:
|
||||
def __gt__(self, other: "IndexerQueryResult") -> bool:
|
||||
if self.quality.value != other.quality.value:
|
||||
return self.quality.value < other.quality.value
|
||||
if self.score != other.score:
|
||||
@@ -76,7 +119,7 @@ class IndexerQueryResult(BaseModel):
|
||||
|
||||
return self.size < other.size
|
||||
|
||||
def __lt__(self, other) -> bool:
|
||||
def __lt__(self, other: "IndexerQueryResult") -> bool:
|
||||
if self.quality.value != other.quality.value:
|
||||
return self.quality.value > other.quality.value
|
||||
if self.score != other.score:
|
||||
|
||||
@@ -14,7 +14,7 @@ log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class IndexerService:
|
||||
def __init__(self, indexer_repository: IndexerRepository):
|
||||
def __init__(self, indexer_repository: IndexerRepository) -> None:
|
||||
config = MediaManagerConfig()
|
||||
self.repository = indexer_repository
|
||||
self.indexers: list[GenericIndexer] = []
|
||||
@@ -45,9 +45,9 @@ class IndexerService:
|
||||
log.debug(
|
||||
f"Indexer {indexer.__class__.__name__} returned {len(indexer_results)} results for query: {query}"
|
||||
)
|
||||
except Exception as e:
|
||||
log.error(
|
||||
f"Indexer {indexer.__class__.__name__} failed for query '{query}': {e}"
|
||||
except Exception:
|
||||
log.exception(
|
||||
f"Indexer {indexer.__class__.__name__} failed for query '{query}'"
|
||||
)
|
||||
|
||||
for result in results:
|
||||
@@ -55,7 +55,7 @@ class IndexerService:
|
||||
|
||||
return results
|
||||
|
||||
def search_movie(self, movie: Movie):
|
||||
def search_movie(self, movie: Movie) -> list[IndexerQueryResult]:
|
||||
query = f"{movie.name} {movie.year}"
|
||||
query = remove_special_chars_and_parentheses(query)
|
||||
|
||||
@@ -65,9 +65,9 @@ class IndexerService:
|
||||
indexer_results = indexer.search_movie(query=query, movie=movie)
|
||||
if indexer_results:
|
||||
results.extend(indexer_results)
|
||||
except Exception as e:
|
||||
log.error(
|
||||
f"Indexer {indexer.__class__.__name__} failed for movie search '{query}': {e}"
|
||||
except Exception:
|
||||
log.exception(
|
||||
f"Indexer {indexer.__class__.__name__} failed for movie search '{query}'"
|
||||
)
|
||||
|
||||
for result in results:
|
||||
@@ -75,7 +75,7 @@ class IndexerService:
|
||||
|
||||
return results
|
||||
|
||||
def search_season(self, show: Show, season_number: int):
|
||||
def search_season(self, show: Show, season_number: int) -> list[IndexerQueryResult]:
|
||||
query = f"{show.name} {show.year} S{season_number:02d}"
|
||||
query = remove_special_chars_and_parentheses(query)
|
||||
|
||||
@@ -87,9 +87,9 @@ class IndexerService:
|
||||
)
|
||||
if indexer_results:
|
||||
results.extend(indexer_results)
|
||||
except Exception as e:
|
||||
log.error(
|
||||
f"Indexer {indexer.__class__.__name__} failed for season search '{query}': {e}"
|
||||
except Exception:
|
||||
log.exception(
|
||||
f"Indexer {indexer.__class__.__name__} failed for season search '{query}'"
|
||||
)
|
||||
|
||||
for result in results:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import logging
|
||||
import re
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import requests
|
||||
@@ -14,7 +15,7 @@ log = logging.getLogger(__name__)
|
||||
|
||||
def evaluate_indexer_query_result(
|
||||
query_result: IndexerQueryResult, ruleset: ScoringRuleSet
|
||||
) -> (IndexerQueryResult, bool):
|
||||
) -> tuple[IndexerQueryResult, bool]:
|
||||
title_rules = MediaManagerConfig().indexers.title_scoring_rules
|
||||
indexer_flag_rules = MediaManagerConfig().indexers.indexer_flag_scoring_rules
|
||||
for rule_name in ruleset.rule_names:
|
||||
@@ -23,7 +24,11 @@ def evaluate_indexer_query_result(
|
||||
log.debug(f"Applying rule {rule.name} to {query_result.title}")
|
||||
if (
|
||||
any(
|
||||
keyword.lower() in query_result.title.lower()
|
||||
re.search(
|
||||
rf"\b{re.escape(keyword)}\b",
|
||||
query_result.title,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
for keyword in rule.keywords
|
||||
)
|
||||
and not rule.negate
|
||||
@@ -34,7 +39,11 @@ def evaluate_indexer_query_result(
|
||||
query_result.score += rule.score_modifier
|
||||
elif (
|
||||
not any(
|
||||
keyword.lower() in query_result.title.lower()
|
||||
re.search(
|
||||
rf"\b{re.escape(keyword)}\b",
|
||||
query_result.title,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
for keyword in rule.keywords
|
||||
)
|
||||
and rule.negate
|
||||
@@ -149,8 +158,9 @@ def follow_redirects_to_final_torrent_url(
|
||||
raise RuntimeError(msg)
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
log.debug(f"An error occurred during the request for {initial_url}: {e}")
|
||||
msg = f"An error occurred during the request: {e}"
|
||||
log.debug(
|
||||
f"An error occurred during the request for {initial_url}",
|
||||
exc_info=True,
|
||||
)
|
||||
msg = "An error occurred during the request"
|
||||
raise RuntimeError(msg) from e
|
||||
|
||||
return current_url
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from logging.config import dictConfig
|
||||
from pathlib import Path
|
||||
from typing import override
|
||||
@@ -11,8 +11,8 @@ from pythonjsonlogger.json import JsonFormatter
|
||||
|
||||
class ISOJsonFormatter(JsonFormatter):
|
||||
@override
|
||||
def formatTime(self, record, datefmt=None):
|
||||
dt = datetime.fromtimestamp(record.created, tz=timezone.utc)
|
||||
def formatTime(self, record: logging.LogRecord, datefmt: str | None = None) -> str:
|
||||
dt = datetime.fromtimestamp(record.created, tz=UTC)
|
||||
return dt.isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
@@ -21,13 +21,20 @@ LOG_FILE = Path(os.getenv("LOG_FILE", "/app/config/media_manager.log"))
|
||||
LOGGING_CONFIG = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"filters": {
|
||||
"correlation_id": {
|
||||
"()": "asgi_correlation_id.CorrelationIdFilter",
|
||||
"uuid_length": 32,
|
||||
"default_value": "-",
|
||||
},
|
||||
},
|
||||
"formatters": {
|
||||
"default": {
|
||||
"format": "%(asctime)s - %(levelname)s - %(name)s - %(funcName)s(): %(message)s"
|
||||
"format": "%(asctime)s - [%(correlation_id)s] %(levelname)s - %(name)s - %(funcName)s(): %(message)s"
|
||||
},
|
||||
"json": {
|
||||
"()": ISOJsonFormatter,
|
||||
"format": "%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
"format": "%(asctime)s %(correlation_id)s %(levelname)s %(name)s %(message)s",
|
||||
"rename_fields": {
|
||||
"levelname": "level",
|
||||
"asctime": "timestamp",
|
||||
@@ -39,11 +46,13 @@ LOGGING_CONFIG = {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "default",
|
||||
"filters": ["correlation_id"],
|
||||
"stream": sys.stdout,
|
||||
},
|
||||
"file": {
|
||||
"class": "logging.handlers.RotatingFileHandler",
|
||||
"formatter": "json",
|
||||
"filters": ["correlation_id"],
|
||||
"filename": str(LOG_FILE),
|
||||
"maxBytes": 10485760,
|
||||
"backupCount": 5,
|
||||
@@ -62,7 +71,7 @@ LOGGING_CONFIG = {
|
||||
}
|
||||
|
||||
|
||||
def setup_logging():
|
||||
def setup_logging() -> None:
|
||||
dictConfig(LOGGING_CONFIG)
|
||||
logging.basicConfig(
|
||||
level=LOG_LEVEL,
|
||||
@@ -74,3 +83,4 @@ def setup_logging():
|
||||
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)
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import uvicorn
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from asgi_correlation_id import CorrelationIdMiddleware
|
||||
from fastapi import APIRouter, FastAPI, Request, Response
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from psycopg.errors import UniqueViolation
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from starlette.responses import FileResponse, RedirectResponse, Response
|
||||
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
|
||||
@@ -27,6 +33,7 @@ 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,
|
||||
@@ -41,18 +48,24 @@ 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 setup_scheduler
|
||||
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,
|
||||
)
|
||||
|
||||
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", "")
|
||||
@@ -61,7 +74,57 @@ DISABLE_FRONTEND_MOUNT = os.getenv("DISABLE_FRONTEND_MOUNT", "").lower() == "tru
|
||||
FRONTEND_FOLLOW_SYMLINKS = os.getenv("FRONTEND_FOLLOW_SYMLINKS", "").lower() == "true"
|
||||
|
||||
log.info("Hello World!")
|
||||
app = FastAPI(root_path=BASE_PATH)
|
||||
|
||||
|
||||
@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.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
|
||||
origins = config.misc.cors_urls
|
||||
log.info(f"CORS URLs activated for following origins: {origins}")
|
||||
@@ -71,6 +134,7 @@ app.add_middleware(
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "PUT", "POST", "DELETE", "PATCH", "HEAD", "OPTIONS"],
|
||||
)
|
||||
app.add_middleware(CorrelationIdMiddleware, header_name="X-Correlation-ID")
|
||||
api_app = APIRouter(prefix="/api/v1")
|
||||
|
||||
|
||||
@@ -143,23 +207,23 @@ else:
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
async def root() -> RedirectResponse:
|
||||
return RedirectResponse(url="/web/")
|
||||
|
||||
|
||||
@app.get("/dashboard")
|
||||
async def dashboard():
|
||||
async def dashboard() -> RedirectResponse:
|
||||
return RedirectResponse(url="/web/")
|
||||
|
||||
|
||||
@app.get("/login")
|
||||
async def login():
|
||||
async def login() -> RedirectResponse:
|
||||
return RedirectResponse(url="/web/")
|
||||
|
||||
|
||||
# this will serve the custom 404 page for frontend routes, so SvelteKit can handle routing
|
||||
@app.exception_handler(404)
|
||||
async def not_found_handler(request, _exc):
|
||||
async def not_found_handler(request: Request, _exc: Exception) -> Response:
|
||||
if not DISABLE_FRONTEND_MOUNT and any(
|
||||
base_path in ["/web", "/dashboard", "/login"] for base_path in request.url.path
|
||||
):
|
||||
|
||||
@@ -18,15 +18,11 @@ class AbstractMetadataProvider(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_show_metadata(
|
||||
self, show_id: int | None = None, language: str | None = None
|
||||
) -> Show:
|
||||
def get_show_metadata(self, show_id: int, language: str | None = None) -> Show:
|
||||
raise NotImplementedError()
|
||||
|
||||
@abstractmethod
|
||||
def get_movie_metadata(
|
||||
self, movie_id: int | None = None, language: str | None = None
|
||||
) -> Movie:
|
||||
def get_movie_metadata(self, movie_id: int, language: str | None = None) -> Movie:
|
||||
raise NotImplementedError()
|
||||
|
||||
@abstractmethod
|
||||
|
||||
@@ -21,7 +21,7 @@ log = logging.getLogger(__name__)
|
||||
class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
name = "tmdb"
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
config = MediaManagerConfig().metadata.tmdb
|
||||
self.url = config.tmdb_relay_url
|
||||
self.primary_languages = config.primary_languages
|
||||
@@ -51,7 +51,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error getting show metadata for ID {show_id}: {e}")
|
||||
log.exception(f"TMDB API error getting show metadata for ID {show_id}")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -68,7 +68,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error getting show external IDs for ID {show_id}: {e}")
|
||||
log.exception(f"TMDB API error getting show external IDs for ID {show_id}")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -90,8 +90,8 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(
|
||||
f"TMDB API error getting season {season_number} metadata for show ID {show_id}: {e}"
|
||||
log.exception(
|
||||
f"TMDB API error getting season {season_number} metadata for show ID {show_id}"
|
||||
)
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
@@ -113,7 +113,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error searching TV shows with query '{query}': {e}")
|
||||
log.exception(f"TMDB API error searching TV shows with query '{query}'")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -131,7 +131,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error getting trending TV: {e}")
|
||||
log.exception("TMDB API error getting trending TV")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -151,7 +151,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error getting movie metadata for ID {movie_id}: {e}")
|
||||
log.exception(f"TMDB API error getting movie metadata for ID {movie_id}")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -167,8 +167,8 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(
|
||||
f"TMDB API error getting movie external IDs for ID {movie_id}: {e}"
|
||||
log.exception(
|
||||
f"TMDB API error getting movie external IDs for ID {movie_id}"
|
||||
)
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
@@ -190,7 +190,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error searching movies with query '{query}': {e}")
|
||||
log.exception(f"TMDB API error searching movies with query '{query}'")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -208,7 +208,7 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
log.error(f"TMDB API error getting trending movies: {e}")
|
||||
log.exception("TMDB API error getting trending movies")
|
||||
if notification_manager.is_configured():
|
||||
notification_manager.send_notification(
|
||||
title="TMDB API Error",
|
||||
@@ -243,13 +243,11 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
return True
|
||||
|
||||
@override
|
||||
def get_show_metadata(
|
||||
self, show_id: int | None = None, language: str | None = None
|
||||
) -> Show:
|
||||
def get_show_metadata(self, show_id: int, language: str | None = None) -> Show:
|
||||
"""
|
||||
|
||||
:param id: the external id of the show
|
||||
:type id: int
|
||||
:param show_id: the external id of the show
|
||||
:type show_id: int
|
||||
:param language: optional language code (ISO 639-1) to fetch metadata in
|
||||
:type language: str | None
|
||||
:return: returns a Show object
|
||||
@@ -368,19 +366,17 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
original_language=original_language,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Error processing search result: {e}")
|
||||
except Exception:
|
||||
log.warning("Error processing search result", exc_info=True)
|
||||
return formatted_results
|
||||
|
||||
@override
|
||||
def get_movie_metadata(
|
||||
self, movie_id: int | None = None, language: str | None = None
|
||||
) -> Movie:
|
||||
def get_movie_metadata(self, movie_id: int, language: str | None = None) -> Movie:
|
||||
"""
|
||||
Get movie metadata with language-aware fetching.
|
||||
|
||||
:param id: the external id of the movie
|
||||
:type id: int
|
||||
:param movie_id: the external id of the movie
|
||||
:type movie_id: int
|
||||
:param language: optional language code (ISO 639-1) to fetch metadata in
|
||||
:type language: str | None
|
||||
:return: returns a Movie object
|
||||
@@ -470,8 +466,8 @@ class TmdbMetadataProvider(AbstractMetadataProvider):
|
||||
original_language=original_language,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Error processing search result: {e}")
|
||||
except Exception:
|
||||
log.warning("Error processing search result", exc_info=True)
|
||||
return formatted_results
|
||||
|
||||
@override
|
||||
|
||||
@@ -18,7 +18,7 @@ log = logging.getLogger(__name__)
|
||||
class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
name = "tvdb"
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self) -> None:
|
||||
config = MediaManagerConfig().metadata.tvdb
|
||||
self.url = config.tvdb_relay_url
|
||||
|
||||
@@ -63,12 +63,10 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
return False
|
||||
|
||||
@override
|
||||
def get_show_metadata(
|
||||
self, show_id: int | None = None, language: str | None = None
|
||||
) -> Show:
|
||||
def get_show_metadata(self, show_id: int, language: str | None = None) -> Show:
|
||||
"""
|
||||
|
||||
:param id: the external id of the show
|
||||
:param show_id: The external id of the show
|
||||
:param language: does nothing, TVDB does not support multiple languages
|
||||
"""
|
||||
series = self.__get_show(show_id)
|
||||
@@ -150,8 +148,8 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
vote_average=None,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Error processing search result: {e}")
|
||||
except Exception:
|
||||
log.warning("Error processing search result", exc_info=True)
|
||||
return formatted_results
|
||||
results = self.__get_trending_tv()
|
||||
formatted_results = []
|
||||
@@ -178,8 +176,8 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
vote_average=None,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Error processing search result: {e}")
|
||||
except Exception:
|
||||
log.warning("Error processing search result", exc_info=True)
|
||||
return formatted_results
|
||||
|
||||
@override
|
||||
@@ -215,8 +213,8 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
vote_average=None,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Error processing search result: {e}")
|
||||
except Exception:
|
||||
log.warning("Error processing search result", exc_info=True)
|
||||
return formatted_results
|
||||
results = self.__get_trending_movies()
|
||||
results = results[0:20]
|
||||
@@ -230,11 +228,16 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
except KeyError:
|
||||
year = None
|
||||
|
||||
if result.get("image"):
|
||||
poster_path = "https://artworks.thetvdb.com" + str(
|
||||
result.get("image")
|
||||
)
|
||||
else:
|
||||
poster_path = None
|
||||
|
||||
formatted_results.append(
|
||||
MetaDataProviderSearchResult(
|
||||
poster_path="https://artworks.thetvdb.com" + result.get("image")
|
||||
if result.get("image")
|
||||
else None,
|
||||
poster_path=poster_path if result.get("image") else None,
|
||||
overview=result.get("overview"),
|
||||
name=result["name"],
|
||||
external_id=result["id"],
|
||||
@@ -244,8 +247,8 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
vote_average=None,
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
log.warning(f"Error processing search result: {e}")
|
||||
except Exception:
|
||||
log.warning("Error processing search result", exc_info=True)
|
||||
return formatted_results
|
||||
|
||||
@override
|
||||
@@ -264,16 +267,14 @@ class TvdbMetadataProvider(AbstractMetadataProvider):
|
||||
return False
|
||||
|
||||
@override
|
||||
def get_movie_metadata(
|
||||
self, movie_id: int | None = None, language: str | None = None
|
||||
) -> Movie:
|
||||
def get_movie_metadata(self, movie_id: int, language: str | None = None) -> Movie:
|
||||
"""
|
||||
|
||||
:param movie_id: the external id of the movie
|
||||
:param language: does nothing, TVDB does not support multiple languages
|
||||
:return: returns a Movie object
|
||||
"""
|
||||
movie = self.__get_movie(movie_id)
|
||||
movie = self.__get_movie(movie_id=movie_id)
|
||||
|
||||
# get imdb id from remote ids
|
||||
imdb_id = None
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3,7 +3,6 @@ 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
|
||||
|
||||
@@ -22,10 +21,6 @@ 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"
|
||||
@@ -42,31 +37,3 @@ 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)
|
||||
|
||||
@@ -5,10 +5,10 @@ from sqlalchemy.exc import (
|
||||
IntegrityError,
|
||||
SQLAlchemyError,
|
||||
)
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from media_manager.exceptions import ConflictError, NotFoundError
|
||||
from media_manager.movies.models import Movie, MovieFile, MovieRequest
|
||||
from media_manager.movies.models import Movie, MovieFile
|
||||
from media_manager.movies.schemas import (
|
||||
Movie as MovieSchema,
|
||||
)
|
||||
@@ -17,17 +17,10 @@ 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
|
||||
|
||||
@@ -40,7 +33,7 @@ class MovieRepository:
|
||||
Provides methods to retrieve, save, and delete movies.
|
||||
"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
def __init__(self, db: Session) -> None:
|
||||
self.db = db
|
||||
|
||||
def get_movie_by_id(self, movie_id: MovieId) -> MovieSchema:
|
||||
@@ -59,8 +52,8 @@ class MovieRepository:
|
||||
msg = f"Movie with id {movie_id} not found."
|
||||
raise NotFoundError(msg)
|
||||
return MovieSchema.model_validate(result)
|
||||
except SQLAlchemyError as e:
|
||||
log.error(f"Database error while retrieving movie {movie_id}: {e}")
|
||||
except SQLAlchemyError:
|
||||
log.exception(f"Database error while retrieving movie {movie_id}")
|
||||
raise
|
||||
|
||||
def get_movie_by_external_id(
|
||||
@@ -86,9 +79,9 @@ class MovieRepository:
|
||||
msg = f"Movie with external_id {external_id} and provider {metadata_provider} not found."
|
||||
raise NotFoundError(msg)
|
||||
return MovieSchema.model_validate(result)
|
||||
except SQLAlchemyError as e:
|
||||
log.error(
|
||||
f"Database error while retrieving movie by external_id {external_id}: {e}"
|
||||
except SQLAlchemyError:
|
||||
log.exception(
|
||||
f"Database error while retrieving movie by external_id {external_id}"
|
||||
)
|
||||
raise
|
||||
|
||||
@@ -103,8 +96,8 @@ class MovieRepository:
|
||||
stmt = select(Movie)
|
||||
results = self.db.execute(stmt).scalars().unique().all()
|
||||
return [MovieSchema.model_validate(movie) for movie in results]
|
||||
except SQLAlchemyError as e:
|
||||
log.error(f"Database error while retrieving all movies: {e}")
|
||||
except SQLAlchemyError:
|
||||
log.exception("Database error while retrieving all movies")
|
||||
raise
|
||||
|
||||
def save_movie(self, movie: MovieSchema) -> MovieSchema:
|
||||
@@ -140,14 +133,14 @@ class MovieRepository:
|
||||
return MovieSchema.model_validate(db_movie)
|
||||
except IntegrityError as e:
|
||||
self.db.rollback()
|
||||
log.error(f"Integrity error while saving movie {movie.name}: {e}")
|
||||
log.exception(f"Integrity error while saving movie {movie.name}")
|
||||
msg = (
|
||||
f"Movie with this primary key or unique constraint violation: {e.orig}"
|
||||
)
|
||||
raise ConflictError(msg) from e
|
||||
except SQLAlchemyError as e:
|
||||
except SQLAlchemyError:
|
||||
self.db.rollback()
|
||||
log.error(f"Database error while saving movie {movie.name}: {e}")
|
||||
log.exception(f"Database error while saving movie {movie.name}")
|
||||
raise
|
||||
|
||||
def delete_movie(self, movie_id: MovieId) -> None:
|
||||
@@ -168,49 +161,9 @@ class MovieRepository:
|
||||
self.db.delete(movie)
|
||||
self.db.commit()
|
||||
log.info(f"Successfully deleted movie with id: {movie_id}")
|
||||
except SQLAlchemyError as e:
|
||||
except SQLAlchemyError:
|
||||
self.db.rollback()
|
||||
log.error(f"Database error while deleting movie {movie_id}: {e}")
|
||||
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 as e:
|
||||
self.db.rollback()
|
||||
log.error(f"Integrity error while adding movie request: {e}")
|
||||
raise
|
||||
except SQLAlchemyError as e:
|
||||
self.db.rollback()
|
||||
log.error(f"Database error while adding movie request: {e}")
|
||||
log.exception(f"Database error while deleting movie {movie_id}")
|
||||
raise
|
||||
|
||||
def set_movie_library(self, movie_id: MovieId, library: str) -> None:
|
||||
@@ -229,52 +182,9 @@ class MovieRepository:
|
||||
raise NotFoundError(msg)
|
||||
movie.library = library
|
||||
self.db.commit()
|
||||
except SQLAlchemyError as e:
|
||||
except SQLAlchemyError:
|
||||
self.db.rollback()
|
||||
log.error(f"Database error setting library for movie {movie_id}: {e}")
|
||||
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 as e:
|
||||
self.db.rollback()
|
||||
log.error(
|
||||
f"Database error while deleting movie request {movie_request_id}: {e}"
|
||||
)
|
||||
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 as e:
|
||||
log.error(f"Database error while retrieving movie requests: {e}")
|
||||
log.exception(f"Database error setting library for movie {movie_id}")
|
||||
raise
|
||||
|
||||
def add_movie_file(self, movie_file: MovieFileSchema) -> MovieFileSchema:
|
||||
@@ -292,13 +202,13 @@ class MovieRepository:
|
||||
self.db.commit()
|
||||
self.db.refresh(db_model)
|
||||
return MovieFileSchema.model_validate(db_model)
|
||||
except IntegrityError as e:
|
||||
except IntegrityError:
|
||||
self.db.rollback()
|
||||
log.error(f"Integrity error while adding movie file: {e}")
|
||||
log.exception("Integrity error while adding movie file")
|
||||
raise
|
||||
except SQLAlchemyError as e:
|
||||
except SQLAlchemyError:
|
||||
self.db.rollback()
|
||||
log.error(f"Database error while adding movie file: {e}")
|
||||
log.exception("Database error while adding movie file")
|
||||
raise
|
||||
|
||||
def remove_movie_files_by_torrent_id(self, torrent_id: TorrentId) -> int:
|
||||
@@ -313,14 +223,15 @@ class MovieRepository:
|
||||
stmt = delete(MovieFile).where(MovieFile.torrent_id == torrent_id)
|
||||
result = self.db.execute(stmt)
|
||||
self.db.commit()
|
||||
return result.rowcount
|
||||
except SQLAlchemyError as e:
|
||||
except SQLAlchemyError:
|
||||
self.db.rollback()
|
||||
log.error(
|
||||
f"Database error removing movie files for torrent_id {torrent_id}: {e}"
|
||||
log.exception(
|
||||
f"Database error removing movie files for torrent_id {torrent_id}"
|
||||
)
|
||||
raise
|
||||
|
||||
return result.rowcount
|
||||
|
||||
def get_movie_files_by_movie_id(self, movie_id: MovieId) -> list[MovieFileSchema]:
|
||||
"""
|
||||
Retrieve all movie files for a given movie ID.
|
||||
@@ -333,9 +244,9 @@ class MovieRepository:
|
||||
stmt = select(MovieFile).where(MovieFile.movie_id == movie_id)
|
||||
results = self.db.execute(stmt).scalars().all()
|
||||
return [MovieFileSchema.model_validate(sf) for sf in results]
|
||||
except SQLAlchemyError as e:
|
||||
log.error(
|
||||
f"Database error retrieving movie files for movie_id {movie_id}: {e}"
|
||||
except SQLAlchemyError:
|
||||
log.exception(
|
||||
f"Database error retrieving movie files for movie_id {movie_id}"
|
||||
)
|
||||
raise
|
||||
|
||||
@@ -367,13 +278,13 @@ class MovieRepository:
|
||||
usenet=torrent.usenet,
|
||||
)
|
||||
formatted_results.append(movie_torrent)
|
||||
return formatted_results
|
||||
except SQLAlchemyError as e:
|
||||
log.error(
|
||||
f"Database error retrieving torrents for movie_id {movie_id}: {e}"
|
||||
)
|
||||
|
||||
except SQLAlchemyError:
|
||||
log.exception(f"Database error retrieving torrents for movie_id {movie_id}")
|
||||
raise
|
||||
|
||||
return formatted_results
|
||||
|
||||
def get_all_movies_with_torrents(self) -> list[MovieSchema]:
|
||||
"""
|
||||
Retrieve all movies that are associated with a torrent, ordered alphabetically by movie name.
|
||||
@@ -391,29 +302,8 @@ class MovieRepository:
|
||||
)
|
||||
results = self.db.execute(stmt).scalars().unique().all()
|
||||
return [MovieSchema.model_validate(movie) for movie in results]
|
||||
except SQLAlchemyError as e:
|
||||
log.error(f"Database error retrieving all movies with torrents: {e}")
|
||||
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 as e:
|
||||
log.error(
|
||||
f"Database error retrieving movie request {movie_request_id}: {e}"
|
||||
)
|
||||
except SQLAlchemyError:
|
||||
log.exception("Database error retrieving all movies with torrents")
|
||||
raise
|
||||
|
||||
def get_movie_by_torrent_id(self, torrent_id: TorrentId) -> MovieSchema:
|
||||
@@ -436,10 +326,8 @@ class MovieRepository:
|
||||
msg = f"Movie for torrent_id {torrent_id} not found."
|
||||
raise NotFoundError(msg)
|
||||
return MovieSchema.model_validate(result)
|
||||
except SQLAlchemyError as e:
|
||||
log.error(
|
||||
f"Database error retrieving movie by torrent_id {torrent_id}: {e}"
|
||||
)
|
||||
except SQLAlchemyError:
|
||||
log.exception(f"Database error retrieving movie by torrent_id {torrent_id}")
|
||||
raise
|
||||
|
||||
def update_movie_attributes(
|
||||
|
||||
@@ -1,32 +1,24 @@
|
||||
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
|
||||
from media_manager.exceptions import ConflictError, NotFoundError
|
||||
from media_manager.indexer.schemas import (
|
||||
IndexerQueryResult,
|
||||
IndexerQueryResultId,
|
||||
)
|
||||
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
|
||||
@@ -97,7 +89,7 @@ def get_all_importable_movies(
|
||||
)
|
||||
def import_detected_movie(
|
||||
movie_service: movie_service_dep, movie: movie_dep, directory: str
|
||||
):
|
||||
) -> None:
|
||||
"""
|
||||
Import a detected movie from the specified directory into the library.
|
||||
"""
|
||||
@@ -145,7 +137,7 @@ def add_a_movie(
|
||||
metadata_provider: metadata_provider_dep,
|
||||
movie_id: int,
|
||||
language: str | None = None,
|
||||
):
|
||||
) -> Movie:
|
||||
"""
|
||||
Add a new movie to the library.
|
||||
"""
|
||||
@@ -159,6 +151,8 @@ def add_a_movie(
|
||||
movie = movie_service.get_movie_by_external_id(
|
||||
external_id=movie_id, metadata_provider=metadata_provider.name
|
||||
)
|
||||
if not movie:
|
||||
raise NotFoundError from ConflictError
|
||||
return movie
|
||||
|
||||
|
||||
@@ -186,103 +180,6 @@ 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.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,
|
||||
):
|
||||
"""
|
||||
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
|
||||
return 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
|
||||
):
|
||||
"""
|
||||
Delete a movie request.
|
||||
"""
|
||||
movie_service.delete_movie_request(movie_request_id=movie_request_id)
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# MOVIES - SINGLE RESOURCE
|
||||
# -----------------------------------------------------------------------------
|
||||
@@ -309,7 +206,7 @@ def delete_a_movie(
|
||||
movie: movie_dep,
|
||||
delete_files_on_disk: bool = False,
|
||||
delete_torrents: bool = False,
|
||||
):
|
||||
) -> None:
|
||||
"""
|
||||
Delete a movie from the library.
|
||||
"""
|
||||
|
||||
@@ -2,20 +2,18 @@ import typing
|
||||
import uuid
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
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):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: MovieId = Field(default_factory=uuid.uuid4)
|
||||
id: MovieId = Field(default_factory=lambda: MovieId(uuid.uuid4()))
|
||||
name: str
|
||||
overview: str
|
||||
year: int | None
|
||||
@@ -40,38 +38,6 @@ 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=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)
|
||||
|
||||
|
||||
@@ -4,12 +4,9 @@ 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
|
||||
from media_manager.indexer.repository import IndexerRepository
|
||||
from media_manager.exceptions import InvalidConfigError, NotFoundError, RenameError
|
||||
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
|
||||
@@ -25,19 +22,14 @@ from media_manager.movies.schemas import (
|
||||
Movie,
|
||||
MovieFile,
|
||||
MovieId,
|
||||
MovieRequest,
|
||||
MovieRequestId,
|
||||
PublicMovie,
|
||||
PublicMovieFile,
|
||||
RichMovieRequest,
|
||||
RichMovieTorrent,
|
||||
)
|
||||
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,
|
||||
)
|
||||
@@ -58,8 +50,8 @@ class MovieService:
|
||||
movie_repository: MovieRepository,
|
||||
torrent_service: TorrentService,
|
||||
indexer_service: IndexerService,
|
||||
notification_service: NotificationService = None,
|
||||
):
|
||||
notification_service: NotificationService,
|
||||
) -> None:
|
||||
self.movie_repository = movie_repository
|
||||
self.torrent_service = torrent_service
|
||||
self.indexer_service = indexer_service
|
||||
@@ -70,7 +62,7 @@ class MovieService:
|
||||
external_id: int,
|
||||
metadata_provider: AbstractMetadataProvider,
|
||||
language: str | None = None,
|
||||
) -> Movie | None:
|
||||
) -> Movie:
|
||||
"""
|
||||
Add a new movie to the database.
|
||||
|
||||
@@ -82,52 +74,12 @@ class MovieService:
|
||||
movie_id=external_id, language=language
|
||||
)
|
||||
if not movie_with_metadata:
|
||||
return None
|
||||
raise NotFoundError
|
||||
|
||||
saved_movie = self.movie_repository.save_movie(movie=movie_with_metadata)
|
||||
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 | None:
|
||||
"""
|
||||
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,
|
||||
@@ -150,10 +102,8 @@ class MovieService:
|
||||
try:
|
||||
shutil.rmtree(movie_dir)
|
||||
log.info(f"Deleted movie directory: {movie_dir}")
|
||||
except OSError as e:
|
||||
log.error(
|
||||
f"Deleting movie directory: {movie_dir} : {e.strerror}"
|
||||
)
|
||||
except OSError:
|
||||
log.exception(f"Deleting movie directory: {movie_dir}")
|
||||
|
||||
if delete_torrents:
|
||||
# Get all torrents associated with this movie
|
||||
@@ -170,8 +120,10 @@ class MovieService:
|
||||
torrent=torrent, delete_files=True
|
||||
)
|
||||
log.info(f"Deleted torrent: {torrent.torrent_title}")
|
||||
except Exception as e:
|
||||
log.warning(f"Failed to delete torrent {torrent.hash}: {e}")
|
||||
except Exception:
|
||||
log.warning(
|
||||
f"Failed to delete torrent {torrent.hash}", exc_info=True
|
||||
)
|
||||
|
||||
# Delete from database
|
||||
self.movie_repository.delete_movie(movie_id=movie.id)
|
||||
@@ -236,19 +188,19 @@ class MovieService:
|
||||
self.movie_repository.get_movie_by_external_id(
|
||||
external_id=external_id, metadata_provider=metadata_provider
|
||||
)
|
||||
return True
|
||||
except NotFoundError:
|
||||
return False
|
||||
elif movie_id is not None:
|
||||
try:
|
||||
self.movie_repository.get_movie_by_id(movie_id=movie_id)
|
||||
return True
|
||||
except NotFoundError:
|
||||
return False
|
||||
else:
|
||||
msg = "Use one of the provided overloads for this function!"
|
||||
raise ValueError(msg)
|
||||
|
||||
return True
|
||||
|
||||
def get_all_available_torrents_for_movie(
|
||||
self, movie: Movie, search_query_override: str | None = None
|
||||
) -> list[IndexerQueryResult]:
|
||||
@@ -392,14 +344,6 @@ 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)
|
||||
|
||||
@@ -472,65 +416,6 @@ 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 = (
|
||||
@@ -569,8 +454,8 @@ class MovieService:
|
||||
|
||||
try:
|
||||
movie_root_path.mkdir(parents=True, exist_ok=True)
|
||||
except Exception as e:
|
||||
log.error(f"Failed to create directory {movie_root_path}: {e}")
|
||||
except Exception:
|
||||
log.exception("Failed to create directory {movie_root_path}")
|
||||
return False
|
||||
|
||||
# import movie video
|
||||
@@ -681,9 +566,8 @@ class MovieService:
|
||||
try:
|
||||
source_directory.rename(new_source_path)
|
||||
except Exception as e:
|
||||
log.error(f"Failed to rename {source_directory} to {new_source_path}: {e}")
|
||||
msg = "Failed to rename directory"
|
||||
raise Exception(msg) from e
|
||||
log.exception(f"Failed to rename {source_directory} to {new_source_path}")
|
||||
raise RenameError from e
|
||||
|
||||
video_files, subtitle_files, _all_files = get_files_for_import(
|
||||
directory=new_source_path
|
||||
@@ -725,7 +609,7 @@ class MovieService:
|
||||
)
|
||||
if not fresh_movie_data:
|
||||
log.warning(
|
||||
f"Could not fetch fresh metadata for movie: {db_movie.name} (ID: {db_movie.external_id})"
|
||||
f"Could not fetch fresh metadata for movie: {db_movie.name} ({db_movie.year})"
|
||||
)
|
||||
return None
|
||||
log.debug(f"Fetched fresh metadata for movie: {fresh_movie_data.name}")
|
||||
@@ -740,7 +624,9 @@ class MovieService:
|
||||
|
||||
updated_movie = self.movie_repository.get_movie_by_id(movie_id=db_movie.id)
|
||||
|
||||
log.info(f"Successfully updated metadata for movie ID: {db_movie.id}")
|
||||
log.info(
|
||||
f"Successfully updated metadata for movie: {db_movie.name} ({db_movie.year})"
|
||||
)
|
||||
metadata_provider.download_movie_poster_image(movie=updated_movie)
|
||||
return updated_movie
|
||||
|
||||
@@ -775,94 +661,29 @@ class MovieService:
|
||||
log.debug(f"Found {len(importable_movies)} importable movies.")
|
||||
return importable_movies
|
||||
|
||||
|
||||
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()
|
||||
movie_repository = MovieRepository(db=db)
|
||||
torrent_service = TorrentService(torrent_repository=TorrentRepository(db=db))
|
||||
indexer_service = IndexerService(indexer_repository=IndexerRepository(db=db))
|
||||
movie_service = MovieService(
|
||||
movie_repository=movie_repository,
|
||||
torrent_service=torrent_service,
|
||||
indexer_service=indexer_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))
|
||||
movie_service = MovieService(
|
||||
movie_repository=movie_repository,
|
||||
torrent_service=torrent_service,
|
||||
indexer_service=indexer_service,
|
||||
)
|
||||
def import_all_torrents(self) -> None:
|
||||
log.info("Importing all torrents")
|
||||
torrents = torrent_service.get_all_torrents()
|
||||
torrents = self.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 = torrent_service.get_movie_of_torrent(torrent=t)
|
||||
movie = self.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
|
||||
movie_service.import_torrent_files(torrent=t, movie=movie)
|
||||
except RuntimeError as e:
|
||||
log.error(
|
||||
f"Failed to import torrent {t.title}: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
self.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)),
|
||||
)
|
||||
|
||||
def update_all_metadata(self) -> None:
|
||||
"""Updates the metadata of all movies."""
|
||||
log.info("Updating metadata for all movies")
|
||||
|
||||
movies = movie_repository.get_movies()
|
||||
|
||||
movies = self.movie_repository.get_movies()
|
||||
log.info(f"Found {len(movies)} movies to update")
|
||||
|
||||
for movie in movies:
|
||||
try:
|
||||
if movie.metadata_provider == "tmdb":
|
||||
@@ -874,12 +695,11 @@ def update_all_movies_metadata() -> None:
|
||||
f"Unsupported metadata provider {movie.metadata_provider} for movie {movie.name}, skipping update."
|
||||
)
|
||||
continue
|
||||
except InvalidConfigError as e:
|
||||
log.error(
|
||||
f"Error initializing metadata provider {movie.metadata_provider} for movie {movie.name}: {e}"
|
||||
except InvalidConfigError:
|
||||
log.exception(
|
||||
f"Error initializing metadata provider {movie.metadata_provider} for movie {movie.name}",
|
||||
)
|
||||
continue
|
||||
movie_service.update_movie_metadata(
|
||||
self.update_movie_metadata(
|
||||
db_movie=movie, metadata_provider=metadata_provider
|
||||
)
|
||||
db.commit()
|
||||
|
||||