shindan_cli.shindan

Implements the function to get the shindan result from https://shindanmaker.com.

  1"""Implements the function to get the shindan result from <https://shindanmaker.com>."""
  2
  3from __future__ import annotations
  4
  5from typing import TYPE_CHECKING, cast
  6
  7from bs4 import BeautifulSoup
  8
  9from . import _http
 10from ._http import create_session, request_with_retry, xhr_headers
 11from .constants import BASE_URL, HEADERS, TARGET_KEYS_BY_TYPE
 12from .get_results import (
 13    Params,
 14    get_result_by_ai,
 15    get_result_by_branch,
 16    get_result_by_check,
 17    get_result_by_name,
 18)
 19from .interactive import get_choices, get_rbr, get_user_inputs
 20from .models import ShindanResult
 21
 22if TYPE_CHECKING:
 23    from curl_cffi.requests import Session
 24
 25
 26class ShindanError(Exception):
 27    """Error class for shindan-cli."""
 28
 29
 30def __get_csrf_token(session: Session, source: BeautifulSoup, *, shindan_url: str) -> str:
 31    """Get a CSRF token to submit the shindan form with.
 32
 33    The shindan pages are served from a cache with their token fields left
 34    blank, and the browser fills them in from `/csrf-token` just before
 35    submitting the form.
 36
 37    Args:
 38        session (Session): session object
 39        source (BeautifulSoup): parsed shindan page
 40        shindan_url (str): url of the shindan page the token is submitted from
 41
 42    Returns:
 43        str: CSRF token
 44
 45    Raises:
 46        ShindanError
 47
 48    """
 49    csrf_meta = source.select_one('meta[name="csrf-token"]')
 50    if csrf_meta and isinstance(token := csrf_meta.get("content"), str) and token:
 51        return token
 52
 53    response = request_with_retry(
 54        session,
 55        "GET",
 56        f"{BASE_URL}/csrf-token",
 57        headers=xhr_headers(shindan_url),
 58    )
 59    if response.status_code != 200:  # noqa: PLR2004
 60        raise ShindanError(response.status_code)
 61    if not isinstance(token := response.json().get("token"), str) or not token:
 62        msg = "Could not find CSRF token on the shindan page."
 63        raise ShindanError(msg)
 64    return token
 65
 66
 67def shindan(
 68    page_id: int,
 69    shindan_name: str,
 70    *,
 71    wait: bool | None = False,
 72) -> ShindanResult:
 73    """Get the shindan result from <https://shindanmaker.com>.
 74
 75    Args:
 76        page_id : int
 77            shindan page id (e.g. `1036646`)
 78        shindan_name : str
 79            shindan name (e.g. your name)
 80        wait : bool | None, optional
 81            enable random waits while fetching shindan data, by default False
 82
 83    Returns:
 84        ShindanResult: the returned result from <https://shindanmaker.com>
 85
 86    Raises:
 87        ShindanError
 88
 89    """
 90    if not isinstance(page_id, int) or page_id < 0:
 91        msg = f"invalid page id: {page_id}"
 92        raise ShindanError(msg)
 93    shindan_url = f"{BASE_URL}/{page_id}"
 94
 95    session = create_session()
 96
 97    shindan_page = request_with_retry(session, "GET", shindan_url, headers=HEADERS)
 98    if shindan_page.status_code != 200:  # noqa: PLR2004
 99        raise ShindanError(shindan_page.status_code)
100
101    source = BeautifulSoup(shindan_page.text, features="lxml")
102
103    shindan_type_input = source.select_one('input[name="type"]')
104    if not shindan_type_input or not shindan_type_input.get("value"):
105        msg = "Cannot detect shindan type!"
106        raise ValueError(msg)
107    shindan_type = str(shindan_type_input.get("value"))
108    params = cast(
109        "Params",
110        {
111            key: key_input.get("value")
112            for key in TARGET_KEYS_BY_TYPE[shindan_type]
113            if (key_input := source.select_one(f'input[name="{key}"]'))
114        },
115    )
116    # overwrite randname (old: shindanName)
117    params["randname"] = shindan_name
118    params["_token"] = params["_token"] or __get_csrf_token(session, source, shindan_url=shindan_url)
119
120    if wait:
121        _http.random_wait()
122
123    if params["type"] == "ai":
124        hashtag_title = source.select_one("h1#shindanTitle")
125        if not hashtag_title or not isinstance(
126            hashtag := hashtag_title.get("data-shindan_hashtag"),
127            str,
128        ):
129            hashtag = None
130        return get_result_by_ai(
131            session,
132            params,
133            user_inputs=get_user_inputs(source, shindan_name),
134            hashtag=hashtag,
135            csrf_token=params["_token"],
136            shindan_url=shindan_url,
137        )
138    if params["type"] == "branch":
139        params["rbr"] = get_rbr(source)
140        return get_result_by_branch(
141            session,
142            params,
143            shindan_url=shindan_url,
144        )
145    if params["type"] == "check":
146        return get_result_by_check(
147            session,
148            params,
149            user_choices=get_choices(source),
150            shindan_url=shindan_url,
151        )
152    if params["type"] == "name":
153        return get_result_by_name(
154            session,
155            params,
156            shindan_url=shindan_url,
157        )
158    raise NotImplementedError(shindan_type)
159
160
161__all__ = ("ShindanResult", "shindan")
class ShindanResult(typing.TypedDict):
 9class ShindanResult(TypedDict):
