sidepanel.js 77 KB

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