-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathdev_server.py
More file actions
3900 lines (3477 loc) · 147 KB
/
Copy pathdev_server.py
File metadata and controls
3900 lines (3477 loc) · 147 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from contextlib import asynccontextmanager
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
import importlib.metadata
import json
from pathlib import Path
import platform
import re
import socket
import subprocess
import sys
import tempfile
from threading import Lock
from typing import Any
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from pydantic import model_validator
from ruamel.yaml import YAML
import uvicorn
from src.app.main_orchestrator import (
ApplicationRuntime,
build_application_runtime,
create_capture_task_manager,
load_application_runtime,
)
from src.config.config_loader import build_app_config, load_config_mapping
from src.domain.enums import TaskStatus
from src.domain.models import TaskCommand
from src.modules.window.article_date_filter import ArticleDateFilter
from src.modules.processes.process_launcher import set_process_observer
from src.modules.proxy.capture_buffer import CaptureBuffer
from src.modules.proxy.mitmproxy_listener import MitmproxyListener, MitmproxyListenerError
from src.modules.proxy.proxy_state import ProxySnapshot, proxy_points_to
from src.modules.request.chrome_headers import build_chrome_document_headers
from src.modules.system.windows_system_proxy import WindowsSystemProxy
from src.services.archive.archive_delete_service import ArchiveDeleteService
from src.services.archive.archive_excel_export_service import ArchiveExcelExportService
from src.services.archive.offline_cache_job_service import (
OfflineCacheConflictError,
OfflineCacheJobService,
)
from src.services.capture.capture_runtime_factory import CaptureRuntimeFactory
from src.services.capture.window_runtime_factory import WindowRuntimeFactory
from src.services.history.history_query_service import HistoryQueryService
from src.services.history.history_clear_service import HistoryClearService
from src.services.main_flow.main_flow_models import MainFlowCommand
from src.services.main_flow.main_flow_factory import build_main_flow_service
from src.services.main_flow.main_flow_service import (
MainFlowConflictError,
MainFlowService,
)
from src.services.runtime.database_init_service import DatabaseInitService
from src.services.runtime.article_card_probe_service import ArticleCardProbeService
from src.services.runtime.runtime_cache_clear_service import RuntimeCacheClearService
from src.services.runtime.runtime_directory_service import RuntimeDirectoryService
from src.services.runtime.runtime_log_service import RuntimeLogService
from src.services.runtime.startup_self_check_service import StartupSelfCheckService
from src.services.runtime.process_tree_resource_monitor import ProcessTreeResourceMonitor
from src.services.runtime.task_runtime_state import TaskRuntimeTracker
from src.services.runtime.window_diagnostic_service import (
WINDOW_DIAGNOSTIC_ACTIONS,
WindowDiagnosticService,
)
from src.services.task.window_click_flow_huey_service import (
WindowClickFlowConflictError,
WindowClickFlowHueyService,
)
from src.services.task.single_article_detail_huey_service import (
SingleArticleDetailHueyService,
)
from src.services.task.initial_content_storage_huey_service import (
InitialContentStorageHueyService,
)
from src.services.task.article_detail_comments_huey_service import (
ArticleDetailCommentsHueyService,
)
from src.services.task.article_detail_offline_cache_huey_service import (
ArticleDetailOfflineCacheHueyService,
)
from src.services.task.huey_runtime_queue import reset_runtime_huey_queue_dir
from src.services.task.task_manager import TaskConflictError
from src.storage.sqlite.connection import sqlite_connection
DEFAULT_API_HOST = "127.0.0.1"
DEFAULT_API_PORT = 8766
DEFAULT_TRAVERSE_ALL_MAX_ATTEMPTS = 1000
WEBVIEW_DIR = Path(__file__).resolve().parent / "src" / "webview"
@dataclass(slots=True)
class DevBackendContext:
"""开发期后端共享上下文,只保存入口层需要的运行时对象。"""
project_root: Path
runtime: ApplicationRuntime | Any
db_path: Path
task_manager: Any
main_flow_service: MainFlowService | Any | None = None
runtime_logger: RuntimeLogService | Any | None = None
system_resource_monitor: Any | None = None
started_at: datetime = field(default_factory=datetime.now)
active_task_id: str | None = None
logs: list[dict[str, Any]] = field(default_factory=list)
config_mapping: dict[str, Any] | None = None
directory_selector: Any | None = None
command_runner: Any | None = None
proxy_tester: Any | None = None
system_proxy: Any | None = None
port_checker: Any | None = None
mitm_listener_factory: Any | None = None
window_diagnostic_runner: Any | None = None
window_click_flow_huey_service: Any | None = None
article_detail_card_probe_service: Any | None = None
article_detail_huey_service: Any | None = None
main_flow_foreground_huey_service: Any | None = None
main_flow_detail_huey_service: Any | None = None
diagnostic_mitm_listener: Any | None = None
diagnostic_mitm_started_at: float = 0.0
diagnostic_system_proxy_snapshot: ProxySnapshot | None = None
initial_content_storage_huey_service: Any | None = None
article_detail_comments_huey_service: Any | None = None
article_detail_offline_cache_huey_service: Any | None = None
health_check_results: dict[str, dict[str, Any]] = field(default_factory=dict)
health_startup_completed: bool = False
health_check_lock: Any = field(default_factory=Lock, repr=False)
startup_self_check_lock: Any = field(default_factory=Lock, repr=False)
offline_cache_service: Any | None = None
def append_log(
self,
level: str,
message: str,
source: str = "dev_server",
*,
summary: bool = False,
channel: str | None = None,
phase: str | None = None,
task_index: int | str | None = None,
article_task_id: str | None = None,
article_title: str | None = None,
context: dict[str, Any] | None = None,
exception: BaseException | None = None,
) -> None:
if self.runtime_logger is not None:
if str(level).upper() == "ERROR":
self.runtime_logger.write_error(
message,
source=source,
channel=channel,
phase=phase,
task_index=task_index,
article_task_id=article_task_id,
article_title=article_title,
context=context,
exception=exception,
summary=summary,
)
elif summary:
self.runtime_logger.write_summary(
level,
message,
source=source,
channel=channel,
phase=phase,
task_index=task_index,
article_task_id=article_task_id,
article_title=article_title,
context=context,
)
else:
self.runtime_logger.write_detail(
level,
message,
source=source,
channel=channel,
phase=phase,
task_index=task_index,
article_task_id=article_task_id,
article_title=article_title,
context=context,
exception=exception,
)
return
if summary:
self.logs.append(
{
"level": level.upper(),
"message": message,
"source": source,
"createdAt": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"channel": channel or "system",
"phase": phase or "",
"taskIndex": task_index or "",
"articleTaskId": article_task_id or "",
"articleTitle": article_title or "",
}
)
del self.logs[:-100]
def recent_summary_logs(self, limit: int = 100) -> list[dict[str, Any]]:
if self.runtime_logger is not None:
return self.runtime_logger.recent_summary(limit)
safe_limit = max(1, min(int(limit), 100))
return [dict(item) for item in self.logs[-safe_limit:]]
class RuntimePathOpenPayload(BaseModel):
key: str
class RuntimeDirectorySelectPayload(BaseModel):
configKey: str
currentPath: str | None = None
class ArchiveArticleOpenDirectoryPayload(BaseModel):
articleId: int
class ArchiveDeleteArticlesPayload(BaseModel):
articleIds: list[int]
class ArchiveExcelExportPayload(BaseModel):
accountIds: list[int]
class ArchiveCacheArticlesPayload(BaseModel):
articleIds: list[int]
class UnsupportedPayload(BaseModel):
"""占位请求体,避免前端 POST 空对象时触发 422。"""
class HealthCheckPayload(BaseModel):
target: str
class WindowDiagnosticPayload(BaseModel):
action: str
# 仅覆盖本次“滚动页面”诊断,不写回运行配置或 YAML。
scrollSteps: int | None = Field(default=None, ge=1, le=200)
@model_validator(mode="after")
def validate_scroll_steps(self) -> WindowDiagnosticPayload:
if self.action.strip() == "scroll-page" and self.scrollSteps is None:
raise ValueError("滚动页面诊断必须提供滚动步长")
return self
class WindowClickFlowDiagnosticPayload(BaseModel):
"""窗口点击流程诊断条件;数量为零表示由日期边界结束。"""
maxRecords: int = 20
dateFilterMode: str = "all"
startDate: str | None = None
endDate: str | None = None
@model_validator(mode="after")
def validate_options(self) -> WindowClickFlowDiagnosticPayload:
date_filter = ArticleDateFilter.create(
mode=self.dateFilterMode,
start_date=self.startDate,
end_date=self.endDate,
)
self.dateFilterMode = date_filter.mode
self.startDate = date_filter.start_date.isoformat() if date_filter.start_date else None
self.endDate = date_filter.end_date.isoformat() if date_filter.end_date else None
# 范围和截止模式由日期边界停止;其他模式最多读取 20 条。
self.maxRecords = (
0
if date_filter.mode in {"range", "before"}
else max(1, min(int(self.maxRecords), 20))
)
return self
class ArticleDetailDiagnosticPayload(BaseModel):
"""单篇详情诊断输入;当前前端只传跳过已采集记录开关。"""
cardIndex: int = Field(default=1, ge=1)
accountName: str | None = None
card: dict[str, Any] | None = None
skipCollectedRecords: bool = False
class InitialContentStorageDiagnosticPayload(BaseModel):
"""初始内容存储诊断输入;文章详情存储是该流程的锁定动作。"""
skipCollectedRecords: bool = False
storeArticleDetail: bool = True
@model_validator(mode="after")
def lock_store_article_detail(self) -> InitialContentStorageDiagnosticPayload:
# 前端显示为锁定勾选;后端也强制为 True,避免被手动请求绕过。
self.storeArticleDetail = True
return self
class ArticleDetailCommentsDiagnosticPayload(BaseModel):
"""评论信息存储诊断输入;文章详情和评论信息都是锁定动作。"""
skipCollectedRecords: bool = False
storeArticleDetail: bool = True
storeCommentInfo: bool = True
@model_validator(mode="after")
def lock_store_options(self) -> ArticleDetailCommentsDiagnosticPayload:
# 前端两个存储项显示为锁定勾选;后端也强制开启,避免手动请求绕过流程。
self.storeArticleDetail = True
self.storeCommentInfo = True
return self
class ArticleDetailOfflineCacheDiagnosticPayload(BaseModel):
"""离线缓存诊断输入;文章详情和离线归档内容都是锁定动作。"""
skipCollectedRecords: bool = False
storeArticleDetail: bool = True
archiveOfflineContent: bool = True
statefulOfflineCache: bool = False
@model_validator(mode="after")
def lock_store_options(self) -> ArticleDetailOfflineCacheDiagnosticPayload:
# 前端两个存储项显示为锁定勾选;带状态是可选实验项,不在这里锁定。
self.storeArticleDetail = True
self.archiveOfflineContent = True
return self
def create_dev_backend(
*,
project_root: str | Path | None = None,
config_path: str | Path | None = None,
) -> DevBackendContext:
"""按新结构装配开发期 FastAPI 后端,并在启动阶段初始化数据库。"""
root = Path(project_root or Path(__file__).resolve().parent).resolve()
runtime = load_application_runtime(project_root=root, config_path=config_path)
RuntimeDirectoryService().prepare(runtime.config)
db_path = DatabaseInitService(project_root=root).initialize(runtime.config)
runtime_logger = RuntimeLogService(
log_dir=runtime.config.storage.log_dir,
level=runtime.config.runtime.log_level,
redactions={str(db_path): db_path.name},
)
# Huey 的 SQLite 队列只保存当前进程运行态任务,启动时清理旧队列,
# 并放在 data/runtime/huey,避免被“清理缓存”误删 data/tmp 时破坏。
reset_runtime_huey_queue_dir(runtime.config.storage.temp_dir)
# 诊断工具和主服务使用独立的详情队列;两者仍通过服务内部的进程级
# foreground lease 互斥接管主页和全局代理。
initial_content_service = InitialContentStorageHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
worker_count=1,
)
main_flow_foreground_service = InitialContentStorageHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
write_coordinator=runtime.database_write_coordinator,
worker_count=1,
job_prefix="main-flow-foreground",
queue_name="main-flow-foreground",
task_name="MainFlowForegroundTask",
action="main-flow-foreground",
title="主服务单篇前台结果",
flow_label="主服务单篇前台捕获",
)
main_flow_detail_service = InitialContentStorageHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
write_coordinator=runtime.database_write_coordinator,
worker_count=2,
job_prefix="main-flow-detail",
queue_name="main-flow-detail",
task_name="MainFlowDetailTask",
action="main-flow-detail",
title="主服务单篇详情结果",
flow_label="主服务单篇详情",
)
# 主服务和诊断工具使用不同的 Huey 队列;两套 service 可以共享运行时
# DatabaseWriteCoordinator,但不能共享队列、任务记录或关闭生命周期。
main_flow_comments_service = ArticleDetailCommentsHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
write_coordinator=runtime.database_write_coordinator,
worker_count=runtime.config.comment.max_concurrent_processes,
)
main_flow_offline_service = ArticleDetailOfflineCacheHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
browser_cache_dir=root / ".playwright-browsers",
write_coordinator=runtime.database_write_coordinator,
worker_count=runtime.config.offline_cache.max_concurrent_processes,
)
diagnostic_comments_service = ArticleDetailCommentsHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
write_coordinator=runtime.database_write_coordinator,
worker_count=1,
)
diagnostic_offline_service = ArticleDetailOfflineCacheHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
browser_cache_dir=root / ".playwright-browsers",
write_coordinator=runtime.database_write_coordinator,
worker_count=1,
)
main_flow_service, _main_flow_dispatcher = build_main_flow_service(
project_root=root,
config=runtime.config,
db_path=db_path,
storage_root=runtime.config.storage.article_storage_root,
temp_root=runtime.config.storage.temp_dir,
window_factory=runtime.window_factory,
foreground_service=main_flow_foreground_service,
detail_service=main_flow_detail_service,
comments_service=main_flow_comments_service,
offline_service=main_flow_offline_service,
runtime_logger=runtime_logger,
)
# 运行状态区只展示当前软件进程树的资源占用;后台独立采样,前端读取时不再临时扫整机。
resource_monitor = ProcessTreeResourceMonitor(
history_sample_count=120,
sample_interval_seconds=0.5,
)
set_process_observer(resource_monitor)
resource_monitor.start()
backend = DevBackendContext(
project_root=root,
runtime=runtime,
db_path=db_path,
task_manager=create_capture_task_manager(
runtime=runtime,
db_path=db_path,
runtime_logger=runtime_logger,
),
main_flow_service=main_flow_service,
runtime_logger=runtime_logger,
system_resource_monitor=resource_monitor,
window_click_flow_huey_service=WindowClickFlowHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
),
article_detail_card_probe_service=ArticleCardProbeService(
config=runtime.config,
window_factory=runtime.window_factory,
),
article_detail_huey_service=SingleArticleDetailHueyService(
temp_root=runtime.config.storage.temp_dir,
config=runtime.config,
window_factory=runtime.window_factory,
capture_factory=runtime.capture_factory,
database_path=db_path,
),
main_flow_foreground_huey_service=main_flow_foreground_service,
main_flow_detail_huey_service=main_flow_detail_service,
initial_content_storage_huey_service=initial_content_service,
article_detail_comments_huey_service=diagnostic_comments_service,
article_detail_offline_cache_huey_service=diagnostic_offline_service,
offline_cache_service=OfflineCacheJobService(
database_path=db_path,
storage_root=runtime.config.storage.article_storage_root,
temp_root=runtime.config.storage.temp_dir,
browser_cache_dir=root / ".playwright-browsers",
max_concurrent_processes=runtime.config.offline_cache.max_concurrent_processes,
max_scroll_seconds=runtime.config.offline_cache.max_scroll_seconds,
resource_timeout_seconds=runtime.config.offline_cache.resource_timeout_seconds,
write_coordinator=runtime.database_write_coordinator,
),
)
backend.append_log(
"INFO",
f"程序已就绪,数据库:{db_path.name}",
source="startup",
summary=True,
channel="system",
phase="startup",
)
return backend
def create_backend_app(backend: DevBackendContext) -> FastAPI:
"""创建开发期 FastAPI 应用;业务路由只调用 Service / TaskManager。"""
@asynccontextmanager
async def lifespan(_app: FastAPI):
try:
yield
finally:
shutdown_backend(backend)
app = FastAPI(
title="Access WeChat Article Dev API",
version=str(backend.runtime.config.software.version),
lifespan=lifespan,
)
app.state.backend = backend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.exception_handler(Exception)
async def handle_unexpected_error(_request: Request, exc: Exception):
backend.append_log(
"ERROR",
f"程序运行异常:{type(exc).__name__}: {exc}",
source="api",
summary=True,
exception=exc,
)
return JSONResponse(
{
"ok": False,
"status": "error",
"message": f"{type(exc).__name__}: {exc}",
},
status_code=500,
)
@app.get("/api/status")
def get_status() -> dict[str, Any]:
return {
"ok": True,
"status": "ready",
"webviewExists": False,
"serverTime": datetime.now().isoformat(timespec="seconds"),
"environment": _environment_payload(backend.runtime.config),
**_runtime_status_fields(backend),
}
@app.post("/api/health/startup")
def run_startup_health_checks(_payload: UnsupportedPayload | None = None) -> dict[str, Any]:
return _startup_health_payload(backend)
@app.get("/api/startup-self-check/status")
def get_startup_self_check_status() -> dict[str, Any]:
return _startup_self_check_status_payload(backend)
@app.post("/api/startup-self-check/run")
def run_startup_self_check(_payload: UnsupportedPayload | None = None) -> dict[str, Any]:
return _startup_self_check_run_payload(backend)
@app.post("/api/health/check")
def run_health_check(payload: HealthCheckPayload):
target = payload.target.strip().lower()
if target not in HEALTH_CHECK_TARGETS:
return JSONResponse(
{
"ok": False,
"status": "invalid-target",
"message": f"不支持的健康检测项:{payload.target}",
},
status_code=400,
)
result = _run_health_check(backend, target)
backend.health_check_results[target] = result
return result
@app.post("/api/task/start")
def start_task(payload: dict[str, Any] | None = None):
if backend.main_flow_service is not None:
try:
command = _main_flow_command_from_payload(
payload or {},
backend.runtime.config,
)
snapshot = backend.main_flow_service.start(command)
except MainFlowConflictError as exc:
return JSONResponse(
{
"ok": False,
"status": "conflict",
"message": str(exc),
"ownerTaskId": exc.owner_task_id,
},
status_code=409,
)
except Exception as exc:
backend.append_log(
"ERROR",
f"启动主流程失败:{exc}",
source="main-flow-api",
summary=True,
exception=exc,
)
return JSONResponse(
{"ok": False, "status": "failed", "message": str(exc)},
status_code=400,
)
backend.active_task_id = snapshot.task_id
return _main_flow_snapshot_payload(snapshot, backend)
try:
command = _task_command_from_payload(payload or {}, backend.runtime.config)
snapshot = backend.task_manager.start_capture(command)
except TaskConflictError as exc:
return JSONResponse(
{
"ok": False,
"status": "conflict",
"message": str(exc),
"ownerTaskId": exc.owner_task_id,
},
status_code=409,
)
except Exception as exc:
backend.append_log(
"ERROR",
f"启动采集任务失败:{exc}",
source="task-api",
summary=True,
exception=exc,
)
return JSONResponse(
{"ok": False, "status": "failed", "message": str(exc)},
status_code=400,
)
backend.active_task_id = snapshot.task_id
return _task_snapshot_payload(snapshot, backend)
@app.post("/api/task/stop")
def stop_task() -> dict[str, Any]:
if backend.main_flow_service is not None:
task_id = backend.active_task_id or backend.main_flow_service.active_task_id
if not task_id:
return _idle_task_payload(backend)
stopped = backend.main_flow_service.stop(task_id)
if not stopped:
backend.append_log(
"WARN",
"当前主流程已经结束,无法再次停止",
source="main-flow-api",
summary=True,
)
return _current_task_payload(backend)
task_id = backend.active_task_id
if not task_id:
return _idle_task_payload(backend)
cancelled = bool(backend.task_manager.cancel(task_id))
if not cancelled:
backend.append_log(
"WARN",
"当前任务已经结束,无法再次停止",
source="task-api",
summary=True,
)
return _current_task_payload(backend)
@app.get("/api/task/status")
def get_task_status() -> dict[str, Any]:
return _current_task_payload(backend)
@app.get("/api/runtime/hardware")
def get_runtime_hardware() -> dict[str, Any]:
return _hardware_status_payload(backend)
@app.get("/api/task/logs")
def get_task_logs(limit: int = 100) -> dict[str, Any]:
safe_limit = max(1, min(int(limit), 100))
return {"ok": True, "items": backend.recent_summary_logs(safe_limit)}
@app.get("/api/runtime/paths")
def get_runtime_paths() -> dict[str, Any]:
paths = _runtime_paths(backend)
return {
"ok": True,
"status": "ok",
"paths": {key: str(path) for key, path in paths.items()},
}
@app.post("/api/runtime/paths/open")
def open_runtime_path(payload: RuntimePathOpenPayload):
paths = _runtime_paths(backend)
path = paths.get(payload.key)
if path is None:
return JSONResponse(
{
"ok": False,
"status": "invalid-key",
"key": payload.key,
"message": "未知运行目录 key。",
},
status_code=400,
)
opened = _open_directory(path)
return {
"ok": opened,
"status": "opened" if opened else "open-failed",
"key": payload.key,
"path": str(path),
"message": "已打开目录。" if opened else "打开目录失败。",
}
@app.post("/api/runtime/paths/select-directory")
def select_runtime_directory(payload: RuntimeDirectorySelectPayload):
return _select_runtime_directory(
backend,
config_key=payload.configKey,
current_path=payload.currentPath,
)
@app.get("/api/archive/summary")
def get_archive_summary() -> dict[str, Any]:
return _archive_summary_payload(backend)
@app.get("/api/archive/accounts")
def list_archive_accounts() -> dict[str, Any]:
items = _archive_account_items(backend)
return {
"ok": True,
"status": "ok",
"items": items,
"total": len(items),
"dbPath": str(backend.db_path),
}
@app.get("/api/archive/accounts/{account_id}/articles")
def list_archive_account_articles(
account_id: int,
page: int = 1,
pageSize: int = 10,
) -> dict[str, Any]:
return _archive_account_articles_payload(backend, account_id, page, pageSize)
@app.post("/api/archive/articles/open-directory")
def open_archive_article_directory(payload: ArchiveArticleOpenDirectoryPayload):
return _open_archive_article_directory(backend, payload.articleId)
@app.delete("/api/archive/articles")
def delete_archive_articles(payload: ArchiveDeleteArticlesPayload):
return ArchiveDeleteService().delete_articles(
database_path=backend.db_path,
storage_root=backend.runtime.config.storage.article_storage_root,
article_ids=payload.articleIds,
)
@app.delete("/api/archive/accounts/{account_id}")
def delete_archive_account(account_id: int):
return ArchiveDeleteService().delete_account(
database_path=backend.db_path,
storage_root=backend.runtime.config.storage.article_storage_root,
account_id=account_id,
)
@app.delete("/api/archive")
def delete_archive_all():
return ArchiveDeleteService().delete_all(
database_path=backend.db_path,
storage_root=backend.runtime.config.storage.article_storage_root,
)
@app.post("/api/archive/export/accounts")
def export_archive_accounts(payload: ArchiveExcelExportPayload):
storage_root = backend.runtime.config.storage.article_storage_root
return ArchiveExcelExportService().export_accounts(
database_path=backend.db_path,
storage_root=storage_root,
account_ids=payload.accountIds,
target_dir=storage_root,
)
@app.get("/api/history/records")
def list_history_records(
page: int = 1,
pageSize: int = 15,
keyword: str = "",
collectType: str = "",
status: str = "",
collectDate: str = "",
collectStartDate: str = "",
collectEndDate: str = "",
) -> dict[str, Any]:
return HistoryQueryService(backend.db_path).list_records(
page=page,
page_size=pageSize,
keyword=keyword,
collect_type=collectType,
status=status,
collect_date=collectDate,
collect_start_date=collectStartDate,
collect_end_date=collectEndDate,
)
@app.delete("/api/history/records")
def clear_history_records():
if getattr(backend, "active_task_id", None):
return JSONResponse(
{
"ok": False,
"status": "busy",
"message": "当前采集任务仍在运行,不能清空采集历史。",
},
status_code=409,
)
result = HistoryClearService(backend.db_path).clear_all()
backend.append_log(
"INFO",
result["message"],
source="history-clear",
summary=True,
)
return result
@app.get("/api/history/summary")
def get_history_summary() -> dict[str, Any]:
return HistoryQueryService(backend.db_path).get_summary()
@app.get("/api/history/suggestions")
def list_history_suggestions(keyword: str = "", limit: int = 20) -> dict[str, Any]:
return HistoryQueryService(backend.db_path).list_suggestions(keyword=keyword, limit=limit)
@app.get("/api/ca/status")
def check_ca_certificate() -> dict[str, Any]:
return _ca_certificate_status_payload(backend)
@app.post("/api/proxy/test")
def test_proxy_connection():
return _proxy_connection_test_payload(backend)
@app.post("/api/config/save")
def save_runtime_config(payload: dict[str, Any] | None = None):
try:
_update_runtime_config_memory(backend, payload or {})
config_path = _write_runtime_config_yaml(backend)
except Exception as exc:
return JSONResponse(
{
"ok": False,
"status": "save-failed",
"message": f"保存配置失败:{exc}",
},
status_code=400,
)
backend.append_log("INFO", f"配置已保存到 custom.yaml:{config_path}")
return {
"ok": True,
"status": "saved",
"message": "配置已保存到 custom.yaml。",
"configPath": str(config_path),
"taskStatus": _current_task_payload(backend),
}
@app.post("/api/config/update")
def update_runtime_config(payload: dict[str, Any] | None = None):
try:
_update_runtime_config_memory(backend, payload or {})
except Exception as exc:
return JSONResponse(
{
"ok": False,
"status": "update-failed",
"message": f"更新运行配置失败:{exc}",
},
status_code=400,
)
backend.append_log("INFO", "配置已更新到当前进程内存,尚未写入 custom.yaml。")
return {
"ok": True,
"status": "updated",
"message": "配置已同步到当前进程内存。",
"taskStatus": _current_task_payload(backend),
}
@app.post("/api/config/reset")
def reset_runtime_config(_payload: UnsupportedPayload | None = None):
busy_reason = _runtime_cache_busy_reason(backend)
if busy_reason:
return JSONResponse(
{
"ok": False,
"status": "busy",
"message": f"{busy_reason},暂不能恢复系统默认配置。",
},
status_code=409,
)
config_service = getattr(backend.runtime, "config_service", None)
if config_service is None or not hasattr(config_service, "restore_system_defaults"):
return JSONResponse(
{
"ok": False,
"status": "reset-unavailable",
"message": "当前运行时未提供系统默认配置恢复能力。",
},
status_code=400,
)
try:
result = config_service.restore_system_defaults()
backend.config_mapping = load_config_mapping(result.config_path)
_replace_runtime_config(backend, result.config)
except Exception as exc:
backend.append_log(
"ERROR",
f"恢复系统默认配置失败:{exc}",
source="config-api",
summary=True,
exception=exc,
)
return JSONResponse(
{
"ok": False,
"status": "reset-failed",
"message": f"恢复系统默认配置失败:{exc}",
},
status_code=400,
)
backend.append_log(
"INFO",
f"已使用 system.yaml 恢复 custom.yaml:{result.config_path}",
source="config-api",
summary=True,
)
return {
"ok": True,
"status": "restored",
"message": "已恢复系统默认配置。",
"configPath": str(result.config_path),
"backupPath": str(result.backup_path) if result.backup_path else None,
"taskStatus": _current_task_payload(backend),
}
@app.post("/api/proxy/mitm/start")
def start_mitm_proxy(_payload: UnsupportedPayload | None = None):
return _set_diagnostic_mitm_payload(backend, enabled=True)
@app.post("/api/proxy/mitm/stop")
def stop_mitm_proxy(_payload: UnsupportedPayload | None = None):
return _set_diagnostic_mitm_payload(backend, enabled=False)
@app.post("/api/proxy/system/enable")
def enable_system_proxy(_payload: UnsupportedPayload | None = None):
return _set_system_proxy_payload(backend, enabled=True)
@app.post("/api/proxy/system/disable")
def disable_system_proxy(_payload: UnsupportedPayload | None = None):
return _set_system_proxy_payload(backend, enabled=False)
@app.post("/api/diagnostics/window")
def run_window_diagnostic(payload: WindowDiagnosticPayload):
action = payload.action.strip()
if action not in WINDOW_DIAGNOSTIC_ACTIONS:
return JSONResponse(
{
"ok": False,
"status": "invalid-action",
"action": action,
"message": f"不支持的窗口诊断动作:{payload.action}",
},
status_code=400,
)
try:
return _window_diagnostic_payload(
backend,
action,
scroll_steps=payload.scrollSteps,
)
except Exception as exc:
backend.append_log("ERROR", f"窗口诊断失败:{exc}")
return JSONResponse(
{
"ok": False,