-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathsetup.py
More file actions
343 lines (292 loc) · 11.4 KB
/
setup.py
File metadata and controls
343 lines (292 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import ipaddress
import logging
import socket
from pathlib import Path
from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from module.conf import VERSION, settings
from module.models import Config, ResponseModel
from module.models.config import NotificationProvider as ProviderConfig
from module.network import RequestContent
from module.notification import PROVIDER_REGISTRY
from module.security.jwt import get_password_hash
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/setup", tags=["setup"])
SENTINEL_PATH = Path("config/.setup_complete")
def _require_setup_needed():
"""Guard: raise 403 if setup is already completed."""
if SENTINEL_PATH.exists():
raise HTTPException(status_code=403, detail="Setup already completed.")
# Allow setup in dev mode even if settings differ
if VERSION != "DEV_VERSION" and settings.dict() != Config().dict():
raise HTTPException(status_code=403, detail="Setup already completed.")
def _validate_url(url: str) -> None:
"""Reject non-HTTP schemes and private/reserved/loopback IPs."""
parsed = urlparse(url)
if parsed.scheme not in ("http", "https"):
raise HTTPException(status_code=400, detail="Only http/https URLs are allowed.")
hostname = parsed.hostname
if not hostname:
raise HTTPException(status_code=400, detail="Invalid URL: no hostname.")
try:
addrs = socket.getaddrinfo(hostname, None)
except socket.gaierror:
raise HTTPException(status_code=400, detail="Cannot resolve hostname.")
for family, _, _, _, sockaddr in addrs:
ip = ipaddress.ip_address(sockaddr[0])
if ip.is_private or ip.is_reserved or ip.is_loopback:
raise HTTPException(
status_code=400,
detail="URLs pointing to private/reserved IPs are not allowed.",
)
# --- Request/Response Models ---
class SetupStatusResponse(BaseModel):
need_setup: bool
version: str
class TestDownloaderRequest(BaseModel):
type: str = Field("qbittorrent")
host: str
username: str
password: str
ssl: bool = False
class TestRSSRequest(BaseModel):
url: str
class TestNotificationRequest(BaseModel):
type: str
token: str
chat_id: str = ""
class TestResultResponse(BaseModel):
success: bool
message_en: str
message_zh: str
title: str | None = None
item_count: int | None = None
class SetupCompleteRequest(BaseModel):
username: str = Field(..., min_length=4, max_length=20)
password: str = Field(..., min_length=8)
downloader_type: str = Field("qbittorrent")
downloader_host: str
downloader_username: str
downloader_password: str
downloader_path: str = Field("/downloads/Bangumi")
downloader_ssl: bool = False
rss_url: str = ""
rss_name: str = ""
notification_enable: bool = False
notification_type: str = "telegram"
notification_token: str = ""
notification_chat_id: str = ""
# --- Endpoints ---
@router.get("/status", response_model=SetupStatusResponse)
async def get_setup_status():
"""Check whether the setup wizard is needed."""
# In dev mode, always allow setup wizard for testing
if VERSION == "DEV_VERSION":
need_setup = not SENTINEL_PATH.exists()
else:
need_setup = not SENTINEL_PATH.exists() and settings.dict() == Config().dict()
return SetupStatusResponse(need_setup=need_setup, version=VERSION)
@router.post("/test-downloader", response_model=TestResultResponse)
async def test_downloader(req: TestDownloaderRequest):
"""Test connection to the download client."""
_require_setup_needed()
# Support mock mode for development
if req.type == "mock":
return TestResultResponse(
success=True,
message_en="Mock downloader enabled.",
message_zh="已启用模拟下载器。",
)
scheme = "https" if req.ssl else "http"
host = req.host if "://" in req.host else f"{scheme}://{req.host}"
try:
async with httpx.AsyncClient(timeout=5.0) as client:
# Check if host is reachable and is qBittorrent
resp = await client.get(host)
if (
"qbittorrent" not in resp.text.lower()
and "vuetorrent" not in resp.text.lower()
):
return TestResultResponse(
success=False,
message_en="Host is reachable but does not appear to be qBittorrent.",
message_zh="主机可达但似乎不是 qBittorrent。",
)
# Try to authenticate
login_url = f"{host}/api/v2/auth/login"
login_resp = await client.post(
login_url,
data={"username": req.username, "password": req.password},
)
if login_resp.status_code == 200 and "ok" in login_resp.text.lower():
return TestResultResponse(
success=True,
message_en="Connection successful.",
message_zh="连接成功。",
)
elif login_resp.status_code == 403:
return TestResultResponse(
success=False,
message_en="Authentication failed: IP is banned by qBittorrent.",
message_zh="认证失败:IP 被 qBittorrent 封禁。",
)
else:
return TestResultResponse(
success=False,
message_en="Authentication failed: incorrect username or password.",
message_zh="认证失败:用户名或密码错误。",
)
except httpx.TimeoutException:
return TestResultResponse(
success=False,
message_en="Connection timed out.",
message_zh="连接超时。",
)
except httpx.ConnectError:
return TestResultResponse(
success=False,
message_en="Cannot connect to the host.",
message_zh="无法连接到主机。",
)
except Exception as e:
logger.error(f"[Setup] Downloader test failed: {e}")
return TestResultResponse(
success=False,
message_en=f"Connection failed: {e}",
message_zh=f"连接失败:{e}",
)
@router.post("/test-rss", response_model=TestResultResponse)
async def test_rss(req: TestRSSRequest):
"""Test an RSS feed URL."""
_require_setup_needed()
_validate_url(req.url)
try:
async with RequestContent() as request:
soup = await request.get_xml(req.url)
if soup is None:
return TestResultResponse(
success=False,
message_en="Failed to fetch or parse the RSS feed.",
message_zh="无法获取或解析 RSS 源。",
)
title = soup.find("./channel/title")
title_text = title.text if title is not None else None
items = soup.findall("./channel/item")
return TestResultResponse(
success=True,
message_en="RSS feed is valid.",
message_zh="RSS 源有效。",
title=title_text,
item_count=len(items),
)
except Exception as e:
logger.error(f"[Setup] RSS test failed: {e}")
return TestResultResponse(
success=False,
message_en=f"Failed to fetch RSS feed: {e}",
message_zh=f"获取 RSS 源失败:{e}",
)
@router.post("/test-notification", response_model=TestResultResponse)
async def test_notification(req: TestNotificationRequest):
"""Send a test notification."""
_require_setup_needed()
provider_cls = PROVIDER_REGISTRY.get(req.type.lower())
if provider_cls is None:
return TestResultResponse(
success=False,
message_en=f"Unknown notification type: {req.type}",
message_zh=f"未知的通知类型:{req.type}",
)
try:
# Create provider config
config = ProviderConfig(
type=req.type,
enabled=True,
token=req.token,
chat_id=req.chat_id,
)
provider = provider_cls(config)
async with provider:
success, message = await provider.test()
if success:
return TestResultResponse(
success=True,
message_en="Test notification sent successfully.",
message_zh="测试通知发送成功。",
)
else:
return TestResultResponse(
success=False,
message_en=f"Failed to send test notification: {message}",
message_zh=f"测试通知发送失败:{message}",
)
except Exception as e:
logger.error(f"[Setup] Notification test failed: {e}")
return TestResultResponse(
success=False,
message_en=f"Notification test failed: {e}",
message_zh=f"通知测试失败:{e}",
)
@router.post("/complete", response_model=ResponseModel)
async def complete_setup(req: SetupCompleteRequest):
"""Save all wizard configuration and mark setup as complete."""
_require_setup_needed()
try:
# 1. Update user credentials
from module.database import Database
with Database() as db:
from module.models.user import UserUpdate
db.user.update_user(
"admin",
UserUpdate(username=req.username, password=req.password),
)
# 2. Update configuration
config_dict = settings.dict()
config_dict["downloader"] = {
"type": req.downloader_type,
"host": req.downloader_host,
"username": req.downloader_username,
"password": req.downloader_password,
"path": req.downloader_path,
"ssl": req.downloader_ssl,
}
if req.notification_enable:
config_dict["notification"] = {
"enable": True,
"providers": [
{
"type": req.notification_type,
"enabled": True,
"token": req.notification_token,
"chat_id": req.notification_chat_id,
}
],
}
settings.save(config_dict)
# Reload settings in-place
config_obj = Config.parse_obj(config_dict)
settings.__dict__.update(config_obj.__dict__)
# 3. Add RSS feed if provided
if req.rss_url:
from module.rss import RSSEngine
with RSSEngine() as rss_engine:
await rss_engine.add_rss(req.rss_url, name=req.rss_name or None)
# 4. Create sentinel file
SENTINEL_PATH.parent.mkdir(parents=True, exist_ok=True)
SENTINEL_PATH.touch()
return ResponseModel(
status=True,
status_code=200,
msg_en="Setup completed successfully.",
msg_zh="设置完成。",
)
except Exception as e:
logger.error(f"[Setup] Complete failed: {e}")
return ResponseModel(
status=False,
status_code=500,
msg_en=f"Setup failed: {e}",
msg_zh=f"设置失败:{e}",
)