Merge branch 'fork/Hylouis233/feat/accounts-image-capability'
Browse files- services/account_service.py +29 -15
- services/config.py +48 -9
- services/utils.py +9 -0
- test/__init__.py +1 -0
- test/test_account_image_capabilities.py +64 -0
- web/src/app/accounts/page.tsx +25 -4
- web/src/lib/api.ts +2 -1
services/account_service.py
CHANGED
|
@@ -13,12 +13,15 @@ from curl_cffi.requests import Session
|
|
| 13 |
|
| 14 |
from services.config import config
|
| 15 |
from services.proxy_service import proxy_settings
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
class AccountService:
|
| 19 |
ACCOUNT_TYPE_MAP = {
|
| 20 |
"free": "Free",
|
| 21 |
"plus": "Plus",
|
|
|
|
|
|
|
| 22 |
"team": "Team",
|
| 23 |
"pro": "Pro",
|
| 24 |
"personal": "Plus",
|
|
@@ -56,8 +59,11 @@ class AccountService:
|
|
| 56 |
def _is_image_account_available(account: dict) -> bool:
|
| 57 |
if not isinstance(account, dict):
|
| 58 |
return False
|
| 59 |
-
|
|
|
|
| 60 |
return False
|
|
|
|
|
|
|
| 61 |
return int(account.get("quota") or 0) > 0
|
| 62 |
|
| 63 |
def _decode_access_token_payload(self, access_token: str) -> dict[str, Any]:
|
|
@@ -125,6 +131,7 @@ class AccountService:
|
|
| 125 |
normalized["quota"] = int(normalized.get("quota") if normalized.get("quota") is not None else 0)
|
| 126 |
if normalized["quota"] < 0:
|
| 127 |
normalized["quota"] = 0
|
|
|
|
| 128 |
normalized["email"] = self._clean_token(normalized.get("email")) or None
|
| 129 |
normalized["user_id"] = self._clean_token(normalized.get("user_id")) or None
|
| 130 |
limits_progress = normalized.get("limits_progress")
|
|
@@ -137,7 +144,7 @@ class AccountService:
|
|
| 137 |
return normalized
|
| 138 |
|
| 139 |
@staticmethod
|
| 140 |
-
def _extract_quota_and_restore_at(limits_progress: list[Any]) -> tuple[int, str | None]:
|
| 141 |
quota = 0
|
| 142 |
restore_at = None
|
| 143 |
for item in limits_progress:
|
|
@@ -145,8 +152,8 @@ class AccountService:
|
|
| 145 |
continue
|
| 146 |
quota = int(item.get("remaining") or 0)
|
| 147 |
restore_at = str(item.get("reset_after") or "").strip() or None
|
| 148 |
-
|
| 149 |
-
return quota, restore_at
|
| 150 |
|
| 151 |
def _load_accounts(self) -> list[dict]:
|
| 152 |
if not self.store_file.exists():
|
|
@@ -205,6 +212,7 @@ class AccountService:
|
|
| 205 |
"type": account.get("type") or "Free",
|
| 206 |
"status": account.get("status") or "正常",
|
| 207 |
"quota": account.get("quota") if account.get("quota") is not None else 0,
|
|
|
|
| 208 |
"email": account.get("email"),
|
| 209 |
"user_id": account.get("user_id"),
|
| 210 |
"limits_progress": account.get("limits_progress") or [],
|
|
@@ -242,11 +250,12 @@ class AccountService:
|
|
| 242 |
return access_token
|
| 243 |
|
| 244 |
def refresh_account_state(self, access_token: str) -> dict | None:
|
|
|
|
| 245 |
try:
|
| 246 |
remote_info = self.fetch_remote_info(access_token)
|
| 247 |
except Exception as exc:
|
| 248 |
message = str(exc)
|
| 249 |
-
print(f"[account-available] refresh token={
|
| 250 |
if "/backend-api/me failed: HTTP 401" in message:
|
| 251 |
return self.update_account(
|
| 252 |
access_token,
|
|
@@ -263,11 +272,12 @@ class AccountService:
|
|
| 263 |
while True:
|
| 264 |
access_token = self._pick_next_candidate_token(excluded_tokens=attempted_tokens)
|
| 265 |
attempted_tokens.add(access_token)
|
|
|
|
| 266 |
account = self.refresh_account_state(access_token)
|
| 267 |
if self._is_image_account_available(account or {}):
|
| 268 |
return access_token
|
| 269 |
print(
|
| 270 |
-
f"[account-available] skip token={
|
| 271 |
f"quota={account.get('quota') if account else 'unknown'} "
|
| 272 |
f"status={account.get('status') if account else 'unknown'}"
|
| 273 |
)
|
|
@@ -374,10 +384,12 @@ class AccountService:
|
|
| 374 |
return None
|
| 375 |
next_item = dict(self._accounts[index])
|
| 376 |
next_item["last_used_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
| 377 |
if success:
|
| 378 |
next_item["success"] = int(next_item.get("success") or 0) + 1
|
| 379 |
-
|
| 380 |
-
|
|
|
|
| 381 |
next_item["status"] = "限流"
|
| 382 |
next_item["restore_at"] = next_item.get("restore_at") or None
|
| 383 |
elif next_item.get("status") == "限流":
|
|
@@ -398,7 +410,8 @@ class AccountService:
|
|
| 398 |
raise ValueError("access_token is required")
|
| 399 |
|
| 400 |
headers, impersonate = self._build_remote_headers(access_token)
|
| 401 |
-
|
|
|
|
| 402 |
session = Session(**proxy_settings.build_session_kwargs(impersonate=impersonate, verify=True))
|
| 403 |
session.headers.update(headers)
|
| 404 |
try:
|
|
@@ -439,14 +452,16 @@ class AccountService:
|
|
| 439 |
if not isinstance(limits_progress, list):
|
| 440 |
limits_progress = []
|
| 441 |
|
| 442 |
-
|
| 443 |
-
|
|
|
|
| 444 |
|
| 445 |
result = {
|
| 446 |
"email": me_payload.get("email"),
|
| 447 |
"user_id": me_payload.get("id"),
|
| 448 |
-
"type":
|
| 449 |
"quota": quota,
|
|
|
|
| 450 |
"limits_progress": limits_progress,
|
| 451 |
"default_model_slug": init_payload.get("default_model_slug"),
|
| 452 |
"restore_at": restore_at,
|
|
@@ -454,8 +469,7 @@ class AccountService:
|
|
| 454 |
}
|
| 455 |
print(
|
| 456 |
"[account-refresh] ok",
|
| 457 |
-
|
| 458 |
-
result.get("email"),
|
| 459 |
f"quota={result.get('quota')}",
|
| 460 |
f"restore_at={result.get('restore_at')}",
|
| 461 |
)
|
|
@@ -482,7 +496,7 @@ class AccountService:
|
|
| 482 |
refreshed += 1
|
| 483 |
except Exception as exc:
|
| 484 |
message = str(exc)
|
| 485 |
-
print(f"[account-refresh] fail {access_token
|
| 486 |
if "/backend-api/me failed: HTTP 401" in message:
|
| 487 |
self.update_account(
|
| 488 |
access_token,
|
|
|
|
| 13 |
|
| 14 |
from services.config import config
|
| 15 |
from services.proxy_service import proxy_settings
|
| 16 |
+
from services.utils import anonymize_token
|
| 17 |
|
| 18 |
|
| 19 |
class AccountService:
|
| 20 |
ACCOUNT_TYPE_MAP = {
|
| 21 |
"free": "Free",
|
| 22 |
"plus": "Plus",
|
| 23 |
+
"prolite": "ProLite",
|
| 24 |
+
"pro_lite": "ProLite",
|
| 25 |
"team": "Team",
|
| 26 |
"pro": "Pro",
|
| 27 |
"personal": "Plus",
|
|
|
|
| 59 |
def _is_image_account_available(account: dict) -> bool:
|
| 60 |
if not isinstance(account, dict):
|
| 61 |
return False
|
| 62 |
+
status = str(account.get("status") or "").strip()
|
| 63 |
+
if status in {"禁用", "限流"}:
|
| 64 |
return False
|
| 65 |
+
if bool(account.get("image_quota_unknown")):
|
| 66 |
+
return True
|
| 67 |
return int(account.get("quota") or 0) > 0
|
| 68 |
|
| 69 |
def _decode_access_token_payload(self, access_token: str) -> dict[str, Any]:
|
|
|
|
| 131 |
normalized["quota"] = int(normalized.get("quota") if normalized.get("quota") is not None else 0)
|
| 132 |
if normalized["quota"] < 0:
|
| 133 |
normalized["quota"] = 0
|
| 134 |
+
normalized["image_quota_unknown"] = bool(normalized.get("image_quota_unknown"))
|
| 135 |
normalized["email"] = self._clean_token(normalized.get("email")) or None
|
| 136 |
normalized["user_id"] = self._clean_token(normalized.get("user_id")) or None
|
| 137 |
limits_progress = normalized.get("limits_progress")
|
|
|
|
| 144 |
return normalized
|
| 145 |
|
| 146 |
@staticmethod
|
| 147 |
+
def _extract_quota_and_restore_at(limits_progress: list[Any]) -> tuple[int, str | None, bool]:
|
| 148 |
quota = 0
|
| 149 |
restore_at = None
|
| 150 |
for item in limits_progress:
|
|
|
|
| 152 |
continue
|
| 153 |
quota = int(item.get("remaining") or 0)
|
| 154 |
restore_at = str(item.get("reset_after") or "").strip() or None
|
| 155 |
+
return quota, restore_at, False
|
| 156 |
+
return quota, restore_at, True
|
| 157 |
|
| 158 |
def _load_accounts(self) -> list[dict]:
|
| 159 |
if not self.store_file.exists():
|
|
|
|
| 212 |
"type": account.get("type") or "Free",
|
| 213 |
"status": account.get("status") or "正常",
|
| 214 |
"quota": account.get("quota") if account.get("quota") is not None else 0,
|
| 215 |
+
"imageQuotaUnknown": bool(account.get("image_quota_unknown")),
|
| 216 |
"email": account.get("email"),
|
| 217 |
"user_id": account.get("user_id"),
|
| 218 |
"limits_progress": account.get("limits_progress") or [],
|
|
|
|
| 250 |
return access_token
|
| 251 |
|
| 252 |
def refresh_account_state(self, access_token: str) -> dict | None:
|
| 253 |
+
token_ref = anonymize_token(access_token)
|
| 254 |
try:
|
| 255 |
remote_info = self.fetch_remote_info(access_token)
|
| 256 |
except Exception as exc:
|
| 257 |
message = str(exc)
|
| 258 |
+
print(f"[account-available] refresh token={token_ref} fail {message}")
|
| 259 |
if "/backend-api/me failed: HTTP 401" in message:
|
| 260 |
return self.update_account(
|
| 261 |
access_token,
|
|
|
|
| 272 |
while True:
|
| 273 |
access_token = self._pick_next_candidate_token(excluded_tokens=attempted_tokens)
|
| 274 |
attempted_tokens.add(access_token)
|
| 275 |
+
token_ref = anonymize_token(access_token)
|
| 276 |
account = self.refresh_account_state(access_token)
|
| 277 |
if self._is_image_account_available(account or {}):
|
| 278 |
return access_token
|
| 279 |
print(
|
| 280 |
+
f"[account-available] skip token={token_ref} "
|
| 281 |
f"quota={account.get('quota') if account else 'unknown'} "
|
| 282 |
f"status={account.get('status') if account else 'unknown'}"
|
| 283 |
)
|
|
|
|
| 384 |
return None
|
| 385 |
next_item = dict(self._accounts[index])
|
| 386 |
next_item["last_used_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 387 |
+
image_quota_unknown = bool(next_item.get("image_quota_unknown"))
|
| 388 |
if success:
|
| 389 |
next_item["success"] = int(next_item.get("success") or 0) + 1
|
| 390 |
+
if not image_quota_unknown:
|
| 391 |
+
next_item["quota"] = max(0, int(next_item.get("quota") or 0) - 1)
|
| 392 |
+
if not image_quota_unknown and next_item["quota"] == 0:
|
| 393 |
next_item["status"] = "限流"
|
| 394 |
next_item["restore_at"] = next_item.get("restore_at") or None
|
| 395 |
elif next_item.get("status") == "限流":
|
|
|
|
| 410 |
raise ValueError("access_token is required")
|
| 411 |
|
| 412 |
headers, impersonate = self._build_remote_headers(access_token)
|
| 413 |
+
token_ref = anonymize_token(access_token)
|
| 414 |
+
print(f"[account-refresh] start {token_ref}")
|
| 415 |
session = Session(**proxy_settings.build_session_kwargs(impersonate=impersonate, verify=True))
|
| 416 |
session.headers.update(headers)
|
| 417 |
try:
|
|
|
|
| 452 |
if not isinstance(limits_progress, list):
|
| 453 |
limits_progress = []
|
| 454 |
|
| 455 |
+
account_type = self._detect_account_type(access_token, me_payload, init_payload)
|
| 456 |
+
quota, restore_at, image_quota_unknown = self._extract_quota_and_restore_at(limits_progress)
|
| 457 |
+
status = "正常" if image_quota_unknown and account_type != "Free" else ("限流" if quota == 0 else "正常")
|
| 458 |
|
| 459 |
result = {
|
| 460 |
"email": me_payload.get("email"),
|
| 461 |
"user_id": me_payload.get("id"),
|
| 462 |
+
"type": account_type,
|
| 463 |
"quota": quota,
|
| 464 |
+
"image_quota_unknown": image_quota_unknown,
|
| 465 |
"limits_progress": limits_progress,
|
| 466 |
"default_model_slug": init_payload.get("default_model_slug"),
|
| 467 |
"restore_at": restore_at,
|
|
|
|
| 469 |
}
|
| 470 |
print(
|
| 471 |
"[account-refresh] ok",
|
| 472 |
+
token_ref,
|
|
|
|
| 473 |
f"quota={result.get('quota')}",
|
| 474 |
f"restore_at={result.get('restore_at')}",
|
| 475 |
)
|
|
|
|
| 496 |
refreshed += 1
|
| 497 |
except Exception as exc:
|
| 498 |
message = str(exc)
|
| 499 |
+
print(f"[account-refresh] fail {anonymize_token(access_token)} {message}")
|
| 500 |
if "/backend-api/me failed: HTTP 401" in message:
|
| 501 |
self.update_account(
|
| 502 |
access_token,
|
services/config.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import json
|
| 4 |
import os
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
|
| 7 |
BASE_DIR = Path(__file__).resolve().parents[1]
|
|
@@ -9,6 +11,49 @@ DATA_DIR = BASE_DIR / "data"
|
|
| 9 |
CONFIG_FILE = BASE_DIR / "config.json"
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
class ConfigStore:
|
| 13 |
def __init__(self, path: Path):
|
| 14 |
self.path = path
|
|
@@ -25,13 +70,7 @@ class ConfigStore:
|
|
| 25 |
)
|
| 26 |
|
| 27 |
def _load(self) -> dict[str, object]:
|
| 28 |
-
|
| 29 |
-
return {}
|
| 30 |
-
try:
|
| 31 |
-
data = json.loads(self.path.read_text(encoding="utf-8"))
|
| 32 |
-
except Exception:
|
| 33 |
-
return {}
|
| 34 |
-
return data if isinstance(data, dict) else {}
|
| 35 |
|
| 36 |
def _save(self) -> None:
|
| 37 |
self.path.write_text(json.dumps(self.data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
@@ -47,9 +86,9 @@ class ConfigStore:
|
|
| 47 |
@property
|
| 48 |
def refresh_account_interval_minute(self) -> int:
|
| 49 |
try:
|
| 50 |
-
return int(self.data.get("refresh_account_interval_minute",
|
| 51 |
except (TypeError, ValueError):
|
| 52 |
-
return
|
| 53 |
|
| 54 |
@property
|
| 55 |
def images_dir(self) -> Path:
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
import json
|
| 5 |
import os
|
| 6 |
+
import sys
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
BASE_DIR = Path(__file__).resolve().parents[1]
|
|
|
|
| 11 |
CONFIG_FILE = BASE_DIR / "config.json"
|
| 12 |
|
| 13 |
|
| 14 |
+
@dataclass(frozen=True)
|
| 15 |
+
class LoadedSettings:
|
| 16 |
+
auth_key: str
|
| 17 |
+
refresh_account_interval_minute: int
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _read_json_object(path: Path, *, name: str) -> dict[str, object]:
|
| 21 |
+
if not path.exists():
|
| 22 |
+
return {}
|
| 23 |
+
if path.is_dir():
|
| 24 |
+
print(
|
| 25 |
+
f"Warning: {name} at '{path}' is a directory, ignoring it and falling back to other configuration sources.",
|
| 26 |
+
file=sys.stderr,
|
| 27 |
+
)
|
| 28 |
+
return {}
|
| 29 |
+
try:
|
| 30 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 31 |
+
except Exception:
|
| 32 |
+
return {}
|
| 33 |
+
return data if isinstance(data, dict) else {}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _load_settings() -> LoadedSettings:
|
| 37 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
raw_config = _read_json_object(CONFIG_FILE, name="config.json")
|
| 39 |
+
auth_key = str(os.getenv("CHATGPT2API_AUTH_KEY") or raw_config.get("auth-key") or "").strip()
|
| 40 |
+
if not auth_key:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
"❌ auth-key 未设置!\n"
|
| 43 |
+
"请在环境变量 CHATGPT2API_AUTH_KEY 中设置,或者在 config.json 中填写 auth-key。"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
refresh_interval = int(raw_config.get("refresh_account_interval_minute", 5))
|
| 48 |
+
except (TypeError, ValueError):
|
| 49 |
+
refresh_interval = 5
|
| 50 |
+
|
| 51 |
+
return LoadedSettings(
|
| 52 |
+
auth_key=auth_key,
|
| 53 |
+
refresh_account_interval_minute=refresh_interval,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
class ConfigStore:
|
| 58 |
def __init__(self, path: Path):
|
| 59 |
self.path = path
|
|
|
|
| 70 |
)
|
| 71 |
|
| 72 |
def _load(self) -> dict[str, object]:
|
| 73 |
+
return _read_json_object(self.path, name="config.json")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
def _save(self) -> None:
|
| 76 |
self.path.write_text(json.dumps(self.data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
|
|
| 86 |
@property
|
| 87 |
def refresh_account_interval_minute(self) -> int:
|
| 88 |
try:
|
| 89 |
+
return int(self.data.get("refresh_account_interval_minute", 5))
|
| 90 |
except (TypeError, ValueError):
|
| 91 |
+
return 5
|
| 92 |
|
| 93 |
@property
|
| 94 |
def images_dir(self) -> Path:
|
services/utils.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import time
|
| 4 |
import uuid
|
| 5 |
|
|
@@ -9,6 +10,14 @@ from fastapi import HTTPException
|
|
| 9 |
IMAGE_MODELS = {"gpt-image-1", "gpt-image-2"}
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
def is_image_chat_request(body: dict[str, object]) -> bool:
|
| 13 |
model = str(body.get("model") or "").strip()
|
| 14 |
modalities = body.get("modalities")
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import hashlib
|
| 4 |
import time
|
| 5 |
import uuid
|
| 6 |
|
|
|
|
| 10 |
IMAGE_MODELS = {"gpt-image-1", "gpt-image-2"}
|
| 11 |
|
| 12 |
|
| 13 |
+
def anonymize_token(token: object) -> str:
|
| 14 |
+
value = str(token or "").strip()
|
| 15 |
+
if not value:
|
| 16 |
+
return "token:empty"
|
| 17 |
+
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:10]
|
| 18 |
+
return f"token:{digest}"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
def is_image_chat_request(body: dict[str, object]) -> bool:
|
| 22 |
model = str(body.get("model") or "").strip()
|
| 23 |
modalities = body.get("modalities")
|
test/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
test/test_account_image_capabilities.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import tempfile
|
| 5 |
+
import unittest
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
os.environ.setdefault("CHATGPT2API_AUTH_KEY", "test-auth")
|
| 9 |
+
|
| 10 |
+
from services.account_service import AccountService
|
| 11 |
+
from services.utils import anonymize_token
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AccountCapabilityTests(unittest.TestCase):
|
| 15 |
+
def test_unknown_quota_accounts_are_available_only_when_not_throttled(self) -> None:
|
| 16 |
+
self.assertFalse(
|
| 17 |
+
AccountService._is_image_account_available(
|
| 18 |
+
{"status": "限流", "image_quota_unknown": True, "quota": 0}
|
| 19 |
+
)
|
| 20 |
+
)
|
| 21 |
+
self.assertTrue(
|
| 22 |
+
AccountService._is_image_account_available(
|
| 23 |
+
{"status": "正常", "image_quota_unknown": True, "quota": 0}
|
| 24 |
+
)
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def test_prolite_variants_are_normalized(self) -> None:
|
| 28 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 29 |
+
service = AccountService(Path(tmp_dir) / "accounts.json")
|
| 30 |
+
self.assertEqual(service._normalize_account_type("prolite"), "ProLite")
|
| 31 |
+
self.assertEqual(service._normalize_account_type("pro_lite"), "ProLite")
|
| 32 |
+
|
| 33 |
+
def test_mark_image_result_does_not_consume_unknown_quota(self) -> None:
|
| 34 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 35 |
+
service = AccountService(Path(tmp_dir) / "accounts.json")
|
| 36 |
+
service.add_accounts(["token-1"])
|
| 37 |
+
service.update_account(
|
| 38 |
+
"token-1",
|
| 39 |
+
{
|
| 40 |
+
"status": "正常",
|
| 41 |
+
"quota": 0,
|
| 42 |
+
"image_quota_unknown": True,
|
| 43 |
+
},
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
updated = service.mark_image_result("token-1", success=True)
|
| 47 |
+
|
| 48 |
+
self.assertIsNotNone(updated)
|
| 49 |
+
self.assertEqual(updated["quota"], 0)
|
| 50 |
+
self.assertEqual(updated["status"], "正常")
|
| 51 |
+
self.assertTrue(updated["image_quota_unknown"])
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class TokenLogTests(unittest.TestCase):
|
| 55 |
+
def test_anonymize_token_hides_raw_value(self) -> None:
|
| 56 |
+
token = "super-secret-token"
|
| 57 |
+
token_ref = anonymize_token(token)
|
| 58 |
+
|
| 59 |
+
self.assertTrue(token_ref.startswith("token:"))
|
| 60 |
+
self.assertNotIn(token, token_ref)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
unittest.main()
|
web/src/app/accounts/page.tsx
CHANGED
|
@@ -57,6 +57,7 @@ const accountTypeOptions: { label: string; value: AccountType | "all" }[] = [
|
|
| 57 |
{ label: "全部类型", value: "all" },
|
| 58 |
{ label: "Free", value: "Free" },
|
| 59 |
{ label: "Plus", value: "Plus" },
|
|
|
|
| 60 |
{ label: "Team", value: "Team" },
|
| 61 |
{ label: "Pro", value: "Pro" },
|
| 62 |
];
|
|
@@ -91,6 +92,10 @@ const metricCards = [
|
|
| 91 |
{ key: "quota", label: "剩余额度", color: "text-blue-500", icon: RefreshCw },
|
| 92 |
] as const;
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
function formatCompact(value: number) {
|
| 95 |
if (value >= 1000) {
|
| 96 |
return `${(value / 1000).toFixed(1)}k`;
|
|
@@ -98,8 +103,14 @@ function formatCompact(value: number) {
|
|
| 98 |
return String(value);
|
| 99 |
}
|
| 100 |
|
| 101 |
-
function formatQuota(
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
|
| 105 |
function formatRestoreAt(value?: string | null) {
|
|
@@ -127,6 +138,12 @@ function formatRestoreAt(value?: string | null) {
|
|
| 127 |
}
|
| 128 |
|
| 129 |
function formatQuotaSummary(accounts: Account[]) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
return formatCompact(accounts.reduce((sum, account) => sum + Math.max(0, account.quota), 0));
|
| 131 |
}
|
| 132 |
|
|
@@ -151,7 +168,11 @@ function normalizeAccounts(items: Account[]): Account[] {
|
|
| 151 |
return items.map((item) => ({
|
| 152 |
...item,
|
| 153 |
type:
|
| 154 |
-
item.type === "Plus" ||
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
? item.type
|
| 156 |
: "Free",
|
| 157 |
}));
|
|
@@ -683,7 +704,7 @@ export default function AccountsPage() {
|
|
| 683 |
</td>
|
| 684 |
<td className="px-4 py-3">
|
| 685 |
<Badge variant="info" className="rounded-md">
|
| 686 |
-
{formatQuota(account
|
| 687 |
</Badge>
|
| 688 |
</td>
|
| 689 |
<td className="px-4 py-3 text-xs leading-5 text-stone-500">
|
|
|
|
| 57 |
{ label: "全部类型", value: "all" },
|
| 58 |
{ label: "Free", value: "Free" },
|
| 59 |
{ label: "Plus", value: "Plus" },
|
| 60 |
+
{ label: "ProLite", value: "ProLite" },
|
| 61 |
{ label: "Team", value: "Team" },
|
| 62 |
{ label: "Pro", value: "Pro" },
|
| 63 |
];
|
|
|
|
| 92 |
{ key: "quota", label: "剩余额度", color: "text-blue-500", icon: RefreshCw },
|
| 93 |
] as const;
|
| 94 |
|
| 95 |
+
function isUnlimitedImageQuotaAccount(account: Account) {
|
| 96 |
+
return account.type === "Pro" || account.type === "ProLite";
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
function formatCompact(value: number) {
|
| 100 |
if (value >= 1000) {
|
| 101 |
return `${(value / 1000).toFixed(1)}k`;
|
|
|
|
| 103 |
return String(value);
|
| 104 |
}
|
| 105 |
|
| 106 |
+
function formatQuota(account: Account) {
|
| 107 |
+
if (isUnlimitedImageQuotaAccount(account)) {
|
| 108 |
+
return "∞";
|
| 109 |
+
}
|
| 110 |
+
if (account.imageQuotaUnknown) {
|
| 111 |
+
return "未知";
|
| 112 |
+
}
|
| 113 |
+
return String(Math.max(0, account.quota));
|
| 114 |
}
|
| 115 |
|
| 116 |
function formatRestoreAt(value?: string | null) {
|
|
|
|
| 138 |
}
|
| 139 |
|
| 140 |
function formatQuotaSummary(accounts: Account[]) {
|
| 141 |
+
if (accounts.some((account) => account.status !== "禁用" && isUnlimitedImageQuotaAccount(account))) {
|
| 142 |
+
return "∞";
|
| 143 |
+
}
|
| 144 |
+
if (accounts.some((account) => account.status !== "禁用" && account.imageQuotaUnknown)) {
|
| 145 |
+
return "未知";
|
| 146 |
+
}
|
| 147 |
return formatCompact(accounts.reduce((sum, account) => sum + Math.max(0, account.quota), 0));
|
| 148 |
}
|
| 149 |
|
|
|
|
| 168 |
return items.map((item) => ({
|
| 169 |
...item,
|
| 170 |
type:
|
| 171 |
+
item.type === "Plus" ||
|
| 172 |
+
item.type === "ProLite" ||
|
| 173 |
+
item.type === "Team" ||
|
| 174 |
+
item.type === "Pro" ||
|
| 175 |
+
item.type === "Free"
|
| 176 |
? item.type
|
| 177 |
: "Free",
|
| 178 |
}));
|
|
|
|
| 704 |
</td>
|
| 705 |
<td className="px-4 py-3">
|
| 706 |
<Badge variant="info" className="rounded-md">
|
| 707 |
+
{formatQuota(account)}
|
| 708 |
</Badge>
|
| 709 |
</td>
|
| 710 |
<td className="px-4 py-3 text-xs leading-5 text-stone-500">
|
web/src/lib/api.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import { httpRequest } from "@/lib/request";
|
| 2 |
|
| 3 |
-
export type AccountType = "Free" | "Plus" | "Pro" | "Team";
|
| 4 |
export type AccountStatus = "正常" | "限流" | "异常" | "禁用";
|
| 5 |
export type ImageModel = "gpt-image-1" | "gpt-image-2";
|
| 6 |
|
|
@@ -10,6 +10,7 @@ export type Account = {
|
|
| 10 |
type: AccountType;
|
| 11 |
status: AccountStatus;
|
| 12 |
quota: number;
|
|
|
|
| 13 |
email?: string | null;
|
| 14 |
user_id?: string | null;
|
| 15 |
limits_progress?: Array<{
|
|
|
|
| 1 |
import { httpRequest } from "@/lib/request";
|
| 2 |
|
| 3 |
+
export type AccountType = "Free" | "Plus" | "ProLite" | "Pro" | "Team";
|
| 4 |
export type AccountStatus = "正常" | "限流" | "异常" | "禁用";
|
| 5 |
export type ImageModel = "gpt-image-1" | "gpt-image-2";
|
| 6 |
|
|
|
|
| 10 |
type: AccountType;
|
| 11 |
status: AccountStatus;
|
| 12 |
quota: number;
|
| 13 |
+
imageQuotaUnknown?: boolean;
|
| 14 |
email?: string | null;
|
| 15 |
user_id?: string | null;
|
| 16 |
limits_progress?: Array<{
|