Skip to content

comicbox.readinglists.session ¶

ReadingListSession: the façade codex holds to fetch reading lists.

Synchronous: each call is one fetch, with no prompt loop. Network libraries are imported inside methods, so importing this module stays cheap. A fetch that fails raises ReadingListFetchError; a cancel raises OnlineLookupAbortedError, as tagging does.

ReadingListSession ¶

Fetch reading lists from URLs and online sources.

credentials are an OnlineCredentials, as OnlineSession takes; without them the config’s online.auth is used. config is a ComicboxSettings; without it the usual config files and environment are read once. on_event receives the ReadingListFetch* events. client_name names the embedding application in the outgoing User-Agent.

A context manager: leaving it closes the connections the session opened.

Source code in comicbox/readinglists/session.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
class ReadingListSession:
    """
    Fetch reading lists from URLs and online sources.

    ``credentials`` are an ``OnlineCredentials``, as ``OnlineSession``
    takes; without them the config's ``online.auth`` is used. ``config``
    is a ``ComicboxSettings``; without it the usual config files and
    environment are read once. ``on_event`` receives the
    ``ReadingListFetch*`` events. ``client_name`` names the embedding
    application in the outgoing User-Agent.

    A context manager: leaving it closes the connections the session
    opened.
    """

    def __init__(
        self,
        *,
        credentials: OnlineCredentials | None = None,
        config: ComicboxSettings | None = None,
        on_event: EventHandler | None = None,
        client_name: str | None = None,
    ) -> None:
        """Read the config once; open nothing until the first fetch."""
        if client_name is not None:
            # Set before any client exists: clients bake the header in.
            set_user_agent_context("lib", client=client_name)
        self._credentials = credentials
        self._settings: ComicboxSettings = (
            config if config is not None else get_config()
        )
        self._on_event = on_event
        self._cancelled = threading.Event()
        self._http: httpx.Client | None = None
        # Tests and embedders may set an httpx transport before first use.
        self._transport: httpx.BaseTransport | None = None

    def __enter__(self) -> Self:
        """Use the session in a with block."""
        return self

    def __exit__(self, *_exc_info: object) -> None:
        """Close the session's connections."""
        self.close()

    @property
    def settings(self) -> ComicboxSettings:
        """The settings every fetch uses."""
        return self._settings

    @property
    def credentials(self) -> OnlineCredentials | None:
        """The credentials the session was given, if any."""
        return self._credentials

    def cancel(self) -> None:
        """Stop the session: the fetch under way, or the next, raises."""
        self._cancelled.set()

    def close(self) -> None:
        """
        Close the HTTP client and Metron's shared sessions, if opened.

        Comic Vine's shared client is left open. Closing it closes its
        rate-limit buckets, which can fail a tagging lookup in the same
        process that holds one; ``OnlineSession.close`` releases it.
        """
        if self._http is not None:
            self._http.close()
            self._http = None
        if (metron := sys.modules.get(_METRON_SOURCE_MODULE)) is not None:
            metron.close_shared_sessions()

    # Internals shared by the sources.

    def check_cancelled(self) -> None:
        """Raise if the session was cancelled."""
        if self._cancelled.is_set():
            reason = "Reading-list fetch cancelled."
            raise OnlineLookupAbortedError(reason)

    @property
    def cancelled(self) -> threading.Event:
        """The event ``cancel()`` sets, for sources that wait."""
        return self._cancelled

    def emit(self, event: Event) -> None:
        """Hand an event to the caller's handler, if any."""
        if self._on_event is not None:
            self._on_event(event)

    def http(self) -> httpx.Client:
        """Get the session's HTTP client, built on first use."""
        if self._http is None:
            import httpx

            self._http = httpx.Client(
                follow_redirects=True,
                timeout=_TIMEOUT_SECONDS,
                headers={"User-Agent": user_agent()},
                transport=self._transport,
            )
        return self._http

    @contextmanager
    def fetching(self, kind: str, key: str) -> Generator[None]:
        """Bracket one fetch with its start and finish events."""
        self.check_cancelled()
        self.emit(ReadingListFetchStarted(source=kind, key=key))
        try:
            yield
        finally:
            self.emit(ReadingListFetchFinished(source=kind, key=key))

    def load_fetched(self, data: bytes, source: dict[str, Any]) -> ReadingListResult:
        """
        Read fetched bytes as a list from ``source``, detecting the format.

        A document that will not read names where it came from, as a
        file's error names its path.
        """
        try:
            result = loads(data)
        except ReadingListFormatError as exc:
            where = source.get(SOURCE_URL_KEY) or source.get(SOURCE_KEY_KEY)
            reason = f"{where}: {exc}"
            raise type(exc)(reason) from exc
        reading_list = attach_source(result.reading_list, source)
        return ReadingListResult(reading_list, result.fmt, result.warnings)

    # Fetches.

    def fetch_url(self, url: str) -> ReadingListResult:
        """
        Fetch a list from an http or https URL, in any format comicbox reads.

        Redirects are followed and the download is capped at
        ``readinglists.max_download_bytes``. Its source is of kind ``url``.
        A user name and password in the URL are sent, and never recorded.
        """
        from comicbox.readinglists.sources.url import fetch, without_userinfo

        kind = SourceKind.URL.value
        # A user name and password in the URL go with the request; they are
        # never recorded on the list, nor shown in an event or an error.
        shown = without_userinfo(url)
        with self.fetching(kind, shown):
            max_bytes = self._settings.readinglists.max_download_bytes
            data, revision = fetch(
                self.http(), url, max_bytes, cancelled=self._cancelled.is_set
            )
            self.check_cancelled()
            source = {
                SOURCE_KIND_KEY: kind,
                SOURCE_KEY_KEY: shown,
                SOURCE_URL_KEY: shown,
                SOURCE_REVISION_KEY: revision,
            }
            return self.load_fetched(data, source)

    def search_metron(
        self,
        *,
        name: str | None = None,
        curator: str | None = None,
        username: str | None = None,
        modified_since: datetime | None = None,
    ) -> list[MetronListSummary]:
        """
        Search Metron's reading lists: public ones and the token's own.

        ``curator`` is a site Metron credits lists to, such as ``cbro``.
        Needs a Metron API token.
        """
        from comicbox.readinglists.sources import metron

        self.check_cancelled()
        found = metron.search(
            self,
            name=name,
            curator=curator,
            username=username,
            modified_since=modified_since,
        )
        self.check_cancelled()
        return found

    def fetch_metron_list(
        self, list_id: int, *, if_modified_since: datetime | None = None
    ) -> ReadingListResult | None:
        """
        Fetch a Metron reading list, in its order.

        Returns None, having fetched no items, when the list is unchanged
        since ``if_modified_since``. Progress events count the items as
        their pages arrive. Needs a Metron API token. The result has no
        ``fmt``: it was read from no document.
        """
        from comicbox.readinglists.sources import metron

        metron.check_token(self)
        with self.fetching(SourceKind.METRON_LIST.value, str(list_id)):
            result = metron.fetch_list(
                self, list_id, if_modified_since=if_modified_since
            )
            # A cancel during the last request still cancels.
            self.check_cancelled()
            return result

    def fetch_metron_arc(
        self, arc_id: int, *, if_modified_since: datetime | None = None
    ) -> ReadingListResult | None:
        """
        Fetch a Metron story arc as an unordered list.

        Returns None, having fetched no issues, when the arc is unchanged
        since ``if_modified_since``. Needs a Metron API token.
        """
        from comicbox.readinglists.sources import metron

        metron.check_token(self)
        with self.fetching(SourceKind.METRON_ARC.value, str(arc_id)):
            result = metron.fetch_arc(self, arc_id, if_modified_since=if_modified_since)
            self.check_cancelled()
            return result

    def fetch_comicvine_arc(self, arc_id: int) -> ReadingListResult:
        """
        Fetch a Comic Vine story arc as an unordered list.

        Comic Vine names an arc's issues by id alone, so after the arc come
        its issues, a hundred a call, then their volumes the same way: an
        arc of N issues in V volumes costs ``1 + ceil(N/100) + ceil(V/100)``
        calls, each on its own hourly budget. Progress events count the
        issues as they arrive. A budget already spent fails the fetch at
        once, saying when it frees, rather than waiting.

        Comic Vine has no conditional request, so there is no
        ``if_modified_since``: compare the result's source revision instead.
        Needs a Comic Vine API key. The result has no ``fmt``.
        """
        from comicbox.readinglists.sources import comicvine

        comicvine.check_key(self)
        with self.fetching(SourceKind.COMICVINE_ARC.value, str(arc_id)):
            result = comicvine.fetch_arc(self, arc_id)
            self.check_cancelled()
            return result

    def catalog(self, *, refresh: bool = False) -> Catalog:
        """
        Get the index of the reading-list catalog on GitHub.

        The repository and ref are ``readinglists.catalog_repo`` and
        ``catalog_ref``. The index is cached under the online cache
        directory: within ``readinglists.catalog_ttl`` no request is made,
        and after it the cached index is revalidated. ``refresh`` asks
        GitHub now.
        """
        from comicbox.readinglists.sources.catalog import load_catalog

        self.check_cancelled()
        catalog = load_catalog(self, refresh=refresh)[0]
        self.check_cancelled()
        return catalog

    def search_catalog(self, query: str) -> tuple[CatalogEntry, ...]:
        """Find the catalog's lists whose path holds every word of ``query``."""
        return self.catalog().search(query)

    def fetch_catalog(self, path: str, *, sha: str | None = None) -> ReadingListResult:
        """
        Fetch a list from the catalog by its path.

        Paths change there; when ``path`` is gone and ``sha`` names the
        blob it had, the list with that sha is fetched in its place. The
        result's source is of kind ``catalog``, keyed by the path it was
        found at, with the blob sha as its revision.
        """
        from comicbox.readinglists.sources.catalog import fetch_entry

        with self.fetching(SourceKind.CATALOG.value, path):
            data, source = fetch_entry(self, path, sha)
            self.check_cancelled()
            return self.load_fetched(data, source)

