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
+6
View File
@@ -97,6 +97,12 @@ class ParseConfigTest(unittest.TestCase):
with self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN}, "media": []})
def test_media_thumbnails_switch(self) -> None:
self.assertTrue(parse_config({"server": {"token": TOKEN}}).media_thumbnails)
self.assertFalse(parse_config({"server": {"token": TOKEN}, "media": {"thumbnails": False}}).media_thumbnails)
with self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN}, "media": {"thumbnails": "oui"}})
def test_max_volume_bounds(self) -> None:
with self.assertRaises(ConfigError):
parse_config({"server": {"token": TOKEN}, "audio": {"max_volume": 3}})
+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()
+179
View File
@@ -0,0 +1,179 @@
"""Tests des miniatures (ffmpeg) : images, vidéos, pochettes, cache, refus et nettoyage. Ignorés sans ffmpeg."""
import asyncio
import os
import shutil
import struct
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from mediadeck import thumbs
from mediadeck.thumbs import Thumbnailer
FFMPEG = shutil.which("ffmpeg")
def ffmpeg(*args: str) -> bool:
assert FFMPEG
return subprocess.run([FFMPEG, "-v", "error", "-y", *args], capture_output=True).returncode == 0
def jpeg_size(path: Path) -> tuple[int, int]:
data = path.read_bytes()
assert data[:2] == b"\xff\xd8", "not a JPEG"
index = 2
while index < len(data):
marker, length = data[index + 1], struct.unpack(">H", data[index + 2 : index + 4])[0]
if marker in (0xC0, 0xC2):
height, width = struct.unpack(">HH", data[index + 5 : index + 9])
return width, height
index += 2 + length
raise AssertionError("no SOF marker")
@unittest.skipUnless(FFMPEG, "ffmpeg is required")
class ThumbnailerTest(unittest.IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls) -> None:
cls._tmp = tempfile.TemporaryDirectory()
cls.media = Path(cls._tmp.name) / "media"
cls.media.mkdir()
m = cls.media
assert ffmpeg("-f", "lavfi", "-i", "testsrc=s=1600x1200", "-frames:v", "1", str(m / "photo.jpg"))
assert ffmpeg("-f", "lavfi", "-i", "testsrc=s=400x900", "-frames:v", "1", str(m / "portrait.png"))
cls.has_video = ffmpeg("-f", "lavfi", "-i", "testsrc=d=3:s=640x360:r=10", "-pix_fmt", "yuv420p", "-c:v", "mpeg4", str(m / "clip.mp4"))
ffmpeg("-f", "lavfi", "-i", "testsrc=d=1:s=320x180:r=10", "-pix_fmt", "yuv420p", "-c:v", "mpeg4", str(m / "short.mp4"))
cls.has_cover = ffmpeg(
"-f", "lavfi", "-i", "sine=d=1", "-i", str(m / "photo.jpg"), "-map", "0:a", "-map", "1:v",
"-c:a", "flac", "-c:v", "mjpeg", "-disposition:v", "attached_pic", str(m / "withcover.flac"),
)
assert ffmpeg("-f", "lavfi", "-i", "sine=d=1", "-c:a", "flac", str(m / "nocover.flac"))
(m / "playlist.jpg").write_text("#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n")
(m / "photo.heic").write_bytes(b"not decodable here")
@classmethod
def tearDownClass(cls) -> None:
cls._tmp.cleanup()
def setUp(self) -> None:
self._cache = tempfile.TemporaryDirectory()
self.cache = Path(self._cache.name) / "thumbs"
self.thumbnailer = Thumbnailer(self.cache)
def tearDown(self) -> None:
self._cache.cleanup()
async def test_image_thumbnail_is_a_square_jpeg(self) -> None:
for source, size in (("photo.jpg", 160), ("photo.jpg", 640), ("portrait.png", 320)):
with self.subTest(source=source, size=size):
result = await self.thumbnailer.thumbnail(self.media / source, "image", size)
assert result is not None
self.assertEqual(jpeg_size(result), (size, size))
self.assertEqual(self.cache.stat().st_mode & 0o077, 0)
async def test_cache_avoids_a_second_ffmpeg_run(self) -> None:
first = await self.thumbnailer.thumbnail(self.media / "photo.jpg", "image", 160)
with mock.patch("mediadeck.thumbs.asyncio.create_subprocess_exec", side_effect=AssertionError("ffmpeg relancé")):
again = await self.thumbnailer.thumbnail(self.media / "photo.jpg", "image", 160)
self.assertEqual(first, again)
async def test_modified_file_gets_a_new_thumbnail(self) -> None:
photo = self.media / "edit.jpg"
shutil.copy(self.media / "photo.jpg", photo)
first = await self.thumbnailer.thumbnail(photo, "image", 160)
os.utime(photo, ns=(2_000_000_000, 2_000_000_000))
second = await self.thumbnailer.thumbnail(photo, "image", 160)
self.assertNotEqual(first, second)
async def test_refused_sizes_and_missing_ffmpeg(self) -> None:
self.assertIsNone(await self.thumbnailer.thumbnail(self.media / "photo.jpg", "image", 100))
with mock.patch("mediadeck.thumbs.shutil.which", return_value=None):
unavailable = Thumbnailer(self.cache)
self.assertFalse(unavailable.available)
self.assertIsNone(await unavailable.thumbnail(self.media / "photo.jpg", "image", 160))
async def test_unsupported_and_disguised_files_give_nothing(self) -> None:
# HEIC : pas de décodeur ; « playlist.jpg » : texte HLS déguisé, jamais interprété comme une liste de lecture
for name in ("photo.heic", "playlist.jpg"):
with self.subTest(name=name):
self.assertIsNone(await self.thumbnailer.thumbnail(self.media / name, "image", 160))
async def test_failure_is_remembered(self) -> None:
self.assertIsNone(await self.thumbnailer.thumbnail(self.media / "nocover.flac", "audio", 160))
self.assertEqual(len(list(self.cache.glob("*.none"))), 1)
with mock.patch("mediadeck.thumbs.asyncio.create_subprocess_exec", side_effect=AssertionError("ffmpeg relancé")):
self.assertIsNone(await self.thumbnailer.thumbnail(self.media / "nocover.flac", "audio", 160))
async def test_embedded_cover_of_a_sound_file(self) -> None:
if not self.has_cover:
self.skipTest("cannot build a FLAC with a cover")
result = await self.thumbnailer.thumbnail(self.media / "withcover.flac", "audio", 320)
assert result is not None
self.assertEqual(jpeg_size(result), (320, 320))
async def test_folder_art_is_the_fallback_for_sound_and_preferred_for_video(self) -> None:
result = await self.thumbnailer.thumbnail(self.media / "nocover.flac", "audio", 160, art=self.media / "portrait.png")
assert result is not None
self.assertEqual(jpeg_size(result), (160, 160))
async def test_video_frame_even_for_a_short_video(self) -> None:
if not self.has_video:
self.skipTest("cannot encode a test video")
for name in ("clip.mp4", "short.mp4"): # short.mp4 dure 1 s : le repli sur la première image doit servir
with self.subTest(name=name):
result = await self.thumbnailer.thumbnail(self.media / name, "video", 160)
assert result is not None
self.assertEqual(jpeg_size(result), (160, 160))
async def test_timeout_kills_ffmpeg(self) -> None:
# « sleep <arguments> » ne termine pas dans le délai : le processus doit être tué, sans miniature
with mock.patch.object(thumbs, "TIMEOUT_SECONDS", 0.05):
slow = Thumbnailer(self.cache, ffmpeg="/bin/sleep")
result = await slow.thumbnail(self.media / "photo.jpg", "image", 160)
self.assertIsNone(result)
async def test_prune_keeps_the_most_recent_files(self) -> None:
self.cache.mkdir(parents=True)
for index in range(8):
entry = self.cache / f"{index}.jpg"
entry.write_bytes(b"x")
os.utime(entry, (1000 + index, 1000 + index))
(self.cache / ".partiel.part.jpg").write_bytes(b"x")
with mock.patch.object(thumbs, "MAX_FILES", 5), mock.patch.object(thumbs, "KEEP_FILES", 3):
self.thumbnailer._prune()
self.assertEqual(sorted(entry.name for entry in self.cache.glob("[0-9]*.jpg")), ["5.jpg", "6.jpg", "7.jpg"])
self.assertTrue((self.cache / ".partiel.part.jpg").exists())
async def test_concurrency_is_bounded(self) -> None:
running = 0
peak = 0
original = Thumbnailer._run
async def counting(command: list[str]) -> bool:
nonlocal running, peak
running += 1
peak = max(peak, running)
try:
await asyncio.sleep(0.05)
return await original(command)
finally:
running -= 1
shutil.copy(self.media / "photo.jpg", self.media / "a1.jpg")
files = []
for index in range(8):
copy = self.media / f"c{index}.jpg"
shutil.copy(self.media / "photo.jpg", copy)
os.utime(copy, ns=(3_000_000_000 + index, 3_000_000_000 + index))
files.append(copy)
with mock.patch.object(Thumbnailer, "_run", staticmethod(counting)):
await asyncio.gather(*(self.thumbnailer.thumbnail(path, "image", 160) for path in files))
self.assertLessEqual(peak, thumbs.CONCURRENCY)
self.assertGreater(peak, 1)
if __name__ == "__main__":
unittest.main()
+75
View File
@@ -0,0 +1,75 @@
"""Mise en page de l'onglet Lecture dans un vrai Chromium : rien d'essentiel ne doit être coupé, quelle que soit la taille.
Régression visée : les commandes du lecteur (précédent / lecture / suivant) et la barre de volume sortaient de la zone
visible quand la fenêtre était basse (tablette avec barre de navigateur, téléphone). Ignoré sans Chromium.
"""
import json
import unittest
from aiohttp.test_utils import TestServer
from uidriver import CHROMIUM, Browser, make_app
# (largeur, hauteur) en pixels CSS : tablettes avec ou sans barre de navigateur, portrait, téléphones
SIZES = [(960, 420), (960, 480), (960, 600), (1280, 640), (1280, 800), (800, 1280), (1024, 1366), (600, 960),
(412, 915), (412, 800), (390, 844), (360, 780), (360, 640)]
# Un élément est « visible » s'il est entièrement dans le rectangle qui le contient
VISIBLE = """(() => {
const inside = (el, box) => { const r = el.getBoundingClientRect(); return r.height > 0 && r.top >= box.top - 1 && r.bottom <= box.bottom + 1; };
const byId = (id) => document.getElementById(id);
const zone = document.querySelector('#panel-player .now-playing').getBoundingClientRect();
const panels = document.querySelector('.panels').getBoundingClientRect();
const result = {};
for (const id of ['btn-prev', 'btn-play', 'btn-next', 'seek']) result[id] = inside(byId(id), zone);
result['volume-bar'] = inside(document.querySelector('.volume-bar'), panels);
result['master-volume'] = inside(byId('master-volume'), panels);
return JSON.stringify(result);
})()"""
LAST_CARD = """(() => {
const zone = document.querySelector('#panel-player .empty');
const box = zone.getBoundingClientRect();
const title = document.getElementById('last-title').getBoundingClientRect();
const art = document.querySelector('.last-art').getBoundingClientRect();
return JSON.stringify({title: title.top >= box.top - 1 && title.bottom <= box.bottom + 1, art: art.top >= box.top - 1});
})()"""
@unittest.skipUnless(CHROMIUM, "Chromium is required")
class PlayerLayoutTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self.server = TestServer(make_app())
await self.server.start_server()
self.browser = Browser()
await self.browser.start()
async def asyncTearDown(self) -> None:
await self.browser.close()
await self.server.close()
def url(self, scenario: str) -> str:
return f"http://127.0.0.1:{self.server.port}/?token={scenario}"
async def test_player_controls_and_volume_stay_visible(self) -> None:
failures = []
for width, height in SIZES:
await self.browser.open(self.url("player"), width, height)
await self.browser.wait_for("document.getElementById('track-title') && document.getElementById('track-title').textContent !== ''")
visible = json.loads(await self.browser.evaluate(VISIBLE))
failures += [f"{width}x{height}: {name} coupé" for name, ok in visible.items() if not ok]
self.assertEqual(failures, [])
async def test_last_opened_card_is_not_cut_off(self) -> None:
failures = []
for width, height in SIZES:
await self.browser.open(self.url("last"), width, height)
await self.browser.wait_for("document.getElementById('last-title') && document.getElementById('last-title').textContent !== ''")
visible = json.loads(await self.browser.evaluate(LAST_CARD))
failures += [f"{width}x{height}: {name} coupé" for name, ok in visible.items() if not ok]
self.assertEqual(failures, [])
if __name__ == "__main__":
unittest.main()
+157
View File
@@ -0,0 +1,157 @@
"""Pilote minimal de Chromium (protocole DevTools) et faux serveur de la vraie interface, pour les tests de mise en page."""
import asyncio
import json
import os
import shutil
import signal
import socket
import subprocess
import tempfile
from typing import Any
import aiohttp
from aiohttp import WSMsgType, web
from mediadeck.server import render_page, versioned_static
CHROMIUM = shutil.which("chromium") or shutil.which("chromium-browser") or shutil.which("google-chrome")
PLAYER: dict[str, Any] = {
"name": "org.mpris.MediaPlayer2.test", "identity": "Lecteur de test", "can_raise": True, "status": "Playing",
"metadata": {"title": "Concerto pour piano n°21 en do majeur, K. 467 – II. Andante", "artist": "Wolfgang Amadeus Mozart",
"album": "Les plus grands concertos", "length": 412_000_000, "art": None},
"volume": 0.8, "shuffle": False, "loop": "None", "can_play": True, "can_pause": True, "can_seek": True,
"can_next": True, "can_previous": True, "position": 131_000_000,
}
SINKS = [{"name": "hdmi", "description": "Sortie HDMI / DisplayPort", "volume": 0.62, "muted": False}]
LAST = {"name": "Un très long nom de fichier vidéo qui dépasse largement une ligne - 1080p", "type": "video", "art": None}
def state(scenario: str) -> dict[str, Any]:
players = [] if scenario == "last" else [PLAYER]
media = {"roots": [{"id": "videos", "name": "Videos"}], "thumbnails": False, "last": LAST if scenario == "last" else None}
return {
"type": "state", "version": "test",
"mpris": {"players": players, "active": PLAYER["name"] if players else None, "available": True},
"audio": {"available": True, "default": "hdmi", "max_volume": 1.0, "sinks": SINKS},
"input": {"available": True, "reason": None, "keys": [], "text": {"available": False, "reason": None}},
"system": {"power": True, "admin": True, "launchers": [], "media": media},
}
async def _websocket(request: web.Request) -> web.WebSocketResponse:
socket_ = web.WebSocketResponse()
await socket_.prepare(request)
# La page ne transmet que le jeton : il porte ici le nom du scénario (« player » ou « last »)
await socket_.send_json(state(request.query.get("token", "player")))
async for message in socket_:
if message.type == WSMsgType.ERROR:
break
return socket_
async def _index(_request: web.Request) -> web.Response:
return render_page("index.html")
def make_app() -> web.Application:
"""La vraie page et les vrais fichiers statiques (mêmes fonctions que le serveur), avec un état de démonstration."""
app = web.Application()
app.router.add_get("/", _index)
app.router.add_get("/ws", _websocket)
app.router.add_get("/static/{version}/{path:.+}", versioned_static)
return app
def free_port() -> int:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
class Browser:
"""Chromium sans interface, piloté par DevTools."""
def __init__(self) -> None:
assert CHROMIUM
self._profile = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
self._port = free_port()
self._process: subprocess.Popen[bytes] | None = None
self._session: aiohttp.ClientSession | None = None
self._socket: aiohttp.ClientWebSocketResponse | None = None
self._next_id = 0
async def start(self) -> None:
assert CHROMIUM
self._process = subprocess.Popen(
[CHROMIUM, "--headless=new", "--no-sandbox", "--disable-gpu", "--hide-scrollbars",
f"--remote-debugging-port={self._port}", f"--user-data-dir={self._profile.name}", "about:blank"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True, # groupe à part : close() termine aussi les processus enfants de Chromium
)
self._session = aiohttp.ClientSession()
for _ in range(100):
try:
async with self._session.get(f"http://127.0.0.1:{self._port}/json") as response:
pages = [page for page in await response.json() if page["type"] == "page"]
if pages:
self._socket = await self._session.ws_connect(pages[0]["webSocketDebuggerUrl"], max_msg_size=0)
return
except aiohttp.ClientError:
pass
await asyncio.sleep(0.1)
raise RuntimeError("Chromium did not start")
def signal_group(self, number: signal.Signals) -> None:
assert self._process
try:
os.killpg(self._process.pid, number)
except ProcessLookupError:
pass
async def close(self) -> None:
if self._socket:
await self._socket.close()
if self._session:
await self._session.close()
if self._process:
# Les processus enfants de Chromium écrivent encore dans le profil : on termine tout le groupe avant de le supprimer
self.signal_group(signal.SIGTERM)
try:
self._process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
self.signal_group(signal.SIGKILL) # enfants restants
self._process.wait(timeout=10)
self._profile.cleanup()
async def call(self, method: str, **params: Any) -> dict[str, Any]:
assert self._socket
self._next_id += 1
await self._socket.send_json({"id": self._next_id, "method": method, "params": params})
while True:
message = json.loads((await self._socket.receive()).data)
if message.get("id") == self._next_id:
if "error" in message:
raise RuntimeError(message["error"])
return message.get("result", {})
async def open(self, url: str, width: int, height: int) -> None:
await self.call("Emulation.setDeviceMetricsOverride", width=width, height=height, deviceScaleFactor=1, mobile=height > width)
await self.call("Page.navigate", url=url)
async def evaluate(self, expression: str) -> Any:
result = await self.call("Runtime.evaluate", expression=expression, returnByValue=True)
if "exceptionDetails" in result:
raise RuntimeError(result["exceptionDetails"])
return result["result"].get("value")
async def wait_for(self, expression: str, timeout: float = 8.0) -> None:
loop = asyncio.get_running_loop()
deadline = loop.time() + timeout
while loop.time() < deadline:
if await self.evaluate(expression):
return
await asyncio.sleep(0.1)
raise TimeoutError(expression)