sidepanel.js 86 KB

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