cancelled property ¶

The event cancel() sets, for sources that wait.

credentials property ¶

The credentials the session was given, if any.

settings property ¶

The settings every fetch uses.

__enter__() ¶

Use the session in a with block.

Source code in comicbox/readinglists/session.py
87
88
89
def __enter__(self) -> Self:
    """Use the session in a with block."""
    return self

__exit__(*_exc_info) ¶

Close the session’s connections.

Source code in comicbox/readinglists/session.py
91
92
93
def __exit__(self, *_exc_info: object) -> None:
    """Close the session's connections."""
    self.close()

__init__(*, credentials=None, config=None, on_event=None, client_name=None) ¶

Read the config once; open nothing until the first fetch.

Source code in comicbox/readinglists/session.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(
    self,
    *,
    credentials: OnlineCredentials | None = None,
    config: ComicboxSettings | None = None,
    on_event: EventHandler | None = None,
    client_name: str | None = None,
) -> None:
    """Read the config once; open nothing until the first fetch."""
    if client_name is not None:
        # Set before any client exists: clients bake the header in.
        set_user_agent_context("lib", client=client_name)
    self._credentials = credentials
    self._settings: ComicboxSettings = (
        config if config is not None else get_config()
    )
    self._on_event = on_event
    self._cancelled = threading.Event()
    self._http: httpx.Client | None = None
    # Tests and embedders may set an httpx transport before first use.
    self._transport: httpx.BaseTransport | None = None

