message-router.js 22 KB

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