sidepanel.js 78 KB

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