diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 7940496..2b28f5d 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,5 +1,47 @@ # backend HASHOUT_LOG · formDAM current: v1.27.2 · 2026-10-22 +### app/routers/trash.py keychain_enable · wrong passkeys sent to save the passkey on the device count toward the same limit +- refers-to: routers/trash.py keychain_enable; vault.py attempt_guard, attempt_failed, attempt_cleared; tests/test_f1_guard.py (one new test) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +Saving the passkey to the device store checks it against the vault passkey first, so it answered right or wrong like vault unlock did, but without the limit on wrong passkeys. It now shares the vault's count: after 10 wrong passkeys within 5 minutes on either route, both answer 429, and a right passkey clears the count. +### app/routers/library.py _disk_packet, app/services/xmpsvc.py merge_packet · a sidecar that is not UTF-8 is left alone, and one file's prefixes do not carry into the next +- refers-to: routers/library.py _disk_packet; services/xmpsvc.py merge_packet; tests/test_p1_xmp.py (two new tests) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +The Disk browser read another tool's sidecar with undecodable bytes replaced, so merging a rating into a sidecar saved in another encoding would have rewritten its text with replacement characters. It now reads strictly and leaves such a sidecar as it is, not counted as written. merge_packet registers a sidecar's own namespace prefixes so they serialize under their own names; those registrations are process wide, so a sidecar that used an older prefix for a known namespace (xap for xmp) changed the prefix of every later merge. The known prefixes are registered again after each merge. +### app/services/native_picker.py _mac, _windows · the starting folder reaches the system dialog as data, never inside the script text +- refers-to: services/native_picker.py SEED_ENV (new), _run, _mac, _windows; tests/test_native_picker.py (new) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +The Windows picker put the starting folder inside a single-quoted PowerShell string and turned away only the ASCII apostrophe, but PowerShell also reads the curly single quotes as quotes, so a folder name could end the string. The macOS picker did the same with a double-quoted AppleScript string. Windows now reads the folder from the `FORMDAM_PICK_INITIAL` environment variable of the PowerShell child (`$env:FORMDAM_PICK_INITIAL`). macOS passes the absolute folder as the script's first argument (`on run argv`, `item 1 of argv`); `system attribute` was tried and rejected because it decodes the variable as Mac Roman and mangled a name with a curly quote. Folders whose names held a quote are now offered as the starting folder too, where before they were dropped. Linux already passed it as an argument. Checked here: the macOS script compiles with osacompile and argv kept a name with curly and straight quotes unchanged. Not run on Windows. +### app/services/outputsvc.py _free_target · export with sidecars picks a name whose sidecar is free too +- refers-to: services/outputsvc.py _free_target (new), export_one; tests/test_p1_xmp.py (one new test) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +Only the exported image's name was made unique, so `.xmp` could replace a sidecar already in the destination folder (exporting beside the originals), and the two halves of a RAW and JPEG pair wrote the same sidecar. With the sidecar option on, a candidate name is used only when neither the image nor its `.xmp` exists or was taken earlier in the same export; the next free `-1`, `-2` name is used otherwise, and both names are recorded as taken. With the option off, naming is as before. +### app/vaultcrypt.py purge, _edit_files_in_use · deleting an item for good keeps an edit file another item points at +- refers-to: vaultcrypt.py purge, _edit_files_in_use (new); services/syncsvc.py _fetch_edit (unchanged); tests/test_trash.py (one new test) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +Edit files are named `-[-n].ext` after the id on the device that made them, and sync copies them under that same name, so on another device the name can start with the id of an unrelated item. purge removed every `edits/-*` file and could take another photo's edited version with it. It now skips any file named in another item's edit_json `external.file`. The files are not renamed on arrival, because the name travels inside the synced edit record. +### app/routers/trash.py vault_setup, vault_unlock; app/routers/albums.py unlock_album; app/vault.py attempt_guard · the vault passkey is set only in the window, and wrong passkeys are limited +- refers-to: routers/trash.py vault_setup, vault_unlock; routers/albums.py unlock_album; vault.py ATTEMPT_LIMIT, ATTEMPT_WINDOW, attempt_guard, attempt_failed, attempt_cleared (new); tests/test_f1_guard.py (two new tests) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +Choosing the vault passkey decides who can open Hidden and Recently Deleted, so it is now a window or desktop shell action, the same rule device unlock already had; an automation token gets 403. Unlocking with a passkey still works for automation. After 10 wrong passkeys within 5 minutes, for the vault or for one album with its own passkey, the engine answers 429 until the oldest failure is 5 minutes old; a right passkey clears the count. The count lives in the engine process and starts empty at each launch. +### app/routers/library.py disk_meta, app/services/xmpsvc.py merge_packet · a rating from the Disk browser keeps the rest of a sidecar written by another tool +- refers-to: routers/library.py _disk_packet (new), disk_meta; services/xmpsvc.py owned_packet, merge_packet (new), write_sidecar; tests/test_p1_xmp.py (three new tests) +- kind: fix +- logged: after v1.32.4 · 2026-11-28 + +Setting a rating, label or keyword on a file in the Disk browser rebuilt its sidecar from the few fields formDAM reads, so develop settings, history and anything else another tool kept there were lost. The Disk browser now treats a sidecar the way write_sidecar does: one that formDAM wrote (x:xmptk="FormDAM") is rebuilt as before; one from another tool is parsed as XML and only xmp:Rating, xmp:Label, xmp:MetadataDate, dc:subject and lr:hierarchicalSubject on its first rdf:Description are changed, every other attribute and element is kept, and its namespace prefixes are registered so they serialize under their own names. A sidecar that does not parse is left as it is and the file is not counted as written. A file with no sidecar gets a new formDAM packet as before. ### ../setup/build_windows_app.bat WINDOWED · the Windows engine is frozen with no console of its own - refers-to: setup/build_windows_app.bat WINDOWED, FORMDAM_ENGINE_WINDOWED; desktop_entry.py the stream guard at the top, _Tee, _open_log; src-tauri/src/main.rs backend_command, forward_lines, read_port; tests/test_entry_streams.py (three new tests) - kind: decision diff --git a/backend/app/routers/albums.py b/backend/app/routers/albums.py index db6570c..be09b75 100644 --- a/backend/app/routers/albums.py +++ b/backend/app/routers/albums.py @@ -4,7 +4,7 @@ from pydantic import BaseModel, Field from ..db import ex, media_dict, now, q, q1 -from ..vault import check_token, hash_passkey, issue_token, vault_hash, verify_passkey +from ..vault import attempt_cleared, attempt_failed, attempt_guard, check_token, hash_passkey, issue_token, vault_hash, verify_passkey from .guard import token_of router = APIRouter() @@ -94,8 +94,12 @@ def unlock_album(album_id: int, body: UnlockIn): if not album["is_private"]: raise HTTPException(422, detail="Album is not private") stored = album["passkey_hash"] or vault_hash() + key = f"album:{album_id}" if album["passkey_hash"] else "vault" + attempt_guard(key) if stored is None or not verify_passkey(body.passkey, stored): + attempt_failed(key) raise HTTPException(401, detail="Wrong passkey") + attempt_cleared(key) from .. import vaultcrypt if album["passkey_hash"]: opened = vaultcrypt.unlock_album(album_id, body.passkey) diff --git a/backend/app/routers/library.py b/backend/app/routers/library.py index 0205216..df13ca8 100644 --- a/backend/app/routers/library.py +++ b/backend/app/routers/library.py @@ -281,6 +281,23 @@ def _sidecar_record(path: str) -> Dict[str, Any]: return {} +def _disk_packet(path: str, rec: Dict[str, Any], body: DiskMetaIn) -> Optional[tuple]: + from ..services import xmpsvc + + side = xmpsvc.find_sidecar(path) + if side is None: + return xmpsvc.sidecar_for(path), xmpsvc.build_xmp(rec) + try: + with open(side, "r", encoding="utf-8") as fh: + current = fh.read() + except (OSError, UnicodeDecodeError): + return None + if xmpsvc.owned_packet(current): + return side, xmpsvc.build_xmp(rec) + merged = xmpsvc.merge_packet(current, rating=body.rating, label=body.label, keywords=body.keywords) + return (side, merged) if merged is not None else None + + @router.post("/disk/meta") def disk_meta(body: DiskMetaIn): from ..services import xmpsvc @@ -296,10 +313,13 @@ def disk_meta(body: DiskMetaIn): rec["label"] = body.label if body.keywords: rec["keywords"] = sorted(set(rec.get("keywords") or []) | set(body.keywords)) - side = xmpsvc.find_sidecar(path) or xmpsvc.sidecar_for(path) + packet = _disk_packet(path, rec, body) + if packet is None: + continue + side, text = packet tmp = side + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: - fh.write(xmpsvc.build_xmp(rec)) + fh.write(text) os.replace(tmp, side) hit = q1("SELECT id FROM media WHERE rel_path=?", (path,)) if hit: diff --git a/backend/app/routers/trash.py b/backend/app/routers/trash.py index bf5b40a..ef154c9 100644 --- a/backend/app/routers/trash.py +++ b/backend/app/routers/trash.py @@ -10,7 +10,7 @@ from ..db import ex, media_dict, q, q1 from ..security import shell_allowed, window_allowed from ..services import libraryfs -from ..vault import issue_token, set_vault, vault_hash, verify_passkey +from ..vault import attempt_cleared, attempt_failed, attempt_guard, issue_token, set_vault, vault_hash, verify_passkey from .guard import require_vault router = APIRouter() @@ -26,7 +26,9 @@ def vault_status(): @router.post("/vault/setup") -def vault_setup(body: PasskeyIn): +def vault_setup(body: PasskeyIn, request: Request): + if not (window_allowed(request) or shell_allowed(request)): + raise HTTPException(403, detail="The vault passkey can only be set in the formDAM window") if vault_hash() is not None: raise HTTPException(409, detail="Vault passkey already set") set_vault(body.passkey) @@ -40,8 +42,11 @@ def vault_unlock(body: PasskeyIn): stored = vault_hash() if stored is None: raise HTTPException(409, detail="Vault passkey not set yet") + attempt_guard("vault") if not verify_passkey(body.passkey, stored): + attempt_failed("vault") raise HTTPException(401, detail="Wrong passkey") + attempt_cleared("vault") from .. import vaultcrypt if not vaultcrypt.unlock_vault(body.passkey): raise HTTPException(500, detail="The vault key could not be opened with this passkey") @@ -150,8 +155,11 @@ def device_unlock_labels(): @router.post("/vault/keychain/enable") def keychain_enable(body: PasskeyIn): stored = vault_hash() + attempt_guard("vault") if stored is None or not verify_passkey(body.passkey, stored): + attempt_failed("vault") raise HTTPException(401, detail="Wrong passkey") + attempt_cleared("vault") entry = _ctrl_roundtrip("KCSTORE", passkey=body.passkey) if not entry.get("ok"): raise HTTPException(500, detail=f"The shell could not save the passkey to {device_labels()['store']}") diff --git a/backend/app/services/native_picker.py b/backend/app/services/native_picker.py index e32b95b..dbd1a7c 100644 --- a/backend/app/services/native_picker.py +++ b/backend/app/services/native_picker.py @@ -16,19 +16,27 @@ class PickerUnavailable(Exception): pass -def _run(cmd: List[str]) -> subprocess.CompletedProcess: - return subprocess.run(cmd, capture_output=True, text=True) +SEED_ENV = "FORMDAM_PICK_INITIAL" + + +def _run(cmd: List[str], seed: Optional[str] = None) -> subprocess.CompletedProcess: + env = None + if seed is not None: + env = {**os.environ, SEED_ENV: seed} + return subprocess.run(cmd, capture_output=True, text=True, env=env) def _mac(initial: Optional[str]) -> Optional[str]: prompt = "Choose a folder to import into formDAM" script = f'POSIX path of (choose folder with prompt "{prompt}" with showing package contents)' - if initial and os.path.isdir(initial) and '"' not in initial: + cmd = ["osascript", "-e", script] + if initial and os.path.isdir(initial): script = ( f'POSIX path of (choose folder with prompt "{prompt}" ' - f'default location POSIX file "{initial}" with showing package contents)' + 'default location POSIX file (item 1 of argv) with showing package contents)' ) - proc = _run(["osascript", "-e", script]) + cmd = ["osascript", "-e", "on run argv", "-e", script, "-e", "end run", os.path.abspath(initial)] + proc = _run(cmd) if proc.returncode != 0: if "canceled" in proc.stderr.lower() or "cancelled" in proc.stderr.lower(): return None @@ -38,8 +46,10 @@ def _mac(initial: Optional[str]) -> Optional[str]: def _windows(initial: Optional[str]) -> Optional[str]: seed = "" - if initial and os.path.isdir(initial) and "'" not in initial: - seed = f"$dialog.SelectedPath = '{initial}';" + value = None + if initial and os.path.isdir(initial): + value = initial + seed = f"$dialog.SelectedPath = $env:{SEED_ENV};" script = ( "Add-Type -AssemblyName System.Windows.Forms;" "$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;" @@ -49,7 +59,7 @@ def _windows(initial: Optional[str]) -> Optional[str]: + "if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)" + " { Write-Output $dialog.SelectedPath }" ) - proc = _run(["powershell", "-NoProfile", "-STA", "-Command", script]) + proc = _run(["powershell", "-NoProfile", "-STA", "-Command", script], value) if proc.returncode != 0: raise PickerUnavailable(f"The Windows folder dialog could not open: {proc.stderr.strip() or 'unknown error'}") return proc.stdout.strip() or None diff --git a/backend/app/services/outputsvc.py b/backend/app/services/outputsvc.py index 63d0537..7a33d96 100644 --- a/backend/app/services/outputsvc.py +++ b/backend/app/services/outputsvc.py @@ -128,6 +128,24 @@ def _copy_stripped(src: Any, target: str, row, opts: Dict[str, Any]) -> None: raise ExportError(f"{row['name']}: location could not be removed from this original") +def _free_target(path: str, taken: set, sidecar: bool) -> str: + base, ext = os.path.splitext(path) + cand, i = path, 1 + while True: + side = os.path.splitext(cand)[0] + ".xmp" + busy = os.path.exists(cand) or cand in taken + if sidecar: + busy = busy or os.path.exists(side) or side in taken + if not busy: + break + cand = f"{base}-{i}{ext}" + i += 1 + taken.add(cand) + if sidecar: + taken.add(os.path.splitext(cand)[0] + ".xmp") + return cand + + def export_one(row, dest: str, seq: int, opts: Dict[str, Any], taken: set) -> Optional[str]: from ..routers.render import source_of @@ -139,7 +157,7 @@ def export_one(row, dest: str, seq: int, opts: Dict[str, Any], taken: set) -> Op base = renamesvc.safe(renamesvc.expand(opts.get("naming") or "{name}", dict(row), seq, opts.get("custom", ""))) if opts.get("original") or row["kind"] != "image": ext = os.path.splitext(row["name"])[1] - target = filesvc._unique(os.path.join(folder, base + ext), taken) + target = _free_target(os.path.join(folder, base + ext), taken, bool(opts.get("sidecar"))) if not opts.get("location", True) or row["location_hidden"] or opts.get("metadata") == "none": _copy_stripped(src, target, row, opts) elif isinstance(src, (bytes, bytearray)): @@ -162,7 +180,7 @@ def export_one(row, dest: str, seq: int, opts: Dict[str, Any], taken: set) -> Op img = img.resize(size, Image.Resampling.LANCZOS) if fmt in ("JPEG", "HEIF") or img.mode not in ("RGB", "RGBA"): img = img.convert("RGB") - target = filesvc._unique(os.path.join(folder, base + ext), taken) + target = _free_target(os.path.join(folder, base + ext), taken, bool(opts.get("sidecar"))) quality = int(opts.get("quality") or 90) kwargs: Dict[str, Any] = {} exif = _exif_bytes(src, row, opts) diff --git a/backend/app/services/xmpsvc.py b/backend/app/services/xmpsvc.py index cde5ce9..89a0cb0 100644 --- a/backend/app/services/xmpsvc.py +++ b/backend/app/services/xmpsvc.py @@ -226,6 +226,75 @@ def parse_xmp(text: str) -> Dict[str, Any]: return out +def owned_packet(text: str) -> bool: + return 'x:xmptk="FormDAM"' in text[:65536] + + +def _read_packet(text: str): + import io + + prefixes: Dict[str, str] = {} + try: + events = ET.iterparse(io.StringIO(text), events=("start-ns",)) + for _event, (prefix, uri) in events: + prefixes.setdefault(prefix, uri) + root = events.root + except ET.ParseError: + return None + for prefix, uri in prefixes.items(): + if prefix and prefix not in NS: + try: + ET.register_namespace(prefix, uri) + except ValueError: + pass + return root + + +def _set_simple(desc, prefix: str, name: str, value: Optional[str]) -> None: + for child in [c for c in desc if c.tag == _q(prefix, name)]: + desc.remove(child) + if value is None: + desc.attrib.pop(_q(prefix, name), None) + else: + desc.set(_q(prefix, name), value) + + +def _set_bag(desc, prefix: str, name: str, items: List[str]) -> None: + for child in [c for c in desc if c.tag == _q(prefix, name)]: + desc.remove(child) + desc.attrib.pop(_q(prefix, name), None) + el = ET.SubElement(desc, _q(prefix, name)) + bag = ET.SubElement(el, _q("rdf", "Bag")) + for item in items: + ET.SubElement(bag, _q("rdf", "li")).text = item + + +def merge_packet(text: str, rating: Optional[int] = None, label: Optional[str] = None, + keywords: Optional[List[str]] = None) -> Optional[str]: + root = _read_packet(text) + if root is None: + return None + desc = next(root.iter(_q("rdf", "Description")), None) + if desc is None: + return None + if rating is not None: + _set_simple(desc, "xmp", "Rating", str(int(rating))) + if label is not None: + _set_simple(desc, "xmp", "Label", str(label).title() if label else None) + if keywords: + current = parse_xmp(text).get("keywords") or [] + merged = sorted(set(current) | set(keywords)) + _set_bag(desc, "dc", "subject", sorted({k.split("|")[-1] for k in merged})) + _set_bag(desc, "lr", "hierarchicalSubject", merged) + _set_simple(desc, "xmp", "MetadataDate", time.strftime("%Y-%m-%dT%H:%M:%S")) + try: + body = ET.tostring(root, encoding="unicode") + finally: + for prefix, uri in NS.items(): + ET.register_namespace(prefix, uri) + return '\n' + body + '\n\n' + + def sidecar_for(path: str) -> str: return os.path.splitext(path)[0] + ".xmp" @@ -326,7 +395,7 @@ def write_sidecar(media_id: int) -> Optional[str]: head = fh.read(65536) except OSError: return None - if 'x:xmptk="FormDAM"' not in head: + if not owned_packet(head): return None tmp = side + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: diff --git a/backend/app/vault.py b/backend/app/vault.py index 0bf5125..d105570 100644 --- a/backend/app/vault.py +++ b/backend/app/vault.py @@ -3,12 +3,17 @@ import hmac import os import time -from typing import Optional +from typing import Dict, List, Optional + +from fastapi import HTTPException from .db import setting_get, setting_set TOKEN_TTL = 30 * 60 _SECRET = os.urandom(32) +ATTEMPT_LIMIT = 10 +ATTEMPT_WINDOW = 5 * 60 +_FAILURES: Dict[str, List[float]] = {} def _secret() -> bytes: @@ -65,3 +70,23 @@ def vault_hash() -> Optional[str]: def set_vault(passkey: str) -> None: setting_set("vault_passkey", hash_passkey(passkey)) + + +def _recent(key: str) -> List[float]: + cutoff = time.monotonic() - ATTEMPT_WINDOW + return [t for t in _FAILURES.get(key, []) if t > cutoff] + + +def attempt_guard(key: str) -> None: + recent = _recent(key) + _FAILURES[key] = recent + if len(recent) >= ATTEMPT_LIMIT: + raise HTTPException(429, detail="Too many wrong passkeys. Wait a few minutes and try again.") + + +def attempt_failed(key: str) -> None: + _FAILURES[key] = [*_recent(key), time.monotonic()] + + +def attempt_cleared(key: str) -> None: + _FAILURES.pop(key, None) diff --git a/backend/app/vaultcrypt.py b/backend/app/vaultcrypt.py index c903eec..cee67ba 100644 --- a/backend/app/vaultcrypt.py +++ b/backend/app/vaultcrypt.py @@ -515,9 +515,25 @@ def purge(media_id: int) -> None: _scrub(media_id) from .services.extedit import edits_dir, work_dir + kept = _edit_files_in_use(media_id) for folder in (edits_dir(), work_dir()): for path in glob.glob(os.path.join(glob.escape(folder), f"{media_id}-*")): - _unlink(path) + if os.path.basename(path) not in kept: + _unlink(path) + + +def _edit_files_in_use(media_id: int) -> set: + names = set() + for row in q("SELECT edit_json FROM media WHERE id<>? AND edit_json LIKE '%external%'", (media_id,)): + try: + state = json.loads(row["edit_json"]) or {} + except ValueError: + continue + ext = state.get("external") if isinstance(state, dict) else None + name = os.path.basename(str((ext or {}).get("file") or "")) if isinstance(ext, dict) else "" + if name: + names.add(name) + return names def is_vaulted(media_id: int) -> bool: diff --git a/backend/tests/test_f1_guard.py b/backend/tests/test_f1_guard.py index 6cd8025..2228faa 100644 --- a/backend/tests/test_f1_guard.py +++ b/backend/tests/test_f1_guard.py @@ -154,3 +154,48 @@ def test_automation_token_works_only_while_on(client, anon): client.put("/api/system/automation", json={"enabled": False}, headers=HEADERS) forget_automation() assert anon.get("/api/summary", headers={"x-dam-automation": token}).status_code == 403 + + +def automation_token(client): + from app.security import forget_automation + + on = client.put("/api/system/automation", json={"enabled": True}, headers=HEADERS) + assert on.status_code == 200 + forget_automation() + return on.json()["token"] + + +def test_an_automation_token_cannot_set_the_vault_passkey(client, anon): + from app.vault import vault_hash + + token = automation_token(client) + res = anon.post("/api/vault/setup", json={"passkey": "chosen-elsewhere"}, headers={"x-dam-automation": token, **HEADERS}) + assert res.status_code == 403 + assert vault_hash() is None + assert client.post("/api/vault/setup", json={"passkey": "the-owners-key"}, headers=HEADERS).status_code == 200 + + +def test_repeated_wrong_vault_passkeys_are_slowed_down(client): + from app import vault + + vault.attempt_cleared("vault") + assert client.post("/api/vault/setup", json={"passkey": "right-key"}, headers=HEADERS).status_code == 200 + codes = [client.post("/api/vault/unlock", json={"passkey": f"wrong-{i}"}, headers=HEADERS).status_code + for i in range(vault.ATTEMPT_LIMIT)] + assert codes == [401] * vault.ATTEMPT_LIMIT + assert client.post("/api/vault/unlock", json={"passkey": "right-key"}, headers=HEADERS).status_code == 429 + vault.attempt_cleared("vault") + assert client.post("/api/vault/unlock", json={"passkey": "right-key"}, headers=HEADERS).status_code == 200 + + +def test_wrong_passkeys_to_the_device_store_count_toward_the_same_limit(client): + from app import vault + + vault.attempt_cleared("vault") + assert client.post("/api/vault/setup", json={"passkey": "right-key"}, headers=HEADERS).status_code == 200 + codes = [client.post("/api/vault/keychain/enable", json={"passkey": f"wrong-{i}"}, headers=HEADERS).status_code + for i in range(vault.ATTEMPT_LIMIT)] + assert codes == [401] * vault.ATTEMPT_LIMIT + assert client.post("/api/vault/keychain/enable", json={"passkey": "right-key"}, headers=HEADERS).status_code == 429 + assert client.post("/api/vault/unlock", json={"passkey": "right-key"}, headers=HEADERS).status_code == 429 + vault.attempt_cleared("vault") diff --git a/backend/tests/test_native_picker.py b/backend/tests/test_native_picker.py new file mode 100644 index 0000000..e4bfc09 --- /dev/null +++ b/backend/tests/test_native_picker.py @@ -0,0 +1,41 @@ +import subprocess + +import pytest + +from app.services import native_picker + +ODD_NAMES = ["Trip ’;Write-Output x;’", "Trip 'one' \"two\"", "Trip $(x) `y`"] + + +@pytest.fixture +def captured(monkeypatch): + calls = [] + + def fake_run(cmd, capture_output, text, env=None): + calls.append({"cmd": cmd, "env": env}) + return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") + + monkeypatch.setattr(native_picker.subprocess, "run", fake_run) + return calls + + +@pytest.mark.parametrize("name", ODD_NAMES) +def test_the_windows_seed_folder_reaches_the_dialog_only_as_data(captured, tmp_path, name): + folder = tmp_path / name + folder.mkdir() + native_picker._windows(str(folder)) + call = captured[0] + assert all(str(folder) not in part for part in call["cmd"]) + assert call["env"][native_picker.SEED_ENV] == str(folder) + assert native_picker.SEED_ENV in call["cmd"][-1] + + +@pytest.mark.parametrize("name", ODD_NAMES) +def test_the_macos_seed_folder_reaches_the_dialog_only_as_an_argument(captured, tmp_path, name): + folder = tmp_path / name + folder.mkdir() + native_picker._mac(str(folder)) + cmd = captured[0]["cmd"] + assert cmd[-1] == str(folder) + assert all(str(folder) not in part for part in cmd[:-1]) + assert "argv" in " ".join(cmd[:-1]) diff --git a/backend/tests/test_p1_xmp.py b/backend/tests/test_p1_xmp.py index 8fa1d0b..f0fc029 100644 --- a/backend/tests/test_p1_xmp.py +++ b/backend/tests/test_p1_xmp.py @@ -88,3 +88,96 @@ def test_sidecar_written_by_the_engine_restores_every_field_after_a_wipe(client, assert stored_fields(client, one_photo) == expected row = client.get(f"/api/media/{one_photo}").json() assert row["rating"] == 3 and row["label"] == "blue" + + +FOREIGN_SIDECAR = """ + + +0, 0255, 255 +Beach + + + +""" + + +def disk_file(tmp_path, sidecar_text=None): + folder = tmp_path / "disk" + folder.mkdir() + photo = folder / "IMG_1.jpg" + pattern(64, 48).save(photo, "JPEG") + side = folder / "IMG_1.xmp" + if sidecar_text is not None: + side.write_text(sidecar_text, encoding="utf-8") + return photo, side + + +def test_disk_rating_keeps_other_tools_settings_in_the_sidecar(client, tmp_path): + from app.services import xmpsvc + + photo, side = disk_file(tmp_path, FOREIGN_SIDECAR) + res = client.post("/api/disk/meta", json={"paths": [str(photo)], "rating": 5, "label": "green", "keywords": ["Sunset"]}, + headers=HEADERS) + assert res.status_code == 200 and res.json()["written"] == 1 + text = side.read_text(encoding="utf-8") + assert 'Exposure2012="+0.75"' in text and 'Temperature="5600"' in text + assert "ToneCurvePV2012" in text and "255, 255" in text + assert "Other Toolkit 1.0" in text + parsed = xmpsvc.parse_xmp(text) + assert parsed["rating"] == 5 and parsed["label"] == "Green" + assert sorted(parsed["keywords"]) == ["Beach", "Sunset"] + + +def test_disk_rating_leaves_an_unreadable_sidecar_alone(client, tmp_path): + photo, side = disk_file(tmp_path, "