cancel() ¶

Stop the session: the fetch under way, or the next, raises.

Source code in comicbox/readinglists/session.py
105
106
107
def cancel(self) -> None:
    """Stop the session: the fetch under way, or the next, raises."""
    self._cancelled.set()

catalog(*, refresh=False) ¶

Get the index of the reading-list catalog on GitHub.

The repository and ref are readinglists.catalog_repo and catalog_ref. The index is cached under the online cache directory: within readinglists.catalog_ttl no request is made, and after it the cached index is revalidated. refresh asks GitHub now.

Source code in comicbox/readinglists/session.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def catalog(self, *, refresh: bool = False) -> Catalog:
    """
    Get the index of the reading-list catalog on GitHub.

    The repository and ref are ``readinglists.catalog_repo`` and
    ``catalog_ref``. The index is cached under the online cache
    directory: within ``readinglists.catalog_ttl`` no request is made,
    and after it the cached index is revalidated. ``refresh`` asks
    GitHub now.
    """
    from comicbox.readinglists.sources.catalog import load_catalog

    self.check_cancelled()
    catalog = load_catalog(self, refresh=refresh)[0]
    self.check_cancelled()
    return catalog

check_cancelled() ¶

Raise if the session was cancelled.

Source code in comicbox/readinglists/session.py
125
126
127
128
129
def check_cancelled(self) -> None:
    """Raise if the session was cancelled."""
    if self._cancelled.is_set():
        reason = "Reading-list fetch cancelled."
        raise OnlineLookupAbortedError(reason)

close() ¶

Close the HTTP client and Metron’s shared sessions, if opened.

Comic Vine’s shared client is left open. Closing it closes its rate-limit buckets, which can fail a tagging lookup in the same process that holds one; OnlineSession.close releases it.

Source code in comicbox/readinglists/session.py
109
110
111
112
113
114
115
116
117
118
119
120
121
def close(self) -> None:
    """
    Close the HTTP client and Metron's shared sessions, if opened.

    Comic Vine's shared client is left open. Closing it closes its
    rate-limit buckets, which can fail a tagging lookup in the same
    process that holds one; ``OnlineSession.close`` releases it.
    """
    if self._http is not None:
        self._http.close()
        self._http = None
    if (metron := sys.modules.get(_METRON_SOURCE_MODULE)) is not None:
        metron.close_shared_sessions()

