"""OPDS 1.2 catalog documents. The dialect is Atom with the OPDS profile, because that is what ebook readers actually implement: KOReader, Calibre, Moon+ Reader, Librera, FBReader and Aldiko all browse OPDS 1.2, and its navigation/acquisition split maps exactly onto the category/feed/article tree this server mirrors out of FreshRSS. The two document kinds, and the rules that matter: *Navigation feeds* (``kind=navigation``) are directories. Each entry is a ``rel="subsection"`` link to another feed, carrying a text description such as an unread count. *Acquisition feeds* (``kind=acquisition``) list articles. Each entry carries an ``rel="http://opds-spec.org/acquisition/open-access"`` link with an EPUB media type, which is what a reader downloads. A plain ``http://opds-spec.org/acquisition`` link to the same URL is also emitted: readers disagree about which relation to look for, and both are valid ways to say the same thing. An ``alternate`` link points at the original article, which readers show as "open in browser". Every feed carries ``rel="self"`` with the profile in its type, plus ``rel="start"`` back to the root, because readers navigate by these rather than by URL. Pagination uses ``rel="next"``/``rel="previous"``/``rel="first"``. Documents are built as strings rather than through a DOM library: the output is small, fully determined, and easy to read in a test failure. Every interpolated value goes through an escaper, and the tests parse the result with a strict XML parser. """ from __future__ import annotations from dataclasses import dataclass, field from datetime import UTC, datetime from app import xhtml ATOM_NAMESPACE = "http://www.w3.org/2005/Atom" OPDS_NAMESPACE = "http://opds-spec.org/2010/catalog" OPENSEARCH_NAMESPACE = "http://a9.com/-/spec/opensearch/1.1/" DC_NAMESPACE = "http://purl.org/dc/elements/1.1/" NAVIGATION_TYPE = "application/atom+xml;profile=opds-catalog;kind=navigation" ACQUISITION_TYPE = "application/atom+xml;profile=opds-catalog;kind=acquisition" OPENSEARCH_TYPE = "application/opensearchdescription+xml" EPUB_TYPE = "application/epub+zip" HTML_TYPE = "text/html" ACQUISITION_REL = "http://opds-spec.org/acquisition" OPEN_ACCESS_REL = "http://opds-spec.org/acquisition/open-access" SUBSECTION_REL = "subsection" ALTERNATE_REL = "alternate" @dataclass(frozen=True) class NavEntry: """One row of a navigation feed: a link deeper into the catalog.""" title: str entry_id: str href: str updated: datetime description: str | None = None @dataclass(frozen=True) class AcquisitionEntry: """One row of an acquisition feed: an article, as a downloadable book.""" title: str entry_id: str updated: datetime download_href: str author: str | None = None summary: str | None = None language: str | None = None alternate_href: str | None = None categories: tuple[tuple[str, str], ...] = () @dataclass(frozen=True) class PageLinks: """Pagination targets, already absolute. Omitting one omits its link.""" first: str | None = None previous: str | None = None next: str | None = None @dataclass(frozen=True) class FeedLinks: """Everything a reader needs to place a feed in the catalog. Pagination lives only in :attr:`pages`: an earlier version also carried ``next_url``/``previous_url``, and the renderer read those while callers set ``pages``, so the links silently never appeared. """ self_url: str start_url: str | None = None search_url: str | None = None pages: PageLinks = field(default_factory=PageLinks) def navigation_feed( *, feed_id: str, title: str, updated: datetime, links: FeedLinks, entries: list[NavEntry], author: str = "OPDS", subtitle: str | None = None, ) -> str: """Render a navigation feed.""" return _feed( feed_id=feed_id, title=title, updated=updated, links=links, entries=[_nav_entry_xml(entry) for entry in entries], kind_type=NAVIGATION_TYPE, author=author, subtitle=subtitle, ) def acquisition_feed( *, feed_id: str, title: str, updated: datetime, links: FeedLinks, entries: list[AcquisitionEntry], author: str = "OPDS", subtitle: str | None = None, ) -> str: """Render an acquisition feed.""" return _feed( feed_id=feed_id, title=title, updated=updated, links=links, entries=[_acquisition_entry_xml(entry) for entry in entries], kind_type=ACQUISITION_TYPE, author=author, subtitle=subtitle, ) def opensearch_description( *, search_url: str, short_name: str, description: str, output_type: str = ACQUISITION_TYPE, ) -> str: """Render an OpenSearch description document. Readers that support search advertise it by fetching this document, which is why the root navigation feed links to it with ``rel="search"``. """ return "\n".join( [ '', f'', f" {_escape(short_name)}", f" {_escape(description)}", " UTF-8", " UTF-8", f' ', "", "", ] ) # -- feed assembly ------------------------------------------------------- def _feed( *, feed_id: str, title: str, updated: datetime, links: FeedLinks, entries: list[str], kind_type: str, author: str, subtitle: str | None, ) -> str: lines = [ '', f'', f" {_escape(feed_id)}", f" {_escape(title)}", f" {_timestamp(updated)}", ] if subtitle: lines.append(f" {_escape(subtitle)}") lines.append(f" {_escape(author)}") lines.extend(_feed_links_xml(links, kind_type)) lines.extend(entries) lines.extend(["", ""]) return "\n".join(lines) def _feed_links_xml(links: FeedLinks, kind_type: str) -> list[str]: """Self, start, search and pagination links, in that order.""" rendered = [ f' ' ] if links.start_url: rendered.append( f' ' ) if links.search_url: rendered.append( f' ' ) first = links.pages.first if first: rendered.append( f' ' ) if links.pages.previous: rendered.append( f' ' ) if links.pages.next: rendered.append( f' ' ) return rendered def _nav_entry_xml(entry: NavEntry) -> str: lines = [ " ", f" {_escape(entry.title)}", f" {_escape(entry.entry_id)}", f" {_timestamp(entry.updated)}", ] if entry.description: lines.append(f' {_escape(entry.description)}') lines.extend( [ f' ', " ", ] ) return "\n".join(lines) def _acquisition_entry_xml(entry: AcquisitionEntry) -> str: lines = [ " ", f" {_escape(entry.title)}", f" {_escape(entry.entry_id)}", f" {_timestamp(entry.updated)}", ] if entry.author: lines.append(f" {_escape(entry.author)}") if entry.summary: lines.append(f' {_escape(entry.summary)}') if entry.language: lines.append(f" {_escape(entry.language)}") for term, label in entry.categories: lines.append(f' ') # Two acquisition relations to the same resource, because readers disagree # about which one to look for; both are valid. for rel in (OPEN_ACCESS_REL, ACQUISITION_REL): lines.append( f' ' ) if entry.alternate_href: lines.append( f' ' ) lines.append(" ") return "\n".join(lines) # -- formatting ---------------------------------------------------------- def _escape(text: str) -> str: """Escape text for a document body.""" return xhtml.escape_text(text) def _attribute(value: str) -> str: """Escape a value for a double-quoted attribute.""" return xhtml.escape_attribute(value) def _timestamp(moment: datetime) -> str: """Atom dates are RFC 3339 in UTC.""" return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")