update
Some checks failed
Tests / test (ubuntu-latest, 3.8) (push) Failing after 24m2s
Tests / test (ubuntu-latest, 3.10) (push) Failing after 24m4s
Tests / test (ubuntu-latest, 3.9) (push) Failing after 10m52s
Tests / test (macos-latest, 3.10) (push) Has been cancelled
Tests / test (macos-latest, 3.8) (push) Has been cancelled
Tests / test (macos-latest, 3.9) (push) Has been cancelled
Tests / test (windows-latest, 3.10) (push) Has been cancelled
Tests / test (windows-latest, 3.8) (push) Has been cancelled
Tests / test (windows-latest, 3.9) (push) Has been cancelled

This commit is contained in:
sudacode 2025-03-08 23:52:40 -08:00
parent a66e3ab455
commit ad11faf1b0
Signed by: sudacode
SSH Key Fingerprint: SHA256:lT5C2bB398DcX6daCF/gYFNSTK3y+Du3oTGUnYzfTEw
23 changed files with 2946 additions and 155 deletions

View File

@ -0,0 +1,140 @@
name: Create Release and Publish
on:
workflow_dispatch:
inputs:
version_bump:
description: "Type of version bump"
required: true
default: "patch"
type: choice
options:
- patch
- minor
- major
custom_version:
description: "Custom version (if specified, ignores version_bump)"
required: false
push:
tags:
- "v*.*.*"
jobs:
create-release:
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
steps:
- name: Check out code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel semver
- name: Determine current version
id: current_version
run: |
CURRENT_VERSION=$(grep -E "__version__\s*=\s*['\"]([^'\"]+)['\"]" src/jimaku_dl/cli.py | cut -d'"' -f2)
echo "Current version: $CURRENT_VERSION"
echo "CURRENT_VERSION=$CURRENT_VERSION" >> $GITHUB_ENV
- name: Calculate new version
id: new_version
run: |
if [ -n "${{ github.event.inputs.custom_version }}" ]; then
NEW_VERSION="${{ github.event.inputs.custom_version }}"
echo "Using custom version: $NEW_VERSION"
else
BUMP_TYPE="${{ github.event.inputs.version_bump }}"
CURRENT="${{ env.CURRENT_VERSION }}"
if [ "$BUMP_TYPE" = "patch" ]; then
MAJOR=$(echo $CURRENT | cut -d. -f1)
MINOR=$(echo $CURRENT | cut -d. -f2)
PATCH=$(echo $CURRENT | cut -d. -f3)
NEW_PATCH=$((PATCH + 1))
NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
elif [ "$BUMP_TYPE" = "minor" ]; then
MAJOR=$(echo $CURRENT | cut -d. -f1)
MINOR=$(echo $CURRENT | cut -d. -f2)
NEW_MINOR=$((MINOR + 1))
NEW_VERSION="$MAJOR.$NEW_MINOR.0"
elif [ "$BUMP_TYPE" = "major" ]; then
MAJOR=$(echo $CURRENT | cut -d. -f1)
NEW_MAJOR=$((MAJOR + 1))
NEW_VERSION="$NEW_MAJOR.0.0"
else
echo "Invalid bump type: $BUMP_TYPE"
exit 1
fi
echo "Bumping $BUMP_TYPE version: $CURRENT → $NEW_VERSION"
fi
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
- name: Update version in files
run: |
# Update version in cli.py instead of __init__.py
sed -i "s/__version__ = \"${{ env.CURRENT_VERSION }}\"/__version__ = \"${{ env.NEW_VERSION }}\"/g" src/jimaku_dl/cli.py
# Still update setup.cfg if it exists
if [ -f "setup.cfg" ]; then
sed -i "s/version = ${{ env.CURRENT_VERSION }}/version = ${{ env.NEW_VERSION }}/g" setup.cfg
fi
echo "Updated version to ${{ env.NEW_VERSION }} in code files"
- name: Generate changelog
id: changelog
run: |
PREV_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -z "$PREV_TAG" ]; then
CHANGELOG=$(git log --pretty=format:"* %s (%h)" --no-merges)
else
CHANGELOG=$(git log $PREV_TAG..HEAD --pretty=format:"* %s (%h)" --no-merges)
fi
if [ -z "$CHANGELOG" ]; then
CHANGELOG="* Bug fixes and improvements"
fi
echo "CHANGELOG<<EOF" >> $GITHUB_OUTPUT
echo "$CHANGELOG" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Commit version changes
run: |
git config --local user.email "action@gitea.suda.codes"
git config --local user.name "Gitea Action"
git add src/jimaku_dl/cli.py
if [ -f "setup.cfg" ]; then
git add setup.cfg
fi
git commit -m "Bump version to ${{ env.NEW_VERSION }}"
git tag -a "v${{ env.NEW_VERSION }}" -m "Release v${{ env.NEW_VERSION }}"
git push --follow-tags
- name: Create Gitea Release
id: create_release
uses: softprops/action-gh-release@v1
with:
tag_name: "v${{ env.NEW_VERSION }}"
name: "Release v${{ env.NEW_VERSION }}"
body: |
## Changes in this release
${{ steps.changelog.outputs.CHANGELOG }}
draft: false
prerelease: false
token: ${{ secrets.ACCESS_KEY }}

59
.gitea/workflows/test.yml Normal file
View File

@ -0,0 +1,59 @@
name: Tests
on:
push:
branches: [master]
pull_request:
branches: [master]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python-version: [3.8, 3.9, "3.10"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Cache pip dependencies
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e .
pip install pytest pytest-cov pytest-mock flake8 black isort
- name: Lint with flake8
run: |
flake8 src/jimaku_dl
- name: Check formatting with black
run: |
black --check src/jimaku_dl
- name: Check imports with isort
run: |
isort --check src/jimaku_dl
- name: Test with pytest
run: |
pytest --cov=jimaku_dl --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
fail_ci_if_error: false

161
.github/workflows/create-release.yml vendored Normal file
View File

@ -0,0 +1,161 @@
name: Create Release and Publish
on:
workflow_dispatch:
inputs:
version_bump:
description: "Type of version bump"
required: true
default: "patch"
type: choice
options:
- patch
- minor
- major
custom_version:
description: "Custom version (if specified, ignores version_bump)"
required: false
skip_publish:
description: "Skip publishing to PyPI"
required: false
default: false
type: boolean
push:
tags:
- "v*.*.*"
jobs:
create-release:
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
steps:
- name: Check out code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel semver
- name: Determine current version
id: current_version
run: |
CURRENT_VERSION=$(grep -E "__version__\s*=\s*['\"]([^'\"]+)['\"]" src/jimaku_dl/cli.py | cut -d'"' -f2)
echo "Current version: $CURRENT_VERSION"
echo "CURRENT_VERSION=$CURRENT_VERSION" >> $GITHUB_ENV
- name: Calculate new version
id: new_version
run: |
if [ -n "${{ github.event.inputs.custom_version }}" ]; then
NEW_VERSION="${{ github.event.inputs.custom_version }}"
echo "Using custom version: $NEW_VERSION"
else
BUMP_TYPE="${{ github.event.inputs.version_bump }}"
CURRENT="${{ env.CURRENT_VERSION }}"
if [ "$BUMP_TYPE" = "patch" ]; then
MAJOR=$(echo $CURRENT | cut -d. -f1)
MINOR=$(echo $CURRENT | cut -d. -f2)
PATCH=$(echo $CURRENT | cut -d. -f3)
NEW_PATCH=$((PATCH + 1))
NEW_VERSION="$MAJOR.$MINOR.$NEW_PATCH"
elif [ "$BUMP_TYPE" = "minor" ]; then
MAJOR=$(echo $CURRENT | cut -d. -f1)
MINOR=$(echo $CURRENT | cut -d. -f2)
NEW_MINOR=$((MINOR + 1))
NEW_VERSION="$MAJOR.$NEW_MINOR.0"
elif [ "$BUMP_TYPE" = "major" ]; then
MAJOR=$(echo $CURRENT | cut -d. -f1)
NEW_MAJOR=$((MAJOR + 1))
NEW_VERSION="$NEW_MAJOR.0.0"
else
echo "Invalid bump type: $BUMP_TYPE"
exit 1
fi
echo "Bumping $BUMP_TYPE version: $CURRENT → $NEW_VERSION"
fi
echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV
- name: Update version in files
run: |
# Update version in cli.py instead of __init__.py
sed -i "s/__version__ = \"${{ env.CURRENT_VERSION }}\"/__version__ = \"${{ env.NEW_VERSION }}\"/g" src/jimaku_dl/cli.py
# Still update setup.cfg if it exists
if [ -f "setup.cfg" ]; then
sed -i "s/version = ${{ env.CURRENT_VERSION }}/version = ${{ env.NEW_VERSION }}/g" setup.cfg
fi
echo "Updated version to ${{ env.NEW_VERSION }} in code files"
- name: Generate changelog
id: changelog
run: |
PREV_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -z "$PREV_TAG" ]; then
CHANGELOG=$(git log --pretty=format:"* %s (%h)" --no-merges)
else
CHANGELOG=$(git log $PREV_TAG..HEAD --pretty=format:"* %s (%h)" --no-merges)
fi
if [ -z "$CHANGELOG" ]; then
CHANGELOG="* Bug fixes and improvements"
fi
echo "CHANGELOG<<EOF" >> $GITHUB_OUTPUT
echo "$CHANGELOG" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Commit version changes
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
# Update the git add command to include cli.py instead of __init__.py
git add src/jimaku_dl/cli.py
if [ -f "setup.cfg" ]; then
git add setup.cfg
fi
git commit -m "Bump version to ${{ env.NEW_VERSION }}"
git tag -a "v${{ env.NEW_VERSION }}" -m "Release v${{ env.NEW_VERSION }}"
git push --follow-tags
- name: Create GitHub Release
id: create_release
uses: softprops/action-gh-release@v1
with:
tag_name: "v${{ env.NEW_VERSION }}"
name: "Release v${{ env.NEW_VERSION }}"
body: |
## Changes in this release
${{ steps.changelog.outputs.CHANGELOG }}
draft: false
prerelease: false
token: ${{ secrets.GITHUB_TOKEN }}
- name: Build package
if: ${{ !inputs.skip_publish }}
run: |
python -m pip install --upgrade pip
pip install build
python -m build
- name: Publish package to PyPI
if: ${{ !inputs.skip_publish }}
uses: pypa/gh-action-pypi-publish@release/v1
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
skip_existing: true

