sidepanel.js 84 KB

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