managers.py
27.2 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
from __future__ import annotations
import json
import subprocess
import threading
from copy import deepcopy
from datetime import datetime
from typing import Any, Dict, Optional, Tuple
from loguru import logger
from .catalog import PLATFORM_LABELS, PLATFORM_OPTIONS
from .runtime import (
EVENT_PREFIX,
MAX_LOG_LINES,
build_completed_process_kwargs,
build_crawl_command_spec,
build_login_command_spec,
build_login_status_command_spec,
build_streaming_process_kwargs,
)
from .state_store import (
clip_text,
normalize_bool,
normalize_text,
now_iso,
sanitize_crawl_config,
sanitize_login_config,
ui_state_store,
)
class LoginTaskManager:
def __init__(self):
self._lock = threading.Lock()
self._process: Optional[subprocess.Popen] = None
self._reader_thread: Optional[threading.Thread] = None
self._active_task: Dict[str, Any] = {
"running": False,
"platform": None,
"login_type": None,
"started_at": None,
"message": "",
"history_id": None,
}
self._platform_states: Dict[str, Dict[str, Any]] = {
item["value"]: {
"platform": item["value"],
"label": item["label"],
"status": "unknown",
"logged_in": None,
"message": "尚未检测",
"last_error": "",
"qr_code": "",
"updated_at": None,
"logs": [],
}
for item in PLATFORM_OPTIONS
}
def snapshot(self) -> Dict[str, Any]:
with self._lock:
return {
"active_task": deepcopy(self._active_task),
"platforms": deepcopy(list(self._platform_states.values())),
}
def snapshot_platform(self, platform: str) -> Dict[str, Any]:
with self._lock:
return deepcopy(self._platform_states[platform])
def update_platform_state(self, platform: str, **updates: Any) -> None:
with self._lock:
state = self._platform_states[platform]
state.update(updates)
state["updated_at"] = now_iso()
def append_platform_log(self, platform: str, message: str) -> None:
if not message:
return
with self._lock:
state = self._platform_states[platform]
state["logs"].append(
{"timestamp": datetime.now().strftime("%H:%M:%S"), "message": message}
)
state["logs"] = state["logs"][-80:]
def _is_running(self) -> bool:
return bool(self._process and self._process.poll() is None)
def _active_history_id(self) -> Optional[str]:
with self._lock:
return self._active_task.get("history_id")
def check_login(self, platform: str, headless: bool = True) -> Tuple[bool, Dict[str, Any]]:
sanitized_config = sanitize_login_config(
platform=platform,
login_type="status_check",
headless=headless,
)
with self._lock:
if self._is_running():
return False, {"message": "当前有登录任务执行中,请稍后再试"}
self._platform_states[platform].update(
{
"status": "checking",
"message": "正在检测登录状态",
"last_error": "",
"qr_code": "",
"updated_at": now_iso(),
}
)
command_spec = build_login_status_command_spec(
platform=platform,
headless=headless,
)
try:
completed = subprocess.run(
command_spec.command,
**build_completed_process_kwargs(timeout=120),
)
payload = self._consume_completed_output(platform, completed.stdout)
if completed.returncode != 0 and payload.get("logged_in") is None:
error_message = completed.stderr.strip() or "登录状态检测失败"
ui_state_store.create_history_entry(
kind="login_check",
platform=platform,
status="error",
message=error_message,
config=sanitized_config,
)
self.update_platform_state(
platform,
status="error",
message=error_message,
last_error=error_message,
)
return False, {"message": error_message}
state = self.snapshot_platform(platform)
ui_state_store.create_history_entry(
kind="login_check",
platform=platform,
status="logged_in" if state.get("logged_in") else "logged_out",
message=state.get("message") or "登录状态已刷新",
config=sanitized_config,
)
return True, state
except subprocess.TimeoutExpired:
error_message = "登录状态检测超时"
ui_state_store.create_history_entry(
kind="login_check",
platform=platform,
status="error",
message=error_message,
config=sanitized_config,
)
self.update_platform_state(
platform,
status="error",
message=error_message,
last_error=error_message,
)
return False, {"message": error_message}
def start_login(
self,
*,
platform: str,
login_type: str,
cookies: str = "",
phone: str = "",
headless: bool = True,
) -> Tuple[bool, str]:
with self._lock:
if self._is_running():
return False, "当前已有登录任务在运行"
sanitized_config = sanitize_login_config(
platform=platform,
login_type=login_type,
headless=headless,
cookies=cookies,
phone=phone,
)
history_id = ui_state_store.create_history_entry(
kind="login",
platform=platform,
status="running",
message="登录任务已启动",
config=sanitized_config,
)
ui_state_store.save_last_login_config(platform, sanitized_config)
self._active_task = {
"running": True,
"platform": platform,
"login_type": login_type,
"started_at": now_iso(),
"message": "正在启动登录任务",
"history_id": history_id,
}
self._platform_states[platform].update(
{
"status": "logging_in",
"message": "正在启动登录任务",
"last_error": "",
"qr_code": "",
"updated_at": now_iso(),
"logs": [],
}
)
command_spec = build_login_command_spec(
platform=platform,
login_type=login_type,
headless=headless,
cookies=cookies,
phone=phone,
)
try:
self._process = subprocess.Popen(
command_spec.command,
**build_streaming_process_kwargs(),
)
except Exception as exc:
error_message = clip_text(str(exc), limit=200) or "登录任务启动失败"
self._active_task = {
"running": False,
"platform": None,
"login_type": None,
"started_at": None,
"message": error_message,
"history_id": None,
}
self._platform_states[platform].update(
{
"status": "error",
"message": error_message,
"last_error": error_message,
"qr_code": "",
"updated_at": now_iso(),
}
)
ui_state_store.update_history_entry(
history_id,
status="error",
message=error_message,
)
return False, error_message
self._reader_thread = threading.Thread(
target=self._read_login_output,
args=(platform,),
daemon=True,
)
self._reader_thread.start()
return True, "登录任务已启动"
def cancel_login(self) -> Tuple[bool, str]:
with self._lock:
if not self._is_running():
return False, "当前没有运行中的登录任务"
process = self._process
platform = self._active_task.get("platform")
history_id = self._active_task.get("history_id")
assert process is not None
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
if platform:
self.update_platform_state(
platform,
status="unknown",
message="登录任务已取消",
qr_code="",
last_error="",
)
with self._lock:
self._active_task = {
"running": False,
"platform": None,
"login_type": None,
"started_at": None,
"message": "登录任务已取消",
"history_id": None,
}
self._process = None
ui_state_store.update_history_entry(
history_id,
status="cancelled",
message="登录任务已取消",
)
return True, "登录任务已取消"
def _consume_completed_output(self, platform: str, output: str) -> Dict[str, Any]:
payload: Dict[str, Any] = {}
for raw_line in output.splitlines():
line = raw_line.strip()
if not line:
continue
if line.startswith(EVENT_PREFIX):
payload = self._handle_login_event(platform, line) or payload
else:
self.append_platform_log(platform, line)
return payload
def _read_login_output(self, platform: str) -> None:
process = self._process
if not process or not process.stdout:
return
try:
for raw_line in process.stdout:
line = raw_line.strip()
if not line:
continue
if line.startswith(EVENT_PREFIX):
self._handle_login_event(platform, line)
else:
self.append_platform_log(platform, line)
return_code = process.wait()
history_id = self._active_history_id()
with self._lock:
current_status = self._platform_states[platform]["status"]
if return_code != 0 and current_status not in {"logged_in", "logged_out", "unknown"}:
self._platform_states[platform].update(
{
"status": "error",
"message": "登录任务失败",
"last_error": "登录任务失败",
"updated_at": now_iso(),
}
)
self._active_task = {
"running": False,
"platform": None,
"login_type": None,
"started_at": None,
"message": "登录任务已结束",
"history_id": None,
}
self._process = None
final_state = self.snapshot_platform(platform)
ui_state_store.update_history_entry(
history_id,
status=final_state.get("status") or ("error" if return_code != 0 else "logged_out"),
message=final_state.get("message") or "登录任务已结束",
)
except Exception as exc:
logger.exception(f"登录任务日志读取异常: {exc}")
self.update_platform_state(
platform,
status="error",
message=str(exc),
last_error=str(exc),
)
ui_state_store.update_history_entry(
self._active_history_id(),
status="error",
message=str(exc),
)
def _handle_login_event(self, platform: str, line: str) -> Optional[Dict[str, Any]]:
try:
payload = json.loads(line[len(EVENT_PREFIX) :])
except json.JSONDecodeError:
self.append_platform_log(platform, line)
return None
event_type = payload.get("type")
if event_type == "qr_code":
self.update_platform_state(
platform,
status="awaiting_scan",
message="请使用手机扫码登录",
qr_code=payload.get("image", ""),
)
self.append_platform_log(platform, "二维码已生成,请在前端扫码")
elif event_type == "login_status":
logged_in = bool(payload.get("logged_in"))
self.update_platform_state(
platform,
status="logged_in" if logged_in else "logged_out",
logged_in=logged_in,
message="登录成功" if logged_in else "当前未登录",
last_error="",
qr_code="" if logged_in else self.snapshot_platform(platform).get("qr_code", ""),
)
self.append_platform_log(platform, "登录状态已更新")
ui_state_store.update_history_entry(
self._active_history_id(),
status="logged_in" if logged_in else "logged_out",
message="登录成功" if logged_in else "当前未登录",
)
elif event_type in {"login_started", "status_check_started"}:
message = payload.get("message") or "任务已启动"
self.update_platform_state(platform, message=message)
self.append_platform_log(platform, message)
elif event_type == "error":
message = payload.get("message") or "任务执行失败"
self.update_platform_state(
platform,
status="error",
message=message,
last_error=message,
)
self.append_platform_log(platform, message)
ui_state_store.update_history_entry(
self._active_history_id(),
status="error",
message=message,
)
elif event_type == "cancelled":
message = payload.get("message") or "任务已取消"
self.update_platform_state(
platform,
status="unknown",
message=message,
qr_code="",
)
self.append_platform_log(platform, message)
ui_state_store.update_history_entry(
self._active_history_id(),
status="cancelled",
message=message,
)
return payload
class CrawlTaskManager:
def __init__(self, login_manager: LoginTaskManager):
self._lock = threading.Lock()
self._process: Optional[subprocess.Popen] = None
self._reader_thread: Optional[threading.Thread] = None
self._login_manager = login_manager
self._state: Dict[str, Any] = {
"status": "idle",
"platform": None,
"platform_label": None,
"crawler_type": None,
"started_at": None,
"message": "尚未启动爬虫任务",
"qr_code": "",
"last_error": "",
"logs": [],
"current_config": None,
"history_id": None,
}
def snapshot(self) -> Dict[str, Any]:
with self._lock:
return deepcopy(self._state)
def _is_running(self) -> bool:
return bool(self._process and self._process.poll() is None)
def _history_id(self) -> Optional[str]:
with self._lock:
return self._state.get("history_id")
def _clear_pending_login_prompt(
self,
platform: Optional[str],
message: str = "扫码已取消,当前未登录",
) -> None:
if not platform or platform not in PLATFORM_LABELS:
return
platform_state = self._login_manager.snapshot_platform(platform)
if platform_state.get("status") not in {"awaiting_scan", "logging_in"}:
return
self._login_manager.update_platform_state(
platform,
status="logged_out",
logged_in=False,
message=message,
qr_code="",
last_error="",
)
def start(self, payload: Dict[str, Any]) -> Tuple[bool, str]:
with self._lock:
if self._is_running():
return False, "当前已有爬虫任务在运行"
if self._login_manager.snapshot()["active_task"]["running"]:
return False, "当前有登录任务在运行,请先完成登录"
platform = normalize_text(payload.get("platform"))
crawler_type = normalize_text(payload.get("crawler_type") or "search")
login_type = normalize_text(payload.get("login_type") or "qrcode")
cookies = normalize_text(payload.get("cookies"))
phone = normalize_text(payload.get("phone"))
headless = normalize_bool(payload.get("headless"), True)
keywords = normalize_text(payload.get("keywords"))
specified_ids = normalize_text(payload.get("specified_ids"))
creator_ids = normalize_text(payload.get("creator_ids"))
crawl_command_spec = build_crawl_command_spec(
platform=platform,
login_type=login_type,
crawler_type=crawler_type,
keywords=keywords,
specified_ids=specified_ids,
creator_ids=creator_ids,
start_page=int(payload.get("start_page") or 1),
max_notes=int(payload.get("max_notes") or 20),
max_comments=int(payload.get("max_comments") or 20),
enable_comments=normalize_bool(payload.get("enable_comments"), True),
enable_sub_comments=normalize_bool(payload.get("enable_sub_comments"), False),
save_data_option=normalize_text(payload.get("save_option")),
headless=headless,
cookies=cookies,
phone=phone,
)
save_option = crawl_command_spec.resolved_save_data_option or ""
sanitized_config = sanitize_crawl_config(
{
**payload,
"platform": platform,
"crawler_type": crawler_type,
"login_type": login_type,
"save_option": save_option,
"headless": headless,
}
)
history_id = ui_state_store.create_history_entry(
kind="crawl",
platform=platform,
status="running",
message="爬虫任务已启动",
config=sanitized_config,
extra={"crawler_type": crawler_type},
)
ui_state_store.save_last_crawl_config(platform, sanitized_config)
try:
process = subprocess.Popen(
crawl_command_spec.command,
**build_streaming_process_kwargs(),
)
except Exception as exc:
error_message = clip_text(str(exc), limit=200) or "爬虫任务启动失败"
ui_state_store.update_history_entry(
history_id,
status="error",
message=error_message,
)
return False, error_message
with self._lock:
self._process = process
self._state = {
"status": "running",
"platform": platform,
"platform_label": PLATFORM_LABELS.get(platform, platform),
"crawler_type": crawler_type,
"started_at": now_iso(),
"message": "爬虫任务已启动",
"qr_code": "",
"last_error": "",
"logs": [],
"current_config": {**sanitized_config},
"history_id": history_id,
}
self._reader_thread = threading.Thread(
target=self._read_output,
daemon=True,
)
self._reader_thread.start()
return True, "爬虫任务已启动"
def stop(self) -> Tuple[bool, str]:
with self._lock:
if not self._is_running():
return False, "当前没有运行中的爬虫任务"
process = self._process
self._state["status"] = "stopping"
self._state["message"] = "正在停止爬虫任务"
history_id = self._state.get("history_id")
platform = self._state.get("platform")
assert process is not None
process.terminate()
try:
process.wait(timeout=12)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
with self._lock:
self._state["status"] = "idle"
self._state["message"] = "爬虫任务已停止"
self._state["qr_code"] = ""
self._process = None
self._state["history_id"] = None
self._clear_pending_login_prompt(platform)
ui_state_store.update_history_entry(
history_id,
status="cancelled",
message="爬虫任务已停止",
)
return True, "爬虫任务已停止"
def _append_log(self, message: str) -> None:
if not message:
return
with self._lock:
self._state["logs"].append(
{"timestamp": datetime.now().strftime("%H:%M:%S"), "message": message}
)
self._state["logs"] = self._state["logs"][-MAX_LOG_LINES:]
def _read_output(self) -> None:
process = self._process
if not process or not process.stdout:
return
try:
for raw_line in process.stdout:
line = raw_line.strip()
if not line:
continue
if line.startswith(EVENT_PREFIX):
self._handle_event(line)
else:
self._append_log(line)
return_code = process.wait()
history_id = self._history_id()
with self._lock:
if return_code == 0 and self._state["status"] not in {"idle"}:
self._state["status"] = "idle"
self._state["message"] = "爬虫任务执行完成"
self._state["qr_code"] = ""
elif return_code != 0 and self._state["status"] not in {"idle", "error"}:
self._state["status"] = "error"
self._state["message"] = "爬虫任务执行失败"
self._state["last_error"] = self._state["message"]
self._process = None
self._state["history_id"] = None
final_state = deepcopy(self._state)
ui_state_store.update_history_entry(
history_id,
status=final_state.get("status") or ("error" if return_code != 0 else "completed"),
message=final_state.get("message") or "爬虫任务已结束",
)
except Exception as exc:
history_id = self._history_id()
logger.exception(f"爬虫任务日志读取异常: {exc}")
with self._lock:
self._state["status"] = "error"
self._state["message"] = str(exc)
self._state["last_error"] = str(exc)
self._process = None
self._state["history_id"] = None
ui_state_store.update_history_entry(
history_id,
status="error",
message=str(exc),
)
def _handle_event(self, line: str) -> None:
try:
payload = json.loads(line[len(EVENT_PREFIX) :])
except json.JSONDecodeError:
self._append_log(line)
return
event_type = payload.get("type")
if event_type == "crawl_started":
with self._lock:
self._state["status"] = "running"
self._state["message"] = "爬虫任务正在运行"
elif event_type == "crawl_finished":
with self._lock:
self._state["status"] = "idle"
self._state["message"] = "爬虫任务执行完成"
self._state["qr_code"] = ""
elif event_type == "qr_code":
with self._lock:
self._state["qr_code"] = payload.get("image", "")
self._state["message"] = "检测到登录二维码,请先扫码完成登录"
platform = payload.get("platform")
if platform in PLATFORM_LABELS:
self._login_manager.update_platform_state(
platform,
status="awaiting_scan",
message="爬虫任务等待扫码登录",
qr_code=payload.get("image", ""),
)
elif event_type == "login_status":
platform = payload.get("platform")
if platform in PLATFORM_LABELS:
logged_in = bool(payload.get("logged_in"))
self._login_manager.update_platform_state(
platform,
status="logged_in" if logged_in else "logged_out",
logged_in=logged_in,
message="登录成功" if logged_in else "当前未登录",
qr_code="" if logged_in else self._login_manager.snapshot_platform(platform).get("qr_code", ""),
last_error="",
)
if logged_in:
with self._lock:
self._state["qr_code"] = ""
elif event_type == "error":
message = payload.get("message") or "爬虫执行失败"
with self._lock:
self._state["status"] = "error"
self._state["message"] = message
self._state["last_error"] = message
ui_state_store.update_history_entry(
self._history_id(),
status="error",
message=message,
)
elif event_type == "cancelled":
with self._lock:
platform = self._state.get("platform")
self._state["status"] = "idle"
self._state["message"] = "爬虫任务已取消"
self._state["qr_code"] = ""
self._clear_pending_login_prompt(platform)
ui_state_store.update_history_entry(
self._history_id(),
status="cancelled",
message="爬虫任务已取消",
)