lauschkiste-plugins 0.1.0a7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. lauschkiste_plugin_audiobookshelf/__init__.py +118 -0
  2. lauschkiste_plugin_audiobookshelf/client.py +73 -0
  3. lauschkiste_plugin_audiobookshelf/ledger.py +76 -0
  4. lauschkiste_plugin_audiobookshelf/provider.py +41 -0
  5. lauschkiste_plugin_audiobookshelf/source.py +371 -0
  6. lauschkiste_plugin_audiobookshelf/translations/de.json +26 -0
  7. lauschkiste_plugin_audiobookshelf/translations/en.json +26 -0
  8. lauschkiste_plugin_device_pc/__init__.py +33 -0
  9. lauschkiste_plugin_device_pc/translations/de.json +12 -0
  10. lauschkiste_plugin_device_pc/translations/en.json +12 -0
  11. lauschkiste_plugin_directories/__init__.py +141 -0
  12. lauschkiste_plugin_directories/directories.py +167 -0
  13. lauschkiste_plugin_directories/translations/de.json +134 -0
  14. lauschkiste_plugin_directories/translations/en.json +134 -0
  15. lauschkiste_plugin_rfid_readers/__init__.py +57 -0
  16. lauschkiste_plugin_rfid_readers/configure.py +289 -0
  17. lauschkiste_plugin_rfid_readers/generic_nfcpy/README.md +3 -0
  18. lauschkiste_plugin_rfid_readers/generic_nfcpy/description.py +3 -0
  19. lauschkiste_plugin_rfid_readers/generic_nfcpy/generic_nfcpy.py +128 -0
  20. lauschkiste_plugin_rfid_readers/generic_nfcpy/setup.inc.sh +42 -0
  21. lauschkiste_plugin_rfid_readers/generic_usb/README.md +3 -0
  22. lauschkiste_plugin_rfid_readers/generic_usb/description.py +1 -0
  23. lauschkiste_plugin_rfid_readers/generic_usb/generic_usb.py +214 -0
  24. lauschkiste_plugin_rfid_readers/inputminus.py +84 -0
  25. lauschkiste_plugin_rfid_readers/mfrc522_i2c/README.md +3 -0
  26. lauschkiste_plugin_rfid_readers/mfrc522_i2c/description.py +2 -0
  27. lauschkiste_plugin_rfid_readers/mfrc522_i2c/mfrc522_i2c.py +83 -0
  28. lauschkiste_plugin_rfid_readers/mfrc522_i2c/setup.inc.sh +9 -0
  29. lauschkiste_plugin_rfid_readers/pn532_i2c_py532/README.md +3 -0
  30. lauschkiste_plugin_rfid_readers/pn532_i2c_py532/description.py +3 -0
  31. lauschkiste_plugin_rfid_readers/pn532_i2c_py532/pn532_i2c_py532.py +65 -0
  32. lauschkiste_plugin_rfid_readers/pn532_i2c_py532/setup.inc.sh +9 -0
  33. lauschkiste_plugin_rfid_readers/rc522_spi/README.md +3 -0
  34. lauschkiste_plugin_rfid_readers/rc522_spi/description.py +2 -0
  35. lauschkiste_plugin_rfid_readers/rc522_spi/pirc522/LICENSE.md +22 -0
  36. lauschkiste_plugin_rfid_readers/rc522_spi/pirc522/__init__.py +8 -0
  37. lauschkiste_plugin_rfid_readers/rc522_spi/pirc522/rfid.py +576 -0
  38. lauschkiste_plugin_rfid_readers/rc522_spi/pirc522/util.py +154 -0
  39. lauschkiste_plugin_rfid_readers/rc522_spi/pirc522/version.py +1 -0
  40. lauschkiste_plugin_rfid_readers/rc522_spi/rc522_spi.py +160 -0
  41. lauschkiste_plugin_rfid_readers/rc522_spi/setup.inc.sh +8 -0
  42. lauschkiste_plugin_rfid_readers/rdm6300_serial/README.md +3 -0
  43. lauschkiste_plugin_rfid_readers/rdm6300_serial/description.py +2 -0
  44. lauschkiste_plugin_rfid_readers/rdm6300_serial/rdm6300_serial.py +158 -0
  45. lauschkiste_plugin_rfid_readers/rdm6300_serial/setup.inc.sh +9 -0
  46. lauschkiste_plugin_rfid_readers/translations/de.json +28 -0
  47. lauschkiste_plugin_rfid_readers/translations/en.json +28 -0
  48. lauschkiste_plugin_samba/__init__.py +102 -0
  49. lauschkiste_plugin_samba/translations/de.json +8 -0
  50. lauschkiste_plugin_samba/translations/en.json +8 -0
  51. lauschkiste_plugins-0.1.0a7.dist-info/METADATA +65 -0
  52. lauschkiste_plugins-0.1.0a7.dist-info/RECORD +55 -0
  53. lauschkiste_plugins-0.1.0a7.dist-info/WHEEL +4 -0
  54. lauschkiste_plugins-0.1.0a7.dist-info/entry_points.txt +13 -0
  55. lauschkiste_plugins-0.1.0a7.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,118 @@
