Add thumbnails, name search and a title/image in the Playing tab; keep player controls visible

- Thumbnails (ffmpeg, optional): square crops of images, a frame or poster of
  videos, embedded or folder cover of sounds, cached on disk; /thumb route
  protected by the token like /art. [media] thumbnails = false disables it.
- Name search in the Media tab (server side, accents and case ignored, all
  words required, bounded by result count, scanned entries and time).
- Playing tab: title and picture for files of the library (also when the
  player gives none), and a "last opened file" card when no player runs.
- The player controls and the volume bar never leave the visible area:
  sticky controls and height breakpoints; tests/test_ui_layout.py measures
  13 window sizes in a real Chromium driven over DevTools (tests/uidriver.py).
- Static files are served under /static/<version>/ and pages are revalidated,
  so a tablet no longer keeps an old interface from its heuristic cache.
- Documentation (README fr/en, CLAUDE.md, config.example.toml, make deps).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Denis
2026-10-26 16:28:14 +01:00
parent cd4a8a797b
commit 1de5685338
18 changed files with 1628 additions and 131 deletions
+224 -2
View File
@@ -1,6 +1,8 @@
"""Tests de la bibliothèque multimédia : classification, tri, évasions de dossier (.., liens), API REST."""
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
@@ -11,7 +13,8 @@ from aiohttp.test_utils import TestClient, TestServer
from mediadeck import media
from mediadeck.config import parse_config
from mediadeck.media import MediaApi, MediaError, MediaLibrary, MediaNotFound, user_media_dirs
from mediadeck.media import Located, MediaApi, MediaError, MediaLibrary, MediaNotFound, thumb_url, user_media_dirs
from mediadeck.thumbs import Thumbnailer
TOKEN = "m" * 32
AUTH = {"Authorization": f"Bearer {TOKEN}"}
@@ -67,6 +70,16 @@ class ListingTest(LibraryCase):
["CD 2", "CD 10", "Piste 1.mp3", "piste 2.mp3", "piste 10.mp3"],
)
def test_images_carry_their_modification_date_for_thumbnail_caching(self) -> None:
touch(self.root / "a.jpg")
touch(self.root / "b.mp3")
(self.root / "Dossier").mkdir()
os.utime(self.root / "a.jpg", (1_700_000_000, 1_700_000_000))
entries = {entry["name"]: entry for entry in self.library.list("musique", "")["entries"]}
self.assertEqual(entries["a.jpg"], {"name": "a.jpg", "kind": "image", "v": 1_700_000_000})
self.assertEqual(entries["b.mp3"], {"name": "b.mp3", "kind": "audio"})
self.assertEqual(entries["Dossier"], {"name": "Dossier", "kind": "dir"})
def test_subfolder_and_parent(self) -> None:
touch(self.root / "Rock" / "Live" / "a.mp3")
listing = self.library.list("musique", "Rock/Live")
@@ -193,7 +206,7 @@ class RootsTest(unittest.TestCase):
self.assertEqual([root["name"] for root in library.snapshot()["roots"]], ["Vidéos", "Vidéos", "Mes Images!"])
def test_empty_list_disables_the_library(self) -> None:
self.assertEqual(MediaLibrary([]).snapshot(), {"roots": []})
self.assertEqual(MediaLibrary([]).snapshot(), {"roots": [], "thumbnails": False, "last": None})
def test_user_dirs_from_xdg_and_defaults(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
@@ -261,5 +274,214 @@ class MediaApiTest(unittest.IsolatedAsyncioTestCase):
self.assertIn("error", await response.json())
class SearchTest(LibraryCase):
def setUp(self) -> None:
super().setUp()
for name in ("Rock/Live/Été 1980.mp3", "Rock/studio.flac", "Rock/été.txt", "Jazz/Ete indien.mp3", "Films/Été meurtrier.mkv",
"Photos/ete-2020.JPG", ".caché/ete.mp3", "Rock/.ete-cache.mp3"):
touch(self.root / name)
(self.root / "Été" / "Sous-dossier").mkdir(parents=True)
def found(self, result: dict) -> list[tuple[str, str, str]]:
return [(entry["folder"], entry["name"], entry["kind"]) for entry in result["entries"]]
def test_matches_ignore_case_and_accents_and_need_every_word(self) -> None:
result = self.library.search("ETE", "musique", "")
self.assertEqual(
self.found(result),
[("", "Été", "dir"), ("Films", "Été meurtrier.mkv", "video"), ("Jazz", "Ete indien.mp3", "audio"),
("Photos", "ete-2020.JPG", "image"), ("Rock/Live", "Été 1980.mp3", "audio")],
)
self.assertEqual(self.found(self.library.search("été indien", "musique")), [("Jazz", "Ete indien.mp3", "audio")])
self.assertEqual(self.found(self.library.search("indien 1980", "musique")), [])
def test_non_media_hidden_and_escaping_entries_are_never_found(self) -> None:
os.symlink(self.outside, self.root / "dehors-ete")
os.symlink(self.outside / "private.mp3", self.root / "lien-ete.mp3")
result = self.found(self.library.search("ete", "musique"))
names = [name for _folder, name, _kind in result]
for forbidden in ("été.txt", "ete.mp3", ".ete-cache.mp3", "dehors-ete", "lien-ete.mp3", "private.mp3"):
self.assertNotIn(forbidden, names)
def test_search_is_scoped_to_the_folder_and_its_subfolders(self) -> None:
self.assertEqual(self.found(self.library.search("ete", "musique", "Rock")), [("Rock/Live", "Été 1980.mp3", "audio")])
with self.assertRaises(MediaError):
self.library.search("ete", "musique", "Jazz/Ete indien.mp3")
with self.assertRaises(MediaError):
self.library.search("ete", "musique", "..")
def test_all_roots_when_none_is_given(self) -> None:
other = Path(self._tmp.name).resolve() / "Videos"
touch(other / "Été au ciné.mp4")
library = MediaLibrary([self.root, other])
result = library.search("été")
self.assertEqual({entry["root"] for entry in result["entries"]}, {"musique", "videos"})
self.assertIsNone(result["root"])
def test_image_results_carry_their_version(self) -> None:
os.utime(self.root / "Photos" / "ete-2020.JPG", (1_700_000_000, 1_700_000_000))
result = self.library.search("2020", "musique")
self.assertEqual(result["entries"], [
{"name": "ete-2020.JPG", "kind": "image", "v": 1_700_000_000, "root": "musique", "folder": "Photos"}])
def test_symlinked_folders_are_not_followed(self) -> None:
os.symlink(self.root, self.root / "Rock" / "boucle") # boucle vers la racine
result = self.library.search("studio", "musique")
self.assertEqual(self.found(result), [("Rock", "studio.flac", "audio")])
def test_invalid_queries(self) -> None:
for query in (None, 5, "", "a", " é ", "x" * 101, "a b c d e f g h i"):
with self.subTest(query=query), self.assertRaises(MediaError):
self.library.search(query, "musique")
with self.assertRaises(MediaNotFound):
self.library.search("ete", "nope")
def test_limits(self) -> None:
with mock.patch.object(media, "MAX_RESULTS", 2):
result = self.library.search("ete", "musique")
self.assertEqual((len(result["entries"]), result["truncated"]), (2, True))
with mock.patch.object(media, "SEARCH_SECONDS", -1):
self.assertTrue(self.library.search("ete", "musique")["truncated"])
with mock.patch.object(media, "MAX_SEARCH_SCANNED", 3):
self.assertTrue(self.library.search("ete", "musique")["truncated"])
class LocateAndArtTest(LibraryCase):
def test_locate_a_file_by_its_absolute_path(self) -> None:
file = touch(self.root / "Rock" / "été.mp3")
located = self.library.locate(file)
self.assertEqual(located, Located("musique", "Rock/été.mp3", "audio", file))
os.symlink(file, self.root / "alias.mp3")
again = self.library.locate(self.root / "alias.mp3")
assert again is not None
self.assertEqual(again.relative, "Rock/été.mp3")
def test_locate_refuses_everything_else(self) -> None:
touch(self.root / "notes.txt")
touch(self.root / ".caché" / "a.mp3")
for path in (self.outside / "private.mp3", self.root / "notes.txt", self.root / ".caché" / "a.mp3", self.root / "absent.mp3", self.root):
with self.subTest(path=path):
self.assertIsNone(self.library.locate(path))
def test_enrich_adds_a_title_and_an_image_to_a_library_file(self) -> None:
file = touch(self.root / "Films" / "Mon film (2020).mkv")
library = MediaLibrary([self.root], thumbnails=True)
metadata = {"url": file.as_uri(), "title": "", "art": None}
library.enrich(metadata)
self.assertEqual(metadata["title"], "Mon film (2020)")
self.assertTrue(metadata["art"].startswith("/thumb?root=musique&path=Films/Mon%20film%20%282020%29.mkv&size=640&v="))
def test_enrich_keeps_what_the_player_provides(self) -> None:
file = touch(self.root / "a.mp3")
library = MediaLibrary([self.root], thumbnails=True)
metadata = {"url": file.as_uri(), "title": "Vrai titre", "art": "/art?x"}
library.enrich(metadata)
self.assertEqual((metadata["title"], metadata["art"]), ("Vrai titre", "/art?x"))
def test_enrich_ignores_foreign_urls_and_works_without_thumbnails(self) -> None:
library = MediaLibrary([self.root], thumbnails=False)
for url in ("https://example.com/a.mp3", (self.outside / "private.mp3").as_uri(), "file:///absent.mp3", None, 5):
metadata: dict = {"url": url, "title": ""}
library.enrich(metadata)
self.assertEqual(metadata, {"url": url, "title": ""}, url)
file = touch(self.root / "b.mp3")
metadata = {"url": file.as_uri(), "title": ""}
library.enrich(metadata)
self.assertEqual(metadata["title"], "b")
self.assertNotIn("art", metadata)
def test_remember_feeds_the_snapshot(self) -> None:
file = touch(self.root / "Rock" / "a.mp3")
library = MediaLibrary([self.root], thumbnails=True)
self.assertIsNone(library.snapshot()["last"])
library.remember(library.resolve_file("musique", "Rock/a.mp3"))
last = library.snapshot()["last"]
self.assertEqual((last["name"], last["type"]), ("a", "audio"))
self.assertIn("/thumb?root=musique&path=Rock/a.mp3&size=640", last["art"])
self.assertTrue(file.exists())
def test_find_art_prefers_the_file_name_then_generic_names(self) -> None:
file = touch(self.root / "Film" / "Mon film.mkv")
self.assertIsNone(self.library.find_art("musique", file))
touch(self.root / "Film" / "folder.png")
self.assertEqual(self.library.find_art("musique", file), self.root / "Film" / "folder.png")
touch(self.root / "Film" / "COVER.JPG")
self.assertEqual(self.library.find_art("musique", file), self.root / "Film" / "COVER.JPG")
touch(self.root / "Film" / "Mon film-poster.jpg")
self.assertEqual(self.library.find_art("musique", file), self.root / "Film" / "Mon film-poster.jpg")
touch(self.root / "Film" / "Mon film.jpg")
self.assertEqual(self.library.find_art("musique", file), self.root / "Film" / "Mon film.jpg")
self.assertIsNone(self.library.find_art("nope", file))
def test_find_art_never_follows_a_link_out_of_the_root(self) -> None:
file = touch(self.root / "a.mp3")
os.symlink(self.outside / "private.mp3", self.root / "cover.jpg")
self.assertIsNone(self.library.find_art("musique", file))
def test_thumb_url_is_quoted(self) -> None:
self.assertEqual(thumb_url("r", "a b/é&c.jpg", 160, 7), "/thumb?root=r&path=a%20b/%C3%A9%26c.jpg&size=160&v=7")
class SearchAndThumbApiTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.root = Path(self._tmp.name).resolve() / "Images"
touch(self.root / "Vacances" / "plage été.png")
touch(self.root / "notes.txt")
self.cache = Path(self._tmp.name) / "cache"
self.config = parse_config({"server": {"token": TOKEN}})
self.library = MediaLibrary([self.root], thumbnails=True)
async def asyncTearDown(self) -> None:
self._tmp.cleanup()
async def client(self, thumbnailer: Thumbnailer | None) -> TestClient:
app = web.Application()
MediaApi(self.config, self.library, thumbnailer).add_routes(app)
client = TestClient(TestServer(app))
await client.start_server()
self.addAsyncCleanup(client.close)
return client
async def test_search_route(self) -> None:
client = await self.client(None)
for headers in ({}, {"Authorization": "Bearer nope"}):
self.assertEqual((await client.get("/api/media/search?q=ete&root=images", headers=headers)).status, 401)
self.assertEqual((await client.get(f"/api/media/search?q=ete&token={TOKEN}")).status, 401)
data = await (await client.get("/api/media/search", params={"q": "ÉTÉ", "root": "images"}, headers=AUTH)).json()
self.assertEqual([(e["folder"], e["name"]) for e in data["entries"]], [("Vacances", "plage été.png")])
for query, status in (("q=a&root=images", 400), ("root=images", 400), ("q=ete&root=nope", 404), ("q=ete&root=images&path=..", 400)):
self.assertEqual((await client.get(f"/api/media/search?{query}", headers=AUTH)).status, status, query)
async def test_thumb_route_is_only_mounted_with_ffmpeg(self) -> None:
client = await self.client(None)
self.assertEqual((await client.get(f"/thumb?root=images&path=x&size=160&token={TOKEN}")).status, 404)
@unittest.skipUnless(shutil.which("ffmpeg"), "ffmpeg is required")
async def test_thumb_route(self) -> None:
subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=s=300x200", "-frames:v", "1",
str(self.root / "Vacances" / "plage été.png")], check=True)
client = await self.client(Thumbnailer(self.cache))
good = "root=images&path=Vacances/plage%20%C3%A9t%C3%A9.png&size=160"
self.assertEqual((await client.get(f"/thumb?{good}")).status, 401)
self.assertEqual((await client.get(f"/thumb?{good}&token=nope")).status, 401)
self.assertEqual((await client.get(f"/thumb?{good}", headers=AUTH)).status, 401) # l'en-tête ne suffit pas ici
response = await client.get(f"/thumb?{good}&token={TOKEN}")
self.assertEqual(response.status, 200)
self.assertEqual(response.headers["Content-Type"], "image/jpeg")
self.assertEqual(response.headers["Cache-Control"], "private, max-age=86400")
self.assertEqual((await response.read())[:2], b"\xff\xd8")
for query, status in (
("root=images&path=Vacances/plage%20%C3%A9t%C3%A9.png&size=100", 400),
("root=images&path=Vacances/plage%20%C3%A9t%C3%A9.png&size=abc", 400),
("root=images&path=..%2F..%2Fetc%2Fpasswd&size=160", 400),
("root=images&path=notes.txt&size=160", 400),
("root=images&path=absent.png&size=160", 404),
("root=nope&path=a.png&size=160", 404),
):
response = await client.get(f"/thumb?{query}&token={TOKEN}")
self.assertEqual(response.status, status, query)
if __name__ == "__main__":
unittest.main()