dojinvoice_db.models

Plain data structures shared by the client, database, crawler and CLI.

The canonical work model is dlsite_async.Work; this module only adds what DLsite exposes but dlsite-async does not model (sales/price/rating figures), plus the search-listing query and the crawl option/result records.

  1"""Plain data structures shared by the client, database, crawler and CLI.
  2
  3The canonical work model is :class:`dlsite_async.Work`; this module only adds
  4what DLsite exposes but ``dlsite-async`` does not model (sales/price/rating
  5figures), plus the search-listing query and the crawl option/result records.
  6"""
  7
  8from __future__ import annotations
  9
 10import re
 11from dataclasses import dataclass, field
 12from typing import TYPE_CHECKING, Any
 13from urllib.parse import quote
 14
 15if TYPE_CHECKING:
 16    from collections.abc import Mapping
 17
 18DEFAULT_PER_PAGE = 100
 19"""Works per search listing page. 100 is the maximum DLsite accepts."""
 20
 21DEFAULT_INFO_BATCH = 100
 22"""Product IDs per ``product/info/ajax`` request."""
 23
 24_SIZE_UNITS = {"B": 1, "KB": 1000, "MB": 1000**2, "GB": 1000**3, "TB": 1000**4}
 25_SIZE_RE = re.compile(r"([\d.,]+)\s*([KMGT]?B)", flags=re.IGNORECASE)
 26
 27
 28def parse_file_size(value: str | None) -> int | None:
 29    """Convert a DLsite file size label (``"総計 1.2GB"``) into bytes.
 30
 31    Returns:
 32        Size in bytes, or ``None`` when ``value`` holds no recognizable size.
 33    """
 34    if not value:
 35        return None
 36    m = _SIZE_RE.search(value)
 37    if not m:
 38        return None
 39    try:
 40        number = float(m.group(1).replace(",", ""))
 41    except ValueError:  # pragma: no cover - regex already restricts the shape
 42        return None
 43    return int(number * _SIZE_UNITS[m.group(2).upper()])
 44
 45
 46@dataclass(frozen=True)
 47class SearchQuery:
 48    """A DLsite search listing (``fsr``) query.
 49
 50    The defaults reproduce "同人 / 男性向け / ボイス・ASMR, newest first", which is
 51    the set of works this database is about.
 52    """
 53
 54    site: str = "maniax"
 55    language: str = "jp"
 56    sex_category: tuple[str, ...] = ("male",)
 57    work_category: tuple[str, ...] = ("doujin",)
 58    work_type: tuple[str, ...] = ("SOU",)
 59    order: str = "release_d"
 60    per_page: int = DEFAULT_PER_PAGE
 61
 62    def page_url(self, page: int) -> str:
 63        """Return the listing URL for the 1-based ``page``."""
 64        params: list[tuple[str, str]] = [("language", self.language)]
 65        for key, values in (
 66            ("sex_category", self.sex_category),
 67            ("work_category", self.work_category),
 68            ("work_type", self.work_type),
 69        ):
 70            params.extend((f"{key}[{i}]", value) for i, value in enumerate(values))
 71        params.append(("order[0]", self.order))
 72        params.append(("per_page", str(self.per_page)))
 73        params.append(("page", str(page)))
 74        path = "/".join(f"{quote(k, safe='')}/{quote(v, safe='')}" for k, v in params)
 75        return f"https://www.dlsite.com/{self.site}/fsr/=/{path}"
 76
 77    def describe(self) -> str:
 78        """Return a compact human-readable form, used for logs and crawl state."""
 79        return (
 80            f"{self.site}:{'+'.join(self.sex_category)}/{'+'.join(self.work_category)}"
 81            f"/{'+'.join(self.work_type)}/{self.order}"
 82        )
 83
 84
 85def _as_int(value: Any) -> int | None:  # noqa: ANN401 - raw JSON value
 86    if isinstance(value, bool) or value is None:
 87        return None
 88    try:
 89        return int(value)
 90    except (TypeError, ValueError):
 91        return None
 92
 93
 94def _as_float(value: Any) -> float | None:  # noqa: ANN401 - raw JSON value
 95    if isinstance(value, bool) or value is None:
 96        return None
 97    try:
 98        return float(value)
 99    except (TypeError, ValueError):