63
.github/workflows/publish-pypi.yml vendored Normal file
View File

@ -0,0 +1,63 @@
name: Publish to PyPI
on:
release:
types: [published, released]
workflow_dispatch:
inputs:
skip_release_check:
description: "Skip release check (use current version in files)"
required: false
default: false
type: boolean
jobs:
deploy:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
ref: ${{ github.event.release.tag_name }}
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build twine
pip install -e .
- name: Verify version matches release tag
if: github.event_name == 'release' && !inputs.skip_release_check
run: |
TAG_VERSION=${GITHUB_REF#refs/tags/}
TAG_VERSION=${TAG_VERSION#v}
CODE_VERSION=$(grep -E "__version__\s*=\s*['\"]([^'\"]+)['\"]" src/jimaku_dl/__init__.py | cut -d'"' -f2)
echo "Tag version: $TAG_VERSION"
echo "Code version: $CODE_VERSION"
if [ "$TAG_VERSION" != "$CODE_VERSION" ]; then
echo "Error: Version mismatch between tag ($TAG_VERSION) and code ($CODE_VERSION)"
exit 1
fi
echo "Version verified: $CODE_VERSION"
- name: Build package
run: python -m build
- name: Publish package to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
skip_existing: true

59
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,59 @@
name: Tests
on:
push:
branches: [master]
pull_request:
branches: [master]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
python-version: [3.8, 3.9, "3.10"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Cache pip dependencies
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e .
pip install pytest pytest-cov pytest-mock flake8 black isort
- name: Lint with flake8
run: |
flake8 src/jimaku_dl
- name: Check formatting with black
run: |
black --check src/jimaku_dl
- name: Check imports with isort
run: |
isort --check src/jimaku_dl
- name: Test with pytest
run: |
pytest --cov=jimaku_dl --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
fail_ci_if_error: false

4
.gitignore vendored
View File

@ -3,3 +3,7 @@
dist
src/jimaku_dl.egg-info
src/jimaku_dl/__pycache__
tests/__pycache__/
.pytest_cache
.env
.coverage

142
README.md
View File

@ -1,83 +1,127 @@
# Jimaku Downloader
A Python package to download japanese subtitles for anime from Jimaku.cc
<div align="center">
A tool for downloading Japanese subtitles for anime from <a href="https://jimaku.cc" target="_blank" rel="noopener noreferrer">Jimaku</a>
</div>
<div align="center">
<p>
<video controls muted src="https://github.com/user-attachments/assets/3723866f-4e7d-4f89-8b55-17f2fb6fa6be"></video>
</p>
</div>
## Features
- Search for subtitles using AniList IDs
- Supports both individual files and directories
- Interactive subtitle selection using fzf
- Auto-detects anime from filenames with season and episode numbers
- Recursively checks parent directories for anime titles
- Optional MPV playback with downloaded subtitles
- Caches AniList IDs to reduce API calls
- Queries AniList for anime titles
- Select subtitle entries from Jimaku
- Download subtitles to a specified directory
- Launch MPV with the downloaded subtitles
- Supports both file and directory inputs
- Support for selecting/downloading multiple subtitle files
## Installation
```bash
# From PyPI
pip install jimaku-dl
You can install Jimaku Downloader using pip
```sh
pip install jimaku-dl
```
### Arch Linux
Arch Linux users can install
<a href="https://aur.archlinux.org/packages/python-jimaku-dl" target="_blank">python-jimaku-dl</a>
from the AUR
```sh
paru -S python-jimaku-dl
# or
yay -S python-jimaku-dl
# From source
git clone https://github.com/InsaneDesperado/jimaku-dl.git
cd jimaku-dl
pip install -e .
```
## Usage
### Command Line
### Command Line Interface
```bash
# Download subtitles for a video file
jimaku-dl /path/to/your/anime.S01E02.mkv
The main entry point for Jimaku Downloader is the `jimaku-dl` command. Here are some examples of how to use it:
# Download subtitles for an entire series (directory mode)
jimaku-dl /path/to/your/anime/directory/
```sh
# Download subtitles for a single video file
jimaku-dl /path/to/video.mkv
# Specify a different destination directory
jimaku-dl /path/to/your/anime.mkv --dest /path/to/subtitles/
# Download subtitles for a directory
jimaku-dl /path/to/anime/directory
# Play the video with MPV after downloading subtitles
jimaku-dl /path/to/your/anime.mkv --play
# Specify a custom destination directory
jimaku-dl /path/to/video.mkv --dest /custom/path
# Set API token via command line
jimaku-dl /path/to/your/anime.mkv --api-token YOUR_TOKEN
```
# Launch MPV with the downloaded subtitles
jimaku-dl /path/to/video.mkv --play
### Environment Variables
# Specify an AniList ID directly
jimaku-dl /path/to/video.mkv --anilist-id 123456
You can set your Jimaku API token using the `JIMAKU_API_TOKEN` environment variable:
# Set the Jimaku API token
jimaku-dl /path/to/video.mkv --token your_api_token
```bash
export JIMAKU_API_TOKEN=your_api_token
# Set the logging level
jimaku-dl /path/to/video.mkv --log-level DEBUG
```
### Python API
You can also use Jimaku Downloader as a Python library:
```python
from jimaku_downloader import JimakuDownloader
from jimaku_dl.downloader import JimakuDownloader
# Create a downloader instance
downloader = JimakuDownloader(api_token="your_api_token", log_level="INFO")
# Download subtitles
downloaded_files = downloader.download_subtitles(
media_path="/path/to/your/anime.mkv",
dest_dir="/path/to/save/subtitles/", # Optional
play=True # Optional: play with MPV after downloading
)
print(f"Downloaded {len/downloaded_files)} subtitle files")
downloaded_files = downloader.download_subtitles("/path/to/video.mkv", dest_dir="/custom/path", play=True)
print(f"Downloaded files: {downloaded_files}")
```
## Requirements
## File Naming
- Python 3.8 or higher
- `fzf` command-line utility for interactive selection
- `mpv` (optional, for playback functionality)
- A valid Jimaku.cc API token
Jimaku Downloader supports various file naming conventions to extract show title, season, and episode information. It is recommended to follow the [Trash Guides recommended naming schema](https://trash-guides.info/Sonarr/Sonarr-recommended-naming-scheme/#recommended-naming-scheme) for best results.
### Examples
- `Show Title - S01E02 - Episode Name [1080p].mkv`
- `Show.Name.S01E02.1080p.mkv`
- `Show_Name_S01E02_HEVC.mkv`
- `/path/to/Show Name/Season-1/Show Name - 02 [1080p].mkv`
## Development
To contribute to Jimaku Downloader, follow these steps:
1. Clone the repository:
```sh
git clone https://github.com/yourusername/jimaku-dl.git
cd jimaku-dl
```
2. Create a virtual environment and activate it:
```sh
python -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
```
3. Install the dependencies:
```sh
pip install -r requirements_dev.txt
```
4. Run the tests:
```sh
pytest
```
## License
GPL v3
Jimaku Downloader is licensed under the GPLv3 License. See the [LICENSE](LICENSE) file for more information.

9
pytest.ini Normal file
View File

@ -0,0 +1,9 @@
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
unit: Unit tests
integration: Integration tests
api: Tests that mock API calls

6
requirements_dev.txt Normal file
View File

@ -0,0 +1,6 @@
pytest>=7.3.1
pytest-cov>=4.1.0
pytest-mock>=3.10.0
flake8>=6.0.0
black>=23.3.0
mypy>=1.3.0

View File

@ -1,14 +1,14 @@
[metadata]
name = jimaku-dl
version = 0.1.3
author = InsaneDesperado
author_email = insane@lmaoxd.lol
version = 0.1.2
author = sudacode
author_email = suda@sudacode.com
description = Download japanese anime subtitles from Jimaku
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/InsaneDesperado/jimaku-dl
url = https://github.com/ksyasuda/jimaku-dl
project_urls =
Bug Tracker = https://github.com/InsaneDesperado/jimaku-dl/issues
Bug Tracker = https://github.com/ksyasuda/jimaku-dl/issues
classifiers =
Programming Language :: Python :: 3
Programming Language :: Python :: 3.8

View File

@ -5,7 +5,7 @@ This package provides functionality to search for, select, and download
subtitles for anime media files or directories.
"""
__version__ = "0.1.0"
__version__ = "0.1.1"
from .downloader import JimakuDownloader

View File

@ -7,6 +7,8 @@ from sys import exit as sysexit
from jimaku_dl.downloader import JimakuDownloader
__version__ = "0.1.2"
def main():
"""
@ -17,34 +19,55 @@ def main():
)
parser.add_argument("media_path", help="Path to the media file or directory")
parser.add_argument(
"-d",
"--dest",
help="Directory to save downloaded subtitles (default: same directory as video/input directory)",
)
parser.add_argument(
"--play", action="store_true", help="Launch MPV with the subtitle(s) loaded"
"-p",
"--play",
action="store_true",
help="Launch MPV with the subtitle(s) loaded",
)
parser.add_argument(
"--api-token",
"-t",
"--token",
dest="api_token",
default=environ.get("JIMAKU_API_TOKEN", ""),
help="Jimaku API token (or set JIMAKU_API_TOKEN env var)",
)
parser.add_argument(
"-l",
"--log-level",
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help="Set the logging level (default: INFO)",
)
parser.add_argument(
"-a",
"--anilist-id",
type=int,
help="Specify AniList ID directly instead of searching",
)
parser.add_argument(
"-v",
"--version",
action="version",
version=f"jimaku-dl {__version__}",
help="Show program version and exit",
)
args = parser.parse_args()
try:
# Create downloader instance
downloader = JimakuDownloader(
api_token=args.api_token, log_level=args.log_level
)
# Download subtitles
downloaded_files = downloader.download_subtitles(
media_path=args.media_path, dest_dir=args.dest, play=args.play
media_path=args.media_path,
dest_dir=args.dest,
play=args.play,
anilist_id=args.anilist_id,
)
if not downloaded_files:
@ -57,6 +80,9 @@ def main():
except ValueError as e:
print(f"Error: {str(e)}")
return 1
except KeyboardInterrupt:
print("\nOperation cancelled by user.")
return 1
except Exception as e:
print(f"Unexpected error: {str(e)}")
return 1

View File

@ -4,7 +4,7 @@ from os import environ
from os.path import abspath, basename, dirname, exists, isdir, join, normpath, splitext
from re import IGNORECASE
from re import compile as re_compile
from re import search
from re import search, sub
from subprocess import CalledProcessError
from subprocess import run as subprocess_run
from typing import Any, Dict, List, Optional, Tuple, Union
@ -21,7 +21,6 @@ class JimakuDownloader:
subtitles for anime media files or directories.
"""
# API endpoints
ANILIST_API_URL = "https://graphql.anilist.co"
JIMAKU_SEARCH_URL = "https://jimaku.cc/api/entries/search"
JIMAKU_FILES_BASE = "https://jimaku.cc/api/entries"
@ -37,10 +36,8 @@ class JimakuDownloader:
log_level : str, default="INFO"
Logging level to use (DEBUG, INFO, WARNING, ERROR, CRITICAL)
"""
# Set up logging
self.logger = self._setup_logging(log_level)
# Initialize API token
self.api_token = api_token or environ.get("JIMAKU_API_TOKEN", "")
if not self.api_token:
self.logger.warning(
@ -107,30 +104,115 @@ class JimakuDownloader:
- season (int): Season number
- episode (int): Episode number
"""
match = search(r"(.+?)[. _-]+[Ss](\d+)[Ee](\d+)", filename)
# Clean up filename first to handle parentheses and brackets
clean_filename = filename
# Try Trash Guides anime naming schema first
# Format: {Series Title} - S{season:00}E{episode:00} - {Episode Title} [...]
trash_guide_match = search(
r"(.+?)(?:\(\d{4}\))?\s*-\s*[Ss](\d+)[Ee](\d+)\s*-\s*.+",
basename(clean_filename),
)
if trash_guide_match:
title = trash_guide_match.group(1).strip()
season = int(trash_guide_match.group(2))
episode = int(trash_guide_match.group(3))
self.logger.debug(
f"Parsed using Trash Guides format: {title=}, {season=}, {episode=}"
)
return title, season, episode
# Try to extract from directory structure following Trash Guides format
# Format: /path/to/{Series Title}/Season {season}/{filename}
parts = normpath(clean_filename).split("/")
if len(parts) >= 3 and "season" in parts[-2].lower():
# Get season from the Season XX directory
season_match = search(r"season\s*(\d+)", parts[-2].lower())
if season_match:
season = int(season_match.group(1))
# The show title is likely the directory name one level up
title = parts[-3]
# Try to get episode number from filename
ep_match = search(
r"[Ss](\d+)[Ee](\d+)|[Ee](?:pisode)?\s*(\d+)|(?:^|\s|[._-])(\d+)(?:\s|$|[._-])",
parts[-1],
)
if ep_match:
# Find the first non-None group which contains the episode number
episode_groups = ep_match.groups()
episode_str = next(
(g for g in episode_groups if g is not None), "1"
)
# If we found S01E01 format, use the episode part (second group)
if ep_match.group(1) is not None and ep_match.group(2) is not None:
episode_str = ep_match.group(2)
episode = int(episode_str)
else:
episode = 1
self.logger.debug(
f"Parsed from Trash Guides directory structure: {title=}, {season=}, {episode=}"
)
return title, season, episode
# Try the standard S01E01 format
match = search(r"(.+?)[. _-]+[Ss](\d+)[Ee](\d+)", clean_filename)
if match:
title = match.group(1).replace(".", " ").strip()
title = match.group(1).replace(".", " ").strip().replace("_", " ")
season = int(match.group(2))
episode = int(match.group(3))
self.logger.debug(
f"Parsed using S01E01 format: {title=}, {season=}, {episode=}"
)
return title, season, episode
else:
self.logger.warning("Could not parse filename automatically.")
title = input(
"Could not parse media title. Please enter show title: "
).strip()
try:
season = int(
input("Enter season number (or 0 if not applicable): ").strip()
or "0"
)
episode = int(
input("Enter episode number (or 0 if not applicable): ").strip()
or "0"
)
except ValueError:
self.logger.error("Invalid input.")
raise ValueError("Invalid season or episode number")
return title, season, episode
# Try to extract from paths like "Show Name/Season-1/Episode" format
parts = normpath(filename).split("/")
if len(parts) >= 3:
# Check if the parent directory contains "Season" in the name
season_dir = parts[-2]
if "season" in season_dir.lower():
season_match = search(r"season[. _-]*(\d+)", season_dir.lower())
if season_match:
season = int(season_match.group(1))
# The show name is likely 2 directories up
title = parts[-3].replace(".", " ").strip()
# Try to find episode number in the filename
ep_match = search(
r"[Ee](?:pisode)?[. _-]*(\d+)|[. _-](\d+)[. _-]", parts[-1]
)
episode = int(
ep_match.group(1)
if ep_match and ep_match.group(1)
else ep_match.group(2) if ep_match and ep_match.group(2) else 1
)
self.logger.debug(
f"Parsed from directory structure: {title=}, {season=}, {episode=}"
)
return title, season, episode
return self._prompt_for_title_info(filename)
def _prompt_for_title_info(self, filename: str) -> Tuple[str, int, int]:
"""
Prompt the user to manually enter show title and episode info.
"""
self.logger.warning("Could not parse filename automatically.")
print(f"\nFilename: {filename}")
print("Could not automatically determine anime title and episode information.")
title = input("Please enter the anime title: ").strip()
try:
season = int(
input("Enter season number (or 0 if not applicable): ").strip() or "1"
)
episode = int(
input("Enter episode number (or 0 if not applicable): ").strip() or "1"
)
except ValueError:
self.logger.error("Invalid input.")
raise ValueError("Invalid season or episode number")
return title, season, episode
def parse_directory_name(self, dirname: str) -> Tuple[bool, str, int, int]:
"""
@ -150,15 +232,12 @@ class JimakuDownloader:
- season (int): Defaults to 1
- episode (int): Defaults to 0 (indicating all episodes)
"""
# Clean up the directory name to use as the title
title = basename(dirname.rstrip("/"))
# Skip empty titles or obviously non-anime directories
if not title or title in [".", "..", "/"]:
self.logger.debug(f"Directory name '{title}' is not usable")
return False, "", 1, 0
# Skip common system directories
common_dirs = [
"bin",
"etc",
@ -179,7 +258,6 @@ class JimakuDownloader:
title = title.replace("_", " ").replace(".", " ").strip()
# Check if the title seems usable (at least 3 characters)
if len(title) < 3:
self.logger.debug(
f"Directory name '{title}' too short, likely not a show title"
@ -188,7 +266,6 @@ class JimakuDownloader:
self.logger.debug(f"Parsed title from directory name: {title}")
# For directories, assume season 1 and episode 0 (indicating all episodes)
return True, title, 1, 0
def find_anime_title_in_path(self, path: str) -> Tuple[str, int, int]:
@ -221,17 +298,14 @@ class JimakuDownloader:
self.logger.debug(f"Found anime title '{title}' from directory: {path}")
return title, season, episode
# Try parent directory
self.logger.debug(f"No anime title in '{path}', trying parent directory")
parent_path = dirname(path)
# Check if we're stuck (parent is same as current)
if parent_path == path:
break
path = parent_path
# If we get here, we've reached root without finding a suitable title
self.logger.error(
f"Could not extract anime title from directory path: {original_path}"
)
@ -284,7 +358,7 @@ class JimakuDownloader:
except Exception as e:
self.logger.warning(f"Could not save AniList cache file: {e}")
def query_anilist(self, title: str) -> int:
def query_anilist(self, title: str, season: Optional[int] = None) -> int:
"""
Query AniList's GraphQL API for the given title and return its media ID.
@ -292,6 +366,8 @@ class JimakuDownloader:
----------
title : str
The anime title to search for
season : int, optional
The season number to search for
Returns
-------
@ -312,28 +388,64 @@ class JimakuDownloader:
english
native
}
synonyms
}
}
"""
variables = {"search": title}
# Clean up the title to remove special characters and extra spaces
cleaned_title = sub(r"[^\w\s]", "", title).strip()
# Append season to the title if season is greater than 1
if season and season > 1:
cleaned_title += f" - Season {season}"
variables = {
"search": cleaned_title
}
try:
self.logger.debug(f"Sending AniList query for title: {title}")
self.logger.debug("Querying AniList API for title: %s", title)
self.logger.debug(f"Query variables: {variables}")
response = requests_post(
self.ANILIST_API_URL, json={"query": query, "variables": variables}
)
response.raise_for_status()
data = response.json()
self.logger.debug(f"AniList response: {data}")
media = data.get("data", {}).get("Media")
if media:
return media.get("id")
else:
self.logger.error("AniList: No media found for title.")
raise ValueError(f"No media found on AniList for title: {title}")
anilist_id = media.get("id")
self.logger.info(f"Found AniList ID: {anilist_id}")
return anilist_id
# If all automatic methods fail, raise ValueError
self.logger.error(
f"AniList search failed for title: {title}, season: {season}"
)
raise ValueError(f"Could not find anime on AniList for title: {title}")
except Exception as e:
self.logger.error(f"Error querying AniList: {e}")
raise ValueError(f"Error querying AniList API: {str(e)}")
def _prompt_for_anilist_id(self, title: str) -> int:
"""
Prompt the user to manually enter an AniList ID.
"""
print(f"\nPlease find the AniList ID for: {title}")
print("Visit https://anilist.co and search for your anime.")
print(
"The ID is the number in the URL, e.g., https://anilist.co/anime/12345 -> ID is 12345"
)
while True:
try:
anilist_id = int(input("Enter AniList ID: ").strip())
return anilist_id
except ValueError:
print("Please enter a valid number.")
def query_jimaku_entries(self, anilist_id: int) -> List[Dict[str, Any]]:
"""
Query the Jimaku API to list available subtitle entries.
@ -355,7 +467,8 @@ class JimakuDownloader:
"""
if not self.api_token:
raise ValueError(
"API token is required. Set it in the constructor or JIMAKU_API_TOKEN env var."
"API token is required for downloading subtitles from Jimaku. "
"Set it in the constructor or JIMAKU_API_TOKEN env var."
)
params = {"anilist_id": anilist_id}
@ -403,7 +516,8 @@ class JimakuDownloader:
"""
if not self.api_token:
raise ValueError(
"API token is required. Set it in the constructor or JIMAKU_API_TOKEN env var."
"API token is required for downloading subtitles from Jimaku. "
"Set it in the constructor or JIMAKU_API_TOKEN env var."
)
url = f"{self.JIMAKU_FILES_BASE}/{entry_id}/files"
@ -445,68 +559,64 @@ class JimakuDownloader:
Filtered list of file info dictionaries matching the target episode,
or all files if no matches are found
"""
filtered_files = []
# More flexible episode pattern that can detect various formats:
# - E01, e01, Ep01, EP01, episode01
# - Just the number: 01, 1
# - With separators: - 01, _01, .01
# Using word boundaries to avoid matching random numbers
specific_matches = []
episode_patterns = [
# Standard episode markers
re_compile(r"[Ee](?:p(?:isode)?)?[ ._-]*(\d+)", IGNORECASE),
# Just the number with word boundary or separator before it
re_compile(r"(?:^|\s|[._-])(\d+)(?:\s|$|[._-])", IGNORECASE),
# Number with hash
re_compile(r"#(\d+)", IGNORECASE),
]
# Check for keywords that indicate a file covers all episodes
all_episodes_keywords = ["all", "batch", "complete", "season", "full"]
batch_files = []
has_specific_match = False
# First pass: find exact episode matches
for file_info in files:
filename = file_info.get("name", "").lower()
matched = False
# Try each pattern to find episode number
# Try to match specific episode numbers
for pattern in episode_patterns:
matches = pattern.findall(filename)
for match in matches:
try:
file_episode = int(match)
if file_episode == target_episode:
filtered_files.append(file_info)
specific_matches.append(file_info)
self.logger.debug(
f"Matched episode {target_episode} in: {filename}"
)
matched = True
has_specific_match = True
break
except (ValueError, TypeError):
continue
if matched:
break
# If we didn't find a match but it might be a batch file
# Identify batch files
if not matched:
# Check if it seems to be a batch file that would include our episode
might_include_episode = any(
keyword in filename for keyword in all_episodes_keywords
)
if might_include_episode:
self.logger.debug(
f"Might include episode {target_episode} (batch): {filename}"
)
filtered_files.append(file_info)
self.logger.debug(f"Potential batch file: {filename}")
batch_files.append(file_info)
# Always include batch files, but sort them to the end
filtered_files = specific_matches + batch_files
if filtered_files:
total_specific = len(specific_matches)
total_batch = len(batch_files)
self.logger.info(
f"Found {len(filtered_files)} files matching episode {target_episode}"
f"Found {len(filtered_files)} files matching episode {target_episode} "
f"({total_specific} specific matches, {total_batch} batch files)"
)
return filtered_files
else:
# If no matches found, return all files to avoid empty selection
self.logger.warning(
f"No files specifically matched episode {target_episode}, showing all options"
f"No files matched episode {target_episode}, showing all options"
)
return files
@ -593,7 +703,11 @@ class JimakuDownloader:
raise ValueError(f"Error downloading file: {str(e)}")
def download_subtitles(
self, media_path: str, dest_dir: Optional[str] = None, play: bool = False
self,
media_path: str,
dest_dir: Optional[str] = None,
play: bool = False,
anilist_id: Optional[int] = None,
) -> List[str]:
"""
Download subtitles for the given media path.
@ -608,6 +722,8 @@ class JimakuDownloader:
Directory to save downloaded subtitles (default: same directory as media)
play : bool, default=False
Whether to launch MPV with the subtitles after download
anilist_id : int, optional
AniList ID to use directly instead of searching
Returns
-------
@ -624,13 +740,11 @@ class JimakuDownloader:
self.logger.info("Starting subtitle search and download process")
# Check if input is a file or directory
is_directory = self.is_directory_input(media_path)
self.logger.info(
f"Processing {'directory' if is_directory else 'file'}: {media_path}"
)
# Set destination directory
if dest_dir:
dest_dir = dest_dir
else:
@ -641,11 +755,10 @@ class JimakuDownloader:
self.logger.debug(f"Destination directory: {dest_dir}")
# Parse media information based on input type
if is_directory:
title, season, episode = self.find_anime_title_in_path(media_path)
media_dir = media_path
media_file = None # No specific file for directory input
media_file = None
self.logger.debug(
f"Found anime title '{title}' but will save subtitles to: {dest_dir}"
)
@ -659,21 +772,36 @@ class JimakuDownloader:
f"Identified show: {title}, Season: {season}, Episode: {episode}"
)
# Get AniList ID (either from cache or by querying)
anilist_id = self.load_cached_anilist_id(media_dir)
if anilist_id is None:
anilist_id = self.load_cached_anilist_id(media_dir)
if not anilist_id:
self.logger.info("Querying AniList for media ID...")
anilist_id = self.query_anilist(title)
anilist_id = self.query_anilist(title, season)
self.logger.info(f"AniList ID for '{title}' is {anilist_id}")
self.save_anilist_id(media_dir, anilist_id)
else:
self.logger.info(f"Using cached AniList ID: {anilist_id}")
self.logger.info(
f"Using {'provided' if anilist_id else 'cached'} AniList ID: {anilist_id}"
)
# Now check for API token before making Jimaku API calls
if not self.api_token:
self.logger.error(
"Jimaku API token is required to download subtitles. "
"Please set it with --token or the JIMAKU_API_TOKEN environment variable."
)
raise ValueError(
"Jimaku API token is required to download subtitles. "
"Please set it with --token or the JIMAKU_API_TOKEN environment variable."
)
# Query Jimaku for available subtitle entries
self.logger.info("Querying Jimaku for subtitle entries...")
entries = self.query_jimaku_entries(anilist_id)
# Present entries in fzf for selection
if not entries:
raise ValueError("No subtitle entries found for AniList ID")
entry_options = []
entry_mapping = {}
for i, entry in enumerate(entries, start=1):
@ -681,13 +809,10 @@ class JimakuDownloader:
entry_options.append(opt)
entry_mapping[opt] = entry
# Sort entry options alphabetically
entry_options.sort()
self.logger.info("Select a subtitle entry using fzf:")
selected_entry_option = self.fzf_menu(
entry_options, multi=False
) # Always single selection for entries
selected_entry_option = self.fzf_menu(entry_options, multi=False)
if not selected_entry_option or selected_entry_option not in entry_mapping:
raise ValueError("No valid entry selected")
@ -696,16 +821,13 @@ class JimakuDownloader:
if not entry_id:
raise ValueError("Selected entry does not have a valid ID")
# Retrieve the files for the selected entry
self.logger.info(f"Retrieving files for entry ID: {entry_id}")
files = self.get_entry_files(entry_id)
# For file input: filter files by episode
if not is_directory and episode > 0:
self.logger.info(f"Filtering subtitle files for episode {episode}")
files = self.filter_files_by_episode(files, episode)
# Present available subtitle files for selection
file_options = []
file_mapping = {}
for i, file_info in enumerate(files, start=1):
@ -713,28 +835,22 @@ class JimakuDownloader:
file_options.append(display)
file_mapping[display] = file_info
# Sort the file options alphabetically for better readability
file_options.sort()
# Use multi-select mode only for directory input
self.logger.info(
f"Select {'one or more' if is_directory else 'one'} subtitle file(s):"
)
selected_files = self.fzf_menu(file_options, multi=is_directory)
# Handle the different return types based on multi or single selection
if is_directory: # multi-select mode
if is_directory:
if not selected_files:
raise ValueError("No subtitle files selected")
selected_files_list = selected_files # already a list
else: # single-select mode
selected_files_list = selected_files
else:
if not selected_files:
raise ValueError("No subtitle file selected")
selected_files_list = [
selected_files
] # convert to list for consistent processing
selected_files_list = [selected_files]
# Download each selected subtitle file
downloaded_files = []
for opt in selected_files_list:
file_info = file_mapping.get(opt)
@ -749,11 +865,9 @@ class JimakuDownloader:
)
continue
# Use provided filename if available; otherwise, default to base video name + suffix.
filename = file_info.get("name")
if not filename:
if is_directory:
# For directory input, use the file's own name or ID
filename = f"{file_info.get('name', 'subtitle.srt')}"
dest_path = join(dest_dir, filename)
@ -762,7 +876,6 @@ class JimakuDownloader:
downloaded_files.append(dest_path)
self.logger.info(f"Subtitle saved to: {dest_path}")
# Optionally, launch MPV with the video file and the downloaded subtitles
if play and not is_directory:
self.logger.info("Launching MPV with the subtitle files...")
mpv_cmd = ["mpv", media_file]

