comicbox.identifiers.other

[docs] module comicbox.identifiers.other

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""Non urn identifier substring parsers."""

import re
from contextlib import suppress

from comicbox.enums.comicbox import IdSources
from comicbox.enums.maps.identifiers import get_id_source_by_alias
from comicbox.identifiers import (
    DEFAULT_ID_TYPE,
    IDENTIFIER_RE_EXP,
    PARSE_COMICVINE_RE,
)
from comicbox.identifiers.identifiers import IDENTIFIER_PARTS_MAP

# I haven't identified which program adds these other notes encodings. Could be mylar.
_PARSE_OTHER_RE = re.compile(IDENTIFIER_RE_EXP, flags=re.IGNORECASE)


def _parse_identifier_str_comicvine(
    full_identifier: str,
) -> tuple[IdSources | None, str, str]:
    id_source = None
    id_type = id_key = ""
    match = PARSE_COMICVINE_RE.search(full_identifier)
    if not match:
        return id_source, id_type, id_key
    id_source = IdSources.COMICVINE
    id_type_code = match.group("id_type") or ""
    id_type = IDENTIFIER_PARTS_MAP[id_source].get_type_by_code(id_type_code)
    id_key = match.group("id_key")
    return id_source, id_type, id_key


def _parse_identifier_other_str(
    full_identifier: str,
) -> tuple[IdSources | None, str, str]:
    id_source = None
    id_type = id_key = ""
    match = _PARSE_OTHER_RE.search(full_identifier)
    if not match:
        return id_source, id_type, id_key
    with suppress(IndexError):
        id_source_str = match.group("id_source") or ""
        id_source = get_id_source_by_alias(id_source_str)
        id_type = DEFAULT_ID_TYPE
        id_key = match.group("id_key")
    return id_source, id_type, id_key


def parse_identifier_other_str(
    full_identifier: str,
) -> tuple[IdSources | None, str, str]:
    """Parse an identifier string with optional prefix."""
    id_source, id_type, id_key = _parse_identifier_str_comicvine(full_identifier)
    if not id_key:
        id_source, id_type, id_key = _parse_identifier_other_str(full_identifier)
    if not id_key:
        id_key = full_identifier
    return id_source, id_type, id_key