Coverage for src/scixplorer/models/library.py: 98%
371 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""ADS libraries ("biblib"): collections of documents curated by ADS users.
3Every interaction is first described without I/O: a private function builds the
4:class:`~scixplorer.client.Request`, or a generator in the sans-IO backend protocol of
5:mod:`scixplorer.query` yields the requests and returns the result
6(:func:`fetch_library`, :func:`fetch_bibcodes`). The public methods of
7:class:`Library` only send those requests and update the object from the
8responses, one API call per method.
9"""
11from __future__ import annotations
13from collections.abc import Generator, Iterable, Iterator, Mapping
14from typing import TYPE_CHECKING, Any, TypeVar
15from urllib.parse import quote
17from ..client import Client, Request, Response, get_default_client
18from ..exceptions import SciXError, APIError
19from ..expr import And, Expr, In, Match
20from ..fields import BooleanField, DateTimeField, Field, IntegerField, StringField
21from ..model import Model
22from ..query import Explanation, Query, drive, filter_rows, select_rows
23from ..utils import _require_bibcodes, _response_field, to_bibcodes
25if TYPE_CHECKING:
26 # ``scixplorer.models.document`` is written separately. Until it exists, ``Document``
27 # is ``Any`` here; ``unused-ignore`` keeps this line valid once it does.
28 from .document import Document # type: ignore[import-not-found, unused-ignore]
30__all__ = ["DEFAULT_PAGE_SIZE", "Library", "LibraryBackend", "fetch_bibcodes", "fetch_library"]
32T = TypeVar("T")
34#: Bibcodes requested per page by :func:`fetch_bibcodes`.
35DEFAULT_PAGE_SIZE = 2000
37_LIBRARIES = "/biblib/libraries"
40# Requests. Each is a pure function of its arguments.
43def _path(prefix: str, library_id: str) -> str:
44 """``/biblib/<prefix>/<library_id>``, with the id percent-encoded as one path segment."""
45 return f"/biblib/{prefix}/{quote(library_id, safe='')}"
48def _list_request() -> Request:
49 """List the caller's libraries."""
50 return Request("GET", _LIBRARIES)
53def _get_request(library_id: str, *, start: int | None = None, rows: int | None = None) -> Request:
54 """Fetch one library's metadata and (a page of) its bibcodes."""
55 params = {key: value for key, value in (("start", start), ("rows", rows)) if value is not None}
56 return Request("GET", _path("libraries", library_id), params=params or None)
59def _create_request(
60 name: str | None, description: str | None, public: bool, bibcodes: list[str]
61) -> Request:
62 """Create a library. ``None`` name or description are left for ADS to choose."""
63 payload: dict[str, Any] = {}
64 if name is not None:
65 payload["name"] = name
66 if description is not None:
67 payload["description"] = description
68 payload["public"] = public
69 if bibcodes:
70 payload["bibcode"] = bibcodes
71 return Request("POST", _LIBRARIES, json=payload)
74def _update_request(library_id: str, changes: Mapping[str, Any]) -> Request:
75 """Change a library's name, description or visibility (note: ``documents``, not ``libraries``)."""
76 return Request("PUT", _path("documents", library_id), json=dict(changes))
79def _documents_request(library_id: str, action: str, bibcodes: list[str]) -> Request:
80 """Add (``action="add"``) or remove (``"remove"``) documents."""
81 return Request("POST", _path("documents", library_id), json={"bibcode": bibcodes, "action": action})
84def _delete_request(library_id: str) -> Request:
85 """Delete a library."""
86 return Request("DELETE", _path("documents", library_id))
89def _operation_request(
90 library_id: str,
91 action: str,
92 libraries: Iterable[str] = (),
93 *,
94 name: str | None = None,
95 description: str | None = None,
96 public: bool | None = None,
97) -> Request:
98 """A set operation: ``union``, ``intersection``, ``difference``, ``copy`` or ``empty``.
100 Only ``empty`` is safe to repeat; the others create a library or add documents.
101 """
102 payload: dict[str, Any] = {"action": action}
103 others = list(libraries)
104 if others:
105 payload["libraries"] = others
106 for key, value in (("name", name), ("description", description), ("public", public)):
107 if value is not None:
108 payload[key] = value
109 return Request(
110 "POST",
111 _path("libraries/operations", library_id),
112 json=payload,
113 idempotent=True if action == "empty" else None,
114 )
117def _get_permissions_request(library_id: str) -> Request:
118 """List who may access a library."""
119 return Request("GET", _path("permissions", library_id))
122def _set_permissions_request(
123 library_id: str, email: str, *, read: bool, write: bool, admin: bool
124) -> Request:
125 """Set one user's permissions. Setting the same permissions twice is harmless."""
126 payload = {"email": email, "permission": {"read": read, "write": write, "admin": admin}}
127 return Request("POST", _path("permissions", library_id), json=payload, idempotent=True)
130def _transfer_request(library_id: str, email: str) -> Request:
131 """Make another user the owner of a library."""
132 return Request("POST", _path("transfer", library_id), json={"email": email})
135# Responses.
138def _unexpected(request: Request, response: Response, detail: str) -> APIError:
139 return APIError(
140 f"{request.method} {request.path}: unexpected response from ADS ({detail})",
141 status_code=response.status_code,
142 response=response,
143 )
146def _object(request: Request, response: Response, *keys: str) -> dict[str, Any]:
147 """``response.data[keys...]``, which must be a JSON object."""
148 value = _response_field(request, response, *keys) if keys else response.data
149 if not isinstance(value, dict):
150 raise _unexpected(request, response, f"expected a JSON object, got {type(value).__name__}")
151 return value
154def _strings(request: Request, response: Response, *keys: str) -> list[str]:
155 """``response.data[keys...]``, which must be a list of strings."""
156 value = _response_field(request, response, *keys)
157 if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
158 raise _unexpected(request, response, f"{keys[-1]!r} is not a list of strings")
159 return value
162def _count(request: Request, response: Response, key: str) -> int:
163 value = _response_field(request, response, key)
164 if isinstance(value, bool) or not isinstance(value, int):
165 raise _unexpected(request, response, f"{key!r} is not an integer")
166 return value
169def _listing(request: Request, response: Response) -> list[dict[str, Any]]:
170 """The metadata of each library in a ``GET /biblib/libraries`` response."""
171 libraries = _response_field(request, response, "libraries")
172 if not isinstance(libraries, list) or not all(isinstance(item, dict) for item in libraries):
173 raise _unexpected(request, response, "'libraries' is not a list of objects")
174 return libraries
177def _permissions(request: Request, response: Response) -> dict[str, list[str]]:
178 """Merge ADS's list of single-key ``{email: [permission, ...]}`` objects into one dict."""
179 entries = response.data
180 if not isinstance(entries, list) or not all(isinstance(entry, dict) for entry in entries):
181 raise _unexpected(request, response, "expected a list of {email: [permission, ...]} objects")
182 merged: dict[str, list[str]] = {}
183 for entry in entries:
184 for email, permissions in entry.items():
185 if not isinstance(permissions, list): 185 ↛ 186line 185 didn't jump to line 186 because the condition on line 185 was never true
186 raise _unexpected(request, response, f"permissions of {email!r} are not a list")
187 merged.setdefault(email, []).extend(permissions)
188 return merged
191# Generators in the backend protocol, for use by other modules too.
194def fetch_library(library_id: str) -> Generator[Request, Response, dict[str, Any]]:
195 """Yield the request for one library and return its metadata dict.
197 Works for any library the caller may read, including other users' public
198 libraries. The response also carries the first page of bibcodes, which is
199 ignored (use :func:`fetch_bibcodes` for those).
200 """
201 _check_id(library_id)
202 return _fetch_library(library_id)
205def _fetch_library(library_id: str) -> Generator[Request, Response, dict[str, Any]]:
206 request = _get_request(library_id)
207 response = yield request
208 return _object(request, response, "metadata")
211def fetch_bibcodes(
212 library_id: str, *, page_size: int = DEFAULT_PAGE_SIZE
213) -> Generator[Request, Response, list[str]]:
214 """Yield the requests for every bibcode in a library and return them, in order, de-duplicated.
216 Pages through ``GET /biblib/libraries/<id>`` with ``start``/``rows``,
217 advancing ``start`` by the number of bibcodes each page returned (so a
218 server that caps ``rows`` below ``page_size`` loses nothing). It stops when
219 ``start`` reaches the library's ``num_documents``, or when a page adds no
220 new bibcode (an empty page, or a server that ignores ``start``). Only if
221 ``num_documents`` is missing does a short page end the listing, because ADS
222 may return fewer bibcodes than ``num_documents`` says. Arguments are
223 checked when this is called, not when the generator starts.
224 """
225 _check_id(library_id)
226 if isinstance(page_size, bool) or not isinstance(page_size, int) or page_size < 1:
227 raise ValueError(f"page_size must be a positive int, not {page_size!r}")
228 return _fetch_bibcodes(library_id, page_size)
231def _fetch_bibcodes(library_id: str, page_size: int) -> Generator[Request, Response, list[str]]:
232 found: dict[str, None] = {}
233 start = 0
234 while True:
235 request = _get_request(library_id, start=start, rows=page_size)
236 response = yield request
237 page = _strings(request, response, "documents")
238 total = _object(request, response, "metadata").get("num_documents")
239 before = len(found)
240 found.update(dict.fromkeys(page))
241 start += len(page)
242 if len(found) == before:
243 break
244 if isinstance(total, int) and not isinstance(total, bool):
245 if start >= total:
246 break
247 elif len(page) < page_size:
248 break
249 return list(found)
252def _complete(gen: Generator[Request, Response, T], client: Client) -> T:
253 """Run a generator that only yields Requests with ``client`` and return its result."""
254 driven = drive(gen, client.send)
255 try:
256 item = next(driven)
257 except StopIteration as stop:
258 result: T = stop.value
259 return result
260 driven.close()
261 raise TypeError(f"expected only Requests from {gen!r}, got {item!r}")
264# Querying.
267def _pinned_ids(expr: Expr | None, id_field: Field[Any, Any]) -> tuple[str, ...] | None:
268 """The library ids a query is restricted to, or ``None`` if it is not restricted.
270 Only top-level conjuncts ``id == v`` and ``id.in_(vs)`` pin ids (several
271 pins intersect); anything under ``|`` or ``~`` does not.
272 """
273 if expr is None:
274 return None
275 conjuncts = expr.operands if isinstance(expr, And) else (expr,)
276 pinned: list[str] | None = None
277 for conjunct in conjuncts:
278 if isinstance(conjunct, Match) and conjunct.field is id_field:
279 values: tuple[Any, ...] = (conjunct.value,)
280 elif isinstance(conjunct, In) and conjunct.field is id_field:
281 values = conjunct.values
282 else:
283 continue
284 if not all(isinstance(value, str) for value in values): 284 ↛ 285line 284 didn't jump to line 285 because the condition on line 284 was never true
285 continue
286 ids = list(dict.fromkeys(values))
287 pinned = ids if pinned is None else [i for i in pinned if i in ids]
288 return None if pinned is None else tuple(pinned)
291class LibraryBackend:
292 """Runs :class:`Library` queries: fetch metadata from ADS, then filter locally.
294 A query whose filter pins library ids (a top-level ``Library.id == v`` or
295 ``Library.id.in_(vs)``) fetches exactly those libraries, so other users'
296 public libraries can be found; an id ADS does not know (404) yields no row.
297 Any other query lists the caller's own libraries with one request. The
298 filter, ordering, offset and limit are then applied in Python.
299 """
301 def __repr__(self) -> str:
302 return "<LibraryBackend>"
304 def run(self, query: Query[Any]) -> Generator[Request | list[Any], Response | None, None]:
305 """Yield the requests, then the matching libraries as one batch."""
306 rows = yield from self._fetch(query)
307 yield select_rows(rows, query)
309 def count(self, query: Query[Any]) -> Generator[Request, Response, int]:
310 """Yield the requests and return the number of matching libraries."""
311 rows = yield from self._fetch(query)
312 return len(filter_rows(rows, query))
314 def explain(self, query: Query[Any]) -> Explanation:
315 """Show the request(s) that would be sent; filtering happens locally."""
316 ids = _pinned_ids(query.expr, query.model._fields["id"])
317 if ids is None:
318 summary = "Lists your libraries with one request, then filters them locally."
319 requests: tuple[Request, ...] = (_list_request(),)
320 else:
321 noun = "library" if len(ids) == 1 else "libraries"
322 summary = f"Fetches {len(ids)} {noun} by id, then filters them locally."
323 requests = tuple(_get_request(library_id) for library_id in ids)
324 notes = ["filtering, ordering, offset and limit are applied locally to the library metadata"]
325 if ids is not None:
326 notes.append("an id that ADS does not know yields no row")
327 if query.expr is not None: 327 ↛ 329line 327 didn't jump to line 329 because the condition on line 327 was always true
328 notes.append(f"filter: {query.expr!r}")
329 return Explanation(summary, requests, tuple(notes))
331 def _fetch(self, query: Query[Any]) -> Generator[Request, Response, list[Any]]:
332 model = query.model
333 ids = _pinned_ids(query.expr, model._fields["id"])
334 if ids is None:
335 request = _list_request()
336 response = yield request
337 found = _listing(request, response)
338 else:
339 found = []
340 for library_id in ids:
341 try:
342 metadata = yield from fetch_library(library_id)
343 except APIError as exc:
344 if exc.status_code == 404:
345 continue
346 raise
347 found.append(metadata)
348 rows = []
349 for metadata in found:
350 row = model._from_row(metadata)
351 # The metadata is complete: reading a field ADS did not send must
352 # not make a request per row while the query is being filtered.
353 row._metadata_fetched = True
354 rows.append(row)
355 return rows
358# The model.
361def _check_id(library_id: Any) -> str:
362 if not isinstance(library_id, str) or not library_id.strip():
363 raise ValueError(f"a library id must be a non-empty str, not {library_id!r}")
364 return library_id
367def _check_email(email: Any) -> str:
368 if not isinstance(email, str) or "@" not in email or not email.strip():
369 raise ValueError(f"expected an email address, not {email!r}")
370 return email.strip()
373def _check_metadata(name: Any, description: Any, public: Any) -> None:
374 for label, value in (("name", name), ("description", description)):
375 if value is not None and not isinstance(value, str):
376 raise TypeError(f"{label} must be a str, not {type(value).__name__}")
377 if public is not None and not isinstance(public, bool):
378 raise TypeError(f"public must be a bool, not {type(public).__name__}")
381def _other_id(library: Any) -> str:
382 """The id of another library given as a :class:`Library` or an id string."""
383 if isinstance(library, Library):
384 return library._remote_id()
385 if isinstance(library, str):
386 return _check_id(library)
387 raise TypeError(f"expected a Library or a library id, not {type(library).__name__}")
390class Library(Model):
391 """An ADS library: a named collection of documents kept by ADS for a user.
393 Find libraries with queries (``Library.get(name="Gaia")``,
394 ``Library.select().where(Library.num_documents > 100)``), which list your
395 libraries and filter them locally; a query pinning ``Library.id`` fetches
396 that library directly, so other users' public libraries work too. Create one
397 with :meth:`create`. Every other change is an explicit method making one
398 API call (:meth:`update`, :meth:`add`, :meth:`remove`, :meth:`empty`,
399 :meth:`delete`, set operations, permissions); nothing is saved implicitly,
400 and assigning to a field only changes the local object.
402 Metadata fields missing from the object (for example after :meth:`create`)
403 are fetched together, once, on first access. :attr:`bibcodes` is fetched on
404 first access and cached until a method changes the documents. Fields the
405 server maintains (such as ``date_last_modified``) are not updated locally by
406 the methods; call :meth:`refresh` for that.
408 Requests are sent with the ``client=`` argument of a method if given, else
409 with the client in the ``client`` attribute (``None`` unless set by the
410 user, or by :meth:`create` and the set operations when given a client),
411 else with :func:`~scixplorer.client.get_default_client`. Lazy loading and
412 :attr:`bibcodes` use the attribute or the default. Libraries returned by a
413 query do not remember the query's client: set ``library.client`` if needed.
414 """
416 _key = "id"
417 _backend = LibraryBackend()
419 id = StringField("Unique identifier of the library, assigned by ADS.")
420 name = StringField("Name of the library (unique among its owner's libraries).")
421 description = StringField("Description of the library.")
422 public = BooleanField("Whether anyone may read the library.")
423 owner = StringField("ADS username of the owner (not their email address).")
424 permission = StringField("Your own access level: 'owner', 'admin', 'write' or 'read'.")
425 num_documents = IntegerField("Number of documents in the library.")
426 num_users = IntegerField("Number of users with access to the library.")
427 date_created = DateTimeField("When the library was created (UTC).")
428 date_last_modified = DateTimeField("When the library was last modified (UTC).")
430 def __init__(self, **values: Any):
431 self.client: Client | None = None
432 self._bibcodes: tuple[str, ...] | None = None
433 self._metadata_fetched = False
434 self._deleted = False
435 super().__init__(**values)
437 # Creating.
439 @classmethod
440 def create(
441 cls,
442 name: str | None = None,
443 description: str | None = None,
444 public: bool = False,
445 documents: Any = (),
446 *,
447 client: Client | None = None,
448 ) -> Library:
449 """Create a library on ADS and return it.
451 :param name: the name, which must be unique among your libraries;
452 if ``None`` it is not sent and ADS assigns one.
453 :param description: the description; if ``None`` it is not sent.
454 :param public: whether anyone may read the library.
455 :param documents: bibcodes, documents, libraries, or iterables of these.
456 :param client: the client to use; it is also remembered as ``client``
457 on the returned library.
458 """
459 _check_metadata(name, description, public)
460 request = _create_request(name, description, public, to_bibcodes(documents))
461 response = _resolve(client).send(request)
462 sent = {"name": name, "description": description, "public": public}
463 return cls._created(request, response, sent, client)
465 @classmethod
466 def _created(
467 cls, request: Request, response: Response, sent: Mapping[str, Any], client: Client | None
468 ) -> Library:
469 """The library ADS just created: what it returned, plus what was sent."""
470 data = _object(request, response)
471 library_id = _response_field(request, response, "id")
472 if not isinstance(library_id, str) or not library_id.strip():
473 raise _unexpected(request, response, f"'id' is {library_id!r}")
474 library = cls._from_row(data)
475 for key, value in sent.items():
476 if value is not None and key not in library._data:
477 library._data[key] = value
478 library.client = client
479 return library
481 # Metadata.
483 def update(
484 self,
485 *,
486 name: str | None = None,
487 description: str | None = None,
488 public: bool | None = None,
489 client: Client | None = None,
490 ) -> None:
491 """Change the name, description and/or visibility on ADS, and locally.
493 Only the arguments given are sent. Raises ``ValueError`` if none is given.
494 """
495 _check_metadata(name, description, public)
496 changes = {
497 key: value
498 for key, value in (("name", name), ("description", description), ("public", public))
499 if value is not None
500 }
501 if not changes:
502 raise ValueError("update() needs at least one of name, description or public")
503 self._send(_update_request(self._remote_id(), changes), client)
504 self._data.update(changes)
506 def refresh(self, *, client: Client | None = None) -> Library:
507 """Fetch the metadata again, replacing the local values, and forget cached bibcodes."""
508 metadata = _complete(fetch_library(self._remote_id()), self._client(client))
509 self._data.update(self._convert(metadata))
510 self._metadata_fetched = True
511 self._bibcodes = None
512 return self
514 def _load_missing(self, field: Field[Any, Any]) -> Any:
515 """Fetch the metadata once and fill every field that is still missing."""
516 if self._metadata_fetched or self._data.get("id") is None:
517 return None
518 metadata = _complete(fetch_library(self._remote_id()), self._client(None))
519 self._metadata_fetched = True
520 for name, value in self._convert(metadata).items():
521 self._data.setdefault(name, value)
522 return self._data.get(field.name)
524 @classmethod
525 def _convert(cls, metadata: Mapping[str, Any]) -> dict[str, Any]:
526 """Field values (by field name) from an API metadata mapping."""
527 return {
528 field.name: field.to_python(metadata[field.solr_name])
529 for field in cls._fields.values()
530 if field.solr_name in metadata
531 }
533 # Documents.
535 @property
536 def bibcodes(self) -> tuple[str, ...]:
537 """The bibcodes of the documents, fetched on first access and cached."""
538 if self._bibcodes is None:
539 library_id = self._remote_id()
540 self._bibcodes = tuple(_complete(fetch_bibcodes(library_id), self._client(None)))
541 return self._bibcodes
543 @property
544 def documents(self) -> Query[Document]:
545 """A query for the documents in this library, searched on ADS."""
546 self._remote_id()
547 from .document import Document # type: ignore[import-not-found, unused-ignore] # see top of module
549 query: Query[Document] = Document.select().where(Document.in_(self))
550 return query
552 def add(self, *documents: Any, client: Client | None = None) -> int:
553 """Add documents (bibcodes, documents, libraries, or iterables of these).
555 Returns the number ADS actually added (documents already present are not).
556 """
557 return self._change("add", "number_added", documents, client)
559 def remove(self, *documents: Any, client: Client | None = None) -> int:
560 """Remove documents; returns the number ADS actually removed."""
561 return self._change("remove", "number_removed", documents, client)
563 def _change(self, action: str, key: str, documents: tuple[Any, ...], client: Client | None) -> int:
564 library_id = self._remote_id()
565 request = _documents_request(library_id, action, _require_bibcodes(documents))
566 changed = _count(request, self._send(request, client), key)
567 self._bibcodes = None
568 current = self._data.get("num_documents")
569 if isinstance(current, int):
570 self._data["num_documents"] = max(0, current + (changed if action == "add" else -changed))
571 return changed
573 def empty(self, *, client: Client | None = None) -> None:
574 """Remove every document."""
575 self._send(_operation_request(self._remote_id(), "empty"), client)
576 self._data["num_documents"] = 0
577 self._bibcodes = ()
579 def delete(self, *, client: Client | None = None) -> None:
580 """Delete the library from ADS. The object can no longer be used afterwards."""
581 self._send(_delete_request(self._remote_id()), client)
582 self._deleted = True
583 self._bibcodes = None
585 # Set operations.
587 def union(
588 self,
589 *libraries: Library | str,
590 name: str | None = None,
591 description: str | None = None,
592 public: bool = False,
593 client: Client | None = None,
594 ) -> Library:
595 """Create a library holding the documents in this library or any of ``libraries``."""
596 return self._combine("union", libraries, name, description, public, client)
598 def intersection(
599 self,
600 *libraries: Library | str,
601 name: str | None = None,
602 description: str | None = None,
603 public: bool = False,
604 client: Client | None = None,
605 ) -> Library:
606 """Create a library holding the documents in this library and all of ``libraries``."""
607 return self._combine("intersection", libraries, name, description, public, client)
609 def difference(
610 self,
611 *libraries: Library | str,
612 name: str | None = None,
613 description: str | None = None,
614 public: bool = False,
615 client: Client | None = None,
616 ) -> Library:
617 """Create a library holding the documents in this library but in none of ``libraries``."""
618 return self._combine("difference", libraries, name, description, public, client)
620 def _combine(
621 self,
622 action: str,
623 libraries: tuple[Library | str, ...],
624 name: str | None,
625 description: str | None,
626 public: bool,
627 client: Client | None,
628 ) -> Library:
629 library_id = self._remote_id()
630 if not libraries:
631 raise ValueError(f"{action}() needs at least one other library")
632 _check_metadata(name, description, public)
633 request = _operation_request(
634 library_id,
635 action,
636 [_other_id(library) for library in libraries],
637 name=name,
638 description=description,
639 public=public,
640 )
641 response = self._send(request, client)
642 sent = {"name": name, "description": description, "public": public}
643 return type(self)._created(request, response, sent, client)
645 def copy_to(self, library: Library | str, *, client: Client | None = None) -> None:
646 """Add this library's documents to ``library`` (a :class:`Library` or an id)."""
647 request = _operation_request(self._remote_id(), "copy", [_other_id(library)])
648 self._send(request, client)
649 if isinstance(library, Library):
650 library._bibcodes = None
651 if library._data.pop("num_documents", None) is not None: 651 ↛ exitline 651 didn't return from function 'copy_to' because the condition on line 651 was always true
652 library._metadata_fetched = False
654 # Permissions.
656 def get_permissions(self, *, client: Client | None = None) -> dict[str, list[str]]:
657 """Who may access the library: ``{email: ["owner"] or ["read", "write", ...]}``."""
658 request = _get_permissions_request(self._remote_id())
659 return _permissions(request, self._send(request, client))
661 def set_permissions(
662 self,
663 email: str,
664 *,
665 read: bool = False,
666 write: bool = False,
667 admin: bool = False,
668 client: Client | None = None,
669 ) -> None:
670 """Set the permissions of the ADS user with this email address (all ``False`` revokes them)."""
671 address = _check_email(email)
672 for label, value in (("read", read), ("write", write), ("admin", admin)):
673 if not isinstance(value, bool):
674 raise TypeError(f"{label} must be a bool, not {type(value).__name__}")
675 request = _set_permissions_request(self._remote_id(), address, read=read, write=write, admin=admin)
676 self._send(request, client)
678 def transfer(self, email: str, *, client: Client | None = None) -> None:
679 """Make the ADS user with this email address the owner.
681 You lose all access to the library unless the new owner grants it.
682 """
683 address = _check_email(email)
684 self._send(_transfer_request(self._remote_id(), address), client)
686 # Python protocols.
688 def __iter__(self) -> Iterator[Any]:
689 """Iterate over the documents (searched on ADS)."""
690 return iter(self.documents)
692 def __len__(self) -> int:
693 """The number of documents, as ADS reports it in ``num_documents``."""
694 count = self.num_documents
695 if count is None:
696 raise SciXError(f"{self!r}: the number of documents is not known")
697 return count
699 def __contains__(self, item: object) -> bool:
700 """Whether a document (a bibcode or an object with a ``bibcode``) is in the library."""
701 bibcodes = to_bibcodes(item)
702 if len(bibcodes) != 1:
703 raise ValueError(f"`in` needs a single bibcode or document, not {item!r}")
704 return bibcodes[0] in self.bibcodes
706 def __bool__(self) -> bool:
707 """Always true: an empty library is still a library."""
708 return True
710 def __repr__(self) -> str:
711 library_id = self._data.get("id")
712 if library_id is None:
713 return super().__repr__()
714 name = self._data.get("name")
715 return f"<Library: id={library_id!r}{f' name={name!r}' if name is not None else ''}>"
717 # Helpers.
719 def _remote_id(self) -> str:
720 """This library's id; raises ``SciXError`` if it was deleted or never existed on ADS."""
721 if self._deleted:
722 raise SciXError(f"{self!r} was deleted from ADS and can no longer be used")
723 library_id = self._data.get("id")
724 if library_id is None:
725 raise SciXError(f"{self!r} has no id, so it is not on ADS; use Library.create()")
726 return _check_id(library_id)
728 def _client(self, client: Client | None) -> Client:
729 return client if client is not None else _resolve(self.client)
731 def _send(self, request: Request, client: Client | None) -> Response:
732 return self._client(client).send(request)
735def _resolve(client: Client | None) -> Client:
736 return client if client is not None else get_default_client()