sidepanel.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const settingsCard = document.getElementById('settings-card');
  13. const displayOauthUrl = document.getElementById('display-oauth-url');
  14. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  15. const displayStatus = document.getElementById('display-status');
  16. const statusBar = document.getElementById('status-bar');
  17. const inputEmail = document.getElementById('input-email');
  18. const inputPassword = document.getElementById('input-password');
  19. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  20. const btnToggleVpsPassword = document.getElementById('btn-toggle-vps-password');
  21. const btnFetchEmail = document.getElementById('btn-fetch-email');
  22. const btnTogglePassword = document.getElementById('btn-toggle-password');
  23. const btnSaveSettings = document.getElementById('btn-save-settings');
  24. const btnStop = document.getElementById('btn-stop');
  25. const btnReset = document.getElementById('btn-reset');
  26. const stepsProgress = document.getElementById('steps-progress');
  27. const btnAutoRun = document.getElementById('btn-auto-run');
  28. const btnAutoContinue = document.getElementById('btn-auto-continue');
  29. const autoContinueBar = document.getElementById('auto-continue-bar');
  30. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  31. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  32. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  33. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  34. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  35. const btnClearLog = document.getElementById('btn-clear-log');
  36. const selectPanelMode = document.getElementById('select-panel-mode');
  37. const rowVpsUrl = document.getElementById('row-vps-url');
  38. const inputVpsUrl = document.getElementById('input-vps-url');
  39. const rowVpsPassword = document.getElementById('row-vps-password');
  40. const inputVpsPassword = document.getElementById('input-vps-password');
  41. const rowLocalCpaStep9Mode = document.getElementById('row-local-cpa-step9-mode');
  42. const localCpaStep9ModeButtons = Array.from(document.querySelectorAll('[data-local-cpa-step9-mode]'));
  43. const rowSub2ApiUrl = document.getElementById('row-sub2api-url');
  44. const inputSub2ApiUrl = document.getElementById('input-sub2api-url');
  45. const rowSub2ApiEmail = document.getElementById('row-sub2api-email');
  46. const inputSub2ApiEmail = document.getElementById('input-sub2api-email');
  47. const rowSub2ApiPassword = document.getElementById('row-sub2api-password');
  48. const inputSub2ApiPassword = document.getElementById('input-sub2api-password');
  49. const rowSub2ApiGroup = document.getElementById('row-sub2api-group');
  50. const inputSub2ApiGroup = document.getElementById('input-sub2api-group');
  51. const selectMailProvider = document.getElementById('select-mail-provider');
  52. const selectEmailGenerator = document.getElementById('select-email-generator');
  53. const hotmailSection = document.getElementById('hotmail-section');
  54. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  55. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  56. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  57. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  58. const inputHotmailImport = document.getElementById('input-hotmail-import');
  59. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  60. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  61. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  62. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  63. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  64. const hotmailListShell = document.getElementById('hotmail-list-shell');
  65. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  66. const rowInbucketHost = document.getElementById('row-inbucket-host');
  67. const inputInbucketHost = document.getElementById('input-inbucket-host');
  68. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  69. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  70. const rowCfDomain = document.getElementById('row-cf-domain');
  71. const selectCfDomain = document.getElementById('select-cf-domain');
  72. const inputCfDomain = document.getElementById('input-cf-domain');
  73. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  74. const inputRunCount = document.getElementById('input-run-count');
  75. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  76. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  77. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  78. const autoStartModal = document.getElementById('auto-start-modal');
  79. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  80. const autoStartMessage = document.getElementById('auto-start-message');
  81. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  82. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  83. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  84. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  85. const autoHintText = document.querySelector('.auto-hint');
  86. const STEP_DEFAULT_STATUSES = {
  87. 1: 'pending',
  88. 2: 'pending',
  89. 3: 'pending',
  90. 4: 'pending',
  91. 5: 'pending',
  92. 6: 'pending',
  93. 7: 'pending',
  94. 8: 'pending',
  95. 9: 'pending',
  96. };
  97. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  98. const AUTO_DELAY_MIN_MINUTES = 1;
  99. const AUTO_DELAY_MAX_MINUTES = 1440;
  100. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  101. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  102. let latestState = null;
  103. let currentAutoRun = {
  104. autoRunning: false,
  105. phase: 'idle',
  106. currentRun: 0,
  107. totalRuns: 1,
  108. attemptRun: 0,
  109. scheduledAt: null,
  110. };
  111. let settingsDirty = false;
  112. let settingsSaveInFlight = false;
  113. let settingsAutoSaveTimer = null;
  114. let cloudflareDomainEditMode = false;
  115. let modalChoiceResolver = null;
  116. let currentModalActions = [];
  117. let scheduledCountdownTimer = null;
  118. let hotmailActionInFlight = false;
  119. let hotmailListExpanded = false;
  120. const EYE_OPEN_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>';
  121. const EYE_CLOSED_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19C5 19 1 12 1 12a21.77 21.77 0 0 1 5.06-6.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.86 21.86 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
  122. const COPY_ICON = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
  123. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  124. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  125. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  126. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  127. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  128. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  129. const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
  130. // ============================================================
  131. // Toast Notifications
  132. // ============================================================
  133. const toastContainer = document.getElementById('toast-container');
  134. const TOAST_ICONS = {
  135. error: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
  136. warn: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  137. success: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
  138. info: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  139. };
  140. const LOG_LEVEL_LABELS = {
  141. info: '信息',
  142. ok: '成功',
  143. warn: '警告',
  144. error: '错误',
  145. };
  146. function showToast(message, type = 'error', duration = 4000) {
  147. const toast = document.createElement('div');
  148. toast.className = `toast toast-${type}`;
  149. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  150. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  151. toastContainer.appendChild(toast);
  152. if (duration > 0) {
  153. setTimeout(() => dismissToast(toast), duration);
  154. }
  155. }
  156. function dismissToast(toast) {
  157. if (!toast.parentNode) return;
  158. toast.classList.add('toast-exit');
  159. toast.addEventListener('animationend', () => toast.remove());
  160. }
  161. function resetActionModalButtons() {
  162. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  163. buttons.forEach((button) => {
  164. if (!button) return;
  165. button.hidden = true;
  166. button.disabled = false;
  167. button.onclick = null;
  168. });
  169. currentModalActions = [];
  170. }
  171. function configureActionModalButton(button, action) {
  172. if (!button) return;
  173. if (!action) {
  174. button.hidden = true;
  175. button.onclick = null;
  176. return;
  177. }
  178. button.hidden = false;
  179. button.disabled = false;
  180. button.textContent = action.label;
  181. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  182. button.onclick = () => resolveModalChoice(action.id);
  183. }
  184. function resolveModalChoice(choice) {
  185. if (modalChoiceResolver) {
  186. modalChoiceResolver(choice);
  187. modalChoiceResolver = null;
  188. }
  189. resetActionModalButtons();
  190. if (autoStartModal) {
  191. autoStartModal.hidden = true;
  192. }
  193. }
  194. function openActionModal({ title, message, actions }) {
  195. if (!autoStartModal) {
  196. return Promise.resolve(null);
  197. }
  198. if (modalChoiceResolver) {
  199. resolveModalChoice(null);
  200. }
  201. autoStartTitle.textContent = title;
  202. autoStartMessage.textContent = message;
  203. currentModalActions = actions || [];
  204. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  205. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  206. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  207. autoStartModal.hidden = false;
  208. return new Promise((resolve) => {
  209. modalChoiceResolver = resolve;
  210. });
  211. }
  212. function openAutoStartChoiceDialog(startStep, options = {}) {
  213. const runningStep = Number.isInteger(options.runningStep) ? options.runningStep : null;
  214. const continueMessage = runningStep
  215. ? `继续当前会先等待步骤 ${runningStep} 完成,再按最新进度自动执行。`
  216. : `继续当前会从步骤 ${startStep} 开始自动执行。`;
  217. return openActionModal({
  218. title: '启动自动',
  219. message: `检测到当前已有流程进度。${continueMessage}重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  220. actions: [
  221. { id: null, label: '取消', variant: 'btn-ghost' },
  222. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  223. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  224. ],
  225. });
  226. }
  227. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  228. const choice = await openActionModal({
  229. title,
  230. message,
  231. actions: [
  232. { id: null, label: '取消', variant: 'btn-ghost' },
  233. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  234. ],
  235. });
  236. return choice === 'confirm';
  237. }
  238. function isDoneStatus(status) {
  239. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  240. }
  241. function getStepStatuses(state = latestState) {
  242. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  243. }
  244. function getFirstUnfinishedStep(state = latestState) {
  245. const statuses = getStepStatuses(state);
  246. for (let step = 1; step <= 9; step++) {
  247. if (!isDoneStatus(statuses[step])) {
  248. return step;
  249. }
  250. }
  251. return null;
  252. }
  253. function getRunningSteps(state = latestState) {
  254. const statuses = getStepStatuses(state);
  255. return Object.entries(statuses)
  256. .filter(([, status]) => status === 'running')
  257. .map(([step]) => Number(step))
  258. .sort((a, b) => a - b);
  259. }
  260. function hasSavedProgress(state = latestState) {
  261. const statuses = getStepStatuses(state);
  262. return Object.values(statuses).some((status) => status !== 'pending');
  263. }
  264. function shouldOfferAutoModeChoice(state = latestState) {
  265. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  266. }
  267. function syncLatestState(nextState) {
  268. const mergedStepStatuses = nextState?.stepStatuses
  269. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  270. : getStepStatuses(latestState);
  271. latestState = {
  272. ...(latestState || {}),
  273. ...(nextState || {}),
  274. stepStatuses: mergedStepStatuses,
  275. };
  276. }
  277. function syncAutoRunState(source = {}) {
  278. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  279. const autoRunning = source.autoRunning !== undefined
  280. ? Boolean(source.autoRunning)
  281. : (source.autoRunPhase !== undefined || source.phase !== undefined
  282. ? ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(phase)
  283. : currentAutoRun.autoRunning);
  284. currentAutoRun = {
  285. autoRunning,
  286. phase,
  287. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  288. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  289. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  290. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  291. };
  292. }
  293. function isAutoRunLockedPhase() {
  294. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'waiting_step' || currentAutoRun.phase === 'retrying';
  295. }
  296. function isAutoRunPausedPhase() {
  297. return currentAutoRun.phase === 'waiting_email';
  298. }
  299. function isAutoRunWaitingStepPhase() {
  300. return currentAutoRun.phase === 'waiting_step';
  301. }
  302. function isAutoRunScheduledPhase() {
  303. return currentAutoRun.phase === 'scheduled';
  304. }
  305. function getAutoRunLabel(payload = currentAutoRun) {
  306. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  307. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  308. }
  309. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  310. if ((payload.totalRuns || 1) > 1) {
  311. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  312. }
  313. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  314. }
  315. function normalizeAutoDelayMinutes(value) {
  316. const numeric = Number(value);
  317. if (!Number.isFinite(numeric)) {
  318. return AUTO_DELAY_DEFAULT_MINUTES;
  319. }
  320. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  321. }
  322. function updateAutoDelayInputState() {
  323. const scheduled = isAutoRunScheduledPhase();
  324. inputAutoDelayEnabled.disabled = scheduled;
  325. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  326. }
  327. function formatCountdown(remainingMs) {
  328. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  329. const hours = Math.floor(totalSeconds / 3600);
  330. const minutes = Math.floor((totalSeconds % 3600) / 60);
  331. const seconds = totalSeconds % 60;
  332. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  333. }
  334. function formatScheduleTime(timestamp) {
  335. return new Date(timestamp).toLocaleString('zh-CN', {
  336. hour12: false,
  337. month: '2-digit',
  338. day: '2-digit',
  339. hour: '2-digit',
  340. minute: '2-digit',
  341. second: '2-digit',
  342. });
  343. }
  344. function stopScheduledCountdownTicker() {
  345. clearInterval(scheduledCountdownTimer);
  346. scheduledCountdownTimer = null;
  347. }
  348. function renderScheduledAutoRunInfo() {
  349. if (!autoScheduleBar) {
  350. return;
  351. }
  352. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  353. autoScheduleBar.style.display = 'none';
  354. return;
  355. }
  356. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  357. autoScheduleBar.style.display = 'flex';
  358. autoScheduleTitle.textContent = '已计划自动运行';
  359. autoScheduleMeta.textContent = remainingMs > 0
  360. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  361. : '倒计时即将结束,正在准备启动...';
  362. }
  363. function syncScheduledCountdownTicker() {
  364. renderScheduledAutoRunInfo();
  365. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  366. stopScheduledCountdownTicker();
  367. return;
  368. }
  369. if (scheduledCountdownTimer) {
  370. return;
  371. }
  372. scheduledCountdownTimer = setInterval(() => {
  373. renderScheduledAutoRunInfo();
  374. updateStatusDisplay(latestState);
  375. }, 1000);
  376. }
  377. function setDefaultAutoRunButton() {
  378. btnAutoRun.disabled = false;
  379. inputRunCount.disabled = false;
  380. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> 自动';
  381. }
  382. function normalizeCloudflareDomainValue(value = '') {
  383. let normalized = String(value || '').trim().toLowerCase();
  384. if (!normalized) return '';
  385. normalized = normalized.replace(/^@+/, '');
  386. normalized = normalized.replace(/^https?:\/\//, '');
  387. normalized = normalized.replace(/\/.*$/, '');
  388. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  389. return '';
  390. }
  391. return normalized;
  392. }
  393. function normalizeCloudflareDomains(values = []) {
  394. const seen = new Set();
  395. const domains = [];
  396. for (const value of Array.isArray(values) ? values : []) {
  397. const normalized = normalizeCloudflareDomainValue(value);
  398. if (!normalized || seen.has(normalized)) continue;
  399. seen.add(normalized);
  400. domains.push(normalized);
  401. }
  402. return domains;
  403. }
  404. function getCloudflareDomainsFromState() {
  405. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  406. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  407. if (activeDomain && !domains.includes(activeDomain)) {
  408. domains.unshift(activeDomain);
  409. }
  410. return { domains, activeDomain: activeDomain || domains[0] || '' };
  411. }
  412. function renderCloudflareDomainOptions(preferredDomain = '') {
  413. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  414. const { domains, activeDomain } = getCloudflareDomainsFromState();
  415. const selected = preferred || activeDomain;
  416. selectCfDomain.innerHTML = '';
  417. if (domains.length === 0) {
  418. const option = document.createElement('option');
  419. option.value = '';
  420. option.textContent = '请先添加域名';
  421. selectCfDomain.appendChild(option);
  422. selectCfDomain.disabled = true;
  423. selectCfDomain.value = '';
  424. return;
  425. }
  426. for (const domain of domains) {
  427. const option = document.createElement('option');
  428. option.value = domain;
  429. option.textContent = domain;
  430. selectCfDomain.appendChild(option);
  431. }
  432. selectCfDomain.disabled = false;
  433. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  434. }
  435. function setCloudflareDomainEditMode(editing, options = {}) {
  436. const { clearInput = false } = options;
  437. cloudflareDomainEditMode = Boolean(editing);
  438. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  439. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  440. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  441. if (cloudflareDomainEditMode) {
  442. if (clearInput) {
  443. inputCfDomain.value = '';
  444. }
  445. inputCfDomain.focus();
  446. } else if (clearInput) {
  447. inputCfDomain.value = '';
  448. }
  449. }
  450. function collectSettingsPayload() {
  451. const { domains, activeDomain } = getCloudflareDomainsFromState();
  452. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  453. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  454. ) || activeDomain;
  455. return {
  456. panelMode: selectPanelMode.value,
  457. vpsUrl: inputVpsUrl.value.trim(),
  458. vpsPassword: inputVpsPassword.value,
  459. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  460. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  461. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  462. sub2apiPassword: inputSub2ApiPassword.value,
  463. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  464. customPassword: inputPassword.value,
  465. mailProvider: selectMailProvider.value,
  466. emailGenerator: selectEmailGenerator.value,
  467. inbucketHost: inputInbucketHost.value.trim(),
  468. inbucketMailbox: inputInbucketMailbox.value.trim(),
  469. cloudflareDomain: selectedCloudflareDomain,
  470. cloudflareDomains: domains,
  471. autoRunSkipFailures: inputAutoSkipFailures.checked,
  472. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  473. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  474. };
  475. }
  476. function normalizeLocalCpaStep9Mode(value = '') {
  477. return String(value || '').trim().toLowerCase() === 'bypass'
  478. ? 'bypass'
  479. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  480. }
  481. function getSelectedLocalCpaStep9Mode() {
  482. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  483. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  484. }
  485. function setLocalCpaStep9Mode(mode) {
  486. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  487. localCpaStep9ModeButtons.forEach((button) => {
  488. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  489. button.classList.toggle('is-active', active);
  490. button.setAttribute('aria-pressed', String(active));
  491. });
  492. }
  493. function setSettingsCardLocked(locked) {
  494. if (!settingsCard) {
  495. return;
  496. }
  497. settingsCard.classList.toggle('is-locked', locked);
  498. settingsCard.toggleAttribute('inert', locked);
  499. }
  500. async function setRuntimeEmailState(email) {
  501. const normalizedEmail = String(email || '').trim() || null;
  502. const response = await chrome.runtime.sendMessage({
  503. type: 'SET_EMAIL_STATE',
  504. source: 'sidepanel',
  505. payload: { email: normalizedEmail },
  506. });
  507. if (response?.error) {
  508. throw new Error(response.error);
  509. }
  510. return normalizedEmail;
  511. }
  512. async function clearRegistrationEmail(options = {}) {
  513. const { silent = false } = options;
  514. if (!inputEmail.value.trim() && !latestState?.email) {
  515. return;
  516. }
  517. inputEmail.value = '';
  518. syncLatestState({ email: null });
  519. try {
  520. await setRuntimeEmailState(null);
  521. } catch (err) {
  522. if (!silent) {
  523. showToast(`清空邮箱失败:${err.message}`, 'error');
  524. }
  525. throw err;
  526. }
  527. }
  528. function markSettingsDirty(isDirty = true) {
  529. settingsDirty = isDirty;
  530. updateSaveButtonState();
  531. }
  532. function updateSaveButtonState() {
  533. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  534. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  535. }
  536. function scheduleSettingsAutoSave() {
  537. clearTimeout(settingsAutoSaveTimer);
  538. settingsAutoSaveTimer = setTimeout(() => {
  539. saveSettings({ silent: true }).catch(() => { });
  540. }, 500);
  541. }
  542. async function saveSettings(options = {}) {
  543. const { silent = false } = options;
  544. clearTimeout(settingsAutoSaveTimer);
  545. if (!settingsDirty && !settingsSaveInFlight && silent) {
  546. return;
  547. }
  548. const payload = collectSettingsPayload();
  549. settingsSaveInFlight = true;
  550. updateSaveButtonState();
  551. try {
  552. const response = await chrome.runtime.sendMessage({
  553. type: 'SAVE_SETTING',
  554. source: 'sidepanel',
  555. payload,
  556. });
  557. if (response?.error) {
  558. throw new Error(response.error);
  559. }
  560. syncLatestState(payload);
  561. markSettingsDirty(false);
  562. updatePanelModeUI();
  563. updateMailProviderUI();
  564. updateButtonStates();
  565. if (!silent) {
  566. showToast('配置已保存', 'success', 1800);
  567. }
  568. } catch (err) {
  569. markSettingsDirty(true);
  570. if (!silent) {
  571. showToast(`保存失败:${err.message}`, 'error');
  572. }
  573. throw err;
  574. } finally {
  575. settingsSaveInFlight = false;
  576. updateSaveButtonState();
  577. }
  578. }
  579. function applyAutoRunStatus(payload = currentAutoRun) {
  580. syncAutoRunState(payload);
  581. const runLabel = getAutoRunLabel(currentAutoRun);
  582. const locked = isAutoRunLockedPhase();
  583. const paused = isAutoRunPausedPhase();
  584. const scheduled = isAutoRunScheduledPhase();
  585. const settingsCardLocked = scheduled || locked;
  586. setSettingsCardLocked(settingsCardLocked);
  587. inputRunCount.disabled = currentAutoRun.autoRunning;
  588. btnAutoRun.disabled = currentAutoRun.autoRunning;
  589. btnFetchEmail.disabled = locked;
  590. inputEmail.disabled = locked;
  591. inputAutoSkipFailures.disabled = scheduled;
  592. if (currentAutoRun.totalRuns > 0) {
  593. inputRunCount.value = String(currentAutoRun.totalRuns);
  594. }
  595. switch (currentAutoRun.phase) {
  596. case 'scheduled':
  597. autoContinueBar.style.display = 'none';
  598. btnAutoRun.innerHTML = `已计划${runLabel}`;
  599. break;
  600. case 'waiting_step':
  601. autoContinueBar.style.display = 'none';
  602. btnAutoRun.innerHTML = `等待中${runLabel}`;
  603. break;
  604. case 'waiting_email':
  605. autoContinueBar.style.display = 'flex';
  606. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  607. break;
  608. case 'running':
  609. autoContinueBar.style.display = 'none';
  610. btnAutoRun.innerHTML = `运行中${runLabel}`;
  611. break;
  612. case 'retrying':
  613. autoContinueBar.style.display = 'none';
  614. btnAutoRun.innerHTML = `重试中${runLabel}`;
  615. break;
  616. default:
  617. autoContinueBar.style.display = 'none';
  618. setDefaultAutoRunButton();
  619. inputEmail.disabled = false;
  620. if (!locked) {
  621. btnFetchEmail.disabled = false;
  622. }
  623. break;
  624. }
  625. updateAutoDelayInputState();
  626. syncScheduledCountdownTicker();
  627. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  628. }
  629. function initializeManualStepActions() {
  630. document.querySelectorAll('.step-row').forEach((row) => {
  631. const step = Number(row.dataset.step);
  632. const statusEl = row.querySelector('.step-status');
  633. if (!statusEl) return;
  634. const actions = document.createElement('div');
  635. actions.className = 'step-actions';
  636. const manualBtn = document.createElement('button');
  637. manualBtn.type = 'button';
  638. manualBtn.className = 'step-manual-btn';
  639. manualBtn.dataset.step = String(step);
  640. manualBtn.title = '跳过此步';
  641. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  642. manualBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';
  643. manualBtn.addEventListener('click', async (event) => {
  644. event.stopPropagation();
  645. try {
  646. await handleSkipStep(step);
  647. } catch (err) {
  648. showToast(err.message, 'error');
  649. }
  650. });
  651. statusEl.parentNode.replaceChild(actions, statusEl);
  652. actions.appendChild(manualBtn);
  653. actions.appendChild(statusEl);
  654. });
  655. }
  656. // ============================================================
  657. // State Restore on load
  658. // ============================================================
  659. async function restoreState() {
  660. try {
  661. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  662. syncLatestState(state);
  663. syncAutoRunState(state);
  664. if (state.oauthUrl) {
  665. displayOauthUrl.textContent = state.oauthUrl;
  666. displayOauthUrl.classList.add('has-value');
  667. }
  668. if (state.localhostUrl) {
  669. displayLocalhostUrl.textContent = state.localhostUrl;
  670. displayLocalhostUrl.classList.add('has-value');
  671. }
  672. if (state.email) {
  673. inputEmail.value = state.email;
  674. }
  675. syncPasswordField(state);
  676. if (state.vpsUrl) {
  677. inputVpsUrl.value = state.vpsUrl;
  678. }
  679. if (state.vpsPassword) {
  680. inputVpsPassword.value = state.vpsPassword;
  681. }
  682. setLocalCpaStep9Mode(state.localCpaStep9Mode);
  683. if (state.panelMode) {
  684. selectPanelMode.value = state.panelMode;
  685. }
  686. if (state.sub2apiUrl) {
  687. inputSub2ApiUrl.value = state.sub2apiUrl;
  688. }
  689. if (state.sub2apiEmail) {
  690. inputSub2ApiEmail.value = state.sub2apiEmail;
  691. }
  692. if (state.sub2apiPassword) {
  693. inputSub2ApiPassword.value = state.sub2apiPassword;
  694. }
  695. if (state.sub2apiGroupName) {
  696. inputSub2ApiGroup.value = state.sub2apiGroupName;
  697. }
  698. if (state.mailProvider) {
  699. selectMailProvider.value = state.mailProvider;
  700. }
  701. if (state.emailGenerator) {
  702. selectEmailGenerator.value = state.emailGenerator;
  703. }
  704. if (state.inbucketHost) {
  705. inputInbucketHost.value = state.inbucketHost;
  706. }
  707. if (state.inbucketMailbox) {
  708. inputInbucketMailbox.value = state.inbucketMailbox;
  709. }
  710. renderCloudflareDomainOptions(state.cloudflareDomain || '');
  711. setCloudflareDomainEditMode(false, { clearInput: true });
  712. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  713. inputAutoDelayEnabled.checked = Boolean(state.autoRunDelayEnabled);
  714. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state.autoRunDelayMinutes));
  715. if (state.autoRunTotalRuns) {
  716. inputRunCount.value = String(state.autoRunTotalRuns);
  717. }
  718. if (state.stepStatuses) {
  719. for (const [step, status] of Object.entries(state.stepStatuses)) {
  720. updateStepUI(Number(step), status);
  721. }
  722. }
  723. if (state.logs) {
  724. for (const entry of state.logs) {
  725. appendLog(entry);
  726. }
  727. }
  728. applyAutoRunStatus(state);
  729. markSettingsDirty(false);
  730. updateAutoDelayInputState();
  731. updateStatusDisplay(latestState);
  732. updateProgressCounter();
  733. updatePanelModeUI();
  734. updateMailProviderUI();
  735. updateButtonStates();
  736. } catch (err) {
  737. console.error('Failed to restore state:', err);
  738. }
  739. }
  740. function syncPasswordField(state) {
  741. inputPassword.value = state.customPassword || state.password || '';
  742. }
  743. function getSelectedEmailGenerator() {
  744. return selectEmailGenerator.value === 'cloudflare' ? 'cloudflare' : 'duck';
  745. }
  746. function getEmailGeneratorUiCopy() {
  747. if (getSelectedEmailGenerator() === 'cloudflare') {
  748. return {
  749. buttonLabel: '生成 Cloudflare',
  750. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  751. successVerb: '生成',
  752. label: 'Cloudflare 邮箱',
  753. };
  754. }
  755. return {
  756. buttonLabel: '获取 Duck',
  757. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  758. successVerb: '获取',
  759. label: 'Duck 邮箱',
  760. };
  761. }
  762. function getHotmailAccounts(state = latestState) {
  763. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  764. }
  765. function getCurrentHotmailAccount(state = latestState) {
  766. const currentId = state?.currentHotmailAccountId;
  767. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  768. }
  769. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  770. const accounts = getHotmailAccounts(state);
  771. if (typeof filterHotmailAccountsByUsage === 'function') {
  772. return filterHotmailAccountsByUsage(accounts, mode);
  773. }
  774. if (mode === 'used') {
  775. return accounts.filter((account) => Boolean(account?.used));
  776. }
  777. return accounts.slice();
  778. }
  779. function getHotmailBulkActionText(mode, count) {
  780. if (typeof getHotmailBulkActionLabel === 'function') {
  781. return getHotmailBulkActionLabel(mode, count);
  782. }
  783. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  784. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  785. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  786. return `${prefix}${suffix}`;
  787. }
  788. function getHotmailListToggleText(expanded, count) {
  789. if (typeof getHotmailListToggleLabel === 'function') {
  790. return getHotmailListToggleLabel(expanded, count);
  791. }
  792. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  793. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  794. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  795. }
  796. function updateHotmailListViewport() {
  797. const count = getHotmailAccounts().length;
  798. const usedCount = getHotmailAccountsByUsage('used').length;
  799. if (btnClearUsedHotmailAccounts) {
  800. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  801. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  802. }
  803. if (btnDeleteAllHotmailAccounts) {
  804. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  805. btnDeleteAllHotmailAccounts.disabled = count === 0;
  806. }
  807. if (btnToggleHotmailList) {
  808. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  809. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  810. btnToggleHotmailList.disabled = count === 0;
  811. }
  812. if (hotmailListShell) {
  813. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  814. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  815. }
  816. }
  817. function setHotmailListExpanded(expanded, options = {}) {
  818. const { persist = true } = options;
  819. hotmailListExpanded = Boolean(expanded);
  820. updateHotmailListViewport();
  821. if (persist) {
  822. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  823. }
  824. }
  825. function initHotmailListExpandedState() {
  826. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  827. setHotmailListExpanded(saved === '1', { persist: false });
  828. }
  829. function shouldClearCurrentHotmailSelectionLocally(account) {
  830. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  831. return shouldClearHotmailCurrentSelection(account);
  832. }
  833. return Boolean(account) && account.used === true;
  834. }
  835. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  836. if (typeof upsertHotmailAccountInList === 'function') {
  837. return upsertHotmailAccountInList(accounts, nextAccount);
  838. }
  839. const list = Array.isArray(accounts) ? accounts.slice() : [];
  840. if (!nextAccount?.id) return list;
  841. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  842. if (existingIndex === -1) {
  843. list.push(nextAccount);
  844. return list;
  845. }
  846. list[existingIndex] = nextAccount;
  847. return list;
  848. }
  849. function refreshHotmailSelectionUI() {
  850. renderHotmailAccounts();
  851. if (selectMailProvider.value === 'hotmail-api') {
  852. const currentAccount = getCurrentHotmailAccount();
  853. inputEmail.value = currentAccount?.email || latestState?.email || '';
  854. }
  855. }
  856. function applyHotmailAccountMutation(account, options = {}) {
  857. if (!account?.id) return;
  858. const { preserveCurrentSelection = false } = options;
  859. const nextState = {
  860. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  861. };
  862. if (!preserveCurrentSelection
  863. && latestState?.currentHotmailAccountId === account.id
  864. && shouldClearCurrentHotmailSelectionLocally(account)) {
  865. nextState.currentHotmailAccountId = null;
  866. if (selectMailProvider.value === 'hotmail-api') {
  867. nextState.email = null;
  868. }
  869. }
  870. syncLatestState(nextState);
  871. refreshHotmailSelectionUI();
  872. }
  873. function formatDateTime(timestamp) {
  874. const value = Number(timestamp);
  875. if (!Number.isFinite(value) || value <= 0) {
  876. return '未使用';
  877. }
  878. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  879. }
  880. function getHotmailAvailabilityLabel(account) {
  881. if (account.used) return '已用';
  882. return '可分配';
  883. }
  884. function getHotmailStatusLabel(account) {
  885. if (account.used) return '已用';
  886. switch (account.status) {
  887. case 'authorized':
  888. return '可用';
  889. case 'error':
  890. return '异常';
  891. default:
  892. return '待校验';
  893. }
  894. }
  895. function getHotmailStatusClass(account) {
  896. if (account.used) return 'status-used';
  897. return `status-${account.status || 'pending'}`;
  898. }
  899. function clearHotmailForm() {
  900. inputHotmailEmail.value = '';
  901. inputHotmailClientId.value = '';
  902. inputHotmailPassword.value = '';
  903. inputHotmailRefreshToken.value = '';
  904. }
  905. function renderHotmailAccounts() {
  906. if (!hotmailAccountsList) return;
  907. const accounts = getHotmailAccounts();
  908. const currentId = latestState?.currentHotmailAccountId || '';
  909. if (!accounts.length) {
  910. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  911. updateHotmailListViewport();
  912. return;
  913. }
  914. hotmailAccountsList.innerHTML = accounts.map((account) => `
  915. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  916. <div class="hotmail-account-top">
  917. <div class="hotmail-account-title-row">
  918. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  919. <button
  920. class="hotmail-copy-btn"
  921. type="button"
  922. data-account-action="copy-email"
  923. data-account-id="${escapeHtml(account.id)}"
  924. title="复制邮箱"
  925. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  926. >${COPY_ICON}</button>
  927. </div>
  928. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  929. </div>
  930. <div class="hotmail-account-meta">
  931. <span>客户端 ID:${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  932. <span>刷新令牌:${account.refreshToken ? '已保存' : '未保存'}</span>
  933. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  934. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  935. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  936. </div>
  937. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  938. <div class="hotmail-account-actions">
  939. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  940. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  941. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  942. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  943. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  944. </div>
  945. </div>
  946. `).join('');
  947. updateHotmailListViewport();
  948. }
  949. function updateMailProviderUI() {
  950. const useInbucket = selectMailProvider.value === 'inbucket';
  951. const useHotmail = selectMailProvider.value === 'hotmail-api';
  952. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  953. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  954. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  955. rowCfDomain.style.display = !useHotmail && useCloudflare ? '' : 'none';
  956. const { domains } = getCloudflareDomainsFromState();
  957. if (useCloudflare) {
  958. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  959. } else {
  960. setCloudflareDomainEditMode(false, { clearInput: false });
  961. }
  962. if (hotmailSection) {
  963. hotmailSection.style.display = useHotmail ? '' : 'none';
  964. }
  965. selectEmailGenerator.disabled = useHotmail;
  966. btnFetchEmail.hidden = useHotmail;
  967. inputEmail.readOnly = useHotmail;
  968. const uiCopy = getEmailGeneratorUiCopy();
  969. inputEmail.placeholder = useHotmail ? '由 Hotmail 账号池自动分配' : uiCopy.placeholder;
  970. if (!btnFetchEmail.disabled) {
  971. btnFetchEmail.textContent = uiCopy.buttonLabel;
  972. }
  973. if (autoHintText) {
  974. autoHintText.textContent = useHotmail
  975. ? '请先校验并选择一个 Hotmail 账号'
  976. : '先自动获取邮箱,或手动粘贴邮箱后再继续';
  977. }
  978. if (useHotmail) {
  979. const currentAccount = getCurrentHotmailAccount();
  980. inputEmail.value = currentAccount?.email || latestState?.email || '';
  981. }
  982. renderHotmailAccounts();
  983. }
  984. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  985. const { silent = false } = options;
  986. const normalizedDomains = normalizeCloudflareDomains(domains);
  987. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  988. const payload = {
  989. cloudflareDomain: normalizedActiveDomain,
  990. cloudflareDomains: normalizedDomains,
  991. };
  992. const response = await chrome.runtime.sendMessage({
  993. type: 'SAVE_SETTING',
  994. source: 'sidepanel',
  995. payload,
  996. });
  997. if (response?.error) {
  998. throw new Error(response.error);
  999. }
  1000. syncLatestState({
  1001. ...payload,
  1002. });
  1003. renderCloudflareDomainOptions(normalizedActiveDomain);
  1004. setCloudflareDomainEditMode(false, { clearInput: true });
  1005. markSettingsDirty(false);
  1006. updateMailProviderUI();
  1007. if (!silent) {
  1008. showToast('Cloudflare 域名已保存', 'success', 1800);
  1009. }
  1010. }
  1011. function updatePanelModeUI() {
  1012. const useSub2Api = selectPanelMode.value === 'sub2api';
  1013. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  1014. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  1015. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  1016. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  1017. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  1018. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  1019. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  1020. const step9Btn = document.querySelector('.step-btn[data-step="9"]');
  1021. if (step9Btn) {
  1022. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  1023. }
  1024. }
  1025. // ============================================================
  1026. // UI Updates
  1027. // ============================================================
  1028. function updateStepUI(step, status) {
  1029. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  1030. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  1031. syncLatestState({
  1032. stepStatuses: {
  1033. ...getStepStatuses(),
  1034. [step]: status,
  1035. },
  1036. });
  1037. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  1038. if (row) {
  1039. row.className = `step-row ${status}`;
  1040. }
  1041. updateButtonStates();
  1042. updateProgressCounter();
  1043. }
  1044. function updateProgressCounter() {
  1045. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  1046. stepsProgress.textContent = `${completed} / 9`;
  1047. }
  1048. function updateButtonStates() {
  1049. const statuses = getStepStatuses();
  1050. const anyRunning = Object.values(statuses).some(s => s === 'running');
  1051. const autoLocked = isAutoRunLockedPhase();
  1052. const autoScheduled = isAutoRunScheduledPhase();
  1053. for (let step = 1; step <= 9; step++) {
  1054. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  1055. if (!btn) continue;
  1056. if (anyRunning || autoLocked || autoScheduled) {
  1057. btn.disabled = true;
  1058. } else if (step === 1) {
  1059. btn.disabled = false;
  1060. } else {
  1061. const prevStatus = statuses[step - 1];
  1062. const currentStatus = statuses[step];
  1063. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  1064. }
  1065. }
  1066. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  1067. const step = Number(btn.dataset.step);
  1068. const currentStatus = statuses[step];
  1069. const prevStatus = statuses[step - 1];
  1070. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  1071. btn.style.display = 'none';
  1072. btn.disabled = true;
  1073. btn.title = '当前不可跳过';
  1074. return;
  1075. }
  1076. if (step > 1 && !isDoneStatus(prevStatus)) {
  1077. btn.style.display = 'none';
  1078. btn.disabled = true;
  1079. btn.title = `请先完成步骤 ${step - 1}`;
  1080. return;
  1081. }
  1082. btn.style.display = '';
  1083. btn.disabled = false;
  1084. btn.title = `跳过步骤 ${step}`;
  1085. });
  1086. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  1087. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  1088. }
  1089. function updateStopButtonState(active) {
  1090. btnStop.disabled = !active;
  1091. }
  1092. function updateStatusDisplay(state) {
  1093. if (!state || !state.stepStatuses) return;
  1094. statusBar.className = 'status-bar';
  1095. if (isAutoRunScheduledPhase()) {
  1096. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  1097. ? currentAutoRun.scheduledAt - Date.now()
  1098. : 0;
  1099. displayStatus.textContent = remainingMs > 0
  1100. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  1101. : '倒计时即将结束,正在准备启动...';
  1102. statusBar.classList.add('scheduled');
  1103. return;
  1104. }
  1105. if (isAutoRunPausedPhase()) {
  1106. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  1107. statusBar.classList.add('paused');
  1108. return;
  1109. }
  1110. if (isAutoRunWaitingStepPhase()) {
  1111. const runningSteps = getRunningSteps(state);
  1112. displayStatus.textContent = runningSteps.length
  1113. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  1114. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  1115. statusBar.classList.add('running');
  1116. return;
  1117. }
  1118. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  1119. if (running) {
  1120. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  1121. statusBar.classList.add('running');
  1122. return;
  1123. }
  1124. if (isAutoRunLockedPhase()) {
  1125. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  1126. statusBar.classList.add('running');
  1127. return;
  1128. }
  1129. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  1130. if (failed) {
  1131. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  1132. statusBar.classList.add('failed');
  1133. return;
  1134. }
  1135. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  1136. if (stopped) {
  1137. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  1138. statusBar.classList.add('stopped');
  1139. return;
  1140. }
  1141. const lastCompleted = Object.entries(state.stepStatuses)
  1142. .filter(([, s]) => isDoneStatus(s))
  1143. .map(([k]) => Number(k))
  1144. .sort((a, b) => b - a)[0];
  1145. if (lastCompleted === 9) {
  1146. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  1147. statusBar.classList.add('completed');
  1148. } else if (lastCompleted) {
  1149. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  1150. ? `步骤 ${lastCompleted} 已跳过`
  1151. : `步骤 ${lastCompleted} 已完成`;
  1152. } else {
  1153. displayStatus.textContent = '就绪';
  1154. }
  1155. }
  1156. function appendLog(entry) {
  1157. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  1158. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  1159. const line = document.createElement('div');
  1160. line.className = `log-line log-${entry.level}`;
  1161. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  1162. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  1163. let html = `<span class="log-time">${time}</span> `;
  1164. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  1165. if (stepNum) {
  1166. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  1167. }
  1168. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  1169. line.innerHTML = html;
  1170. logArea.appendChild(line);
  1171. logArea.scrollTop = logArea.scrollHeight;
  1172. }
  1173. function escapeHtml(text) {
  1174. const div = document.createElement('div');
  1175. div.textContent = text;
  1176. return div.innerHTML;
  1177. }
  1178. async function fetchGeneratedEmail(options = {}) {
  1179. const { showFailureToast = true } = options;
  1180. const uiCopy = getEmailGeneratorUiCopy();
  1181. const defaultLabel = uiCopy.buttonLabel;
  1182. btnFetchEmail.disabled = true;
  1183. btnFetchEmail.textContent = '...';
  1184. try {
  1185. const response = await chrome.runtime.sendMessage({
  1186. type: 'FETCH_GENERATED_EMAIL',
  1187. source: 'sidepanel',
  1188. payload: {
  1189. generateNew: true,
  1190. generator: selectEmailGenerator.value,
  1191. },
  1192. });
  1193. if (response?.error) {
  1194. throw new Error(response.error);
  1195. }
  1196. if (!response?.email) {
  1197. throw new Error('未返回可用邮箱。');
  1198. }
  1199. inputEmail.value = response.email;
  1200. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  1201. return response.email;
  1202. } catch (err) {
  1203. if (showFailureToast) {
  1204. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  1205. }
  1206. throw err;
  1207. } finally {
  1208. btnFetchEmail.disabled = false;
  1209. btnFetchEmail.textContent = defaultLabel;
  1210. }
  1211. }
  1212. function syncToggleButtonLabel(button, input, labels) {
  1213. if (!button || !input) return;
  1214. const isHidden = input.type === 'password';
  1215. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  1216. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  1217. button.title = isHidden ? labels.show : labels.hide;
  1218. }
  1219. async function copyTextToClipboard(text) {
  1220. const value = String(text || '').trim();
  1221. if (!value) {
  1222. throw new Error('没有可复制的内容。');
  1223. }
  1224. if (!navigator.clipboard?.writeText) {
  1225. throw new Error('当前环境不支持剪贴板复制。');
  1226. }
  1227. await navigator.clipboard.writeText(value);
  1228. }
  1229. async function deleteHotmailAccountsByMode(mode) {
  1230. const isUsedMode = mode === 'used';
  1231. const targetAccounts = getHotmailAccountsByUsage(isUsedMode ? 'used' : 'all');
  1232. if (!targetAccounts.length) {
  1233. showToast(isUsedMode ? '没有已用账号可清空。' : '没有可删除的 Hotmail 账号。', 'warn');
  1234. return;
  1235. }
  1236. const confirmed = await openConfirmModal({
  1237. title: isUsedMode ? '清空已用账号' : '全部删除账号',
  1238. message: isUsedMode
  1239. ? `确认删除当前 ${targetAccounts.length} 个已用 Hotmail 账号吗?`
  1240. : `确认删除全部 ${targetAccounts.length} 个 Hotmail 账号吗?`,
  1241. confirmLabel: isUsedMode ? '确认清空已用' : '确认全部删除',
  1242. confirmVariant: isUsedMode ? 'btn-outline' : 'btn-danger',
  1243. });
  1244. if (!confirmed) {
  1245. return;
  1246. }
  1247. const response = await chrome.runtime.sendMessage({
  1248. type: 'DELETE_HOTMAIL_ACCOUNTS',
  1249. source: 'sidepanel',
  1250. payload: { mode: isUsedMode ? 'used' : 'all' },
  1251. });
  1252. if (response?.error) {
  1253. throw new Error(response.error);
  1254. }
  1255. const targetIds = new Set(targetAccounts.map((account) => account.id));
  1256. const nextAccounts = isUsedMode
  1257. ? getHotmailAccounts().filter((account) => !targetIds.has(account.id))
  1258. : [];
  1259. const nextState = { hotmailAccounts: nextAccounts };
  1260. if (latestState?.currentHotmailAccountId && targetIds.has(latestState.currentHotmailAccountId)) {
  1261. nextState.currentHotmailAccountId = null;
  1262. if (selectMailProvider.value === 'hotmail-api') {
  1263. nextState.email = null;
  1264. }
  1265. }
  1266. syncLatestState(nextState);
  1267. refreshHotmailSelectionUI();
  1268. showToast(
  1269. isUsedMode
  1270. ? `已清空 ${response.deletedCount || 0} 个已用 Hotmail 账号`
  1271. : `已删除全部 ${response.deletedCount || 0} 个 Hotmail 账号`,
  1272. 'success',
  1273. 2200
  1274. );
  1275. }
  1276. function syncPasswordToggleLabel() {
  1277. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  1278. show: '显示密码',
  1279. hide: '隐藏密码',
  1280. });
  1281. }
  1282. function syncVpsUrlToggleLabel() {
  1283. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  1284. show: '显示 CPA 地址',
  1285. hide: '隐藏 CPA 地址',
  1286. });
  1287. }
  1288. function syncVpsPasswordToggleLabel() {
  1289. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  1290. show: '显示管理密钥',
  1291. hide: '隐藏管理密钥',
  1292. });
  1293. }
  1294. async function maybeTakeoverAutoRun(actionLabel) {
  1295. if (!isAutoRunPausedPhase()) {
  1296. return true;
  1297. }
  1298. const confirmed = await openConfirmModal({
  1299. title: '接管自动',
  1300. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  1301. confirmLabel: '确认接管',
  1302. confirmVariant: 'btn-primary',
  1303. });
  1304. if (!confirmed) {
  1305. return false;
  1306. }
  1307. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  1308. return true;
  1309. }
  1310. async function handleSkipStep(step) {
  1311. if (isAutoRunPausedPhase()) {
  1312. const takeoverResponse = await chrome.runtime.sendMessage({
  1313. type: 'TAKEOVER_AUTO_RUN',
  1314. source: 'sidepanel',
  1315. payload: {},
  1316. });
  1317. if (takeoverResponse?.error) {
  1318. throw new Error(takeoverResponse.error);
  1319. }
  1320. }
  1321. const response = await chrome.runtime.sendMessage({
  1322. type: 'SKIP_STEP',
  1323. source: 'sidepanel',
  1324. payload: { step },
  1325. });
  1326. if (response?.error) {
  1327. throw new Error(response.error);
  1328. }
  1329. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  1330. }
  1331. // ============================================================
  1332. // Button Handlers
  1333. // ============================================================
  1334. document.querySelectorAll('.step-btn').forEach(btn => {
  1335. btn.addEventListener('click', async () => {
  1336. try {
  1337. const step = Number(btn.dataset.step);
  1338. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  1339. return;
  1340. }
  1341. if (step === 3) {
  1342. if (inputPassword.value !== (latestState?.customPassword || '')) {
  1343. await chrome.runtime.sendMessage({
  1344. type: 'SAVE_SETTING',
  1345. source: 'sidepanel',
  1346. payload: { customPassword: inputPassword.value },
  1347. });
  1348. syncLatestState({ customPassword: inputPassword.value });
  1349. }
  1350. let email = inputEmail.value.trim();
  1351. if (selectMailProvider.value === 'hotmail-api') {
  1352. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1353. if (response?.error) {
  1354. throw new Error(response.error);
  1355. }
  1356. } else {
  1357. let email = inputEmail.value.trim();
  1358. if (!email) {
  1359. try {
  1360. email = await fetchGeneratedEmail({ showFailureToast: false });
  1361. } catch (err) {
  1362. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  1363. return;
  1364. }
  1365. }
  1366. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  1367. if (response?.error) {
  1368. throw new Error(response.error);
  1369. }
  1370. }
  1371. } else {
  1372. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1373. if (response?.error) {
  1374. throw new Error(response.error);
  1375. }
  1376. }
  1377. } catch (err) {
  1378. showToast(err.message, 'error');
  1379. }
  1380. });
  1381. });
  1382. btnFetchEmail.addEventListener('click', async () => {
  1383. if (selectMailProvider.value === 'hotmail-api') {
  1384. return;
  1385. }
  1386. await fetchGeneratedEmail().catch(() => { });
  1387. });
  1388. btnToggleHotmailList?.addEventListener('click', () => {
  1389. setHotmailListExpanded(!hotmailListExpanded);
  1390. });
  1391. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  1392. if (hotmailActionInFlight) return;
  1393. hotmailActionInFlight = true;
  1394. btnClearUsedHotmailAccounts.disabled = true;
  1395. try {
  1396. await deleteHotmailAccountsByMode('used');
  1397. } catch (err) {
  1398. showToast(err.message, 'error');
  1399. } finally {
  1400. hotmailActionInFlight = false;
  1401. updateHotmailListViewport();
  1402. }
  1403. });
  1404. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  1405. if (hotmailActionInFlight) return;
  1406. hotmailActionInFlight = true;
  1407. btnDeleteAllHotmailAccounts.disabled = true;
  1408. try {
  1409. await deleteHotmailAccountsByMode('all');
  1410. } catch (err) {
  1411. showToast(err.message, 'error');
  1412. } finally {
  1413. hotmailActionInFlight = false;
  1414. updateHotmailListViewport();
  1415. }
  1416. });
  1417. btnAddHotmailAccount?.addEventListener('click', async () => {
  1418. if (hotmailActionInFlight) return;
  1419. const email = inputHotmailEmail.value.trim();
  1420. const clientId = inputHotmailClientId.value.trim();
  1421. const refreshToken = inputHotmailRefreshToken.value.trim();
  1422. if (!email) {
  1423. showToast('请先填写 Hotmail 邮箱。', 'warn');
  1424. return;
  1425. }
  1426. if (!clientId) {
  1427. showToast('请先填写微软应用客户端 ID。', 'warn');
  1428. return;
  1429. }
  1430. if (!refreshToken) {
  1431. showToast('请先填写刷新令牌(refresh token)。', 'warn');
  1432. return;
  1433. }
  1434. hotmailActionInFlight = true;
  1435. btnAddHotmailAccount.disabled = true;
  1436. try {
  1437. const response = await chrome.runtime.sendMessage({
  1438. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1439. source: 'sidepanel',
  1440. payload: {
  1441. email,
  1442. clientId,
  1443. password: inputHotmailPassword.value,
  1444. refreshToken,
  1445. },
  1446. });
  1447. if (response?.error) {
  1448. throw new Error(response.error);
  1449. }
  1450. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  1451. clearHotmailForm();
  1452. } catch (err) {
  1453. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  1454. } finally {
  1455. hotmailActionInFlight = false;
  1456. btnAddHotmailAccount.disabled = false;
  1457. }
  1458. });
  1459. btnImportHotmailAccounts?.addEventListener('click', async () => {
  1460. if (hotmailActionInFlight) return;
  1461. if (typeof parseHotmailImportText !== 'function') {
  1462. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  1463. return;
  1464. }
  1465. const rawText = inputHotmailImport.value.trim();
  1466. if (!rawText) {
  1467. showToast('请先粘贴账号导入内容。', 'warn');
  1468. return;
  1469. }
  1470. const parsedAccounts = parseHotmailImportText(rawText);
  1471. if (!parsedAccounts.length) {
  1472. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  1473. return;
  1474. }
  1475. hotmailActionInFlight = true;
  1476. btnImportHotmailAccounts.disabled = true;
  1477. try {
  1478. for (const account of parsedAccounts) {
  1479. const response = await chrome.runtime.sendMessage({
  1480. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1481. source: 'sidepanel',
  1482. payload: account,
  1483. });
  1484. if (response?.error) {
  1485. throw new Error(response.error);
  1486. }
  1487. }
  1488. inputHotmailImport.value = '';
  1489. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  1490. } catch (err) {
  1491. showToast(`批量导入失败:${err.message}`, 'error');
  1492. } finally {
  1493. hotmailActionInFlight = false;
  1494. btnImportHotmailAccounts.disabled = false;
  1495. }
  1496. });
  1497. hotmailAccountsList?.addEventListener('click', async (event) => {
  1498. const actionButton = event.target.closest('[data-account-action]');
  1499. if (!actionButton || hotmailActionInFlight) {
  1500. return;
  1501. }
  1502. const accountId = actionButton.dataset.accountId;
  1503. const action = actionButton.dataset.accountAction;
  1504. if (!accountId || !action) {
  1505. return;
  1506. }
  1507. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  1508. hotmailActionInFlight = true;
  1509. actionButton.disabled = true;
  1510. try {
  1511. if (action === 'copy-email') {
  1512. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  1513. await copyTextToClipboard(targetAccount.email);
  1514. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  1515. } else if (action === 'select') {
  1516. const response = await chrome.runtime.sendMessage({
  1517. type: 'SELECT_HOTMAIL_ACCOUNT',
  1518. source: 'sidepanel',
  1519. payload: { accountId },
  1520. });
  1521. if (response?.error) throw new Error(response.error);
  1522. syncLatestState({ currentHotmailAccountId: response.account.id });
  1523. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1524. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  1525. } else if (action === 'toggle-used') {
  1526. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  1527. const response = await chrome.runtime.sendMessage({
  1528. type: 'PATCH_HOTMAIL_ACCOUNT',
  1529. source: 'sidepanel',
  1530. payload: {
  1531. accountId,
  1532. updates: { used: !targetAccount.used },
  1533. },
  1534. });
  1535. if (response?.error) throw new Error(response.error);
  1536. applyHotmailAccountMutation(response.account);
  1537. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  1538. } else if (action === 'verify') {
  1539. const response = await chrome.runtime.sendMessage({
  1540. type: 'VERIFY_HOTMAIL_ACCOUNT',
  1541. source: 'sidepanel',
  1542. payload: { accountId },
  1543. });
  1544. if (response?.error) throw new Error(response.error);
  1545. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1546. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  1547. } else if (action === 'test') {
  1548. const response = await chrome.runtime.sendMessage({
  1549. type: 'TEST_HOTMAIL_ACCOUNT',
  1550. source: 'sidepanel',
  1551. payload: { accountId },
  1552. });
  1553. if (response?.error) throw new Error(response.error);
  1554. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1555. if (response.latestCode) {
  1556. await copyTextToClipboard(response.latestCode);
  1557. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1558. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  1559. } else if (response.latestSubject) {
  1560. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1561. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  1562. } else {
  1563. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  1564. }
  1565. } else if (action === 'delete') {
  1566. const confirmed = await openConfirmModal({
  1567. title: '删除账号',
  1568. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  1569. confirmLabel: '确认删除',
  1570. confirmVariant: 'btn-danger',
  1571. });
  1572. if (!confirmed) {
  1573. return;
  1574. }
  1575. const response = await chrome.runtime.sendMessage({
  1576. type: 'DELETE_HOTMAIL_ACCOUNT',
  1577. source: 'sidepanel',
  1578. payload: { accountId },
  1579. });
  1580. if (response?.error) throw new Error(response.error);
  1581. showToast('Hotmail 账号已删除', 'success', 1800);
  1582. }
  1583. } catch (err) {
  1584. showToast(err.message, 'error');
  1585. } finally {
  1586. hotmailActionInFlight = false;
  1587. actionButton.disabled = false;
  1588. }
  1589. });
  1590. btnTogglePassword.addEventListener('click', () => {
  1591. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  1592. syncPasswordToggleLabel();
  1593. });
  1594. btnToggleVpsUrl.addEventListener('click', () => {
  1595. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  1596. syncVpsUrlToggleLabel();
  1597. });
  1598. btnToggleVpsPassword.addEventListener('click', () => {
  1599. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  1600. syncVpsPasswordToggleLabel();
  1601. });
  1602. localCpaStep9ModeButtons.forEach((button) => {
  1603. button.addEventListener('click', () => {
  1604. const nextMode = button.dataset.localCpaStep9Mode;
  1605. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  1606. return;
  1607. }
  1608. setLocalCpaStep9Mode(nextMode);
  1609. markSettingsDirty(true);
  1610. saveSettings({ silent: true }).catch(() => { });
  1611. });
  1612. });
  1613. btnSaveSettings.addEventListener('click', async () => {
  1614. if (!settingsDirty) {
  1615. showToast('配置已是最新', 'info', 1400);
  1616. return;
  1617. }
  1618. await saveSettings({ silent: false }).catch(() => { });
  1619. });
  1620. btnStop.addEventListener('click', async () => {
  1621. btnStop.disabled = true;
  1622. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  1623. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  1624. });
  1625. autoStartModal?.addEventListener('click', (event) => {
  1626. if (event.target === autoStartModal) {
  1627. resolveModalChoice(null);
  1628. }
  1629. });
  1630. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  1631. // Auto Run
  1632. btnAutoRun.addEventListener('click', async () => {
  1633. try {
  1634. const totalRuns = Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  1635. let mode = 'restart';
  1636. if (shouldOfferAutoModeChoice()) {
  1637. const startStep = getFirstUnfinishedStep();
  1638. const runningStep = getRunningSteps()[0] ?? null;
  1639. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  1640. if (!choice) {
  1641. return;
  1642. }
  1643. mode = choice;
  1644. }
  1645. btnAutoRun.disabled = true;
  1646. inputRunCount.disabled = true;
  1647. const delayEnabled = inputAutoDelayEnabled.checked;
  1648. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  1649. inputAutoDelayMinutes.value = String(delayMinutes);
  1650. btnAutoRun.innerHTML = delayEnabled
  1651. ? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 计划中...'
  1652. : '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> 运行中...';
  1653. const response = await chrome.runtime.sendMessage({
  1654. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  1655. source: 'sidepanel',
  1656. payload: {
  1657. totalRuns,
  1658. delayMinutes,
  1659. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1660. mode,
  1661. },
  1662. });
  1663. if (response?.error) {
  1664. throw new Error(response.error);
  1665. }
  1666. } catch (err) {
  1667. setDefaultAutoRunButton();
  1668. inputRunCount.disabled = false;
  1669. showToast(err.message, 'error');
  1670. }
  1671. });
  1672. btnAutoContinue.addEventListener('click', async () => {
  1673. const email = inputEmail.value.trim();
  1674. if (!email) {
  1675. showToast('请先获取或粘贴邮箱。', 'warn');
  1676. return;
  1677. }
  1678. autoContinueBar.style.display = 'none';
  1679. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  1680. });
  1681. btnAutoRunNow?.addEventListener('click', async () => {
  1682. try {
  1683. btnAutoRunNow.disabled = true;
  1684. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  1685. } catch (err) {
  1686. showToast(err.message, 'error');
  1687. } finally {
  1688. btnAutoRunNow.disabled = false;
  1689. }
  1690. });
  1691. btnAutoCancelSchedule?.addEventListener('click', async () => {
  1692. try {
  1693. btnAutoCancelSchedule.disabled = true;
  1694. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  1695. showToast('已取消倒计时计划。', 'info', 1800);
  1696. } catch (err) {
  1697. showToast(err.message, 'error');
  1698. } finally {
  1699. btnAutoCancelSchedule.disabled = false;
  1700. }
  1701. });
  1702. // Reset
  1703. btnReset.addEventListener('click', async () => {
  1704. const confirmed = await openConfirmModal({
  1705. title: '重置流程',
  1706. message: '确认重置全部步骤和数据吗?',
  1707. confirmLabel: '确认重置',
  1708. confirmVariant: 'btn-danger',
  1709. });
  1710. if (!confirmed) {
  1711. return;
  1712. }
  1713. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  1714. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  1715. syncAutoRunState({
  1716. autoRunning: false,
  1717. autoRunPhase: 'idle',
  1718. autoRunCurrentRun: 0,
  1719. autoRunTotalRuns: 1,
  1720. autoRunAttemptRun: 0,
  1721. scheduledAutoRunAt: null,
  1722. });
  1723. displayOauthUrl.textContent = '等待中...';
  1724. displayOauthUrl.classList.remove('has-value');
  1725. displayLocalhostUrl.textContent = '等待中...';
  1726. displayLocalhostUrl.classList.remove('has-value');
  1727. inputEmail.value = '';
  1728. displayStatus.textContent = '就绪';
  1729. statusBar.className = 'status-bar';
  1730. logArea.innerHTML = '';
  1731. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1732. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1733. setDefaultAutoRunButton();
  1734. applyAutoRunStatus(currentAutoRun);
  1735. markSettingsDirty(false);
  1736. updateStopButtonState(false);
  1737. updateButtonStates();
  1738. updateProgressCounter();
  1739. renderHotmailAccounts();
  1740. });
  1741. // Clear log
  1742. btnClearLog.addEventListener('click', () => {
  1743. logArea.innerHTML = '';
  1744. });
  1745. // Save settings on change
  1746. inputEmail.addEventListener('change', async () => {
  1747. if (selectMailProvider.value === 'hotmail-api') {
  1748. return;
  1749. }
  1750. const email = inputEmail.value.trim();
  1751. inputEmail.value = email;
  1752. try {
  1753. if (email) {
  1754. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  1755. if (response?.error) {
  1756. throw new Error(response.error);
  1757. }
  1758. } else {
  1759. await setRuntimeEmailState(null);
  1760. }
  1761. } catch (err) {
  1762. showToast(err.message, 'error');
  1763. }
  1764. });
  1765. inputEmail.addEventListener('input', updateButtonStates);
  1766. inputVpsUrl.addEventListener('input', () => {
  1767. markSettingsDirty(true);
  1768. scheduleSettingsAutoSave();
  1769. });
  1770. inputVpsUrl.addEventListener('blur', () => {
  1771. saveSettings({ silent: true }).catch(() => { });
  1772. });
  1773. inputVpsPassword.addEventListener('input', () => {
  1774. markSettingsDirty(true);
  1775. scheduleSettingsAutoSave();
  1776. });
  1777. inputVpsPassword.addEventListener('blur', () => {
  1778. saveSettings({ silent: true }).catch(() => { });
  1779. });
  1780. inputPassword.addEventListener('input', () => {
  1781. markSettingsDirty(true);
  1782. updateButtonStates();
  1783. scheduleSettingsAutoSave();
  1784. });
  1785. inputPassword.addEventListener('blur', () => {
  1786. saveSettings({ silent: true }).catch(() => { });
  1787. });
  1788. selectMailProvider.addEventListener('change', () => {
  1789. updateMailProviderUI();
  1790. markSettingsDirty(true);
  1791. saveSettings({ silent: true }).catch(() => { });
  1792. });
  1793. selectEmailGenerator.addEventListener('change', () => {
  1794. updateMailProviderUI();
  1795. clearRegistrationEmail({ silent: true }).catch(() => { });
  1796. markSettingsDirty(true);
  1797. saveSettings({ silent: true }).catch(() => { });
  1798. });
  1799. selectPanelMode.addEventListener('change', () => {
  1800. updatePanelModeUI();
  1801. markSettingsDirty(true);
  1802. saveSettings({ silent: true }).catch(() => { });
  1803. });
  1804. selectCfDomain.addEventListener('change', () => {
  1805. if (selectCfDomain.disabled) {
  1806. return;
  1807. }
  1808. markSettingsDirty(true);
  1809. saveSettings({ silent: true }).catch(() => { });
  1810. });
  1811. btnCfDomainMode.addEventListener('click', async () => {
  1812. try {
  1813. if (!cloudflareDomainEditMode) {
  1814. setCloudflareDomainEditMode(true, { clearInput: true });
  1815. return;
  1816. }
  1817. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  1818. if (!newDomain) {
  1819. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  1820. inputCfDomain.focus();
  1821. return;
  1822. }
  1823. const { domains } = getCloudflareDomainsFromState();
  1824. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  1825. } catch (err) {
  1826. showToast(err.message, 'error');
  1827. }
  1828. });
  1829. inputCfDomain.addEventListener('keydown', (event) => {
  1830. if (event.key === 'Enter') {
  1831. event.preventDefault();
  1832. btnCfDomainMode.click();
  1833. }
  1834. });
  1835. inputSub2ApiUrl.addEventListener('input', () => {
  1836. markSettingsDirty(true);
  1837. scheduleSettingsAutoSave();
  1838. });
  1839. inputSub2ApiUrl.addEventListener('blur', () => {
  1840. saveSettings({ silent: true }).catch(() => { });
  1841. });
  1842. inputSub2ApiEmail.addEventListener('input', () => {
  1843. markSettingsDirty(true);
  1844. scheduleSettingsAutoSave();
  1845. });
  1846. inputSub2ApiEmail.addEventListener('blur', () => {
  1847. saveSettings({ silent: true }).catch(() => { });
  1848. });
  1849. inputSub2ApiPassword.addEventListener('input', () => {
  1850. markSettingsDirty(true);
  1851. scheduleSettingsAutoSave();
  1852. });
  1853. inputSub2ApiPassword.addEventListener('blur', () => {
  1854. saveSettings({ silent: true }).catch(() => { });
  1855. });
  1856. inputSub2ApiGroup.addEventListener('input', () => {
  1857. markSettingsDirty(true);
  1858. scheduleSettingsAutoSave();
  1859. });
  1860. inputSub2ApiGroup.addEventListener('blur', () => {
  1861. saveSettings({ silent: true }).catch(() => { });
  1862. });
  1863. inputInbucketMailbox.addEventListener('input', () => {
  1864. markSettingsDirty(true);
  1865. scheduleSettingsAutoSave();
  1866. });
  1867. inputInbucketMailbox.addEventListener('blur', () => {
  1868. saveSettings({ silent: true }).catch(() => { });
  1869. });
  1870. inputInbucketHost.addEventListener('input', () => {
  1871. markSettingsDirty(true);
  1872. scheduleSettingsAutoSave();
  1873. });
  1874. inputInbucketHost.addEventListener('blur', () => {
  1875. saveSettings({ silent: true }).catch(() => { });
  1876. });
  1877. inputAutoSkipFailures.addEventListener('change', () => {
  1878. markSettingsDirty(true);
  1879. saveSettings({ silent: true }).catch(() => { });
  1880. });
  1881. inputAutoDelayEnabled.addEventListener('change', () => {
  1882. updateAutoDelayInputState();
  1883. markSettingsDirty(true);
  1884. saveSettings({ silent: true }).catch(() => { });
  1885. });
  1886. inputAutoDelayMinutes.addEventListener('input', () => {
  1887. markSettingsDirty(true);
  1888. scheduleSettingsAutoSave();
  1889. });
  1890. inputAutoDelayMinutes.addEventListener('blur', () => {
  1891. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  1892. saveSettings({ silent: true }).catch(() => { });
  1893. });
  1894. // ============================================================
  1895. // Listen for Background broadcasts
  1896. // ============================================================
  1897. chrome.runtime.onMessage.addListener((message) => {
  1898. switch (message.type) {
  1899. case 'LOG_ENTRY':
  1900. appendLog(message.payload);
  1901. if (message.payload.level === 'error') {
  1902. showToast(message.payload.message, 'error');
  1903. }
  1904. break;
  1905. case 'STEP_STATUS_CHANGED': {
  1906. const { step, status } = message.payload;
  1907. updateStepUI(step, status);
  1908. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  1909. syncLatestState(state);
  1910. syncAutoRunState(state);
  1911. updateStatusDisplay(latestState);
  1912. updateButtonStates();
  1913. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  1914. syncPasswordField(state);
  1915. if (state.oauthUrl) {
  1916. displayOauthUrl.textContent = state.oauthUrl;
  1917. displayOauthUrl.classList.add('has-value');
  1918. }
  1919. if (state.localhostUrl) {
  1920. displayLocalhostUrl.textContent = state.localhostUrl;
  1921. displayLocalhostUrl.classList.add('has-value');
  1922. }
  1923. }
  1924. }
  1925. ).catch(() => { });
  1926. break;
  1927. }
  1928. case 'AUTO_RUN_RESET': {
  1929. // Full UI reset for next run
  1930. syncLatestState({
  1931. oauthUrl: null,
  1932. localhostUrl: null,
  1933. email: null,
  1934. password: null,
  1935. stepStatuses: STEP_DEFAULT_STATUSES,
  1936. logs: [],
  1937. scheduledAutoRunAt: null,
  1938. });
  1939. displayOauthUrl.textContent = '等待中...';
  1940. displayOauthUrl.classList.remove('has-value');
  1941. displayLocalhostUrl.textContent = '等待中...';
  1942. displayLocalhostUrl.classList.remove('has-value');
  1943. inputEmail.value = '';
  1944. displayStatus.textContent = '就绪';
  1945. statusBar.className = 'status-bar';
  1946. logArea.innerHTML = '';
  1947. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1948. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1949. applyAutoRunStatus(currentAutoRun);
  1950. updateProgressCounter();
  1951. updateButtonStates();
  1952. renderHotmailAccounts();
  1953. break;
  1954. }
  1955. case 'DATA_UPDATED': {
  1956. syncLatestState(message.payload);
  1957. if (message.payload.email !== undefined) {
  1958. inputEmail.value = message.payload.email || '';
  1959. }
  1960. if (message.payload.password !== undefined) {
  1961. inputPassword.value = message.payload.password || '';
  1962. }
  1963. if (message.payload.localCpaStep9Mode !== undefined) {
  1964. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  1965. }
  1966. if (message.payload.oauthUrl !== undefined) {
  1967. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  1968. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  1969. }
  1970. if (message.payload.localhostUrl !== undefined) {
  1971. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  1972. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  1973. }
  1974. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  1975. renderHotmailAccounts();
  1976. if (selectMailProvider.value === 'hotmail-api') {
  1977. const currentAccount = getCurrentHotmailAccount();
  1978. inputEmail.value = currentAccount?.email || latestState?.email || '';
  1979. }
  1980. }
  1981. if (message.payload.autoRunDelayEnabled !== undefined) {
  1982. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  1983. updateAutoDelayInputState();
  1984. }
  1985. if (message.payload.autoRunDelayMinutes !== undefined) {
  1986. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  1987. }
  1988. break;
  1989. }
  1990. case 'AUTO_RUN_STATUS': {
  1991. syncLatestState({
  1992. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(message.payload.phase),
  1993. autoRunPhase: message.payload.phase,
  1994. autoRunCurrentRun: message.payload.currentRun,
  1995. autoRunTotalRuns: message.payload.totalRuns,
  1996. autoRunAttemptRun: message.payload.attemptRun,
  1997. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  1998. });
  1999. applyAutoRunStatus(message.payload);
  2000. updateStatusDisplay(latestState);
  2001. updateButtonStates();
  2002. break;
  2003. }
  2004. }
  2005. });
  2006. // ============================================================
  2007. // Theme Toggle
  2008. // ============================================================
  2009. const btnTheme = document.getElementById('btn-theme');
  2010. function setTheme(theme) {
  2011. document.documentElement.setAttribute('data-theme', theme);
  2012. localStorage.setItem('multipage-theme', theme);
  2013. }
  2014. function initTheme() {
  2015. const saved = localStorage.getItem('multipage-theme');
  2016. if (saved) {
  2017. setTheme(saved);
  2018. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  2019. setTheme('dark');
  2020. }
  2021. }
  2022. btnTheme.addEventListener('click', () => {
  2023. const current = document.documentElement.getAttribute('data-theme');
  2024. setTheme(current === 'dark' ? 'light' : 'dark');
  2025. });
  2026. // ============================================================
  2027. // Init
  2028. // ============================================================
  2029. initializeManualStepActions();
  2030. initTheme();
  2031. initHotmailListExpandedState();
  2032. updateSaveButtonState();
  2033. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  2034. restoreState().then(() => {
  2035. syncPasswordToggleLabel();
  2036. syncVpsUrlToggleLabel();
  2037. syncVpsPasswordToggleLabel();
  2038. updatePanelModeUI();
  2039. updateButtonStates();
  2040. updateStatusDisplay(latestState);
  2041. });