100        return None
101
102
103def _as_bool(value: Any) -> bool | None:  # noqa: ANN401 - raw JSON value
104    if value is None:
105        return None
106    return bool(value)
107
108
109@dataclass(frozen=True)
110class WorkStats:
111    """Volatile figures for a work (price, sales, ratings).
112
113    These change over time for works already in the database, so they are
114    stored separately from the (mostly immutable) work metadata and can be
115    refreshed on their own with one request per 100 works.
116    """
117
118    product_id: str
119    price: int | None = None
120    price_without_tax: int | None = None
121    official_price: int | None = None
122    discount_rate: int | None = None
123    dl_count: int | None = None
124    wishlist_count: int | None = None
125    rate_average: float | None = None
126    rate_count: int | None = None
127    review_count: int | None = None
128    is_sale: bool | None = None
129    is_discount: bool | None = None
130
131    @classmethod
132    def from_info(cls, product_id: str, info: Mapping[str, Any]) -> WorkStats:
133        """Build stats from one ``product/info/ajax`` entry."""
134        return cls(
135            product_id=product_id,
136            price=_as_int(info.get("price")),
137            price_without_tax=_as_int(info.get("price_without_tax")),
138            official_price=_as_int(info.get("official_price")),
139            discount_rate=_as_int(info.get("discount_rate")),
140            dl_count=_as_int(info.get("dl_count")),
141            wishlist_count=_as_int(info.get("wishlist_count")),
142            rate_average=_as_float(info.get("rate_average_2dp")),
143            rate_count=_as_int(info.get("rate_count")),
144            review_count=_as_int(info.get("review_count")),
145            is_sale=_as_bool(info.get("is_sale")),
146            is_discount=_as_bool(info.get("is_discount")),
147        )
148
149
150@dataclass
151class CrawlOptions:
152    """Options for :func:`dojinvoice_db.crawler.crawl`."""
153
154    query: SearchQuery = field(default_factory=SearchQuery)
155    max_pages: int | None = None
156    stop_after_known_pages: int = 2
157    full: bool = False
158    limit: int | None = None
159    concurrency: int = 4
160    interval: float = 0.5
161    skip_details: bool = False
162    detail_stale_days: int | None = None
163    retry_errors: bool = False
164    info_batch: int = DEFAULT_INFO_BATCH
165
166
167@dataclass
168class CrawlResult:
169    """Counters describing what a crawl did."""
170
171    pages_fetched: int = 0
172    ids_seen: int = 0
173    new_ids: int = 0
174    summaries_written: int = 0
175    details_fetched: int = 0
176    errors: int = 0
177
178    def as_dict(self) -> dict[str, int]:
179        """Return the counters as a plain dict."""
180        return {
181            "pages_fetched": self.pages_fetched,
182            "ids_seen": self.ids_seen,
183            "new_ids": self.new_ids,
184            "summaries_written": self.summaries_written,
185            "details_fetched": self.details_fetched,
186            "errors": self.errors,
187        }
DEFAULT_PER_PAGE = 100

Works per search listing page. 100 is the maximum DLsite accepts.

DEFAULT_INFO_BATCH = 100

Product IDs per product/info/ajax request.

def parse_file_size(value: str | None) -> int | None:
29def parse_file_size(value: str | None) -> int | None:
30    """Convert a DLsite file size label (``"総計 1.2GB"``) into bytes.
31
32    Returns:
33        Size in bytes, or ``None`` when ``value`` holds no recognizable size.
34    """
35    if not value:
36        return None
37    m = _SIZE_RE.search(value)
38    if not m:
39        return None
40    try:
41        number = float(m.group(1).replace(",", ""))
42    except ValueError:  # pragma: no cover - regex already restricts the shape
43        return None
44    return int(number * _SIZE_UNITS[m.group(2).upper()])

Convert a DLsite file size label ("総計 1.2GB") into bytes.

Returns:

Size in bytes, or None when value holds no recognizable size.

