Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ git_cache/
backup_state.json
logs.jsonl

# Downloaded mihomo kernel binary (subscription sync script)
scripts/.bin/

# Generated web assets
web/.next/
web/out/
Expand Down
13 changes: 13 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ RUN apt-get update && apt-get install -y --no-install-recommends \

RUN pip install --no-cache-dir uv

# mihomo 代理内核(订阅代理池用,固定 v1.19.27 与开发环境一致)
RUN case "$TARGETARCH" in \
amd64) _ARCH="linux-amd64-compatible" ;; \
arm64) _ARCH="linux-arm64" ;; \
*) echo "unsupported arch: $TARGETARCH" && exit 1 ;; \
esac && \
_VER="v1.19.27" && \
mkdir -p /app/scripts/.bin && \
curl -fsSL "https://github.com/MetaCubeX/mihomo/releases/download/${_VER}/mihomo-${_ARCH}-${_VER}.gz" -o /tmp/mihomo.gz && \
python3 -c "import gzip,shutil; shutil.copyfileobj(gzip.open('/tmp/mihomo.gz','rb'), open('/app/scripts/.bin/mihomo','wb'))" && \
chmod +x /app/scripts/.bin/mihomo && \
rm -f /tmp/mihomo.gz

COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project

Expand Down
10 changes: 10 additions & 0 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from api.support import resolve_web_asset, start_limited_account_watcher, web_index_asset
from services.backup_service import backup_service
from services.config import config
from services.mihomo_manager import mihomo_manager
from services.proxy_health_service import proxy_health_service


def serve_web_asset(full_path: str):
Expand All @@ -35,12 +37,20 @@ async def lifespan(_: FastAPI):
thread = start_limited_account_watcher(stop_event)
backup_service.start()
config.cleanup_old_images()
# mihomo 常驻代理内核(启动失败不拖垮主服务,订阅代理功能降级)
try:
mihomo_manager.start()
except Exception as e: # noqa: BLE001
print(f"[lifespan] mihomo 启动失败,订阅代理功能降级: {e}", flush=True)
proxy_health_service.start()
try:
yield
finally:
stop_event.set()
thread.join(timeout=1)
backup_service.stop()
proxy_health_service.stop()
mihomo_manager.stop()

app = FastAPI(title="webchat2api", version=app_version, lifespan=lifespan)
install_exception_handlers(app)
Expand Down
88 changes: 88 additions & 0 deletions api/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
from services.image_storage_service import ImageStorageError, image_storage_service
from services.image_tags_service import delete_tag, get_all_tags, set_tags
from services.log_service import log_service
from services.proxy_health_service import proxy_health_service
from services.proxy_pool_service import proxy_pool_service
from services.proxy_service import test_proxy


Expand Down Expand Up @@ -43,6 +45,20 @@ class LogDeleteRequest(BaseModel):
class BackupDeleteRequest(BaseModel):
key: str = ""

class ProxyPoolImportRequest(BaseModel):
proxies: str = ""

class ProxyPoolDeleteRequest(BaseModel):
ids: list[str] = []

class ProxyPoolSubscriptionRequest(BaseModel):
name: str = ""
url: str = ""
region_keywords: str = ""

class ProxyPoolSyncRequest(BaseModel):
subscription_id: str | None = None


def create_router(app_version: str) -> APIRouter:
router = APIRouter()
Expand Down Expand Up @@ -233,4 +249,76 @@ async def delete_image_tag(tag: str, authorization: str | None = Header(default=
count = delete_tag(tag)
return {"ok": True, "removed_from": count}

@router.get("/api/proxy-pool")
async def list_proxy_pool(authorization: str | None = Header(default=None)):
require_admin(authorization)
return {"items": proxy_pool_service.list_items()}

@router.post("/api/proxy-pool")
async def import_proxy_pool(body: ProxyPoolImportRequest, authorization: str | None = Header(default=None)):
require_admin(authorization)
text = (body.proxies or "").strip()
if not text:
raise HTTPException(status_code=400, detail={"error": "proxies is required"})
result = proxy_pool_service.import_proxies(text)
return {**result, "items": proxy_pool_service.list_items()}

@router.delete("/api/proxy-pool")
async def delete_proxy_pool(body: ProxyPoolDeleteRequest, authorization: str | None = Header(default=None)):
require_admin(authorization)
if not body.ids:
result = proxy_pool_service.clear_all()
else:
result = proxy_pool_service.delete_proxies(body.ids)
return {**result, "items": proxy_pool_service.list_items()}

@router.post("/api/proxy-pool/assign")
async def assign_proxy_pool(authorization: str | None = Header(default=None)):
require_admin(authorization)
return await run_in_threadpool(proxy_pool_service.assign_to_accounts)

@router.post("/api/proxy-pool/clear")
async def clear_proxy_pool_assignments(authorization: str | None = Header(default=None)):
require_admin(authorization)
return await run_in_threadpool(proxy_pool_service.clear_assignments)

# ── 订阅源管理 ──
@router.get("/api/proxy-pool/subscriptions")
async def list_subscriptions(authorization: str | None = Header(default=None)):
require_admin(authorization)
return {"items": proxy_health_service.list_subscriptions()}

@router.post("/api/proxy-pool/subscriptions")
async def add_subscription(body: ProxyPoolSubscriptionRequest, authorization: str | None = Header(default=None)):
require_admin(authorization)
if not body.url.strip():
raise HTTPException(status_code=400, detail={"error": "url is required"})
sub = await run_in_threadpool(
proxy_health_service.add_subscription, body.name, body.url, body.region_keywords
)
return {"item": sub, "items": proxy_health_service.list_subscriptions()}

@router.delete("/api/proxy-pool/subscriptions/{sub_id}")
async def delete_subscription(sub_id: str, authorization: str | None = Header(default=None)):
require_admin(authorization)
result = await run_in_threadpool(proxy_health_service.delete_subscription, sub_id)
return {**result, "items": proxy_health_service.list_subscriptions()}

# ── 同步(异步 task,前端轮询 sync/{task_id}) ──
@router.post("/api/proxy-pool/sync")
async def sync_proxy_pool(body: ProxyPoolSyncRequest, authorization: str | None = Header(default=None)):
require_admin(authorization)
return proxy_health_service.run_sync_now(body.subscription_id)

@router.get("/api/proxy-pool/sync/{task_id}")
async def get_sync_status(task_id: str, authorization: str | None = Header(default=None)):
require_admin(authorization)
return proxy_health_service.get_task_status(task_id)

# ── 健康视图(pool item 带 health/latency 字段) ──
@router.get("/api/proxy-pool/health")
async def proxy_pool_health(authorization: str | None = Header(default=None)):
require_admin(authorization)
return {"items": proxy_pool_service.list_items()}

return router
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ services:
# - ./config.json:/app/config.json
environment:
LOGIN_SECRET: admin
STORAGE_BACKEND: json
STORAGE_BACKEND: sqlite
# 如需访问宿主机代理,可同时取消下一行和 extra_hosts 的注释。
# PROXY_URL: http://host.docker.internal:7890
# WEBCHAT2API_BASE_URL: https://your-domain.com
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ dependencies = [
"sqlalchemy>=2.0.0",
"psycopg2-binary>=2.9.0",
"gitpython>=3.1.0",
"pyyaml>=6.0.3",
]

[dependency-groups]
Expand Down
Loading
Loading