10    """TypedDict Class for result of shindan."""
11
12    results: list[str]
13    hashtags: list[str]
14    shindan_url: str

TypedDict Class for result of shindan.

results: list[str]
hashtags: list[str]
shindan_url: str
def shindan( page_id: int, shindan_name: str, *, wait: bool | None = False) -> ShindanResult:
 68def shindan(
 69    page_id: int,
 70    shindan_name: str,
 71    *,
 72    wait: bool | None = False,
 73) -> ShindanResult:
 74    """Get the shindan result from <https://shindanmaker.com>.
 75
 76    Args:
 77        page_id : int
 78            shindan page id (e.g. `1036646`)
 79        shindan_name : str
 80            shindan name (e.g. your name)
 81        wait : bool | None, optional
 82            enable random waits while fetching shindan data, by default False
 83
 84    Returns:
 85        ShindanResult: the returned result from <https://shindanmaker.com>
 86
 87    Raises:
 88        ShindanError
 89
 90    """
 91    if not isinstance(page_id, int) or page_id < 0:
 92        msg = f"invalid page id: {page_id}"
 93        raise ShindanError(msg)
 94    shindan_url = f"{BASE_URL}/{page_id}"
 95
 96    session = create_session()
 97
 98    shindan_page = request_with_retry(session, "GET", shindan_url, headers=HEADERS)
 99    if shindan_page.status_code != 200:  # noqa: PLR2004
100        raise ShindanError(shindan_page.status_code)
101
102    source = BeautifulSoup(shindan_page.text, features="lxml")
103
104    shindan_type_input = source.select_one('input[name="type"]')
105    if not shindan_type_input or not shindan_type_input.get("value"):
106        msg = "Cannot detect shindan type!"
107        raise ValueError(msg)
108    shindan_type = str(shindan_type_input.get("value"))
109    params = cast(
110        "Params",
111        {
112            key: key_input.get("value")
113            for key in TARGET_KEYS_BY_TYPE[shindan_type]
114            if (key_input := source.select_one(f'input[name="{key}"]'))
115        },
116    )
117    # overwrite randname (old: shindanName)
118    params["randname"] = shindan_name
119    params["_token"] = params["_token"] or __get_csrf_token(session, source, shindan_url=shindan_url)
120
121    if wait:
122        _http.random_wait()
123
124    if params["type"] == "ai":
125        hashtag_title = source.select_one("h1#shindanTitle")
126        if not hashtag_title or not isinstance(
127            hashtag := hashtag_title.get("data-shindan_hashtag"),
128            str,
129        ):
130            hashtag = None
131        return get_result_by_ai(
132            session,
133            params,
134            user_inputs=get_user_inputs(source, shindan_name),
135            hashtag=hashtag,
136            csrf_token=params["_token"],
137            shindan_url=shindan_url,
138        )
139    if params["type"] == "branch":
140        params["rbr"] = get_rbr(source)
141        return get_result_by_branch(
142            session,
143            params,
144            shindan_url=shindan_url,
145        )
146    if params["type"] == "check":
147        return get_result_by_check(
148            session,
149            params,
150            user_choices=get_choices(source),
151            shindan_url=shindan_url,
152        )
153    if params["type"] == "name":
154        return get_result_by_name(
155            session,
156            params,
157            shindan_url=shindan_url,
158        )
159    raise NotImplementedError(shindan_type)

Get the shindan result from https://shindanmaker.com.

Arguments:
  • page_id : int shindan page id (e.g. 1036646)
  • shindan_name : str shindan name (e.g. your name)
  • wait : bool | None, optional enable random waits while fetching shindan data, by default False
Returns:

ShindanResult: the returned result from https://shindanmaker.com

Raises:
  • ShindanError