50
tests/README.md Normal file
View File

@ -0,0 +1,50 @@
# Jimaku-DL Tests
This directory contains tests for the jimaku-dl package using pytest.
## Running Tests
To run all tests:
```bash
pytest
```
To run with verbose output:
```bash
pytest -v
```
To run a specific test file:
```bash
pytest tests/test_downloader.py
```
To run a specific test:
```bash
pytest tests/test_downloader.py::TestJimakuDownloader::test_init
```
## Test Coverage
To generate a test coverage report:
```bash
pytest --cov=jimaku_dl
```
For an HTML coverage report:
```bash
pytest --cov=jimaku_dl --cov-report=html
```
## Adding Tests
1. Create test files with the naming convention `test_*.py`
2. Create test classes with the naming convention `Test*`
3. Create test methods with the naming convention `test_*`
4. Use the fixtures defined in `conftest.py` for common functionality

1
tests/__init__.py Normal file
View File

@ -0,0 +1 @@
"""Test package for jimaku-dl."""

147
tests/conftest.py Normal file
View File

@ -0,0 +1,147 @@
"""Global pytest fixtures for jimaku-dl tests."""
import os
import sys
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
# Add the src directory to the Python path
project_root = Path(__file__).parent.parent
src_path = project_root / "src"
sys.path.insert(0, str(src_path))
@pytest.fixture
def temp_dir():
"""Create a temporary directory for test files."""
with tempfile.TemporaryDirectory() as tmpdirname:
yield tmpdirname
@pytest.fixture
def mock_anilist_response():
"""Mock response from AniList API."""
return {
"data": {
"Media": {
"id": 123456,
"title": {
"romaji": "Test Anime",
"english": "Test Anime English",
"native": "テストアニメ",
},
"synonyms": ["Test Show"],
}
}
}
@pytest.fixture
def mock_jimaku_entries_response():
"""Mock response from Jimaku entries endpoint."""
return [
{
"id": 1,
"english_name": "Test Anime",
"japanese_name": "テストアニメ",
"anilist_id": 123456,
}
]
@pytest.fixture
def mock_jimaku_files_response():
"""Mock response from Jimaku files endpoint."""
return [
{
"id": 101,
"name": "Test Anime - 01.srt",
"url": "https://jimaku.cc/api/files/101",
},
{
"id": 102,
"name": "Test Anime - 02.srt",
"url": "https://jimaku.cc/api/files/102",
},
]
@pytest.fixture
def mock_requests(
monkeypatch,
mock_anilist_response,
mock_jimaku_entries_response,
mock_jimaku_files_response,
):
"""Mock requests module for API calls."""
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_response.json = MagicMock()
def mock_requests_post(url, **kwargs):
if "anilist.co" in url:
mock_response.json.return_value = mock_anilist_response
return mock_response
def mock_requests_get(url, **kwargs):
if "entries/search" in url:
mock_response.json.return_value = mock_jimaku_entries_response
elif "entries/" in url and "/files" in url:
mock_response.json.return_value = mock_jimaku_files_response
return mock_response
# Patch both the direct imports used in downloader.py and the regular requests module
monkeypatch.setattr("requests.post", mock_requests_post)
monkeypatch.setattr("requests.get", mock_requests_get)
monkeypatch.setattr("jimaku_dl.downloader.requests_post", mock_requests_post)
monkeypatch.setattr("jimaku_dl.downloader.requests_get", mock_requests_get)
return {
"post": mock_requests_post,
"get": mock_requests_get,
"response": mock_response,
}
@pytest.fixture
def mock_subprocess(monkeypatch):
"""Mock subprocess module for fzf and mpv calls."""
mock_run = MagicMock()
mock_result = MagicMock()
mock_result.stdout = "1. Test Selection"
mock_run.return_value = mock_result
monkeypatch.setattr("subprocess.run", mock_run)
return mock_run
@pytest.fixture
def sample_video_file(temp_dir):
"""Create a sample video file."""
file_path = os.path.join(temp_dir, "Test Anime S01E01 [1080p].mkv")
with open(file_path, "wb") as f:
f.write(b"dummy video content")
return file_path
@pytest.fixture
def sample_anime_directory(temp_dir):
"""Create a sample directory structure for anime."""
# Main directory
anime_dir = os.path.join(temp_dir, "Test Anime")
os.makedirs(anime_dir)
# Season subdirectory
season_dir = os.path.join(anime_dir, "Season-1")
os.makedirs(season_dir)
# Episode files
for i in range(1, 3):
file_path = os.path.join(season_dir, f"Test Anime S01E0{i} [1080p].mkv")
with open(file_path, "wb") as f:
f.write(b"dummy video content")
return anime_dir