@dataclass(frozen=True)
class SearchQuery:
47@dataclass(frozen=True)
48class SearchQuery:
49    """A DLsite search listing (``fsr``) query.
50
51    The defaults reproduce "同人 / 男性向け / ボイス・ASMR, newest first", which is
52    the set of works this database is about.
53    """
54
55    site: str = "maniax"
56    language: str = "jp"
57    sex_category: tuple[str, ...] = ("male",)
58    work_category: tuple[str, ...] = ("doujin",)
59    work_type: tuple[str, ...] = ("SOU",)
60    order: str = "release_d"
61    per_page: int = DEFAULT_PER_PAGE
62
63    def page_url(self, page: int) -> str:
64        """Return the listing URL for the 1-based ``page``."""
65        params: list[tuple[str, str]] = [("language", self.language)]
66        for key, values in (
67            ("sex_category", self.sex_category),
68            ("work_category", self.work_category),
69            ("work_type", self.work_type),
70        ):
71            params.extend((f"{key}[{i}]", value) for i, value in enumerate(values))
72        params.append(("order[0]", self.order))
73        params.append(("per_page", str(self.per_page)))
74        params.append(("page", str(page)))
75        path = "/".join(f"{quote(k, safe='')}/{quote(v, safe='')}" for k, v in params)
76        return f"https://www.dlsite.com/{self.site}/fsr/=/{path}"
77
78    def describe(self) -> str:
79        """Return a compact human-readable form, used for logs and crawl state."""
80        return (
81            f"{self.site}:{'+'.join(self.sex_category)}/{'+'.join(self.work_category)}"
82            f"/{'+'.join(self.work_type)}/{self.order}"
83        )

A DLsite search listing (fsr) query.

The defaults reproduce "同人 / 男性向け / ボイス・ASMR, newest first", which is the set of works this database is about.

SearchQuery( site: str = 'maniax', language: str = 'jp', sex_category: tuple[str, ...] = ('male',), work_category: tuple[str, ...] = ('doujin',), work_type: tuple[str, ...] = ('SOU',), order: str = 'release_d', per_page: int = 100)
site: str = 'maniax'
language: str = 'jp'
sex_category: tuple[str, ...] = ('male',)
work_category: tuple[str, ...] = ('doujin',)
work_type: tuple[str, ...] = ('SOU',)
order: str = 'release_d'
per_page: int = 100
def page_url(self, page: int) -> str:
63    def page_url(self, page: int) -> str:
64        """Return the listing URL for the 1-based ``page``."""
65        params: list[tuple[str, str]] = [("language", self.language)]
66        for key, values in (
67            ("sex_category", self.sex_category),
68            ("work_category", self.work_category),
69            ("work_type", self.work_type),
70        ):
71            params.extend((f"{key}[{i}]", value) for i, value in enumerate(values))
72        params.append(("order[0]", self.order))
73        params.append(("per_page", str(self.per_page)))
74        params.append(("page", str(page)))
75        path = "/".join(f"{quote(k, safe='')}/{quote(v, safe='')}" for k, v in params)
76        return f"https://www.dlsite.com/{self.site}/fsr/=/{path}"

Return the listing URL for the 1-based page.

def describe(self) -> str:
78    def describe(self) -> str:
79        """Return a compact human-readable form, used for logs and crawl state."""
80        return (
81            f"{self.site}:{'+'.join(self.sex_category)}/{'+'.join(self.work_category)}"
82            f"/{'+'.join(self.work_type)}/{self.order}"
83        )

Return a compact human-readable form, used for logs and crawl state.

@dataclass(frozen=True)
class WorkStats:
110@dataclass(frozen=True)
111class WorkStats:
112    """Volatile figures for a work (price, sales, ratings).
113
114    These change over time for works already in the database, so they are
115    stored separately from the (mostly immutable) work metadata and can be
116    refreshed on their own with one request per 100 works.
117    """
118
119    product_id: str
120    price: int | None = None
121    price_without_tax: int | None = None
122    official_price: int | None = None
123    discount_rate: int | None = None
124    dl_count: int | None = None
125    wishlist_count: int | None = None
126    rate_average: float | None = None
127    rate_count: int | None = None
128    review_count: int | None = None
129    is_sale: bool | None = None
130    is_discount: bool | None = None
131
132    @classmethod
133    def from_info(cls, product_id: str, info: Mapping[str, Any]) -> WorkStats:
134        """Build stats from one ``product/info/ajax`` entry."""
135        return cls(
136            product_id=product_id,
137            price=_as_int(info.get("price")),
138            price_without_tax=_as_int(info.get("price_without_tax")),
139            official_price=_as_int(info.get("official_price")),
140            discount_rate=_as_int(info.get("discount_rate")),
141            dl_count=_as_int(info.get("dl_count")),
142            wishlist_count=_as_int(info.get("wishlist_count")),
143            rate_average=_as_float(info.get("rate_average_2dp")),
144            rate_count=_as_int(info.get("rate_count")),
145            review_count=_as_int(info.get("review_count")),
146            is_sale=_as_bool(info.get("is_sale")),
147            is_discount=_as_bool(info.get("is_discount")),
148        )

Volatile figures for a work (price, sales, ratings).

These change over time for works already in the database, so they are stored separately from the (mostly immutable) work metadata and can be refreshed on their own with one request per 100 works.

