@cloud411716/fancy-webnovel 4.10.0 → 4.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,7 +34,11 @@ import {
34
34
  updateAccountProfile,
35
35
  } from './state.js';
36
36
  import { analysisPrompt, articlePrompt, capabilityPrompt, helpText, loginQuestion, summaryText, videoAnalysisPrompt, videoRelevancePrompt } from './templates.js';
37
- import { createSerialLock, getSubagentRuntime, runJobPool, subagentWorkerCount } from './subagents.js';
37
+ import { createJobQueue, createSerialLock, getSubagentRuntime, subagentWorkerCount } from './subagents.js';
38
+ import {
39
+ countJobsByAccount, createJob, jobKeyFor, jobRelDir,
40
+ listJobsForAccount, migrateCrawledJobs, openJobStore, updateJob,
41
+ } from './jobs.js';
38
42
 
39
43
  export const inject = ['commands', 'userQuestions'];
40
44
 
@@ -769,6 +773,43 @@ async function runLocalAnalysisJob(ctx, invocation, session, job, {
769
773
  });
770
774
  }
771
775
 
776
+ function readJsonArtifact(dir, name) {
777
+ try {
778
+ return JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
779
+ } catch {
780
+ return null;
781
+ }
782
+ }
783
+
784
+ function reusableNote(dir) {
785
+ const note = readJsonArtifact(dir, 'note.json');
786
+ if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) return null;
787
+ if (!note.screenshots.every((shot) => shot && shot.file && fs.existsSync(shot.file))) return null;
788
+ return note;
789
+ }
790
+
791
+ function reusableVideo(dir) {
792
+ const video = readJsonArtifact(dir, 'video.json');
793
+ if (!video || !Array.isArray(video.frames) || !video.frames.length) return null;
794
+ if (!video.frames.every((frame) => frame && frame.file && fs.existsSync(frame.file))) return null;
795
+ return video;
796
+ }
797
+
798
+ function reusableArticle(dir) {
799
+ const article = readJsonArtifact(dir, 'article.json');
800
+ if (!article || !article.body || String(article.body).trim().length < 50) return null;
801
+ return article;
802
+ }
803
+
804
+ function materialFileReady(dir) {
805
+ const file = path.join(dir, 'materials.jsonl');
806
+ try {
807
+ return fs.statSync(file).size > 0;
808
+ } catch {
809
+ return false;
810
+ }
811
+ }
812
+
772
813
  async function runCrawl(ctx, invocation, session, taskList) {
773
814
  const root = workspaceOf(session);
774
815
  const paths = ensureDouyinDir(root);
@@ -779,6 +820,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
779
820
 
780
821
  const runDir = path.join(paths.output, stampOfNow());
781
822
  fs.mkdirSync(runDir, { recursive: true });
823
+ fs.mkdirSync(paths.jobs, { recursive: true });
782
824
 
783
825
  // 先做能力自检:如果模型既不能看图也不能看视频,直接退出,
784
826
  // 不启动 Chrome,也不扫描账号。
@@ -803,9 +845,21 @@ async function runCrawl(ctx, invocation, session, taskList) {
803
845
  return notify(session, 'error', '❌ 部署素材校验脚本失败:\n' + (materialTools.problems.join('\n') || '未知错误'));
804
846
  }
805
847
 
848
+ let jobStore;
849
+ let queue = null;
850
+ let workerPromises = [];
851
+ try {
852
+ jobStore = await openJobStore(root);
853
+ await migrateCrawledJobs(jobStore.db, root);
854
+ } catch (err) {
855
+ if (jobStore) await jobStore.close();
856
+ return notify(session, 'error', '❌ 初始化抖音任务状态表失败:' + (err && err.message ? err.message : String(err)));
857
+ }
858
+
806
859
  const mode = hasDouyinLogin(paths) ? 'headless' : 'headed';
807
860
  const started = await startChrome(root, tools, paths, mode);
808
861
  if (!started.ok) {
862
+ await jobStore.close();
809
863
  return notify(session, 'error', '❌ 启动 Chrome 失败:' + started.error);
810
864
  }
811
865
  const browser = { cdp: started.cdp, mode: started.mode };
@@ -827,7 +881,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
827
881
  else invocation.signal.addEventListener('abort', () => abortController.abort(), { once: true });
828
882
  }
829
883
  const jobSignal = abortController.signal;