5
tests/coverage.sh Executable file
View File

@ -0,0 +1,5 @@
#!/usr/bin/env bash
coverage run -m pytest
coverage html
coverage report -m

2
tests/fixtures/__init__.py vendored Normal file
View File

@ -0,0 +1,2 @@
"""Test fixtures package."""
# This file can be empty, it's just to make the directory a proper package

318
tests/test_cli.py Normal file
View File

@ -0,0 +1,318 @@
"""Tests for the command line interface module."""
import sys
from unittest.mock import MagicMock, patch
import pytest
from jimaku_dl.cli import __version__, main
class TestCli:
"""Tests for the command line interface."""
def test_main_success(self, monkeypatch):
"""Test successful execution of the CLI main function."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/path/to/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch("sys.argv", ["jimaku-dl", "/path/to/video.mkv"]):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
result = main()
assert result == 0
mock_downloader.assert_called_once_with(
api_token="test_token", log_level="INFO"
)
mock_downloader.return_value.download_subtitles.assert_called_once_with(
media_path="/path/to/video.mkv",
dest_dir=None,
play=False,
anilist_id=None,
)
def test_main_error(self, monkeypatch):
"""Test CLI error handling."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.side_effect = ValueError(
"Test error"
)
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch("sys.argv", ["jimaku-dl", "/path/to/video.mkv"]):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
with patch("builtins.print") as mock_print:
result = main()
assert result == 1
mock_print.assert_called_with("Error: Test error")
def test_main_unexpected_error(self, monkeypatch):
"""Test CLI handling of unexpected errors."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.side_effect = Exception(
"Unexpected error"
)
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch("sys.argv", ["jimaku-dl", "/path/to/video.mkv"]):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
with patch("builtins.print") as mock_print:
result = main()
assert result == 1
mock_print.assert_called_with("Unexpected error: Unexpected error")
def test_anilist_id_arg(self, monkeypatch):
"""Test CLI with anilist_id argument."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/path/to/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch(
"sys.argv", ["jimaku-dl", "/path/to/video.mkv", "--anilist-id", "123456"]
):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = 123456
result = main()
assert result == 0
mock_downloader.return_value.download_subtitles.assert_called_once_with(
media_path="/path/to/video.mkv",
dest_dir=None,
play=False,
anilist_id=123456,
)
def test_dest_arg(self, monkeypatch):
"""Test CLI with dest argument."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/custom/path/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch(
"sys.argv", ["jimaku-dl", "/path/to/video.mkv", "--dest", "/custom/path"]
):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = "/custom/path"
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
result = main()
assert result == 0
mock_downloader.return_value.download_subtitles.assert_called_once_with(
media_path="/path/to/video.mkv",
dest_dir="/custom/path",
play=False,
anilist_id=None,
)
def test_play_arg(self, monkeypatch):
"""Test CLI with play argument."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/path/to/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch("sys.argv", ["jimaku-dl", "/path/to/video.mkv", "--play"]):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = True
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
result = main()
assert result == 0
mock_downloader.return_value.download_subtitles.assert_called_once_with(
media_path="/path/to/video.mkv",
dest_dir=None,
play=True,
anilist_id=None,
)
def test_token_arg(self, monkeypatch):
"""Test CLI with token argument."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/path/to/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch(
"sys.argv", ["jimaku-dl", "/path/to/video.mkv", "--token", "custom_token"]
):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "custom_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
result = main()
assert result == 0
mock_downloader.assert_called_once_with(
api_token="custom_token", log_level="INFO"
)
def test_log_level_arg(self, monkeypatch):
"""Test CLI with log_level argument."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/path/to/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch(
"sys.argv", ["jimaku-dl", "/path/to/video.mkv", "--log-level", "DEBUG"]
):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "DEBUG"
mock_args.return_value.anilist_id = None
result = main()
assert result == 0
mock_downloader.assert_called_once_with(
api_token="test_token", log_level="DEBUG"
)
def test_version_arg(self, capsys, monkeypatch):
"""Test CLI with version argument."""
with patch("sys.argv", ["jimaku-dl", "--version"]):
with pytest.raises(SystemExit) as excinfo:
main()
assert excinfo.value.code == 0
# Check that version is printed
captured = capsys.readouterr()
assert f"jimaku-dl {__version__}" in captured.out
def test_help_arg(self, capsys, monkeypatch):
"""Test CLI with help argument."""
with patch("sys.argv", ["jimaku-dl", "--help"]):
with pytest.raises(SystemExit) as excinfo:
main()
assert excinfo.value.code == 0
# Help text is printed to stdout by argparse
captured = capsys.readouterr()
assert "usage:" in captured.out
def test_keyboard_interrupt(self, monkeypatch):
"""Test handling of keyboard interrupt."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.side_effect = (
KeyboardInterrupt()
)
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch("sys.argv", ["jimaku-dl", "/path/to/video.mkv"]):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = None
mock_args.return_value.play = False
mock_args.return_value.api_token = "test_token"
mock_args.return_value.log_level = "INFO"
mock_args.return_value.anilist_id = None
with patch("builtins.print") as mock_print:
result = main()
assert result == 1
mock_print.assert_called_with("\nOperation cancelled by user.")
def test_short_options(self, monkeypatch):
"""Test CLI with short options instead of long options."""
mock_downloader = MagicMock()
mock_downloader.return_value.download_subtitles.return_value = [
"/path/to/subtitle.srt"
]
monkeypatch.setattr("jimaku_dl.cli.JimakuDownloader", mock_downloader)
with patch(
"sys.argv",
[
"jimaku-dl",
"/path/to/video.mkv",
"-d",
"/custom/path",
"-p",
"-t",
"short_token",
"-l",
"DEBUG",
"-a",
"789",
],
):
with patch("jimaku_dl.cli.ArgumentParser.parse_args") as mock_args:
mock_args.return_value.media_path = "/path/to/video.mkv"
mock_args.return_value.dest = "/custom/path"
mock_args.return_value.play = True
mock_args.return_value.api_token = "short_token"
mock_args.return_value.log_level = "DEBUG"
mock_args.return_value.anilist_id = 789
result = main()
assert result == 0
mock_downloader.assert_called_once_with(
api_token="short_token", log_level="DEBUG"
)
mock_downloader.return_value.download_subtitles.assert_called_once_with(
media_path="/path/to/video.mkv",
dest_dir="/custom/path",
play=True,
anilist_id=789,
)

1004
tests/test_downloader.py Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,200 @@
"""Tests specifically for the filter_files_by_episode method."""
import pytest
from jimaku_dl.downloader import JimakuDownloader
class TestFilterFilesByEpisode:
"""Test suite for filter_files_by_episode method."""
def setup_method(self):
"""Set up test method with a fresh downloader instance."""
self.downloader = JimakuDownloader(api_token="test_token")
# Setup common test files
self.all_files = [
{"id": 1, "name": "Show - 01.srt"},
{"id": 2, "name": "Show - 02.srt"},
{"id": 3, "name": "Show - 03.srt"},
{"id": 4, "name": "Show - E04.srt"},
{"id": 5, "name": "Show Episode 05.srt"},
{"id": 6, "name": "Show #06.srt"},
{"id": 7, "name": "Show.S01E07.srt"},
{"id": 8, "name": "Show - BATCH.srt"},
{"id": 9, "name": "Show - Complete.srt"},
{"id": 10, "name": "Show - All Episodes.srt"},
]
def test_exact_episode_matches(self):
"""Test finding exact episode matches with different filename patterns."""
# Test standard episode format
filtered = self.downloader.filter_files_by_episode(self.all_files, 1)
assert len(filtered) == 4 # 1 specific match + 3 batch files
assert filtered[0]["name"] == "Show - 01.srt" # Specific match should be first
# Test E## format
filtered = self.downloader.filter_files_by_episode(self.all_files, 4)
assert len(filtered) == 4 # 1 specific match + 3 batch files
assert filtered[0]["name"] == "Show - E04.srt" # Specific match should be first
# Test 'Episode ##' format
filtered = self.downloader.filter_files_by_episode(self.all_files, 5)
assert len(filtered) == 4 # 1 specific match + 3 batch files
assert (
filtered[0]["name"] == "Show Episode 05.srt"
) # Specific match should be first
# Test '#' format
filtered = self.downloader.filter_files_by_episode(self.all_files, 6)
assert len(filtered) == 4 # 1 specific match + 3 batch files
assert filtered[0]["name"] == "Show #06.srt" # Specific match should be first
# Test S##E## format
filtered = self.downloader.filter_files_by_episode(self.all_files, 7)
assert len(filtered) == 4 # 1 specific match + 3 batch files
assert (
filtered[0]["name"] == "Show.S01E07.srt"
) # Specific match should be first
def test_batch_files_inclusion(self):
"""Test that batch files are always included but sorted after specific matches."""
# For all episodes, batch files should be included now
filtered = self.downloader.filter_files_by_episode(self.all_files, 1)
assert len(filtered) == 4 # 1 specific + 3 batch
assert any("BATCH" in f["name"] for f in filtered)
assert any("Complete" in f["name"] for f in filtered)
assert any("All Episodes" in f["name"] for f in filtered)
# Specific match should be first, followed by batch files
assert filtered[0]["name"] == "Show - 01.srt"
assert all(
keyword in f["name"]
for f, keyword in zip(filtered[1:], ["BATCH", "Complete", "All Episodes"])
)
# Same for episode 3
filtered = self.downloader.filter_files_by_episode(self.all_files, 3)
assert len(filtered) == 4 # 1 specific + 3 batch
assert filtered[0]["name"] == "Show - 03.srt"
assert all(
keyword in " ".join([f["name"] for f in filtered[1:]])
for keyword in ["BATCH", "Complete", "All Episodes"]
)
# For high episode numbers with no match, only batch files should be returned
filtered = self.downloader.filter_files_by_episode(self.all_files, 10)
assert len(filtered) == 3
assert all(
f["name"]
in ["Show - BATCH.srt", "Show - Complete.srt", "Show - All Episodes.srt"]
for f in filtered
)
def test_no_episode_matches(self):
"""Test behavior when no episodes match."""
# For non-existent episodes, should return batch files
filtered = self.downloader.filter_files_by_episode(self.all_files, 99)
assert len(filtered) == 3
assert all(
f["name"]
in ["Show - BATCH.srt", "Show - Complete.srt", "Show - All Episodes.srt"]
for f in filtered
)
# For a list with no batch files and no matches, should return all files
no_batch_files = [
f
for f in self.all_files
if not any(
keyword in f["name"].lower()
for keyword in ["batch", "complete", "all", "season"]
)
]
filtered = self.downloader.filter_files_by_episode(no_batch_files, 99)
assert filtered == no_batch_files
def test_ordering_of_results(self):
"""Test that specific episode matches are always before batch files."""
# Create a reversed test set to ensure sorting works
reversed_files = list(reversed(self.all_files))
# Test with episode that has a specific match
filtered = self.downloader.filter_files_by_episode(reversed_files, 4)
# Verify specific match is first
assert filtered[0]["name"] == "Show - E04.srt"
# Verify batch files follow
for f in filtered[1:]:
assert any(
keyword in f["name"].lower()
for keyword in ["batch", "complete", "all episodes"]
)
def test_edge_case_episode_formats(self):
"""Test edge case episode number formats."""
# Create test files with unusual formats
edge_case_files = [
{"id": 1, "name": "Show - ep.01.srt"}, # With period
{"id": 2, "name": "Show - ep01v2.srt"}, # With version
{"id": 3, "name": "Show - e.03.srt"}, # Abbreviated with period
{"id": 4, "name": "Show - episode.04.srt"}, # Full word with period
{"id": 5, "name": "Show - 05.v2.srt"}, # Version format
{"id": 6, "name": "Show - [06].srt"}, # Bracketed number
]
# Test detection of 01 in filenames
filtered = self.downloader.filter_files_by_episode(edge_case_files, 1)
# In the current implementation, these might all be included since regex matching is imperfect
# So we just check that the correct ones are present and first
assert any(f["name"] == "Show - ep.01.srt" for f in filtered)
assert any(f["name"] == "Show - ep01v2.srt" for f in filtered)
# Test detection of episode.04
filtered = self.downloader.filter_files_by_episode(edge_case_files, 4)
assert any(f["name"] == "Show - episode.04.srt" for f in filtered)
# Test detection of [06]
filtered = self.downloader.filter_files_by_episode(edge_case_files, 6)
assert any(f["name"] == "Show - [06].srt" for f in filtered)
# Test episode that doesn't exist
filtered = self.downloader.filter_files_by_episode(edge_case_files, 99)
# Should return all files when no batch files and no matches
assert len(filtered) == len(edge_case_files)
def test_duplicate_episode_matches(self):
"""Test handling of duplicate episode matches in filenames."""
# Files with multiple episode numbers in the name
dup_files = [
{"id": 1, "name": "Show - 01 - Episode 1.srt"}, # Same number twice
{"id": 2, "name": "Show 02 - Ep02.srt"}, # Same number twice
{"id": 3, "name": "Show - 03 - 04.srt"}, # Different numbers
{"id": 4, "name": "Show - Ep05 Extra 06.srt"}, # Different numbers
]
# Should match the first number for episode 1
filtered = self.downloader.filter_files_by_episode(dup_files, 1)
assert len(filtered) == 1
assert filtered[0]["name"] == "Show - 01 - Episode 1.srt"
# Should match both formats for episode 2
filtered = self.downloader.filter_files_by_episode(dup_files, 2)
assert len(filtered) == 1
assert filtered[0]["name"] == "Show 02 - Ep02.srt"
# Should match the first number for episode 3
filtered = self.downloader.filter_files_by_episode(dup_files, 3)
assert len(filtered) == 1
assert filtered[0]["name"] == "Show - 03 - 04.srt"
# Should match the second number for episode 4
filtered = self.downloader.filter_files_by_episode(dup_files, 4)
assert len(filtered) == 1
assert filtered[0]["name"] == "Show - 03 - 04.srt"
def test_empty_file_list(self):
"""Test behavior with empty file list."""
filtered = self.downloader.filter_files_by_episode([], 1)
assert filtered == []

View File

@ -0,0 +1,126 @@
"""Tests specifically for the parse_directory_name method."""
import pytest
from jimaku_dl.downloader import JimakuDownloader
class TestParseDirectoryName:
"""Test suite for parse_directory_name method."""
def setup_method(self):
"""Set up test method with a fresh downloader instance."""
self.downloader = JimakuDownloader(api_token="test_token")
def test_basic_directory_names(self):
"""Test basic directory name parsing."""
# Standard name
success, title, season, episode = self.downloader.parse_directory_name(
"/path/to/My Anime Show"
)
assert success is True
assert title == "My Anime Show"
assert season == 1
assert episode == 0
# Name with underscores
success, title, season, episode = self.downloader.parse_directory_name(
"/path/to/My_Anime_Show"
)
assert success is True
assert title == "My Anime Show" # Underscores should be converted to spaces
assert season == 1
assert episode == 0
# Name with dots
success, title, season, episode = self.downloader.parse_directory_name(
"/path/to/My.Anime.Show"
)
assert success is True
assert title == "My Anime Show" # Dots should be converted to spaces
assert season == 1
assert episode == 0
def test_common_system_directories(self):
"""Test handling of common system directories that should be rejected."""
# Common system directories
for sys_dir in [
"bin",
"etc",
"lib",
"home",
"usr",
"var",
"tmp",
"opt",
"media",
"mnt",
]:
success, _, _, _ = self.downloader.parse_directory_name(
f"/path/to/{sys_dir}"
)
assert success is False, f"Directory '{sys_dir}' should be rejected"
# Root directory
success, _, _, _ = self.downloader.parse_directory_name("/")
assert success is False
# Current directory
success, _, _, _ = self.downloader.parse_directory_name(".")
assert success is False
# Parent directory
success, _, _, _ = self.downloader.parse_directory_name("..")
assert success is False
def test_short_directory_names(self):
"""Test handling of directory names that are too short."""
# One-character name
success, _, _, _ = self.downloader.parse_directory_name("/path/to/A")
assert success is False
# Two-character name
success, _, _, _ = self.downloader.parse_directory_name("/path/to/AB")
assert success is False
# Three-character name (should be accepted)
success, title, _, _ = self.downloader.parse_directory_name("/path/to/ABC")
assert success is True
assert title == "ABC"
def test_special_characters(self):
"""Test directories with special characters."""
# Directory with parentheses
success, title, _, _ = self.downloader.parse_directory_name(
"/path/to/My Anime (2022)"
)
assert success is True
assert title == "My Anime (2022)"
# Directory with brackets
success, title, _, _ = self.downloader.parse_directory_name(
"/path/to/My Anime [Uncensored]"
)
assert success is True
assert title == "My Anime [Uncensored]"
# Directory with other special characters
success, title, _, _ = self.downloader.parse_directory_name(
"/path/to/My Anime: The Movie - Part 2!"
)
assert success is True
assert title == "My Anime: The Movie - Part 2!"
def test_directory_with_season_info(self):
"""Test directories with season information."""
# Directory with season in name
success, title, _, _ = self.downloader.parse_directory_name(
"/path/to/Anime Season 2"
)
assert success is True
assert title == "Anime Season 2"
# Directory that only specifies season
success, title, _, _ = self.downloader.parse_directory_name("/path/to/Season 3")
assert success is True
assert title == "Season 3"

View File

@ -0,0 +1,254 @@
"""Tests specifically for the parse_filename method."""
from unittest.mock import patch
import pytest
from jimaku_dl.downloader import JimakuDownloader
class TestParseFilename:
"""Test suite for parse_filename method."""
def setup_method(self):
"""Set up test method with a fresh downloader instance."""
self.downloader = JimakuDownloader(api_token="test_token")
def test_trash_guides_format(self):
"""Test parsing filenames that follow Trash Guides naming convention."""
# Basic Trash Guides format
title, season, episode = self.downloader.parse_filename(
"Show Title - S01E02 - Episode Name [1080p]"
)
assert title == "Show Title"
assert season == 1
assert episode == 2
# With year included
title, season, episode = self.downloader.parse_filename(
"Show Title (2020) - S03E04 - Episode Name [1080p]"
)
assert title == "Show Title"
assert season == 3
assert episode == 4
# More complex example
title, season, episode = self.downloader.parse_filename(
"My Favorite Anime (2023) - S02E05 - The Big Battle [1080p][10bit][h265][Dual-Audio]"
)
assert title == "My Favorite Anime"
assert season == 2
assert episode == 5
def test_standard_formats(self):
"""Test parsing standard filename formats."""
# S01E01 format
title, season, episode = self.downloader.parse_filename(
"Show.Name.S01E02.1080p.mkv"
)
assert title == "Show Name"
assert season == 1
assert episode == 2
# Separated by dots
title, season, episode = self.downloader.parse_filename(
"Show.Name.S03E04.x264.mkv"
)
assert title == "Show Name"
assert season == 3
assert episode == 4
# Separated by underscores
title, season, episode = self.downloader.parse_filename(
"Show_Name_S05E06_HEVC.mkv"
)
assert title == "Show Name"
assert season == 5
assert episode == 6
def test_directory_structure_extraction(self):
"""Test extracting info from directory structure."""
# Standard Season-## format
title, season, episode = self.downloader.parse_filename(
"/path/to/Show Name/Season-1/Show Name - 02 [1080p].mkv"
)
assert title == "Show Name"
assert season == 1
assert episode == 2
# Season ## format
title, season, episode = self.downloader.parse_filename(
"/path/to/Show Name/Season 03/Episode 4.mkv"
)
assert title == "Show Name"
assert season == 3
assert episode == 4
# Simple number in season directory
title, season, episode = self.downloader.parse_filename(
"/path/to/My Anime/Season 2/5.mkv"
)
assert title == "My Anime"
assert season == 2
assert episode == 5
# Long pathname with complex directory structure
title, season, episode = self.downloader.parse_filename(
"/media/user/Anime/Long Anime Title With Spaces/Season-1/Long Anime Title With Spaces - 03.mkv"
)
assert title == "Long Anime Title With Spaces"
assert season == 1
assert episode == 3
def test_complex_titles(self):
"""Test parsing filenames with complex titles."""
# Since we now prompt for non-standard formats, we need to mock the input
with patch.object(self.downloader, "_prompt_for_title_info") as mock_prompt:
# Set up the return values for the mock
mock_prompt.return_value = (
"Trapped in a Dating Sim - The World of Otome Games Is Tough for Mobs",
1,
11,
)
title, season, episode = self.downloader.parse_filename(
"Trapped in a Dating Sim - The World of Otome Games Is Tough for Mobs - S01E11.mkv"
)
assert (
title
== "Trapped in a Dating Sim - The World of Otome Games Is Tough for Mobs"
)
assert season == 1
assert episode == 11
# Reset the mock for the next call
mock_prompt.reset_mock()
mock_prompt.return_value = ("Re:Zero kara Hajimeru Isekai Seikatsu", 1, 15)
# Titles with special characters and patterns
title, season, episode = self.downloader.parse_filename(
"Re:Zero kara Hajimeru Isekai Seikatsu S01E15 [1080p].mkv"
)
assert title == "Re:Zero kara Hajimeru Isekai Seikatsu"
assert season == 1
assert episode == 15
def test_fallback_title_extraction(self):
"""Test fallback to user input for non-standard formats."""
with patch.object(self.downloader, "_prompt_for_title_info") as mock_prompt:
# Set up the mock to return specific values
mock_prompt.return_value = ("My Show", 1, 5)
# With various tags
title, season, episode = self.downloader.parse_filename(
"My Show [1080p] [HEVC] [10bit] [Dual-Audio] - 05.mkv"
)
assert title == "My Show"
assert season == 1
assert episode == 5
mock_prompt.assert_called_once()
# Reset mock for next test
mock_prompt.reset_mock()
mock_prompt.return_value = ("Great Anime", 1, 3)
# With episode at the end
title, season, episode = self.downloader.parse_filename(
"Great Anime 1080p BluRay x264 - 03.mkv"
)
assert title == "Great Anime"
assert season == 1
assert episode == 3
mock_prompt.assert_called_once()
def test_unparsable_filenames(self):
"""Test handling of filenames that can't be parsed."""
with patch.object(self.downloader, "_prompt_for_title_info") as mock_prompt:
mock_prompt.return_value = ("Manual Title", 2, 3)
title, season, episode = self.downloader.parse_filename("randomstring.mkv")
assert title == "Manual Title"
assert season == 2
assert episode == 3
mock_prompt.assert_called_once_with("randomstring.mkv")
# Test with completely random string
mock_prompt.reset_mock()
mock_prompt.return_value = ("Another Title", 4, 5)
title, season, episode = self.downloader.parse_filename("abc123xyz.mkv")
assert title == "Another Title"
assert season == 4
assert episode == 5
mock_prompt.assert_called_once_with("abc123xyz.mkv")
def test_unicode_filenames(self):
"""Test parsing filenames with unicode characters."""
# Testing with both Japanese title formats
# Standard format with Japanese title - parser can handle this without prompting
title, season, episode = self.downloader.parse_filename(
"この素晴らしい世界に祝福を! S01E03 [1080p].mkv"
)
assert title == "この素晴らしい世界に祝福を!"
assert season == 1
assert episode == 3
# For complex cases that might require prompting, use the mock
with patch.object(self.downloader, "_prompt_for_title_info") as mock_prompt:
# Mock the prompt for a case where the parser likely can't determine the structure
mock_prompt.return_value = ("この素晴らしい世界に祝福を!", 2, 4)
# Non-standard format with Japanese title
title, season, episode = self.downloader.parse_filename(
"この素晴らしい世界に祝福を! #04 [BD 1080p].mkv"
)
# Either the parser handles it or falls back to prompting
# We're mainly checking that the result is correct
assert title == "この素晴らしい世界に祝福を!"
# Season might be detected as 1 from parser or 2 from mock
# Episode might be detected as 4 from parser or from mock
assert episode == 4
# We don't assert on whether mock_prompt was called since that
# depends on implementation details of the parser
def test_unusual_formats(self):
"""Test handling of unusual filename formats."""
with patch.object(self.downloader, "_prompt_for_title_info") as mock_prompt:
# Reset after each test to check if prompt was called
mock_prompt.reset_mock()
mock_prompt.return_value = ("Show Title", 2, 5)
# Double episode format
title, season, episode = self.downloader.parse_filename(
"Show.Title.S02E05E06.1080p.mkv"
)
# Should extract the first episode number
assert title == "Show Title"
assert season == 2
assert episode == 5
mock_prompt.assert_not_called()
# Episode with zero padding
mock_prompt.reset_mock()
title, season, episode = self.downloader.parse_filename(
"Show Name - S03E009 - Episode Title.mkv"
)
assert title == "Show Name"
assert season == 3
assert episode == 9
mock_prompt.assert_not_called()
# Episode with decimal point
mock_prompt.reset_mock()
mock_prompt.return_value = ("Show Name", 1, 5)
title, season, episode = self.downloader.parse_filename(
"Show Name - 5.5 - Special Episode.mkv"
)
# This will likely prompt due to unusual format
assert title == "Show Name"
assert season == 1
assert episode == 5
mock_prompt.assert_called_once()