message-router.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. (function attachBackgroundMessageRouter(root, factory) {
  2. root.MultiPageBackgroundMessageRouter = factory();
  3. })(typeof self !== 'undefined' ? self : globalThis, function createBackgroundMessageRouterModule() {
  4. function createMessageRouter(deps = {}) {
  5. const {
  6. addLog,
  7. appendAccountRunRecord,
  8. batchUpdateLuckmailPurchases,
  9. buildLocalhostCleanupPrefix,
  10. buildLuckmailSessionSettingsPayload,
  11. buildPersistentSettingsPayload,
  12. broadcastDataUpdate,
  13. cancelScheduledAutoRun,
  14. checkIcloudSession,
  15. clearAutoRunTimerAlarm,
  16. clearLuckmailRuntimeState,
  17. clearStopRequest,
  18. closeLocalhostCallbackTabs,
  19. closeTabsByUrlPrefix,
  20. deleteHotmailAccount,
  21. deleteHotmailAccounts,
  22. deleteIcloudAlias,
  23. deleteUsedIcloudAliases,
  24. disableUsedLuckmailPurchases,
  25. doesStepUseCompletionSignal,
  26. ensureManualInteractionAllowed,
  27. executeStep,
  28. executeStepViaCompletionSignal,
  29. exportSettingsBundle,
  30. fetchGeneratedEmail,
  31. finalizeIcloudAliasAfterSuccessfulFlow,
  32. findHotmailAccount,
  33. flushCommand,
  34. getCurrentLuckmailPurchase,
  35. getPendingAutoRunTimerPlan,
  36. getSourceLabel,
  37. getState,
  38. getStopRequested,
  39. handleAutoRunLoopUnhandledError,
  40. importSettingsBundle,
  41. invalidateDownstreamAfterStepRestart,
  42. isAutoRunLockedState,
  43. isHotmailProvider,
  44. isLocalhostOAuthCallbackUrl,
  45. isLuckmailProvider,
  46. isStopError,
  47. launchAutoRunTimerPlan,
  48. listIcloudAliases,
  49. listLuckmailPurchasesForManagement,
  50. normalizeHotmailAccounts,
  51. normalizeRunCount,
  52. AUTO_RUN_TIMER_KIND_SCHEDULED_START,
  53. notifyStepComplete,
  54. notifyStepError,
  55. patchHotmailAccount,
  56. registerTab,
  57. requestStop,
  58. resetState,
  59. resumeAutoRun,
  60. scheduleAutoRun,
  61. selectLuckmailPurchase,
  62. setCurrentHotmailAccount,
  63. setEmailState,
  64. setEmailStateSilently,
  65. setIcloudAliasPreservedState,
  66. setIcloudAliasUsedState,
  67. setLuckmailPurchaseDisabledState,
  68. setLuckmailPurchasePreservedState,
  69. setLuckmailPurchaseUsedState,
  70. setPersistentSettings,
  71. setState,
  72. setStepStatus,
  73. skipAutoRunCountdown,
  74. skipStep,
  75. startAutoRunLoop,
  76. syncHotmailAccounts,
  77. testHotmailAccountMailAccess,
  78. upsertHotmailAccount,
  79. verifyHotmailAccount,
  80. } = deps;
  81. async function appendManualAccountRunRecordIfNeeded(status, stateOverride = null, reason = '') {
  82. if (typeof appendAccountRunRecord !== 'function') {
  83. return null;
  84. }
  85. const state = stateOverride || await getState();
  86. if (isAutoRunLockedState(state)) {
  87. return null;
  88. }
  89. return appendAccountRunRecord(status, state, reason);
  90. }
  91. async function handleStepData(step, payload) {
  92. switch (step) {
  93. case 1: {
  94. const updates = {};
  95. if (payload.oauthUrl) {
  96. updates.oauthUrl = payload.oauthUrl;
  97. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  98. }
  99. if (payload.sub2apiSessionId !== undefined) updates.sub2apiSessionId = payload.sub2apiSessionId || null;
  100. if (payload.sub2apiOAuthState !== undefined) updates.sub2apiOAuthState = payload.sub2apiOAuthState || null;
  101. if (payload.sub2apiGroupId !== undefined) updates.sub2apiGroupId = payload.sub2apiGroupId || null;
  102. if (payload.sub2apiDraftName !== undefined) updates.sub2apiDraftName = payload.sub2apiDraftName || null;
  103. if (Object.keys(updates).length) {
  104. await setState(updates);
  105. }
  106. break;
  107. }
  108. case 3:
  109. if (payload.email) await setEmailState(payload.email);
  110. if (payload.signupVerificationRequestedAt) {
  111. await setState({ signupVerificationRequestedAt: payload.signupVerificationRequestedAt });
  112. }
  113. if (payload.loginVerificationRequestedAt) {
  114. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  115. }
  116. break;
  117. case 6:
  118. if (payload.loginVerificationRequestedAt) {
  119. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  120. }
  121. break;
  122. case 4:
  123. await setState({
  124. lastEmailTimestamp: payload.emailTimestamp || null,
  125. signupVerificationRequestedAt: null,
  126. });
  127. break;
  128. case 7:
  129. await setState({
  130. lastEmailTimestamp: payload.emailTimestamp || null,
  131. loginVerificationRequestedAt: null,
  132. });
  133. break;
  134. case 8:
  135. if (payload.localhostUrl) {
  136. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  137. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  138. }
  139. await setState({ localhostUrl: payload.localhostUrl });
  140. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  141. }
  142. break;
  143. case 9: {
  144. if (payload.localhostUrl) {
  145. await closeLocalhostCallbackTabs(payload.localhostUrl);
  146. }
  147. const latestState = await getState();
  148. if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) {
  149. await patchHotmailAccount(latestState.currentHotmailAccountId, {
  150. used: true,
  151. lastUsedAt: Date.now(),
  152. });
  153. await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok');
  154. }
  155. if (isLuckmailProvider(latestState)) {
  156. const currentPurchase = getCurrentLuckmailPurchase(latestState);
  157. if (currentPurchase?.id) {
  158. await setLuckmailPurchaseUsedState(currentPurchase.id, true);
  159. await addLog(`当前 LuckMail 邮箱 ${currentPurchase.email_address} 已在本地标记为已用。`, 'ok');
  160. }
  161. await clearLuckmailRuntimeState({ clearEmail: true });
  162. await addLog('当前 LuckMail 邮箱运行态已清空,下轮将优先复用未用邮箱或重新购买邮箱。', 'ok');
  163. }
  164. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  165. if (localhostPrefix) {
  166. await closeTabsByUrlPrefix(localhostPrefix, {
  167. excludeUrls: [payload.localhostUrl],
  168. excludeLocalhostCallbacks: true,
  169. });
  170. }
  171. await finalizeIcloudAliasAfterSuccessfulFlow(latestState);
  172. break;
  173. }
  174. default:
  175. break;
  176. }
  177. }
  178. async function handleMessage(message, sender) {
  179. switch (message.type) {
  180. case 'CONTENT_SCRIPT_READY': {
  181. const tabId = sender.tab?.id;
  182. if (tabId && message.source) {
  183. await registerTab(message.source, tabId);
  184. flushCommand(message.source, tabId);
  185. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  186. }
  187. return { ok: true };
  188. }
  189. case 'LOG': {
  190. const { message: msg, level } = message.payload;
  191. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  192. return { ok: true };
  193. }
  194. case 'STEP_COMPLETE': {
  195. if (getStopRequested()) {
  196. await setStepStatus(message.step, 'stopped');
  197. await appendManualAccountRunRecordIfNeeded(`step${message.step}_stopped`, null, '流程已被用户停止。');
  198. notifyStepError(message.step, '流程已被用户停止。');
  199. return { ok: true };
  200. }
  201. const completionState = message.step === 9 ? await getState() : null;
  202. await setStepStatus(message.step, 'completed');
  203. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  204. await handleStepData(message.step, message.payload);
  205. if (message.step === 9 && typeof appendAccountRunRecord === 'function') {
  206. await appendAccountRunRecord('success', completionState);
  207. }
  208. notifyStepComplete(message.step, message.payload);
  209. return { ok: true };
  210. }
  211. case 'STEP_ERROR': {
  212. if (isStopError(message.error)) {
  213. await setStepStatus(message.step, 'stopped');
  214. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  215. await appendManualAccountRunRecordIfNeeded(`step${message.step}_stopped`, null, message.error);
  216. notifyStepError(message.step, message.error);
  217. } else {
  218. await setStepStatus(message.step, 'failed');
  219. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  220. await appendManualAccountRunRecordIfNeeded(`step${message.step}_failed`, null, message.error);
  221. notifyStepError(message.step, message.error);
  222. }
  223. return { ok: true };
  224. }
  225. case 'GET_STATE': {
  226. return await getState();
  227. }
  228. case 'RESET': {
  229. clearStopRequest();
  230. await clearAutoRunTimerAlarm();
  231. await resetState();
  232. await addLog('流程已重置', 'info');
  233. return { ok: true };
  234. }
  235. case 'EXECUTE_STEP': {
  236. clearStopRequest();
  237. if (message.source === 'sidepanel') {
  238. await ensureManualInteractionAllowed('手动执行步骤');
  239. }
  240. const step = message.payload.step;
  241. if (message.source === 'sidepanel') {
  242. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  243. }
  244. if (message.payload.email) {
  245. await setEmailState(message.payload.email);
  246. }
  247. if (message.payload.emailPrefix !== undefined) {
  248. await setPersistentSettings({ emailPrefix: message.payload.emailPrefix });
  249. await setState({ emailPrefix: message.payload.emailPrefix });
  250. }
  251. if (doesStepUseCompletionSignal(step)) {
  252. await executeStepViaCompletionSignal(step);
  253. } else {
  254. await executeStep(step);
  255. }
  256. return { ok: true };
  257. }
  258. case 'AUTO_RUN': {
  259. clearStopRequest();
  260. const state = await getState();
  261. if (getPendingAutoRunTimerPlan(state)) {
  262. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  263. }
  264. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  265. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  266. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  267. await setState({ autoRunSkipFailures });
  268. startAutoRunLoop(totalRuns, { autoRunSkipFailures, mode });
  269. return { ok: true };
  270. }
  271. case 'SCHEDULE_AUTO_RUN': {
  272. clearStopRequest();
  273. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  274. return await scheduleAutoRun(totalRuns, {
  275. delayMinutes: message.payload?.delayMinutes,
  276. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  277. mode: message.payload?.mode,
  278. });
  279. }
  280. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  281. clearStopRequest();
  282. const started = await launchAutoRunTimerPlan('manual', {
  283. expectedKinds: [AUTO_RUN_TIMER_KIND_SCHEDULED_START],
  284. });
  285. if (!started) {
  286. throw new Error('当前没有可立即开始的倒计时计划。');
  287. }
  288. return { ok: true };
  289. }
  290. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  291. const cancelled = await cancelScheduledAutoRun();
  292. if (!cancelled) {
  293. throw new Error('当前没有可取消的倒计时计划。');
  294. }
  295. return { ok: true };
  296. }
  297. case 'SKIP_AUTO_RUN_COUNTDOWN': {
  298. clearStopRequest();
  299. const skipped = await skipAutoRunCountdown();
  300. if (!skipped) {
  301. throw new Error('当前没有可立即开始的倒计时。');
  302. }
  303. return { ok: true };
  304. }
  305. case 'RESUME_AUTO_RUN': {
  306. clearStopRequest();
  307. if (message.payload.email) {
  308. await setEmailState(message.payload.email);
  309. }
  310. resumeAutoRun().catch((error) => {
  311. handleAutoRunLoopUnhandledError(error).catch(() => {});
  312. });
  313. return { ok: true };
  314. }
  315. case 'TAKEOVER_AUTO_RUN': {
  316. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  317. await addLog('自动流程已切换为手动控制。', 'warn');
  318. return { ok: true };
  319. }
  320. case 'SKIP_STEP': {
  321. const step = Number(message.payload?.step);
  322. return await skipStep(step);
  323. }
  324. case 'SAVE_SETTING': {
  325. const updates = buildPersistentSettingsPayload(message.payload || {});
  326. const sessionUpdates = buildLuckmailSessionSettingsPayload(message.payload || {});
  327. await setPersistentSettings(updates);
  328. await setState({
  329. ...updates,
  330. ...sessionUpdates,
  331. });
  332. return { ok: true, state: await getState() };
  333. }
  334. case 'EXPORT_SETTINGS': {
  335. return { ok: true, ...(await exportSettingsBundle()) };
  336. }
  337. case 'IMPORT_SETTINGS': {
  338. const state = await importSettingsBundle(message.payload?.config || null);
  339. return { ok: true, state };
  340. }
  341. case 'UPSERT_HOTMAIL_ACCOUNT': {
  342. const account = await upsertHotmailAccount(message.payload || {});
  343. return { ok: true, account };
  344. }
  345. case 'DELETE_HOTMAIL_ACCOUNT': {
  346. await deleteHotmailAccount(String(message.payload?.accountId || ''));
  347. return { ok: true };
  348. }
  349. case 'DELETE_HOTMAIL_ACCOUNTS': {
  350. const result = await deleteHotmailAccounts(String(message.payload?.mode || 'all'));
  351. return { ok: true, ...result };
  352. }
  353. case 'SELECT_HOTMAIL_ACCOUNT': {
  354. const account = await setCurrentHotmailAccount(String(message.payload?.accountId || ''), {
  355. markUsed: false,
  356. syncEmail: true,
  357. });
  358. return { ok: true, account };
  359. }
  360. case 'PATCH_HOTMAIL_ACCOUNT': {
  361. const account = await patchHotmailAccount(
  362. String(message.payload?.accountId || ''),
  363. message.payload?.updates || {}
  364. );
  365. return { ok: true, account };
  366. }
  367. case 'VERIFY_HOTMAIL_ACCOUNT':
  368. case 'AUTHORIZE_HOTMAIL_ACCOUNT': {
  369. const accountId = String(message.payload?.accountId || '');
  370. try {
  371. const result = await verifyHotmailAccount(accountId);
  372. await setCurrentHotmailAccount(result.account.id, { markUsed: false, syncEmail: true });
  373. await addLog(`Hotmail 账号 ${result.account.email} 校验通过,可直接用于收信。`, 'ok');
  374. return { ok: true, account: result.account, messageCount: result.messageCount };
  375. } catch (err) {
  376. const state = await getState();
  377. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  378. const target = findHotmailAccount(accounts, accountId);
  379. if (target) {
  380. target.status = 'error';
  381. target.lastError = err.message;
  382. await syncHotmailAccounts(accounts.map((item) => (item.id === target.id ? target : item)));
  383. }
  384. throw err;
  385. }
  386. }
  387. case 'TEST_HOTMAIL_ACCOUNT': {
  388. const result = await testHotmailAccountMailAccess(String(message.payload?.accountId || ''));
  389. return { ok: true, ...result };
  390. }
  391. case 'LIST_LUCKMAIL_PURCHASES': {
  392. const purchases = await listLuckmailPurchasesForManagement();
  393. return { ok: true, purchases };
  394. }
  395. case 'SELECT_LUCKMAIL_PURCHASE': {
  396. const purchase = await selectLuckmailPurchase(message.payload?.purchaseId);
  397. return { ok: true, purchase };
  398. }
  399. case 'SET_LUCKMAIL_PURCHASE_USED_STATE': {
  400. const result = await setLuckmailPurchaseUsedState(message.payload?.purchaseId, Boolean(message.payload?.used));
  401. return { ok: true, ...result };
  402. }
  403. case 'SET_LUCKMAIL_PURCHASE_PRESERVED_STATE': {
  404. const purchase = await setLuckmailPurchasePreservedState(message.payload?.purchaseId, Boolean(message.payload?.preserved));
  405. return { ok: true, purchase };
  406. }
  407. case 'SET_LUCKMAIL_PURCHASE_DISABLED_STATE': {
  408. const purchase = await setLuckmailPurchaseDisabledState(message.payload?.purchaseId, Boolean(message.payload?.disabled));
  409. return { ok: true, purchase };
  410. }
  411. case 'BATCH_UPDATE_LUCKMAIL_PURCHASES': {
  412. const result = await batchUpdateLuckmailPurchases(message.payload || {});
  413. return { ok: true, ...result };
  414. }
  415. case 'DISABLE_USED_LUCKMAIL_PURCHASES': {
  416. const result = await disableUsedLuckmailPurchases();
  417. return { ok: true, ...result };
  418. }
  419. case 'SET_EMAIL_STATE': {
  420. const state = await getState();
  421. if (isAutoRunLockedState(state)) {
  422. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  423. }
  424. const email = String(message.payload?.email || '').trim() || null;
  425. await setEmailStateSilently(email);
  426. return { ok: true, email };
  427. }
  428. case 'SAVE_EMAIL': {
  429. const state = await getState();
  430. if (isAutoRunLockedState(state)) {
  431. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  432. }
  433. await setEmailState(message.payload.email);
  434. await resumeAutoRun();
  435. return { ok: true, email: message.payload.email };
  436. }
  437. case 'FETCH_GENERATED_EMAIL': {
  438. clearStopRequest();
  439. const state = await getState();
  440. if (isAutoRunLockedState(state)) {
  441. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  442. }
  443. const email = await fetchGeneratedEmail(state, message.payload || {});
  444. await resumeAutoRun();
  445. return { ok: true, email };
  446. }
  447. case 'FETCH_DUCK_EMAIL': {
  448. clearStopRequest();
  449. const state = await getState();
  450. if (isAutoRunLockedState(state)) {
  451. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  452. }
  453. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  454. await resumeAutoRun();
  455. return { ok: true, email };
  456. }
  457. case 'CHECK_ICLOUD_SESSION': {
  458. clearStopRequest();
  459. return await checkIcloudSession();
  460. }
  461. case 'LIST_ICLOUD_ALIASES': {
  462. clearStopRequest();
  463. const aliases = await listIcloudAliases();
  464. return { ok: true, aliases };
  465. }
  466. case 'SET_ICLOUD_ALIAS_USED_STATE': {
  467. clearStopRequest();
  468. const result = await setIcloudAliasUsedState(message.payload || {});
  469. return { ok: true, ...result };
  470. }
  471. case 'SET_ICLOUD_ALIAS_PRESERVED_STATE': {
  472. clearStopRequest();
  473. const result = await setIcloudAliasPreservedState(message.payload || {});
  474. return { ok: true, ...result };
  475. }
  476. case 'DELETE_ICLOUD_ALIAS': {
  477. clearStopRequest();
  478. const result = await deleteIcloudAlias(message.payload || {});
  479. return { ok: true, ...result };
  480. }
  481. case 'DELETE_USED_ICLOUD_ALIASES': {
  482. clearStopRequest();
  483. const result = await deleteUsedIcloudAliases();
  484. return { ok: true, ...result };
  485. }
  486. case 'STOP_FLOW': {
  487. await requestStop();
  488. return { ok: true };
  489. }
  490. default:
  491. console.warn('Unknown message type:', message.type);
  492. return { error: `Unknown message type: ${message.type}` };
  493. }
  494. }
  495. return {
  496. handleMessage,
  497. handleStepData,
  498. };
  499. }
  500. return {
  501. createMessageRouter,
  502. };
  503. });