feat: 增加设置页和托盘,登录后关闭窗口留在托盘
This commit is contained in:
@@ -13,6 +13,7 @@ import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from concurrent.futures import Future
|
||||
@@ -340,25 +341,65 @@ def _new_job_id() -> str:
|
||||
return candidate
|
||||
|
||||
|
||||
def load_task_limit() -> int:
|
||||
_SETTINGS_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _read_settings() -> dict:
|
||||
try:
|
||||
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
|
||||
return min(8, max(1, int(data.get("maxConcurrentJobs") or 2)))
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError):
|
||||
return 2
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_settings(data: dict) -> None:
|
||||
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")
|
||||
write_atomic(SETTINGS_PATH, payload)
|
||||
|
||||
|
||||
def load_task_limit() -> int:
|
||||
with _SETTINGS_LOCK:
|
||||
try:
|
||||
return min(8, max(1, int(_read_settings().get("maxConcurrentJobs") or 2)))
|
||||
except (TypeError, ValueError):
|
||||
return 2
|
||||
|
||||
|
||||
def store_task_limit(value: int) -> int:
|
||||
limit = min(8, max(1, int(value)))
|
||||
data = json.dumps({"maxConcurrentJobs": limit}, ensure_ascii=False, indent=2).encode("utf-8")
|
||||
try:
|
||||
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_atomic(SETTINGS_PATH, data)
|
||||
except OSError as exc:
|
||||
raise NqiError(explain_os_error(exc) or "设置保存失败,请稍后重试") from exc
|
||||
with _SETTINGS_LOCK:
|
||||
data = _read_settings()
|
||||
data["maxConcurrentJobs"] = limit
|
||||
try:
|
||||
_write_settings(data)
|
||||
except OSError as exc:
|
||||
raise NqiError(explain_os_error(exc) or "设置保存失败,请稍后重试") from exc
|
||||
return limit
|
||||
|
||||
|
||||
def app_settings() -> dict:
|
||||
"""未写过的项用默认值:显示托盘,关闭窗口时留在托盘。"""
|
||||
with _SETTINGS_LOCK:
|
||||
data = _read_settings()
|
||||
return {
|
||||
"showTray": data.get("showTray") is not False,
|
||||
"closeToTray": data.get("closeToTray") is not False,
|
||||
}
|
||||
|
||||
|
||||
def store_app_settings(show_tray: bool, close_to_tray: bool) -> dict:
|
||||
with _SETTINGS_LOCK:
|
||||
data = _read_settings()
|
||||
data["showTray"] = bool(show_tray)
|
||||
data["closeToTray"] = bool(close_to_tray)
|
||||
try:
|
||||
_write_settings(data)
|
||||
except OSError as exc:
|
||||
raise NqiError(explain_os_error(exc) or "设置保存失败,请稍后重试") from exc
|
||||
return app_settings()
|
||||
|
||||
|
||||
class JobManager:
|
||||
def __init__(self) -> None:
|
||||
self.jobs: dict[str, DownloadJob] = {}
|
||||
|
||||
@@ -14,7 +14,7 @@ from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile
|
||||
|
||||
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
|
||||
from app.features.download.ids import parse_upload
|
||||
from app.features.download.jobs import _write_ids, ensure_output_dir, run_download
|
||||
from app.features.download.jobs import _write_ids, app_settings, ensure_output_dir, run_download, store_app_settings
|
||||
from app.features.download.journal import explain_os_error
|
||||
from app.platform.client import NqiError
|
||||
from app.platform.constants import CITIES
|
||||
@@ -62,6 +62,21 @@ def fill_slots() -> None:
|
||||
_spawn(waiting[0])
|
||||
|
||||
|
||||
@router.get("/settings/app")
|
||||
async def read_app_settings() -> dict:
|
||||
return app_settings()
|
||||
|
||||
|
||||
@router.put("/settings/app")
|
||||
async def write_app_settings(body: Any = Body(default=None)) -> dict:
|
||||
if not isinstance(body, dict):
|
||||
raise _bad("参数格式不正确")
|
||||
try:
|
||||
return store_app_settings(bool(body.get("showTray")), bool(body.get("closeToTray")))
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/meta")
|
||||
async def meta() -> dict:
|
||||
return {
|
||||
|
||||
@@ -10,7 +10,7 @@ import uuid
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from app.platform.client import NqiError, needs_captcha
|
||||
from app.platform.sessions import available_accounts, remember_account, resume
|
||||
from app.platform.sessions import available_accounts, clear_accounts, forget_account, list_local_accounts, remember_account, resume
|
||||
from app.shared.state import state
|
||||
|
||||
logger = logging.getLogger("nqi.auth")
|
||||
@@ -166,6 +166,29 @@ async def saved() -> dict:
|
||||
return {"accounts": await available_accounts()}
|
||||
|
||||
|
||||
@router.get("/accounts")
|
||||
async def accounts() -> dict:
|
||||
state.require_client()
|
||||
return {"accounts": list_local_accounts()}
|
||||
|
||||
|
||||
@router.delete("/accounts/{login_id}")
|
||||
async def remove_account(login_id: str) -> dict:
|
||||
state.require_client()
|
||||
await forget_account(login_id)
|
||||
return {"accounts": list_local_accounts()}
|
||||
|
||||
|
||||
@router.delete("/accounts")
|
||||
async def remove_accounts() -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
await clear_accounts()
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
return {"accounts": []}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume_saved(body: dict) -> dict:
|
||||
login_id = str(body.get("loginId") or "").strip()
|
||||
|
||||
@@ -83,6 +83,20 @@ async def forget_account(login_id: str) -> None:
|
||||
logger.warning("登录记录暂时写不进去: %s", exc)
|
||||
|
||||
|
||||
def list_local_accounts() -> list[dict]:
|
||||
"""本机保存的账号,不访问平台。"""
|
||||
return [public_view(item) for item in _read()]
|
||||
|
||||
|
||||
async def clear_accounts() -> None:
|
||||
async with _write_lock:
|
||||
try:
|
||||
_write([])
|
||||
except OSError as exc:
|
||||
logger.warning("登录记录暂时写不进去: %s", exc)
|
||||
raise NqiError("登录记录暂时无法清除") from exc
|
||||
|
||||
|
||||
def public_view(item: dict) -> dict:
|
||||
return {
|
||||
"loginId": item.get("loginId") or "",
|
||||
|
||||
Reference in New Issue
Block a user