emit(event) ¶

Hand an event to the caller’s handler, if any.

Source code in comicbox/readinglists/session.py
136
137
138
139
def emit(self, event: Event) -> None:
    """Hand an event to the caller's handler, if any."""
    if self._on_event is not None:
        self._on_event(event)

fetch_catalog(path, *, sha=None) ¶

Fetch a list from the catalog by its path.

Paths change there; when path is gone and sha names the blob it had, the list with that sha is fetched in its place. The result’s source is of kind catalog, keyed by the path it was found at, with the blob sha as its revision.

Source code in comicbox/readinglists/session.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def fetch_catalog(self, path: str, *, sha: str | None = None) -> ReadingListResult:
    """
    Fetch a list from the catalog by its path.

    Paths change there; when ``path`` is gone and ``sha`` names the
    blob it had, the list with that sha is fetched in its place. The
    result's source is of kind ``catalog``, keyed by the path it was
    found at, with the blob sha as its revision.
    """
    from comicbox.readinglists.sources.catalog import fetch_entry

    with self.fetching(SourceKind.CATALOG.value, path):
        data, source = fetch_entry(self, path, sha)
        self.check_cancelled()
        return self.load_fetched(data, source)

fetch_comicvine_arc(arc_id) ¶

Fetch a Comic Vine story arc as an unordered list.

Comic Vine names an arc’s issues by id alone, so after the arc come its issues, a hundred a call, then their volumes the same way: an arc of N issues in V volumes costs 1 + ceil(N/100) + ceil(V/100) calls, each on its own hourly budget. Progress events count the issues as they arrive. A budget already spent fails the fetch at once, saying when it frees, rather than waiting.

Comic Vine has no conditional request, so there is no if_modified_since: compare the result’s source revision instead. Needs a Comic Vine API key. The result has no fmt.

Source code in comicbox/readinglists/session.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def fetch_comicvine_arc(self, arc_id: int) -> ReadingListResult:
    """
    Fetch a Comic Vine story arc as an unordered list.

    Comic Vine names an arc's issues by id alone, so after the arc come
    its issues, a hundred a call, then their volumes the same way: an
    arc of N issues in V volumes costs ``1 + ceil(N/100) + ceil(V/100)``
    calls, each on its own hourly budget. Progress events count the
    issues as they arrive. A budget already spent fails the fetch at
    once, saying when it frees, rather than waiting.

    Comic Vine has no conditional request, so there is no
    ``if_modified_since``: compare the result's source revision instead.
    Needs a Comic Vine API key. The result has no ``fmt``.
    """
    from comicbox.readinglists.sources import comicvine

    comicvine.check_key(self)
    with self.fetching(SourceKind.COMICVINE_ARC.value, str(arc_id)):
        result = comicvine.fetch_arc(self, arc_id)
        self.check_cancelled()
        return result

fetch_metron_arc(arc_id, *, if_modified_since=None) ¶

Fetch a Metron story arc as an unordered list.

Returns None, having fetched no issues, when the arc is unchanged since if_modified_since. Needs a Metron API token.

Source code in comicbox/readinglists/session.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def fetch_metron_arc(
    self, arc_id: int, *, if_modified_since: datetime | None = None
) -> ReadingListResult | None:
    """
    Fetch a Metron story arc as an unordered list.

    Returns None, having fetched no issues, when the arc is unchanged
    since ``if_modified_since``. Needs a Metron API token.
    """
    from comicbox.readinglists.sources import metron

    metron.check_token(self)
    with self.fetching(SourceKind.METRON_ARC.value, str(arc_id)):
        result = metron.fetch_arc(self, arc_id, if_modified_since=if_modified_since)
        self.check_cancelled()
        return result

fetch_metron_list(list_id, *, if_modified_since=None) ¶

Fetch a Metron reading list, in its order.

Returns None, having fetched no items, when the list is unchanged since if_modified_since. Progress events count the items as their pages arrive. Needs a Metron API token. The result has no fmt: it was read from no document.

Source code in comicbox/readinglists/session.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def fetch_metron_list(
    self, list_id: int, *, if_modified_since: datetime | None = None
) -> ReadingListResult | None:
    """
    Fetch a Metron reading list, in its order.

    Returns None, having fetched no items, when the list is unchanged
    since ``if_modified_since``. Progress events count the items as
    their pages arrive. Needs a Metron API token. The result has no
    ``fmt``: it was read from no document.
    """
    from comicbox.readinglists.sources import metron

    metron.check_token(self)
    with self.fetching(SourceKind.METRON_LIST.value, str(list_id)):
        result = metron.fetch_list(
            self, list_id, if_modified_since=if_modified_since
        )
        # A cancel during the last request still cancels.
        self.check_cancelled()
        return result

