# SPDX-License-Identifier: AGPL-3.0-or-later
"""Typprüfung, Bildverarbeitung, Einbettungen und Ablage (ohne Datenbank)."""
from __future__ import annotations
import io
import os
import time
import zipfile
from pathlib import Path
import pytest
from surveybox.media import embeds, sniff, storage
# ---------------------------------------------------------------------------
# Typprüfung
# ---------------------------------------------------------------------------
def _write(tmp_path: Path, name: str, data: bytes) -> Path:
path = tmp_path / name
path.write_bytes(data)
return path
@pytest.mark.parametrize(
("data", "name", "key"),
[
(b"\xff\xd8\xff\xe0" + b"0" * 20, "a.jpg", "jpeg"),
(b"\x89PNG\r\n\x1a\n" + b"0" * 20, "a.png", "png"),
(b"RIFF\x00\x00\x00\x00WEBPVP8 ", "a.webp", "webp"),
(b"\x00\x00\x00\x18ftypisom" + b"0" * 20, "a.mp4", "mp4"),
(b"\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01webm", "a.webm", "webm"),
(b"%PDF-1.7\n", "a.pdf", "pdf"),
(b"WEBVTT\n\n00:00.000 --> 00:01.000\nHallo\n", "a.vtt", "vtt"),
("Name;Ort\nÄrger;Köln\n".encode(), "liste.csv", "csv"),
(b"einfacher Text\n", "notiz", "txt"),
],
)
def test_detects_by_content(tmp_path: Path, data: bytes, name: str, key: str) -> None:
detected = sniff.detect_file(_write(tmp_path, name, data), name)
assert detected is not None
assert detected.key == key
def test_rejects_unknown_and_disguised(tmp_path: Path) -> None:
exe = _write(tmp_path, "bild.jpg", b"MZ\x90\x00" + b"\x00" * 50)
assert sniff.detect_file(exe, "bild.jpg") is None
mov = _write(tmp_path, "film.mp4", b"\x00\x00\x00\x14ftypqt " + b"0" * 20)
assert sniff.detect_file(mov, "film.mp4") is None
html = _write(tmp_path, "x.png", b"")
assert sniff.detect_file(html, "x.png").key == "txt" # type: ignore[union-attr]
def _zip(tmp_path: Path, name: str, files: dict[str, bytes]) -> Path:
path = tmp_path / name
with zipfile.ZipFile(path, "w") as archive:
for inner, content in files.items():
archive.writestr(inner, content)
return path
def test_office_formats_from_archive(tmp_path: Path) -> None:
docx = _zip(tmp_path, "a.docx", {"[Content_Types].xml": b"", "word/document.xml": b""})
assert sniff.detect_file(docx).key == "docx" # type: ignore[union-attr]
ods = _zip(tmp_path, "a.ods", {"mimetype": b"application/vnd.oasis.opendocument.spreadsheet"})
assert sniff.detect_file(ods).key == "ods" # type: ignore[union-attr]
plain = _zip(tmp_path, "a.zip", {"readme.txt": b"hi"})
assert sniff.detect_file(plain).key == "zip" # type: ignore[union-attr]
def test_safe_filename() -> None:
assert sniff.safe_filename("C:\\Users\\x\\Bericht 2026.PDF", "pdf") == "Bericht 2026.pdf"
assert sniff.safe_filename('../../etc/pa"ss\x00wd', "txt") == "passwd.txt"
assert sniff.safe_filename("", "png") == "datei.png"
# ---------------------------------------------------------------------------
# Bilder
# ---------------------------------------------------------------------------
PIL = pytest.importorskip("PIL")
def _jpeg_with_gps(path: Path, size: tuple[int, int] = (3000, 2000)) -> None:
from PIL import Image
img = Image.new("RGB", size, (200, 30, 30))
exif = Image.Exif()
exif[0x010F] = "Kamerahersteller"
exif[0x0112] = 6 # um 90° gedreht
exif[0x8825] = {1: "N", 2: (47.0, 54.0, 0.0)}
img.save(path, "JPEG", exif=exif)
def test_image_is_rotated_resized_and_stripped(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
source = tmp_path / "foto.jpg"
_jpeg_with_gps(source)
full, thumb = tmp_path / "full", tmp_path / "thumb"
result = images.process(source, full, thumb)
# Ausrichtung angewandt (hochkant), auf 2560 begrenzt
assert (result.width, result.height) == (1707, 2560)
with Image.open(full) as out:
assert out.format == "WEBP"
assert not out.getexif()
assert "exif" not in out.info
with Image.open(thumb) as small:
assert max(small.size) == 640
def test_image_rejects_garbage_and_bombs(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
junk = _write(tmp_path, "x.png", b"\x89PNG\r\n\x1a\n" + os.urandom(200))
with pytest.raises(images.ImageError):
images.process(junk, tmp_path / "f", tmp_path / "t")
gif = tmp_path / "a.gif"
Image.new("RGB", (10, 10)).save(gif, "GIF")
with pytest.raises(images.ImageError):
images.process(gif, tmp_path / "f", tmp_path / "t")
bomb = tmp_path / "bomb.png"
Image.new("1", (9000, 9000)).save(bomb, "PNG")
with pytest.raises(images.ImageError):
images.process(bomb, tmp_path / "f", tmp_path / "t")
def test_transparent_png_keeps_alpha(tmp_path: Path) -> None:
from PIL import Image
from surveybox.media import images
source = tmp_path / "logo.png"
Image.new("RGBA", (100, 50), (0, 0, 0, 0)).save(source, "PNG")
images.process(source, tmp_path / "f", tmp_path / "t")
with Image.open(tmp_path / "f") as out:
assert out.mode == "RGBA"
# ---------------------------------------------------------------------------
# Externe Videos
# ---------------------------------------------------------------------------
ALL = embeds.EmbedPolicy(youtube=True, vimeo=True, peertube_hosts=("video.example.org",))
@pytest.mark.parametrize(
("url", "provider", "video"),
[
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=10", "youtube", "dQw4w9WgXcQ"),
("https://youtu.be/dQw4w9WgXcQ?si=abc", "youtube", "dQw4w9WgXcQ"),
("https://www.youtube.com/shorts/dQw4w9WgXcQ", "youtube", "dQw4w9WgXcQ"),
("https://vimeo.com/76979871", "vimeo", "76979871"),
("https://player.vimeo.com/video/76979871?h=abc123def", "vimeo", "76979871"),
("https://video.example.org/w/9c9de5e8-0a1e-484a-b099-e80766180a6d", "peertube",
"9c9de5e8-0a1e-484a-b099-e80766180a6d"),
("https://video.example.org/videos/watch/kkGMgK9ZtnKfYAgnEtQxbv", "peertube",
"kkGMgK9ZtnKfYAgnEtQxbv"),
],
)
def test_parse_video_urls(url: str, provider: str, video: str) -> None:
embed = embeds.parse_url(url, ALL)
assert (embed.provider, embed.video) == (provider, video)
assert embeds.from_config(embed.to_config()) == embed
@pytest.mark.parametrize(
"url",
[
"javascript:alert(1)",
"https://www.youtube.com/watch?v=short",
"https://www.youtube.com/watch?v=dQw4w9WgXcQ\">