830
- const markJobFailed = (job, reason) => {
884
+ const markJobFailedLocked = async (job, reason, { crawl = false } = {}) => {
831
885
  if (!job || !job.id) return;
832
886
  markCrawled(root, job.id, {
833
887
  account_url: job.accountUrl,
@@ -849,7 +903,51 @@ async function runCrawl(ctx, invocation, session, taskList) {
849
903
  reason,
850
904
  });
851
905
  crawled[job.id] = true;
906
+ if (job.jobKey) {
907
+ await updateJob(jobStore.db, job.jobKey, {
908
+ ...(crawl ? { crawl_status: 'failed' } : { analysis_status: 'failed' }),
909
+ import_status: 'failed',
910
+ reason,
911
+ error: reason,
912
+ });
913
+ }
852
914
  };
915
+ const markJobFailed = async (job, reason, options) => withStateLock(
916
+ () => markJobFailedLocked(job, reason, options),
917
+ );
918
+
919
+ const markJobSkippedLocked = async (job, reason, { crawl = false } = {}) => {
920
+ if (!job || !job.id) return;
921
+ markCrawled(root, job.id, {
922
+ account_url: job.accountUrl,
923
+ url: job.url || (job.card && job.card.href) || '',
924
+ title: job.title || (job.card && job.card.text) || '',
925
+ type: job.type,
926
+ duration: job.duration,
927
+ dir: job.dir,
928
+ inserted: 0,
929
+ skipped: 0,
930
+ skip: true,
931
+ reason,
932
+ });
933
+ crawled[job.id] = true;
934
+ if (job.jobKey) {
935
+ await updateJob(jobStore.db, job.jobKey, {
936
+ ...(crawl ? { crawl_status: 'crawled' } : {}),
937
+ analysis_status: 'analyzed',
938
+ import_status: 'skipped',
939
+ reason,
940
+ error: '',
941
+ imported_at: new Date(),
942
+ });
943
+ }
944
+ };
945
+ const markJobSkipped = async (job, reason, options) => withStateLock(
946
+ () => markJobSkippedLocked(job, reason, options),
947
+ );
948
+
949
+ queue = useSubagents ? createJobQueue() : null;
950
+ const queueStats = { queued: 0, finished: 0 };
853
951
  let scannedAccounts = 0;
854
952
  let foundNotes = 0;
855
953
  let foundVideos = 0;
@@ -865,26 +963,166 @@ async function runCrawl(ctx, invocation, session, taskList) {
865
963
  let skippedMaterials = 0;
866
964
  let aborted = false;
867
965
 
966
+ const progressText = () => queue
967
+ ? `分析素材(子 Agent 并行:${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`
968
+ : `分析素材(${queueStats.finished}/${jobs.length})`;
969
+
970
+ const jobRecord = (job, extra = {}) => ({
971
+ account_url: job.accountUrl,
972
+ url: job.url,
973
+ title: job.title || (job.card && job.card.text) || '',
974
+ type: job.type,
975
+ duration: job.duration,
976
+ screenshots: job.type === 'note' && Array.isArray(job.screenshots)
977
+ ? job.screenshots.map((shot) => shot.file)
978
+ : undefined,
979
+ body_file: job.article && job.article.body_file,
980
+ reading_time: job.article && job.article.reading_time,
981
+ body_length: job.article && job.article.body_length,
982
+ dir: job.dir,
983
+ ...extra,
984
+ });
985
+
986
+ const finalizeJob = async (job, analyzed) => {
987
+ await withStateLock(async () => {
988
+ if (analyzed && analyzed.needsFinalize) {
989
+ analyzed = await finalizeMaterialFile({
990
+ root,
991
+ target: job.target,
992
+ title: job.title,
993
+ materialTools,
994
+ });
995
+ }
996
+ if (analyzed && analyzed.aborted) {
997
+ aborted = true;
998
+ if (job.jobKey) {
999
+ await updateJob(jobStore.db, job.jobKey, { analysis_status: 'pending' });
1000
+ }
1001
+ return;
1002
+ }
1003
+ if (!analyzed || !analyzed.ok) {
1004
+ const reason = (analyzed && (analyzed.error || analyzed.detail)) || '素材没有通过校验';
1005
+ failures.push({ id: job.id, url: job.url, reason });
1006
+ await markJobFailedLocked(job, reason);
1007
+ queueStats.finished += 1;
1008
+ taskList.progress(progressText());
1009
+ return;
1010
+ }
1011
+ if (analyzed.skipped) {
1012
+ skippedIrrelevant += 1;
1013
+ markCrawled(root, job.id, jobRecord(job, {
1014
+ inserted: 0,
1015
+ skipped: 0,
1016
+ skip: true,
1017
+ reason: analyzed.reason || '与网文创作无关',
1018
+ }));
1019
+ if (job.jobKey) {
1020
+ await updateJob(jobStore.db, job.jobKey, {
1021
+ analysis_status: 'analyzed',
1022
+ import_status: 'skipped',
1023
+ material_count: 0,
1024
+ reason: analyzed.reason || '与网文创作无关',
1025
+ error: '',
1026
+ imported_at: new Date(),
1027
+ });
1028
+ }
1029
+ } else {
1030
+ inserted += analyzed.inserted || 0;
1031
+ skippedMaterials += analyzed.skipped || 0;
1032
+ markCrawled(root, job.id, jobRecord(job, {
1033
+ inserted: analyzed.inserted || 0,
1034
+ skipped: analyzed.skipped || 0,
1035
+ }));
1036
+ if (job.jobKey) {
1037
+ await updateJob(jobStore.db, job.jobKey, {
1038
+ analysis_status: 'analyzed',
1039
+ import_status: 'imported',
1040
+ material_count: analyzed.inserted || 0,
1041
+ reason: '',
1042
+ error: '',
1043
+ imported_at: new Date(),
1044
+ });
1045
+ }
1046
+ }
1047
+ crawled[job.id] = true;
1048
+ queueStats.finished += 1;
1049
+ taskList.progress(progressText());
1050
+ });
1051
+ };
1052
+
1053
+ const enqueueJob = async (job) => {
1054
+ if (job.jobKey) {
1055
+ await updateJob(jobStore.db, job.jobKey, {
1056
+ crawl_status: 'crawled',
1057
+ analysis_status: job.finalizeOnly ? 'analyzed' : 'pending',
1058
+ dir_rel: job.dirRel,
1059
+ title: job.title || '',
1060
+ work_url: job.url,
1061
+ error: '',
1062
+ reason: '',
1063
+ });
1064
+ }
1065
+ if (queue) {
1066
+ queueStats.queued += 1;
1067
+ if (taskList.index < 4) taskList.advance(4);
1068
+ queue.push(job);
1069
+ taskList.progress(progressText());
1070
+ } else {
1071
+ jobs.push(job);
1072
+ }
1073
+ };
1074
+
1075
+ const runWorker = async () => {
1076
+ while (true) {
1077
+ if (abortRequested(invocation)) { aborted = true; return; }
1078
+ const job = await queue.next();
1079
+ if (!job) return;
1080
+ let analyzed;
1081
+ if (job.finalizeOnly) {
1082
+ analyzed = { ok: true, needsFinalize: true };
1083
+ } else {
1084
+ try {
1085
+ analyzed = await runSubagentAnalysisJob({
1086
+ subagents: subagentRuntime,
1087
+ provider: 'spawn',
1088
+ invocation,
1089
+ job,
1090
+ root,
1091
+ materialTools,
1092
+ signal: jobSignal,
1093
+ });
1094
+ } catch (err) {
1095
+ analyzed = {
1096
+ ok: false,
1097
+ error: '子 Agent 分析失败:' + (err && err.message ? err.message : String(err)),
1098
+ };
1099
+ }
1100
+ }
1101
+ await finalizeJob(job, analyzed);
1102
+ }
1103
+ };
1104
+
1105
+ workerPromises = queue
1106
+ ? Array.from({ length: subagentWorkers }, () => runWorker())
1107
+ : [];
868
1108
  outer:
869
1109
  for (const account of accounts) {
870
1110
  if (abortRequested(invocation)) { aborted = true; break; }
871
1111
  const accountDir = path.join(runDir, accountSlug(account.url));
872
- const markFailed = (id, card, data, reason) => {
1112
+ const markFailed = async (id, card, data, reason) => {
873
1113
  if (!id) return;
874
- markCrawled(root, id, {
875
- account_url: account.url,
1114
+ const job = {
1115
+ id,
1116
+ jobKey: jobKeyFor(account.url, id),
1117
+ accountUrl: account.url,
876
1118
  url: data.url || card.href,
877
1119
  title: data.title || card.text || '',
878
1120
  type: data.type,
879
1121
  duration: data.duration,
880
1122
  dir: data.dir,
881
- inserted: 0,
882
- skipped: 0,
883
- skip: true,
884
- failed: true,
885
- reason,
886
- });
887
- crawled[id] = true;
1123
+ card,
1124
+ };
1125
+ await markJobFailed(job, reason, { crawl: true });
888
1126
  };
889
1127
  const scan = await runWithLogin(
890
1128
  ctx, invocation, session, root, tools.scripts.scan,
@@ -906,61 +1144,159 @@ async function runCrawl(ctx, invocation, session, taskList) {
906
1144
  scannedAccounts += 1;
907
1145
  if (scan.json.profile) {
908
1146
  updateAccountProfile(root, account.url, scan.json.profile);
1147
+ account.name = scan.json.profile.name || account.name || '';
1148
+ account.douyin_id = scan.json.profile.douyin_id || account.douyin_id || '';
1149
+ account.sec_uid = scan.json.profile.sec_uid || account.sec_uid || '';
909
1150
  }
1151
+ const existingJobs = new Map((await listJobsForAccount(jobStore.db, account.url))
1152
+ .map((job) => [String(job.work_id), job]));
1153
+ const ensureJob = async (workId, type, card, dirRel, title = '') => {
1154
+ const key = jobKeyFor(account.url, workId);
1155
+ let row = existingJobs.get(String(workId)) || null;
1156
+ if (!row) {
1157
+ row = await createJob(jobStore.db, {
1158
+ job_key: key,
1159
+ account_url: account.url,
1160
+ account_name: account.name || '',
1161
+ douyin_id: account.douyin_id || '',
1162
+ account_sec_uid: account.sec_uid || '',
1163
+ work_id: String(workId),
1164
+ work_type: type,
1165
+ work_url: card.href,
1166
+ title: title || card.text || '',
1167
+ dir_rel: dirRel,
1168
+ });
1169
+ existingJobs.set(String(workId), row);
1170
+ } else {
1171
+ await updateJob(jobStore.db, row.job_key || key, {
1172
+ account_name: account.name || '',
1173
+ douyin_id: account.douyin_id || '',
1174
+ account_sec_uid: account.sec_uid || '',
1175
+ title: title || row.title || '',
1176
+ work_url: card.href,
1177
+ dir_rel: dirRel,
1178
+ });
1179
+ }
1180
+ return row.job_key || key;
1181
+ };
910
1182
  const notes = Array.isArray(scan.json.notes) ? scan.json.notes : [];
911
1183
  const videos = Array.isArray(scan.json.videos) ? scan.json.videos : [];
912
1184
  const articles = Array.isArray(scan.json.articles) ? scan.json.articles : [];
913
1185
  foundNotes += notes.length;
914
1186
  foundVideos += videos.length;
915
1187
  foundArticles += articles.length;
916
- taskList.advance(3);
1188
+ if (taskList.index < 3) taskList.advance(3);
917
1189
 
918
1190
  for (const card of notes) {
919
1191
  if (abortRequested(invocation)) { aborted = true; break outer; }
920
- if (!capabilities.image_supported) {
921
- skippedNotesByCapability += 1;
922
- continue;
923
- }
924
1192
  const noteId = noteIdFromUrl(card.href);
925
1193
  if (!noteId) continue;
926
- if (crawled[noteId] || queued.has(noteId)) {
1194
+ const existing = existingJobs.get(String(noteId)) || null;
1195
+ if (existing && existing.import_status !== 'pending') {
927
1196
  skippedNotes += 1;
928
1197
  continue;
929
1198
  }
930
- const noteDir = path.join(accountDir, noteId);
931
- const noteResult = await runWithLogin(
932
- ctx, invocation, session, root, tools.scripts.note,
933
- ['--workspace', root, '--note', card.href, '--cdp', browser.cdp,
934
- '--out', noteDir, '--login-state', paths.loginState],
935
- noteDir,
936
- paths,
937
- '采集图文作品',
938
- tools.nodePath,
939
- browser,
940
- tools,
941
- );
942
- if (!noteResult.ok) {
943
- failures.push({ id: noteId, url: card.href, reason: noteResult.error });
944
- if (noteResult.cancelled || authFailureText(noteResult.error)) { aborted = true; break outer; }
945
- markFailed(noteId, card, { type: 'note', dir: noteDir }, noteResult.error);
1199
+ if ((!existing && crawled[noteId]) || queued.has(noteId)) {
1200
+ skippedNotes += 1;
1201
+ continue;
1202
+ }
1203
+
1204
+ const dirRel = existing && existing.dir_rel ? existing.dir_rel : jobRelDir(account.url, noteId);
1205
+ const noteDir = path.join(paths.jobs, dirRel);
1206
+ const jobKey = await ensureJob(noteId, 'note', card, dirRel, existing && existing.title);
1207
+ const target = path.join(noteDir, 'materials.jsonl');
1208
+
1209
+ if (materialFileReady(noteDir)) {
1210
+ processedWorks += 1;
1211
+ await enqueueJob({
1212
+ type: 'note',
1213
+ id: noteId,
1214
+ jobKey,
1215
+ card,
1216
+ accountUrl: account.url,
1217
+ url: (existing && existing.work_url) || card.href,
1218
+ dir: noteDir,
1219
+ dirRel,
1220
+ target,
1221
+ title: (existing && existing.title) || card.text || '',
1222
+ screenshots: [],
1223
+ finalizeOnly: true,
1224
+ });
1225
+ queued.add(noteId);
1226
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1227
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1228
+ await sleep(delay);
1229
+ }
946
1230
  continue;
947
1231
  }
948
- const note = noteResult.json.note;
949
- if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) {
950
- failures.push({ id: noteId, url: card.href, reason: '没有截图' });
951
- markFailed(noteId, card, { type: 'note', dir: noteDir }, '没有截图');
1232
+
1233
+ if (!capabilities.image_supported) {
1234
+ skippedNotesByCapability += 1;
952
1235
  continue;
953
1236
  }
1237
+
1238
+ let note = reusableNote(noteDir);
1239
+ if (note) {
1240
+ note.account_url = account.url;
1241
+ await updateJob(jobStore.db, jobKey, {
1242
+ crawl_status: 'crawled',
1243
+ analysis_status: 'pending',
1244
+ dir_rel: dirRel,
1245
+ title: note.title || card.text || '',
1246
+ work_url: note.url || card.href,
1247
+ error: '',
1248
+ });
1249
+ } else {
1250
+ await updateJob(jobStore.db, jobKey, {
1251
+ crawl_status: 'crawling',
1252
+ analysis_status: 'pending',
1253
+ dir_rel: dirRel,
1254
+ attempts: (Number(existing && existing.attempts) || 0) + 1,
1255
+ error: '',
1256
+ });
1257
+ const noteResult = await runWithLogin(
1258
+ ctx, invocation, session, root, tools.scripts.note,
1259
+ ['--workspace', root, '--note', card.href, '--cdp', browser.cdp,
1260
+ '--out', noteDir, '--login-state', paths.loginState],
1261
+ noteDir,
1262
+ paths,
1263
+ '采集图文作品',
1264
+ tools.nodePath,
1265
+ browser,
1266
+ tools,
1267
+ );
1268
+ if (!noteResult.ok) {
1269
+ failures.push({ id: noteId, url: card.href, reason: noteResult.error });
1270
+ if (noteResult.cancelled || authFailureText(noteResult.error)) { aborted = true; break outer; }
1271
+ await markFailed(noteId, card, { type: 'note', dir: noteDir }, noteResult.error);
1272
+ continue;
1273
+ }
1274
+ note = noteResult.json.note;
1275
+ if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) {
1276
+ failures.push({ id: noteId, url: card.href, reason: '没有截图' });
1277
+ await markFailed(noteId, card, { type: 'note', dir: noteDir }, '没有截图');
1278
+ continue;
1279
+ }
1280
+ await updateJob(jobStore.db, jobKey, {
1281
+ crawl_status: 'crawled',
1282
+ title: note.title || '',
1283
+ work_url: note.url || card.href,
1284
+ dir_rel: dirRel,
1285
+ error: '',
1286
+ });
1287
+ }
1288
+
954
1289
  processedWorks += 1;
955
1290
  note.account_url = account.url;
956
- const target = path.join(noteDir, 'materials.jsonl');
957
- jobs.push({
1291
+ await enqueueJob({
958
1292
  type: 'note',
959
1293
  id: noteId,
1294
+ jobKey,
960
1295
  card,
961
1296
  accountUrl: account.url,
962
1297
  url: note.url || card.href,
963
1298
  dir: noteDir,
1299
+ dirRel,
964
1300
  note,
965
1301
  screenshots: note.screenshots,
966
1302
  target,
@@ -975,64 +1311,124 @@ async function runCrawl(ctx, invocation, session, taskList) {
975
1311
 
976
1312
  for (const card of videos) {
977
1313
  if (abortRequested(invocation)) { aborted = true; break outer; }
978
- if (!capabilities.video_supported) {
979
- skippedVideosByCapability += 1;
980
- continue;
981
- }
982
1314
  const videoId = noteIdFromUrl(card.href);
983
1315
  if (!videoId) continue;
984
- if (crawled[videoId] || queued.has(videoId)) {
1316
+ const existing = existingJobs.get(String(videoId)) || null;
1317
+ if (existing && existing.import_status !== 'pending') {
985
1318
  skippedNotes += 1;
986
1319
  continue;
987
1320
  }
988
- const videoDir = path.join(accountDir, videoId);
989
- const videoResult = await runWithLogin(
990
- ctx, invocation, session, root, tools.scripts.video,
991
- ['--workspace', root, '--video', card.href, '--cdp', browser.cdp,
992
- '--out', videoDir, '--login-state', paths.loginState,
993
- '--max-seconds', String(MAX_VIDEO_SECONDS)],
994
- videoDir,
995
- paths,
996
- '采集视频作品',
997
- tools.nodePath,
998
- browser,
999
- tools,
1000
- VIDEO_SCRIPT_TIMEOUT_MS,
1001
- );
1002
- if (!videoResult.ok) {
1003
- failures.push({ id: videoId, url: card.href, reason: videoResult.error });
1004
- if (videoResult.cancelled || authFailureText(videoResult.error)) { aborted = true; break outer; }
1005
- markFailed(videoId, card, { type: 'video', dir: videoDir }, videoResult.error);
1321
+ if ((!existing && crawled[videoId]) || queued.has(videoId)) {
1322
+ skippedNotes += 1;
1006
1323
  continue;
1007
1324
  }
1008
- const video = videoResult.json.video || {};
1009
- if (videoResult.json.skip) {
1010
- skippedLongVideos += 1;
1011
- markCrawled(root, videoId, {
1012
- account_url: account.url,
1013
- url: video.url || card.href,
1014
- title: video.title || card.text || '',
1325
+
1326
+ const dirRel = existing && existing.dir_rel ? existing.dir_rel : jobRelDir(account.url, videoId);
1327
+ const videoDir = path.join(paths.jobs, dirRel);
1328
+ const jobKey = await ensureJob(videoId, 'video', card, dirRel, existing && existing.title);
1329
+ const target = path.join(videoDir, 'materials.jsonl');
1330
+
1331
+ if (materialFileReady(videoDir)) {
1332
+ processedWorks += 1;
1333
+ await enqueueJob({
1015
1334
  type: 'video',
1016
- duration: video.duration,
1335
+ id: videoId,
1336
+ jobKey,
1337
+ card,
1338
+ accountUrl: account.url,
1339
+ url: (existing && existing.work_url) || card.href,
1017
1340
  dir: videoDir,
1018
- inserted: 0,
1019
- skipped: 0,
1020
- skip: true,
1021
- reason: videoResult.json.reason || '视频时长超过 1 分钟',
1341
+ dirRel,
1342
+ target,
1343
+ title: (existing && existing.title) || card.text || '',
1344
+ duration: existing && existing.duration,
1345
+ video: null,
1346
+ finalizeOnly: true,
1022
1347
  });
1023
- crawled[videoId] = true;
1348
+ queued.add(videoId);
1349
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1350
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1351
+ await sleep(delay);
1352
+ }
1024
1353
  continue;
1025
1354
  }
1026
- if (!video || !Array.isArray(video.frames) || !video.frames.length) {
1027
- failures.push({ id: videoId, url: card.href, reason: '没有视频关键帧' });
1028
- markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title }, '没有视频关键帧');
1355
+
1356
+ if (!capabilities.video_supported) {
1357
+ skippedVideosByCapability += 1;
1029
1358
  continue;
1030
1359
  }
1360
+
1361
+ let video = reusableVideo(videoDir);
1362
+ if (!video) {
1363
+ await updateJob(jobStore.db, jobKey, {
1364
+ crawl_status: 'crawling',
1365
+ analysis_status: 'pending',
1366
+ dir_rel: dirRel,
1367
+ attempts: (Number(existing && existing.attempts) || 0) + 1,
1368
+ error: '',
1369
+ });
1370
+ const videoResult = await runWithLogin(
1371
+ ctx, invocation, session, root, tools.scripts.video,
1372
+ ['--workspace', root, '--video', card.href, '--cdp', browser.cdp,
1373
+ '--out', videoDir, '--login-state', paths.loginState,
1374
+ '--max-seconds', String(MAX_VIDEO_SECONDS)],
1375
+ videoDir,
1376
+ paths,
1377
+ '采集视频作品',
1378
+ tools.nodePath,
1379
+ browser,
1380
+ tools,
1381
+ VIDEO_SCRIPT_TIMEOUT_MS,
1382
+ );
1383
+ if (!videoResult.ok) {
1384
+ failures.push({ id: videoId, url: card.href, reason: videoResult.error });
1385
+ if (videoResult.cancelled || authFailureText(videoResult.error)) { aborted = true; break outer; }
1386
+ await markFailed(videoId, card, { type: 'video', dir: videoDir }, videoResult.error);
1387
+ continue;
1388
+ }
1389
+ video = videoResult.json.video || {};
1390
+ if (videoResult.json.skip) {
1391
+ skippedLongVideos += 1;
1392
+ await markJobSkipped({
1393
+ id: videoId,
1394
+ jobKey,
1395
+ accountUrl: account.url,
1396
+ url: video.url || card.href,
1397
+ title: video.title || card.text || '',
1398
+ type: 'video',
1399
+ duration: video.duration,
1400
+ dir: videoDir,
1401
+ card,
1402
+ }, videoResult.json.reason || '视频时长超过 1 分钟', { crawl: true });
1403
+ continue;
1404
+ }
1405
+ if (!video || !Array.isArray(video.frames) || !video.frames.length) {
1406
+ failures.push({ id: videoId, url: card.href, reason: '没有视频关键帧' });
1407
+ await markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title }, '没有视频关键帧');
1408
+ continue;
1409
+ }
1410
+ await updateJob(jobStore.db, jobKey, {
1411
+ crawl_status: 'crawled',
1412
+ title: video.title || '',
1413
+ work_url: video.url || card.href,
1414
+ dir_rel: dirRel,
1415
+ error: '',
1416
+ });
1417
+ } else {
1418
+ await updateJob(jobStore.db, jobKey, {
1419
+ crawl_status: 'crawled',
1420
+ analysis_status: 'pending',
1421
+ dir_rel: dirRel,
1422
+ title: video.title || '',
1423
+ work_url: video.url || card.href,
1424
+ error: '',
1425
+ });
1426
+ }
1427
+
1031
1428
  processedWorks += 1;
1032
1429
  video.account_url = account.url;
1033
- const target = path.join(videoDir, 'materials.jsonl');
1034
- taskList.advance(4);
1035
- taskList.progress(`LLM 判断视频前 5 秒(${video.title || videoId})`);
1430
+ if (taskList.index < 4) taskList.advance(4);
1431
+ taskList.progress(`分析素材(视频前 5 秒筛选:${video.title || videoId})`);
1036
1432
  const relevance = await analyzeVideoRelevance(ctx, invocation, session, {
1037
1433
  root,
1038
1434
  accountUrl: account.url,
@@ -1043,34 +1439,34 @@ async function runCrawl(ctx, invocation, session, taskList) {
1043
1439
  if (!relevance.ok) {
1044
1440
  failures.push({ id: videoId, url: card.href, reason: relevance.error });
1045
1441
  if (relevance.aborted) { aborted = true; break outer; }
1046
- markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
1442
+ await markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
1047
1443
  continue;
1048
1444
  }
1049
1445
  if (relevance.skip) {
1050
1446
  skippedIrrelevant += 1;
1051
- markCrawled(root, videoId, {
1052
- account_url: account.url,
1447
+ await markJobSkipped({
1448
+ id: videoId,
1449
+ jobKey,
1450
+ accountUrl: account.url,
1053
1451
  url: video.url || card.href,
1054
1452
  title: video.title || card.text || '',
1055
1453
  type: 'video',
1056
1454
  duration: video.duration,
1057
1455
  dir: videoDir,
1058
- inserted: 0,
1059
- skipped: 0,
1060
- skip: true,
1061
- reason: relevance.reason || '前 5 秒与网文创作无关',
1062
- });
1063
- crawled[videoId] = true;
1456
+ card,
1457
+ }, relevance.reason || '前 5 秒与网文创作无关');
1064
1458
  continue;
1065
1459
  }
1066
1460
 
1067
- jobs.push({
1461
+ await enqueueJob({
1068
1462
  type: 'video',
1069
1463
  id: videoId,
1464
+ jobKey,
1070
1465
  card,
1071
1466
  accountUrl: account.url,
1072
1467
  url: video.url || card.href,
1073
1468
  dir: videoDir,
1469
+ dirRel,
1074
1470
  video,
1075
1471
  target,
1076
1472
  title: video.title,
@@ -1087,44 +1483,106 @@ async function runCrawl(ctx, invocation, session, taskList) {
1087
1483
  if (abortRequested(invocation)) { aborted = true; break outer; }
1088
1484
  const articleId = noteIdFromUrl(card.href);
1089
1485
  if (!articleId) continue;
1090
- if (crawled[articleId] || queued.has(articleId)) {
1486
+ const existing = existingJobs.get(String(articleId)) || null;
1487
+ if (existing && existing.import_status !== 'pending') {
1091
1488
  skippedArticles += 1;
1092
1489
  continue;
1093
1490
  }
1094
- const articleDir = path.join(accountDir, articleId);
1095
- const articleResult = await runWithLogin(
1096
- ctx, invocation, session, root, tools.scripts.article,
1097
- ['--workspace', root, '--article', card.href, '--cdp', browser.cdp,
1098
- '--out', articleDir, '--login-state', paths.loginState],
1099
- articleDir,
1100
- paths,
1101
- '采集文章',
1102
- tools.nodePath,
1103
- browser,
1104
- tools,
1105
- );
1106
- if (!articleResult.ok) {
1107
- failures.push({ id: articleId, url: card.href, reason: articleResult.error });
1108
- if (articleResult.cancelled || authFailureText(articleResult.error)) { aborted = true; break outer; }
1109
- markFailed(articleId, card, { type: 'article', dir: articleDir }, articleResult.error);
1491
+ if ((!existing && crawled[articleId]) || queued.has(articleId)) {
1492
+ skippedArticles += 1;
1110
1493
  continue;
1111
1494
  }
1112
- const article = articleResult.json.article || {};
1113
- if (!article || !article.body || String(article.body).trim().length < 50) {
1114
- failures.push({ id: articleId, url: card.href, reason: '文章正文为空' });
1115
- markFailed(articleId, card, { type: 'article', dir: articleDir, title: article.title }, '文章正文为空');
1495
+
1496
+ const dirRel = existing && existing.dir_rel ? existing.dir_rel : jobRelDir(account.url, articleId);
1497
+ const articleDir = path.join(paths.jobs, dirRel);
1498
+ const jobKey = await ensureJob(articleId, 'article', card, dirRel, existing && existing.title);
1499
+ const target = path.join(articleDir, 'materials.jsonl');
1500
+
1501
+ if (materialFileReady(articleDir)) {
1502
+ processedWorks += 1;
1503
+ await enqueueJob({
1504
+ type: 'article',
1505
+ id: articleId,
1506
+ jobKey,
1507
+ card,
1508
+ accountUrl: account.url,
1509
+ url: (existing && existing.work_url) || card.href,
1510
+ dir: articleDir,
1511
+ dirRel,
1512
+ target,
1513
+ title: (existing && existing.title) || card.text || '',
1514
+ article: null,
1515
+ finalizeOnly: true,
1516
+ });
1517
+ queued.add(articleId);
1518
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1519
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1520
+ await sleep(delay);
1521
+ }
1116
1522
  continue;
1117
1523
  }
1524
+
1525
+ let article = reusableArticle(articleDir);
1526
+ if (!article) {
1527
+ await updateJob(jobStore.db, jobKey, {
1528
+ crawl_status: 'crawling',
1529
+ analysis_status: 'pending',
1530
+ dir_rel: dirRel,
1531
+ attempts: (Number(existing && existing.attempts) || 0) + 1,
1532
+ error: '',
1533
+ });
1534
+ const articleResult = await runWithLogin(
1535
+ ctx, invocation, session, root, tools.scripts.article,
1536
+ ['--workspace', root, '--article', card.href, '--cdp', browser.cdp,
1537
+ '--out', articleDir, '--login-state', paths.loginState],
1538
+ articleDir,
1539
+ paths,
1540
+ '采集文章',
1541
+ tools.nodePath,
1542
+ browser,
1543
+ tools,
1544
+ );
1545
+ if (!articleResult.ok) {
1546
+ failures.push({ id: articleId, url: card.href, reason: articleResult.error });
1547
+ if (articleResult.cancelled || authFailureText(articleResult.error)) { aborted = true; break outer; }
1548
+ await markFailed(articleId, card, { type: 'article', dir: articleDir }, articleResult.error);
1549
+ continue;
1550
+ }
1551
+ article = articleResult.json.article || {};
1552
+ if (!article || !article.body || String(article.body).trim().length < 50) {
1553
+ failures.push({ id: articleId, url: card.href, reason: '文章正文为空' });
1554
+ await markFailed(articleId, card, { type: 'article', dir: articleDir, title: article.title }, '文章正文为空');
1555
+ continue;
1556
+ }
1557
+ await updateJob(jobStore.db, jobKey, {
1558
+ crawl_status: 'crawled',
1559
+ title: article.title || '',
1560
+ work_url: article.url || card.href,
1561
+ dir_rel: dirRel,
1562
+ error: '',
1563
+ });
1564
+ } else {
1565
+ await updateJob(jobStore.db, jobKey, {
1566
+ crawl_status: 'crawled',
1567
+ analysis_status: 'pending',
1568
+ dir_rel: dirRel,
1569
+ title: article.title || '',
1570
+ work_url: article.url || card.href,
1571
+ error: '',
1572
+ });
1573
+ }
1574
+
1118
1575
  processedWorks += 1;
1119
1576
  article.account_url = account.url;
1120
- const target = path.join(articleDir, 'materials.jsonl');
1121
- jobs.push({
1577
+ await enqueueJob({
1122
1578
  type: 'article',
1123
1579
  id: articleId,
1580
+ jobKey,
1124
1581
  card,
1125
1582
  accountUrl: account.url,
1126
1583
  url: article.url || card.href,
1127
1584
  dir: articleDir,
1585
+ dirRel,
1128
1586
  article,
1129
1587
  target,
1130
1588
  title: article.title,
@@ -1137,115 +1595,22 @@ async function runCrawl(ctx, invocation, session, taskList) {
1137
1595
  }
1138
1596
  }
1139
1597
 
1140
- if (jobs.length) {
1598
+ if (queue) {
1599
+ queue.close();
1600
+ await Promise.all(workerPromises);
1601
+ } else if (jobs.length) {
1141
1602
  taskList.advance(4);
1142
- let finishedJobs = 0;
1143
- const progressText = () => useSubagents
1144
- ? `子 Agent 并行分析(${finishedJobs}/${jobs.length})`
1145
- : `LLM 整理素材(${finishedJobs}/${jobs.length})`;
1146
1603
  taskList.progress(progressText());
1147
-
1148
- const finalizeJob = async (job, analyzed) => {
1149
- await withStateLock(async () => {
1150
- if (analyzed && analyzed.needsFinalize) {
1151
- analyzed = await finalizeMaterialFile({
1152
- root,
1153
- target: job.target,
1154
- title: job.title,
1155
- materialTools,
1156
- });
1157
- }
1158
- if (analyzed && analyzed.aborted) {
1159
- aborted = true;
1160
- return;
1161
- }
1162
- if (!analyzed || !analyzed.ok) {
1163
- const reason = (analyzed && (analyzed.error || analyzed.detail)) || '素材没有通过校验';
1164
- failures.push({ id: job.id, url: job.url, reason });
1165
- markJobFailed(job, reason);
1166
- return;
1167
- }
1168
- if (analyzed.skipped) {
1169
- skippedIrrelevant += 1;
1170
- markCrawled(root, job.id, {
1171
- account_url: job.accountUrl,
1172
- url: job.url,
1173
- title: job.title || (job.card && job.card.text) || '',
1174
- type: job.type,
1175
- duration: job.duration,
1176
- screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1177
- ? job.screenshots.map((shot) => shot.file)
1178
- : undefined,
1179
- body_file: job.article && job.article.body_file,
1180
- reading_time: job.article && job.article.reading_time,
1181
- body_length: job.article && job.article.body_length,
1182
- dir: job.dir,
1183
- inserted: 0,
1184
- skipped: 0,
1185
- skip: true,
1186
- reason: analyzed.reason || '与网文创作无关',
1187
- });
1188
- } else {
1189
- inserted += analyzed.inserted || 0;
1190
- skippedMaterials += analyzed.skipped || 0;
1191
- markCrawled(root, job.id, {
1192
- account_url: job.accountUrl,
1193
- url: job.url,
1194
- title: job.title || (job.card && job.card.text) || '',
1195
- type: job.type,
1196
- duration: job.duration,
1197
- screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1198
- ? job.screenshots.map((shot) => shot.file)
1199
- : undefined,
1200
- body_file: job.article && job.article.body_file,
1201
- reading_time: job.article && job.article.reading_time,
1202
- body_length: job.article && job.article.body_length,
1203
- dir: job.dir,
1204
- inserted: analyzed.inserted || 0,
1205
- skipped: analyzed.skipped || 0,
1206
- });
1207
- }
1208
- crawled[job.id] = true;
1209
- finishedJobs += 1;
1210
- taskList.progress(progressText());
1211
- });
1212
- };
1213
-
1214
- if (useSubagents) {
1215
- taskList.progress(`子 Agent 并行分析(0/${jobs.length},并发 ${subagentWorkers})`);
1216
- await runJobPool(jobs, subagentWorkers, async (job) => {
1217
- if (abortRequested(invocation)) { aborted = true; return; }
1218
- let analyzed;
1219
- try {
1220
- analyzed = await runSubagentAnalysisJob({
1221
- subagents: subagentRuntime,
1222
- provider: 'spawn',
1223
- invocation,
1224
- job,
1225
- root,
1226
- materialTools,
1227
- signal: jobSignal,
1228
- });
1229
- } catch (err) {
1230
- analyzed = {
1231
- ok: false,
1232
- error: '子 Agent 分析失败:' + (err && err.message ? err.message : String(err)),
1233
- };
1234
- }
1235
- await finalizeJob(job, analyzed);
1604
+ for (const job of jobs) {
1605
+ if (abortRequested(invocation)) { aborted = true; break; }
1606
+ const analyzed = await runLocalAnalysisJob(ctx, invocation, session, job, {
1607
+ root,
1608
+ materialTools,
1609
+ paths,
1610
+ taskList,
1236
1611
  });
1237
- } else {
1238
- for (const job of jobs) {
1239
- if (abortRequested(invocation)) { aborted = true; break; }
1240
- const analyzed = await runLocalAnalysisJob(ctx, invocation, session, job, {
1241
- root,
1242
- materialTools,
1243
- paths,
1244
- taskList,
1245
- });
1246
- await finalizeJob(job, analyzed);
1247
- if (analyzed && analyzed.fatal) { aborted = true; break; }
1248
- }
1612
+ await finalizeJob(job, analyzed);
1613
+ if (analyzed && analyzed.fatal) { aborted = true; break; }
1249
1614
  }
1250
1615
  }
1251
1616
 
@@ -1274,7 +1639,12 @@ async function runCrawl(ctx, invocation, session, taskList) {
1274
1639
  subagentWorkers,
1275
1640
  }));
1276
1641
  } finally {
1642
+ if (queue) {
1643
+ queue.close();
1644
+ await Promise.allSettled(workerPromises);
1645
+ }
1277
1646
  await stopChrome(root, tools, paths);
1647
+ if (jobStore) await jobStore.close();
1278
1648
  }
1279
1649
  }
1280
1650
 
@@ -1296,7 +1666,17 @@ async function runAdd(session, rawUrl) {
1296
1666
 
1297
1667
  async function runList(session) {
1298
1668
  const root = workspaceOf(session);
1299
- return notify(session, 'success', accountListText(root));
1669
+ let counts = null;
1670
+ try {
1671
+ const store = await openJobStore(root);
1672
+ try {
1673
+ await migrateCrawledJobs(store.db, root);
1674
+ counts = await countJobsByAccount(store.db);
1675
+ } finally {
1676
+ await store.close();
1677
+ }
1678
+ } catch { /* fall back to local crawled.json */ }
1679
+ return notify(session, 'success', accountListText(root, counts));
1300
1680
  }
1301
1681
 
1302
1682
  async function runRemove(session, selector, taskList) {
@@ -1322,7 +1702,7 @@ function douyinTaskTitles(invocation) {
1322
1702
  'LLM 能力自检(图片 / 视频)',
1323
1703
  '扫描账号主页',
1324
1704
  '采集图文 / 视频 / 文章作品',
1325
- '分析作品素材',
1705
+ '分析素材',
1326
1706
  '写入素材库',
1327
1707
  ];
1328
1708
  }