@cloud411716/fancy-webnovel 4.16.3 → 4.17.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.
@@ -90,7 +90,7 @@ cookies 会额外镜像到:
90
90
 
91
91
  ```text
92
92
  <工作区>/.fancy/douyin/
93
- ├── accounts.json # 账号主页记录(含账号名、抖音号、sec_uid、最近扫描时间)
93
+ ├── accounts.json # 旧版账号文件;首次运行会迁移到 douyin_account 表
94
94
  ├── crawled.json # 旧版本地记录,仅用于一次性迁移/备份
95
95
  ├── jobs/<账号>/<作品ID>/ # 稳定任务目录,重启后复用
96
96
  ├── login-state.json # cookies 镜像(0600)
@@ -183,7 +183,9 @@ id / kind / subkind / name / tags / genres / note / source
183
183
 
184
184
  ## 任务状态与恢复
185
185
 
186
- 素材库 schema v11 新增多层素材 facet,并保留 `douyin_job` 和 `douyin_meta` 任务表。任务状态与素材在同一个数据库里,备份/迁移整个素材库时会一起带走。
186
+ 素材库 schema v12 新增 `douyin_account` 账号表;schema v11 新增多层素材 facet,并保留 `douyin_job` 和 `douyin_meta` 任务表。账号、任务状态与素材在同一个数据库里,备份/迁移整个素材库时会一起带走。
187
+
188
+ `/fancy-douyin add`、`list`、`remove` 现在直接读写 `douyin_account`。旧 `accounts.json` 只在首次运行时迁移一次,之后不再作为运行时状态源。
187
189
 
188
190
  - `crawl_status`:pending / crawling / crawled / failed
189
191
  - `analysis_status`:pending / analyzing / analyzed / failed
@@ -355,7 +355,7 @@ node plugins/fancy-material/scripts/query.js \
355
355
  | `material_kind_name_unique` | `kind, name` | 防止同名同类型重复 |
356
356
  | `material_name_search` | `name` | 中文 ngram 全文检索 |
357
357
 
358
- 素材库 schema v11 还包含 `douyin_job` 表,用于记录抖音作品的采集/分析/导入状态;它和素材在同一个数据库里,完整备份/迁移素材库时会一起带走。`douyin_meta` 保存一次性迁移标记。
358
+ 素材库 schema v12 还包含 `douyin_account` 账号表和 `douyin_job` 任务表;账号、作品采集/分析/导入状态和素材在同一个数据库里,完整备份/迁移素材库时会一起带走。`douyin_meta` 保存一次性迁移标记。
359
359
 
360
360
  中文全文检索:
361
361
 
@@ -1,4 +1,4 @@
1
- -- 网文创作素材库 · 原子素材 schema v11(SurrealDB 2.3+)
1
+ -- 网文创作素材库 · 原子素材 schema v12(SurrealDB 2.3+)
2
2
  -- 用法:
3
3
  -- surreal sql --endpoint http://127.0.0.1:8000 --user root --pass ... \
4
4
  -- --namespace fancy --database material_library --multi < schema.surql
@@ -67,6 +67,27 @@ DEFINE INDEX IF NOT EXISTS material_name_search
67
67
  SEARCH ANALYZER material_zh
68
68
  BM25(1.2, 0.75);
69
69
 
70
+ -- ---------------------------------------------------------------------------
71
+ -- 抖音账号(v12)
72
+ --
73
+ -- 账号原来是 .fancy/douyin/accounts.json;放进素材库后,备份/迁移素材库
74
+ -- 会同时带走账号列表,不需要重新执行 add。
75
+ -- ---------------------------------------------------------------------------
76
+ DEFINE TABLE IF NOT EXISTS douyin_account SCHEMAFULL;
77
+
78
+ DEFINE FIELD OVERWRITE account_url ON douyin_account TYPE string;
79
+ DEFINE FIELD OVERWRITE added_at ON douyin_account TYPE datetime DEFAULT time::now();
80
+ DEFINE FIELD OVERWRITE name ON douyin_account TYPE option<string>;
81
+ DEFINE FIELD OVERWRITE douyin_id ON douyin_account TYPE option<string>;
82
+ DEFINE FIELD OVERWRITE sec_uid ON douyin_account TYPE option<string>;
83
+ DEFINE FIELD OVERWRITE last_scan_at ON douyin_account TYPE option<datetime>;
84
+ DEFINE FIELD OVERWRITE updated_at ON douyin_account TYPE datetime VALUE time::now();
85
+
86
+ DEFINE INDEX IF NOT EXISTS douyin_account_url_unique ON douyin_account FIELDS account_url UNIQUE;
87
+ DEFINE INDEX IF NOT EXISTS douyin_account_added_at ON douyin_account FIELDS added_at;
88
+
89
+ ALTER TABLE douyin_account PERMISSIONS FOR select, create, update, delete FULL;
90
+
70
91
  -- ---------------------------------------------------------------------------
71
92
  -- 抖音作品任务状态(v10 引入,v11 保留)
72
93
  --
@@ -17,7 +17,7 @@ import { readSecrets, readWorkspace } from './workspace.js';
17
17
  import { rpcUrl, startServer } from './surreal-server.js';
18
18
 
19
19
  export const MATERIAL_DATABASE = 'material_library';
20
- export const MATERIAL_SCHEMA_VERSION = 11;
20
+ export const MATERIAL_SCHEMA_VERSION = 12;
21
21
 
22
22
  const SCHEMA_FILE = fileURLToPath(new URL('../docs/material-library/schema.surql', import.meta.url));
23
23
 
@@ -61,7 +61,7 @@ export async function connectMaterial(root) {
61
61
  /**
62
62
  * Ensure the material database and its schema exist. Idempotent.
63
63
  *
64
- * Schema v11 adds the multi-layer material facets (`subject`, `tropes`, `narrative`, `traits`, `roles`, `relations`, `moods`, `settings`) and keeps the v10 douyin task tables / v9 subkind / v8 note assertion / v7 group_id / 58-kind catalog. Before applying the
64
+ * Schema v12 adds the douyin_account table; v11 adds the multi-layer material facets (`subject`, `tropes`, `narrative`, `traits`, `roles`, `relations`, `moods`, `settings`) and keeps the v10 douyin task tables / v9 subkind / v8 note assertion / v7 group_id / 58-kind catalog. Before applying the
65
65
  * new ASSERT, rows belonging to retired kinds are removed; otherwise SurrealDB
66
66
  * refuses to overwrite the field because existing records no longer conform.
67
67
  *
@@ -111,6 +111,11 @@ export async function ensureMaterialDatabase(root) {
111
111
  if (!jobTable.fields || !jobTable.fields.job_key || !jobTable.fields.crawl_status || !jobTable.fields.analysis_status || !jobTable.fields.import_status) {
112
112
  throw new Error('素材库 schema 初始化后仍未找到 douyin_job 任务状态字段。');
113
113
  }
114
+ const accountInfo = await db.query('INFO FOR TABLE douyin_account;');
115
+ const accountTable = Array.isArray(accountInfo) && accountInfo[0] ? accountInfo[0] : {};
116
+ if (!accountTable.fields || !accountTable.fields.account_url || !accountTable.fields.added_at) {
117
+ throw new Error('素材库 schema 初始化后仍未找到 douyin_account 账号字段。');
118
+ }
114
119
  return {
115
120
  ok: true,
116
121
  namespace,
@@ -152,8 +157,22 @@ export async function removeMaterialDatabase(root) {
152
157
  password: secrets.surreal?.password,
153
158
  });
154
159
  await db.use({ namespace, database: registry });
155
- await db.query('REMOVE DATABASE IF EXISTS ' + database + ';');
156
- return { removed: true, database };
160
+ let lastError = null;
161
+ const delays = [0, 1000, 2500, 5000];
162
+ for (const delay of delays) {
163
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
164
+ try {
165
+ await db.query('REMOVE DATABASE IF EXISTS ' + database + ';');
166
+ return { removed: true, database };
167
+ } catch (err) {
168
+ const message = err && err.message ? err.message : String(err);
169
+ const retryable = /read or write conflict|transaction can be retried|failed to commit transaction/i.test(message);
170
+ if (!retryable) throw err;
171
+ lastError = err;
172
+ }
173
+ }
174
+ throw new Error('素材库删除时数据库事务冲突,可能有其他素材/抖音任务正在读写。请等任务结束后重试。原始错误:'
175
+ + (lastError && lastError.message ? lastError.message : String(lastError)));
157
176
  } finally {
158
177
  try { await db.close(); } catch { /* ignore */ }
159
178
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.16.3",
3
+ "version": "4.17.1",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -304,7 +304,7 @@ export async function apply(ctx) {
304
304
  formatWorkspace(result.workspace),
305
305
  '',
306
306
  '数据库:schema ' + result.schema_version + ' · validation ' + result.validation_version,
307
- '素材库:' + (result.material?.database || 'material_library') + '(schema ' + (result.material?.schema_version || 11) + ')',
307
+ '素材库:' + (result.material?.database || 'material_library') + '(schema ' + (result.material?.schema_version || 12) + ')',
308
308
  '服务:' + (result.server.running ? '运行中' : '未运行'),
309
309
  ...(result.started && result.started.endpoint_changed
310
310
  ? ['⚠️ 原端口被另一个 SurrealDB 占用,已改用:' + result.started.endpoint]
@@ -151,7 +151,7 @@ export async function apply(ctx) {
151
151
  '✅ 工作区数据库初始化完成',
152
152
  '服务:' + (result.server.running ? '运行中' : '未运行'),
153
153
  'schema:' + result.schema_version + ' validation:' + result.validation_version,
154
- '素材库:' + (result.material?.database || 'material_library') + '(schema ' + (result.material?.schema_version || 11) + ')',
154
+ '素材库:' + (result.material?.database || 'material_library') + '(schema ' + (result.material?.schema_version || 12) + ')',
155
155
  '项目库:' + result.projects.length + ' 个' + (failed.length ? ',失败 ' + failed.length + ' 个' : ''),
156
156
  ...failed.map((f) => '❌ ' + f.project.name + ':' + f.error),
157
157
  ].join('\n'));
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Douyin account state stored in the material database.
3
+ *
4
+ * Accounts used to live in `.fancy/douyin/accounts.json`. Keeping them in the
5
+ * material database means a material-library backup/restore also carries the
6
+ * account list. The old JSON file remains only as a one-time migration source.
7
+ */
8
+
9
+ import { RecordId } from 'surrealdb';
10
+
11
+ import { accountSlug, normalizeAccountUrl, readAccounts as readLegacyAccounts } from './state.js';
12
+
13
+ export const ACCOUNT_TABLE = 'douyin_account';
14
+ export const ACCOUNT_META_KEY = 'accounts_migrated';
15
+
16
+ function firstRows(result) {
17
+ return Array.isArray(result) && Array.isArray(result[0]) ? result[0] : [];
18
+ }
19
+
20
+ function asDate(value, fallback = new Date()) {
21
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value;
22
+ const parsed = value ? new Date(value) : fallback;
23
+ return Number.isNaN(parsed.getTime()) ? fallback : parsed;
24
+ }
25
+
26
+ function normalizeAccount(row) {
27
+ return {
28
+ id: row.id ? String(row.id) : '',
29
+ url: String(row.account_url || ''),
30
+ added_at: row.added_at instanceof Date ? row.added_at.toISOString() : String(row.added_at || ''),
31
+ name: typeof row.name === 'string' ? row.name : '',
32
+ douyin_id: typeof row.douyin_id === 'string' ? row.douyin_id : '',
33
+ sec_uid: typeof row.sec_uid === 'string' ? row.sec_uid : '',
34
+ last_scan_at: row.last_scan_at instanceof Date
35
+ ? row.last_scan_at.toISOString()
36
+ : String(row.last_scan_at || ''),
37
+ };
38
+ }
39
+
40
+ async function getMeta(db, key) {
41
+ const rows = firstRows(await db.query('SELECT meta_value FROM douyin_meta WHERE meta_key = $key LIMIT 1;', { key }));
42
+ return rows[0] ? String(rows[0].meta_value || '') : '';
43
+ }
44
+
45
+ async function setMeta(db, key, value) {
46
+ await db.upsert(new RecordId('douyin_meta', key)).content({
47
+ meta_key: key,
48
+ meta_value: String(value),
49
+ updated_at: new Date(),
50
+ });
51
+ }
52
+
53
+ export async function findAccount(db, url) {
54
+ const rows = firstRows(await db.query(
55
+ 'SELECT * FROM douyin_account WHERE account_url = $url LIMIT 1;',
56
+ { url },
57
+ ));
58
+ return rows[0] ? normalizeAccount(rows[0]) : null;
59
+ }
60
+
61
+ export async function listAccounts(db) {
62
+ const rows = firstRows(await db.query(
63
+ 'SELECT * FROM douyin_account ORDER BY added_at, account_url;',
64
+ ));
65
+ return rows.map(normalizeAccount).filter((item) => item.url);
66
+ }
67
+
68
+ function accountRecord(account) {
69
+ return {
70
+ account_url: account.url,
71
+ added_at: asDate(account.added_at),
72
+ ...(account.name ? { name: String(account.name) } : {}),
73
+ ...(account.douyin_id ? { douyin_id: String(account.douyin_id) } : {}),
74
+ ...(account.sec_uid ? { sec_uid: String(account.sec_uid) } : {}),
75
+ ...(account.last_scan_at ? { last_scan_at: asDate(account.last_scan_at) } : {}),
76
+ updated_at: new Date(),
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Import the legacy accounts.json once, then mark it migrated.
82
+ * Existing DB rows win; account URLs are unique.
83
+ */
84
+ export async function migrateAccounts(db, root) {
85
+ if (await getMeta(db, ACCOUNT_META_KEY) === '1') return { migrated: 0 };
86
+ let migrated = 0;
87
+ for (const account of readLegacyAccounts(root)) {
88
+ if (await findAccount(db, account.url)) continue;
89
+ await db.create(new RecordId(ACCOUNT_TABLE, accountSlug(account.url)))
90
+ .content(accountRecord(account));
91
+ migrated += 1;
92
+ }
93
+ await setMeta(db, ACCOUNT_META_KEY, '1');
94
+ return { migrated };
95
+ }
96
+
97
+ /**
98
+ * @param {object} db material database connection
99
+ * @param {string} root workspace directory
100
+ * @param {string} rawUrl Douyin homepage URL
101
+ * @returns {Promise<{added: boolean, url: string, accounts: Array}>}
102
+ */
103
+ export async function addAccount(db, root, rawUrl) {
104
+ await migrateAccounts(db, root);
105
+ const url = normalizeAccountUrl(rawUrl);
106
+ const existing = await findAccount(db, url);
107
+ if (existing) {
108
+ return { added: false, url, accounts: await listAccounts(db) };
109
+ }
110
+ await db.create(new RecordId(ACCOUNT_TABLE, accountSlug(url))).content(accountRecord({
111
+ url,
112
+ added_at: new Date(),
113
+ }));
114
+ return { added: true, url, accounts: await listAccounts(db) };
115
+ }
116
+
117
+ export async function updateAccountProfile(db, root, url, profile) {
118
+ await migrateAccounts(db, root);
119
+ const account = await findAccount(db, url);
120
+ if (!account || !account.id) return null;
121
+ const patch = {
122
+ last_scan_at: new Date(),
123
+ updated_at: new Date(),
124
+ ...(profile && typeof profile.name === 'string' && profile.name.trim() ? { name: profile.name.trim() } : {}),
125
+ ...(profile && typeof profile.douyin_id === 'string' && profile.douyin_id.trim() ? { douyin_id: profile.douyin_id.trim() } : {}),
126
+ ...(profile && typeof profile.sec_uid === 'string' && profile.sec_uid.trim() ? { sec_uid: profile.sec_uid.trim() } : {}),
127
+ };
128
+ await db.upsert(new RecordId(ACCOUNT_TABLE, accountSlug(url))).merge(patch);
129
+ return findAccount(db, url);
130
+ }
131
+
132
+ export async function removeAccount(db, root, selector) {
133
+ await migrateAccounts(db, root);
134
+ const accounts = await listAccounts(db);
135
+ const text = String(selector || '').trim();
136
+ if (!text) throw new Error('缺少要删除的账号序号或主页地址');
137
+ let index = -1;
138
+ if (/^\d+$/.test(text)) {
139
+ index = Number(text) - 1;
140
+ } else {
141
+ const url = normalizeAccountUrl(text);
142
+ index = accounts.findIndex((item) => item.url === url);
143
+ }
144
+ if (index < 0 || index >= accounts.length) {
145
+ throw new Error('没有找到要删除的账号:' + selector);
146
+ }
147
+ const removed = accounts[index];
148
+ await db.delete(new RecordId(ACCOUNT_TABLE, accountSlug(removed.url)));
149
+ return { removed: true, url: removed.url, accounts: await listAccounts(db) };
150
+ }
@@ -24,16 +24,19 @@ import { deployDouyinTools } from './deploy.js';
24
24
  import {
25
25
  accountListText,
26
26
  accountSlug,
27
- addAccount,
28
27
  douyinPaths,
29
28
  ensureDouyinDir,
30
29
  markCrawled,
31
30
  noteIdFromUrl,
32
- readAccounts,
33
31
  readCrawled,
32
+ } from './state.js';
33
+ import {
34
+ addAccount,
35
+ listAccounts,
36
+ migrateAccounts,
34
37
  removeAccount,
35
38
  updateAccountProfile,
36
- } from './state.js';
39
+ } from './accounts.js';
37
40
  import { analysisPrompt, articlePrompt, capabilityPrompt, helpText, loginQuestion, summaryText, videoAnalysisPrompt, videoRelevancePrompt } from './templates.js';
38
41
  import { createJobQueue, createSerialLock, getSubagentRuntime, subagentWorkerCount } from './subagents.js';
39
42
  import {
@@ -905,8 +908,27 @@ function materialFileReady(dir) {
905
908
  async function runCrawl(ctx, invocation, session, taskList) {
906
909
  const root = workspaceOf(session);
907
910
  const paths = ensureDouyinDir(root);
908
- const accounts = readAccounts(root);
911
+
912
+ let jobStore;
913
+ try {
914
+ await ensureMaterialDatabase(root);
915
+ jobStore = await openJobStore(root);
916
+ await migrateAccounts(jobStore.db, root);
917
+ } catch (err) {
918
+ if (jobStore) await jobStore.close();
919
+ return notify(session, 'error', '❌ 初始化抖音账号/任务状态表失败:'
920
+ + (err && err.message ? err.message : String(err)));
921
+ }
922
+ let accounts;
923
+ try {
924
+ accounts = await listAccounts(jobStore.db);
925
+ } catch (err) {
926
+ await jobStore.close();
927
+ return notify(session, 'error', '❌ 读取抖音账号失败:'
928
+ + (err && err.message ? err.message : String(err)));
929
+ }
909
930
  if (!accounts.length) {
931
+ await jobStore.close();
910
932
  return notify(session, 'error', '还没有记录抖音账号。先运行:/fancy-douyin add <主页地址>');
911
933
  }
912
934
 
@@ -933,6 +955,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
933
955
  signal: jobSignal,
934
956
  });
935
957
  if (!capabilities.ok) {
958
+ await jobStore.close();
936
959
  return notify(session, 'error', '❌ LLM 能力自检失败:' + capabilities.error);
937
960
  }
938
961
  if (!capabilities.image_supported && !capabilities.video_supported) {
@@ -942,22 +965,21 @@ async function runCrawl(ctx, invocation, session, taskList) {
942
965
 
943
966
  const tools = deployDouyinTools(root);
944
967
  if (!tools.ok) {
968
+ await jobStore.close();
945
969
  return notify(session, 'error', '❌ 部署抖音脚本失败:\n' + (tools.problems.join('\n') || '未知错误'));
946
970
  }
947
- await ensureMaterialDatabase(root);
948
971
  const materialTools = deployMaterialTools(root);
949
972
  if (!materialTools.ok) {
973
+ await jobStore.close();
950
974
  return notify(session, 'error', '❌ 部署素材校验脚本失败:\n' + (materialTools.problems.join('\n') || '未知错误'));
951
975
  }
952
976
 
953
- let jobStore;
954
977
  let queue = null;
955
978
  let workerPromises = [];
956
979
  try {
957
- jobStore = await openJobStore(root);
958
- await migrateCrawledJobs(jobStore.db, root);
980
+ await migrateCrawledJobs(jobStore.db, root, accounts);
959
981
  } catch (err) {
960
- if (jobStore) await jobStore.close();
982
+ await jobStore.close();
961
983
  return notify(session, 'error', '❌ 初始化抖音任务状态表失败:' + (err && err.message ? err.message : String(err)));
962
984
  }
963
985
 
@@ -1255,7 +1277,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
1255
1277
 
1256
1278
  scannedAccounts += 1;
1257
1279
  if (scan.json.profile) {
1258
- updateAccountProfile(root, account.url, scan.json.profile);
1280
+ await updateAccountProfile(jobStore.db, root, account.url, scan.json.profile);
1259
1281
  account.name = scan.json.profile.name || account.name || '';
1260
1282
  account.douyin_id = scan.json.profile.douyin_id || account.douyin_id || '';
1261
1283
  account.sec_uid = scan.json.profile.sec_uid || account.sec_uid || '';
@@ -1778,14 +1800,21 @@ async function runCrawl(ctx, invocation, session, taskList) {
1778
1800
  async function runAdd(session, rawUrl) {
1779
1801
  const root = workspaceOf(session);
1780
1802
  try {
1781
- const result = addAccount(root, rawUrl);
1782
- if (!result.added) {
1783
- return notify(session, 'success', '账号已存在:' + result.url);
1803
+ await ensureMaterialDatabase(root);
1804
+ const store = await openJobStore(root);
1805
+ try {
1806
+ await migrateAccounts(store.db, root);
1807
+ const result = await addAccount(store.db, root, rawUrl);
1808
+ if (!result.added) {
1809
+ return notify(session, 'success', '账号已存在:' + result.url);
1810
+ }
1811
+ return notify(session, 'success', [
1812
+ '✅ 已添加抖音账号:' + result.url,
1813
+ '运行 /fancy-douyin 开始采集。',
1814
+ ].join('\n'));
1815
+ } finally {
1816
+ await store.close();
1784
1817
  }
1785
- return notify(session, 'success', [
1786
- '✅ 已添加抖音账号:' + result.url,
1787
- '运行 /fancy-douyin 开始采集。',
1788
- ].join('\n'));
1789
1818
  } catch (err) {
1790
1819
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
1791
1820
  }
@@ -1795,23 +1824,34 @@ async function runList(session) {
1795
1824
  const root = workspaceOf(session);
1796
1825
  let counts = null;
1797
1826
  try {
1827
+ await ensureMaterialDatabase(root);
1798
1828
  const store = await openJobStore(root);
1799
1829
  try {
1800
- await migrateCrawledJobs(store.db, root);
1830
+ await migrateAccounts(store.db, root);
1831
+ const accounts = await listAccounts(store.db);
1832
+ await migrateCrawledJobs(store.db, root, accounts);
1801
1833
  counts = await countJobsByAccount(store.db);
1834
+ return notify(session, 'success', accountListText(accounts, counts));
1802
1835
  } finally {
1803
1836
  await store.close();
1804
1837
  }
1805
- } catch { /* fall back to local crawled.json */ }
1838
+ } catch { /* fall back to the legacy accounts.json */ }
1806
1839
  return notify(session, 'success', accountListText(root, counts));
1807
1840
  }
1808
1841
 
1809
1842
  async function runRemove(session, selector, taskList) {
1810
1843
  const root = workspaceOf(session);
1811
1844
  try {
1812
- taskList.advance(1);
1813
- const result = removeAccount(root, selector);
1814
- return notify(session, 'success', '✅ 已删除账号:' + result.url);
1845
+ await ensureMaterialDatabase(root);
1846
+ const store = await openJobStore(root);
1847
+ try {
1848
+ await migrateAccounts(store.db, root);
1849
+ taskList.advance(1);
1850
+ const result = await removeAccount(store.db, root, selector);
1851
+ return notify(session, 'success', '✅ 已删除账号:' + result.url);
1852
+ } finally {
1853
+ await store.close();
1854
+ }
1815
1855
  } catch (err) {
1816
1856
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
1817
1857
  }
@@ -11,7 +11,7 @@ import path from 'path';
11
11
  import { RecordId } from 'surrealdb';
12
12
 
13
13
  import { connectMaterial } from '#material-db';
14
- import { accountSlug, douyinPaths, readAccounts, readCrawled } from './state.js';
14
+ import { accountSlug, douyinPaths, readCrawled } from './state.js';
15
15
 
16
16
  export const JOB_TABLE = 'douyin_job';
17
17
  export const META_TABLE = 'douyin_meta';
@@ -125,10 +125,13 @@ function inferWorkType(record, workId) {
125
125
  * One-time migration from the legacy workspace crawled.json into douyin_job.
126
126
  * Existing database rows win; the marker prevents re-running the migration.
127
127
  */
128
- export async function migrateCrawledJobs(db, root) {
128
+ export async function migrateCrawledJobs(db, root, accountList = null) {
129
129
  if (await getMeta(db, 'crawled_migrated') === '1') return { migrated: 0 };
130
130
  const crawled = readCrawled(root);
131
- const accounts = new Map(readAccounts(root).map((item) => [item.url, item]));
131
+ const rows = accountList || firstRows(await db.query(
132
+ 'SELECT account_url, name, douyin_id, sec_uid FROM douyin_account;',
133
+ ));
134
+ const accounts = new Map(rows.map((item) => [item.account_url || item.url, item]));
132
135
  let migrated = 0;
133
136
  for (const [workId, record] of Object.entries(crawled)) {
134
137
  if (!record || typeof record !== 'object' || !record.account_url) continue;
@@ -90,6 +90,7 @@ export function isNoteUrl(url) {
90
90
  return /\/note\/\d+/.test(String(url || ''));
91
91
  }
92
92
 
93
+ /** Legacy accounts.json reader; runtime reads and writes douyin_account in the material DB. */
93
94
  export function readAccounts(root) {
94
95
  const paths = douyinPaths(root);
95
96
  const value = readJsonFile(paths.accounts);
@@ -205,8 +206,8 @@ export function markCrawled(root, noteId, data) {
205
206
  return state[noteId];
206
207
  }
207
208
 
208
- export function accountListText(root, countsOverride = null) {
209
- const accounts = readAccounts(root);
209
+ export function accountListText(accountsOrRoot, countsOverride = null) {
210
+ const accounts = Array.isArray(accountsOrRoot) ? accountsOrRoot : readAccounts(accountsOrRoot);
210
211
  if (!accounts.length) {
211
212
  return [
212
213
  '还没有记录抖音账号。',
@@ -214,8 +215,8 @@ export function accountListText(root, countsOverride = null) {
214
215
  ].join('\n');
215
216
  }
216
217
  const counts = countsOverride instanceof Map ? countsOverride : new Map();
217
- if (!(countsOverride instanceof Map)) {
218
- const crawled = readCrawled(root);
218
+ if (!(countsOverride instanceof Map) && typeof accountsOrRoot === 'string') {
219
+ const crawled = readCrawled(accountsOrRoot);
219
220
  for (const item of Object.values(crawled)) {
220
221
  if (!item || typeof item !== 'object' || !item.account_url) continue;
221
222
  counts.set(item.account_url, (counts.get(item.account_url) || 0) + 1);