WorkStats( product_id: str, price: int | None = None, price_without_tax: int | None = None, official_price: int | None = None, discount_rate: int | None = None, dl_count: int | None = None, wishlist_count: int | None = None, rate_average: float | None = None, rate_count: int | None = None, review_count: int | None = None, is_sale: bool | None = None, is_discount: bool | None = None)
product_id: str
price: int | None = None
price_without_tax: int | None = None
official_price: int | None = None
discount_rate: int | None = None
dl_count: int | None = None
wishlist_count: int | None = None
rate_average: float | None = None
rate_count: int | None = None
review_count: int | None = None
is_sale: bool | None = None
is_discount: bool | None = None
@classmethod
def from_info( cls, product_id: str, info: Mapping[str, typing.Any]) -> WorkStats:
132    @classmethod
133    def from_info(cls, product_id: str, info: Mapping[str, Any]) -> WorkStats:
134        """Build stats from one ``product/info/ajax`` entry."""
135        return cls(
136            product_id=product_id,
137            price=_as_int(info.get("price")),
138            price_without_tax=_as_int(info.get("price_without_tax")),
139            official_price=_as_int(info.get("official_price")),
140            discount_rate=_as_int(info.get("discount_rate")),
141            dl_count=_as_int(info.get("dl_count")),
142            wishlist_count=_as_int(info.get("wishlist_count")),
143            rate_average=_as_float(info.get("rate_average_2dp")),
144            rate_count=_as_int(info.get("rate_count")),
145            review_count=_as_int(info.get("review_count")),
146            is_sale=_as_bool(info.get("is_sale")),
147            is_discount=_as_bool(info.get("is_discount")),
148        )

Build stats from one product/info/ajax entry.

@dataclass
class CrawlOptions:
151@dataclass
152class CrawlOptions:
153    """Options for :func:`dojinvoice_db.crawler.crawl`."""
154
155    query: SearchQuery = field(default_factory=SearchQuery)
156    max_pages: int | None = None
157    stop_after_known_pages: int = 2
158    full: bool = False
159    limit: int | None = None
160    concurrency: int = 4
161    interval: float = 0.5
162    skip_details: bool = False
163    detail_stale_days: int | None = None
164    retry_errors: bool = False
165    info_batch: int = DEFAULT_INFO_BATCH
CrawlOptions( query: SearchQuery = <factory>, max_pages: int | None = None, stop_after_known_pages: int = 2, full: bool = False, limit: int | None = None, concurrency: int = 4, interval: float = 0.5, skip_details: bool = False, detail_stale_days: int | None = None, retry_errors: bool = False, info_batch: int = 100)
query: SearchQuery
max_pages: int | None = None
stop_after_known_pages: int = 2
full: bool = False
limit: int | None = None
concurrency: int = 4
interval: float = 0.5
skip_details: bool = False
detail_stale_days: int | None = None
retry_errors: bool = False
info_batch: int = 100
@dataclass
class CrawlResult:
168@dataclass
169class CrawlResult:
170    """Counters describing what a crawl did."""
171
172    pages_fetched: int = 0
173    ids_seen: int = 0
174    new_ids: int = 0
175    summaries_written: int = 0
176    details_fetched: int = 0
177    errors: int = 0
178
179    def as_dict(self) -> dict[str, int]:
180        """Return the counters as a plain dict."""
181        return {
182            "pages_fetched": self.pages_fetched,
183            "ids_seen": self.ids_seen,
184            "new_ids": self.new_ids,
185            "summaries_written": self.summaries_written,
186            "details_fetched": self.details_fetched,
187            "errors": self.errors,
188        }

Counters describing what a crawl did.

CrawlResult( pages_fetched: int = 0, ids_seen: int = 0, new_ids: int = 0, summaries_written: int = 0, details_fetched: int = 0, errors: int = 0)
pages_fetched: int = 0
ids_seen: int = 0
new_ids: int = 0
summaries_written: int = 0
details_fetched: int = 0
errors: int = 0
def as_dict(self) -> dict[str, int]:
179    def as_dict(self) -> dict[str, int]:
180        """Return the counters as a plain dict."""
181        return {
182            "pages_fetched": self.pages_fetched,
183            "ids_seen": self.ids_seen,
184            "new_ids": self.new_ids,
185            "summaries_written": self.summaries_written,
186            "details_fetched": self.details_fetched,
187            "errors": self.errors,
188        }

Return the counters as a plain dict.