1
+ """Audiobooks from an Audiobookshelf server.
2
+
3
+ Enable with::
4
+
5
+ plugins:
6
+ audiobookshelf:
7
+ server_url: https://abs.example.org
8
+ api_key: ...
9
+ """
10
+
11
+ import logging
12
+ import threading
13
+ from typing import List, Optional
14
+
15
+ from pydantic import BaseModel, Field
16
+
17
+ import lauschkiste.common.paths
18
+ from lauschkiste.contract import Plugin, query
19
+ from lauschkiste_plugin_audiobookshelf.provider import AudiobookshelfProvider
20
+ from lauschkiste_plugin_audiobookshelf.source import COVER_ROUTE, SCHEME, AudiobookshelfSource
21
+
22
+ logger = logging.getLogger('lauschkiste.audiobookshelf')
23
+
24
+ SYNC_EVERY_SEC = 60.0
25
+
26
+
27
+ class AudiobookshelfSettings(BaseModel):
28
+ server_url: str = Field('', title='Server address',
29
+ description='e.g. https://audiobookshelf.example.org or http://nas:13378')
30
+ api_key: str = Field('', title='API key', json_schema_extra={'secret': True},
31
+ description='Create one in Audiobookshelf under Settings, API Keys, for the user the box '
32
+ 'should use. Leave empty to keep the current one.')
33
+ refresh_minutes: int = Field(10, ge=1, le=1440, title='Ask for new books every (minutes)',
34
+ description='The position is always read fresh')
35
+ prefer_downloaded: bool = Field(True, title='Play downloaded books from the box',
36
+ description='Even when the server is reachable')
37
+
38
+
39
+ class ServerStatus(BaseModel):
40
+ configured: bool
41
+ reachable: bool
42
+ error: Optional[str] = None
43
+ waiting: int = 0
44
+
45
+
46
+ class Audiobookshelf(Plugin):
47
+ """Audiobooks from an Audiobookshelf server, streamed or downloaded; the position is shared with its apps."""
48
+
49
+ name = 'audiobookshelf'
50
+ title = 'Audiobookshelf'
51
+ interface_version = '1.2'
52
+ requires = {'audiobooks': '>=4.0,<5', 'player': '>=7.0,<8', 'cache': '>=1.0,<2'}
53
+ settings = AudiobookshelfSettings
54
+
55
+ def __init__(self):
56
+ self._source = AudiobookshelfSource()
57
+ self._stopped = threading.Event()
58
+ self._sync: Optional[threading.Thread] = None
59
+
60
+ def start(self, ctx) -> None:
61
+ self._ctx = ctx
62
+ self._configure()
63
+ cache = ctx.modules.cache
64
+ self._source.local_files = lambda book: cache.files('audiobookshelf', book)
65
+ self._source.cached_books = lambda: cache.cached('audiobookshelf')
66
+ self._source.attach(lauschkiste.common.paths.resolve('settings/audiobookshelf_positions.json'),
67
+ lauschkiste.common.paths.resolve('cache/audiobookshelf_books.json'))
68
+ ctx.modules.audiobooks.sources.register('audiobookshelf', self._source)
69
+ ctx.modules.player.resolvers.register(SCHEME, self._source)
70
+ cache.providers.register('audiobookshelf', AudiobookshelfProvider(self._source))
71
+ self._sync = threading.Thread(target=self._sync_loop, name='abs-sync', daemon=True)
72
+ self._sync.start()
73
+
74
+ def stop(self):
75
+ self._stopped.set()
76
+ return []
77
+
78
+ def _sync_loop(self) -> None:
79
+ """Send the positions recorded without the server once it answers again."""
80
+ while not self._stopped.wait(SYNC_EVERY_SEC):
81
+ try:
82
+ self._source.sync_pending()
83
+ except Exception:
84
+ logger.exception("Could not send the recorded positions")
85
+
86
+ @query(path='/status')
87
+ def status(self) -> ServerStatus:
88
+ """Whether the server is set up and answered the last request."""
89
+ return ServerStatus(**self._source.status())
90
+
91
+ def _configure(self) -> None:
92
+ config = self._ctx.config
93
+ self._source.prefer_downloaded = bool(config.get('prefer_downloaded', default=True))
94
+ self._source.configure(config.get('server_url', default=''), config.get('api_key', default=''),
95
+ config.get('refresh_minutes', default=10))
96
+
97
+ def settings_changed(self, changed) -> bool:
98
+ self._configure()
99
+ return True
100
+
101
+ def extra_routes(self, router) -> None:
102
+ from fastapi.concurrency import run_in_threadpool
103
+ from fastapi.responses import JSONResponse, Response
104
+
105
+ @router.get(COVER_ROUTE + '/{book}', tags=['audiobookshelf'])
106
+ async def cover(book: str):
107
+ def fetch():
108
+ try:
109
+ return self._source.client().cover(book, 400)
110
+ except Exception:
111
+ return None
112
+
113
+ upstream = await run_in_threadpool(fetch) if '/' not in book else None
114
+ if upstream is None:
115
+ return JSONResponse(status_code=404, content={'error': {'code': 'unknown_cover', 'message': book}})
116
+ body = await run_in_threadpool(lambda: upstream.content)
117
+ return Response(body, media_type=upstream.headers.get('content-type', 'image/jpeg'),
118
+ headers={'Cache-Control': 'public, max-age=86400'})
@@ -0,0 +1,73 @@
1
+ """The parts of the Audiobookshelf API the plugin uses."""
2
+
3
+ from typing import Any, Dict, List, Optional
4
+
5
+ import requests
6
+
7
+ TIMEOUT = (5, 20)
8
+
9
+
10
+ class AudiobookshelfError(Exception):
11
+ pass
12
+
13
+
14
+ class Client:
15
+ def __init__(self, server_url: str, api_key: str):
16
+ self.base = server_url.rstrip('/')
17
+ self.key = api_key
18
+ self._headers = {'Authorization': f'Bearer {api_key}'}
19
+ self._session = requests.Session()
20
+
21
+ @property
22
+ def headers(self) -> Dict[str, str]:
23
+ return dict(self._headers)
24
+
25
+ def request(self, method: str, path: str, **kwargs) -> Optional[Any]:
26
+ """The decoded JSON answer; None for 404."""
27
+ try:
28
+ response = self._session.request(method, self.base + path, headers=self._headers, timeout=TIMEOUT, **kwargs)
29
+ except requests.RequestException as error:
30
+ raise AudiobookshelfError(f"Audiobookshelf is not reachable: {error.__class__.__name__}") from error
31
+ if response.status_code == 404:
32
+ return None
33
+ if response.status_code in (401, 403):
34
+ raise AudiobookshelfError("Audiobookshelf refused the API key")
35
+ if not response.ok:
36
+ raise AudiobookshelfError(f"Audiobookshelf answered {response.status_code} for {path}")
37
+ try:
38
+ return response.json() if response.content else {}
39
+ except ValueError:
40
+ return {} # answers like "OK" carry no data
41
+
42
+ def libraries(self) -> List[Dict[str, Any]]:
43
+ return [library for library in (self.request('GET', '/api/libraries') or {}).get('libraries', [])
44
+ if library.get('mediaType') == 'book']
45
+
46
+ def books(self, library: str) -> List[Dict[str, Any]]:
47
+ return (self.request('GET', f'/api/libraries/{library}/items', params={'limit': 0, 'minified': 1}) or {}
48
+ ).get('results', [])
49
+
50
+ def item(self, book: str) -> Optional[Dict[str, Any]]:
51
+ return self.request('GET', f'/api/items/{book}')
52
+
53
+ def progress(self) -> Dict[str, Dict[str, Any]]:
54
+ """The progress entries of this user by library item."""
55
+ entries = (self.request('GET', '/api/me') or {}).get('mediaProgress', [])
56
+ return {entry['libraryItemId']: entry for entry in entries if entry.get('libraryItemId')}
57
+
58
+ def progress_of(self, book: str) -> Optional[Dict[str, Any]]:
59
+ return self.request('GET', f'/api/me/progress/{book}')
60
+
61
+ def save_progress(self, book: str, position: float, duration: float, finished: bool) -> None:
62
+ self.request('PATCH', f'/api/me/progress/{book}', json={
63
+ 'currentTime': position, 'duration': duration,
64
+ 'progress': (position / duration) if duration else 0, 'isFinished': finished})
65
+
66
+ def cover(self, book: str, width: int):
67
+ """The cover as a streamed response, or None."""
68
+ try:
69
+ response = self._session.get(f'{self.base}/api/items/{book}/cover', headers=self._headers,
70
+ params={'width': width}, timeout=TIMEOUT, stream=True)
71
+ except requests.RequestException:
72
+ return None
73
+ return response if response.ok else None
@@ -0,0 +1,76 @@
1
+ """What the box knows about the positions of the books, so that it keeps working without the server."""
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import threading
7
+ from pathlib import Path
8
+ from typing import Any, Dict, Optional
9
+
10
+ logger = logging.getLogger('lauschkiste.audiobookshelf')
11
+
12
+ #: Positions that differ by less than this many seconds are the same position
13
+ SAME_SEC = 1.0
14
+
15
+
16
+ class Ledger:
17
+ """Per book: ``position`` (seconds into the book), ``finished``, ``pending`` (not yet sent to the server)
18
+ and ``seen`` (what the server had when we last looked), in one JSON file."""
19
+
20
+ def __init__(self, path: Path):
21
+ self.path = path
22
+ self._lock = threading.Lock()
23
+ self._data: Dict[str, Dict[str, Any]] = {}
24
+ try:
25
+ data = json.loads(path.read_text())
26
+ if isinstance(data, dict):
27
+ self._data = {key: value for key, value in data.items() if isinstance(value, dict)}
28
+ except (OSError, ValueError):
29
+ pass
30
+
31
+ def get(self, book: str) -> Optional[Dict[str, Any]]:
32
+ with self._lock:
33
+ entry = self._data.get(book)
34
+ return dict(entry) if entry else None
35
+
36
+ def pending(self):
37
+ with self._lock:
38
+ return [book for book, entry in self._data.items() if entry.get('pending')]
39
+
40
+ def update(self, book: str, **fields) -> None:
41
+ with self._lock:
42
+ self._data.setdefault(book, {}).update(fields)
43
+ self._write()
44
+
45
+ def forget(self, book: str) -> None:
46
+ with self._lock:
47
+ if self._data.pop(book, None) is not None:
48
+ self._write()
49
+
50
+ def _write(self) -> None:
51
+ tmp = self.path.with_name(self.path.name + '.tmp')
52
+ try:
53
+ self.path.parent.mkdir(parents=True, exist_ok=True)
54
+ tmp.write_text(json.dumps(self._data))
55
+ os.replace(tmp, self.path)
56
+ except OSError as error:
57
+ logger.warning(f"Could not save the positions to '{self.path}': {error}")
58
+
59
+
60
+ def same(a: float, b: float) -> bool:
61
+ return abs(a - b) < SAME_SEC
62
+
63
+
64
+ def winner(local: Dict[str, Any], remote_position: float, remote_finished: bool) -> Dict[str, Any]:
65
+ """Which position counts after the box played offline (``local``, pending) and the server answers again.
66
+
67
+ Only the server's change since the box last looked matters, not the clocks (a Pi can be days off while offline).
68
+ The box's position wins if the server has not moved; otherwise the furthest position wins and a book finished
69
+ anywhere stays finished."""
70
+ seen = local.get('seen') or {}
71
+ moved = ('position' not in seen or not same(float(seen['position']), remote_position)
72
+ or bool(seen.get('finished')) != remote_finished)
73
+ if not moved:
74
+ return {'position': float(local.get('position') or 0), 'finished': bool(local.get('finished'))}
75
+ finished = remote_finished or bool(local.get('finished'))
76
+ return {'position': max(remote_position, float(local.get('position') or 0)), 'finished': finished}
@@ -0,0 +1,41 @@
1
+ """The books of the server as items of the download cache."""
2
+
3
+ from typing import Optional
4
+
5
+ from lauschkiste.content.cache import CacheFile, CachePlan
6
+ from lauschkiste.contract import OperationError
7
+ from lauschkiste_plugin_audiobookshelf.client import AudiobookshelfError
8
+
9
+
10
+ class AudiobookshelfProvider:
11
+ """``cache.providers`` entry ``audiobookshelf``: a book is all its audio files."""
12
+
13
+ def __init__(self, source):
14
+ self._source = source
15
+
16
+ def plan(self, item: str) -> CachePlan:
17
+ client = self._source.client()
18
+ try:
19
+ book = client.item(item)
20
+ except AudiobookshelfError as error:
21
+ raise OperationError(503, 'audiobookshelf_unavailable', str(error)) from None
22
+ if book is None:
23
+ raise OperationError(404, 'unknown_audiobook', f"No audiobook '{item}' on the Audiobookshelf server")
24
+ media = book.get('media') or {}
25
+ audio = sorted(media.get('audioFiles') or [], key=lambda f: f.get('index', 0))
26
+ files = [CacheFile(name=f"{number:03d}_{entry['ino']}{entry['metadata'].get('ext') or ''}",
27
+ url=f"{client.base}/api/items/{item}/file/{entry['ino']}/download",
28
+ size=int(entry['metadata']['size']), duration=entry.get('duration'),
29
+ headers=client.headers)
30
+ for number, entry in enumerate(audio, 1)]
31
+ return CachePlan(title=(media.get('metadata') or {}).get('title') or item,
32
+ version=str(book.get('updatedAt')) if book.get('updatedAt') is not None else None,
33
+ files=files)
34
+
35
+ def version(self, item: str) -> Optional[str]:
36
+ known = next((i for i in self._source.known_items() if i.get('id') == item), None)
37
+ return str(known['updatedAt']) if known and known.get('updatedAt') is not None else None
38
+
39
+ def removable(self, item: str) -> bool:
40
+ entry = self._source.ledger.get(item) if self._source.ledger else None
41
+ return bool(entry and entry.get('finished'))
@@ -0,0 +1,371 @@
1
+ """The books of an Audiobookshelf server as audiobook source ``audiobookshelf``.
2
+
3
+ The box keeps working without the server: the book list is kept on disk, downloaded books play from the
4
+ box, and positions are written to a ledger first and sent to the server when it is reachable again.
5
+ """
6
+
7
+ import json
8
+ import logging
9
+ import os
10
+ import threading
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, NamedTuple, Optional
14
+
15
+ from lauschkiste.contract import OperationError
16
+ from lauschkiste_plugin_audiobookshelf.client import AudiobookshelfError, Client
17
+ from lauschkiste_plugin_audiobookshelf.ledger import Ledger, winner
18
+
19
+ logger = logging.getLogger('lauschkiste.audiobookshelf')
20
+
21
+ SCHEME = 'abs'
22
+ COVER_ROUTE = '/api/v1/audiobookshelf/covers'
23
+ TRACKS_TTL_SEC = 600.0
24
+ #: After a failed request the server is not asked again for this long (each try would wait for the timeout)
25
+ RETRY_AFTER_SEC = 30.0
26
+
27
+
28
+ class Track(NamedTuple):
29
+ url: str
30
+ start: float
31
+ duration: float
32
+
33
+
34
+ def track_url(book: str, ino: str) -> str:
35
+ return f'{SCHEME}://{book}/{ino}'
36
+
37
+
38
+ def total_of(tracks: List[Track]) -> float:
39
+ return tracks[-1].start + tracks[-1].duration
40
+
41
+
42
+ class BookPosition:
43
+ """The position of one book: on the server, with the ledger of the box as fallback and backup."""
44
+
45
+ def __init__(self, source: 'AudiobookshelfSource', book: str):
46
+ self._source = source
47
+ self._book = book
48
+
49
+ def load(self) -> Dict[str, Any]:
50
+ state = self._source.reconcile(self._book)
51
+ if not state:
52
+ return {}
53
+ if state['finished']:
54
+ return {'finished': True}
55
+ try:
56
+ tracks = self._source.tracks(self._book)
57
+ except (OperationError, AudiobookshelfError):
58
+ return {}
59
+ position = float(state['position'])
60
+ track = next((t for t in reversed(tracks) if t.start <= position), tracks[0])
61
+ return {'file': track.url, 'elapsed': position - track.start, 'finished': False}
62
+
63
+ def save(self, entry: Dict[str, Any]) -> None:
64
+ tracks = self._source.tracks(self._book)
65
+ total = total_of(tracks)
66
+ if entry.get('finished'):
67
+ position, finished = total, True
68
+ else:
69
+ track = next((t for t in tracks if t.url == entry.get('file')), None)
70
+ if track is None:
71
+ return
72
+ position, finished = track.start + float(entry.get('elapsed') or 0), False
73
+ self._source.record(self._book, position, total, finished)
74
+
75
+
76
+ class AudiobookshelfSource:
77
+ def __init__(self):
78
+ self._lock = threading.Lock()
79
+ self._client: Optional[Client] = None
80
+ self._refresh_sec = 600.0
81
+ self._items: Optional[List[Dict[str, Any]]] = None
82
+ self._items_at = 0.0
83
+ self._tracks: Dict[str, tuple] = {}
84
+ self._down_until = 0.0
85
+ self.last_error: Optional[str] = None
86
+ self.ledger: Optional[Ledger] = None
87
+ self.prefer_downloaded = True
88
+ self._list_file: Optional[Path] = None
89
+ #: ``local_files(book)`` and ``cached_books()`` answer from the download cache of the core
90
+ self.local_files = lambda book: None
91
+ self.cached_books = lambda: []
92
+
93
+ def attach(self, positions: Path, book_list: Path) -> None:
94
+ """Where the box keeps what it knows: the positions and the list of books."""
95
+ self.ledger = Ledger(positions)
96
+ self._list_file = book_list
97
+
98
+ # -- the server -----------------------------------------------------------------------------
99
+
100
+ def configure(self, server_url: str, api_key: str, refresh_minutes: float) -> None:
101
+ with self._lock:
102
+ self._client = Client(server_url, api_key) if server_url and api_key else None
103
+ self._refresh_sec = float(refresh_minutes) * 60
104
+ self._items, self._tracks, self._down_until = None, {}, 0.0
105
+ self.last_error = None
106
+
107
+ def client(self) -> Client:
108
+ client = self._client
109
+ if client is None:
110
+ raise OperationError(503, 'audiobookshelf_not_configured',
111
+ 'Audiobookshelf: enter the server address and an API key in the settings')
112
+ return client
113
+
114
+ def reachable(self) -> bool:
115
+ """False for a while after the server did not answer."""
116
+ return self._client is not None and time.monotonic() >= self._down_until
117
+
118
+ def _failed(self, error: Exception) -> None:
119
+ self._down_until = time.monotonic() + RETRY_AFTER_SEC
120
+ self.last_error = str(error)
121
+
122
+ def _ok(self) -> None:
123
+ self._down_until, self.last_error = 0.0, None
124
+
125
+ # -- positions ------------------------------------------------------------------------------
126
+
127
+ def reconcile(self, book: str) -> Optional[Dict[str, Any]]:
128
+ """The position to continue from: ``{'position', 'finished'}`` or None for a book never played.
129
+
130
+ Sends what the box recorded offline once the server answers."""
131
+ ledger = self.ledger
132
+ local = ledger.get(book) if ledger else None
133
+ remote: Optional[Dict[str, Any]] = None
134
+ if self.reachable():
135
+ try:
136
+ remote = self.client().progress_of(book) or {}
137
+ self._ok()
138
+ except AudiobookshelfError as error:
139
+ self._failed(error)
140
+ if remote is None:
141
+ return {'position': float(local.get('position') or 0), 'finished': bool(local.get('finished'))} \
142
+ if local else None
143
+ seen = {'position': float(remote.get('currentTime') or 0), 'finished': bool(remote.get('isFinished'))}
144
+ state, waiting = dict(seen), False
145
+ if local and local.get('pending'):
146
+ state = winner(local, seen['position'], seen['finished'])
147
+ if state != seen:
148
+ if self._send(book, state['position'], float(local.get('duration') or 0), state['finished']):
149
+ seen = dict(state)
150
+ else:
151
+ waiting = True
152
+ if ledger is not None and (local or remote):
153
+ ledger.update(book, **state, seen=seen, pending=waiting)
154
+ return state if (local or remote) else None
155
+
156
+ def _send(self, book: str, position: float, duration: float, finished: bool) -> bool:
157
+ try:
158
+ self.client().save_progress(book, duration if finished and duration else position, duration, finished)
159
+ except AudiobookshelfError as error:
160
+ self._failed(error)
161
+ return False
162
+ self._ok()
163
+ return True
164
+
165
+ def record(self, book: str, position: float, duration: float, finished: bool) -> None:
166
+ """Remember a position on the box and send it to the server (or keep it for later)."""
167
+ ledger = self.ledger
168
+ if ledger is not None:
169
+ ledger.update(book, position=position, duration=duration, finished=finished, pending=True)
170
+ if self.reachable() and self._send(book, position, duration, finished):
171
+ if ledger is not None:
172
+ ledger.update(book, pending=False, seen={'position': position, 'finished': finished})
173
+
174
+ def sync_pending(self) -> int:
175
+ """Send the positions recorded offline; returns how many are still waiting."""
176
+ if self.ledger is None or not self.reachable():
177
+ return len(self.ledger.pending()) if self.ledger else 0
178
+ for book in self.ledger.pending():
179
+ if not self.reachable():
180
+ break
181
+ self.reconcile(book)
182
+ return len(self.ledger.pending())
183
+
184
+ def position(self, book: str) -> BookPosition:
185
+ return BookPosition(self, book)
186
+
187
+ def set_finished(self, book: str, finished: bool) -> None:
188
+ total = total_of(self.tracks(book))
189
+ self.record(book, total if finished else 0.0, total, finished)
190
+
191
+ # -- the book list --------------------------------------------------------------------------
192
+
193
+ def _remember_items(self, items: List[Dict[str, Any]]) -> None:
194
+ path = self._list_file
195
+ if path is None:
196
+ return
197
+ try:
198
+ path.parent.mkdir(parents=True, exist_ok=True)
199
+ tmp = path.with_name(path.name + '.tmp')
200
+ tmp.write_text(json.dumps(items))
201
+ os.replace(tmp, path)
202
+ except OSError as error:
203
+ logger.warning(f"Could not save the book list: {error}")
204
+
205
+ def known_items(self) -> List[Dict[str, Any]]:
206
+ with self._lock:
207
+ if self._items is not None:
208
+ return self._items
209
+ path = self._list_file
210
+ try:
211
+ items = json.loads(path.read_text()) if path else []
212
+ except (OSError, ValueError):
213
+ items = []
214
+ return items if isinstance(items, list) else []
215
+
216
+ def _all_items(self, client: Client) -> List[Dict[str, Any]]:
217
+ with self._lock:
218
+ if self._items is not None and time.monotonic() - self._items_at < self._refresh_sec:
219
+ return self._items
220
+ items: List[Dict[str, Any]] = []
221
+ for library in client.libraries():
222
+ items.extend(client.books(library['id']))
223
+ with self._lock:
224
+ self._items, self._items_at = items, time.monotonic()
225
+ self._remember_items(items)
226
+ return items
227
+
228
+ def list_books(self) -> List[Dict[str, Any]]:
229
+ if self._client is None:
230
+ return []
231
+ items, progress = self.known_items(), None
232
+ if self.reachable():
233
+ try:
234
+ items, progress = self._all_items(self._client), self._client.progress()
235
+ self._ok()
236
+ except AudiobookshelfError as error:
237
+ self._failed(error)
238
+ items = self.known_items()
239
+ books = [self._describe(item, progress) for item in items]
240
+ books += self._only_downloaded({item['id'] for item in items})
241
+ online = progress is not None
242
+ return sorted(books, key=lambda b: (online is False and not b.get('downloaded'), str(b['title']).casefold()))
243
+
244
+ def _describe(self, item: Dict[str, Any], progress: Optional[Dict[str, Dict[str, Any]]]) -> Dict[str, Any]:
245
+ media = item.get('media') or {}
246
+ book = item['id']
247
+ duration = float(media.get('duration') or 0)
248
+ local = self.ledger.get(book) if self.ledger else None
249
+ if local and (local.get('pending') or progress is None):
250
+ finished, position = bool(local.get('finished')), float(local.get('position') or 0)
251
+ else:
252
+ entry = (progress or {}).get(book, {})
253
+ finished, position = bool(entry.get('isFinished')), float(entry.get('currentTime') or 0)
254
+ listened = duration if finished else position
255
+ chapter, elapsed = self._place(book, listened) if 0 < listened and not finished else (0, 0.0)
256
+ return {'book': book, 'title': (media.get('metadata') or {}).get('title') or book,
257
+ 'chapters': int(media.get('numAudioFiles') or 0), 'duration': duration or None,
258
+ 'chapter': chapter, 'elapsed': elapsed, 'listened': listened, 'finished': finished,
259
+ 'cover_url': f'{COVER_ROUTE}/{book}',
260
+ 'downloaded': bool(self.local_files(book))}
261
+
262
+ def _only_downloaded(self, known: set) -> List[Dict[str, Any]]:
263
+ """Downloaded books the list does not know (yet): they play without the server."""
264
+ books = []
265
+ for cached in self.cached_books():
266
+ if cached.item in known:
267
+ continue
268
+ local = self.ledger.get(cached.item) if self.ledger else None
269
+ books.append({'book': cached.item, 'title': cached.title or cached.item, 'chapters': len(cached.files),
270
+ 'duration': sum(float(f.duration or 0) for f in cached.files) or None,
271
+ 'chapter': 0, 'elapsed': 0.0, 'listened': float(local.get('position') or 0) if local else 0.0,
272
+ 'finished': bool(local and local.get('finished')), 'cover_url': None, 'downloaded': True})
273
+ return books
274
+
275
+ def status(self) -> Dict[str, Any]:
276
+ """Whether the server is configured and answers (the answer to the last request, not a new one)."""
277
+ configured = self._client is not None
278
+ return {'configured': configured, 'reachable': configured and self.last_error is None,
279
+ 'error': self.last_error, 'waiting': len(self.ledger.pending()) if self.ledger else 0}
280
+
281
+ # -- the files ------------------------------------------------------------------------------
282
+
283
+ def _downloaded(self, book: str) -> Optional[List[Track]]:
284
+ cached = self.local_files(book) if self.prefer_downloaded else None
285
+ if not cached:
286
+ return None
287
+ tracks, start = [], 0.0
288
+ for entry in cached.files:
289
+ duration = float(entry.duration or 0)
290
+ tracks.append(Track(entry.path, start, duration))
291
+ start += duration
292
+ return tracks or None
293
+
294
+ def _place(self, book: str, position: float):
295
+ """(file index, seconds into it) of a position in the book; (0, position) if the files are unknown."""
296
+ try:
297
+ tracks = self._downloaded(book) or self._cached_tracks(book)
298
+ except Exception as error:
299
+ logger.debug(f"No tracks for '{book}': {error}")
300
+ tracks = None
301
+ if not tracks:
302
+ tracks = self._fetch_tracks_online(book)
303
+ if not tracks:
304
+ return 0, position
305
+ index = max((i for i, track in enumerate(tracks) if track.start <= position), default=0)
306
+ return index, position - tracks[index].start
307
+
308
+ def _cached_tracks(self, book: str) -> Optional[List[Track]]:
309
+ with self._lock:
310
+ cached = self._tracks.get(book)
311
+ return cached[1] if cached and time.monotonic() - cached[0] < TRACKS_TTL_SEC else None
312
+
313
+ def _fetch_tracks_online(self, book: str) -> Optional[List[Track]]:
314
+ if not self.reachable():
315
+ return None
316
+ try:
317
+ return self.tracks(book)
318
+ except (OperationError, AudiobookshelfError) as error:
319
+ logger.debug(f"No tracks for '{book}': {error}")
320
+ return None
321
+
322
+ def tracks(self, book: str) -> List[Track]:
323
+ downloaded = self._downloaded(book)
324
+ if downloaded:
325
+ return downloaded
326
+ cached = self._cached_tracks(book)
327
+ if cached:
328
+ return cached
329
+ if not self.reachable():
330
+ raise OperationError(503, 'audiobookshelf_unavailable',
331
+ self.last_error or 'The server is not reachable and the book is not downloaded')
332
+ try:
333
+ item = self.client().item(book)
334
+ except AudiobookshelfError as error:
335
+ self._failed(error)
336
+ raise OperationError(503, 'audiobookshelf_unavailable', str(error)) from None
337
+ self._ok()
338
+ if item is None:
339
+ raise OperationError(404, 'unknown_audiobook', f"No audiobook '{book}' on the Audiobookshelf server")
340
+ files = sorted((item.get('media') or {}).get('audioFiles') or [], key=lambda f: f.get('index', 0))
341
+ tracks, start = [], 0.0
342
+ for audio in files:
343
+ duration = float(audio.get('duration') or 0)
344
+ tracks.append(Track(track_url(book, str(audio['ino'])), start, duration))
345
+ start += duration
346
+ if not tracks:
347
+ raise OperationError(404, 'unknown_audiobook', f"The audiobook '{book}' has no audio files")
348
+ with self._lock:
349
+ self._tracks[book] = (time.monotonic(), tracks, (item.get('media') or {}).get('metadata', {}).get('title'))
350
+ return tracks
351
+
352
+ def files(self, book: str) -> List[str]:
353
+ return [track.url for track in self.tracks(book)]
354
+
355
+ def cover_url(self, book: str) -> str:
356
+ return f'{COVER_ROUTE}/{book}'
357
+
358
+ def title(self, book: str) -> str:
359
+ for item in self.known_items():
360
+ if item.get('id') == book:
361
+ return (item.get('media', {}).get('metadata') or {}).get('title') or book
362
+ cached = self.local_files(book)
363
+ return (cached.title if cached else '') or book
364
+
365
+ # -- the resolver ---------------------------------------------------------------------------
366
+
367
+ def resolve(self, url: str):
368
+ """``abs://<book>/<file id>`` -> the file on the server and the header that authorises it."""
369
+ book, _, ino = url[len(SCHEME) + 3:].partition('/')
370
+ client = self.client()
371
+ return f'{client.base}/api/items/{book}/file/{ino}/download', client.headers