Coverage for downtify/library_preference.py: 100%

30 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""A non-destructive listing preference for one external source.""" 

2 

3from __future__ import annotations 

4 

5import re 

6import unicodedata 

7from collections.abc import Callable 

8from typing import Any 

9 

10 

11def _key(value: Any) -> str: 

12 text = unicodedata.normalize('NFKD', str(value or '').casefold()) 

13 return re.sub( 

14 r'[^\w]+', '', ''.join(c for c in text if not unicodedata.combining(c)) 

15 ) 

16 

17 

18def _release(entry: dict[str, Any]) -> tuple[str, str, str]: 

19 return ( 

20 _key(entry.get('artist')), 

21 _key(entry.get('title')), 

22 _key(entry.get('album')), 

23 ) 

24 

25 

26def prefer_entries( 

27 entries: list[dict[str, Any]], 

28 folder_id: str, 

29 fold: Callable[[list[dict[str, Any]]], list[dict[str, Any]]], 

30) -> list[dict[str, Any]]: 

31 """Prefer full recording/release metadata, without mutating input rows. 

32 

33 Do not use an old clip's duration to override an explicit preference. 

34 Unknown artist/title/album and distinct versions remain separate. 

35 """ 

36 prefix = f'ext/{folder_id}/' 

37 chosen = [ 

38 dict(e) for e in entries if str(e.get('file', '')).startswith(prefix) 

39 ] 

40 if not chosen: 

41 return fold(entries) 

42 others = [ 

43 e for e in entries if not str(e.get('file', '')).startswith(prefix) 

44 ] 

45 by_release = {_release(e): e for e in chosen if all(_release(e))} 

46 kept = [] 

47 for row in fold(others): 

48 preferred = by_release.get(_release(row)) 

49 if preferred is None: 

50 kept.append(row) 

51 continue 

52 playlists = list(preferred.get('playlists') or []) 

53 for playlist in row.get('playlists') or []: 

54 if playlist not in playlists: 

55 playlists.append(playlist) 

56 if playlists: 

57 preferred['playlists'] = playlists 

58 return chosen + kept