fetch_url(url) ¶

Fetch a list from an http or https URL, in any format comicbox reads.

Redirects are followed and the download is capped at readinglists.max_download_bytes. Its source is of kind url. A user name and password in the URL are sent, and never recorded.

Source code in comicbox/readinglists/session.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def fetch_url(self, url: str) -> ReadingListResult:
    """
    Fetch a list from an http or https URL, in any format comicbox reads.

    Redirects are followed and the download is capped at
    ``readinglists.max_download_bytes``. Its source is of kind ``url``.
    A user name and password in the URL are sent, and never recorded.
    """
    from comicbox.readinglists.sources.url import fetch, without_userinfo

    kind = SourceKind.URL.value
    # A user name and password in the URL go with the request; they are
    # never recorded on the list, nor shown in an event or an error.
    shown = without_userinfo(url)
    with self.fetching(kind, shown):
        max_bytes = self._settings.readinglists.max_download_bytes
        data, revision = fetch(
            self.http(), url, max_bytes, cancelled=self._cancelled.is_set
        )
        self.check_cancelled()
        source = {
            SOURCE_KIND_KEY: kind,
            SOURCE_KEY_KEY: shown,
            SOURCE_URL_KEY: shown,
            SOURCE_REVISION_KEY: revision,
        }
        return self.load_fetched(data, source)

fetching(kind, key) ¶

Bracket one fetch with its start and finish events.

Source code in comicbox/readinglists/session.py
154
155
156
157
158
159
160
161
162
@contextmanager
def fetching(self, kind: str, key: str) -> Generator[None]:
    """Bracket one fetch with its start and finish events."""
    self.check_cancelled()
    self.emit(ReadingListFetchStarted(source=kind, key=key))
    try:
        yield
    finally:
        self.emit(ReadingListFetchFinished(source=kind, key=key))

http() ¶

Get the session’s HTTP client, built on first use.

Source code in comicbox/readinglists/session.py
141
142
143
144
145
146
147
148
149
150
151
152
def http(self) -> httpx.Client:
    """Get the session's HTTP client, built on first use."""
    if self._http is None:
        import httpx

        self._http = httpx.Client(
            follow_redirects=True,
            timeout=_TIMEOUT_SECONDS,
            headers={"User-Agent": user_agent()},
            transport=self._transport,
        )
    return self._http

load_fetched(data, source) ¶

Read fetched bytes as a list from source, detecting the format.

A document that will not read names where it came from, as a file’s error names its path.

Source code in comicbox/readinglists/session.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def load_fetched(self, data: bytes, source: dict[str, Any]) -> ReadingListResult:
    """
    Read fetched bytes as a list from ``source``, detecting the format.

    A document that will not read names where it came from, as a
    file's error names its path.
    """
    try:
        result = loads(data)
    except ReadingListFormatError as exc:
        where = source.get(SOURCE_URL_KEY) or source.get(SOURCE_KEY_KEY)
        reason = f"{where}: {exc}"
        raise type(exc)(reason) from exc
    reading_list = attach_source(result.reading_list, source)
    return ReadingListResult(reading_list, result.fmt, result.warnings)

search_catalog(query) ¶

Find the catalog’s lists whose path holds every word of query.

Source code in comicbox/readinglists/session.py
316
317
318
def search_catalog(self, query: str) -> tuple[CatalogEntry, ...]:
    """Find the catalog's lists whose path holds every word of ``query``."""
    return self.catalog().search(query)

search_metron(*, name=None, curator=None, username=None, modified_since=None) ¶

Search Metron’s reading lists: public ones and the token’s own.

curator is a site Metron credits lists to, such as cbro. Needs a Metron API token.

Source code in comicbox/readinglists/session.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def search_metron(
    self,
    *,
    name: str | None = None,
    curator: str | None = None,
    username: str | None = None,
    modified_since: datetime | None = None,
) -> list[MetronListSummary]:
    """
    Search Metron's reading lists: public ones and the token's own.

    ``curator`` is a site Metron credits lists to, such as ``cbro``.
    Needs a Metron API token.
    """
    from comicbox.readinglists.sources import metron

    self.check_cancelled()
    found = metron.search(
        self,
        name=name,
        curator=curator,
        username=username,
        modified_since=modified_since,
    )
    self.check_cancelled()
    return found