mirror of
https://github.com/deunix-educ/mediadeck.git
synced 2026-11-25 04:39:42 +01:00
Add the Media tab: browse sound, image and video files and open them on the PC
Media tab (needs at least one folder, hidden otherwise): - Folders from [media] roots in config.toml, default = the user's Music, Videos and Pictures (XDG, never $HOME); [] disables the tab - Icons per type, subfolders, breadcrumb, back, refresh, All/Sounds/Images/ Videos filter; a tap opens the file on the PC (WebSocket system/open_media) - Three special launchers (audio, image, video), editable on /admin: system default (gio open), installed application (gio launch) or a raw command (allow_custom_command); the file path is appended as the last argument - The client never sends an absolute path: (root, relative path) is resolved server side; refuses "..", hidden entries, symlinks leaving the root, and anything but known media extensions (a script renamed .mp3 is refused) - GET /api/media (Bearer token), listing runs in a thread, 1000 entries max Interface cache: pages are revalidated (Cache-Control: no-cache) and static files are served under /static/<version>/ (immutable cache), so a tablet can no longer keep an old interface after an update. Reproduced and verified: opening the same link serves the cached page, one refresh fixes it for good. Refactors: restapi.py (shared REST helpers), AppPicker (shared by the launcher and opener forms on /admin). Tests: 159 (library escapes, openers, admin API, config, cache headers). Also checked end to end with a real server (fake gio recording its arguments) and headless Chromium. Not tried on the real tablet. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -143,6 +143,58 @@ class AdminApiTest(AdminApiCase):
|
||||
self.assertEqual(unknown.status, 400)
|
||||
|
||||
|
||||
class OpenersApiTest(AdminApiCase):
|
||||
async def test_token_required(self) -> None:
|
||||
for method, path in (("GET", "/api/media/openers"), ("PUT", "/api/media/openers/audio")):
|
||||
for headers in ({}, {"Authorization": "Bearer nope"}, {"Authorization": TOKEN}):
|
||||
response = await self.client.request(method, path, headers=headers, json={"kind": "default"})
|
||||
self.assertEqual(response.status, 401, (method, headers))
|
||||
|
||||
async def test_list_defaults_to_the_system_application(self) -> None:
|
||||
data = await (await self.client.get("/api/media/openers", headers=AUTH)).json()
|
||||
self.assertEqual([opener["type"] for opener in data["openers"]], ["audio", "image", "video"])
|
||||
self.assertTrue(all(opener["kind"] == "default" for opener in data["openers"]))
|
||||
self.assertEqual(data["kinds"], ["default", "app", "command"])
|
||||
self.assertFalse(data["allow_command"])
|
||||
|
||||
async def test_set_and_read_back(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
(Path(tmp) / "vlc.desktop").write_text("[Desktop Entry]\nType=Application\nName=VLC\nExec=vlc\n")
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]):
|
||||
response = await self.client.put(
|
||||
"/api/media/openers/video", headers=AUTH, json={"kind": "app", "spec": {"desktop_id": "vlc.desktop"}}
|
||||
)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(await response.json(), {"type": "video", "kind": "app", "spec": {"desktop_id": "vlc.desktop"}})
|
||||
data = await (await self.client.get("/api/media/openers", headers=AUTH)).json()
|
||||
self.assertEqual({o["type"]: o["kind"] for o in data["openers"]}, {"audio": "default", "image": "default", "video": "app"})
|
||||
back = await self.client.put("/api/media/openers/video", headers=AUTH, json={"kind": "default"})
|
||||
self.assertEqual((await back.json())["kind"], "default")
|
||||
|
||||
async def test_errors(self) -> None:
|
||||
unknown_type = await self.client.put("/api/media/openers/document", headers=AUTH, json={"kind": "default"})
|
||||
self.assertEqual(unknown_type.status, 404)
|
||||
for body in ({"kind": "web"}, {"kind": "app", "spec": {"desktop_id": "nope.desktop"}}, {}):
|
||||
response = await self.client.put("/api/media/openers/audio", headers=AUTH, json=body)
|
||||
self.assertEqual(response.status, 400, body)
|
||||
forbidden = await self.client.put(
|
||||
"/api/media/openers/audio", headers=AUTH, json={"kind": "command", "spec": {"argv": ["mpv"]}}
|
||||
)
|
||||
self.assertEqual(forbidden.status, 403)
|
||||
self.assertTrue(all(opener.kind == "default" for opener in self.store.openers().values()))
|
||||
|
||||
|
||||
class OpenersApiCommandAllowedTest(AdminApiCase):
|
||||
allow_command = True
|
||||
|
||||
async def test_command_opener(self) -> None:
|
||||
response = await self.client.put(
|
||||
"/api/media/openers/video", headers=AUTH, json={"kind": "command", "spec": {"argv": ["mpv", "--fs"]}}
|
||||
)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(self.store.openers()["video"].spec, {"argv": ["mpv", "--fs"]})
|
||||
|
||||
|
||||
class AdminApiCommandAllowedTest(AdminApiCase):
|
||||
allow_command = True
|
||||
|
||||
|
||||
@@ -84,6 +84,19 @@ class ParseConfigTest(unittest.TestCase):
|
||||
with self.subTest(server=server), self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN, **server}})
|
||||
|
||||
def test_media_roots(self) -> None:
|
||||
self.assertIsNone(parse_config({"server": {"token": TOKEN}}).media_roots) # défaut : dossiers de l'utilisateur
|
||||
self.assertEqual(parse_config({"server": {"token": TOKEN}, "media": {"roots": []}}).media_roots, ())
|
||||
config = parse_config({"server": {"token": TOKEN}, "media": {"roots": ["~/Musique", "/srv/films", "~/Musique"]}})
|
||||
self.assertEqual(config.media_roots, (Path.home() / "Musique", Path("/srv/films")))
|
||||
|
||||
def test_media_roots_are_validated(self) -> None:
|
||||
for roots in ("~/Musique", ["relatif/dossier"], [""], [3], ["~/a", None]):
|
||||
with self.subTest(roots=roots), self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN}, "media": {"roots": roots}})
|
||||
with self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN}, "media": []})
|
||||
|
||||
def test_max_volume_bounds(self) -> None:
|
||||
with self.assertRaises(ConfigError):
|
||||
parse_config({"server": {"token": TOKEN}, "audio": {"max_volume": 3}})
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Tests des en-têtes de sécurité et de cache posés par le serveur."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from mediadeck.server import CSP, STATIC_DIR, WEB_DIR, render_page, security_headers, static_version, versioned_static
|
||||
|
||||
|
||||
async def page(_request: web.Request) -> web.Response:
|
||||
return web.Response(text="ok")
|
||||
|
||||
|
||||
async def art(_request: web.Request) -> web.Response:
|
||||
return web.Response(text="x", headers={"Cache-Control": "private, max-age=3600"})
|
||||
|
||||
|
||||
class HeadersTest(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
(Path(self._tmp.name) / "app.js").write_text("console.log(1)")
|
||||
app = web.Application(middlewares=[security_headers])
|
||||
app.router.add_static("/static", self._tmp.name)
|
||||
app.router.add_get("/page", page)
|
||||
app.router.add_get("/art", art)
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self) -> None:
|
||||
await self.client.close()
|
||||
self._tmp.cleanup()
|
||||
|
||||
async def test_pages_and_static_files_are_revalidated(self) -> None:
|
||||
for path in ("/page", "/static/app.js"):
|
||||
response = await self.client.get(path)
|
||||
self.assertEqual(response.headers["Cache-Control"], "no-cache", path)
|
||||
self.assertEqual(response.headers["Content-Security-Policy"], CSP)
|
||||
|
||||
async def test_conditional_request_gets_a_304(self) -> None:
|
||||
first = await self.client.get("/static/app.js")
|
||||
etag = first.headers["ETag"]
|
||||
again = await self.client.get("/static/app.js", headers={"If-None-Match": etag})
|
||||
self.assertEqual(again.status, 304)
|
||||
|
||||
async def test_existing_cache_policy_is_kept(self) -> None:
|
||||
response = await self.client.get("/art")
|
||||
self.assertEqual(response.headers["Cache-Control"], "private, max-age=3600")
|
||||
|
||||
|
||||
class StaticVersionTest(unittest.TestCase):
|
||||
def test_version_follows_the_files(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = Path(tmp)
|
||||
(directory / "app.js").write_text("a")
|
||||
first = static_version(directory)
|
||||
self.assertEqual(static_version(directory), first)
|
||||
(directory / "app.js").write_text("b") # même taille : la date suffit à changer l'empreinte
|
||||
os.utime(directory / "app.js", ns=(2_000_000_000, 2_000_000_000))
|
||||
second = static_version(directory)
|
||||
self.assertNotEqual(second, first)
|
||||
(directory / "style.css").write_text("c")
|
||||
self.assertNotEqual(static_version(directory), second)
|
||||
|
||||
def test_pages_point_to_versioned_files(self) -> None:
|
||||
for name in ("index.html", "admin.html"):
|
||||
html = render_page(name).text or ""
|
||||
version = static_version()
|
||||
self.assertNotRegex(html, r'"/static/(?!%s/)' % version, name)
|
||||
self.assertIn(f'"/static/{version}/', html)
|
||||
self.assertEqual(len(re.findall(r'"/static/', html)), len(re.findall(rf'"/static/{version}/', html)), name)
|
||||
|
||||
def test_html_source_files_only_reference_static_with_a_leading_slash_quote(self) -> None:
|
||||
# render_page remplace '"/static/' : toute autre forme de référence échapperait au versionnement
|
||||
for name in ("index.html", "admin.html"):
|
||||
source = (WEB_DIR / name).read_text(encoding="utf-8")
|
||||
self.assertEqual(source.count("/static/"), source.count('"/static/'), name)
|
||||
|
||||
|
||||
class VersionedStaticTest(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self) -> None:
|
||||
app = web.Application(middlewares=[security_headers])
|
||||
app.router.add_get("/static/{version}/{path:.+}", versioned_static)
|
||||
app.router.add_static("/static", STATIC_DIR, show_index=False, follow_symlinks=False)
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self) -> None:
|
||||
await self.client.close()
|
||||
|
||||
async def test_versioned_url_serves_the_current_file_with_an_immutable_cache(self) -> None:
|
||||
response = await self.client.get("/static/whatever/app.js")
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.headers["Cache-Control"], "public, max-age=31536000, immutable")
|
||||
self.assertIn("class MediaPanel", await response.text())
|
||||
|
||||
async def test_relative_imports_resolve_under_the_same_version(self) -> None:
|
||||
response = await self.client.get("/static/whatever/common.js")
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertIn("class I18n", await response.text())
|
||||
|
||||
async def test_old_addresses_still_work_but_are_revalidated(self) -> None:
|
||||
response = await self.client.get("/static/app.js")
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.headers["Cache-Control"], "no-cache")
|
||||
|
||||
async def test_nothing_outside_the_static_folder(self) -> None:
|
||||
for path in (
|
||||
"/static/v/..%2F..%2Fserver.py", "/static/v/%2e%2e/%2e%2e/server.py", "/static/v/../../server.py",
|
||||
"/static/v/%2Fetc%2Fpasswd", "/static/v/absent.js", "/static/v/",
|
||||
):
|
||||
response = await self.client.get(path)
|
||||
self.assertIn(response.status, (400, 404), path)
|
||||
self.assertNotIn("import", (await response.text())[:200], path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -13,8 +13,11 @@ from mediadeck.launchers import (
|
||||
LauncherError,
|
||||
LauncherNotFound,
|
||||
LauncherStore,
|
||||
OpenerEntry,
|
||||
build_argv,
|
||||
build_open_argv,
|
||||
validate,
|
||||
validate_opener,
|
||||
)
|
||||
|
||||
WEB = {"label": "Arte", "icon": "tv", "kind": "web", "spec": {"url": "https://www.arte.tv/fr/", "browser": "chromium"}}
|
||||
@@ -185,6 +188,112 @@ class BuildArgvTest(unittest.TestCase):
|
||||
build_argv(entry)
|
||||
|
||||
|
||||
class OpenerStoreTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self._tmp.name) / "launchers.db"
|
||||
self.store = LauncherStore(self.path)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.store.close()
|
||||
self._tmp.cleanup()
|
||||
|
||||
def test_system_default_until_one_is_chosen(self) -> None:
|
||||
openers = self.store.openers()
|
||||
self.assertEqual(list(openers), ["audio", "image", "video"])
|
||||
self.assertTrue(all(opener.kind == "default" and opener.spec == {} for opener in openers.values()))
|
||||
|
||||
def test_set_replaces_and_survives_reopening(self) -> None:
|
||||
self.store.set_opener("video", "app", {"desktop_id": "vlc.desktop"})
|
||||
self.store.set_opener("video", "command", {"argv": ["mpv", "--fs"]})
|
||||
self.store.close()
|
||||
self.store = LauncherStore(self.path)
|
||||
openers = self.store.openers()
|
||||
self.assertEqual((openers["video"].kind, openers["video"].spec), ("command", {"argv": ["mpv", "--fs"]}))
|
||||
self.assertEqual(openers["audio"].kind, "default")
|
||||
|
||||
def test_database_refuses_unknown_types(self) -> None:
|
||||
with self.assertRaises(Exception):
|
||||
self.store.set_opener("document", "default", {})
|
||||
|
||||
def test_opener_table_added_to_an_existing_database(self) -> None:
|
||||
# Base créée avant les lecteurs : seule la table des lanceurs existe
|
||||
self.store.close()
|
||||
import sqlite3
|
||||
|
||||
db = sqlite3.connect(self.path)
|
||||
db.execute("DROP TABLE media_openers")
|
||||
db.commit()
|
||||
db.close()
|
||||
self.store = LauncherStore(self.path)
|
||||
self.assertEqual(self.store.openers()["audio"].kind, "default")
|
||||
|
||||
|
||||
class ValidateOpenerTest(unittest.TestCase):
|
||||
def test_default_needs_no_spec(self) -> None:
|
||||
self.assertEqual(validate_opener("audio", {"kind": "default"}, allow_command=False), ("audio", "default", {}))
|
||||
# Un spec fourni avec « default » est ignoré : rien d'autre n'est enregistré
|
||||
self.assertEqual(
|
||||
validate_opener("audio", {"kind": "default", "spec": {"argv": ["rm"]}}, allow_command=False),
|
||||
("audio", "default", {}),
|
||||
)
|
||||
|
||||
def test_app_must_be_installed(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
write_desktop(Path(tmp), "vlc.desktop", "vlc")
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]):
|
||||
self.assertEqual(
|
||||
validate_opener("video", {"kind": "app", "spec": {"desktop_id": "vlc.desktop"}}, allow_command=False),
|
||||
("video", "app", {"desktop_id": "vlc.desktop"}),
|
||||
)
|
||||
with self.assertRaises(LauncherError):
|
||||
validate_opener("video", {"kind": "app", "spec": {"desktop_id": "../vlc.desktop"}}, allow_command=False)
|
||||
|
||||
def test_command_needs_the_config_switch(self) -> None:
|
||||
data = {"kind": "command", "spec": {"argv": ["mpv", "--fs"]}}
|
||||
with self.assertRaises(CommandNotAllowed):
|
||||
validate_opener("video", data, allow_command=False)
|
||||
self.assertEqual(validate_opener("video", data, allow_command=True), ("video", "command", {"argv": ["mpv", "--fs"]}))
|
||||
# Une commande déjà enregistrée peut être « réenregistrée » telle quelle
|
||||
current = OpenerEntry("video", "command", {"argv": ["mpv", "--fs"]})
|
||||
self.assertEqual(validate_opener("video", data, allow_command=False, current=current)[1], "command")
|
||||
with self.assertRaises(CommandNotAllowed):
|
||||
validate_opener("video", {"kind": "command", "spec": {"argv": ["evil"]}}, allow_command=False, current=current)
|
||||
|
||||
def test_rejected_input(self) -> None:
|
||||
with self.assertRaises(LauncherNotFound):
|
||||
validate_opener("document", {"kind": "default"}, allow_command=True)
|
||||
for data in (None, [], {}, {"kind": "web"}, {"kind": "command"}, {"kind": "command", "spec": {"argv": []}}):
|
||||
with self.subTest(data=data), self.assertRaises(LauncherError):
|
||||
validate_opener("audio", data, allow_command=True)
|
||||
|
||||
|
||||
class BuildOpenArgvTest(unittest.TestCase):
|
||||
PATH = Path("/home/u/Musique/-weird name.mp3")
|
||||
|
||||
def test_default_uses_gio_open(self) -> None:
|
||||
with mock.patch("mediadeck.launchers.shutil.which", return_value="/usr/bin/gio"):
|
||||
self.assertEqual(build_open_argv(OpenerEntry("audio", "default", {}), self.PATH), ["gio", "open", str(self.PATH)])
|
||||
with mock.patch("mediadeck.launchers.shutil.which", return_value=None), self.assertRaises(LauncherError):
|
||||
build_open_argv(OpenerEntry("audio", "default", {}), self.PATH)
|
||||
|
||||
def test_app_uses_gio_launch_with_the_file(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
write_desktop(Path(tmp), "vlc.desktop", "vlc")
|
||||
opener = OpenerEntry("video", "app", {"desktop_id": "vlc.desktop"})
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp)]), \
|
||||
mock.patch("mediadeck.launchers.shutil.which", return_value="/usr/bin/gio"):
|
||||
self.assertEqual(build_open_argv(opener, self.PATH), ["gio", "launch", str(Path(tmp) / "vlc.desktop"), str(self.PATH)])
|
||||
with mock.patch("mediadeck.launchers.desktop_dirs", return_value=[Path(tmp) / "vide"]), self.assertRaises(LauncherError):
|
||||
build_open_argv(opener, self.PATH)
|
||||
|
||||
def test_command_gets_the_path_as_last_argument_without_a_shell(self) -> None:
|
||||
opener = OpenerEntry("video", "command", {"argv": ["mpv", "--fs"]})
|
||||
self.assertEqual(build_open_argv(opener, self.PATH), ["mpv", "--fs", str(self.PATH)])
|
||||
tricky = Path("/home/u/V/$(reboot); rm -rf x.mkv")
|
||||
self.assertEqual(build_open_argv(opener, tricky)[-1], str(tricky))
|
||||
|
||||
|
||||
class DesktopAppsTest(unittest.TestCase):
|
||||
def test_listing_filters_and_precedence(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Tests de la bibliothèque multimédia : classification, tri, évasions de dossier (.., liens), API REST."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from aiohttp import web
|
||||
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
|
||||
|
||||
TOKEN = "m" * 32
|
||||
AUTH = {"Authorization": f"Bearer {TOKEN}"}
|
||||
|
||||
|
||||
def touch(path: Path, content: bytes = b"x") -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(content)
|
||||
return path
|
||||
|
||||
|
||||
class LibraryCase(unittest.TestCase):
|
||||
"""Un dossier « Musique » dans un répertoire temporaire, et un fichier secret hors de la racine."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
base = Path(self._tmp.name).resolve()
|
||||
self.root = base / "Musique"
|
||||
self.outside = base / "secret"
|
||||
touch(self.outside / "private.mp3")
|
||||
touch(self.outside / "private.sh")
|
||||
self.root.mkdir()
|
||||
self.library = MediaLibrary([self.root])
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self._tmp.cleanup()
|
||||
|
||||
def names(self, listing: dict) -> list[tuple[str, str]]:
|
||||
return [(entry["name"], entry["kind"]) for entry in listing["entries"]]
|
||||
|
||||
|
||||
class ListingTest(LibraryCase):
|
||||
def test_classifies_by_extension_and_hides_the_rest(self) -> None:
|
||||
for name in ("a.mp3", "b.FLAC", "c.jpg", "d.png", "e.mkv", "f.MP4", "g.txt", "h.sh", "i.desktop", ".hidden.mp3", "j.ts"):
|
||||
touch(self.root / name)
|
||||
(self.root / "Albums").mkdir()
|
||||
(self.root / ".cache").mkdir()
|
||||
listing = self.library.list("musique", "")
|
||||
self.assertEqual(
|
||||
self.names(listing),
|
||||
[("Albums", "dir"), ("a.mp3", "audio"), ("b.FLAC", "audio"), ("c.jpg", "image"), ("d.png", "image"),
|
||||
("e.mkv", "video"), ("f.MP4", "video")],
|
||||
)
|
||||
self.assertFalse(listing["truncated"])
|
||||
|
||||
def test_folders_first_then_natural_order(self) -> None:
|
||||
for name in ("piste 10.mp3", "piste 2.mp3", "Piste 1.mp3"):
|
||||
touch(self.root / name)
|
||||
for name in ("CD 10", "CD 2"):
|
||||
(self.root / name).mkdir()
|
||||
self.assertEqual(
|
||||
[name for name, _ in self.names(self.library.list("musique", ""))],
|
||||
["CD 2", "CD 10", "Piste 1.mp3", "piste 2.mp3", "piste 10.mp3"],
|
||||
)
|
||||
|
||||
def test_subfolder_and_parent(self) -> None:
|
||||
touch(self.root / "Rock" / "Live" / "a.mp3")
|
||||
listing = self.library.list("musique", "Rock/Live")
|
||||
self.assertEqual((listing["path"], listing["parent"]), ("Rock/Live", "Rock"))
|
||||
self.assertEqual(self.library.list("musique", "Rock")["parent"], "")
|
||||
self.assertIsNone(self.library.list("musique", "")["parent"])
|
||||
|
||||
def test_truncation(self) -> None:
|
||||
for index in range(5):
|
||||
touch(self.root / f"{index}.mp3")
|
||||
with mock.patch.object(media, "MAX_ENTRIES", 3):
|
||||
listing = self.library.list("musique", "")
|
||||
self.assertEqual(len(listing["entries"]), 3)
|
||||
self.assertTrue(listing["truncated"])
|
||||
|
||||
def test_undecodable_names_are_skipped(self) -> None:
|
||||
touch(self.root / "ok.mp3")
|
||||
(self.root / os.fsdecode(b"bad-\xff.mp3")).write_bytes(b"x")
|
||||
self.assertEqual(self.names(self.library.list("musique", "")), [("ok.mp3", "audio")])
|
||||
|
||||
def test_unavailable_root(self) -> None:
|
||||
library = MediaLibrary([Path(self._tmp.name) / "absent"])
|
||||
with self.assertRaises(MediaNotFound):
|
||||
library.list("absent", "")
|
||||
|
||||
def test_unknown_root(self) -> None:
|
||||
for root in ("nope", None, 3, ""):
|
||||
with self.subTest(root=root), self.assertRaises(MediaNotFound):
|
||||
self.library.list(root, "")
|
||||
|
||||
|
||||
class EscapeTest(LibraryCase):
|
||||
"""Rien de ce qui est hors de la racine ne doit être listé ni ouvert."""
|
||||
|
||||
def test_path_tricks_are_refused(self) -> None:
|
||||
touch(self.root / "a.mp3")
|
||||
for path in ("..", "../secret", "a/../..", "/etc", "/etc/passwd", ".", "./a.mp3", "a//b", "a/", "x\0y", "\\..\\x", 5, ["a"]):
|
||||
with self.subTest(path=path):
|
||||
with self.assertRaises(MediaError):
|
||||
self.library.list("musique", path)
|
||||
with self.assertRaises(MediaError):
|
||||
self.library.file("musique", path)
|
||||
|
||||
def test_hidden_entries_are_not_reachable_by_name(self) -> None:
|
||||
touch(self.root / ".cache.mp3")
|
||||
touch(self.root / ".prive" / "a.mp3")
|
||||
for path in (".cache.mp3", ".prive", ".prive/a.mp3"):
|
||||
with self.subTest(path=path):
|
||||
with self.assertRaisesRegex(MediaError, "invalid path"):
|
||||
self.library.file("musique", path)
|
||||
with self.assertRaisesRegex(MediaError, "invalid path"):
|
||||
self.library.list("musique", path)
|
||||
|
||||
def test_overlong_path(self) -> None:
|
||||
with self.assertRaises(MediaError):
|
||||
self.library.list("musique", "a/" * 600 + "a")
|
||||
|
||||
def test_symlinks_leaving_the_root_are_neither_listed_nor_reachable(self) -> None:
|
||||
os.symlink(self.outside, self.root / "dehors") # dossier
|
||||
os.symlink(self.outside / "private.mp3", self.root / "lien.mp3") # fichier
|
||||
touch(self.root / "ok.mp3")
|
||||
self.assertEqual(self.names(self.library.list("musique", "")), [("ok.mp3", "audio")])
|
||||
for path in ("dehors", "dehors/private.mp3"):
|
||||
with self.subTest(path=path), self.assertRaisesRegex(MediaError, "outside"):
|
||||
self.library.list("musique", path)
|
||||
with self.assertRaisesRegex(MediaError, "outside"):
|
||||
self.library.file("musique", "lien.mp3")
|
||||
with self.assertRaisesRegex(MediaError, "outside"):
|
||||
self.library.file("musique", "dehors/private.mp3")
|
||||
|
||||
def test_symlinks_inside_the_root_are_followed(self) -> None:
|
||||
touch(self.root / "Vrai" / "a.mp3")
|
||||
os.symlink(self.root / "Vrai", self.root / "Alias")
|
||||
os.symlink(self.root / "Vrai" / "a.mp3", self.root / "b.mp3")
|
||||
self.assertEqual(
|
||||
self.names(self.library.list("musique", "")), [("Alias", "dir"), ("Vrai", "dir"), ("b.mp3", "audio")]
|
||||
)
|
||||
real, kind = self.library.file("musique", "Alias/a.mp3")
|
||||
self.assertEqual((real, kind), (self.root / "Vrai" / "a.mp3", "audio"))
|
||||
|
||||
def test_a_media_name_cannot_hide_a_script(self) -> None:
|
||||
# lien.mp3 -> script.sh dans la racine : le type vient du fichier réel, pas du nom du lien
|
||||
touch(self.root / "script.sh")
|
||||
os.symlink(self.root / "script.sh", self.root / "lien.mp3")
|
||||
self.assertEqual(self.names(self.library.list("musique", "")), [])
|
||||
with self.assertRaisesRegex(MediaError, "not a media file"):
|
||||
self.library.file("musique", "lien.mp3")
|
||||
|
||||
def test_symlink_loop(self) -> None:
|
||||
os.symlink("boucle", self.root / "boucle")
|
||||
self.assertEqual(self.names(self.library.list("musique", "")), [])
|
||||
with self.assertRaises(MediaNotFound):
|
||||
self.library.list("musique", "boucle")
|
||||
|
||||
def test_root_itself_may_be_a_symlink(self) -> None:
|
||||
touch(self.outside / "b.mp3")
|
||||
link = Path(self._tmp.name) / "lien-racine"
|
||||
os.symlink(self.outside, link)
|
||||
library = MediaLibrary([link])
|
||||
self.assertIn(("b.mp3", "audio"), self.names(library.list("lien-racine", "")))
|
||||
|
||||
|
||||
class FileTest(LibraryCase):
|
||||
def test_returns_real_path_and_type(self) -> None:
|
||||
touch(self.root / "A B" / "été 1.flac")
|
||||
real, kind = self.library.file("musique", "A B/été 1.flac")
|
||||
self.assertEqual((real, kind), (self.root / "A B" / "été 1.flac", "audio"))
|
||||
|
||||
def test_refuses_folders_roots_unknown_and_non_media(self) -> None:
|
||||
touch(self.root / "notes.txt")
|
||||
touch(self.root / "run.sh")
|
||||
(self.root / "Dossier").mkdir()
|
||||
for path, message in (("Dossier", "not a file"), ("", "not a file"), ("notes.txt", "not a media"), ("run.sh", "not a media")):
|
||||
with self.subTest(path=path), self.assertRaisesRegex(MediaError, message):
|
||||
self.library.file("musique", path)
|
||||
with self.assertRaises(MediaNotFound):
|
||||
self.library.file("musique", "absent.mp3")
|
||||
|
||||
|
||||
class RootsTest(unittest.TestCase):
|
||||
def test_ids_are_unique_slugs(self) -> None:
|
||||
library = MediaLibrary([Path("/a/Vidéos"), Path("/b/Vidéos"), Path("/c/Mes Images!")])
|
||||
self.assertEqual([root.id for root in library.roots], ["videos", "videos-2", "mes-images"])
|
||||
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": []})
|
||||
|
||||
def test_user_dirs_from_xdg_and_defaults(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
for name in ("Musique", "Films", "Pictures"):
|
||||
(home / name).mkdir()
|
||||
config = home / ".config"
|
||||
config.mkdir()
|
||||
(config / "user-dirs.dirs").write_text(
|
||||
'# commentaire\nXDG_MUSIC_DIR="$HOME/Musique"\nXDG_VIDEOS_DIR="$HOME/Films"\n'
|
||||
'XDG_PICTURES_DIR="$HOME/"\nXDG_DOWNLOAD_DIR="$HOME/Téléchargements"\n'
|
||||
)
|
||||
with mock.patch("pathlib.Path.home", return_value=home), mock.patch.dict(os.environ, {"XDG_CONFIG_HOME": str(config)}):
|
||||
# Images désactivé par XDG (= $HOME) : jamais publié ; Pictures par défaut ne s'applique pas
|
||||
self.assertEqual(user_media_dirs(), [home / "Musique", home / "Films"])
|
||||
(config / "user-dirs.dirs").unlink()
|
||||
with mock.patch("pathlib.Path.home", return_value=home), mock.patch.dict(os.environ, {"XDG_CONFIG_HOME": str(config)}):
|
||||
self.assertEqual(user_media_dirs(), [home / "Pictures"])
|
||||
|
||||
def test_default_roots_when_not_configured(self) -> None:
|
||||
with mock.patch("mediadeck.media.user_media_dirs", return_value=[Path("/x/Music")]):
|
||||
self.assertEqual([root.id for root in MediaLibrary(None).roots], ["music"])
|
||||
|
||||
|
||||
class MediaApiTest(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self) -> None:
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self._tmp.name).resolve() / "Videos"
|
||||
touch(self.root / "Films" / "a.mkv")
|
||||
touch(self.root / "b.mp4")
|
||||
config = parse_config({"server": {"token": TOKEN}})
|
||||
app = web.Application()
|
||||
MediaApi(config, MediaLibrary([self.root])).add_routes(app)
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self) -> None:
|
||||
await self.client.close()
|
||||
self._tmp.cleanup()
|
||||
|
||||
async def test_token_required(self) -> None:
|
||||
for headers in ({}, {"Authorization": "Bearer nope"}, {"Authorization": TOKEN}):
|
||||
response = await self.client.get("/api/media?root=videos", headers=headers)
|
||||
self.assertEqual(response.status, 401)
|
||||
# Pas de jeton dans l'URL : il finirait dans les journaux
|
||||
response = await self.client.get(f"/api/media?root=videos&token={TOKEN}")
|
||||
self.assertEqual(response.status, 401)
|
||||
|
||||
async def test_listing(self) -> None:
|
||||
response = await self.client.get("/api/media?root=videos", headers=AUTH)
|
||||
data = await response.json()
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.headers["Cache-Control"], "no-store")
|
||||
self.assertEqual([(e["name"], e["kind"]) for e in data["entries"]], [("Films", "dir"), ("b.mp4", "video")])
|
||||
response = await self.client.get("/api/media", params={"root": "videos", "path": "Films"}, headers=AUTH)
|
||||
self.assertEqual([e["name"] for e in (await response.json())["entries"]], ["a.mkv"])
|
||||
|
||||
async def test_errors(self) -> None:
|
||||
for query, status in (
|
||||
("root=nope", 404), ("", 404), ("root=videos&path=absent", 404),
|
||||
("root=videos&path=..", 400), ("root=videos&path=b.mp4", 400), ("root=videos&path=%2Fetc", 400),
|
||||
):
|
||||
response = await self.client.get(f"/api/media?{query}", headers=AUTH)
|
||||
self.assertEqual(response.status, status, query)
|
||||
self.assertIn("error", await response.json())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user