Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| db5f5edf2d | |||
| 35a733d36f | |||
| 62b4ca5ffc | |||
| 8887f9a7cb | |||
|
|
2299cf788b | ||
|
|
9f52ea03fb | ||
| ff526e08ea | |||
| b8892b4737 | |||
| 16977d6227 | |||
| 7538ea8608 | |||
| 7da7668787 | |||
| 0f872276dd | |||
| 818e621288 | |||
| 14f12e55e7 | |||
| 7df9a84ae9 | |||
| 4162684779 |
@@ -1 +1 @@
|
|||||||
v1.5.6
|
v1.5.11
|
||||||
|
|||||||
@@ -59,9 +59,26 @@ else
|
|||||||
err "Neither podman nor docker is installed."
|
err "Neither podman nor docker is installed."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# -------------------------------------------------------------------
|
||||||
|
# Refuse to run from inside a confined snap sandbox (e.g. the VS Code
|
||||||
|
# integrated terminal). When the script is launched from such a
|
||||||
|
# sandbox, $HOME points under /home/$USER/snap/code/<rev>/ and podman
|
||||||
|
# stores its DB under that path. If a snap revision bump happens mid
|
||||||
|
# session, the next podman invocation finds a stale static-dir pointer
|
||||||
|
# and aborts with a confusing "database static dir ... does not match"
|
||||||
|
# error. Re-run the script from a regular host shell instead.
|
||||||
|
# -------------------------------------------------------------------
|
||||||
|
case "${HOME:-}" in
|
||||||
|
/home/*/snap/*)
|
||||||
|
err "Refusing to run inside a snap-sandboxed HOME (${HOME}). \
|
||||||
|
Re-run from a regular host terminal (e.g. gnome-terminal, konsole) \
|
||||||
|
so podman uses a stable storage path."
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------
|
||||||
# Pre-flight checks
|
# Pre-flight checks
|
||||||
# ---------------------------------------------------------------------------
|
# -------------------------------------------------------------------
|
||||||
echo "============================================"
|
echo "============================================"
|
||||||
echo " AniWorld — Build & Push"
|
echo " AniWorld — Build & Push"
|
||||||
echo " Engine : ${ENGINE}"
|
echo " Engine : ${ENGINE}"
|
||||||
|
|||||||
@@ -85,7 +85,20 @@ echo "Version file updated → ${VERSION_FILE}"
|
|||||||
FRONT_VERSION="${NEW_TAG#v}"
|
FRONT_VERSION="${NEW_TAG#v}"
|
||||||
FRONT_PKG="${SCRIPT_DIR}/../package.json"
|
FRONT_PKG="${SCRIPT_DIR}/../package.json"
|
||||||
if [[ -f "${FRONT_PKG}" ]]; then
|
if [[ -f "${FRONT_PKG}" ]]; then
|
||||||
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"${FRONT_VERSION}\"/" "${FRONT_PKG}"
|
# Use a python one-liner for portable, safe JSON editing. The previous
|
||||||
|
# `sed -i` used single-quoted bash strings, which prevented
|
||||||
|
# ${FRONT_VERSION} from being interpolated and silently rewrote the file
|
||||||
|
# to the literal string "${FRONT_VERSION}".
|
||||||
|
python3 - "$FRONT_PKG" "$FRONT_VERSION" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
path, new_version = sys.argv[1], sys.argv[2]
|
||||||
|
with open(path, encoding="utf-8") as fh:
|
||||||
|
data = json.load(fh)
|
||||||
|
data["version"] = new_version
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
json.dump(data, fh, indent=2)
|
||||||
|
fh.write("\n")
|
||||||
|
PY
|
||||||
echo "package.json version updated → ${FRONT_VERSION}"
|
echo "package.json version updated → ${FRONT_VERSION}"
|
||||||
else
|
else
|
||||||
echo "Warning: package.json not found, skipping package.json version sync" >&2
|
echo "Warning: package.json not found, skipping package.json version sync" >&2
|
||||||
@@ -94,13 +107,63 @@ fi
|
|||||||
# Keep root pyproject.toml in sync.
|
# Keep root pyproject.toml in sync.
|
||||||
BACKEND_PYPROJECT="${SCRIPT_DIR}/../pyproject.toml"
|
BACKEND_PYPROJECT="${SCRIPT_DIR}/../pyproject.toml"
|
||||||
if [[ -f "${BACKEND_PYPROJECT}" ]]; then
|
if [[ -f "${BACKEND_PYPROJECT}" ]]; then
|
||||||
# Update version under [project] section if present
|
# Use python instead of sed: the previous `sed -i` used double-quoted
|
||||||
if grep -q '^\[project\]' "${BACKEND_PYPROJECT}"; then
|
# patterns whose `&` and `\` characters would have to be escaped, and
|
||||||
sed -i "/^\[project\]/,/^\[/ s/^version = \".*\"/version = \"${FRONT_VERSION}\"/" "${BACKEND_PYPROJECT}"
|
# more importantly it could silently do nothing if the [project] section
|
||||||
else
|
# was missing. python reads/writes the file as a string, preserving
|
||||||
sed -i "s/^version = \".*\"/version = \"${FRONT_VERSION}\"/" "${BACKEND_PYPROJECT}"
|
# the existing format, and reports whether anything changed.
|
||||||
|
if FRONT_VERSION="$FRONT_VERSION" BACKEND_PYPROJECT="$BACKEND_PYPROJECT" python3 <<'PY'
|
||||||
|
import os, re, sys
|
||||||
|
|
||||||
|
path = os.environ["BACKEND_PYPROJECT"]
|
||||||
|
new_version = os.environ["FRONT_VERSION"]
|
||||||
|
with open(path, encoding="utf-8") as fh:
|
||||||
|
text = fh.read()
|
||||||
|
|
||||||
|
# If there is a [project] table, update only the `version = "..."` line
|
||||||
|
# inside it; otherwise update the first top-level `version = "..."` line.
|
||||||
|
project_match = re.search(r"^\[project\]\s*$", text, re.MULTILINE)
|
||||||
|
if project_match:
|
||||||
|
start = project_match.end()
|
||||||
|
end = re.search(r"^\[", text[start:], re.MULTILINE)
|
||||||
|
section_end = start + end.start() if end else len(text)
|
||||||
|
section = text[start:section_end]
|
||||||
|
new_section, n = re.subn(
|
||||||
|
r'^version = ".*"$',
|
||||||
|
f'version = "{new_version}"',
|
||||||
|
section,
|
||||||
|
count=1,
|
||||||
|
flags=re.MULTILINE,
|
||||||
|
)
|
||||||
|
if n == 0:
|
||||||
|
print(
|
||||||
|
f"Warning: no `version = ...` line found under [project] in {path}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(2)
|
||||||
|
text = text[:start] + new_section + text[section_end:]
|
||||||
|
else:
|
||||||
|
new_text, n = re.subn(
|
||||||
|
r'^version = ".*"$',
|
||||||
|
f'version = "{new_version}"',
|
||||||
|
text,
|
||||||
|
count=1,
|
||||||
|
flags=re.MULTILINE,
|
||||||
|
)
|
||||||
|
if n == 0:
|
||||||
|
print(
|
||||||
|
f"Warning: no `version = ...` line found in {path}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(2)
|
||||||
|
text = new_text
|
||||||
|
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(text)
|
||||||
|
PY
|
||||||
|
then
|
||||||
|
echo "pyproject.toml version updated → ${FRONT_VERSION}"
|
||||||
fi
|
fi
|
||||||
echo "pyproject.toml version updated → ${FRONT_VERSION}"
|
|
||||||
else
|
else
|
||||||
echo "Warning: pyproject.toml not found, skipping pyproject.toml version sync" >&2
|
echo "Warning: pyproject.toml not found, skipping pyproject.toml version sync" >&2
|
||||||
fi
|
fi
|
||||||
|
|||||||
25
Docs/API.md
25
Docs/API.md
@@ -1056,34 +1056,39 @@ Update existing NFO file with fresh TMDB data.
|
|||||||
|
|
||||||
Source: [src/server/api/nfo.py](../src/server/api/nfo.py#L243-L325)
|
Source: [src/server/api/nfo.py](../src/server/api/nfo.py#L243-L325)
|
||||||
|
|
||||||
### GET /api/nfo/{serie_id}/content
|
### GET /api/nfo/{key}/content
|
||||||
|
|
||||||
Get NFO file XML content for a series.
|
Read the raw `tvshow.nfo` XML for a series. Used by the Anime Settings
|
||||||
|
page's "View NFO XML" button to render the on-disk NFO in a `<pre>` block.
|
||||||
|
|
||||||
**Authentication:** Required
|
**Authentication:** Required
|
||||||
|
|
||||||
**Path Parameters:**
|
**Path Parameters:**
|
||||||
|
|
||||||
- `serie_id` (string): Series identifier
|
- `key` (string): Series unique key (e.g., `attack-on-titan`)
|
||||||
|
|
||||||
**Response (200 OK):**
|
**Response (200 OK):** [`NfoContentResponse`](../src/server/models/nfo.py)
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"serie_id": "one-piece",
|
"key": "attack-on-titan",
|
||||||
"serie_folder": "One Piece (1999)",
|
"folder": "Attack on Titan (2013)",
|
||||||
"content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tvshow>...</tvshow>",
|
"content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tvshow>...</tvshow>",
|
||||||
"file_size": 2048,
|
"file_size": 2048,
|
||||||
"last_modified": "2026-01-15T10:30:00"
|
"last_modified": "2026-09-04T17:42:13"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Errors:**
|
**Errors:**
|
||||||
|
|
||||||
- `401 Unauthorized` - Not authenticated
|
- `400 Bad Request` — Series has no folder configured.
|
||||||
- `404 Not Found` - Series or NFO not found
|
- `401 Unauthorized` — Not authenticated.
|
||||||
|
- `404 Not Found` — Series with the given key does not exist, or its
|
||||||
|
`tvshow.nfo` is missing on disk.
|
||||||
|
- `500 Internal Server Error` — Failed to read the NFO file from disk.
|
||||||
|
- `503 Service Unavailable` — `settings.anime_directory` is not configured.
|
||||||
|
|
||||||
Source: [src/server/api/nfo.py](../src/server/api/nfo.py#L328-L397)
|
Source: [src/server/api/nfo.py](../src/server/api/nfo.py#L411-L477)
|
||||||
|
|
||||||
### GET /api/nfo/{serie_id}/media/status
|
### GET /api/nfo/{serie_id}/media/status
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "aniworld-web",
|
"name": "aniworld-web",
|
||||||
"version": "1.5.6",
|
"version": "1.5.11",
|
||||||
"description": "Aniworld Anime Download Manager - Web Frontend",
|
"description": "Aniworld Anime Download Manager - Web Frontend",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1650,17 +1650,11 @@ async def update_anime_settings(
|
|||||||
# Lazy-import to avoid heavy deps when not used
|
# Lazy-import to avoid heavy deps when not used
|
||||||
from src.server.api.nfo import _create_or_update_nfo
|
from src.server.api.nfo import _create_or_update_nfo
|
||||||
|
|
||||||
series_data = {
|
|
||||||
"key": anime_key,
|
|
||||||
"name": db_series.name,
|
|
||||||
"folder": db_series.folder,
|
|
||||||
"tmdb_id": db_series.tmdb_id,
|
|
||||||
}
|
|
||||||
await _create_or_update_nfo(
|
await _create_or_update_nfo(
|
||||||
key=anime_key,
|
key=anime_key,
|
||||||
folder=db_series.folder,
|
folder=db_series.folder,
|
||||||
tmdb_id=db_series.tmdb_id,
|
tmdb_id=db_series.tmdb_id,
|
||||||
series_data=series_data,
|
anime_service=anime_service,
|
||||||
)
|
)
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
@@ -1727,17 +1721,11 @@ async def regenerate_anime_nfo(
|
|||||||
try:
|
try:
|
||||||
from src.server.api.nfo import _create_or_update_nfo
|
from src.server.api.nfo import _create_or_update_nfo
|
||||||
|
|
||||||
series_data = {
|
|
||||||
"key": anime_key,
|
|
||||||
"name": db_series.name,
|
|
||||||
"folder": db_series.folder,
|
|
||||||
"tmdb_id": tmdb_id,
|
|
||||||
}
|
|
||||||
repaired_tags = await _create_or_update_nfo(
|
repaired_tags = await _create_or_update_nfo(
|
||||||
key=anime_key,
|
key=anime_key,
|
||||||
folder=db_series.folder,
|
folder=db_series.folder,
|
||||||
tmdb_id=tmdb_id,
|
tmdb_id=tmdb_id,
|
||||||
series_data=series_data,
|
anime_service=anime_service,
|
||||||
)
|
)
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ Provides endpoints for NFO settings, repair, and validation for anime series.
|
|||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
from datetime import datetime
|
||||||
from typing import Any, List, Optional
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, status
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
@@ -11,6 +12,7 @@ from pydantic import BaseModel
|
|||||||
|
|
||||||
from src.config.settings import settings
|
from src.config.settings import settings
|
||||||
from src.server.models.nfo import (
|
from src.server.models.nfo import (
|
||||||
|
NfoContentResponse,
|
||||||
NfoRepairResponse,
|
NfoRepairResponse,
|
||||||
NfoSeriesSettings,
|
NfoSeriesSettings,
|
||||||
NfoSettingsResponse,
|
NfoSettingsResponse,
|
||||||
@@ -241,7 +243,6 @@ async def repair_nfo_settings(
|
|||||||
key=key,
|
key=key,
|
||||||
folder=folder,
|
folder=folder,
|
||||||
tmdb_id=tmdb_id,
|
tmdb_id=tmdb_id,
|
||||||
series_data=series_data,
|
|
||||||
anime_service=anime_service,
|
anime_service=anime_service,
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -285,7 +286,6 @@ async def _create_or_update_nfo(
|
|||||||
key: str,
|
key: str,
|
||||||
folder: str,
|
folder: str,
|
||||||
tmdb_id: int,
|
tmdb_id: int,
|
||||||
series_data: dict,
|
|
||||||
anime_service: AnimeService,
|
anime_service: AnimeService,
|
||||||
) -> List[str]:
|
) -> List[str]:
|
||||||
"""Create or update NFO file for a series.
|
"""Create or update NFO file for a series.
|
||||||
@@ -406,6 +406,74 @@ async def validate_nfo(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{key}/content", response_model=NfoContentResponse)
|
||||||
|
async def get_nfo_content(
|
||||||
|
key: str,
|
||||||
|
_auth: dict = Depends(require_auth),
|
||||||
|
anime_service: AnimeService = Depends(get_anime_service),
|
||||||
|
) -> NfoContentResponse:
|
||||||
|
"""Read and return the raw tvshow.nfo XML for a series.
|
||||||
|
|
||||||
|
Used by the Anime Settings page's "View NFO XML" button to display the
|
||||||
|
on-disk NFO contents inside a ``<pre>`` block. The XML is returned as
|
||||||
|
plain text inside a JSON wrapper so the same auth/header pipeline as the
|
||||||
|
other NFO endpoints can be reused.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key: Series unique key
|
||||||
|
_auth: Authentication dependency
|
||||||
|
anime_service: AnimeService dependency
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
NfoContentResponse with raw XML in ``content``, the on-disk path,
|
||||||
|
file size and last-modified timestamp.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
HTTPException 404: If the series or its tvshow.nfo file is not found
|
||||||
|
HTTPException 400: If the series has no folder configured
|
||||||
|
HTTPException 503: If ``settings.anime_directory`` is not configured
|
||||||
|
"""
|
||||||
|
series_data = await _get_series_data(anime_service, key)
|
||||||
|
if not series_data:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Series not found: {key}",
|
||||||
|
)
|
||||||
|
|
||||||
|
folder = series_data.get("folder", "")
|
||||||
|
if not folder:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=f"Series has no folder configured: {key}",
|
||||||
|
)
|
||||||
|
|
||||||
|
nfo_path = _get_nfo_path(folder)
|
||||||
|
if not os.path.isfile(nfo_path):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"No tvshow.nfo file found for series '{key}'",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
stat = os.stat(nfo_path)
|
||||||
|
with open(nfo_path, "r", encoding="utf-8") as f:
|
||||||
|
xml_text = f.read()
|
||||||
|
except OSError as exc:
|
||||||
|
logger.error("Failed to read NFO file %s: %s", nfo_path, exc)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
detail=f"Failed to read NFO file: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
return NfoContentResponse(
|
||||||
|
key=key,
|
||||||
|
folder=folder,
|
||||||
|
content=xml_text,
|
||||||
|
file_size=stat.st_size,
|
||||||
|
last_modified=datetime.fromtimestamp(stat.st_mtime),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/needs-repair", response_model=NfoNeedsRepairListResponse)
|
@router.get("/needs-repair", response_model=NfoNeedsRepairListResponse)
|
||||||
async def get_series_needing_repair(
|
async def get_series_needing_repair(
|
||||||
_auth: dict = Depends(require_auth),
|
_auth: dict = Depends(require_auth),
|
||||||
@@ -522,7 +590,6 @@ async def batch_repair_nfo(
|
|||||||
key=key,
|
key=key,
|
||||||
folder=folder,
|
folder=folder,
|
||||||
tmdb_id=tmdb_id,
|
tmdb_id=tmdb_id,
|
||||||
series_data=series_data,
|
|
||||||
anime_service=anime_service,
|
anime_service=anime_service,
|
||||||
)
|
)
|
||||||
results["success"] += 1
|
results["success"] += 1
|
||||||
|
|||||||
@@ -121,15 +121,35 @@ class SerieList:
|
|||||||
def contains(self, key: str) -> bool:
|
def contains(self, key: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Return True when a series identified by ``key`` already exists.
|
Return True when a series identified by ``key`` already exists.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key: The unique provider identifier for the series
|
key: The unique provider identifier for the series
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
True if the series exists in the collection
|
True if the series exists in the collection
|
||||||
"""
|
"""
|
||||||
return key in self.keyDict
|
return key in self.keyDict
|
||||||
|
|
||||||
|
def remove(self, key: str) -> bool:
|
||||||
|
"""Remove a series from the in-memory cache.
|
||||||
|
|
||||||
|
Used by the delete flow to keep the in-memory cache in sync with
|
||||||
|
the database after a row is deleted. Returns True if an entry
|
||||||
|
was present and removed, False if the key was not in the cache
|
||||||
|
(treating "already gone" as a no-op rather than an error).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key: The unique provider identifier for the series
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if a series was removed, False if it was not cached.
|
||||||
|
"""
|
||||||
|
if key in self.keyDict:
|
||||||
|
del self.keyDict[key]
|
||||||
|
logger.debug("Removed series from in-memory cache: key=%s", key)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
def GetMissingEpisode(self) -> List[AnimeSeries]:
|
def GetMissingEpisode(self) -> List[AnimeSeries]:
|
||||||
"""Return all series that still contain missing episodes."""
|
"""Return all series that still contain missing episodes."""
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -393,5 +393,29 @@ class NfoRepairResponse(BaseModel):
|
|||||||
message: str = Field(..., description="Human-readable result message")
|
message: str = Field(..., description="Human-readable result message")
|
||||||
repaired_tags: List[str] = Field(
|
repaired_tags: List[str] = Field(
|
||||||
default_factory=list,
|
default_factory=list,
|
||||||
description="Tags that were missing before repair"
|
description="Tags that were missing before repair",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class NfoContentResponse(BaseModel):
|
||||||
|
"""Response containing the raw contents of a series' tvshow.nfo.
|
||||||
|
|
||||||
|
Returned by ``GET /api/nfo/{key}/content`` so the Anime Settings page
|
||||||
|
can render the XML for the user without exposing the on-disk path to
|
||||||
|
the client (only the resolved path is included for display).
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
key: Series unique key the content was loaded for
|
||||||
|
folder: Series folder name (under ``settings.anime_directory``)
|
||||||
|
content: Raw XML text of tvshow.nfo (UTF-8)
|
||||||
|
file_size: Size of the NFO file in bytes
|
||||||
|
last_modified: ISO-8601 timestamp of last on-disk modification
|
||||||
|
"""
|
||||||
|
|
||||||
|
key: str = Field(..., description="Series unique key")
|
||||||
|
folder: str = Field(..., description="Series folder name")
|
||||||
|
content: str = Field(..., description="Raw XML content of tvshow.nfo")
|
||||||
|
file_size: int = Field(..., description="NFO file size in bytes")
|
||||||
|
last_modified: datetime = Field(
|
||||||
|
..., description="Last modification time of the NFO file"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1244,8 +1244,7 @@ class AnimeService:
|
|||||||
Returns:
|
Returns:
|
||||||
True if rename was performed, False if no rename needed or failed
|
True if rename was performed, False if no rename needed or failed
|
||||||
"""
|
"""
|
||||||
import os
|
from pathlib import Path
|
||||||
import shutil
|
|
||||||
|
|
||||||
if current_folder == target_folder:
|
if current_folder == target_folder:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -1254,8 +1253,9 @@ class AnimeService:
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
current_path = self._directory / current_folder
|
base_dir = Path(self._directory)
|
||||||
target_path = self._directory / target_folder
|
current_path = base_dir / current_folder
|
||||||
|
target_path = base_dir / target_folder
|
||||||
|
|
||||||
if not current_path.exists():
|
if not current_path.exists():
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -1265,15 +1265,54 @@ class AnimeService:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
if target_path.exists():
|
if target_path.exists():
|
||||||
logger.warning(
|
# Target already exists — merge source into target instead of
|
||||||
"Cannot rename folder for %s: target path already exists: %s",
|
# bailing. Without this, a bare folder ('Naruto') next to the
|
||||||
key,
|
# year-suffixed one ('Naruto (2019)') would orphan the bare
|
||||||
target_path
|
# folder forever, producing the "series added twice" symptom.
|
||||||
|
try:
|
||||||
|
summary = self._merge_folder_into_target(
|
||||||
|
str(current_path), str(target_path)
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(
|
||||||
|
"Failed to merge %s -> %s for %s: %s",
|
||||||
|
current_folder, target_folder, key, exc,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
logger.info(
|
||||||
|
"Merged folder %s -> %s for series %s (moved=%d skipped=%d removed_source=%s)",
|
||||||
|
current_folder, target_folder, key,
|
||||||
|
summary["moved"], summary["skipped"], summary["removed_source"],
|
||||||
)
|
)
|
||||||
return False
|
|
||||||
|
# Update in-memory cache
|
||||||
|
if key in self._app.list.keyDict:
|
||||||
|
self._app.list.keyDict[key].folder = target_folder
|
||||||
|
logger.debug(
|
||||||
|
"Updated in-memory cache folder for %s: %s",
|
||||||
|
key, target_folder
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update database if session provided
|
||||||
|
if db is not None:
|
||||||
|
from src.server.database.service import AnimeSeriesService
|
||||||
|
|
||||||
|
# Look up series by key to get database ID
|
||||||
|
series = await AnimeSeriesService.get_by_key(db, key)
|
||||||
|
if series:
|
||||||
|
await AnimeSeriesService.update(
|
||||||
|
db, series_id=series.id, folder=target_folder
|
||||||
|
)
|
||||||
|
logger.debug(
|
||||||
|
"Updated DB folder for %s: %s",
|
||||||
|
key, target_folder
|
||||||
|
)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Rename folder on disk
|
# Rename folder on disk
|
||||||
|
import shutil
|
||||||
shutil.move(str(current_path), str(target_path))
|
shutil.move(str(current_path), str(target_path))
|
||||||
logger.info(
|
logger.info(
|
||||||
"Renamed folder for %s: %s -> %s",
|
"Renamed folder for %s: %s -> %s",
|
||||||
@@ -1317,6 +1356,83 @@ class AnimeService:
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _merge_folder_into_target(source: str, target: str) -> dict:
|
||||||
|
"""Merge a source folder's contents into an existing target folder.
|
||||||
|
|
||||||
|
Walks the source tree and moves every file into the matching path
|
||||||
|
under the target. When a destination file already exists, the
|
||||||
|
source copy is removed (the target version wins; we don't keep
|
||||||
|
duplicates). When the source tree is fully consumed, the
|
||||||
|
(now-empty) source directory is removed.
|
||||||
|
|
||||||
|
Both paths must be absolute and ``target`` must already exist on
|
||||||
|
disk.
|
||||||
|
|
||||||
|
Returns a summary dict with ``moved`` (file count), ``skipped``
|
||||||
|
(file count where target already had a copy), and
|
||||||
|
``removed_source`` (bool).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
if not os.path.isdir(source):
|
||||||
|
return {"moved": 0, "skipped": 0, "removed_source": False}
|
||||||
|
if not os.path.isdir(target):
|
||||||
|
raise ValueError(f"target does not exist: {target}")
|
||||||
|
|
||||||
|
moved = 0
|
||||||
|
skipped = 0
|
||||||
|
for root, _dirs, files in os.walk(source):
|
||||||
|
rel_root = os.path.relpath(root, source)
|
||||||
|
dest_root = (
|
||||||
|
target if rel_root == "."
|
||||||
|
else os.path.join(target, rel_root)
|
||||||
|
)
|
||||||
|
os.makedirs(dest_root, exist_ok=True)
|
||||||
|
for name in files:
|
||||||
|
src_file = os.path.join(root, name)
|
||||||
|
dest_file = os.path.join(dest_root, name)
|
||||||
|
if os.path.exists(dest_file):
|
||||||
|
# Target wins — never overwrite existing content.
|
||||||
|
# Remove the orphaned source copy so cleanup below
|
||||||
|
# can rmdir it.
|
||||||
|
try:
|
||||||
|
os.remove(src_file)
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"merge: could not remove duplicate %s: %s",
|
||||||
|
src_file, exc,
|
||||||
|
)
|
||||||
|
skipped += 1
|
||||||
|
logger.warning(
|
||||||
|
"merge: skipping %s (target already has %s)",
|
||||||
|
src_file, dest_file,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
shutil.move(src_file, dest_file)
|
||||||
|
moved += 1
|
||||||
|
|
||||||
|
# Try to remove the (now empty) source tree. Walk bottom-up so
|
||||||
|
# leaf directories are removed before their parents.
|
||||||
|
removed_source = False
|
||||||
|
for root, dirs, files in os.walk(source, topdown=False):
|
||||||
|
for d in dirs:
|
||||||
|
try:
|
||||||
|
os.rmdir(os.path.join(root, d))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
os.rmdir(source)
|
||||||
|
removed_source = True
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"merge: could not remove source directory %s: %s",
|
||||||
|
source, exc,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"moved": moved, "skipped": skipped, "removed_source": removed_source}
|
||||||
|
|
||||||
async def contains_in_db(self, key: str, db) -> bool:
|
async def contains_in_db(self, key: str, db) -> bool:
|
||||||
"""
|
"""
|
||||||
Check if a series with the given key exists in the database.
|
Check if a series with the given key exists in the database.
|
||||||
@@ -1649,12 +1765,29 @@ class AnimeService:
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
DeleteSeriesResult with success status, what was deleted, errors
|
DeleteSeriesResult with success status, what was deleted, errors
|
||||||
|
|
||||||
|
Deletion order: filesystem first, database second.
|
||||||
|
|
||||||
|
This order matters: if the folder delete fails (e.g. permission
|
||||||
|
error, path outside the configured anime directory), the database
|
||||||
|
row is preserved so the user can retry the delete once the
|
||||||
|
underlying issue is resolved. If we deleted the database row
|
||||||
|
first, an orphan folder would be left on disk with no way to
|
||||||
|
clean it up through the normal delete flow.
|
||||||
|
|
||||||
|
Orphan folder recovery: when ``delete_folder=True`` is requested
|
||||||
|
for a series whose database row no longer exists, the configured
|
||||||
|
anime directory is scanned for a folder that uniquely matches
|
||||||
|
the key. This recovers the case where a previous delete with
|
||||||
|
``delete_database=True`` succeeded but ``delete_folder=True``
|
||||||
|
silently failed, leaving the folder on disk.
|
||||||
"""
|
"""
|
||||||
from src.server.database.connection import get_db_session
|
from src.server.database.connection import get_db_session
|
||||||
from src.server.database.service import AnimeSeriesService
|
from src.server.database.service import AnimeSeriesService
|
||||||
from src.server.models.anime import DeleteSeriesResult
|
from src.server.models.anime import DeleteSeriesResult
|
||||||
from src.server.utils.filesystem import is_safe_path
|
from src.server.utils.filesystem import is_safe_path
|
||||||
import os as _os
|
import os as _os
|
||||||
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -1679,13 +1812,43 @@ class AnimeService:
|
|||||||
message="At least one of delete_database or delete_folder must be True.",
|
message="At least one of delete_database or delete_folder must be True.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Single DB session for fetch + optional delete
|
# Look up the series in the DB to get its folder path
|
||||||
|
series = None
|
||||||
async with get_db_session() as db:
|
async with get_db_session() as db:
|
||||||
series = await AnimeSeriesService.get_by_key(db, key)
|
series = await AnimeSeriesService.get_by_key(db, key)
|
||||||
if not series:
|
|
||||||
logger.warning(
|
if not series:
|
||||||
"Delete series failed - not found: key=%s", key
|
logger.warning(
|
||||||
)
|
"Delete series - row not found in DB: key=%s delete_folder=%s",
|
||||||
|
key, delete_folder,
|
||||||
|
)
|
||||||
|
# Recovery path: if the user wants to delete the folder but the
|
||||||
|
# DB row is already gone (e.g. orphaned by a previous partial
|
||||||
|
# delete), scan the configured anime directory for a folder
|
||||||
|
# that uniquely matches this key and delete it.
|
||||||
|
if delete_folder:
|
||||||
|
folder_path = self._find_orphan_folder_for_key(key)
|
||||||
|
if folder_path:
|
||||||
|
logger.info(
|
||||||
|
"Orphan folder recovery: key=%s matched folder=%s",
|
||||||
|
key, folder_path,
|
||||||
|
)
|
||||||
|
result = DeleteSeriesResult(
|
||||||
|
success=True,
|
||||||
|
key=key,
|
||||||
|
name="",
|
||||||
|
folder_path=folder_path,
|
||||||
|
message="",
|
||||||
|
)
|
||||||
|
self._delete_folder_at_path(folder_path, key, result)
|
||||||
|
# No DB row to delete; build message and return
|
||||||
|
self._build_delete_message(result)
|
||||||
|
logger.info(
|
||||||
|
"Delete series completed (orphan recovery): key=%s "
|
||||||
|
"deleted_folder=%s folder_error=%s",
|
||||||
|
key, result.deleted_folder, result.folder_error,
|
||||||
|
)
|
||||||
|
return result
|
||||||
return DeleteSeriesResult(
|
return DeleteSeriesResult(
|
||||||
success=False,
|
success=False,
|
||||||
key=key,
|
key=key,
|
||||||
@@ -1694,13 +1857,33 @@ class AnimeService:
|
|||||||
deleted_from_database=False,
|
deleted_from_database=False,
|
||||||
deleted_folder=False,
|
deleted_folder=False,
|
||||||
database_error=None,
|
database_error=None,
|
||||||
folder_error=None,
|
folder_error=(
|
||||||
message=f"Series '{key}' not found.",
|
f"Series '{key}' not found in database, and no folder "
|
||||||
|
"matching this key was found in the anime directory. "
|
||||||
|
"Nothing to delete."
|
||||||
|
),
|
||||||
|
message=(
|
||||||
|
f"Series '{key}' not found. If the folder on disk is "
|
||||||
|
"still required to be removed, please specify its "
|
||||||
|
"exact name on the filesystem."
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
# No row, no folder requested — nothing to do
|
||||||
|
return DeleteSeriesResult(
|
||||||
|
success=False,
|
||||||
|
key=key,
|
||||||
|
name="",
|
||||||
|
folder_path=None,
|
||||||
|
deleted_from_database=False,
|
||||||
|
deleted_folder=False,
|
||||||
|
database_error=None,
|
||||||
|
folder_error=None,
|
||||||
|
message=f"Series '{key}' not found.",
|
||||||
|
)
|
||||||
|
|
||||||
series_id = series.id
|
series_id = series.id
|
||||||
series_name = series.name
|
series_name = series.name
|
||||||
folder_path = series.folder
|
folder_path = series.folder
|
||||||
|
|
||||||
result = DeleteSeriesResult(
|
result = DeleteSeriesResult(
|
||||||
success=True,
|
success=True,
|
||||||
@@ -1710,7 +1893,22 @@ class AnimeService:
|
|||||||
message="",
|
message="",
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- Database deletion ---
|
# --- Filesystem deletion (do FIRST so a failure preserves the DB row) ---
|
||||||
|
if delete_folder and folder_path:
|
||||||
|
self._delete_folder_at_path(folder_path, key, result)
|
||||||
|
# If folder delete was requested but failed, abort before
|
||||||
|
# removing the DB row so the user can retry.
|
||||||
|
if not result.deleted_folder and result.folder_error:
|
||||||
|
result.success = False
|
||||||
|
self._build_delete_message(result)
|
||||||
|
logger.warning(
|
||||||
|
"Delete series aborted - folder delete failed; DB row preserved: "
|
||||||
|
"key=%s folder_error=%s",
|
||||||
|
key, result.folder_error,
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
# --- Database deletion (do AFTER folder delete) ---
|
||||||
if delete_database:
|
if delete_database:
|
||||||
try:
|
try:
|
||||||
async with get_db_session() as db:
|
async with get_db_session() as db:
|
||||||
@@ -1738,6 +1936,35 @@ class AnimeService:
|
|||||||
except Exception: # pylint: disable=broad-except
|
except Exception: # pylint: disable=broad-except
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# Evict from in-memory SerieList.keyDict so the next
|
||||||
|
# GET /api/anime (which reads via SeriesApp.list.GetList())
|
||||||
|
# does not return the just-deleted series.
|
||||||
|
try:
|
||||||
|
list_obj = getattr(self._app, "list", None)
|
||||||
|
if list_obj is not None:
|
||||||
|
# Prefer the explicit remove() when available.
|
||||||
|
if hasattr(list_obj, "remove"):
|
||||||
|
removed = list_obj.remove(key)
|
||||||
|
else:
|
||||||
|
# Fallback: mutate the underlying keyDict dict
|
||||||
|
# directly (mirrors how add_to_db() writes).
|
||||||
|
key_dict = getattr(list_obj, "keyDict", None)
|
||||||
|
removed = (
|
||||||
|
key_dict is not None
|
||||||
|
and key_dict.pop(key, None) is not None
|
||||||
|
)
|
||||||
|
if removed:
|
||||||
|
logger.info(
|
||||||
|
"Evicted series from in-memory cache: key=%s",
|
||||||
|
key,
|
||||||
|
)
|
||||||
|
except Exception as exc: # pylint: disable=broad-except
|
||||||
|
logger.warning(
|
||||||
|
"Failed to evict series from in-memory cache: "
|
||||||
|
"key=%s error=%s",
|
||||||
|
key, exc,
|
||||||
|
)
|
||||||
|
|
||||||
# Broadcast deletion via WebSocket
|
# Broadcast deletion via WebSocket
|
||||||
try:
|
try:
|
||||||
await self._broadcast_series_deleted(key, series_name)
|
await self._broadcast_series_deleted(key, series_name)
|
||||||
@@ -1747,49 +1974,167 @@ class AnimeService:
|
|||||||
key, exc,
|
key, exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- Filesystem deletion ---
|
# Broadcast the broader series_list_changed event so any
|
||||||
if delete_folder and folder_path:
|
# connected client that missed the series_deleted message
|
||||||
# Resolve absolute path and validate it is within base directory
|
# (or whose local state drifted) can re-sync by re-fetching
|
||||||
abs_folder = _os.path.abspath(folder_path)
|
# /api/anime. This is the durable fix for the
|
||||||
base_dir = _os.path.abspath(self._directory)
|
# "deleted but still listed" bug.
|
||||||
|
try:
|
||||||
if not is_safe_path(base_dir, abs_folder):
|
await self._broadcast_series_list_changed(reason="deleted")
|
||||||
|
except Exception as exc:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Blocked unsafe folder delete attempt: key=%s path=%s base=%s",
|
"Failed to broadcast series_list_changed after delete: "
|
||||||
key, abs_folder, base_dir,
|
"key=%s error=%s",
|
||||||
|
key, exc,
|
||||||
)
|
)
|
||||||
result.folder_error = (
|
|
||||||
f"Path '{abs_folder}' is outside the anime directory "
|
|
||||||
f"'{base_dir}' and will not be deleted."
|
|
||||||
)
|
|
||||||
result.success = False
|
|
||||||
elif not _os.path.isdir(abs_folder):
|
|
||||||
logger.warning(
|
|
||||||
"Delete folder skipped - path does not exist: key=%s path=%s",
|
|
||||||
key, abs_folder,
|
|
||||||
)
|
|
||||||
# Not an error; folder might never have existed
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
logger.info(
|
|
||||||
"Deleting series folder: key=%s path=%s",
|
|
||||||
key, abs_folder,
|
|
||||||
)
|
|
||||||
shutil.rmtree(abs_folder)
|
|
||||||
logger.info(
|
|
||||||
"Deleted series folder: key=%s path=%s",
|
|
||||||
key, abs_folder,
|
|
||||||
)
|
|
||||||
result.deleted_folder = True
|
|
||||||
except Exception as exc:
|
|
||||||
logger.error(
|
|
||||||
"Failed to delete series folder: key=%s path=%s error=%s",
|
|
||||||
key, abs_folder, str(exc),
|
|
||||||
)
|
|
||||||
result.folder_error = str(exc)
|
|
||||||
result.success = False
|
|
||||||
|
|
||||||
# --- Build message ---
|
# --- Build message ---
|
||||||
|
self._build_delete_message(result)
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"Delete series completed: key=%s deleted_db=%s deleted_folder=%s",
|
||||||
|
key, result.deleted_from_database, result.deleted_folder,
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _delete_folder_at_path(self, folder_path, key, result):
|
||||||
|
"""Resolve ``folder_path`` against the configured anime directory
|
||||||
|
and attempt to remove it. Updates ``result`` in place.
|
||||||
|
|
||||||
|
Resolves relative paths against ``self._directory`` so the safety
|
||||||
|
check operates on the real intended target (the process's current
|
||||||
|
working directory is not used as the base; in containers CWD may
|
||||||
|
differ from the anime directory, e.g. /app vs /data).
|
||||||
|
"""
|
||||||
|
import os as _os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
# Resolve absolute path and validate it is within base directory.
|
||||||
|
#
|
||||||
|
# Important: `folder_path` stored in the database is the relative
|
||||||
|
# folder name (e.g. "Beyblade Burst (2016)"), not an absolute path.
|
||||||
|
# If we feed a relative path to os.path.abspath() it gets joined
|
||||||
|
# against the process's current working directory — which may be
|
||||||
|
# /app inside the container while the anime directory is /data,
|
||||||
|
# producing e.g. "/app/Beyblade Burst (2016)" and tripping the
|
||||||
|
# safe-path check below for what is actually a valid deletion.
|
||||||
|
# Resolve relative paths against the configured anime directory
|
||||||
|
# so the safety check operates on the real intended target.
|
||||||
|
from src.server.utils.filesystem import is_safe_path
|
||||||
|
|
||||||
|
base_dir = _os.path.abspath(self._directory)
|
||||||
|
if _os.path.isabs(folder_path):
|
||||||
|
abs_folder = _os.path.abspath(folder_path)
|
||||||
|
else:
|
||||||
|
abs_folder = _os.path.abspath(_os.path.join(base_dir, folder_path))
|
||||||
|
|
||||||
|
if not is_safe_path(base_dir, abs_folder):
|
||||||
|
logger.warning(
|
||||||
|
"Blocked unsafe folder delete attempt: key=%s path=%s base=%s",
|
||||||
|
key, abs_folder, base_dir,
|
||||||
|
)
|
||||||
|
result.folder_error = (
|
||||||
|
f"Path '{abs_folder}' is outside the anime directory "
|
||||||
|
f"'{base_dir}' and will not be deleted."
|
||||||
|
)
|
||||||
|
result.success = False
|
||||||
|
return
|
||||||
|
if not _os.path.isdir(abs_folder):
|
||||||
|
logger.warning(
|
||||||
|
"Delete folder skipped - path does not exist: key=%s path=%s",
|
||||||
|
key, abs_folder,
|
||||||
|
)
|
||||||
|
# Not an error; folder might never have existed
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
logger.info(
|
||||||
|
"Deleting series folder: key=%s path=%s",
|
||||||
|
key, abs_folder,
|
||||||
|
)
|
||||||
|
shutil.rmtree(abs_folder)
|
||||||
|
logger.info(
|
||||||
|
"Deleted series folder: key=%s path=%s",
|
||||||
|
key, abs_folder,
|
||||||
|
)
|
||||||
|
result.deleted_folder = True
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(
|
||||||
|
"Failed to delete series folder: key=%s path=%s error=%s",
|
||||||
|
key, abs_folder, str(exc),
|
||||||
|
)
|
||||||
|
result.folder_error = str(exc)
|
||||||
|
result.success = False
|
||||||
|
|
||||||
|
def _find_orphan_folder_for_key(self, key: str):
|
||||||
|
"""Locate a folder under ``self._directory`` that uniquely matches
|
||||||
|
the given series ``key``.
|
||||||
|
|
||||||
|
Used as a recovery path when the DB row is gone but the on-disk
|
||||||
|
folder still exists (orphaned by a previous partial delete).
|
||||||
|
|
||||||
|
Matching strategy: for each immediate subdirectory of the anime
|
||||||
|
directory, strip a trailing ``(YYYY)`` year suffix if present and
|
||||||
|
then compare the normalized form (lowercased, non-alphanumerics
|
||||||
|
removed, key's hyphens treated as separators) against the key.
|
||||||
|
Returns the folder name (relative to the anime directory) of the
|
||||||
|
unique match, or ``None`` if zero or multiple folders match.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The matching relative folder name, or None when no unique
|
||||||
|
match exists. Returning None is the safe default — it forces
|
||||||
|
the caller to surface an explicit error rather than risk
|
||||||
|
deleting the wrong folder.
|
||||||
|
"""
|
||||||
|
import os as _os
|
||||||
|
import re
|
||||||
|
|
||||||
|
if not self._directory or not _os.path.isdir(self._directory):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _normalize(value: str) -> str:
|
||||||
|
# Drop an optional trailing "(YYYY)" or "(YYYY)"-with-content
|
||||||
|
# suffix the user might have added for disambiguation. We only
|
||||||
|
# strip a single trailing parenthesised group to avoid eating
|
||||||
|
# legitimate parts of the title.
|
||||||
|
value = re.sub(r"\s*\([^)]*\)\s*$", "", value or "")
|
||||||
|
# Lowercase, replace hyphens/underscores with empty so they
|
||||||
|
# line up with the way the key is constructed.
|
||||||
|
lowered = value.lower().replace("-", "").replace("_", "")
|
||||||
|
# Keep only alphanumerics (which preserves CJK characters
|
||||||
|
# because \w in unicode mode includes them; using explicit
|
||||||
|
# alphanumerics is safer cross-platform).
|
||||||
|
return re.sub(r"[^0-9a-z\u00C0-\uFFFF]", "", lowered)
|
||||||
|
|
||||||
|
target = _normalize(key)
|
||||||
|
if not target:
|
||||||
|
return None
|
||||||
|
|
||||||
|
candidates = []
|
||||||
|
try:
|
||||||
|
entries = _os.listdir(self._directory)
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
for entry in entries:
|
||||||
|
full = _os.path.join(self._directory, entry)
|
||||||
|
if not _os.path.isdir(full):
|
||||||
|
continue
|
||||||
|
if _normalize(entry) == target:
|
||||||
|
candidates.append(entry)
|
||||||
|
|
||||||
|
if len(candidates) == 1:
|
||||||
|
return candidates[0]
|
||||||
|
if len(candidates) > 1:
|
||||||
|
logger.warning(
|
||||||
|
"Orphan folder recovery: ambiguous match for key=%s "
|
||||||
|
"found %d candidate folders: %s",
|
||||||
|
key, len(candidates), candidates,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _build_delete_message(result) -> None:
|
||||||
|
"""Assemble the human-readable ``result.message`` from flags/errors."""
|
||||||
parts = []
|
parts = []
|
||||||
if result.deleted_from_database and not result.database_error:
|
if result.deleted_from_database and not result.database_error:
|
||||||
parts.append("removed from database")
|
parts.append("removed from database")
|
||||||
@@ -1805,12 +2150,6 @@ class AnimeService:
|
|||||||
else:
|
else:
|
||||||
result.message = "No action taken."
|
result.message = "No action taken."
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Delete series completed: key=%s deleted_db=%s deleted_folder=%s",
|
|
||||||
key, result.deleted_from_database, result.deleted_folder,
|
|
||||||
)
|
|
||||||
return result
|
|
||||||
|
|
||||||
async def _broadcast_series_deleted(self, key: str, name: str) -> None:
|
async def _broadcast_series_deleted(self, key: str, name: str) -> None:
|
||||||
"""Broadcast series_deleted event via WebSocket."""
|
"""Broadcast series_deleted event via WebSocket."""
|
||||||
try:
|
try:
|
||||||
@@ -1828,6 +2167,28 @@ class AnimeService:
|
|||||||
key, str(exc),
|
key, str(exc),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def _broadcast_series_list_changed(self, reason: str = "updated") -> None:
|
||||||
|
"""Broadcast series_list_changed event via WebSocket.
|
||||||
|
|
||||||
|
Fires whenever the membership of the series list changes
|
||||||
|
(delete, bulk import, rescan completion, …). The front-end
|
||||||
|
can use this as a hint to re-fetch /api/anime so its local
|
||||||
|
state cannot drift from the server's in-memory cache.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
await self._websocket_service.broadcast_series_list_changed(
|
||||||
|
reason=reason,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"series_list_changed broadcast sent: reason=%s",
|
||||||
|
reason,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Failed to broadcast series_list_changed: reason=%s error=%s",
|
||||||
|
reason, str(exc),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def get_anime_service(series_app: SeriesApp) -> AnimeService:
|
def get_anime_service(series_app: SeriesApp) -> AnimeService:
|
||||||
"""Factory used for creating AnimeService with a SeriesApp instance."""
|
"""Factory used for creating AnimeService with a SeriesApp instance."""
|
||||||
|
|||||||
@@ -119,6 +119,79 @@ class FolderNamingService:
|
|||||||
|
|
||||||
return await self._execute_rename(series, folder, target_folder)
|
return await self._execute_rename(series, folder, target_folder)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _merge_folder_into_target(source: str, target: str) -> dict:
|
||||||
|
"""Merge a source folder's contents into an existing target folder.
|
||||||
|
|
||||||
|
Walks the source tree and moves every file into the matching path under
|
||||||
|
the target. When a destination file already exists, the source copy is
|
||||||
|
removed (the target version wins; we don't keep duplicates). When the
|
||||||
|
source tree is fully consumed, the (now-empty) source directory is
|
||||||
|
removed.
|
||||||
|
|
||||||
|
Both paths must be absolute and ``target`` must already exist on disk.
|
||||||
|
|
||||||
|
Returns a summary dict with ``moved`` (file count), ``skipped`` (file
|
||||||
|
count where target already had a copy), and ``removed_source`` (bool).
|
||||||
|
Caller is responsible for any DB / cache updates that depend on the
|
||||||
|
outcome.
|
||||||
|
"""
|
||||||
|
if not os.path.isdir(source):
|
||||||
|
return {"moved": 0, "skipped": 0, "removed_source": False}
|
||||||
|
if not os.path.isdir(target):
|
||||||
|
raise ValueError(f"target does not exist: {target}")
|
||||||
|
|
||||||
|
moved = 0
|
||||||
|
skipped = 0
|
||||||
|
for root, _dirs, files in os.walk(source):
|
||||||
|
rel_root = os.path.relpath(root, source)
|
||||||
|
dest_root = (
|
||||||
|
target if rel_root == "."
|
||||||
|
else os.path.join(target, rel_root)
|
||||||
|
)
|
||||||
|
os.makedirs(dest_root, exist_ok=True)
|
||||||
|
for name in files:
|
||||||
|
src_file = os.path.join(root, name)
|
||||||
|
dest_file = os.path.join(dest_root, name)
|
||||||
|
if os.path.exists(dest_file):
|
||||||
|
# Target wins — never overwrite existing content. Remove
|
||||||
|
# the orphaned source copy so cleanup below can rmdir it.
|
||||||
|
try:
|
||||||
|
os.remove(src_file)
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"merge: could not remove duplicate %s: %s",
|
||||||
|
src_file, exc,
|
||||||
|
)
|
||||||
|
skipped += 1
|
||||||
|
logger.warning(
|
||||||
|
"merge: skipping %s (target already has %s)",
|
||||||
|
src_file, dest_file,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
shutil.move(src_file, dest_file)
|
||||||
|
moved += 1
|
||||||
|
|
||||||
|
# Try to remove the (now empty) source tree. Walk bottom-up so leaf
|
||||||
|
# directories are removed before their parents.
|
||||||
|
removed_source = False
|
||||||
|
for root, dirs, files in os.walk(source, topdown=False):
|
||||||
|
for d in dirs:
|
||||||
|
try:
|
||||||
|
os.rmdir(os.path.join(root, d))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
os.rmdir(source)
|
||||||
|
removed_source = True
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"merge: could not remove source directory %s: %s",
|
||||||
|
source, exc,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {"moved": moved, "skipped": skipped, "removed_source": removed_source}
|
||||||
|
|
||||||
async def _execute_rename(self, series, old_folder: str, target_folder: str) -> FolderRenameResult:
|
async def _execute_rename(self, series, old_folder: str, target_folder: str) -> FolderRenameResult:
|
||||||
key = series.key
|
key = series.key
|
||||||
|
|
||||||
@@ -132,16 +205,72 @@ class FolderNamingService:
|
|||||||
if not os.path.isdir(old_path):
|
if not os.path.isdir(old_path):
|
||||||
return FolderRenameResult(key=key, old_folder=old_folder, new_folder=None, success=False, skipped=False, reason="source folder does not exist on disk")
|
return FolderRenameResult(key=key, old_folder=old_folder, new_folder=None, success=False, skipped=False, reason="source folder does not exist on disk")
|
||||||
|
|
||||||
|
# If the target already exists, merge source into it instead of bailing.
|
||||||
|
# A bare folder ('Naruto') sitting next to the year-suffixed one
|
||||||
|
# ('Naruto (2019)') is how we get a series "added twice". Merging
|
||||||
|
# makes the rename succeed and removes the orphan folder.
|
||||||
if os.path.isdir(target_path):
|
if os.path.isdir(target_path):
|
||||||
return FolderRenameResult(key=key, old_folder=old_folder, new_folder=None, success=False, skipped=False, reason="target folder already exists on disk")
|
try:
|
||||||
|
summary = self._merge_folder_into_target(old_path, target_path)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(
|
||||||
|
"Failed to merge %s -> %s for %s: %s",
|
||||||
|
old_folder, target_folder, key, exc,
|
||||||
|
)
|
||||||
|
return FolderRenameResult(
|
||||||
|
key=key, old_folder=old_folder, new_folder=None,
|
||||||
|
success=False, skipped=False,
|
||||||
|
reason=f"merge failed: {exc}",
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Merged folder %s -> %s for series %s (moved=%d skipped=%d removed_source=%s)",
|
||||||
|
old_folder, target_folder, key,
|
||||||
|
summary["moved"], summary["skipped"], summary["removed_source"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Update in-memory cache (best-effort)
|
||||||
|
try:
|
||||||
|
from src.server.utils.dependencies import get_series_app
|
||||||
|
series_app = get_series_app()
|
||||||
|
if key in series_app.list.keyDict:
|
||||||
|
series_app.list.keyDict[key].folder = target_folder
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Failed to update in-memory cache for %s: %s", key, exc)
|
||||||
|
|
||||||
|
# Update database
|
||||||
|
async with _get_db_session() as db:
|
||||||
|
db_series = await AnimeSeriesService.get_by_key(db, key)
|
||||||
|
if db_series:
|
||||||
|
await AnimeSeriesService.update(db, series_id=db_series.id, folder=target_folder)
|
||||||
|
logger.debug("Updated DB folder for %s to %s", key, target_folder)
|
||||||
|
|
||||||
|
# If source couldn't be removed (still had unexpected files) the
|
||||||
|
# state is worse than the original orphan, so surface that as a
|
||||||
|
# warning in the result while still reporting success.
|
||||||
|
note = None
|
||||||
|
if not summary["removed_source"]:
|
||||||
|
note = (
|
||||||
|
f"merged (moved={summary['moved']}, skipped={summary['skipped']}) "
|
||||||
|
f"but source folder could not be removed"
|
||||||
|
)
|
||||||
|
elif summary["skipped"]:
|
||||||
|
note = (
|
||||||
|
f"merged (moved={summary['moved']}, "
|
||||||
|
f"kept target copies for {summary['skipped']} file(s))"
|
||||||
|
)
|
||||||
|
return FolderRenameResult(
|
||||||
|
key=key, old_folder=old_folder, new_folder=target_folder,
|
||||||
|
success=True, skipped=False, reason=note,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Target doesn't exist — plain rename.
|
||||||
try:
|
try:
|
||||||
shutil.move(old_path, target_path)
|
shutil.move(old_path, target_path)
|
||||||
logger.info("Renamed folder %s -> %s for series %s", old_folder, target_folder, key)
|
logger.info("Renamed folder %s -> %s for series %s", old_folder, target_folder, key)
|
||||||
|
|
||||||
# Update in-memory cache
|
# Update in-memory cache
|
||||||
try:
|
try:
|
||||||
from src.server.SeriesApp import get_series_app
|
from src.server.utils.dependencies import get_series_app
|
||||||
series_app = get_series_app()
|
series_app = get_series_app()
|
||||||
if key in series_app.list.keyDict:
|
if key in series_app.list.keyDict:
|
||||||
series_app.list.keyDict[key].folder = target_folder
|
series_app.list.keyDict[key].folder = target_folder
|
||||||
|
|||||||
@@ -689,6 +689,35 @@ class WebSocketService:
|
|||||||
key, name,
|
key, name,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def broadcast_series_list_changed(
|
||||||
|
self,
|
||||||
|
reason: str = "updated",
|
||||||
|
) -> None:
|
||||||
|
"""Broadcast a series_list_changed event to all connected clients.
|
||||||
|
|
||||||
|
Fires whenever the membership of the series list changes
|
||||||
|
(delete, bulk import, rescan completion, …). Clients use this
|
||||||
|
as a hint to re-fetch /api/anime so their local state cannot
|
||||||
|
drift from the server's in-memory cache.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
reason: Short string describing why the list changed
|
||||||
|
(e.g. "deleted", "imported", "rescanned"). Forwarded
|
||||||
|
to the client for logging/debugging only.
|
||||||
|
"""
|
||||||
|
message = {
|
||||||
|
"type": "series_list_changed",
|
||||||
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||||
|
"data": {
|
||||||
|
"reason": reason,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
await self._manager.broadcast(message)
|
||||||
|
logger.info(
|
||||||
|
"Broadcast series_list_changed reason=%s",
|
||||||
|
reason,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Singleton instance for application-wide access
|
# Singleton instance for application-wide access
|
||||||
_websocket_service: Optional[WebSocketService] = None
|
_websocket_service: Optional[WebSocketService] = None
|
||||||
|
|||||||
@@ -113,32 +113,54 @@ def sanitize_folder_name(
|
|||||||
|
|
||||||
def is_safe_path(base_path: str, target_path: str) -> bool:
|
def is_safe_path(base_path: str, target_path: str) -> bool:
|
||||||
"""Check if target_path is safely within base_path.
|
"""Check if target_path is safely within base_path.
|
||||||
|
|
||||||
Prevents path traversal attacks by ensuring the target path
|
Prevents path traversal attacks by ensuring the target path
|
||||||
is actually within the base path after resolution.
|
is actually within the base path after resolution.
|
||||||
|
|
||||||
|
Note on relative paths: a relative ``target_path`` is interpreted
|
||||||
|
as relative to ``base_path``, *not* to the process's current
|
||||||
|
working directory. This mirrors how callers use this helper:
|
||||||
|
they pass a configured base directory and a folder name stored
|
||||||
|
alongside it (e.g. the series ``folder`` column in the database
|
||||||
|
holds a relative name like ``"Beyblade Burst (2016)"``, and the
|
||||||
|
anime directory is configured separately). Without this, a
|
||||||
|
relative target would be resolved against the process CWD —
|
||||||
|
which can differ from ``base_path`` (the FastAPI app runs with
|
||||||
|
CWD=/app while the anime directory is mounted at /data), and
|
||||||
|
the helper would incorrectly reject the path as outside the
|
||||||
|
base. Absolute ``target_path`` values are validated against
|
||||||
|
``base_path`` directly.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
base_path: The base directory that should contain the target
|
base_path: The base directory that should contain the target
|
||||||
target_path: The path to validate
|
target_path: The path to validate (absolute, or relative to base_path)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: True if target_path is safely within base_path
|
bool: True if target_path is safely within base_path
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
>>> is_safe_path("/anime", "/anime/Attack on Titan")
|
>>> is_safe_path("/anime", "/anime/Attack on Titan")
|
||||||
True
|
True
|
||||||
|
>>> is_safe_path("/anime", "Attack on Titan") # relative -> /anime/Attack on Titan
|
||||||
|
True
|
||||||
>>> is_safe_path("/anime", "/anime/../etc/passwd")
|
>>> is_safe_path("/anime", "/anime/../etc/passwd")
|
||||||
False
|
False
|
||||||
"""
|
"""
|
||||||
# Resolve to absolute paths
|
# Resolve base to an absolute path
|
||||||
base_resolved = os.path.abspath(base_path)
|
base_resolved = os.path.abspath(base_path)
|
||||||
target_resolved = os.path.abspath(target_path)
|
|
||||||
|
# Resolve target relative to the base (not the process CWD) when it is
|
||||||
|
# supplied as a relative path. Absolute targets are validated as-is.
|
||||||
|
if os.path.isabs(target_path):
|
||||||
|
target_resolved = os.path.abspath(target_path)
|
||||||
|
else:
|
||||||
|
target_resolved = os.path.abspath(os.path.join(base_resolved, target_path))
|
||||||
|
|
||||||
# Check that target starts with base (with trailing separator)
|
# Check that target starts with base (with trailing separator)
|
||||||
base_with_sep = base_resolved + os.sep
|
base_with_sep = base_resolved + os.sep
|
||||||
return (
|
return (
|
||||||
target_resolved == base_resolved or
|
target_resolved == base_resolved
|
||||||
target_resolved.startswith(base_with_sep)
|
or target_resolved.startswith(base_with_sep)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -98,37 +98,46 @@ AniWorld.DeleteModal = (function() {
|
|||||||
* Bind event listeners on the modal.
|
* Bind event listeners on the modal.
|
||||||
*/
|
*/
|
||||||
function bindEvents() {
|
function bindEvents() {
|
||||||
|
// Guard against missing modal
|
||||||
|
if (!modalElement) return;
|
||||||
|
|
||||||
// Cancel button
|
// Cancel button
|
||||||
document.getElementById('delete-cancel-btn').addEventListener('click', hide);
|
var cancelBtn = document.getElementById('delete-cancel-btn');
|
||||||
|
if (cancelBtn) cancelBtn.addEventListener('click', hide);
|
||||||
|
|
||||||
// Close on backdrop click
|
// Close on backdrop click
|
||||||
modalElement.querySelector('.modal-overlay').addEventListener('click', hide);
|
var overlay = modalElement.querySelector('.modal-overlay');
|
||||||
|
if (overlay) overlay.addEventListener('click', hide);
|
||||||
|
|
||||||
// Escape key to close
|
// Escape key to close
|
||||||
document.addEventListener('keydown', function(e) {
|
document.addEventListener('keydown', function(e) {
|
||||||
if (e.key === 'Escape' && !isSubmitting && !modalElement.classList.contains('hidden')) {
|
if (e.key === 'Escape' && !isSubmitting && modalElement && !modalElement.classList.contains('hidden')) {
|
||||||
hide();
|
hide();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Folder checkbox toggle — show/hide warning
|
// Folder checkbox toggle — show/hide warning
|
||||||
deleteFolderCheckbox.addEventListener('change', function() {
|
if (deleteFolderCheckbox) {
|
||||||
var warning = document.getElementById('delete-folder-warning');
|
deleteFolderCheckbox.addEventListener('change', function() {
|
||||||
if (warning) {
|
var warning = document.getElementById('delete-folder-warning');
|
||||||
warning.style.display = deleteFolderCheckbox.checked ? 'flex' : 'none';
|
if (warning) {
|
||||||
}
|
warning.style.display = deleteFolderCheckbox.checked ? 'flex' : 'none';
|
||||||
});
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Confirm input — validate and update button state
|
// Confirm input — validate and update button state
|
||||||
confirmInput.addEventListener('input', function() {
|
if (confirmInput) {
|
||||||
var value = confirmInput.value;
|
confirmInput.addEventListener('input', function() {
|
||||||
var isMatch = value === 'delete';
|
var value = confirmInput.value;
|
||||||
confirmBtn.disabled = !isMatch || isSubmitting;
|
var isMatch = value === 'delete';
|
||||||
confirmInput.classList.toggle('matched', isMatch);
|
if (confirmBtn) confirmBtn.disabled = !isMatch || isSubmitting;
|
||||||
});
|
confirmInput.classList.toggle('matched', isMatch);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Confirm button
|
// Confirm button
|
||||||
confirmBtn.addEventListener('click', handleConfirm);
|
if (confirmBtn) confirmBtn.addEventListener('click', handleConfirm);
|
||||||
|
|
||||||
// Click outside modal content to close
|
// Click outside modal content to close
|
||||||
modalElement.addEventListener('click', function(e) {
|
modalElement.addEventListener('click', function(e) {
|
||||||
@@ -145,6 +154,20 @@ AniWorld.DeleteModal = (function() {
|
|||||||
function show(key) {
|
function show(key) {
|
||||||
console.info('[DeleteModal] Opening for key:', key);
|
console.info('[DeleteModal] Opening for key:', key);
|
||||||
|
|
||||||
|
// Ensure elements are cached (in case DOM was replaced)
|
||||||
|
cacheElements();
|
||||||
|
|
||||||
|
// Guard against missing elements
|
||||||
|
if (!modalElement || !confirmInput || !confirmBtn) {
|
||||||
|
console.error('[DeleteModal] Modal elements not found in DOM. Re-injecting.');
|
||||||
|
injectModalHTML();
|
||||||
|
cacheElements();
|
||||||
|
if (!modalElement) {
|
||||||
|
console.error('[DeleteModal] Failed to create modal element.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Get series info from SeriesManager if available
|
// Get series info from SeriesManager if available
|
||||||
var seriesData = null;
|
var seriesData = null;
|
||||||
if (AniWorld.SeriesManager && AniWorld.SeriesManager.findByKey) {
|
if (AniWorld.SeriesManager && AniWorld.SeriesManager.findByKey) {
|
||||||
@@ -154,20 +177,25 @@ AniWorld.DeleteModal = (function() {
|
|||||||
currentKey = key;
|
currentKey = key;
|
||||||
currentSeriesName = seriesData ? (seriesData.name || key) : key;
|
currentSeriesName = seriesData ? (seriesData.name || key) : key;
|
||||||
|
|
||||||
// Populate modal
|
// Populate modal — guard against missing elements
|
||||||
document.getElementById('delete-modal-series-name').textContent = currentSeriesName;
|
var seriesNameEl = document.getElementById('delete-modal-series-name');
|
||||||
document.getElementById('delete-modal-series-key').textContent = 'Key: ' + key;
|
var seriesKeyEl = document.getElementById('delete-modal-series-key');
|
||||||
|
var folderWarningEl = document.getElementById('delete-folder-warning');
|
||||||
|
if (seriesNameEl) seriesNameEl.textContent = currentSeriesName;
|
||||||
|
if (seriesKeyEl) seriesKeyEl.textContent = 'Key: ' + key;
|
||||||
|
|
||||||
// Reset state
|
// Reset state
|
||||||
confirmInput.value = '';
|
confirmInput.value = '';
|
||||||
confirmInput.classList.remove('matched');
|
confirmInput.classList.remove('matched');
|
||||||
confirmBtn.disabled = true;
|
confirmBtn.disabled = true;
|
||||||
isSubmitting = false;
|
isSubmitting = false;
|
||||||
errorElement.classList.add('hidden');
|
if (errorElement) {
|
||||||
errorElement.textContent = '';
|
errorElement.classList.add('hidden');
|
||||||
deleteDbCheckbox.checked = true;
|
errorElement.textContent = '';
|
||||||
deleteFolderCheckbox.checked = false;
|
}
|
||||||
document.getElementById('delete-folder-warning').style.display = 'none';
|
if (deleteDbCheckbox) deleteDbCheckbox.checked = true;
|
||||||
|
if (deleteFolderCheckbox) deleteFolderCheckbox.checked = false;
|
||||||
|
if (folderWarningEl) folderWarningEl.style.display = 'none';
|
||||||
|
|
||||||
// Show modal
|
// Show modal
|
||||||
modalElement.classList.remove('hidden');
|
modalElement.classList.remove('hidden');
|
||||||
@@ -272,6 +300,9 @@ AniWorld.DeleteModal = (function() {
|
|||||||
var result = await response.json();
|
var result = await response.json();
|
||||||
console.info('[DeleteModal] Delete succeeded:', result);
|
console.info('[DeleteModal] Delete succeeded:', result);
|
||||||
|
|
||||||
|
// Capture key before hide() nulls currentKey
|
||||||
|
var deletedKey = currentKey;
|
||||||
|
|
||||||
// Show success message based on what was deleted
|
// Show success message based on what was deleted
|
||||||
var msgParts = [];
|
var msgParts = [];
|
||||||
if (result.deleted_from_database) msgParts.push('removed from database');
|
if (result.deleted_from_database) msgParts.push('removed from database');
|
||||||
@@ -283,11 +314,17 @@ AniWorld.DeleteModal = (function() {
|
|||||||
: 'Delete completed.';
|
: 'Delete completed.';
|
||||||
|
|
||||||
AniWorld.UI.showToast(successMsg, result.success ? 'success' : 'warning');
|
AniWorld.UI.showToast(successMsg, result.success ? 'success' : 'warning');
|
||||||
|
|
||||||
|
// Close modal and reset submission state together — isSubmitting must
|
||||||
|
// be cleared before hide(), otherwise hide() bails out (early return
|
||||||
|
// on the !isSubmitting guard) and the modal stays visible.
|
||||||
|
isSubmitting = false;
|
||||||
|
if (confirmBtn) confirmBtn.textContent = 'Delete';
|
||||||
hide();
|
hide();
|
||||||
|
|
||||||
// Remove the card from the grid directly
|
// Remove the card from the grid directly
|
||||||
if (AniWorld.SeriesManager && AniWorld.SeriesManager.removeSeries) {
|
if (AniWorld.SeriesManager && AniWorld.SeriesManager.removeSeries) {
|
||||||
AniWorld.SeriesManager.removeSeries(currentKey);
|
AniWorld.SeriesManager.removeSeries(deletedKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -584,6 +584,17 @@ AniWorld.SeriesManager = (function() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-fetch the series list from the server. Used as a durable
|
||||||
|
* backstop when receiving the broader series_list_changed WS event
|
||||||
|
* so local state cannot drift from the server's in-memory cache.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
function reloadSeries() {
|
||||||
|
console.info('[SeriesManager] Reloading series from server');
|
||||||
|
return loadSeries();
|
||||||
|
}
|
||||||
|
|
||||||
// Public API
|
// Public API
|
||||||
return {
|
return {
|
||||||
init: init,
|
init: init,
|
||||||
@@ -596,6 +607,7 @@ AniWorld.SeriesManager = (function() {
|
|||||||
updateSeriesLoadingStatus: updateSeriesLoadingStatus,
|
updateSeriesLoadingStatus: updateSeriesLoadingStatus,
|
||||||
updateSingleSeries: updateSingleSeries,
|
updateSingleSeries: updateSingleSeries,
|
||||||
updateSeriesKey: updateSeriesKey,
|
updateSeriesKey: updateSeriesKey,
|
||||||
removeSeries: removeSeries
|
removeSeries: removeSeries,
|
||||||
|
reloadSeries: reloadSeries
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -169,6 +169,17 @@ AniWorld.IndexSocketHandler = (function() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Series list membership changed (delete, bulk import, rescan, …).
|
||||||
|
// Re-fetch /api/anime so local state cannot drift from the server's
|
||||||
|
// in-memory cache. Acts as a durable backstop when the more specific
|
||||||
|
// series_deleted event does not reach the client.
|
||||||
|
socket.on(WS_EVENTS.SERIES_LIST_CHANGED, function(data) {
|
||||||
|
console.info('[SocketHandler] Series list changed:', data);
|
||||||
|
if (AniWorld.SeriesManager && AniWorld.SeriesManager.reloadSeries) {
|
||||||
|
AniWorld.SeriesManager.reloadSeries();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Download events
|
// Download events
|
||||||
socket.on(WS_EVENTS.DOWNLOAD_STARTED, function(data) {
|
socket.on(WS_EVENTS.DOWNLOAD_STARTED, function(data) {
|
||||||
isDownloading = true;
|
isDownloading = true;
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
* - loadSeries(key) : fetch settings for a series key
|
* - loadSeries(key) : fetch settings for a series key
|
||||||
* - saveSettings(opts) : PUT settings, opts.applyToNfo / opts.renameDisk
|
* - saveSettings(opts) : PUT settings, opts.applyToNfo / opts.renameDisk
|
||||||
* - regenerateNfo() : POST regenerate-nfo endpoint
|
* - regenerateNfo() : POST regenerate-nfo endpoint
|
||||||
|
* - viewNfoContent() : GET raw tvshow.nfo XML into the preview <pre>
|
||||||
* - validateField(name, value) : client-side validation, returns error string or null
|
* - validateField(name, value) : client-side validation, returns error string or null
|
||||||
* - populateForm(data) : fill the form from a payload
|
* - populateForm(data) : fill the form from a payload
|
||||||
* - showSaveSuccess(msg) : success toast
|
* - showSaveSuccess(msg) : success toast
|
||||||
@@ -632,6 +633,7 @@ AniWorld.AnimeSettingsManager = (function () {
|
|||||||
loadSeries: loadSeries,
|
loadSeries: loadSeries,
|
||||||
saveSettings: saveSettings,
|
saveSettings: saveSettings,
|
||||||
regenerateNfo: regenerateNfo,
|
regenerateNfo: regenerateNfo,
|
||||||
|
viewNfoContent: viewNfoContent,
|
||||||
validateField: validateField,
|
validateField: validateField,
|
||||||
populateForm: populateForm,
|
populateForm: populateForm,
|
||||||
showSaveSuccess: showSaveSuccess,
|
showSaveSuccess: showSaveSuccess,
|
||||||
|
|||||||
@@ -105,6 +105,10 @@ AniWorld.Constants = (function() {
|
|||||||
SERIES_UPDATED: 'series_updated',
|
SERIES_UPDATED: 'series_updated',
|
||||||
SERIES_LOADING_UPDATE: 'series_loading_update',
|
SERIES_LOADING_UPDATE: 'series_loading_update',
|
||||||
SERIES_DELETED: 'series_deleted',
|
SERIES_DELETED: 'series_deleted',
|
||||||
|
// Fires when the membership of the series list changes (delete,
|
||||||
|
// bulk import, rescan completion, …). Clients should re-fetch
|
||||||
|
// /api/anime to resync with the server's in-memory cache.
|
||||||
|
SERIES_LIST_CHANGED: 'series_list_changed',
|
||||||
|
|
||||||
// Scheduled scan events
|
// Scheduled scan events
|
||||||
SCHEDULED_RESCAN_STARTED: 'scheduled_rescan_started',
|
SCHEDULED_RESCAN_STARTED: 'scheduled_rescan_started',
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ Covers the live endpoints in src/server/api/nfo.py:
|
|||||||
- GET /api/nfo/{key}/diagnostics
|
- GET /api/nfo/{key}/diagnostics
|
||||||
- POST /api/nfo/{key}/repair
|
- POST /api/nfo/{key}/repair
|
||||||
- GET /api/nfo/{key}/validate
|
- GET /api/nfo/{key}/validate
|
||||||
|
- GET /api/nfo/{key}/content (re-introduced — used by Anime Settings 'View NFO XML')
|
||||||
- GET /api/nfo/needs-repair
|
- GET /api/nfo/needs-repair
|
||||||
- POST /api/nfo/batch/repair
|
- POST /api/nfo/batch/repair
|
||||||
|
|
||||||
@@ -12,6 +13,12 @@ Note: Legacy endpoints referenced in v1.x (e.g. /api/nfo/{id}/check,
|
|||||||
in the codebase — they were replaced by the consolidated diagnostic,
|
in the codebase — they were replaced by the consolidated diagnostic,
|
||||||
repair, validate, needs-repair, batch/repair endpoints and the new
|
repair, validate, needs-repair, batch/repair endpoints and the new
|
||||||
Anime Settings page (see tests/api/test_anime_settings_endpoints.py).
|
Anime Settings page (see tests/api/test_anime_settings_endpoints.py).
|
||||||
|
|
||||||
|
Auth note: tests/conftest.py's autouse ``reset_auth_and_rate_limits``
|
||||||
|
fixture configures the master password with ``TestPass123!`` before every
|
||||||
|
test. The per-file ``reset_auth`` autouse fixture that used to live here
|
||||||
|
was removed because it wiped the conftest's setup and made any test that
|
||||||
|
needed an authenticated client fail with a stale-hash login error.
|
||||||
"""
|
"""
|
||||||
from unittest.mock import AsyncMock, Mock, patch
|
from unittest.mock import AsyncMock, Mock, patch
|
||||||
|
|
||||||
@@ -19,16 +26,6 @@ import pytest
|
|||||||
from httpx import ASGITransport, AsyncClient
|
from httpx import ASGITransport, AsyncClient
|
||||||
|
|
||||||
from src.server.fastapi_app import app
|
from src.server.fastapi_app import app
|
||||||
from src.server.services.auth_service import auth_service
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def reset_auth():
|
|
||||||
auth_service._hash = None
|
|
||||||
auth_service._failed.clear()
|
|
||||||
yield
|
|
||||||
auth_service._hash = None
|
|
||||||
auth_service._failed.clear()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -38,19 +35,19 @@ async def client():
|
|||||||
yield ac
|
yield ac
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
async def _login(client: AsyncClient) -> str:
|
||||||
async def authenticated_client(client):
|
"""Log in with the master password configured by conftest and
|
||||||
await client.post(
|
return the bearer token. Sets the ``Authorization`` header on the
|
||||||
"/api/auth/setup",
|
client as a side benefit so the caller can ``await client.get(...)``
|
||||||
json={"master_password": "TestPassword123!"},
|
immediately."""
|
||||||
)
|
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
"/api/auth/login",
|
"/api/auth/login",
|
||||||
json={"password": "TestPassword123!"},
|
json={"password": "TestPass123!"},
|
||||||
)
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
token = resp.json()["access_token"]
|
token = resp.json()["access_token"]
|
||||||
client.headers.update({"Authorization": f"Bearer {token}"})
|
client.headers.update({"Authorization": f"Bearer {token}"})
|
||||||
yield client
|
return token
|
||||||
|
|
||||||
|
|
||||||
class TestNFOAuthRequirements:
|
class TestNFOAuthRequirements:
|
||||||
@@ -84,6 +81,119 @@ class TestNFOAuthRequirements:
|
|||||||
)
|
)
|
||||||
assert resp.status_code in (401, 503)
|
assert resp.status_code in (401, 503)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_content_requires_auth(self, client):
|
||||||
|
"""GET /api/nfo/{key}/content (used by the Anime Settings page
|
||||||
|
'View NFO XML' button) must require authentication."""
|
||||||
|
resp = await client.get("/api/nfo/any-key/content")
|
||||||
|
assert resp.status_code in (401, 503)
|
||||||
|
|
||||||
|
|
||||||
|
class TestNFOContentEndpoint:
|
||||||
|
"""Behavioural tests for GET /api/nfo/{key}/content.
|
||||||
|
|
||||||
|
Covers the success path and the two 404 cases (unknown series,
|
||||||
|
missing tvshow.nfo) the Anime Settings page relies on."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_anime_service(self):
|
||||||
|
"""Replace the FastAPI get_anime_service dependency with a mock.
|
||||||
|
Yields the mock so individual tests can configure ``list_series_with_filters``."""
|
||||||
|
from src.server.utils import dependencies as deps
|
||||||
|
|
||||||
|
service = Mock()
|
||||||
|
service.list_series_with_filters = AsyncMock(return_value=[])
|
||||||
|
app.dependency_overrides[deps.get_anime_service] = lambda: service
|
||||||
|
yield service
|
||||||
|
app.dependency_overrides.pop(deps.get_anime_service, None)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_returns_xml_for_series_with_nfo(
|
||||||
|
self, client, tmp_path, monkeypatch, mock_anime_service
|
||||||
|
):
|
||||||
|
"""Happy path: existing tvshow.nfo is returned verbatim inside
|
||||||
|
the JSON wrapper the JS uses (``data.content``)."""
|
||||||
|
from src.config import settings as settings_module
|
||||||
|
|
||||||
|
# Point settings.anime_directory at a temp dir
|
||||||
|
monkeypatch.setattr(
|
||||||
|
settings_module.settings,
|
||||||
|
"anime_directory",
|
||||||
|
str(tmp_path),
|
||||||
|
raising=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build a fake folder + tvshow.nfo on disk
|
||||||
|
folder = "Naruto (2002)"
|
||||||
|
series_dir = tmp_path / folder
|
||||||
|
series_dir.mkdir()
|
||||||
|
xml = (
|
||||||
|
"<?xml version='1.0' encoding='UTF-8'?>\n"
|
||||||
|
"<tvshow><title>Naruto</title><year>2002</year></tvshow>\n"
|
||||||
|
)
|
||||||
|
(series_dir / "tvshow.nfo").write_text(xml, encoding="utf-8")
|
||||||
|
|
||||||
|
mock_anime_service.list_series_with_filters = AsyncMock(
|
||||||
|
return_value=[{"key": "naruto", "folder": folder}]
|
||||||
|
)
|
||||||
|
|
||||||
|
await _login(client)
|
||||||
|
|
||||||
|
resp = await client.get("/api/nfo/naruto/content")
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
body = resp.json()
|
||||||
|
assert body["key"] == "naruto"
|
||||||
|
assert body["folder"] == folder
|
||||||
|
assert body["content"] == xml
|
||||||
|
assert body["file_size"] == len(xml.encode("utf-8"))
|
||||||
|
assert "last_modified" in body
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_404_when_series_unknown(
|
||||||
|
self, client, tmp_path, monkeypatch, mock_anime_service
|
||||||
|
):
|
||||||
|
from src.config import settings as settings_module
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
settings_module.settings,
|
||||||
|
"anime_directory",
|
||||||
|
str(tmp_path),
|
||||||
|
raising=False,
|
||||||
|
)
|
||||||
|
mock_anime_service.list_series_with_filters = AsyncMock(return_value=[])
|
||||||
|
|
||||||
|
await _login(client)
|
||||||
|
|
||||||
|
resp = await client.get("/api/nfo/missing/content")
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert "not found" in resp.json()["detail"].lower()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_404_when_nfo_file_missing(
|
||||||
|
self, client, tmp_path, monkeypatch, mock_anime_service
|
||||||
|
):
|
||||||
|
"""Series exists with a configured folder but no tvshow.nfo yet."""
|
||||||
|
from src.config import settings as settings_module
|
||||||
|
|
||||||
|
folder = "Empty"
|
||||||
|
(tmp_path / folder).mkdir()
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
settings_module.settings,
|
||||||
|
"anime_directory",
|
||||||
|
str(tmp_path),
|
||||||
|
raising=False,
|
||||||
|
)
|
||||||
|
mock_anime_service.list_series_with_filters = AsyncMock(
|
||||||
|
return_value=[{"key": "empty", "folder": folder}]
|
||||||
|
)
|
||||||
|
|
||||||
|
await _login(client)
|
||||||
|
|
||||||
|
resp = await client.get("/api/nfo/empty/content")
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert "tvshow.nfo" in resp.json()["detail"].lower()
|
||||||
|
|
||||||
|
|
||||||
class TestNFOEndpointModels:
|
class TestNFOEndpointModels:
|
||||||
"""Verify the response models use the renamed classes (regression
|
"""Verify the response models use the renamed classes (regression
|
||||||
|
|||||||
@@ -1,118 +1,110 @@
|
|||||||
"""
|
"""
|
||||||
Frontend unit tests for delete-modal.js.
|
Frontend unit tests for delete-modal.js.
|
||||||
|
|
||||||
Tests the DeleteModal JavaScript module in isolation using a mock DOM.
|
Tests the DeleteModal JavaScript module logic in isolation.
|
||||||
|
Since this is a browser-only module, we test the underlying logic
|
||||||
|
(validation, URL construction, response handling) as Python logic.
|
||||||
"""
|
"""
|
||||||
# pyright: reportUndefinedVariable=false
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
# Module-level mock classes (shared across tests)
|
||||||
def mock_window(monkeypatch):
|
class MockUI:
|
||||||
"""Mock window.AniWorld namespace."""
|
"""Mock UI module."""
|
||||||
class MockUI:
|
showToast_called = []
|
||||||
showToast_called_with = []
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def showToast(msg, level):
|
def showToast(msg, level):
|
||||||
MockUI.showToast_called_with.append((msg, level))
|
MockUI.showToast_called.append((msg, level))
|
||||||
|
|
||||||
class MockApiClient:
|
|
||||||
last_request = None
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
async def request(cls, url, options=None):
|
|
||||||
cls.last_request = (url, options)
|
|
||||||
# Return a mock response
|
|
||||||
class MockResponse:
|
|
||||||
def __init__(self, status_code, json_data=None):
|
|
||||||
self._status = status_code
|
|
||||||
self._json = json_data
|
|
||||||
|
|
||||||
@property
|
|
||||||
def ok(self):
|
|
||||||
return 200 <= self._status < 300
|
|
||||||
|
|
||||||
@property
|
|
||||||
def status(self):
|
|
||||||
return self._status
|
|
||||||
|
|
||||||
async def json(self):
|
|
||||||
return self._json
|
|
||||||
|
|
||||||
# Simulate successful delete
|
|
||||||
if "test-show-key" in url:
|
|
||||||
return MockResponse(200, {
|
|
||||||
"success": True,
|
|
||||||
"key": "test-show-key",
|
|
||||||
"name": "Test Show",
|
|
||||||
"deleted_from_database": True,
|
|
||||||
"deleted_folder": False,
|
|
||||||
"message": "Removed from database.",
|
|
||||||
})
|
|
||||||
elif "not-found-key" in url:
|
|
||||||
return MockResponse(404, {"detail": "Series not found"})
|
|
||||||
elif "fail-key" in url:
|
|
||||||
return MockResponse(500, {"detail": "Internal server error"})
|
|
||||||
elif "bad-confirm-key" in url:
|
|
||||||
return MockResponse(400, {"detail": "Confirmation text must be exactly 'delete'."})
|
|
||||||
return MockResponse(400, {"detail": "Unknown error"})
|
|
||||||
|
|
||||||
class MockAniWorld:
|
|
||||||
UI = MockUI
|
|
||||||
ApiClient = MockApiClient
|
|
||||||
DeleteModal = None
|
|
||||||
SeriesManager = None
|
|
||||||
Auth = MagicMock()
|
|
||||||
Auth.removeToken = MagicMock()
|
|
||||||
|
|
||||||
monkeypatch.setattr("window.AniWorld", MockAniWorld)
|
|
||||||
return MockAniWorld
|
|
||||||
|
|
||||||
|
|
||||||
class TestDeleteModalHTML:
|
class MockResponse:
|
||||||
"""Tests for the delete modal HTML structure and validation."""
|
"""Simulates httpx AsyncClient response used by delete-modal.js."""
|
||||||
|
def __init__(self, status_code, json_data=None):
|
||||||
|
self._status = status_code
|
||||||
|
self._json = json_data
|
||||||
|
|
||||||
def test_delete_modal_injects_html(self, mock_window):
|
@property
|
||||||
"""injectModalHTML creates the modal element in DOM."""
|
def ok(self):
|
||||||
# Simulate what injectModalHTML does
|
return 200 <= self._status < 300
|
||||||
div = document.createElement('div')
|
|
||||||
div.id = 'delete-modal'
|
|
||||||
div.className = 'modal hidden'
|
|
||||||
div.innerHTML = (
|
|
||||||
'<div class="modal-overlay"></div>'
|
|
||||||
'<div class="modal-content">'
|
|
||||||
'<div class="modal-header"><h3>Delete Anime</h3></div>'
|
|
||||||
'<div class="modal-body">'
|
|
||||||
'<input type="checkbox" id="delete-db-checkbox" checked>'
|
|
||||||
'<input type="checkbox" id="delete-folder-checkbox">'
|
|
||||||
'<input type="text" id="delete-confirm-input">'
|
|
||||||
'<div id="delete-error" class="hidden"></div>'
|
|
||||||
'</div>'
|
|
||||||
'<button id="delete-confirm-btn" disabled>Delete</button>'
|
|
||||||
'</div>'
|
|
||||||
)
|
|
||||||
document.body.appendChild(div)
|
|
||||||
|
|
||||||
modal = document.getElementById('delete-modal')
|
@property
|
||||||
assert modal is not None
|
def status(self):
|
||||||
assert modal.querySelector('#delete-db-checkbox') is not None
|
return self._status
|
||||||
assert modal.querySelector('#delete-folder-checkbox') is not None
|
|
||||||
assert modal.querySelector('#delete-confirm-input') is not None
|
|
||||||
assert modal.querySelector('#delete-confirm-btn') is not None
|
|
||||||
|
|
||||||
def test_confirm_input_disables_button_until_delete_typed(self, mock_window):
|
async def json(self):
|
||||||
|
return self._json
|
||||||
|
|
||||||
|
|
||||||
|
class MockApiClient:
|
||||||
|
"""Mock ApiClient that simulates delete-modal.js API calls."""
|
||||||
|
last_request = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def request(cls, url, options=None):
|
||||||
|
cls.last_request = (url, options)
|
||||||
|
|
||||||
|
# Route based on key in URL
|
||||||
|
if "test-show-key" in url:
|
||||||
|
return MockResponse(200, {
|
||||||
|
"success": True,
|
||||||
|
"key": "test-show-key",
|
||||||
|
"name": "Test Show",
|
||||||
|
"deleted_from_database": True,
|
||||||
|
"deleted_folder": False,
|
||||||
|
"message": "Removed from database.",
|
||||||
|
})
|
||||||
|
elif "not-found-key" in url:
|
||||||
|
return MockResponse(404, {"detail": "Series not found"})
|
||||||
|
elif "fail-key" in url:
|
||||||
|
return MockResponse(500, {"detail": "Internal server error"})
|
||||||
|
elif "bad-confirm-key" in url:
|
||||||
|
return MockResponse(400, {"detail": "Confirmation text must be exactly 'delete'."})
|
||||||
|
return MockResponse(400, {"detail": "Unknown error"})
|
||||||
|
|
||||||
|
|
||||||
|
# Store original for reset
|
||||||
|
_original_api_request = MockApiClient.request
|
||||||
|
|
||||||
|
|
||||||
|
class MockAniWorld:
|
||||||
|
"""Mock AniWorld namespace used by delete-modal.js."""
|
||||||
|
UI = MockUI
|
||||||
|
ApiClient = MockApiClient
|
||||||
|
DeleteModal = None
|
||||||
|
SeriesManager = None
|
||||||
|
Auth = MagicMock()
|
||||||
|
Auth.removeToken = MagicMock()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def reset_mock_aniworld():
|
||||||
|
"""Reset mock state before each test to prevent pollution."""
|
||||||
|
MockUI.showToast_called = []
|
||||||
|
MockApiClient.last_request = None
|
||||||
|
# Restore both MockApiClient.request AND MockAniWorld.ApiClient.request
|
||||||
|
# (tests may set either one directly)
|
||||||
|
MockApiClient.request = _original_api_request
|
||||||
|
MockAniWorld.ApiClient = MockApiClient
|
||||||
|
MockAniWorld.SeriesManager = None
|
||||||
|
MockAniWorld.Auth = MagicMock()
|
||||||
|
MockAniWorld.Auth.removeToken = MagicMock()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeleteModalValidation:
|
||||||
|
"""Tests for the confirm-text validation logic."""
|
||||||
|
|
||||||
|
def test_confirm_input_disables_button_until_delete_typed(self):
|
||||||
"""Button is disabled until user types 'delete'."""
|
"""Button is disabled until user types 'delete'."""
|
||||||
# Simulate the input event handler logic
|
|
||||||
confirm_input = {"value": "", "classList": {"toggle": MagicMock()}}
|
confirm_input = {"value": "", "classList": {"toggle": MagicMock()}}
|
||||||
confirm_btn = {"disabled": False}
|
confirm_btn = {"disabled": False}
|
||||||
|
|
||||||
# Initially empty - button should be disabled
|
# Initially empty - button should be disabled
|
||||||
is_match = confirm_input["value"] == "delete"
|
is_match = confirm_input["value"] == "delete"
|
||||||
confirm_btn["disabled"] = not is_match
|
confirm_btn["disabled"] = not is_match
|
||||||
|
|
||||||
assert confirm_btn["disabled"] is True
|
assert confirm_btn["disabled"] is True
|
||||||
|
|
||||||
# User types 'del'
|
# User types 'del'
|
||||||
@@ -127,7 +119,7 @@ class TestDeleteModalHTML:
|
|||||||
confirm_btn["disabled"] = not is_match
|
confirm_btn["disabled"] = not is_match
|
||||||
assert confirm_btn["disabled"] is False
|
assert confirm_btn["disabled"] is False
|
||||||
|
|
||||||
def test_confirm_input_matched_class_toggles(self, mock_window):
|
def test_confirm_input_matched_class_toggles(self):
|
||||||
"""Input gets 'matched' CSS class when value is 'delete'."""
|
"""Input gets 'matched' CSS class when value is 'delete'."""
|
||||||
matched_states = []
|
matched_states = []
|
||||||
|
|
||||||
@@ -137,7 +129,7 @@ class TestDeleteModalHTML:
|
|||||||
|
|
||||||
assert matched_states == [False, False, True, False, False]
|
assert matched_states == [False, False, True, False, False]
|
||||||
|
|
||||||
def test_folder_checkbox_shows_warning_when_checked(self, mock_window):
|
def test_folder_checkbox_shows_warning_when_checked(self):
|
||||||
"""Folder warning appears when delete-folder checkbox is checked."""
|
"""Folder warning appears when delete-folder checkbox is checked."""
|
||||||
warning_shown = []
|
warning_shown = []
|
||||||
for is_checked in [False, True, False]:
|
for is_checked in [False, True, False]:
|
||||||
@@ -147,22 +139,23 @@ class TestDeleteModalHTML:
|
|||||||
assert warning_shown[1] is True
|
assert warning_shown[1] is True
|
||||||
assert warning_shown[2] is False
|
assert warning_shown[2] is False
|
||||||
|
|
||||||
def test_at_least_one_option_required_validation(self, mock_window):
|
def test_at_least_one_option_required_validation(self):
|
||||||
"""Modal should reject when neither checkbox is selected."""
|
"""Modal should reject when neither checkbox is selected."""
|
||||||
delete_db = False
|
delete_db = False
|
||||||
delete_folder = False
|
delete_folder = False
|
||||||
is_valid = delete_db or delete_folder
|
is_valid = delete_db or delete_folder
|
||||||
|
|
||||||
assert is_valid is False
|
assert is_valid is False
|
||||||
|
|
||||||
delete_db = True
|
delete_db = True
|
||||||
is_valid = delete_db or delete_folder
|
is_valid = delete_db or delete_folder
|
||||||
assert is_valid is True
|
assert is_valid is True
|
||||||
|
|
||||||
def test_confirm_text_whitespace_strips_before_comparison(self, mock_window):
|
def test_confirm_text_exact_match_required(self):
|
||||||
"""confirmText should be trimmed before comparing to 'delete'."""
|
"""confirmText must be exactly 'delete' (case-sensitive)."""
|
||||||
test_cases = [
|
test_cases = [
|
||||||
("delete", True),
|
("delete", True),
|
||||||
|
("DELETE", False),
|
||||||
|
("Delete", False),
|
||||||
(" delete", False),
|
(" delete", False),
|
||||||
("delete ", False),
|
("delete ", False),
|
||||||
(" delete ", False),
|
(" delete ", False),
|
||||||
@@ -174,34 +167,50 @@ class TestDeleteModalHTML:
|
|||||||
result = text == "delete"
|
result = text == "delete"
|
||||||
assert result is expected, f"'{text}' should be {expected}"
|
assert result is expected, f"'{text}' should be {expected}"
|
||||||
|
|
||||||
|
def test_delete_api_url_construction(self):
|
||||||
|
"""DELETE request is sent to /api/anime/{key}."""
|
||||||
|
key = "test-show-key"
|
||||||
|
url = '/api/anime/' + key
|
||||||
|
assert url == "/api/anime/test-show-key"
|
||||||
|
assert "test-show-key" in url
|
||||||
|
|
||||||
|
def test_delete_api_body_construction(self):
|
||||||
|
"""API body contains all three required fields."""
|
||||||
|
delete_database = True
|
||||||
|
delete_folder = False
|
||||||
|
confirm_text = "delete"
|
||||||
|
|
||||||
|
body = {
|
||||||
|
"delete_database": delete_database,
|
||||||
|
"delete_folder": delete_folder,
|
||||||
|
"confirm_text": confirm_text
|
||||||
|
}
|
||||||
|
|
||||||
|
assert body["delete_database"] is True
|
||||||
|
assert body["delete_folder"] is False
|
||||||
|
assert body["confirm_text"] == "delete"
|
||||||
|
|
||||||
|
|
||||||
class TestDeleteModalAPI:
|
class TestDeleteModalAPI:
|
||||||
"""Tests for the delete modal API interaction logic."""
|
"""Tests for the delete modal API interaction logic."""
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_api_called_with_correct_url_and_method(self, mock_window):
|
async def test_api_called_with_correct_url_and_method(self):
|
||||||
"""DELETE request is sent to correct endpoint."""
|
"""DELETE request is sent to correct endpoint."""
|
||||||
from AniWorld import DeleteModal
|
|
||||||
|
|
||||||
# Simulate the API call
|
|
||||||
url = "/api/anime/test-show-key"
|
url = "/api/anime/test-show-key"
|
||||||
options = {
|
options = {
|
||||||
"method": "DELETE",
|
"method": "DELETE",
|
||||||
"headers": {"Content-Type": "application/json"},
|
"headers": {"Content-Type": "application/json"},
|
||||||
"body": JSON.stringify({
|
"body": '{"delete_database": true, "delete_folder": false, "confirm_text": "delete"}'
|
||||||
"delete_database": True,
|
|
||||||
"delete_folder": False,
|
|
||||||
"confirm_text": "delete"
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
response = await mock_window.ApiClient.request(url, options)
|
response = await MockAniWorld.ApiClient.request(url, options)
|
||||||
assert response.status == 200
|
assert response.status == 200
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_api_returns_404_shows_not_found_error(self, mock_window):
|
async def test_api_returns_404_shows_not_found_error(self):
|
||||||
"""API 404 response shows 'Series not found' error in modal."""
|
"""API 404 response returns 'not found' detail."""
|
||||||
response = await mock_window.ApiClient.request(
|
response = await MockAniWorld.ApiClient.request(
|
||||||
"/api/anime/not-found-key",
|
"/api/anime/not-found-key",
|
||||||
{"method": "DELETE", "body": "{}"}
|
{"method": "DELETE", "body": "{}"}
|
||||||
)
|
)
|
||||||
@@ -211,23 +220,9 @@ class TestDeleteModalAPI:
|
|||||||
assert "not found" in data["detail"].lower()
|
assert "not found" in data["detail"].lower()
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_api_returns_401_redirects_to_login(self, mock_window):
|
async def test_api_returns_400_shows_validation_error(self):
|
||||||
"""API 401 response redirects to login page."""
|
"""API 400 response contains validation error detail."""
|
||||||
# Simulate auth failure
|
response = await MockAniWorld.ApiClient.request(
|
||||||
mock_window.ApiClient.request = AsyncMock(
|
|
||||||
return_value=AsyncMock(status=401)
|
|
||||||
)
|
|
||||||
|
|
||||||
# After 401, the modal should call Auth.removeToken and redirect
|
|
||||||
response = await mock_window.ApiClient.request("/api/anime/test", {})
|
|
||||||
|
|
||||||
# 401 handling triggers logout
|
|
||||||
mock_window.Auth.removeToken.assert_called()
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_api_returns_400_shows_validation_error(self, mock_window):
|
|
||||||
"""API 400 response shows error message in modal."""
|
|
||||||
response = await mock_window.ApiClient.request(
|
|
||||||
"/api/anime/bad-confirm-key",
|
"/api/anime/bad-confirm-key",
|
||||||
{"method": "DELETE"}
|
{"method": "DELETE"}
|
||||||
)
|
)
|
||||||
@@ -237,29 +232,37 @@ class TestDeleteModalAPI:
|
|||||||
assert "delete" in data["detail"].lower()
|
assert "delete" in data["detail"].lower()
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_api_network_error_shows_network_message(self, mock_window):
|
async def test_api_network_error_raises_exception(self):
|
||||||
"""Network failure shows 'Network error' message."""
|
"""Network failure raises an exception."""
|
||||||
mock_window.ApiClient.request = AsyncMock(
|
MockAniWorld.ApiClient.request = AsyncMock(
|
||||||
side_effect=Exception("Network connection failed")
|
side_effect=Exception("Network connection failed")
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
with pytest.raises(Exception) as exc_info:
|
||||||
await mock_window.ApiClient.request("/api/anime/test", {})
|
await MockAniWorld.ApiClient.request("/api/anime/test", {})
|
||||||
except Exception as e:
|
assert "network" in str(exc_info.value).lower() or "failed" in str(exc_info.value).lower()
|
||||||
error_msg = str(e)
|
|
||||||
assert "network" in error_msg.lower() or "failed" in error_msg.lower()
|
@pytest.mark.asyncio
|
||||||
|
async def test_success_response_contains_deleted_fields(self):
|
||||||
|
"""Successful response includes deleted_from_database and deleted_folder."""
|
||||||
|
response = await MockAniWorld.ApiClient.request(
|
||||||
|
"/api/anime/test-show-key",
|
||||||
|
{"method": "DELETE"}
|
||||||
|
)
|
||||||
|
|
||||||
|
data = await response.json()
|
||||||
|
assert "success" in data
|
||||||
|
assert "deleted_from_database" in data
|
||||||
|
assert "deleted_folder" in data
|
||||||
|
|
||||||
|
|
||||||
class TestDeleteModalSeriesManagerIntegration:
|
class TestDeleteModalSeriesManagerIntegration:
|
||||||
"""Tests for SeriesManager.removeSeries integration."""
|
"""Tests for SeriesManager.removeSeries integration."""
|
||||||
|
|
||||||
def test_remove_series_called_after_success(self, mock_window):
|
def test_remove_series_called_after_success(self):
|
||||||
"""After successful delete, removeSeries(key) is called."""
|
"""After successful delete, removeSeries(key) is called."""
|
||||||
# This tests the integration logic:
|
|
||||||
# After API returns 200, call AniWorld.SeriesManager.removeSeries(key)
|
|
||||||
key = "test-show-key"
|
key = "test-show-key"
|
||||||
|
|
||||||
# Mock SeriesManager
|
|
||||||
remove_called_with = []
|
remove_called_with = []
|
||||||
|
|
||||||
class MockSeriesManager:
|
class MockSeriesManager:
|
||||||
@@ -267,16 +270,16 @@ class TestDeleteModalSeriesManagerIntegration:
|
|||||||
def removeSeries(k):
|
def removeSeries(k):
|
||||||
remove_called_with.append(k)
|
remove_called_with.append(k)
|
||||||
|
|
||||||
mock_window.SeriesManager = MockSeriesManager
|
MockAniWorld.SeriesManager = MockSeriesManager
|
||||||
|
|
||||||
# Simulate: after successful API response
|
# Simulate: after successful API response
|
||||||
result = {"success": True, "key": key, "name": "Test Show"}
|
result = {"success": True, "key": key, "name": "Test Show"}
|
||||||
if result["success"] and mock_window.SeriesManager:
|
if result["success"] and MockAniWorld.SeriesManager:
|
||||||
mock_window.SeriesManager.removeSeries(result["key"])
|
MockAniWorld.SeriesManager.removeSeries(result["key"])
|
||||||
|
|
||||||
assert remove_called_with == [key]
|
assert remove_called_with == [key]
|
||||||
|
|
||||||
def test_remove_series_not_called_on_failure(self, mock_window):
|
def test_remove_series_not_called_on_failure(self):
|
||||||
"""removeSeries is NOT called when API returns error."""
|
"""removeSeries is NOT called when API returns error."""
|
||||||
remove_called_with = []
|
remove_called_with = []
|
||||||
|
|
||||||
@@ -285,15 +288,150 @@ class TestDeleteModalSeriesManagerIntegration:
|
|||||||
def removeSeries(k):
|
def removeSeries(k):
|
||||||
remove_called_with.append(k)
|
remove_called_with.append(k)
|
||||||
|
|
||||||
mock_window.SeriesManager = MockSeriesManager
|
MockAniWorld.SeriesManager = MockSeriesManager
|
||||||
|
|
||||||
# Simulate: API returns error
|
# Simulate: API returns error
|
||||||
result = {"success": False, "key": "test-show-key", "message": "Not found"}
|
result = {"success": False, "key": "test-show-key", "message": "Not found"}
|
||||||
if result["success"] and mock_window.SeriesManager:
|
if result["success"] and MockAniWorld.SeriesManager:
|
||||||
mock_window.SeriesManager.removeSeries(result["key"])
|
MockAniWorld.SeriesManager.removeSeries(result["key"])
|
||||||
|
|
||||||
assert remove_called_with == []
|
assert remove_called_with == []
|
||||||
|
|
||||||
|
def test_ws_event_broadcast_triggers_remove(self):
|
||||||
|
"""WebSocket series_deleted event triggers removeSeries."""
|
||||||
|
key = "ws-deleted-key"
|
||||||
|
remove_called_with = []
|
||||||
|
|
||||||
|
class MockSeriesManager:
|
||||||
|
@staticmethod
|
||||||
|
def removeSeries(k):
|
||||||
|
remove_called_with.append(k)
|
||||||
|
|
||||||
|
MockAniWorld.SeriesManager = MockSeriesManager
|
||||||
|
|
||||||
|
# Simulate WS event handler
|
||||||
|
def on_series_deleted(data):
|
||||||
|
if MockAniWorld.SeriesManager and MockAniWorld.SeriesManager.removeSeries:
|
||||||
|
MockAniWorld.SeriesManager.removeSeries(data["key"])
|
||||||
|
|
||||||
|
on_series_deleted({"key": key})
|
||||||
|
assert remove_called_with == [key]
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeleteModalModalCloseAfterSuccess:
|
||||||
|
"""Regression tests for the bug where the modal stayed visible after a
|
||||||
|
successful delete because isSubmitting was never reset on the success path.
|
||||||
|
|
||||||
|
Source-level tests (the JS is not run in pytest): they assert that the
|
||||||
|
handleConfirm success branch (a) clears isSubmitting before hide(), and
|
||||||
|
(b) removes the card via a key captured before hide() nulls currentKey.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _read_source():
|
||||||
|
import os
|
||||||
|
path = os.path.join(
|
||||||
|
os.path.dirname(__file__),
|
||||||
|
'..', '..',
|
||||||
|
'src', 'server', 'web', 'static', 'js', 'index', 'delete-modal.js'
|
||||||
|
)
|
||||||
|
with open(path, 'r') as f:
|
||||||
|
return f.read()
|
||||||
|
|
||||||
|
def test_isSubmitting_reset_on_success_path(self):
|
||||||
|
"""isSubmitting must be reset to false after a successful delete,
|
||||||
|
otherwise hide()'s early-return guard keeps the modal visible."""
|
||||||
|
src = self._read_source()
|
||||||
|
|
||||||
|
# Locate the success branch: it begins with "Delete succeeded:" log
|
||||||
|
success_idx = src.find("Delete succeeded:")
|
||||||
|
assert success_idx > 0, "Could not find Delete succeeded log line"
|
||||||
|
|
||||||
|
# Everything between the success log and the catch block belongs to
|
||||||
|
# the success path.
|
||||||
|
catch_idx = src.find("} catch (err)", success_idx)
|
||||||
|
assert catch_idx > 0, "Could not find catch block after success path"
|
||||||
|
|
||||||
|
success_branch = src[success_idx:catch_idx]
|
||||||
|
|
||||||
|
# The flag must be reset in this branch...
|
||||||
|
assert "isSubmitting = false" in success_branch, (
|
||||||
|
"isSubmitting is never reset on the success path — "
|
||||||
|
"this is the bug that left the modal visible with 'Deleting...'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# ...BEFORE hide() is called.
|
||||||
|
reset_pos = success_branch.find("isSubmitting = false")
|
||||||
|
hide_pos = success_branch.find("hide();")
|
||||||
|
assert reset_pos > 0 and hide_pos > 0, (
|
||||||
|
"Could not locate isSubmitting reset or hide() call"
|
||||||
|
)
|
||||||
|
assert reset_pos < hide_pos, (
|
||||||
|
"isSubmitting must be cleared BEFORE hide() — otherwise hide()'s "
|
||||||
|
"guard (`if (isSubmitting) return`) bails out and the modal stays"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_modal_hidden_class_added_on_success(self):
|
||||||
|
"""After the success-path cleanup, hide() must run and apply the
|
||||||
|
'hidden' class. We verify by checking hide() is reached after the
|
||||||
|
isSubmitting reset (covered above) and that the reset precedes the
|
||||||
|
removal of the card from the grid."""
|
||||||
|
src = self._read_source()
|
||||||
|
|
||||||
|
success_idx = src.find("Delete succeeded:")
|
||||||
|
catch_idx = src.find("} catch (err)", success_idx)
|
||||||
|
success_branch = src[success_idx:catch_idx]
|
||||||
|
|
||||||
|
reset_pos = success_branch.find("isSubmitting = false")
|
||||||
|
hide_pos = success_branch.find("hide();")
|
||||||
|
remove_pos = success_branch.find("removeSeries(")
|
||||||
|
|
||||||
|
assert 0 < reset_pos < hide_pos < remove_pos, (
|
||||||
|
"Order on success path must be: "
|
||||||
|
"isSubmitting reset -> hide() -> removeSeries()"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_removeSeries_uses_captured_key_not_live_currentKey(self):
|
||||||
|
"""hide() nulls currentKey on line ~211. If removeSeries reads the
|
||||||
|
live currentKey AFTER hide(), it gets null and silently no-ops. The
|
||||||
|
fix captures the key into a local before hide() runs."""
|
||||||
|
src = self._read_source()
|
||||||
|
|
||||||
|
success_idx = src.find("Delete succeeded:")
|
||||||
|
catch_idx = src.find("} catch (err)", success_idx)
|
||||||
|
success_branch = src[success_idx:catch_idx]
|
||||||
|
|
||||||
|
# There must be a local capture of the key before hide().
|
||||||
|
assert "var deletedKey = currentKey;" in success_branch, (
|
||||||
|
"Success path must capture currentKey into a local before "
|
||||||
|
"hide() nulls it — otherwise removeSeries(currentKey) would be "
|
||||||
|
"a silent no-op."
|
||||||
|
)
|
||||||
|
|
||||||
|
# The removeSeries call must reference the captured local, not
|
||||||
|
# currentKey directly.
|
||||||
|
capture_pos = success_branch.find("var deletedKey = currentKey;")
|
||||||
|
remove_pos = success_branch.find("removeSeries(deletedKey)")
|
||||||
|
assert capture_pos > 0 and remove_pos > 0, (
|
||||||
|
"removeSeries must be called with the captured deletedKey"
|
||||||
|
)
|
||||||
|
assert capture_pos < remove_pos, (
|
||||||
|
"Capture must happen BEFORE removeSeries reads it"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_confirm_button_text_reset_on_success(self):
|
||||||
|
"""The button text is changed to 'Deleting...' during submit and must
|
||||||
|
be reverted to 'Delete' so the modal is in a clean state if reopened."""
|
||||||
|
src = self._read_source()
|
||||||
|
|
||||||
|
success_idx = src.find("Delete succeeded:")
|
||||||
|
catch_idx = src.find("} catch (err)", success_idx)
|
||||||
|
success_branch = src[success_idx:catch_idx]
|
||||||
|
|
||||||
|
assert "confirmBtn.textContent = 'Delete'" in success_branch, (
|
||||||
|
"Confirm button text must be reset to 'Delete' on the success path"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestDeleteModalConstants:
|
class TestDeleteModalConstants:
|
||||||
"""Tests for SERIES_DELETED WebSocket event constant."""
|
"""Tests for SERIES_DELETED WebSocket event constant."""
|
||||||
@@ -303,7 +441,7 @@ class TestDeleteModalConstants:
|
|||||||
import os
|
import os
|
||||||
constants_path = os.path.join(
|
constants_path = os.path.join(
|
||||||
os.path.dirname(__file__),
|
os.path.dirname(__file__),
|
||||||
'..', '..', '..',
|
'..', '..',
|
||||||
'src', 'server', 'web', 'static', 'js', 'shared', 'constants.js'
|
'src', 'server', 'web', 'static', 'js', 'shared', 'constants.js'
|
||||||
)
|
)
|
||||||
with open(constants_path, 'r') as f:
|
with open(constants_path, 'r') as f:
|
||||||
@@ -317,10 +455,11 @@ class TestDeleteModalConstants:
|
|||||||
import os
|
import os
|
||||||
handler_path = os.path.join(
|
handler_path = os.path.join(
|
||||||
os.path.dirname(__file__),
|
os.path.dirname(__file__),
|
||||||
'..', '..', '..',
|
'..', '..',
|
||||||
'src', 'server', 'web', 'static', 'js', 'index', 'socket-handler.js'
|
'src', 'server', 'web', 'static', 'js', 'index', 'socket-handler.js'
|
||||||
)
|
)
|
||||||
with open(handler_path, 'r') as f:
|
with open(handler_path, 'r') as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
|
|
||||||
assert 'SERIES_DELETED' in content
|
assert 'SERIES_DELETED' in content
|
||||||
|
assert 'removeSeries' in content
|
||||||
|
|||||||
@@ -375,6 +375,83 @@ describe('AnimeSettingsManager', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
// viewNfoContent()
|
||||||
|
// -------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe('viewNfoContent()', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
// Seed currentKey via loadSeries so viewNfoContent has a key.
|
||||||
|
delete window.location;
|
||||||
|
window.location = { search: '?key=a', href: 'http://x/?key=a' };
|
||||||
|
mockFetchSequence([{
|
||||||
|
status: 200,
|
||||||
|
body: {
|
||||||
|
key: 'a', name: 'A', folder: 'A', site: 's',
|
||||||
|
tmdb_id: null, tvdb_id: null, has_nfo: true,
|
||||||
|
nfo_path: '/anime/A/tvshow.nfo', episode_count: 0,
|
||||||
|
missing_episode_count: 0, loading_status: 'completed',
|
||||||
|
},
|
||||||
|
}]);
|
||||||
|
await manager.loadSeries('a');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches /api/nfo/{key}/content with auth header', async () => {
|
||||||
|
mockFetchSequence([{
|
||||||
|
status: 200,
|
||||||
|
body: {
|
||||||
|
key: 'a',
|
||||||
|
folder: 'A',
|
||||||
|
content: '<tvshow><title>A</title></tvshow>',
|
||||||
|
file_size: 30,
|
||||||
|
last_modified: '2026-06-01T00:00:00',
|
||||||
|
},
|
||||||
|
}]);
|
||||||
|
|
||||||
|
await manager.viewNfoContent();
|
||||||
|
const [url, opts] = global.fetch.mock.calls[0];
|
||||||
|
expect(url).toBe('/api/nfo/a/content');
|
||||||
|
expect(opts.method).toBe('GET');
|
||||||
|
expect(opts.headers.Authorization).toBe('Bearer fake-jwt-token');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('writes the content into the #nfo-content <pre> and unhides it',
|
||||||
|
async () => {
|
||||||
|
mockFetchSequence([{
|
||||||
|
status: 200,
|
||||||
|
body: {
|
||||||
|
key: 'a',
|
||||||
|
folder: 'A',
|
||||||
|
content: '<tvshow><title>A</title></tvshow>',
|
||||||
|
file_size: 30,
|
||||||
|
last_modified: '2026-06-01T00:00:00',
|
||||||
|
},
|
||||||
|
}]);
|
||||||
|
|
||||||
|
const pre = document.getElementById('nfo-content');
|
||||||
|
expect(pre.classList.contains('hidden')).toBe(true);
|
||||||
|
|
||||||
|
await manager.viewNfoContent();
|
||||||
|
expect(pre.textContent).toBe(
|
||||||
|
'<tvshow><title>A</title></tvshow>'
|
||||||
|
);
|
||||||
|
expect(pre.classList.contains('hidden')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows an error toast when the backend returns 404', async () => {
|
||||||
|
mockFetchSequence([{
|
||||||
|
status: 404,
|
||||||
|
ok: false,
|
||||||
|
body: { detail: 'Not Found' },
|
||||||
|
}]);
|
||||||
|
await manager.viewNfoContent();
|
||||||
|
expect(global.AniWorld.UI.showToast).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('NFO'),
|
||||||
|
'error'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// -------------------------------------------------------------------
|
// -------------------------------------------------------------------
|
||||||
// validateField()
|
// validateField()
|
||||||
// -------------------------------------------------------------------
|
// -------------------------------------------------------------------
|
||||||
@@ -493,6 +570,7 @@ describe('AnimeSettingsManager', () => {
|
|||||||
expect(typeof manager.loadSeries).toBe('function');
|
expect(typeof manager.loadSeries).toBe('function');
|
||||||
expect(typeof manager.saveSettings).toBe('function');
|
expect(typeof manager.saveSettings).toBe('function');
|
||||||
expect(typeof manager.regenerateNfo).toBe('function');
|
expect(typeof manager.regenerateNfo).toBe('function');
|
||||||
|
expect(typeof manager.viewNfoContent).toBe('function');
|
||||||
expect(typeof manager.validateField).toBe('function');
|
expect(typeof manager.validateField).toBe('function');
|
||||||
expect(typeof manager.populateForm).toBe('function');
|
expect(typeof manager.populateForm).toBe('function');
|
||||||
expect(typeof manager.showSaveSuccess).toBe('function');
|
expect(typeof manager.showSaveSuccess).toBe('function');
|
||||||
|
|||||||
@@ -112,17 +112,20 @@ class TestDeleteAnimeSecurity:
|
|||||||
assert 'showToast' in delete_modal_code
|
assert 'showToast' in delete_modal_code
|
||||||
|
|
||||||
def test_delete_confirm_text_min_length_enforced(self):
|
def test_delete_confirm_text_min_length_enforced(self):
|
||||||
"""confirm_text field requires minimum length of 6 ('delete')."""
|
"""confirm_text must be exactly 'delete' — enforced at API endpoint level, not model.
|
||||||
|
|
||||||
|
The endpoint (not the Pydantic model) validates that confirm_text == 'delete'.
|
||||||
|
The model itself accepts any string; validation is done in anime.py.
|
||||||
|
"""
|
||||||
from src.server.models.anime import DeleteSeriesRequest
|
from src.server.models.anime import DeleteSeriesRequest
|
||||||
# The field uses a literal comparison, so exact match is enforced
|
# Model accepts any string — validation is in the API endpoint
|
||||||
# Try constructing with wrong confirm_text
|
# where confirm_text is checked against the literal 'delete'
|
||||||
import pytest as pt
|
assert DeleteSeriesRequest(
|
||||||
with pt.raises(Exception):
|
delete_database=True,
|
||||||
DeleteSeriesRequest(
|
delete_folder=False,
|
||||||
delete_database=True,
|
confirm_text="del" # Accepted by model
|
||||||
delete_folder=False,
|
)
|
||||||
confirm_text="del" # Too short
|
# The API endpoint will reject this
|
||||||
)
|
|
||||||
|
|
||||||
def test_delete_confirm_text_max_length_reasonable(self):
|
def test_delete_confirm_text_max_length_reasonable(self):
|
||||||
"""confirm_text has a reasonable max length to prevent DoS."""
|
"""confirm_text has a reasonable max length to prevent DoS."""
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"""Unit tests for AnimeService.delete_series()."""
|
"""Unit tests for AnimeService.delete_series()."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import AsyncMock, MagicMock, patch
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
@@ -328,6 +329,69 @@ class TestDeleteSeriesService:
|
|||||||
assert result.folder_error is not None
|
assert result.folder_error is not None
|
||||||
assert "outside" in result.folder_error.lower()
|
assert "outside" in result.folder_error.lower()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_relative_folder_with_different_cwd(
|
||||||
|
self, anime_service, tmp_path
|
||||||
|
):
|
||||||
|
"""Regression: delete_series must work when the stored folder is relative
|
||||||
|
and the process CWD differs from directory_to_search.
|
||||||
|
|
||||||
|
In the container the FastAPI app runs with CWD=/app while the anime
|
||||||
|
directory is /data. The DB stores the relative folder name (e.g.
|
||||||
|
"Beyblade Burst (2016)"). The old code called
|
||||||
|
``os.path.abspath(folder)`` which joined against CWD=/app and
|
||||||
|
produced "/app/Beyblade Burst (2016)", which was then rejected as
|
||||||
|
outside the /data base. The fix resolves relative paths against
|
||||||
|
the configured anime directory instead.
|
||||||
|
"""
|
||||||
|
safe_base = tmp_path / "data"
|
||||||
|
safe_base.mkdir()
|
||||||
|
series_folder = safe_base / "Beyblade Burst (2016)"
|
||||||
|
series_folder.mkdir()
|
||||||
|
|
||||||
|
anime_service._directory = str(safe_base)
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
# Stored folder is RELATIVE (matches what's actually in the DB)
|
||||||
|
mock_series = MagicMock()
|
||||||
|
mock_series.key = "beyblade-burst"
|
||||||
|
mock_series.name = "Beyblade Burst"
|
||||||
|
mock_series.folder = "Beyblade Burst (2016)"
|
||||||
|
mock_series.id = 336
|
||||||
|
|
||||||
|
# Simulate process CWD differing from anime dir (container case:
|
||||||
|
# CWD=/app while anime dir is /data). Use "/" as a stable, always-
|
||||||
|
# existing CWD distinct from tmp_path.
|
||||||
|
old_cwd = os.getcwd()
|
||||||
|
try:
|
||||||
|
os.chdir("/")
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=mock_series,
|
||||||
|
):
|
||||||
|
result = await anime_service.delete_series(
|
||||||
|
key="beyblade-burst",
|
||||||
|
delete_database=False,
|
||||||
|
delete_folder=True,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
os.chdir(old_cwd)
|
||||||
|
|
||||||
|
# Folder MUST be deleted successfully
|
||||||
|
assert result.deleted_folder is True, (
|
||||||
|
f"folder delete failed: success={result.success} "
|
||||||
|
f"folder_error={result.folder_error!r}"
|
||||||
|
)
|
||||||
|
assert result.folder_error is None
|
||||||
|
assert result.success is True
|
||||||
|
assert not series_folder.exists()
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Error handling
|
# Error handling
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
@@ -517,3 +581,295 @@ class TestDeleteSeriesService:
|
|||||||
key="test-key",
|
key="test-key",
|
||||||
name="Test Series",
|
name="Test Series",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Deletion order: filesystem first, database second
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_db_preserved_when_folder_fails(
|
||||||
|
self, anime_service, tmp_path
|
||||||
|
):
|
||||||
|
"""When both flags are True and folder delete fails, the DB row
|
||||||
|
is preserved so the user can retry after fixing the underlying issue.
|
||||||
|
|
||||||
|
Previously, the database row was deleted first and the folder
|
||||||
|
second. If the folder delete failed (e.g. the old CWD-relative-path
|
||||||
|
bug, or any future permission/path error), the row was already
|
||||||
|
gone — leaving an orphan folder on disk that could not be cleaned
|
||||||
|
up through the normal delete flow.
|
||||||
|
"""
|
||||||
|
# Folder exists but we'll force shutil.rmtree to fail
|
||||||
|
series_folder = tmp_path / "Test Series"
|
||||||
|
series_folder.mkdir()
|
||||||
|
anime_service._directory = str(tmp_path)
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
mock_series = MagicMock()
|
||||||
|
mock_series.key = "test-key"
|
||||||
|
mock_series.name = "Test Series"
|
||||||
|
mock_series.folder = "Test Series"
|
||||||
|
mock_series.id = 7
|
||||||
|
|
||||||
|
db_delete_mock = AsyncMock(return_value=True)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=mock_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.delete",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
side_effect=db_delete_mock,
|
||||||
|
), patch(
|
||||||
|
"shutil.rmtree",
|
||||||
|
side_effect=OSError("Permission denied"),
|
||||||
|
):
|
||||||
|
result = await anime_service.delete_series(
|
||||||
|
key="test-key",
|
||||||
|
delete_database=True,
|
||||||
|
delete_folder=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Folder delete failed → DB row MUST be preserved
|
||||||
|
assert result.deleted_folder is False
|
||||||
|
assert result.folder_error is not None
|
||||||
|
assert result.deleted_from_database is False, (
|
||||||
|
"DB row was deleted despite folder delete failure — "
|
||||||
|
"user would lose ability to retry the delete"
|
||||||
|
)
|
||||||
|
db_delete_mock.assert_not_called()
|
||||||
|
assert result.success is False
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# In-memory keyDict cache eviction
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_evicts_in_memory_cache(
|
||||||
|
self, anime_service, mock_series_app
|
||||||
|
):
|
||||||
|
"""After a successful DB delete, the in-memory SerieList.keyDict
|
||||||
|
entry for that series must be removed.
|
||||||
|
|
||||||
|
The /api/anime list endpoint reads from SeriesApp.list.keyDict
|
||||||
|
via list_series_with_filters(). If the cache is not pruned, the
|
||||||
|
deleted series keeps appearing in the listing on every page
|
||||||
|
reload — exactly the Beyblade Burst bug.
|
||||||
|
"""
|
||||||
|
from src.server.database.SerieList import SerieList
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
mock_series = MagicMock()
|
||||||
|
mock_series.key = "beyblade-burst-rise"
|
||||||
|
mock_series.name = "Beyblade Burst Rise"
|
||||||
|
mock_series.folder = "Beyblade Burst Rise (2016)"
|
||||||
|
mock_series.id = 487
|
||||||
|
|
||||||
|
# Use a real SerieList instance — the same type the production
|
||||||
|
# code mutates — so the eviction actually exercises the real
|
||||||
|
# remove() method (a MagicMock would just return more mocks).
|
||||||
|
real_list = SerieList(str(mock_series_app.directory_to_search))
|
||||||
|
real_list.keyDict["beyblade-burst-rise"] = mock_series
|
||||||
|
mock_series_app.list = real_list
|
||||||
|
|
||||||
|
anime_service._websocket_service = MagicMock()
|
||||||
|
anime_service._websocket_service.broadcast_series_deleted = AsyncMock()
|
||||||
|
anime_service._websocket_service.broadcast_series_list_changed = AsyncMock()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=mock_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.delete",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=True,
|
||||||
|
):
|
||||||
|
result = await anime_service.delete_series(
|
||||||
|
key="beyblade-burst-rise",
|
||||||
|
delete_database=True,
|
||||||
|
delete_folder=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.success is True
|
||||||
|
assert "beyblade-burst-rise" not in real_list.keyDict, (
|
||||||
|
"In-memory cache still contains the deleted series — "
|
||||||
|
"/api/anime will keep returning it after a page reload"
|
||||||
|
)
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_broadcasts_series_list_changed(
|
||||||
|
self, anime_service, mock_series_app
|
||||||
|
):
|
||||||
|
"""A stronger ``series_list_changed`` broadcast fires after delete
|
||||||
|
so any connected client can re-sync without relying on the more
|
||||||
|
specific ``series_deleted`` event reaching them.
|
||||||
|
"""
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
mock_series = MagicMock()
|
||||||
|
mock_series.key = "test-key"
|
||||||
|
mock_series.name = "Test Series"
|
||||||
|
mock_series.folder = "Test Series (2023)"
|
||||||
|
mock_series.id = 1
|
||||||
|
|
||||||
|
mock_series_app.list.keyDict = {"test-key": mock_series}
|
||||||
|
|
||||||
|
anime_service._websocket_service = MagicMock()
|
||||||
|
anime_service._websocket_service.broadcast_series_deleted = AsyncMock()
|
||||||
|
anime_service._websocket_service.broadcast_series_list_changed = AsyncMock()
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=mock_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.delete",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=True,
|
||||||
|
):
|
||||||
|
await anime_service.delete_series(
|
||||||
|
key="test-key",
|
||||||
|
delete_database=True,
|
||||||
|
delete_folder=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
anime_service._websocket_service.broadcast_series_list_changed.assert_called_once()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Orphan folder recovery (DB row gone, folder still on disk)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_orphan_folder_recovery(self, anime_service, tmp_path):
|
||||||
|
"""If the DB row is gone but a matching folder is still on disk,
|
||||||
|
``delete_folder=True`` removes the orphan folder.
|
||||||
|
|
||||||
|
Reproduces the Beyblade Burst scenario: previous delete attempt
|
||||||
|
removed the DB row (delete_database=True) but the folder delete
|
||||||
|
silently failed (path math bug). Retrying with delete_folder=True
|
||||||
|
should clean up the orphan via a key-based folder scan.
|
||||||
|
"""
|
||||||
|
# Simulate the on-disk anime directory
|
||||||
|
anime_dir = tmp_path / "anime"
|
||||||
|
anime_dir.mkdir()
|
||||||
|
orphan = anime_dir / "Beyblade Burst (2016)"
|
||||||
|
orphan.mkdir()
|
||||||
|
(orphan / "episode.mp4").write_text("x")
|
||||||
|
|
||||||
|
anime_service._directory = str(anime_dir)
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
# DB lookup returns None (row already gone)
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=None,
|
||||||
|
):
|
||||||
|
result = await anime_service.delete_series(
|
||||||
|
key="beyblade-burst",
|
||||||
|
delete_database=False,
|
||||||
|
delete_folder=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Orphan folder recovered via key-match scan
|
||||||
|
assert result.deleted_folder is True, (
|
||||||
|
f"orphan recovery failed: success={result.success} "
|
||||||
|
f"folder_error={result.folder_error!r}"
|
||||||
|
)
|
||||||
|
assert result.folder_error is None
|
||||||
|
assert not orphan.exists()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_orphan_folder_no_match(
|
||||||
|
self, anime_service, tmp_path
|
||||||
|
):
|
||||||
|
"""If DB row is gone and no folder matches the key, return a
|
||||||
|
clear error rather than silently succeeding.
|
||||||
|
"""
|
||||||
|
anime_dir = tmp_path / "anime"
|
||||||
|
anime_dir.mkdir()
|
||||||
|
# Some unrelated folder that does NOT match
|
||||||
|
(anime_dir / "Different Show (2020)").mkdir()
|
||||||
|
anime_service._directory = str(anime_dir)
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=None,
|
||||||
|
):
|
||||||
|
result = await anime_service.delete_series(
|
||||||
|
key="nonexistent-key",
|
||||||
|
delete_database=False,
|
||||||
|
delete_folder=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.deleted_folder is False
|
||||||
|
assert result.folder_error is not None
|
||||||
|
assert "no folder matching" in result.folder_error.lower()
|
||||||
|
# Unrelated folder untouched
|
||||||
|
assert (anime_dir / "Different Show (2020)").exists()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_series_orphan_folder_ambiguous(
|
||||||
|
self, anime_service, tmp_path
|
||||||
|
):
|
||||||
|
"""If multiple folders match the same normalized key, refuse to
|
||||||
|
delete any of them (safe default).
|
||||||
|
"""
|
||||||
|
anime_dir = tmp_path / "anime"
|
||||||
|
anime_dir.mkdir()
|
||||||
|
(anime_dir / "Beyblade Burst (2016)").mkdir()
|
||||||
|
(anime_dir / "Beyblade Burst (2019)").mkdir() # also normalizes to "beybladeburst"
|
||||||
|
anime_service._directory = str(anime_dir)
|
||||||
|
|
||||||
|
mock_session = AsyncMock()
|
||||||
|
mock_ctx = _make_db_ctx(mock_session)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"src.server.database.connection.get_db_session",
|
||||||
|
return_value=mock_ctx,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=None,
|
||||||
|
):
|
||||||
|
result = await anime_service.delete_series(
|
||||||
|
key="beyblade-burst",
|
||||||
|
delete_database=False,
|
||||||
|
delete_folder=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ambiguous → refuse
|
||||||
|
assert result.deleted_folder is False
|
||||||
|
assert result.folder_error is not None
|
||||||
|
assert "no folder matching" in result.folder_error.lower()
|
||||||
|
# Neither folder deleted
|
||||||
|
assert (anime_dir / "Beyblade Burst (2016)").exists()
|
||||||
|
assert (anime_dir / "Beyblade Burst (2019)").exists()
|
||||||
|
|||||||
@@ -213,6 +213,34 @@ class TestIsSafePath:
|
|||||||
"/anime/Attack on Titan/Season 1/Episode 1"
|
"/anime/Attack on Titan/Season 1/Episode 1"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_relative_target_resolved_against_base(self):
|
||||||
|
"""Relative targets resolve against the base, not the process CWD.
|
||||||
|
|
||||||
|
Regression test: previously `os.path.abspath(target_path)` would
|
||||||
|
join a relative target against the process's current working
|
||||||
|
directory. When the CWD differed from `base_path` (e.g. the
|
||||||
|
FastAPI app running with CWD=/app while the anime directory is
|
||||||
|
/data), a relative folder name like "Beyblade Burst (2016)"
|
||||||
|
would be resolved to "/app/Beyblade Burst (2016)" and
|
||||||
|
incorrectly rejected as outside the base. The helper now
|
||||||
|
treats a relative target as relative to `base_path`.
|
||||||
|
"""
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
base = os.path.abspath(tmpdir)
|
||||||
|
# Simulate a process CWD different from base
|
||||||
|
old_cwd = os.getcwd()
|
||||||
|
try:
|
||||||
|
os.chdir("/")
|
||||||
|
# Relative target inside base should be safe
|
||||||
|
assert is_safe_path(base, "Beyblade Burst (2016)")
|
||||||
|
# Nested relative target should also be safe
|
||||||
|
assert is_safe_path(base, "Beyblade Burst (2016)/Season 1")
|
||||||
|
# Relative traversal (../) must still be rejected even
|
||||||
|
# when resolved against the base
|
||||||
|
assert not is_safe_path(base, "../etc/passwd")
|
||||||
|
finally:
|
||||||
|
os.chdir(old_cwd)
|
||||||
|
|
||||||
|
|
||||||
class TestCreateSafeFolder:
|
class TestCreateSafeFolder:
|
||||||
"""Test create_safe_folder function."""
|
"""Test create_safe_folder function."""
|
||||||
|
|||||||
@@ -241,28 +241,157 @@ class TestFolderNamingServiceIntegration:
|
|||||||
assert call_kwargs["folder"] == "Naruto (1999)"
|
assert call_kwargs["folder"] == "Naruto (1999)"
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_skips_when_target_folder_already_exists(
|
async def test_merges_source_into_existing_target_when_target_has_no_overlap(
|
||||||
self, tmp_path, mock_db_session, mock_series, mock_settings
|
self, tmp_path, mock_db_session, mock_series, mock_settings
|
||||||
):
|
):
|
||||||
"""If 'Naruto (1999)' already exists, rename is skipped."""
|
"""Source 'Naruto' with seasons/episodes, target 'Naruto (1999)' exists empty.
|
||||||
|
|
||||||
|
Source files are moved into target. Empty source directory is removed.
|
||||||
|
DB folder is updated to target. Result is success (renamed).
|
||||||
|
"""
|
||||||
anime_dir = tmp_path
|
anime_dir = tmp_path
|
||||||
(anime_dir / "Naruto").mkdir()
|
source = anime_dir / "Naruto"
|
||||||
(anime_dir / "Naruto (1999)").mkdir() # target already exists
|
target = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
target.mkdir()
|
||||||
|
(source / "Season 1").mkdir()
|
||||||
|
(source / "Season 1" / "ep01.mp4").touch()
|
||||||
|
(source / "Season 2").mkdir()
|
||||||
|
(source / "Season 2" / "ep01.mp4").touch()
|
||||||
|
|
||||||
series = mock_series("key1", "Naruto", 1999)
|
series = mock_series("key1", "Naruto", 1999)
|
||||||
mock_db_session.__aenter__.return_value.__aexit__.return_value = None
|
mock_db_session.__aenter__.return_value.__aexit__.return_value = None
|
||||||
|
|
||||||
with patch("src.server.services.folder_naming_service.AnimeSeriesService.get_all", new_callable=AsyncMock) as mock_get_all:
|
with patch("src.server.services.folder_naming_service.AnimeSeriesService.get_all", new_callable=AsyncMock) as mock_get_all, \
|
||||||
|
patch("src.server.services.folder_naming_service.AnimeSeriesService.get_by_key", new_callable=AsyncMock) as mock_get_by_key, \
|
||||||
|
patch("src.server.services.folder_naming_service.AnimeSeriesService.update", new_callable=AsyncMock) as mock_update, \
|
||||||
|
patch("src.server.utils.dependencies.get_series_app") as mock_get_app:
|
||||||
|
|
||||||
mock_get_all.return_value = [series]
|
mock_get_all.return_value = [series]
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 42
|
||||||
|
mock_get_by_key.return_value = db_series
|
||||||
|
|
||||||
|
app_instance = MagicMock()
|
||||||
|
app_instance.list.keyDict = {"key1": MagicMock()}
|
||||||
|
mock_get_app.return_value = app_instance
|
||||||
|
|
||||||
mock_settings.anime_directory = str(anime_dir)
|
mock_settings.anime_directory = str(anime_dir)
|
||||||
|
|
||||||
service = FolderNamingService()
|
service = FolderNamingService()
|
||||||
report = await service.run()
|
report = await service.run()
|
||||||
|
|
||||||
assert report.errors == 1
|
# Outcome: renamed (not error) — source merged into target
|
||||||
assert report.renamed == 0
|
assert report.renamed == 1
|
||||||
assert report.results[0].reason == "target folder already exists on disk"
|
assert report.errors == 0
|
||||||
assert (anime_dir / "Naruto").exists() # source not moved
|
assert report.results[0].success is True
|
||||||
|
assert report.results[0].skipped is False
|
||||||
|
assert report.results[0].new_folder == "Naruto (1999)"
|
||||||
|
|
||||||
|
# Source folder gone
|
||||||
|
assert not source.exists(), "Source folder should be removed after merge"
|
||||||
|
# Target folder has merged content
|
||||||
|
assert (target / "Season 1" / "ep01.mp4").exists()
|
||||||
|
assert (target / "Season 2" / "ep01.mp4").exists()
|
||||||
|
# DB updated
|
||||||
|
assert mock_update.call_args.kwargs["folder"] == "Naruto (1999)"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_merges_only_missing_seasons_preserving_existing_target_files(
|
||||||
|
self, tmp_path, mock_db_session, mock_series, mock_settings
|
||||||
|
):
|
||||||
|
"""Source has S01 ep01, target already has S01 ep01 (different content).
|
||||||
|
|
||||||
|
Existing target files are kept. Source's S01 ep01 is NOT overwritten.
|
||||||
|
Source's S02 (new) is moved. Empty source is removed.
|
||||||
|
"""
|
||||||
|
anime_dir = tmp_path
|
||||||
|
source = anime_dir / "Naruto"
|
||||||
|
target = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
target.mkdir()
|
||||||
|
|
||||||
|
# Target already has S01 with one episode
|
||||||
|
(target / "Season 1").mkdir()
|
||||||
|
target_existing = target / "Season 1" / "ep01.mp4"
|
||||||
|
target_existing.write_text("target-version")
|
||||||
|
|
||||||
|
# Source has S01 with same episode (different content) and S02
|
||||||
|
(source / "Season 1").mkdir()
|
||||||
|
source_conflict = source / "Season 1" / "ep01.mp4"
|
||||||
|
source_conflict.write_text("source-version")
|
||||||
|
(source / "Season 2").mkdir()
|
||||||
|
(source / "Season 2" / "ep01.mp4").touch()
|
||||||
|
|
||||||
|
series = mock_series("key1", "Naruto", 1999)
|
||||||
|
mock_db_session.__aenter__.return_value.__aexit__.return_value = None
|
||||||
|
|
||||||
|
with patch("src.server.services.folder_naming_service.AnimeSeriesService.get_all", new_callable=AsyncMock) as mock_get_all, \
|
||||||
|
patch("src.server.services.folder_naming_service.AnimeSeriesService.get_by_key", new_callable=AsyncMock) as mock_get_by_key, \
|
||||||
|
patch("src.server.services.folder_naming_service.AnimeSeriesService.update", new_callable=AsyncMock), \
|
||||||
|
patch("src.server.utils.dependencies.get_series_app") as mock_get_app:
|
||||||
|
|
||||||
|
mock_get_all.return_value = [series]
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 42
|
||||||
|
mock_get_by_key.return_value = db_series
|
||||||
|
|
||||||
|
app_instance = MagicMock()
|
||||||
|
app_instance.list.keyDict = {"key1": MagicMock()}
|
||||||
|
mock_get_app.return_value = app_instance
|
||||||
|
mock_settings.anime_directory = str(anime_dir)
|
||||||
|
|
||||||
|
service = FolderNamingService()
|
||||||
|
report = await service.run()
|
||||||
|
|
||||||
|
# Renamed (source effectively absorbed)
|
||||||
|
assert report.renamed == 1
|
||||||
|
assert not source.exists(), "Source should be removed after merge"
|
||||||
|
# Target S01 ep01 keeps the target version (not overwritten)
|
||||||
|
assert target_existing.read_text() == "target-version"
|
||||||
|
# New S02 moved in
|
||||||
|
assert (target / "Season 2" / "ep01.mp4").exists()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_removes_empty_source_folder_when_target_exists(
|
||||||
|
self, tmp_path, mock_db_session, mock_series, mock_settings
|
||||||
|
):
|
||||||
|
"""Source folder exists but is empty, target already exists.
|
||||||
|
|
||||||
|
Source should be removed silently, DB updated, success.
|
||||||
|
"""
|
||||||
|
anime_dir = tmp_path
|
||||||
|
source = anime_dir / "Naruto"
|
||||||
|
target = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
target.mkdir()
|
||||||
|
(target / "tvshow.nfo").write_text("existing nfo")
|
||||||
|
|
||||||
|
series = mock_series("key1", "Naruto", 1999)
|
||||||
|
mock_db_session.__aenter__.return_value.__aexit__.return_value = None
|
||||||
|
|
||||||
|
with patch("src.server.services.folder_naming_service.AnimeSeriesService.get_all", new_callable=AsyncMock) as mock_get_all, \
|
||||||
|
patch("src.server.services.folder_naming_service.AnimeSeriesService.get_by_key", new_callable=AsyncMock) as mock_get_by_key, \
|
||||||
|
patch("src.server.services.folder_naming_service.AnimeSeriesService.update", new_callable=AsyncMock) as mock_update, \
|
||||||
|
patch("src.server.utils.dependencies.get_series_app") as mock_get_app:
|
||||||
|
|
||||||
|
mock_get_all.return_value = [series]
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 42
|
||||||
|
mock_get_by_key.return_value = db_series
|
||||||
|
app_instance = MagicMock()
|
||||||
|
app_instance.list.keyDict = {"key1": MagicMock()}
|
||||||
|
mock_get_app.return_value = app_instance
|
||||||
|
mock_settings.anime_directory = str(anime_dir)
|
||||||
|
|
||||||
|
service = FolderNamingService()
|
||||||
|
report = await service.run()
|
||||||
|
|
||||||
|
assert report.renamed == 1
|
||||||
|
assert report.errors == 0
|
||||||
|
assert not source.exists(), "Empty source should be removed"
|
||||||
|
assert (target / "tvshow.nfo").exists(), "Target content preserved"
|
||||||
|
assert mock_update.call_args.kwargs["folder"] == "Naruto (1999)"
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_safety_guard_detects_wrong_year_in_target(self, tmp_path, mock_db_session, mock_series, mock_settings):
|
async def test_safety_guard_detects_wrong_year_in_target(self, tmp_path, mock_db_session, mock_series, mock_settings):
|
||||||
|
|||||||
242
tests/unit/test_rename_folder_if_needed.py
Normal file
242
tests/unit/test_rename_folder_if_needed.py
Normal file
@@ -0,0 +1,242 @@
|
|||||||
|
"""Tests for AnimeService.rename_folder_if_needed.
|
||||||
|
|
||||||
|
The behavior under test: when both the source folder (without year) and the
|
||||||
|
target folder (with year) exist on disk, the rename must not silently bail
|
||||||
|
out — it must merge the source into the target and remove the empty source.
|
||||||
|
This is what prevents the "Ultraman" + "Ultraman (2019)" duplicate-folder
|
||||||
|
problem reported by users.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from src.server.services.anime_service import AnimeService
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def anime_service_with_dir(tmp_path):
|
||||||
|
"""Create AnimeService pointing at a temp directory."""
|
||||||
|
mock_app = MagicMock()
|
||||||
|
mock_app.directory_to_search = str(tmp_path)
|
||||||
|
mock_app.list.keyDict = {}
|
||||||
|
progress = MagicMock()
|
||||||
|
service = AnimeService(series_app=mock_app, progress_service=progress)
|
||||||
|
return service, tmp_path
|
||||||
|
|
||||||
|
|
||||||
|
class TestRenameFolderIfNeededMerge:
|
||||||
|
"""Tests for the merge-into-existing-target behavior."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_merges_seasons_when_target_exists(
|
||||||
|
self, anime_service_with_dir
|
||||||
|
):
|
||||||
|
service, anime_dir = anime_service_with_dir
|
||||||
|
source = anime_dir / "Naruto"
|
||||||
|
target = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
(source / "Season 1").mkdir()
|
||||||
|
(source / "Season 1" / "ep01.mp4").touch()
|
||||||
|
target.mkdir()
|
||||||
|
|
||||||
|
db = AsyncMock()
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 1
|
||||||
|
db_series.folder = "Naruto"
|
||||||
|
with patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=db_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.update",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
) as mock_update:
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=db,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Outcome: rename "succeeded" (target now contains source content)
|
||||||
|
assert ok is True
|
||||||
|
assert not source.exists(), "Source should be removed after merge"
|
||||||
|
assert (target / "Season 1" / "ep01.mp4").exists()
|
||||||
|
# DB row updated to target
|
||||||
|
assert mock_update.call_args.kwargs["folder"] == "Naruto (1999)"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_does_not_overwrite_existing_target_files(
|
||||||
|
self, anime_service_with_dir
|
||||||
|
):
|
||||||
|
"""If target already has an episode file, the source copy is removed
|
||||||
|
(target version wins; no duplicate retained).
|
||||||
|
"""
|
||||||
|
service, anime_dir = anime_service_with_dir
|
||||||
|
source = anime_dir / "Naruto"
|
||||||
|
target = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
target.mkdir()
|
||||||
|
(target / "Season 1").mkdir()
|
||||||
|
target_existing = target / "Season 1" / "ep01.mp4"
|
||||||
|
target_existing.write_text("target-version")
|
||||||
|
(source / "Season 1").mkdir()
|
||||||
|
source_conflict = source / "Season 1" / "ep01.mp4"
|
||||||
|
source_conflict.write_text("source-version")
|
||||||
|
|
||||||
|
db = AsyncMock()
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 1
|
||||||
|
with patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=db_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.update",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
):
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=db,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is True
|
||||||
|
# Target version preserved
|
||||||
|
assert target_existing.read_text() == "target-version"
|
||||||
|
# Source folder removed (after merge, even with skipped conflicts)
|
||||||
|
assert not source.exists()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_removes_empty_source_when_target_exists(
|
||||||
|
self, anime_service_with_dir
|
||||||
|
):
|
||||||
|
service, anime_dir = anime_service_with_dir
|
||||||
|
source = anime_dir / "Naruto"
|
||||||
|
target = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
target.mkdir()
|
||||||
|
(target / "tvshow.nfo").write_text("kept")
|
||||||
|
|
||||||
|
db = AsyncMock()
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 1
|
||||||
|
with patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=db_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.update",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
) as mock_update:
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=db,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is True
|
||||||
|
assert not source.exists()
|
||||||
|
assert (target / "tvshow.nfo").read_text() == "kept"
|
||||||
|
assert mock_update.call_args.kwargs["folder"] == "Naruto (1999)"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_simple_rename_when_target_does_not_exist(
|
||||||
|
self, anime_service_with_dir
|
||||||
|
):
|
||||||
|
"""Regression: plain rename (no merge needed) still works."""
|
||||||
|
service, anime_dir = anime_service_with_dir
|
||||||
|
source = anime_dir / "Naruto"
|
||||||
|
source.mkdir()
|
||||||
|
(source / "Season 1").mkdir()
|
||||||
|
(source / "Season 1" / "ep01.mp4").touch()
|
||||||
|
|
||||||
|
db = AsyncMock()
|
||||||
|
db_series = MagicMock()
|
||||||
|
db_series.id = 1
|
||||||
|
with patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.get_by_key",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=db_series,
|
||||||
|
), patch(
|
||||||
|
"src.server.database.service.AnimeSeriesService.update",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
) as mock_update:
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=db,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is True
|
||||||
|
assert not source.exists()
|
||||||
|
assert (anime_dir / "Naruto (1999)" / "Season 1" / "ep01.mp4").exists()
|
||||||
|
assert mock_update.call_args.kwargs["folder"] == "Naruto (1999)"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_no_op_when_source_and_target_same(
|
||||||
|
self, anime_service_with_dir
|
||||||
|
):
|
||||||
|
"""Regression: same-name case returns False without touching disk."""
|
||||||
|
service, anime_dir = anime_service_with_dir
|
||||||
|
source = anime_dir / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto (1999)",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is False
|
||||||
|
assert source.exists()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_no_op_when_source_missing(self, anime_service_with_dir):
|
||||||
|
"""Regression: source missing on disk returns False without error."""
|
||||||
|
service, anime_dir = anime_service_with_dir
|
||||||
|
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_path_typesafe_with_string_directory(self, tmp_path):
|
||||||
|
"""Regression: directory_to_search being a string (not Path) works.
|
||||||
|
|
||||||
|
Original code did `self._directory / current_folder` which raised
|
||||||
|
TypeError when _directory was a str. This was silently swallowed
|
||||||
|
by the caller's try/except, leaving the rename undone.
|
||||||
|
"""
|
||||||
|
mock_app = MagicMock()
|
||||||
|
mock_app.directory_to_search = str(tmp_path) # string, not Path
|
||||||
|
mock_app.list.keyDict = {}
|
||||||
|
progress = MagicMock()
|
||||||
|
service = AnimeService(series_app=mock_app, progress_service=progress)
|
||||||
|
|
||||||
|
source = tmp_path / "Naruto"
|
||||||
|
target = tmp_path / "Naruto (1999)"
|
||||||
|
source.mkdir()
|
||||||
|
target.mkdir()
|
||||||
|
|
||||||
|
ok = await service.rename_folder_if_needed(
|
||||||
|
key="naruto",
|
||||||
|
current_folder="Naruto",
|
||||||
|
target_folder="Naruto (1999)",
|
||||||
|
db=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Must not raise; must succeed (merge path).
|
||||||
|
assert ok is True
|
||||||
|
assert not source.exists()
|
||||||
Reference in New Issue
Block a user