mirror of
https://github.com/mikumifa/biliTickerBuy.git
synced 2026-11-18 06:23:16 -08:00
fix: include config dir #901
This commit is contained in:
1 parent
30b6eed939
commit
7195df7fc4
4 files changed
+645
-1
No files matched your search
+2
-1
@@ -27,4 +27,5 @@ btb_runs
|
||||
confirmOrder.*.js
|
||||
dev
|
||||
local_overrides/
|
||||
test.py
|
||||
test.py
|
||||
!app_cmd/config
|
||||
@@ -0,0 +1,241 @@
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from app_cmd.config.ConfigBasic import (
|
||||
BasicConfig,
|
||||
DEFAULT_CREATE_REQUEST_BATCH_SIZE,
|
||||
DEFAULT_CREATE_RETRY_LIMIT,
|
||||
config_field,
|
||||
nested_config_field,
|
||||
normalize_log_level,
|
||||
str_to_bool,
|
||||
)
|
||||
from app_cmd.config.NotifierConfig import NotifierConfig
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class BuyConfig(BasicConfig):
|
||||
"""Ticket buying runtime configuration."""
|
||||
|
||||
_skip_cli_fields: ClassVar[set[str]] = {"tickets_info", "config_file"}
|
||||
|
||||
tickets_info: str = ""
|
||||
"""Ticket JSON content passed to the buyer."""
|
||||
|
||||
config_file: str = config_field(
|
||||
"",
|
||||
cli="--config-file",
|
||||
)
|
||||
"""Path to a ticket configuration JSON file."""
|
||||
|
||||
time_start: str = config_field(
|
||||
"",
|
||||
env="BTB_TIME_START",
|
||||
runtime="time_start",
|
||||
cli="--time-start",
|
||||
)
|
||||
"""Scheduled start time, for example 2026-06-18T20:00:00."""
|
||||
|
||||
interval: int | None = config_field(
|
||||
1000,
|
||||
env="BTB_INTERVAL",
|
||||
runtime="interval",
|
||||
db="requestInterval",
|
||||
cli="--interval",
|
||||
cast=int,
|
||||
)
|
||||
"""Default request interval in milliseconds."""
|
||||
|
||||
notifier_config: NotifierConfig = nested_config_field(NotifierConfig)
|
||||
"""Notification settings."""
|
||||
|
||||
https_proxys: str = config_field(
|
||||
"none",
|
||||
env="BTB_HTTPS_PROXYS",
|
||||
runtime="https_proxys",
|
||||
db="https_proxy",
|
||||
cli="--https-proxys",
|
||||
)
|
||||
"""Proxy string or comma-separated proxy pool."""
|
||||
|
||||
# ConfigDB 里原字段是 hideRandomMessage,语义和 show_random_message 相反
|
||||
show_random_message: bool = config_field(
|
||||
True,
|
||||
runtime="show_random_message",
|
||||
db="hideRandomMessage",
|
||||
db_default=True,
|
||||
cast=str_to_bool,
|
||||
db_transform=lambda hide: not hide,
|
||||
cli_false="--no-show-random-message",
|
||||
)
|
||||
"""Show random failure messages after a round fails."""
|
||||
|
||||
show_qrcode: bool = config_field(
|
||||
True,
|
||||
runtime="show_qrcode",
|
||||
db="showQrcode",
|
||||
db_default=True,
|
||||
cast=str_to_bool,
|
||||
cli_false="--no-show-qrcode",
|
||||
)
|
||||
"""Show the payment QR code after a successful order."""
|
||||
|
||||
use_local_token: bool = config_field(
|
||||
False,
|
||||
env="BTB_USE_LOCAL_TOKEN",
|
||||
runtime="use_local_token",
|
||||
db="useLocalToken",
|
||||
cast=str_to_bool,
|
||||
cli_true="--use-local-token",
|
||||
)
|
||||
"""Use locally generated token when the project flow allows it."""
|
||||
|
||||
create_retry_limit: int = config_field(
|
||||
DEFAULT_CREATE_RETRY_LIMIT,
|
||||
env="BTB_CREATE_RETRY_LIMIT",
|
||||
runtime="create_retry_limit",
|
||||
db="createRetryLimit",
|
||||
cli="--create-retry-limit",
|
||||
cast=int,
|
||||
)
|
||||
"""Maximum create-order attempts per round."""
|
||||
|
||||
create_request_batch_size: int = config_field(
|
||||
DEFAULT_CREATE_REQUEST_BATCH_SIZE,
|
||||
env="BTB_CREATE_REQUEST_BATCH_SIZE",
|
||||
runtime="create_request_batch_size",
|
||||
db="createRequestBatchSize",
|
||||
cli="--create-request-batch-size",
|
||||
cast=int,
|
||||
)
|
||||
"""Number of create-order requests sent in one batch."""
|
||||
|
||||
proxy_max_consecutive_failures: int = config_field(
|
||||
2,
|
||||
env="BTB_PROXY_MAX_CONSECUTIVE_FAILURES",
|
||||
runtime="proxy_max_consecutive_failures",
|
||||
db="proxyMaxConsecutiveFailures",
|
||||
cli="--proxy-max-consecutive-failures",
|
||||
cast=int,
|
||||
)
|
||||
"""Failures before one proxy is temporarily cooled down."""
|
||||
|
||||
proxy_cooldown_seconds: int = config_field(
|
||||
180,
|
||||
env="BTB_PROXY_COOLDOWN_SECONDS",
|
||||
runtime="proxy_cooldown_seconds",
|
||||
db="proxyCooldownSeconds",
|
||||
cli="--proxy-cooldown-seconds",
|
||||
cast=int,
|
||||
)
|
||||
"""Cooldown duration for a failed proxy, in seconds."""
|
||||
|
||||
proxy_backoff_max_seconds: int = config_field(
|
||||
600,
|
||||
env="BTB_PROXY_BACKOFF_MAX_SECONDS",
|
||||
runtime="proxy_backoff_max_seconds",
|
||||
db="proxyBackoffMaxSeconds",
|
||||
cli="--proxy-backoff-max-seconds",
|
||||
cast=int,
|
||||
)
|
||||
"""Maximum sleep time when the whole proxy pool is unavailable."""
|
||||
|
||||
# 你原来的 from_config_db 里 ConfigDB 缺省时是 True,这里保留这个行为
|
||||
auto_open_payment_url: bool = config_field(
|
||||
False,
|
||||
runtime="auto_open_payment_url",
|
||||
db="autoOpenPaymentUrl",
|
||||
db_default=True,
|
||||
cast=str_to_bool,
|
||||
cli_true="--auto-open-payment-url",
|
||||
)
|
||||
"""Open the payment page automatically after success."""
|
||||
|
||||
log_level: str = config_field(
|
||||
"standard",
|
||||
env="BTB_LOG_LEVEL",
|
||||
runtime="log_level",
|
||||
db="logLevel",
|
||||
cli="--log-level",
|
||||
cast=normalize_log_level,
|
||||
)
|
||||
"""Console logging preset: simple, standard, or debug."""
|
||||
|
||||
log_retention_days: int = config_field(
|
||||
7,
|
||||
env="BTB_LOG_RETENTION_DAYS",
|
||||
runtime="log_retention_days",
|
||||
db="logRetentionDays",
|
||||
cli="--log-retention-days",
|
||||
cast=int,
|
||||
)
|
||||
"""Retention period for generated log files, in days."""
|
||||
|
||||
@classmethod
|
||||
def from_runtime_options(
|
||||
cls,
|
||||
tickets_info: str,
|
||||
runtime_options,
|
||||
*,
|
||||
show_qrcode: bool | None = None,
|
||||
) -> "BuyConfig":
|
||||
data = (
|
||||
runtime_options.to_dict()
|
||||
if hasattr(runtime_options, "to_dict")
|
||||
else dict(runtime_options)
|
||||
)
|
||||
|
||||
config = cls.from_mapping(data, source_name="runtime").with_overrides(
|
||||
tickets_info=tickets_info,
|
||||
)
|
||||
|
||||
if show_qrcode is not None:
|
||||
config = config.with_overrides(show_qrcode=show_qrcode)
|
||||
|
||||
return config
|
||||
|
||||
@classmethod
|
||||
def from_config_db(
|
||||
cls,
|
||||
*,
|
||||
tickets_info: str = "",
|
||||
time_start: str = "",
|
||||
interval: int | None = None,
|
||||
https_proxys: str | None = None,
|
||||
show_qrcode: bool | None = None,
|
||||
) -> "BuyConfig":
|
||||
from util import ConfigDB
|
||||
|
||||
config = cls.from_config_getter(ConfigDB.get)
|
||||
|
||||
overrides: dict[str, Any] = {
|
||||
"tickets_info": tickets_info,
|
||||
"time_start": time_start,
|
||||
}
|
||||
|
||||
if interval is not None:
|
||||
overrides["interval"] = interval
|
||||
|
||||
if https_proxys is not None:
|
||||
overrides["https_proxys"] = https_proxys
|
||||
|
||||
if show_qrcode is not None:
|
||||
overrides["show_qrcode"] = show_qrcode
|
||||
|
||||
return config.with_overrides(**overrides)
|
||||
|
||||
def apply_log_env(self) -> None:
|
||||
normalized_log_level = normalize_log_level(self.log_level)
|
||||
|
||||
if normalized_log_level == "simple":
|
||||
os.environ["BTB_LOG_LEVEL"] = "INFO"
|
||||
os.environ["BTB_CONSOLE_LOG_LEVEL"] = "INFO"
|
||||
elif normalized_log_level == "debug":
|
||||
os.environ["BTB_LOG_LEVEL"] = "DEBUG"
|
||||
os.environ["BTB_CONSOLE_LOG_LEVEL"] = "DEBUG"
|
||||
else:
|
||||
os.environ["BTB_LOG_LEVEL"] = "DEBUG"
|
||||
os.environ["BTB_CONSOLE_LOG_LEVEL"] = "INFO"
|
||||
|
||||
os.environ["BTB_LOG_RETENTION_DAYS"] = str(max(1, int(self.log_retention_days)))
|
||||
@@ -0,0 +1,288 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import os
|
||||
from dataclasses import MISSING, field, fields
|
||||
from typing import Any, Callable, ClassVar
|
||||
|
||||
|
||||
DEFAULT_CREATE_RETRY_LIMIT = 3
|
||||
DEFAULT_CREATE_REQUEST_BATCH_SIZE = 1
|
||||
DEFAULT_OUTER_LOOP_INTERVAL = 1000
|
||||
|
||||
|
||||
def str_to_bool(value: Any) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}
|
||||
|
||||
|
||||
def normalize_log_level(value: Any) -> str:
|
||||
return str(value or "standard").lower()
|
||||
|
||||
|
||||
def config_field(
|
||||
default: Any = MISSING,
|
||||
*,
|
||||
default_factory: Callable[[], Any] | Any = MISSING,
|
||||
env: str | None = None,
|
||||
runtime: str | None = None,
|
||||
db: str | None = None,
|
||||
cli: str | None = None,
|
||||
cast: Callable[[Any], Any] | None = None,
|
||||
env_default: Any = MISSING,
|
||||
runtime_default: Any = MISSING,
|
||||
db_default: Any = MISSING,
|
||||
env_transform: Callable[[Any], Any] | None = None,
|
||||
runtime_transform: Callable[[Any], Any] | None = None,
|
||||
db_transform: Callable[[Any], Any] | None = None,
|
||||
cli_false: str | None = None,
|
||||
cli_true: str | None = None,
|
||||
omit_cli_if_empty: bool = True,
|
||||
):
|
||||
metadata = {
|
||||
"env": env,
|
||||
"runtime": runtime,
|
||||
"db": db,
|
||||
"cli": cli,
|
||||
"cast": cast,
|
||||
"env_default": env_default,
|
||||
"runtime_default": runtime_default,
|
||||
"db_default": db_default,
|
||||
"env_transform": env_transform,
|
||||
"runtime_transform": runtime_transform,
|
||||
"db_transform": db_transform,
|
||||
"cli_false": cli_false,
|
||||
"cli_true": cli_true,
|
||||
"omit_cli_if_empty": omit_cli_if_empty,
|
||||
}
|
||||
|
||||
if default is not MISSING and default_factory is not MISSING:
|
||||
raise ValueError("不能同时传 default 和 default_factory")
|
||||
|
||||
if default_factory is not MISSING:
|
||||
return field(default_factory=default_factory, metadata=metadata)
|
||||
|
||||
if default is not MISSING:
|
||||
return field(default=default, metadata=metadata)
|
||||
|
||||
return field(metadata=metadata)
|
||||
|
||||
|
||||
def nested_config_field(default_factory: Callable[[], Any]):
|
||||
return field(
|
||||
default_factory=default_factory,
|
||||
metadata={
|
||||
"nested_config": True,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class BasicConfig:
|
||||
"""
|
||||
通用配置基类。
|
||||
|
||||
支持:
|
||||
1. from_env()
|
||||
2. from_mapping(...)
|
||||
3. from_config_getter(...)
|
||||
4. with_overrides(...)
|
||||
5. to_cli_args()
|
||||
"""
|
||||
|
||||
_skip_cli_fields: ClassVar[set[str]] = set()
|
||||
|
||||
@classmethod
|
||||
def _field_default(cls, f) -> Any:
|
||||
if f.default is not MISSING:
|
||||
return copy.deepcopy(f.default)
|
||||
|
||||
if f.default_factory is not MISSING: # type: ignore[attr-defined]
|
||||
return f.default_factory() # type: ignore[misc]
|
||||
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _source_default(cls, f, source_name: str) -> Any:
|
||||
key = f"{source_name}_default"
|
||||
value = f.metadata.get(key, MISSING)
|
||||
|
||||
if value is not MISSING:
|
||||
return copy.deepcopy(value)
|
||||
|
||||
return cls._field_default(f)
|
||||
|
||||
@staticmethod
|
||||
def _safe_apply(value: Any, func: Callable[[Any], Any] | None, default: Any) -> Any:
|
||||
if func is None:
|
||||
return value
|
||||
|
||||
try:
|
||||
return func(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
@classmethod
|
||||
def _normalize_value(cls, f, value: Any, *, source_name: str) -> Any:
|
||||
default = cls._source_default(f, source_name)
|
||||
|
||||
if value is None:
|
||||
value = default
|
||||
|
||||
cast = f.metadata.get("cast")
|
||||
value = cls._safe_apply(value, cast, default)
|
||||
|
||||
transform = f.metadata.get(f"{source_name}_transform")
|
||||
value = cls._safe_apply(value, transform, default)
|
||||
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def _is_nested_config_field(cls, f) -> bool:
|
||||
return bool(f.metadata.get("nested_config"))
|
||||
|
||||
@classmethod
|
||||
def from_mapping(
|
||||
cls,
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
source_name: str,
|
||||
):
|
||||
kwargs: dict[str, Any] = {}
|
||||
|
||||
for f in fields(cls):
|
||||
if not f.init:
|
||||
continue
|
||||
|
||||
if cls._is_nested_config_field(f):
|
||||
nested_cls = f.default_factory # type: ignore[attr-defined]
|
||||
kwargs[f.name] = nested_cls.from_mapping(
|
||||
source,
|
||||
source_name=source_name,
|
||||
)
|
||||
continue
|
||||
|
||||
source_key = f.metadata.get(source_name)
|
||||
if not source_key:
|
||||
continue
|
||||
|
||||
default = cls._source_default(f, source_name)
|
||||
raw = source.get(source_key, default)
|
||||
|
||||
kwargs[f.name] = cls._normalize_value(
|
||||
f,
|
||||
raw,
|
||||
source_name=source_name,
|
||||
)
|
||||
|
||||
return cls(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
kwargs: dict[str, Any] = {}
|
||||
|
||||
for f in fields(cls):
|
||||
if not f.init:
|
||||
continue
|
||||
|
||||
if cls._is_nested_config_field(f):
|
||||
nested_cls = f.default_factory # type: ignore[attr-defined]
|
||||
kwargs[f.name] = nested_cls.from_env()
|
||||
continue
|
||||
|
||||
env_key = f.metadata.get("env")
|
||||
if not env_key:
|
||||
continue
|
||||
|
||||
default = cls._source_default(f, "env")
|
||||
raw = os.environ.get(env_key, default)
|
||||
|
||||
kwargs[f.name] = cls._normalize_value(
|
||||
f,
|
||||
raw,
|
||||
source_name="env",
|
||||
)
|
||||
|
||||
return cls(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def from_config_getter(
|
||||
cls,
|
||||
getter: Callable[[str], Any],
|
||||
):
|
||||
kwargs: dict[str, Any] = {}
|
||||
|
||||
for f in fields(cls):
|
||||
if not f.init:
|
||||
continue
|
||||
|
||||
if cls._is_nested_config_field(f):
|
||||
nested_cls = f.default_factory # type: ignore[attr-defined]
|
||||
kwargs[f.name] = nested_cls.from_config_getter(getter)
|
||||
continue
|
||||
|
||||
db_key = f.metadata.get("db")
|
||||
if not db_key:
|
||||
continue
|
||||
|
||||
default = cls._source_default(f, "db")
|
||||
raw = getter(db_key)
|
||||
|
||||
if raw is None:
|
||||
raw = default
|
||||
|
||||
kwargs[f.name] = cls._normalize_value(
|
||||
f,
|
||||
raw,
|
||||
source_name="db",
|
||||
)
|
||||
|
||||
return cls(**kwargs)
|
||||
|
||||
def with_overrides(self, **changes):
|
||||
payload = {
|
||||
f.name: copy.deepcopy(getattr(self, f.name)) for f in fields(self) if f.init
|
||||
}
|
||||
payload.update(changes)
|
||||
return type(self)(**payload)
|
||||
|
||||
def to_cli_args(self) -> list[str]:
|
||||
args: list[str] = []
|
||||
|
||||
def append_value(flag: str, value: Any, *, omit_if_empty: bool = True) -> None:
|
||||
if omit_if_empty and value in (None, ""):
|
||||
return
|
||||
args.extend([flag, str(value)])
|
||||
|
||||
for f in fields(self):
|
||||
if not f.init:
|
||||
continue
|
||||
|
||||
if f.name in self._skip_cli_fields:
|
||||
continue
|
||||
|
||||
value = getattr(self, f.name)
|
||||
|
||||
if self._is_nested_config_field(f):
|
||||
if isinstance(value, BasicConfig):
|
||||
args.extend(value.to_cli_args())
|
||||
continue
|
||||
|
||||
cli_true = f.metadata.get("cli_true")
|
||||
cli_false = f.metadata.get("cli_false")
|
||||
cli = f.metadata.get("cli")
|
||||
omit_cli_if_empty = bool(f.metadata.get("omit_cli_if_empty", True))
|
||||
|
||||
if isinstance(value, bool):
|
||||
if value and cli_true:
|
||||
args.append(cli_true)
|
||||
elif not value and cli_false:
|
||||
args.append(cli_false)
|
||||
elif cli:
|
||||
append_value(cli, value, omit_if_empty=omit_cli_if_empty)
|
||||
continue
|
||||
|
||||
if cli:
|
||||
append_value(cli, value, omit_if_empty=omit_cli_if_empty)
|
||||
|
||||
return args
|
||||
@@ -0,0 +1,114 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app_cmd.config.ConfigBasic import BasicConfig, config_field, str_to_bool
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class NotifierConfig(BasicConfig):
|
||||
"""Notification channels used after success or proxy exhaustion."""
|
||||
|
||||
serverchan_key: str = config_field(
|
||||
"",
|
||||
env="BTB_SERVERCHANKEY",
|
||||
runtime="serverchanKey",
|
||||
db="serverchanKey",
|
||||
cli="--notifier-config.serverchan-key",
|
||||
)
|
||||
"""ServerChan Turbo send key."""
|
||||
|
||||
serverchan3_api_url: str = config_field(
|
||||
"",
|
||||
env="BTB_SERVERCHAN3APIURL",
|
||||
runtime="serverchan3ApiUrl",
|
||||
db="serverchan3ApiUrl",
|
||||
cli="--notifier-config.serverchan3-api-url",
|
||||
)
|
||||
"""ServerChan3 API endpoint."""
|
||||
|
||||
pushplus_token: str = config_field(
|
||||
"",
|
||||
env="BTB_PUSHPLUSTOKEN",
|
||||
runtime="pushplusToken",
|
||||
db="pushplusToken",
|
||||
cli="--notifier-config.pushplus-token",
|
||||
)
|
||||
"""PushPlus token."""
|
||||
|
||||
bark_token: str = config_field(
|
||||
"",
|
||||
env="BTB_BARKTOKEN",
|
||||
runtime="barkToken",
|
||||
db="barkToken",
|
||||
cli="--notifier-config.bark-token",
|
||||
)
|
||||
"""Bark token or self-hosted Bark push path."""
|
||||
|
||||
ntfy_url: str = config_field(
|
||||
"",
|
||||
env="BTB_NTFY_URL",
|
||||
runtime="ntfy_url",
|
||||
db="ntfyUrl",
|
||||
cli="--notifier-config.ntfy-url",
|
||||
)
|
||||
"""ntfy topic URL."""
|
||||
|
||||
ntfy_username: str = config_field(
|
||||
"",
|
||||
env="BTB_NTFY_USERNAME",
|
||||
runtime="ntfy_username",
|
||||
db="ntfyUsername",
|
||||
cli="--notifier-config.ntfy-username",
|
||||
)
|
||||
"""Username for ntfy authentication."""
|
||||
|
||||
ntfy_password: str = config_field(
|
||||
"",
|
||||
env="BTB_NTFY_PASSWORD",
|
||||
runtime="ntfy_password",
|
||||
db="ntfyPassword",
|
||||
cli="--notifier-config.ntfy-password",
|
||||
)
|
||||
"""Password for ntfy authentication."""
|
||||
|
||||
meow_nickname: str = config_field(
|
||||
"",
|
||||
env="BTB_MEOWNICKNAME",
|
||||
runtime="meowNickname",
|
||||
db="meowNickname",
|
||||
cli="--notifier-config.meow-nickname",
|
||||
)
|
||||
"""MeoW nickname."""
|
||||
|
||||
audio_path: str = config_field(
|
||||
"",
|
||||
env="BTB_AUDIO_PATH",
|
||||
runtime="audio_path",
|
||||
db="audioPath",
|
||||
cli="--notifier-config.audio-path",
|
||||
)
|
||||
"""Local audio file played after success."""
|
||||
|
||||
notify_proxy_exhausted: bool = config_field(
|
||||
False,
|
||||
env="BTB_NOTIFY_PROXY_EXHAUSTED",
|
||||
runtime="notify_proxy_exhausted",
|
||||
db="notifyProxyExhausted",
|
||||
cast=str_to_bool,
|
||||
cli_true="--notifier-config.notify-proxy-exhausted",
|
||||
)
|
||||
"""Send a notification when all proxies enter cooldown."""
|
||||
|
||||
@classmethod
|
||||
def from_runtime_options(cls, runtime_options) -> "NotifierConfig":
|
||||
data = (
|
||||
runtime_options.to_dict()
|
||||
if hasattr(runtime_options, "to_dict")
|
||||
else dict(runtime_options)
|
||||
)
|
||||
return cls.from_mapping(data, source_name="runtime")
|
||||
|
||||
@classmethod
|
||||
def from_config_db(cls) -> "NotifierConfig":
|
||||
from util import ConfigDB
|
||||
|
||||
return cls.from_config_getter(ConfigDB.get)
|
||||
Reference in new issue
Block a user