biblo 0.1.0__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.
biblo/__init__.py ADDED
@@ -0,0 +1,74 @@
1
+ """Unofficial client for Biblo, the Danish public libraries' app for e-books, audiobooks and
2
+ podcasts (Det Digitale Folkebibliotek).
3
+
4
+ from biblo import Biblo
5
+
6
+ with Biblo("763000") as biblo: # Vejle Bibliotekerne
7
+ for work in biblo.catalog.search("harry potter").works:
8
+ print(work.title)
9
+
10
+ `AsyncBiblo` is the same client for asyncio.
11
+ """
12
+
13
+ from importlib.metadata import PackageNotFoundError, version
14
+
15
+ from . import models, types
16
+ from ._async import AsyncBiblo, AsyncFileTokenStorage, AsyncMemoryTokenStorage, AsyncTokenStorage
17
+ from ._base import Tokens, authorize_url, code_from_redirect
18
+ from ._sync import Biblo, FileTokenStorage, MemoryTokenStorage, TokenStorage
19
+ from .exceptions import (
20
+ APIError,
21
+ AuthenticationError,
22
+ BadRequestError,
23
+ BibloConnectionError,
24
+ BibloError,
25
+ ConflictError,
26
+ InvalidCredentialsError,
27
+ LoginError,
28
+ LoginFlowError,
29
+ NoLibraryError,
30
+ NotFoundError,
31
+ NotLoggedInError,
32
+ PermissionDeniedError,
33
+ RateLimitError,
34
+ ResponseValidationError,
35
+ ServerError,
36
+ )
37
+
38
+ try:
39
+ __version__ = version("biblo")
40
+ except PackageNotFoundError: # running from a source tree without installing
41
+ __version__ = "0.0.0"
42
+
43
+ __all__ = [
44
+ "APIError",
45
+ "AsyncBiblo",
46
+ "AsyncFileTokenStorage",
47
+ "AsyncMemoryTokenStorage",
48
+ "AsyncTokenStorage",
49
+ "AuthenticationError",
50
+ "BadRequestError",
51
+ "Biblo",
52
+ "BibloConnectionError",
53
+ "BibloError",
54
+ "ConflictError",
55
+ "FileTokenStorage",
56
+ "InvalidCredentialsError",
57
+ "LoginError",
58
+ "LoginFlowError",
59
+ "MemoryTokenStorage",
60
+ "NoLibraryError",
61
+ "NotFoundError",
62
+ "NotLoggedInError",
63
+ "PermissionDeniedError",
64
+ "RateLimitError",
65
+ "ResponseValidationError",
66
+ "ServerError",
67
+ "TokenStorage",
68
+ "Tokens",
69
+ "__version__",
70
+ "authorize_url",
71
+ "code_from_redirect",
72
+ "models",
73
+ "types",
74
+ ]
biblo/__main__.py ADDED
@@ -0,0 +1,21 @@
1
+ import sys
2
+
3
+ MISSING_CLI_EXTRA = (
4
+ "The biblo command needs the CLI extra: pip install 'biblo[cli]' "
5
+ "or uvx --from 'biblo[cli]' biblo"
6
+ )
7
+
8
+
9
+ def main() -> None:
10
+ try:
11
+ from .cli import main as cli_main
12
+ except ModuleNotFoundError as err:
13
+ if err.name not in ("typer", "rich"):
14
+ raise
15
+ print(MISSING_CLI_EXTRA, file=sys.stderr)
16
+ sys.exit(1)
17
+ cli_main()
18
+
19
+
20
+ if __name__ == "__main__":
21
+ main()
biblo/_app_types.py ADDED
@@ -0,0 +1,21 @@
1
+ # Generated by scripts/generate.py from spec/ddf-openapi.json. Do not edit.
2
+
3
+ """The `x-app-type` for endpoints that refuse "biblo". The API serves three apps:
4
+ Biblo (digital loans), Mit Biblo (the physical library: branches, events, Scan & Loan)
5
+ and Biblo Go (children). Every endpoint not listed here accepts "biblo"."""
6
+
7
+ DEFAULT_APP_TYPE = "biblo"
8
+
9
+ APP_TYPE_OVERRIDES: dict[tuple[str, str], str] = {
10
+ ("GET", "/v1/agencies/{agencyId}/branches"): "mybiblo",
11
+ ("GET", "/v1/agencies/{agencyId}/branches/{branchId}"): "mybiblo",
12
+ ("GET", "/v1/agencies/{agencyId}/branches/{branchId}/events"): "mybiblo",
13
+ ("GET", "/v1/agencies/{agencyId}/branches/{branchId}/openinghours"): "mybiblo",
14
+ ("GET", "/v1/agencies/{agencyId}/events"): "mybiblo",
15
+ ("GET", "/v1/agencies/{agencyId}/materials/{materialId}/status"): "mybiblo",
16
+ ("GET", "/v1/agencies/{agencyId}/openinghours"): "mybiblo",
17
+ ("GET", "/v1/agencies/{agencyId}/openstatus"): "mybiblo",
18
+ ("GET", "/v1/agencies/{agencyId}/records/holdings"): "mybiblo",
19
+ ("PATCH", "/v1/agencies/{agencyId}/account/reservations/{reservationId}"): "mybiblo",
20
+ ("POST", "/v1/agencies/{agencyId}/account/loans/return"): "mybiblo",
21
+ }
@@ -0,0 +1,4 @@
1
+ from .client import AsyncBiblo
2
+ from .storage import AsyncFileTokenStorage, AsyncMemoryTokenStorage, AsyncTokenStorage
3
+
4
+ __all__ = ["AsyncBiblo", "AsyncFileTokenStorage", "AsyncMemoryTokenStorage", "AsyncTokenStorage"]
biblo/_async/client.py ADDED
@@ -0,0 +1,304 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from types import TracebackType
5
+ from typing import Any, Self
6
+
7
+ import httpx
8
+
9
+ from .. import _base, models
10
+ from .._base import Session, Tokens
11
+ from .._constants import (
12
+ API_BASE_URL,
13
+ CLIENT_ID,
14
+ CLIENT_SECRET,
15
+ DEFAULT_TIMEOUT_SECONDS,
16
+ REDIRECT_URI,
17
+ )
18
+ from ..exceptions import (
19
+ AuthenticationError,
20
+ BadRequestError,
21
+ BibloConnectionError,
22
+ NoLibraryError,
23
+ NotLoggedInError,
24
+ )
25
+ from .login import password_login_code
26
+ from .resources import (
27
+ AsyncAccount,
28
+ AsyncCatalog,
29
+ AsyncContent,
30
+ AsyncDevices,
31
+ AsyncFavorites,
32
+ AsyncLibraries,
33
+ AsyncLoans,
34
+ AsyncMessages,
35
+ AsyncReservations,
36
+ )
37
+ from .storage import AsyncTokenStorage
38
+
39
+
40
+ class AsyncBiblo:
41
+ """Client for the Biblo API, the backend of the Danish public libraries' Biblo app.
42
+
43
+ async with AsyncBiblo("763000") as biblo: # Vejle Bibliotekerne
44
+ result = await biblo.catalog.search("harry potter")
45
+ await biblo.login("1234567890", "1234")
46
+ for loan in await biblo.loans.list():
47
+ print(loan.record.title, loan.due_date)
48
+
49
+ `library_id` is the library ("agency") catalogue calls default to;
50
+ `biblo.libraries.find()` looks it up. Searching and browsing work without logging in.
51
+ Account calls default to the library the user logged in at. With a `storage`, the
52
+ session (tokens, that library, installation id) survives restarts and token refreshes
53
+ are saved as they happen.
54
+
55
+ Pass `http_client` to share an `httpx.AsyncClient`, e.g. Home Assistant's; the client
56
+ then leaves closing it to you.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ library_id: str | None = None,
62
+ *,
63
+ storage: AsyncTokenStorage | None = None,
64
+ http_client: httpx.AsyncClient | None = None,
65
+ base_url: str = API_BASE_URL,
66
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
67
+ ) -> None:
68
+ self._library_id = library_id
69
+ self._storage = storage
70
+ self._owns_http = http_client is None
71
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
72
+ self._base_url = base_url.rstrip("/")
73
+ self._session: Session | None = None
74
+ self._refresh_lock = asyncio.Lock()
75
+
76
+ self.libraries = AsyncLibraries(self)
77
+ self.catalog = AsyncCatalog(self)
78
+ self.account = AsyncAccount(self)
79
+ self.loans = AsyncLoans(self)
80
+ self.reservations = AsyncReservations(self)
81
+ self.favorites = AsyncFavorites(self)
82
+ self.messages = AsyncMessages(self)
83
+ self.content = AsyncContent(self)
84
+ self.devices = AsyncDevices(self)
85
+
86
+ async def __aenter__(self) -> Self:
87
+ return self
88
+
89
+ async def __aexit__(
90
+ self,
91
+ exc_type: type[BaseException] | None,
92
+ exc: BaseException | None,
93
+ tb: TracebackType | None,
94
+ ) -> None:
95
+ await self.aclose()
96
+
97
+ async def aclose(self) -> None:
98
+ if self._owns_http:
99
+ await self._http.aclose()
100
+
101
+ # ------------------------------------------------------------------ session
102
+
103
+ async def _loaded(self) -> Session:
104
+ session = self._session
105
+ if session is None:
106
+ saved = await self._storage.load() if self._storage else None
107
+ session = Session.from_dict(saved) or Session()
108
+ self._session = session
109
+ return session
110
+
111
+ async def _save(self) -> None:
112
+ if self._storage is not None and self._session is not None:
113
+ await self._storage.save(self._session.to_dict())
114
+
115
+ async def library_id(self) -> str | None:
116
+ """The library catalogue calls default to: the client's, else the logged-in user's."""
117
+ return self._library_id or (await self._loaded()).library_id
118
+
119
+ async def login_library_id(self) -> str | None:
120
+ """The library the user logged in at; account calls default to it."""
121
+ return (await self._loaded()).library_id
122
+
123
+ async def is_logged_in(self) -> bool:
124
+ return (await self._loaded()).tokens is not None
125
+
126
+ async def tokens(self) -> Tokens | None:
127
+ """The current tokens, refreshed if they are about to expire."""
128
+ await self._loaded()
129
+ return await self._fresh_tokens()
130
+
131
+ # --------------------------------------------------------------------- auth
132
+
133
+ async def login(self, user_id: str, pincode: str, library_id: str | None = None) -> None:
134
+ """Log in with card number or CPR and pincode at a library. No browser needed.
135
+
136
+ Raises InvalidCredentialsError if login.bib.dk refuses them.
137
+ """
138
+ session = await self._loaded()
139
+ library = library_id or self._library_id or session.library_id
140
+ if not library:
141
+ raise NoLibraryError("Logging in needs a library_id (see libraries.find())")
142
+ try:
143
+ code = await password_login_code(self._http, user_id, pincode, library)
144
+ except httpx.TransportError as err:
145
+ raise BibloConnectionError(f"login.bib.dk could not be reached: {err}") from err
146
+ session.library_id = library
147
+ await self.login_with_code(code)
148
+
149
+ @staticmethod
150
+ def authorize_url() -> str:
151
+ """The login.bib.dk page to open in a browser for MitID and other browser logins.
152
+
153
+ After logging in the browser is sent to a `biblo://?code=...` URL it can't open; pass
154
+ that URL (or just the code) to `login_with_code`.
155
+ """
156
+ return _base.authorize_url()
157
+
158
+ async def login_with_code(self, code_or_redirect_url: str) -> None:
159
+ session = await self._loaded()
160
+ code = _base.code_from_redirect(code_or_redirect_url)
161
+ data = await self._token_request(
162
+ "/v1/auth/login", {"code": code, "redirect_uri": REDIRECT_URI}
163
+ )
164
+ session.tokens = Tokens.from_response(data)
165
+ await self._save()
166
+
167
+ async def refresh(self) -> None:
168
+ """Get new tokens with the refresh token. Happens on its own before they expire."""
169
+ session = await self._loaded()
170
+ if session.tokens is None:
171
+ raise NotLoggedInError("Not logged in")
172
+ try:
173
+ data = await self._token_request(
174
+ "/v1/auth/token-refresh", {"refresh_token": session.tokens.refresh_token}
175
+ )
176
+ except (AuthenticationError, BadRequestError) as err:
177
+ session.tokens = None
178
+ await self._save()
179
+ raise NotLoggedInError("The session has expired; log in again") from err
180
+ session.tokens = Tokens.from_response(data)
181
+ await self._save()
182
+
183
+ async def logout(self) -> None:
184
+ """End the session at the API and forget the tokens. The library is remembered."""
185
+ session = await self._loaded()
186
+ if session.tokens is None:
187
+ return
188
+ try:
189
+ await self._call(
190
+ None,
191
+ "POST",
192
+ "/v1/auth/logout",
193
+ json={"accessToken": session.tokens.access_token},
194
+ )
195
+ finally:
196
+ session.tokens = None
197
+ await self._save()
198
+
199
+ async def _token_request(self, template: str, form: dict[str, str]) -> dict[str, Any]:
200
+ session = await self._loaded()
201
+ response = await self._send(
202
+ "POST",
203
+ template,
204
+ template,
205
+ session,
206
+ None,
207
+ data=form,
208
+ auth=httpx.BasicAuth(CLIENT_ID, CLIENT_SECRET),
209
+ )
210
+ return _base.payload(response)
211
+
212
+ async def _fresh_tokens(self) -> Tokens | None:
213
+ session = await self._loaded()
214
+ if session.tokens is not None and session.tokens.expires_soon:
215
+ async with self._refresh_lock:
216
+ if session.tokens is not None and session.tokens.expires_soon:
217
+ await self.refresh()
218
+ return session.tokens
219
+
220
+ # ------------------------------------------------------------------- global
221
+
222
+ async def config(self) -> models.GlobalConfig:
223
+ return await self._get(models.GlobalConfig, "/v1/config")
224
+
225
+ async def request(
226
+ self,
227
+ method: str,
228
+ path: str,
229
+ *,
230
+ params: dict[str, Any] | None = None,
231
+ json: Any = None,
232
+ ) -> Any:
233
+ """Call any endpoint and get its JSON (without the `data` envelope), for endpoints
234
+ this library doesn't cover yet. `{agencyId}` in `path` is filled in."""
235
+ return await self._call(Any, method.upper(), path, params=params, json=json)
236
+
237
+ # ---------------------------------------------------------------- transport
238
+
239
+ async def _get[T](
240
+ self,
241
+ tp: type[T] | Any,
242
+ template: str,
243
+ path_params: dict[str, str] | None = None,
244
+ *,
245
+ params: dict[str, Any] | None = None,
246
+ library_id: str | None = None,
247
+ auth: bool = False,
248
+ ) -> T:
249
+ return await self._call(
250
+ tp, "GET", template, path_params, params=params, library_id=library_id, auth=auth
251
+ )
252
+
253
+ async def _call(
254
+ self,
255
+ tp: Any,
256
+ method: str,
257
+ template: str,
258
+ path_params: dict[str, str] | None = None,
259
+ *,
260
+ params: dict[str, Any] | None = None,
261
+ json: Any = None,
262
+ library_id: str | None = None,
263
+ auth: bool = False,
264
+ ) -> Any:
265
+ session = await self._loaded()
266
+ if auth and session.tokens is None:
267
+ raise NotLoggedInError(f"{method} {template} needs a logged-in user")
268
+ path_values = dict(path_params or {})
269
+ if "{agencyId}" in template:
270
+ # The user's account lives at the library they logged in at.
271
+ default = (session.library_id or self._library_id) if auth else None
272
+ library = library_id or default or self._library_id or session.library_id
273
+ if not library:
274
+ raise NoLibraryError("No library given (see libraries.find())")
275
+ path_values["agencyId"] = library
276
+ path = _base.fill_path(template, path_values)
277
+
278
+ tokens = await self._fresh_tokens()
279
+ kwargs: dict[str, Any] = {"params": _base.query(params), "json": json}
280
+ response = await self._send(method, template, path, session, tokens, **kwargs)
281
+ if response.status_code == 401 and tokens is not None:
282
+ async with self._refresh_lock:
283
+ if session.tokens is tokens: # nobody refreshed while we waited
284
+ await self.refresh()
285
+ response = await self._send(method, template, path, session, session.tokens, **kwargs)
286
+ data = _base.payload(response)
287
+ return data if tp is Any else _base.parse(tp, data, method, template)
288
+
289
+ async def _send(
290
+ self,
291
+ method: str,
292
+ template: str,
293
+ path: str,
294
+ session: Session,
295
+ tokens: Tokens | None,
296
+ **kwargs: Any,
297
+ ) -> httpx.Response:
298
+ headers = _base.headers(method, template, session.installation_id, tokens)
299
+ try:
300
+ return await self._http.request(
301
+ method, f"{self._base_url}{path}", headers=headers, **kwargs
302
+ )
303
+ except httpx.TransportError as err:
304
+ raise BibloConnectionError(f"The Biblo API could not be reached: {err}") from err
biblo/_async/login.py ADDED
@@ -0,0 +1,76 @@
1
+ """The browser's part of logging in, done over plain HTTP.
2
+
3
+ The app opens login.bib.dk's /oauth/authorize in a browser tab. The user picks their library
4
+ and types their card number or CPR and pincode into an ordinary HTML form, and login.bib.dk
5
+ redirects to `biblo://?code=...`. This module submits that form and returns the code.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from urllib.parse import urljoin
11
+
12
+ import httpx
13
+
14
+ from .._base import authorize_url, code_from_redirect, login_form_action, login_page_error
15
+ from .._constants import BROWSER_USER_AGENT, LOGIN_BASE_URL, LOGIN_MAX_REDIRECTS, REDIRECT_URI
16
+ from ..exceptions import InvalidCredentialsError, LoginFlowError
17
+
18
+
19
+ async def password_login_code(
20
+ http: httpx.AsyncClient, user_id: str, pincode: str, library_id: str
21
+ ) -> str:
22
+ """Log in with card number or CPR + pincode at a library; return the OAuth code."""
23
+ try:
24
+ page = await _follow(http, await _get(http, authorize_url()))
25
+ if isinstance(page, str): # login.bib.dk remembered a session despite force_login
26
+ return code_from_redirect(page)
27
+ action = login_form_action(page.text)
28
+ if action is None:
29
+ raise LoginFlowError(
30
+ f"No library login form on {page.url}; has login.bib.dk changed its page?"
31
+ )
32
+ response = await http.post(
33
+ urljoin(str(page.url), action),
34
+ data={
35
+ "agency": library_id,
36
+ "loginBibDkUserId": user_id.strip(),
37
+ "pincode": pincode.strip(),
38
+ },
39
+ headers={"User-Agent": BROWSER_USER_AGENT},
40
+ follow_redirects=False,
41
+ )
42
+ result = await _follow(http, response)
43
+ finally:
44
+ _forget_login_cookies(http)
45
+
46
+ if isinstance(result, str):
47
+ return code_from_redirect(result)
48
+ if login_form_action(result.text) is not None:
49
+ raise InvalidCredentialsError(
50
+ login_page_error(result.text) or "login.bib.dk refused the card number/CPR or pincode"
51
+ )
52
+ raise LoginFlowError(f"login.bib.dk did not send the browser back to the app ({result.url})")
53
+
54
+
55
+ async def _get(http: httpx.AsyncClient, url: str) -> httpx.Response:
56
+ return await http.get(url, headers={"User-Agent": BROWSER_USER_AGENT}, follow_redirects=False)
57
+
58
+
59
+ async def _follow(http: httpx.AsyncClient, response: httpx.Response) -> httpx.Response | str:
60
+ """Follow redirects to a page, or return the biblo:// URL when the flow reaches it."""
61
+ for _ in range(LOGIN_MAX_REDIRECTS):
62
+ if not response.has_redirect_location:
63
+ return response
64
+ location = urljoin(str(response.url), response.headers["location"])
65
+ if location.startswith(REDIRECT_URI):
66
+ return location
67
+ response = await _get(http, location)
68
+ raise LoginFlowError("Too many redirects on login.bib.dk")
69
+
70
+
71
+ def _forget_login_cookies(http: httpx.AsyncClient) -> None:
72
+ """Don't leave login.bib.dk's cookies in an httpx client the caller may share."""
73
+ domain = LOGIN_BASE_URL.removeprefix("https://")
74
+ for cookie in list(http.cookies.jar):
75
+ if cookie.domain.lstrip(".") == domain:
76
+ http.cookies.jar.clear(cookie.domain, cookie.path, cookie.name)