sidepanel.js 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236
  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 updateSection = document.getElementById('update-section');
  13. const extensionUpdateStatus = document.getElementById('extension-update-status');
  14. const extensionVersionMeta = document.getElementById('extension-version-meta');
  15. const btnReleaseLog = document.getElementById('btn-release-log');
  16. const updateCardVersion = document.getElementById('update-card-version');
  17. const updateCardSummary = document.getElementById('update-card-summary');
  18. const updateReleaseList = document.getElementById('update-release-list');
  19. const btnOpenRelease = document.getElementById('btn-open-release');
  20. const settingsCard = document.getElementById('settings-card');
  21. const displayOauthUrl = document.getElementById('display-oauth-url');
  22. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  23. const displayStatus = document.getElementById('display-status');
  24. const statusBar = document.getElementById('status-bar');
  25. const inputEmail = document.getElementById('input-email');
  26. const inputPassword = document.getElementById('input-password');
  27. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  28. const btnToggleVpsPassword = document.getElementById('btn-toggle-vps-password');
  29. const btnFetchEmail = document.getElementById('btn-fetch-email');
  30. const btnTogglePassword = document.getElementById('btn-toggle-password');
  31. const btnSaveSettings = document.getElementById('btn-save-settings');
  32. const btnStop = document.getElementById('btn-stop');
  33. const btnReset = document.getElementById('btn-reset');
  34. const stepsProgress = document.getElementById('steps-progress');
  35. const btnAutoRun = document.getElementById('btn-auto-run');
  36. const btnAutoContinue = document.getElementById('btn-auto-continue');
  37. const autoContinueBar = document.getElementById('auto-continue-bar');
  38. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  39. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  40. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  41. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  42. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  43. const btnClearLog = document.getElementById('btn-clear-log');
  44. const configMenuShell = document.getElementById('config-menu-shell');
  45. const btnConfigMenu = document.getElementById('btn-config-menu');
  46. const configMenu = document.getElementById('config-menu');
  47. const btnExportSettings = document.getElementById('btn-export-settings');
  48. const btnImportSettings = document.getElementById('btn-import-settings');
  49. const inputImportSettingsFile = document.getElementById('input-import-settings-file');
  50. const selectPanelMode = document.getElementById('select-panel-mode');
  51. const rowVpsUrl = document.getElementById('row-vps-url');
  52. const inputVpsUrl = document.getElementById('input-vps-url');
  53. const rowVpsPassword = document.getElementById('row-vps-password');
  54. const inputVpsPassword = document.getElementById('input-vps-password');
  55. const rowLocalCpaStep9Mode = document.getElementById('row-local-cpa-step9-mode');
  56. const localCpaStep9ModeButtons = Array.from(document.querySelectorAll('[data-local-cpa-step9-mode]'));
  57. const rowSub2ApiUrl = document.getElementById('row-sub2api-url');
  58. const inputSub2ApiUrl = document.getElementById('input-sub2api-url');
  59. const rowSub2ApiEmail = document.getElementById('row-sub2api-email');
  60. const inputSub2ApiEmail = document.getElementById('input-sub2api-email');
  61. const rowSub2ApiPassword = document.getElementById('row-sub2api-password');
  62. const inputSub2ApiPassword = document.getElementById('input-sub2api-password');
  63. const rowSub2ApiGroup = document.getElementById('row-sub2api-group');
  64. const inputSub2ApiGroup = document.getElementById('input-sub2api-group');
  65. const selectMailProvider = document.getElementById('select-mail-provider');
  66. const btnMailLogin = document.getElementById('btn-mail-login');
  67. const rowEmailGenerator = document.getElementById('row-email-generator');
  68. const selectEmailGenerator = document.getElementById('select-email-generator');
  69. const hotmailSection = document.getElementById('hotmail-section');
  70. const rowHotmailServiceMode = document.getElementById('row-hotmail-service-mode');
  71. const hotmailServiceModeButtons = Array.from(document.querySelectorAll('[data-hotmail-service-mode]'));
  72. const rowHotmailRemoteBaseUrl = document.getElementById('row-hotmail-remote-base-url');
  73. const inputHotmailRemoteBaseUrl = document.getElementById('input-hotmail-remote-base-url');
  74. const rowHotmailLocalBaseUrl = document.getElementById('row-hotmail-local-base-url');
  75. const inputHotmailLocalBaseUrl = document.getElementById('input-hotmail-local-base-url');
  76. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  77. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  78. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  79. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  80. const inputHotmailImport = document.getElementById('input-hotmail-import');
  81. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  82. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  83. const btnHotmailUsageGuide = document.getElementById('btn-hotmail-usage-guide');
  84. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  85. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  86. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  87. const hotmailListShell = document.getElementById('hotmail-list-shell');
  88. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  89. const rowEmailPrefix = document.getElementById('row-email-prefix');
  90. const labelEmailPrefix = document.getElementById('label-email-prefix');
  91. const inputEmailPrefix = document.getElementById('input-email-prefix');
  92. const rowInbucketHost = document.getElementById('row-inbucket-host');
  93. const inputInbucketHost = document.getElementById('input-inbucket-host');
  94. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  95. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  96. const rowCfDomain = document.getElementById('row-cf-domain');
  97. const selectCfDomain = document.getElementById('select-cf-domain');
  98. const inputCfDomain = document.getElementById('input-cf-domain');
  99. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  100. const inputRunCount = document.getElementById('input-run-count');
  101. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  102. const inputAutoSkipFailuresThreadIntervalMinutes = document.getElementById('input-auto-skip-failures-thread-interval-minutes');
  103. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  104. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  105. const inputAutoStepDelaySeconds = document.getElementById('input-auto-step-delay-seconds');
  106. const autoStartModal = document.getElementById('auto-start-modal');
  107. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  108. const autoStartMessage = document.getElementById('auto-start-message');
  109. const modalOptionRow = document.getElementById('modal-option-row');
  110. const modalOptionInput = document.getElementById('modal-option-input');
  111. const modalOptionText = document.getElementById('modal-option-text');
  112. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  113. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  114. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  115. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  116. const autoHintText = document.querySelector('.auto-hint');
  117. const STEP_DEFAULT_STATUSES = {
  118. 1: 'pending',
  119. 2: 'pending',
  120. 3: 'pending',
  121. 4: 'pending',
  122. 5: 'pending',
  123. 6: 'pending',
  124. 7: 'pending',
  125. 8: 'pending',
  126. 9: 'pending',
  127. };
  128. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  129. const AUTO_DELAY_MIN_MINUTES = 1;
  130. const AUTO_DELAY_MAX_MINUTES = 1440;
  131. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  132. const AUTO_FALLBACK_THREAD_INTERVAL_MIN_MINUTES = 0;
  133. const AUTO_FALLBACK_THREAD_INTERVAL_MAX_MINUTES = 1440;
  134. const AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES = 0;
  135. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  136. const AUTO_STEP_DELAY_MIN_SECONDS = 0;
  137. const AUTO_STEP_DELAY_MAX_SECONDS = 600;
  138. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  139. const AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-auto-skip-failures-prompt-dismissed';
  140. const AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY = 'multipage-auto-run-fallback-risk-prompt-dismissed';
  141. const AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS = 15;
  142. const AUTO_RUN_FALLBACK_RISK_RECOMMENDED_THREAD_INTERVAL_MINUTES = 5;
  143. const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
  144. const HOTMAIL_SERVICE_MODE_LOCAL = 'local';
  145. let latestState = null;
  146. let currentAutoRun = {
  147. autoRunning: false,
  148. phase: 'idle',
  149. currentRun: 0,
  150. totalRuns: 1,
  151. attemptRun: 0,
  152. scheduledAt: null,
  153. };
  154. let settingsDirty = false;
  155. let settingsSaveInFlight = false;
  156. let settingsAutoSaveTimer = null;
  157. let cloudflareDomainEditMode = false;
  158. let modalChoiceResolver = null;
  159. let currentModalActions = [];
  160. let modalResultBuilder = null;
  161. let scheduledCountdownTimer = null;
  162. let hotmailActionInFlight = false;
  163. let hotmailListExpanded = false;
  164. let configMenuOpen = false;
  165. let configActionInFlight = false;
  166. let currentReleaseSnapshot = null;
  167. 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>';
  168. 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>';
  169. 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>';
  170. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  171. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  172. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  173. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  174. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  175. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  176. const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
  177. const sidepanelUpdateService = window.SidepanelUpdateService;
  178. const MAIL_PROVIDER_LOGIN_CONFIGS = {
  179. '163': {
  180. label: '163 邮箱',
  181. url: 'https://mail.163.com/',
  182. },
  183. '163-vip': {
  184. label: '163 VIP 邮箱',
  185. url: 'https://vip.163.com/',
  186. },
  187. qq: {
  188. label: 'QQ 邮箱',
  189. url: 'https://wx.mail.qq.com/',
  190. },
  191. '2925': {
  192. label: '2925 邮箱',
  193. url: 'https://2925.com/#/mailList',
  194. },
  195. };
  196. // ============================================================
  197. // Toast Notifications
  198. // ============================================================
  199. const toastContainer = document.getElementById('toast-container');
  200. const TOAST_ICONS = {
  201. 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>',
  202. 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>',
  203. 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>',
  204. 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>',
  205. };
  206. const LOG_LEVEL_LABELS = {
  207. info: '信息',
  208. ok: '成功',
  209. warn: '警告',
  210. error: '错误',
  211. };
  212. function usesGeneratedAliasMailProvider(provider) {
  213. return provider === '2925';
  214. }
  215. function showToast(message, type = 'error', duration = 4000) {
  216. const toast = document.createElement('div');
  217. toast.className = `toast toast-${type}`;
  218. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  219. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  220. toastContainer.appendChild(toast);
  221. if (duration > 0) {
  222. setTimeout(() => dismissToast(toast), duration);
  223. }
  224. }
  225. function dismissToast(toast) {
  226. if (!toast.parentNode) return;
  227. toast.classList.add('toast-exit');
  228. toast.addEventListener('animationend', () => toast.remove());
  229. }
  230. function resetActionModalOption() {
  231. if (!modalOptionRow || !modalOptionInput || !modalOptionText) {
  232. return;
  233. }
  234. modalOptionRow.hidden = true;
  235. modalOptionInput.checked = false;
  236. modalOptionInput.disabled = false;
  237. modalOptionText.textContent = '不再提示';
  238. }
  239. function resetActionModalButtons() {
  240. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  241. buttons.forEach((button) => {
  242. if (!button) return;
  243. button.hidden = true;
  244. button.disabled = false;
  245. button.onclick = null;
  246. });
  247. currentModalActions = [];
  248. }
  249. function configureActionModalButton(button, action) {
  250. if (!button) return;
  251. if (!action) {
  252. button.hidden = true;
  253. button.onclick = null;
  254. return;
  255. }
  256. button.hidden = false;
  257. button.disabled = false;
  258. button.textContent = action.label;
  259. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  260. button.onclick = () => resolveModalChoice(action.id);
  261. }
  262. function configureActionModalOption(option) {
  263. if (!modalOptionRow || !modalOptionInput || !modalOptionText) {
  264. return;
  265. }
  266. if (!option) {
  267. resetActionModalOption();
  268. return;
  269. }
  270. modalOptionRow.hidden = false;
  271. modalOptionInput.checked = Boolean(option.checked);
  272. modalOptionInput.disabled = Boolean(option.disabled);
  273. modalOptionText.textContent = option.label || '不再提示';
  274. }
  275. function resolveModalChoice(choice) {
  276. const optionChecked = Boolean(modalOptionInput?.checked);
  277. const result = typeof modalResultBuilder === 'function'
  278. ? modalResultBuilder(choice, { optionChecked })
  279. : choice;
  280. if (modalChoiceResolver) {
  281. modalChoiceResolver(result);
  282. modalChoiceResolver = null;
  283. }
  284. modalResultBuilder = null;
  285. resetActionModalButtons();
  286. resetActionModalOption();
  287. if (autoStartModal) {
  288. autoStartModal.hidden = true;
  289. }
  290. }
  291. function openActionModal({ title, message, actions, option, buildResult }) {
  292. if (!autoStartModal) {
  293. return Promise.resolve(null);
  294. }
  295. if (modalChoiceResolver) {
  296. resolveModalChoice(null);
  297. }
  298. resetActionModalButtons();
  299. autoStartTitle.textContent = title;
  300. autoStartMessage.textContent = message;
  301. currentModalActions = actions || [];
  302. modalResultBuilder = typeof buildResult === 'function' ? buildResult : null;
  303. const buttonSlots = currentModalActions.length <= 2
  304. ? [btnAutoStartCancel, btnAutoStartContinue]
  305. : [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  306. buttonSlots.forEach((button, index) => {
  307. configureActionModalButton(button, currentModalActions[index]);
  308. });
  309. configureActionModalOption(option);
  310. autoStartModal.hidden = false;
  311. return new Promise((resolve) => {
  312. modalChoiceResolver = resolve;
  313. });
  314. }
  315. function openAutoStartChoiceDialog(startStep, options = {}) {
  316. const runningStep = Number.isInteger(options.runningStep) ? options.runningStep : null;
  317. const continueMessage = runningStep
  318. ? `继续当前会先等待步骤 ${runningStep} 完成,再按最新进度自动执行。`
  319. : `继续当前会从步骤 ${startStep} 开始自动执行。`;
  320. return openActionModal({
  321. title: '启动自动',
  322. message: `检测到当前已有流程进度。${continueMessage}重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  323. actions: [
  324. { id: null, label: '取消', variant: 'btn-ghost' },
  325. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  326. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  327. ],
  328. });
  329. }
  330. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  331. const choice = await openActionModal({
  332. title,
  333. message,
  334. actions: [
  335. { id: null, label: '取消', variant: 'btn-ghost' },
  336. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  337. ],
  338. });
  339. return choice === 'confirm';
  340. }
  341. async function openConfirmModalWithOption({
  342. title,
  343. message,
  344. confirmLabel = '确认',
  345. confirmVariant = 'btn-primary',
  346. optionLabel = '不再提示',
  347. optionChecked = false,
  348. optionDisabled = false,
  349. }) {
  350. const result = await openActionModal({
  351. title,
  352. message,
  353. actions: [
  354. { id: null, label: '取消', variant: 'btn-ghost' },
  355. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  356. ],
  357. option: {
  358. label: optionLabel,
  359. checked: optionChecked,
  360. disabled: optionDisabled,
  361. },
  362. buildResult: (choice, meta) => ({
  363. choice,
  364. optionChecked: Boolean(meta?.optionChecked),
  365. }),
  366. });
  367. return {
  368. confirmed: result?.choice === 'confirm',
  369. optionChecked: Boolean(result?.optionChecked),
  370. };
  371. }
  372. function isPromptDismissed(storageKey) {
  373. return localStorage.getItem(storageKey) === '1';
  374. }
  375. function setPromptDismissed(storageKey, dismissed) {
  376. if (dismissed) {
  377. localStorage.setItem(storageKey, '1');
  378. } else {
  379. localStorage.removeItem(storageKey);
  380. }
  381. }
  382. function isAutoSkipFailuresPromptDismissed() {
  383. return isPromptDismissed(AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY);
  384. }
  385. function setAutoSkipFailuresPromptDismissed(dismissed) {
  386. setPromptDismissed(AUTO_SKIP_FAILURES_PROMPT_DISMISSED_STORAGE_KEY, dismissed);
  387. }
  388. function isAutoRunFallbackRiskPromptDismissed() {
  389. return isPromptDismissed(AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY);
  390. }
  391. function setAutoRunFallbackRiskPromptDismissed(dismissed) {
  392. setPromptDismissed(AUTO_RUN_FALLBACK_RISK_PROMPT_DISMISSED_STORAGE_KEY, dismissed);
  393. }
  394. function shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures) {
  395. return totalRuns >= AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS;
  396. }
  397. async function openAutoSkipFailuresConfirmModal() {
  398. const result = await openConfirmModalWithOption({
  399. title: '自动重试说明',
  400. message: `开启后,自动模式在某一轮失败时,会先在当前轮自动重试;单轮最多重试 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次,仍失败则放弃当前轮并继续下一轮。线程间隔只在开启自动重试且总轮数大于 1 时生效。`,
  401. confirmLabel: '确认开启',
  402. });
  403. return {
  404. confirmed: result.confirmed,
  405. dismissPrompt: result.optionChecked,
  406. };
  407. }
  408. async function openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes) {
  409. const intervalLabel = Number.isFinite(fallbackThreadIntervalMinutes)
  410. ? `${fallbackThreadIntervalMinutes} 分钟`
  411. : '未设置';
  412. const result = await openConfirmModalWithOption({
  413. title: '自动运行风险提醒',
  414. message: `当前设置为 ${totalRuns} 轮自动化,已开启自动重试,线程间隔为 ${intervalLabel}。轮数过多时,可能会因为 IP 短时间注册过多而集中失败。建议控制在 ${AUTO_RUN_FALLBACK_RISK_WARNING_MIN_RUNS} 轮以下,并将线程间隔设置在 ${AUTO_RUN_FALLBACK_RISK_RECOMMENDED_THREAD_INTERVAL_MINUTES} 分钟以上。是否继续?`,
  415. confirmLabel: '继续',
  416. });
  417. return {
  418. confirmed: result.confirmed,
  419. dismissPrompt: result.optionChecked,
  420. };
  421. }
  422. function updateConfigMenuControls() {
  423. const disabled = configActionInFlight || settingsSaveInFlight;
  424. const importLocked = disabled
  425. || currentAutoRun.autoRunning
  426. || Object.values(getStepStatuses()).some((status) => status === 'running');
  427. if (btnConfigMenu) {
  428. btnConfigMenu.disabled = disabled;
  429. btnConfigMenu.setAttribute('aria-expanded', String(configMenuOpen));
  430. }
  431. if (configMenu) {
  432. configMenu.hidden = !configMenuOpen;
  433. }
  434. if (btnExportSettings) {
  435. btnExportSettings.disabled = disabled;
  436. }
  437. if (btnImportSettings) {
  438. btnImportSettings.disabled = importLocked;
  439. }
  440. }
  441. function closeConfigMenu() {
  442. configMenuOpen = false;
  443. updateConfigMenuControls();
  444. }
  445. function openConfigMenu() {
  446. configMenuOpen = true;
  447. updateConfigMenuControls();
  448. }
  449. function toggleConfigMenu() {
  450. configMenuOpen ? closeConfigMenu() : openConfigMenu();
  451. }
  452. async function waitForSettingsSaveIdle() {
  453. while (settingsSaveInFlight) {
  454. await new Promise((resolve) => setTimeout(resolve, 50));
  455. }
  456. }
  457. async function flushPendingSettingsBeforeExport() {
  458. clearTimeout(settingsAutoSaveTimer);
  459. await waitForSettingsSaveIdle();
  460. if (settingsDirty) {
  461. await saveSettings({ silent: true });
  462. }
  463. }
  464. async function settlePendingSettingsBeforeImport() {
  465. clearTimeout(settingsAutoSaveTimer);
  466. await waitForSettingsSaveIdle();
  467. }
  468. function downloadTextFile(content, fileName, mimeType = 'application/json;charset=utf-8') {
  469. const blob = new Blob([content], { type: mimeType });
  470. const objectUrl = URL.createObjectURL(blob);
  471. const anchor = document.createElement('a');
  472. anchor.href = objectUrl;
  473. anchor.download = fileName;
  474. document.body.appendChild(anchor);
  475. anchor.click();
  476. anchor.remove();
  477. setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
  478. }
  479. function isDoneStatus(status) {
  480. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  481. }
  482. function getStepStatuses(state = latestState) {
  483. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  484. }
  485. function getFirstUnfinishedStep(state = latestState) {
  486. const statuses = getStepStatuses(state);
  487. for (let step = 1; step <= 9; step++) {
  488. if (!isDoneStatus(statuses[step])) {
  489. return step;
  490. }
  491. }
  492. return null;
  493. }
  494. function getRunningSteps(state = latestState) {
  495. const statuses = getStepStatuses(state);
  496. return Object.entries(statuses)
  497. .filter(([, status]) => status === 'running')
  498. .map(([step]) => Number(step))
  499. .sort((a, b) => a - b);
  500. }
  501. function hasSavedProgress(state = latestState) {
  502. const statuses = getStepStatuses(state);
  503. return Object.values(statuses).some((status) => status !== 'pending');
  504. }
  505. function shouldOfferAutoModeChoice(state = latestState) {
  506. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  507. }
  508. function syncLatestState(nextState) {
  509. const mergedStepStatuses = nextState?.stepStatuses
  510. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  511. : getStepStatuses(latestState);
  512. latestState = {
  513. ...(latestState || {}),
  514. ...(nextState || {}),
  515. stepStatuses: mergedStepStatuses,
  516. };
  517. }
  518. function syncAutoRunState(source = {}) {
  519. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  520. const autoRunning = source.autoRunning !== undefined
  521. ? Boolean(source.autoRunning)
  522. : (source.autoRunPhase !== undefined || source.phase !== undefined
  523. ? ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(phase)
  524. : currentAutoRun.autoRunning);
  525. currentAutoRun = {
  526. autoRunning,
  527. phase,
  528. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  529. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  530. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  531. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  532. };
  533. }
  534. function isAutoRunLockedPhase() {
  535. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'waiting_step' || currentAutoRun.phase === 'retrying';
  536. }
  537. function isAutoRunPausedPhase() {
  538. return currentAutoRun.phase === 'waiting_email';
  539. }
  540. function isAutoRunWaitingStepPhase() {
  541. return currentAutoRun.phase === 'waiting_step';
  542. }
  543. function isAutoRunScheduledPhase() {
  544. return currentAutoRun.phase === 'scheduled';
  545. }
  546. function getAutoRunLabel(payload = currentAutoRun) {
  547. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  548. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  549. }
  550. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  551. if ((payload.totalRuns || 1) > 1) {
  552. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  553. }
  554. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  555. }
  556. function normalizeAutoDelayMinutes(value) {
  557. const numeric = Number(value);
  558. if (!Number.isFinite(numeric)) {
  559. return AUTO_DELAY_DEFAULT_MINUTES;
  560. }
  561. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  562. }
  563. function normalizeAutoRunThreadIntervalMinutes(value) {
  564. const rawValue = String(value ?? '').trim();
  565. if (!rawValue) {
  566. return AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES;
  567. }
  568. const numeric = Number(rawValue);
  569. if (!Number.isFinite(numeric)) {
  570. return AUTO_FALLBACK_THREAD_INTERVAL_DEFAULT_MINUTES;
  571. }
  572. return Math.min(
  573. AUTO_FALLBACK_THREAD_INTERVAL_MAX_MINUTES,
  574. Math.max(AUTO_FALLBACK_THREAD_INTERVAL_MIN_MINUTES, Math.floor(numeric))
  575. );
  576. }
  577. function normalizeAutoStepDelaySeconds(value) {
  578. const rawValue = String(value ?? '').trim();
  579. if (!rawValue) {
  580. return null;
  581. }
  582. const numeric = Number(rawValue);
  583. if (!Number.isFinite(numeric)) {
  584. return null;
  585. }
  586. return Math.min(AUTO_STEP_DELAY_MAX_SECONDS, Math.max(AUTO_STEP_DELAY_MIN_SECONDS, Math.floor(numeric)));
  587. }
  588. function formatAutoStepDelayInputValue(value) {
  589. const normalized = normalizeAutoStepDelaySeconds(value);
  590. return normalized === null ? '' : String(normalized);
  591. }
  592. function getRunCountValue() {
  593. return Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  594. }
  595. function updateFallbackThreadIntervalInputState() {
  596. if (!inputAutoSkipFailuresThreadIntervalMinutes) {
  597. return;
  598. }
  599. inputAutoSkipFailuresThreadIntervalMinutes.disabled = Boolean(inputAutoSkipFailures.disabled);
  600. }
  601. function updateAutoDelayInputState() {
  602. const scheduled = isAutoRunScheduledPhase();
  603. inputAutoDelayEnabled.disabled = scheduled;
  604. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  605. }
  606. function formatCountdown(remainingMs) {
  607. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  608. const hours = Math.floor(totalSeconds / 3600);
  609. const minutes = Math.floor((totalSeconds % 3600) / 60);
  610. const seconds = totalSeconds % 60;
  611. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  612. }
  613. function formatScheduleTime(timestamp) {
  614. return new Date(timestamp).toLocaleString('zh-CN', {
  615. hour12: false,
  616. month: '2-digit',
  617. day: '2-digit',
  618. hour: '2-digit',
  619. minute: '2-digit',
  620. second: '2-digit',
  621. });
  622. }
  623. function stopScheduledCountdownTicker() {
  624. clearInterval(scheduledCountdownTimer);
  625. scheduledCountdownTimer = null;
  626. }
  627. function renderScheduledAutoRunInfo() {
  628. if (!autoScheduleBar) {
  629. return;
  630. }
  631. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  632. autoScheduleBar.style.display = 'none';
  633. return;
  634. }
  635. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  636. autoScheduleBar.style.display = 'flex';
  637. autoScheduleTitle.textContent = '已计划自动运行';
  638. autoScheduleMeta.textContent = remainingMs > 0
  639. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  640. : '倒计时即将结束,正在准备启动...';
  641. }
  642. function syncScheduledCountdownTicker() {
  643. renderScheduledAutoRunInfo();
  644. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  645. stopScheduledCountdownTicker();
  646. return;
  647. }
  648. if (scheduledCountdownTimer) {
  649. return;
  650. }
  651. scheduledCountdownTimer = setInterval(() => {
  652. renderScheduledAutoRunInfo();
  653. updateStatusDisplay(latestState);
  654. }, 1000);
  655. }
  656. function setDefaultAutoRunButton() {
  657. btnAutoRun.disabled = false;
  658. inputRunCount.disabled = false;
  659. 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> 自动';
  660. }
  661. function normalizeCloudflareDomainValue(value = '') {
  662. let normalized = String(value || '').trim().toLowerCase();
  663. if (!normalized) return '';
  664. normalized = normalized.replace(/^@+/, '');
  665. normalized = normalized.replace(/^https?:\/\//, '');
  666. normalized = normalized.replace(/\/.*$/, '');
  667. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  668. return '';
  669. }
  670. return normalized;
  671. }
  672. function normalizeCloudflareDomains(values = []) {
  673. const seen = new Set();
  674. const domains = [];
  675. for (const value of Array.isArray(values) ? values : []) {
  676. const normalized = normalizeCloudflareDomainValue(value);
  677. if (!normalized || seen.has(normalized)) continue;
  678. seen.add(normalized);
  679. domains.push(normalized);
  680. }
  681. return domains;
  682. }
  683. function getCloudflareDomainsFromState() {
  684. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  685. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  686. if (activeDomain && !domains.includes(activeDomain)) {
  687. domains.unshift(activeDomain);
  688. }
  689. return { domains, activeDomain: activeDomain || domains[0] || '' };
  690. }
  691. function renderCloudflareDomainOptions(preferredDomain = '') {
  692. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  693. const { domains, activeDomain } = getCloudflareDomainsFromState();
  694. const selected = preferred || activeDomain;
  695. selectCfDomain.innerHTML = '';
  696. if (domains.length === 0) {
  697. const option = document.createElement('option');
  698. option.value = '';
  699. option.textContent = '请先添加域名';
  700. selectCfDomain.appendChild(option);
  701. selectCfDomain.disabled = true;
  702. selectCfDomain.value = '';
  703. return;
  704. }
  705. for (const domain of domains) {
  706. const option = document.createElement('option');
  707. option.value = domain;
  708. option.textContent = domain;
  709. selectCfDomain.appendChild(option);
  710. }
  711. selectCfDomain.disabled = false;
  712. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  713. }
  714. function setCloudflareDomainEditMode(editing, options = {}) {
  715. const { clearInput = false } = options;
  716. cloudflareDomainEditMode = Boolean(editing);
  717. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  718. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  719. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  720. if (cloudflareDomainEditMode) {
  721. if (clearInput) {
  722. inputCfDomain.value = '';
  723. }
  724. inputCfDomain.focus();
  725. } else if (clearInput) {
  726. inputCfDomain.value = '';
  727. }
  728. }
  729. function collectSettingsPayload() {
  730. const { domains, activeDomain } = getCloudflareDomainsFromState();
  731. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  732. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  733. ) || activeDomain;
  734. return {
  735. panelMode: selectPanelMode.value,
  736. vpsUrl: inputVpsUrl.value.trim(),
  737. vpsPassword: inputVpsPassword.value,
  738. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  739. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  740. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  741. sub2apiPassword: inputSub2ApiPassword.value,
  742. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  743. customPassword: inputPassword.value,
  744. mailProvider: selectMailProvider.value,
  745. emailGenerator: selectEmailGenerator.value,
  746. emailPrefix: inputEmailPrefix.value.trim(),
  747. inbucketHost: inputInbucketHost.value.trim(),
  748. inbucketMailbox: inputInbucketMailbox.value.trim(),
  749. hotmailServiceMode: getSelectedHotmailServiceMode(),
  750. hotmailRemoteBaseUrl: inputHotmailRemoteBaseUrl.value.trim(),
  751. hotmailLocalBaseUrl: inputHotmailLocalBaseUrl.value.trim(),
  752. cloudflareDomain: selectedCloudflareDomain,
  753. cloudflareDomains: domains,
  754. autoRunSkipFailures: inputAutoSkipFailures.checked,
  755. autoRunFallbackThreadIntervalMinutes: normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value),
  756. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  757. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  758. autoStepDelaySeconds: normalizeAutoStepDelaySeconds(inputAutoStepDelaySeconds.value),
  759. };
  760. }
  761. function normalizeLocalCpaStep9Mode(value = '') {
  762. return String(value || '').trim().toLowerCase() === 'bypass'
  763. ? 'bypass'
  764. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  765. }
  766. function normalizeHotmailServiceMode(value = '') {
  767. return HOTMAIL_SERVICE_MODE_LOCAL;
  768. }
  769. function getSelectedLocalCpaStep9Mode() {
  770. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  771. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  772. }
  773. function setLocalCpaStep9Mode(mode) {
  774. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  775. localCpaStep9ModeButtons.forEach((button) => {
  776. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  777. button.classList.toggle('is-active', active);
  778. button.setAttribute('aria-pressed', String(active));
  779. });
  780. }
  781. function getSelectedHotmailServiceMode() {
  782. const activeButton = hotmailServiceModeButtons.find((button) => button.classList.contains('is-active'));
  783. return normalizeHotmailServiceMode(activeButton?.dataset.hotmailServiceMode);
  784. }
  785. function setHotmailServiceMode(mode) {
  786. const resolvedMode = normalizeHotmailServiceMode(mode);
  787. hotmailServiceModeButtons.forEach((button) => {
  788. const isRemoteMode = button.dataset.hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE;
  789. const active = button.dataset.hotmailServiceMode === resolvedMode;
  790. button.disabled = isRemoteMode;
  791. button.setAttribute('aria-disabled', String(isRemoteMode));
  792. button.classList.toggle('is-active', active);
  793. button.setAttribute('aria-pressed', String(active));
  794. });
  795. }
  796. function setSettingsCardLocked(locked) {
  797. if (!settingsCard) {
  798. return;
  799. }
  800. settingsCard.classList.toggle('is-locked', locked);
  801. settingsCard.toggleAttribute('inert', locked);
  802. }
  803. async function setRuntimeEmailState(email) {
  804. const normalizedEmail = String(email || '').trim() || null;
  805. const response = await chrome.runtime.sendMessage({
  806. type: 'SET_EMAIL_STATE',
  807. source: 'sidepanel',
  808. payload: { email: normalizedEmail },
  809. });
  810. if (response?.error) {
  811. throw new Error(response.error);
  812. }
  813. return normalizedEmail;
  814. }
  815. async function clearRegistrationEmail(options = {}) {
  816. const { silent = false } = options;
  817. if (!inputEmail.value.trim() && !latestState?.email) {
  818. return;
  819. }
  820. inputEmail.value = '';
  821. syncLatestState({ email: null });
  822. try {
  823. await setRuntimeEmailState(null);
  824. } catch (err) {
  825. if (!silent) {
  826. showToast(`清空邮箱失败:${err.message}`, 'error');
  827. }
  828. throw err;
  829. }
  830. }
  831. function markSettingsDirty(isDirty = true) {
  832. settingsDirty = isDirty;
  833. updateSaveButtonState();
  834. }
  835. function updateSaveButtonState() {
  836. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  837. updateConfigMenuControls();
  838. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  839. }
  840. function scheduleSettingsAutoSave() {
  841. clearTimeout(settingsAutoSaveTimer);
  842. settingsAutoSaveTimer = setTimeout(() => {
  843. saveSettings({ silent: true }).catch(() => { });
  844. }, 500);
  845. }
  846. async function saveSettings(options = {}) {
  847. const { silent = false } = options;
  848. clearTimeout(settingsAutoSaveTimer);
  849. if (!settingsDirty && !settingsSaveInFlight && silent) {
  850. return;
  851. }
  852. const payload = collectSettingsPayload();
  853. settingsSaveInFlight = true;
  854. updateSaveButtonState();
  855. try {
  856. const response = await chrome.runtime.sendMessage({
  857. type: 'SAVE_SETTING',
  858. source: 'sidepanel',
  859. payload,
  860. });
  861. if (response?.error) {
  862. throw new Error(response.error);
  863. }
  864. if (response?.state) {
  865. applySettingsState(response.state);
  866. } else {
  867. syncLatestState(payload);
  868. markSettingsDirty(false);
  869. updatePanelModeUI();
  870. updateMailProviderUI();
  871. updateButtonStates();
  872. }
  873. if (!silent) {
  874. showToast('配置已保存', 'success', 1800);
  875. }
  876. } catch (err) {
  877. markSettingsDirty(true);
  878. if (!silent) {
  879. showToast(`保存失败:${err.message}`, 'error');
  880. }
  881. throw err;
  882. } finally {
  883. settingsSaveInFlight = false;
  884. updateSaveButtonState();
  885. }
  886. }
  887. function applyAutoRunStatus(payload = currentAutoRun) {
  888. syncAutoRunState(payload);
  889. const runLabel = getAutoRunLabel(currentAutoRun);
  890. const locked = isAutoRunLockedPhase();
  891. const paused = isAutoRunPausedPhase();
  892. const scheduled = isAutoRunScheduledPhase();
  893. const settingsCardLocked = scheduled || locked;
  894. setSettingsCardLocked(settingsCardLocked);
  895. inputRunCount.disabled = currentAutoRun.autoRunning;
  896. btnAutoRun.disabled = currentAutoRun.autoRunning;
  897. btnFetchEmail.disabled = locked
  898. || usesGeneratedAliasMailProvider(selectMailProvider.value)
  899. || isCustomEmailGeneratorSelected();
  900. inputEmail.disabled = locked;
  901. inputAutoSkipFailures.disabled = scheduled;
  902. if (currentAutoRun.totalRuns > 0) {
  903. inputRunCount.value = String(currentAutoRun.totalRuns);
  904. }
  905. switch (currentAutoRun.phase) {
  906. case 'scheduled':
  907. autoContinueBar.style.display = 'none';
  908. btnAutoRun.innerHTML = `已计划${runLabel}`;
  909. break;
  910. case 'waiting_step':
  911. autoContinueBar.style.display = 'none';
  912. btnAutoRun.innerHTML = `等待中${runLabel}`;
  913. break;
  914. case 'waiting_email':
  915. autoContinueBar.style.display = 'flex';
  916. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  917. break;
  918. case 'running':
  919. autoContinueBar.style.display = 'none';
  920. btnAutoRun.innerHTML = `运行中${runLabel}`;
  921. break;
  922. case 'retrying':
  923. autoContinueBar.style.display = 'none';
  924. btnAutoRun.innerHTML = `重试中${runLabel}`;
  925. break;
  926. default:
  927. autoContinueBar.style.display = 'none';
  928. setDefaultAutoRunButton();
  929. inputEmail.disabled = false;
  930. if (!locked) {
  931. btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value)
  932. || isCustomEmailGeneratorSelected();
  933. }
  934. break;
  935. }
  936. updateAutoDelayInputState();
  937. updateFallbackThreadIntervalInputState();
  938. syncScheduledCountdownTicker();
  939. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  940. updateConfigMenuControls();
  941. }
  942. function initializeManualStepActions() {
  943. document.querySelectorAll('.step-row').forEach((row) => {
  944. const step = Number(row.dataset.step);
  945. const statusEl = row.querySelector('.step-status');
  946. if (!statusEl) return;
  947. const actions = document.createElement('div');
  948. actions.className = 'step-actions';
  949. const manualBtn = document.createElement('button');
  950. manualBtn.type = 'button';
  951. manualBtn.className = 'step-manual-btn';
  952. manualBtn.dataset.step = String(step);
  953. manualBtn.title = '跳过此步';
  954. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  955. 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>';
  956. manualBtn.addEventListener('click', async (event) => {
  957. event.stopPropagation();
  958. try {
  959. await handleSkipStep(step);
  960. } catch (err) {
  961. showToast(err.message, 'error');
  962. }
  963. });
  964. statusEl.parentNode.replaceChild(actions, statusEl);
  965. actions.appendChild(manualBtn);
  966. actions.appendChild(statusEl);
  967. });
  968. }
  969. // ============================================================
  970. // State Restore on load
  971. // ============================================================
  972. function applySettingsState(state) {
  973. syncLatestState(state);
  974. syncAutoRunState(state);
  975. inputEmail.value = state?.email || '';
  976. syncPasswordField(state || {});
  977. inputVpsUrl.value = state?.vpsUrl || '';
  978. inputVpsPassword.value = state?.vpsPassword || '';
  979. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  980. selectPanelMode.value = state?.panelMode || 'cpa';
  981. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  982. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  983. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  984. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  985. selectMailProvider.value = state?.mailProvider || '163';
  986. selectEmailGenerator.value = state?.emailGenerator || 'duck';
  987. inputEmailPrefix.value = state?.emailPrefix || '';
  988. inputInbucketHost.value = state?.inbucketHost || '';
  989. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  990. setHotmailServiceMode(state?.hotmailServiceMode);
  991. inputHotmailRemoteBaseUrl.value = state?.hotmailRemoteBaseUrl || '';
  992. inputHotmailLocalBaseUrl.value = state?.hotmailLocalBaseUrl || '';
  993. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  994. setCloudflareDomainEditMode(false, { clearInput: true });
  995. inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures);
  996. inputAutoSkipFailuresThreadIntervalMinutes.value = String(normalizeAutoRunThreadIntervalMinutes(state?.autoRunFallbackThreadIntervalMinutes));
  997. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  998. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  999. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(state?.autoStepDelaySeconds);
  1000. if (state?.autoRunTotalRuns) {
  1001. inputRunCount.value = String(state.autoRunTotalRuns);
  1002. }
  1003. applyAutoRunStatus(state);
  1004. markSettingsDirty(false);
  1005. updateAutoDelayInputState();
  1006. updateFallbackThreadIntervalInputState();
  1007. updatePanelModeUI();
  1008. updateMailProviderUI();
  1009. updateButtonStates();
  1010. }
  1011. async function restoreState() {
  1012. try {
  1013. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  1014. applySettingsState(state);
  1015. if (state.oauthUrl) {
  1016. displayOauthUrl.textContent = state.oauthUrl;
  1017. displayOauthUrl.classList.add('has-value');
  1018. }
  1019. if (state.localhostUrl) {
  1020. displayLocalhostUrl.textContent = state.localhostUrl;
  1021. displayLocalhostUrl.classList.add('has-value');
  1022. }
  1023. if (state.stepStatuses) {
  1024. for (const [step, status] of Object.entries(state.stepStatuses)) {
  1025. updateStepUI(Number(step), status);
  1026. }
  1027. }
  1028. if (state.logs) {
  1029. for (const entry of state.logs) {
  1030. appendLog(entry);
  1031. }
  1032. }
  1033. updateStatusDisplay(latestState);
  1034. updateProgressCounter();
  1035. } catch (err) {
  1036. console.error('Failed to restore state:', err);
  1037. }
  1038. }
  1039. function openExternalUrl(url) {
  1040. const targetUrl = String(url || '').trim();
  1041. if (!targetUrl) {
  1042. return;
  1043. }
  1044. if (chrome?.tabs?.create) {
  1045. chrome.tabs.create({ url: targetUrl, active: true }).catch(() => {
  1046. window.open(targetUrl, '_blank', 'noopener');
  1047. });
  1048. return;
  1049. }
  1050. window.open(targetUrl, '_blank', 'noopener');
  1051. }
  1052. function createUpdateNoteList(notes = []) {
  1053. if (!Array.isArray(notes) || notes.length === 0) {
  1054. const empty = document.createElement('p');
  1055. empty.className = 'update-release-empty';
  1056. empty.textContent = '该版本未提供可解析的更新说明,请查看完整更新日志。';
  1057. return empty;
  1058. }
  1059. const list = document.createElement('ul');
  1060. list.className = 'update-release-notes';
  1061. notes.forEach((note) => {
  1062. const item = document.createElement('li');
  1063. item.textContent = note;
  1064. list.appendChild(item);
  1065. });
  1066. return list;
  1067. }
  1068. function renderUpdateReleaseList(releases = []) {
  1069. if (!updateReleaseList) {
  1070. return;
  1071. }
  1072. updateReleaseList.innerHTML = '';
  1073. releases.forEach((release) => {
  1074. const item = document.createElement('article');
  1075. item.className = 'update-release-item';
  1076. const head = document.createElement('div');
  1077. head.className = 'update-release-head';
  1078. const titleRow = document.createElement('div');
  1079. titleRow.className = 'update-release-title-row';
  1080. const version = document.createElement('span');
  1081. version.className = 'update-release-version';
  1082. version.textContent = `v${release.version}`;
  1083. titleRow.appendChild(version);
  1084. if (release.title) {
  1085. const name = document.createElement('span');
  1086. name.className = 'update-release-name';
  1087. name.textContent = release.title;
  1088. titleRow.appendChild(name);
  1089. }
  1090. head.appendChild(titleRow);
  1091. const publishedAt = sidepanelUpdateService?.formatReleaseDate?.(release.publishedAt) || '';
  1092. if (publishedAt) {
  1093. const date = document.createElement('span');
  1094. date.className = 'update-release-date';
  1095. date.textContent = publishedAt;
  1096. head.appendChild(date);
  1097. }
  1098. item.appendChild(head);
  1099. item.appendChild(createUpdateNoteList(release.notes));
  1100. updateReleaseList.appendChild(item);
  1101. });
  1102. }
  1103. function resetUpdateCard() {
  1104. if (updateSection) {
  1105. updateSection.hidden = true;
  1106. }
  1107. if (updateCardVersion) {
  1108. updateCardVersion.textContent = '';
  1109. }
  1110. if (updateCardSummary) {
  1111. updateCardSummary.textContent = '';
  1112. }
  1113. if (updateReleaseList) {
  1114. updateReleaseList.innerHTML = '';
  1115. }
  1116. if (btnOpenRelease) {
  1117. btnOpenRelease.hidden = true;
  1118. btnOpenRelease.onclick = null;
  1119. }
  1120. }
  1121. function renderReleaseSnapshot(snapshot) {
  1122. currentReleaseSnapshot = snapshot;
  1123. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1124. return;
  1125. }
  1126. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed', 'is-version-label');
  1127. const localVersionText = snapshot?.localVersion ? `v${snapshot.localVersion}` : '';
  1128. const logUrl = snapshot?.logUrl || snapshot?.releasesPageUrl || sidepanelUpdateService?.releasesPageUrl || '';
  1129. if (btnReleaseLog) {
  1130. btnReleaseLog.onclick = () => openExternalUrl(logUrl);
  1131. btnReleaseLog.hidden = true;
  1132. }
  1133. extensionVersionMeta.hidden = true;
  1134. extensionVersionMeta.textContent = '';
  1135. switch (snapshot?.status) {
  1136. case 'update-available': {
  1137. extensionUpdateStatus.textContent = '有更新';
  1138. extensionUpdateStatus.classList.add('is-update-available');
  1139. if (btnReleaseLog) {
  1140. btnReleaseLog.hidden = false;
  1141. }
  1142. if (updateSection) {
  1143. updateSection.hidden = false;
  1144. }
  1145. if (updateCardVersion) {
  1146. updateCardVersion.textContent = `最新版本 v${snapshot.latestVersion}`;
  1147. }
  1148. if (updateCardSummary) {
  1149. const updateCount = Array.isArray(snapshot.newerReleases) ? snapshot.newerReleases.length : 0;
  1150. updateCardSummary.textContent = updateCount > 1
  1151. ? `当前 ${localVersionText},共有 ${updateCount} 个新版本可更新。`
  1152. : `当前 ${localVersionText},可更新到 v${snapshot.latestVersion}。`;
  1153. }
  1154. renderUpdateReleaseList(snapshot.newerReleases || []);
  1155. if (btnOpenRelease) {
  1156. btnOpenRelease.hidden = false;
  1157. btnOpenRelease.textContent = '前往更新';
  1158. btnOpenRelease.onclick = () => openExternalUrl(logUrl);
  1159. }
  1160. break;
  1161. }
  1162. case 'latest': {
  1163. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1164. extensionUpdateStatus.classList.add('is-version-label');
  1165. resetUpdateCard();
  1166. break;
  1167. }
  1168. case 'empty': {
  1169. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1170. extensionUpdateStatus.classList.add('is-version-label');
  1171. resetUpdateCard();
  1172. break;
  1173. }
  1174. case 'error':
  1175. default: {
  1176. extensionUpdateStatus.textContent = localVersionText || 'v0.0.0';
  1177. extensionUpdateStatus.classList.add('is-version-label', 'is-check-failed');
  1178. extensionVersionMeta.textContent = snapshot?.errorMessage || 'GitHub Releases 检查失败';
  1179. extensionVersionMeta.hidden = false;
  1180. resetUpdateCard();
  1181. break;
  1182. }
  1183. }
  1184. }
  1185. async function initializeReleaseInfo() {
  1186. const fallbackReleaseUrl = sidepanelUpdateService?.releasesPageUrl || 'https://github.com/QLHazyCoder/codex-oauth-automation-extension/releases';
  1187. if (btnReleaseLog) {
  1188. btnReleaseLog.onclick = () => openExternalUrl(currentReleaseSnapshot?.logUrl || fallbackReleaseUrl);
  1189. }
  1190. if (!extensionUpdateStatus || !extensionVersionMeta) {
  1191. return;
  1192. }
  1193. const localVersion = sidepanelUpdateService?.stripVersionPrefix?.(chrome.runtime.getManifest()?.version || '') || '';
  1194. extensionUpdateStatus.textContent = localVersion ? `v${localVersion}` : 'v0.0.0';
  1195. extensionUpdateStatus.classList.remove('is-update-available', 'is-check-failed');
  1196. extensionUpdateStatus.classList.add('is-version-label');
  1197. extensionVersionMeta.hidden = true;
  1198. extensionVersionMeta.textContent = '';
  1199. if (btnReleaseLog) {
  1200. btnReleaseLog.hidden = true;
  1201. }
  1202. resetUpdateCard();
  1203. if (!sidepanelUpdateService) {
  1204. extensionVersionMeta.textContent = '更新检查服务不可用';
  1205. extensionVersionMeta.hidden = false;
  1206. return;
  1207. }
  1208. const snapshot = await sidepanelUpdateService.getReleaseSnapshot();
  1209. renderReleaseSnapshot(snapshot);
  1210. }
  1211. function syncPasswordField(state) {
  1212. inputPassword.value = state.customPassword || state.password || '';
  1213. }
  1214. function getSelectedEmailGenerator() {
  1215. const generator = String(selectEmailGenerator.value || '').trim().toLowerCase();
  1216. if (generator === 'custom' || generator === 'manual') {
  1217. return 'custom';
  1218. }
  1219. if (generator === 'cloudflare') {
  1220. return 'cloudflare';
  1221. }
  1222. return 'duck';
  1223. }
  1224. function getEmailGeneratorUiCopy() {
  1225. if (getSelectedEmailGenerator() === 'custom') {
  1226. return {
  1227. buttonLabel: '自定义邮箱',
  1228. placeholder: '请填写本轮要使用的注册邮箱',
  1229. successVerb: '使用',
  1230. label: '自定义邮箱',
  1231. };
  1232. }
  1233. if (getSelectedEmailGenerator() === 'cloudflare') {
  1234. return {
  1235. buttonLabel: '生成',
  1236. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  1237. successVerb: '生成',
  1238. label: 'Cloudflare 邮箱',
  1239. };
  1240. }
  1241. return {
  1242. buttonLabel: '获取',
  1243. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  1244. successVerb: '获取',
  1245. label: 'Duck 邮箱',
  1246. };
  1247. }
  1248. function isCustomEmailGeneratorSelected() {
  1249. return getSelectedEmailGenerator() === 'custom';
  1250. }
  1251. function getHotmailAccounts(state = latestState) {
  1252. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  1253. }
  1254. function getCurrentHotmailAccount(state = latestState) {
  1255. const currentId = state?.currentHotmailAccountId;
  1256. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  1257. }
  1258. function getCurrentHotmailEmail(state = latestState) {
  1259. return String(getCurrentHotmailAccount(state)?.email || '').trim();
  1260. }
  1261. function getMailProviderLoginConfig(provider = selectMailProvider.value) {
  1262. return MAIL_PROVIDER_LOGIN_CONFIGS[String(provider || '').trim()] || null;
  1263. }
  1264. function isCurrentEmailManagedByHotmail(state = latestState) {
  1265. const hotmailEmail = getCurrentHotmailEmail(state);
  1266. if (!hotmailEmail) {
  1267. return false;
  1268. }
  1269. const inputEmailValue = String(inputEmail.value || '').trim();
  1270. const stateEmailValue = String(state?.email || '').trim();
  1271. return inputEmailValue === hotmailEmail || stateEmailValue === hotmailEmail;
  1272. }
  1273. function isCurrentEmailManagedByGeneratedAlias(provider = latestState?.mailProvider, state = latestState) {
  1274. const normalizedProvider = String(provider || '').trim();
  1275. if (!usesGeneratedAliasMailProvider(normalizedProvider)) {
  1276. return false;
  1277. }
  1278. const inputEmailValue = String(inputEmail.value || '').trim().toLowerCase();
  1279. const stateEmailValue = String(state?.email || '').trim().toLowerCase();
  1280. if (normalizedProvider === '2925') {
  1281. return inputEmailValue.endsWith('@2925.com') || stateEmailValue.endsWith('@2925.com');
  1282. }
  1283. return false;
  1284. }
  1285. function updateMailLoginButtonState() {
  1286. if (!btnMailLogin) {
  1287. return;
  1288. }
  1289. const config = getMailProviderLoginConfig();
  1290. btnMailLogin.disabled = !config;
  1291. btnMailLogin.title = config ? `打开 ${config.label} 登录页` : '当前邮箱服务无需网页登录';
  1292. }
  1293. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  1294. const accounts = getHotmailAccounts(state);
  1295. if (typeof filterHotmailAccountsByUsage === 'function') {
  1296. return filterHotmailAccountsByUsage(accounts, mode);
  1297. }
  1298. if (mode === 'used') {
  1299. return accounts.filter((account) => Boolean(account?.used));
  1300. }
  1301. return accounts.slice();
  1302. }
  1303. function getHotmailBulkActionText(mode, count) {
  1304. if (typeof getHotmailBulkActionLabel === 'function') {
  1305. return getHotmailBulkActionLabel(mode, count);
  1306. }
  1307. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  1308. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  1309. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  1310. return `${prefix}${suffix}`;
  1311. }
  1312. function getHotmailListToggleText(expanded, count) {
  1313. if (typeof getHotmailListToggleLabel === 'function') {
  1314. return getHotmailListToggleLabel(expanded, count);
  1315. }
  1316. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  1317. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  1318. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  1319. }
  1320. function updateHotmailListViewport() {
  1321. const count = getHotmailAccounts().length;
  1322. const usedCount = getHotmailAccountsByUsage('used').length;
  1323. if (btnClearUsedHotmailAccounts) {
  1324. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  1325. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  1326. }
  1327. if (btnDeleteAllHotmailAccounts) {
  1328. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  1329. btnDeleteAllHotmailAccounts.disabled = count === 0;
  1330. }
  1331. if (btnToggleHotmailList) {
  1332. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  1333. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  1334. btnToggleHotmailList.disabled = count === 0;
  1335. }
  1336. if (hotmailListShell) {
  1337. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  1338. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  1339. }
  1340. }
  1341. function setHotmailListExpanded(expanded, options = {}) {
  1342. const { persist = true } = options;
  1343. hotmailListExpanded = Boolean(expanded);
  1344. updateHotmailListViewport();
  1345. if (persist) {
  1346. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  1347. }
  1348. }
  1349. function initHotmailListExpandedState() {
  1350. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  1351. setHotmailListExpanded(saved === '1', { persist: false });
  1352. }
  1353. function shouldClearCurrentHotmailSelectionLocally(account) {
  1354. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  1355. return shouldClearHotmailCurrentSelection(account);
  1356. }
  1357. return Boolean(account) && account.used === true;
  1358. }
  1359. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  1360. if (typeof upsertHotmailAccountInList === 'function') {
  1361. return upsertHotmailAccountInList(accounts, nextAccount);
  1362. }
  1363. const list = Array.isArray(accounts) ? accounts.slice() : [];
  1364. if (!nextAccount?.id) return list;
  1365. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  1366. if (existingIndex === -1) {
  1367. list.push(nextAccount);
  1368. return list;
  1369. }
  1370. list[existingIndex] = nextAccount;
  1371. return list;
  1372. }
  1373. function refreshHotmailSelectionUI() {
  1374. renderHotmailAccounts();
  1375. if (selectMailProvider.value === 'hotmail-api') {
  1376. inputEmail.value = getCurrentHotmailEmail();
  1377. }
  1378. }
  1379. function applyHotmailAccountMutation(account, options = {}) {
  1380. if (!account?.id) return;
  1381. const { preserveCurrentSelection = false } = options;
  1382. const nextState = {
  1383. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  1384. };
  1385. if (!preserveCurrentSelection
  1386. && latestState?.currentHotmailAccountId === account.id
  1387. && shouldClearCurrentHotmailSelectionLocally(account)) {
  1388. nextState.currentHotmailAccountId = null;
  1389. if (selectMailProvider.value === 'hotmail-api') {
  1390. nextState.email = null;
  1391. }
  1392. }
  1393. syncLatestState(nextState);
  1394. refreshHotmailSelectionUI();
  1395. }
  1396. function formatDateTime(timestamp) {
  1397. const value = Number(timestamp);
  1398. if (!Number.isFinite(value) || value <= 0) {
  1399. return '未使用';
  1400. }
  1401. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  1402. }
  1403. function getHotmailAvailabilityLabel(account) {
  1404. if (account.used) return '已用';
  1405. return '可分配';
  1406. }
  1407. function getHotmailStatusLabel(account) {
  1408. if (account.used) return '已用';
  1409. switch (account.status) {
  1410. case 'authorized':
  1411. return '可用';
  1412. case 'error':
  1413. return '异常';
  1414. default:
  1415. return '待校验';
  1416. }
  1417. }
  1418. function getHotmailStatusClass(account) {
  1419. if (account.used) return 'status-used';
  1420. return `status-${account.status || 'pending'}`;
  1421. }
  1422. function clearHotmailForm() {
  1423. inputHotmailEmail.value = '';
  1424. inputHotmailClientId.value = '';
  1425. inputHotmailPassword.value = '';
  1426. inputHotmailRefreshToken.value = '';
  1427. }
  1428. function renderHotmailAccounts() {
  1429. if (!hotmailAccountsList) return;
  1430. const accounts = getHotmailAccounts();
  1431. const currentId = latestState?.currentHotmailAccountId || '';
  1432. if (!accounts.length) {
  1433. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  1434. updateHotmailListViewport();
  1435. return;
  1436. }
  1437. hotmailAccountsList.innerHTML = accounts.map((account) => `
  1438. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  1439. <div class="hotmail-account-top">
  1440. <div class="hotmail-account-title-row">
  1441. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  1442. <button
  1443. class="hotmail-copy-btn"
  1444. type="button"
  1445. data-account-action="copy-email"
  1446. data-account-id="${escapeHtml(account.id)}"
  1447. title="复制邮箱"
  1448. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  1449. >${COPY_ICON}</button>
  1450. </div>
  1451. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  1452. </div>
  1453. <div class="hotmail-account-meta">
  1454. <span>客户端 ID:${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  1455. <span>刷新令牌:${account.refreshToken ? '已保存' : '未保存'}</span>
  1456. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  1457. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  1458. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  1459. </div>
  1460. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  1461. <div class="hotmail-account-actions">
  1462. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  1463. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  1464. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  1465. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  1466. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  1467. </div>
  1468. </div>
  1469. `).join('');
  1470. updateHotmailListViewport();
  1471. }
  1472. function updateMailProviderUI() {
  1473. const use2925 = selectMailProvider.value === '2925';
  1474. const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value);
  1475. const useInbucket = selectMailProvider.value === 'inbucket';
  1476. const useHotmail = selectMailProvider.value === 'hotmail-api';
  1477. const useCustomEmail = !useGeneratedAlias && !useHotmail && isCustomEmailGeneratorSelected();
  1478. const useEmailGenerator = !useHotmail && !useGeneratedAlias;
  1479. updateMailLoginButtonState();
  1480. rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
  1481. const hotmailServiceMode = getSelectedHotmailServiceMode();
  1482. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  1483. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  1484. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  1485. const showCloudflareDomain = useEmailGenerator && useCloudflare;
  1486. if (rowEmailGenerator) {
  1487. rowEmailGenerator.style.display = useEmailGenerator ? '' : 'none';
  1488. }
  1489. rowCfDomain.style.display = showCloudflareDomain ? '' : 'none';
  1490. const { domains } = getCloudflareDomainsFromState();
  1491. if (showCloudflareDomain) {
  1492. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  1493. } else {
  1494. setCloudflareDomainEditMode(false, { clearInput: false });
  1495. }
  1496. if (hotmailSection) {
  1497. hotmailSection.style.display = useHotmail ? '' : 'none';
  1498. }
  1499. labelEmailPrefix.textContent = '邮箱前缀';
  1500. inputEmailPrefix.placeholder = '例如 abc';
  1501. selectEmailGenerator.disabled = useHotmail || useGeneratedAlias;
  1502. if (rowHotmailServiceMode) {
  1503. rowHotmailServiceMode.style.display = useHotmail ? '' : 'none';
  1504. }
  1505. if (rowHotmailRemoteBaseUrl) {
  1506. rowHotmailRemoteBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_REMOTE ? '' : 'none';
  1507. }
  1508. if (rowHotmailLocalBaseUrl) {
  1509. rowHotmailLocalBaseUrl.style.display = useHotmail && hotmailServiceMode === HOTMAIL_SERVICE_MODE_LOCAL ? '' : 'none';
  1510. }
  1511. btnFetchEmail.hidden = useHotmail || useCustomEmail;
  1512. inputEmail.readOnly = useHotmail || useGeneratedAlias;
  1513. const uiCopy = getEmailGeneratorUiCopy();
  1514. inputEmail.placeholder = useHotmail
  1515. ? '由 Hotmail 账号池自动分配'
  1516. : (use2925 ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder);
  1517. btnFetchEmail.disabled = useGeneratedAlias || useCustomEmail || isAutoRunLockedPhase();
  1518. if (!btnFetchEmail.disabled) {
  1519. btnFetchEmail.textContent = uiCopy.buttonLabel;
  1520. }
  1521. if (autoHintText) {
  1522. autoHintText.textContent = useHotmail
  1523. ? '请先校验并选择一个 Hotmail 账号'
  1524. : (useGeneratedAlias
  1525. ? '步骤 3 会自动生成邮箱,无需手动获取'
  1526. : (useCustomEmail ? '请先填写自定义注册邮箱,成功一轮后会自动清空' : '先自动获取邮箱,或手动粘贴邮箱后再继续'));
  1527. }
  1528. if (useHotmail) {
  1529. inputEmail.value = getCurrentHotmailEmail();
  1530. }
  1531. renderHotmailAccounts();
  1532. }
  1533. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  1534. const { silent = false } = options;
  1535. const normalizedDomains = normalizeCloudflareDomains(domains);
  1536. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  1537. const payload = {
  1538. cloudflareDomain: normalizedActiveDomain,
  1539. cloudflareDomains: normalizedDomains,
  1540. };
  1541. const response = await chrome.runtime.sendMessage({
  1542. type: 'SAVE_SETTING',
  1543. source: 'sidepanel',
  1544. payload,
  1545. });
  1546. if (response?.error) {
  1547. throw new Error(response.error);
  1548. }
  1549. syncLatestState({
  1550. ...payload,
  1551. });
  1552. renderCloudflareDomainOptions(normalizedActiveDomain);
  1553. setCloudflareDomainEditMode(false, { clearInput: true });
  1554. markSettingsDirty(false);
  1555. updateMailProviderUI();
  1556. if (!silent) {
  1557. showToast('Cloudflare 域名已保存', 'success', 1800);
  1558. }
  1559. }
  1560. function updatePanelModeUI() {
  1561. const useSub2Api = selectPanelMode.value === 'sub2api';
  1562. rowVpsUrl.style.display = useSub2Api ? 'none' : '';
  1563. rowVpsPassword.style.display = useSub2Api ? 'none' : '';
  1564. rowLocalCpaStep9Mode.style.display = useSub2Api ? 'none' : '';
  1565. rowSub2ApiUrl.style.display = useSub2Api ? '' : 'none';
  1566. rowSub2ApiEmail.style.display = useSub2Api ? '' : 'none';
  1567. rowSub2ApiPassword.style.display = useSub2Api ? '' : 'none';
  1568. rowSub2ApiGroup.style.display = useSub2Api ? '' : 'none';
  1569. const step9Btn = document.querySelector('.step-btn[data-step="9"]');
  1570. if (step9Btn) {
  1571. step9Btn.textContent = useSub2Api ? 'SUB2API 回调验证' : 'CPA 回调验证';
  1572. }
  1573. }
  1574. // ============================================================
  1575. // UI Updates
  1576. // ============================================================
  1577. function updateStepUI(step, status) {
  1578. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  1579. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  1580. syncLatestState({
  1581. stepStatuses: {
  1582. ...getStepStatuses(),
  1583. [step]: status,
  1584. },
  1585. });
  1586. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  1587. if (row) {
  1588. row.className = `step-row ${status}`;
  1589. }
  1590. updateButtonStates();
  1591. updateProgressCounter();
  1592. updateConfigMenuControls();
  1593. }
  1594. function updateProgressCounter() {
  1595. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  1596. stepsProgress.textContent = `${completed} / 9`;
  1597. }
  1598. function updateButtonStates() {
  1599. const statuses = getStepStatuses();
  1600. const anyRunning = Object.values(statuses).some(s => s === 'running');
  1601. const autoLocked = isAutoRunLockedPhase();
  1602. const autoScheduled = isAutoRunScheduledPhase();
  1603. for (let step = 1; step <= 9; step++) {
  1604. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  1605. if (!btn) continue;
  1606. if (anyRunning || autoLocked || autoScheduled) {
  1607. btn.disabled = true;
  1608. } else if (step === 1) {
  1609. btn.disabled = false;
  1610. } else {
  1611. const prevStatus = statuses[step - 1];
  1612. const currentStatus = statuses[step];
  1613. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  1614. }
  1615. }
  1616. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  1617. const step = Number(btn.dataset.step);
  1618. const currentStatus = statuses[step];
  1619. const prevStatus = statuses[step - 1];
  1620. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  1621. btn.style.display = 'none';
  1622. btn.disabled = true;
  1623. btn.title = '当前不可跳过';
  1624. return;
  1625. }
  1626. if (step > 1 && !isDoneStatus(prevStatus)) {
  1627. btn.style.display = 'none';
  1628. btn.disabled = true;
  1629. btn.title = `请先完成步骤 ${step - 1}`;
  1630. return;
  1631. }
  1632. btn.style.display = '';
  1633. btn.disabled = false;
  1634. btn.title = `跳过步骤 ${step}`;
  1635. });
  1636. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  1637. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  1638. }
  1639. function updateStopButtonState(active) {
  1640. btnStop.disabled = !active;
  1641. }
  1642. function updateStatusDisplay(state) {
  1643. if (!state || !state.stepStatuses) return;
  1644. statusBar.className = 'status-bar';
  1645. if (isAutoRunScheduledPhase()) {
  1646. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  1647. ? currentAutoRun.scheduledAt - Date.now()
  1648. : 0;
  1649. displayStatus.textContent = remainingMs > 0
  1650. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  1651. : '倒计时即将结束,正在准备启动...';
  1652. statusBar.classList.add('scheduled');
  1653. return;
  1654. }
  1655. if (isAutoRunPausedPhase()) {
  1656. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  1657. statusBar.classList.add('paused');
  1658. return;
  1659. }
  1660. if (isAutoRunWaitingStepPhase()) {
  1661. const runningSteps = getRunningSteps(state);
  1662. displayStatus.textContent = runningSteps.length
  1663. ? `自动等待步骤 ${runningSteps.join(', ')} 完成后继续${getAutoRunLabel()}`
  1664. : `自动正在按最新进度准备继续${getAutoRunLabel()}`;
  1665. statusBar.classList.add('running');
  1666. return;
  1667. }
  1668. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  1669. if (running) {
  1670. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  1671. statusBar.classList.add('running');
  1672. return;
  1673. }
  1674. if (isAutoRunLockedPhase()) {
  1675. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  1676. statusBar.classList.add('running');
  1677. return;
  1678. }
  1679. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  1680. if (failed) {
  1681. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  1682. statusBar.classList.add('failed');
  1683. return;
  1684. }
  1685. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  1686. if (stopped) {
  1687. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  1688. statusBar.classList.add('stopped');
  1689. return;
  1690. }
  1691. const lastCompleted = Object.entries(state.stepStatuses)
  1692. .filter(([, s]) => isDoneStatus(s))
  1693. .map(([k]) => Number(k))
  1694. .sort((a, b) => b - a)[0];
  1695. if (lastCompleted === 9) {
  1696. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  1697. statusBar.classList.add('completed');
  1698. } else if (lastCompleted) {
  1699. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  1700. ? `步骤 ${lastCompleted} 已跳过`
  1701. : `步骤 ${lastCompleted} 已完成`;
  1702. } else {
  1703. displayStatus.textContent = '就绪';
  1704. }
  1705. }
  1706. function appendLog(entry) {
  1707. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  1708. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  1709. const line = document.createElement('div');
  1710. line.className = `log-line log-${entry.level}`;
  1711. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  1712. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  1713. let html = `<span class="log-time">${time}</span> `;
  1714. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  1715. if (stepNum) {
  1716. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  1717. }
  1718. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  1719. line.innerHTML = html;
  1720. logArea.appendChild(line);
  1721. logArea.scrollTop = logArea.scrollHeight;
  1722. }
  1723. function escapeHtml(text) {
  1724. const div = document.createElement('div');
  1725. div.textContent = text;
  1726. return div.innerHTML;
  1727. }
  1728. async function fetchGeneratedEmail(options = {}) {
  1729. const { showFailureToast = true } = options;
  1730. const uiCopy = getEmailGeneratorUiCopy();
  1731. if (isCustomEmailGeneratorSelected()) {
  1732. throw new Error('当前邮箱生成方式为自定义邮箱,请直接填写注册邮箱。');
  1733. }
  1734. const defaultLabel = uiCopy.buttonLabel;
  1735. btnFetchEmail.disabled = true;
  1736. btnFetchEmail.textContent = '...';
  1737. try {
  1738. const response = await chrome.runtime.sendMessage({
  1739. type: 'FETCH_GENERATED_EMAIL',
  1740. source: 'sidepanel',
  1741. payload: {
  1742. generateNew: true,
  1743. generator: selectEmailGenerator.value,
  1744. },
  1745. });
  1746. if (response?.error) {
  1747. throw new Error(response.error);
  1748. }
  1749. if (!response?.email) {
  1750. throw new Error('未返回可用邮箱。');
  1751. }
  1752. inputEmail.value = response.email;
  1753. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  1754. return response.email;
  1755. } catch (err) {
  1756. if (showFailureToast) {
  1757. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  1758. }
  1759. throw err;
  1760. } finally {
  1761. btnFetchEmail.disabled = false;
  1762. btnFetchEmail.textContent = defaultLabel;
  1763. }
  1764. }
  1765. function syncToggleButtonLabel(button, input, labels) {
  1766. if (!button || !input) return;
  1767. const isHidden = input.type === 'password';
  1768. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  1769. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  1770. button.title = isHidden ? labels.show : labels.hide;
  1771. }
  1772. async function copyTextToClipboard(text) {
  1773. const value = String(text || '').trim();
  1774. if (!value) {
  1775. throw new Error('没有可复制的内容。');
  1776. }
  1777. if (!navigator.clipboard?.writeText) {
  1778. throw new Error('当前环境不支持剪贴板复制。');
  1779. }
  1780. await navigator.clipboard.writeText(value);
  1781. }
  1782. async function exportSettingsFile() {
  1783. closeConfigMenu();
  1784. configActionInFlight = true;
  1785. updateConfigMenuControls();
  1786. try {
  1787. await flushPendingSettingsBeforeExport();
  1788. const response = await chrome.runtime.sendMessage({
  1789. type: 'EXPORT_SETTINGS',
  1790. source: 'sidepanel',
  1791. payload: {},
  1792. });
  1793. if (response?.error) {
  1794. throw new Error(response.error);
  1795. }
  1796. if (!response?.fileContent || !response?.fileName) {
  1797. throw new Error('\u672a\u751f\u6210\u53ef\u4e0b\u8f7d\u7684\u914d\u7f6e\u6587\u4ef6\u3002');
  1798. }
  1799. downloadTextFile(response.fileContent, response.fileName);
  1800. showToast('\u914d\u7f6e\u5df2\u5bfc\u51fa\uff1a' + response.fileName, 'success', 2200);
  1801. } catch (err) {
  1802. showToast('\u5bfc\u51fa\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  1803. } finally {
  1804. configActionInFlight = false;
  1805. updateConfigMenuControls();
  1806. }
  1807. }
  1808. async function importSettingsFromFile(file) {
  1809. if (!file) return;
  1810. configActionInFlight = true;
  1811. closeConfigMenu();
  1812. updateConfigMenuControls();
  1813. try {
  1814. await settlePendingSettingsBeforeImport();
  1815. const rawText = await file.text();
  1816. let parsedConfig = null;
  1817. try {
  1818. parsedConfig = JSON.parse(rawText);
  1819. } catch {
  1820. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002');
  1821. }
  1822. const confirmed = await openConfirmModal({
  1823. title: '\u5bfc\u5165\u914d\u7f6e',
  1824. message: '\u786e\u8ba4\u5bfc\u5165\u914d\u7f6e\u6587\u4ef6 "' + file.name + '" \u5417\uff1f\u5bfc\u5165\u540e\u4f1a\u8986\u76d6\u5f53\u524d\u914d\u7f6e\u3002',
  1825. confirmLabel: '\u786e\u8ba4\u8986\u76d6\u5bfc\u5165',
  1826. confirmVariant: 'btn-danger',
  1827. });
  1828. if (!confirmed) {
  1829. return;
  1830. }
  1831. const response = await chrome.runtime.sendMessage({
  1832. type: 'IMPORT_SETTINGS',
  1833. source: 'sidepanel',
  1834. payload: {
  1835. config: parsedConfig,
  1836. },
  1837. });
  1838. if (response?.error) {
  1839. throw new Error(response.error);
  1840. }
  1841. if (!response?.state) {
  1842. throw new Error('\u5bfc\u5165\u540e\u672a\u8fd4\u56de\u6700\u65b0\u914d\u7f6e\u72b6\u6001\u3002');
  1843. }
  1844. applySettingsState(response.state);
  1845. updateStatusDisplay(latestState);
  1846. showToast('\u914d\u7f6e\u5df2\u5bfc\u5165\uff0c\u5f53\u524d\u914d\u7f6e\u5df2\u8986\u76d6\u3002', 'success', 2200);
  1847. } catch (err) {
  1848. showToast('\u5bfc\u5165\u914d\u7f6e\u5931\u8d25\uff1a' + err.message, 'error');
  1849. } finally {
  1850. configActionInFlight = false;
  1851. updateConfigMenuControls();
  1852. if (inputImportSettingsFile) {
  1853. inputImportSettingsFile.value = '';
  1854. }
  1855. }
  1856. }
  1857. async function deleteHotmailAccountsByMode(mode) {
  1858. const isUsedMode = mode === 'used';
  1859. const targetAccounts = getHotmailAccountsByUsage(isUsedMode ? 'used' : 'all');
  1860. if (!targetAccounts.length) {
  1861. showToast(isUsedMode ? '没有已用账号可清空。' : '没有可删除的 Hotmail 账号。', 'warn');
  1862. return;
  1863. }
  1864. const confirmed = await openConfirmModal({
  1865. title: isUsedMode ? '清空已用账号' : '全部删除账号',
  1866. message: isUsedMode
  1867. ? `确认删除当前 ${targetAccounts.length} 个已用 Hotmail 账号吗?`
  1868. : `确认删除全部 ${targetAccounts.length} 个 Hotmail 账号吗?`,
  1869. confirmLabel: isUsedMode ? '确认清空已用' : '确认全部删除',
  1870. confirmVariant: isUsedMode ? 'btn-outline' : 'btn-danger',
  1871. });
  1872. if (!confirmed) {
  1873. return;
  1874. }
  1875. const response = await chrome.runtime.sendMessage({
  1876. type: 'DELETE_HOTMAIL_ACCOUNTS',
  1877. source: 'sidepanel',
  1878. payload: { mode: isUsedMode ? 'used' : 'all' },
  1879. });
  1880. if (response?.error) {
  1881. throw new Error(response.error);
  1882. }
  1883. const targetIds = new Set(targetAccounts.map((account) => account.id));
  1884. const nextAccounts = isUsedMode
  1885. ? getHotmailAccounts().filter((account) => !targetIds.has(account.id))
  1886. : [];
  1887. const nextState = { hotmailAccounts: nextAccounts };
  1888. if (latestState?.currentHotmailAccountId && targetIds.has(latestState.currentHotmailAccountId)) {
  1889. nextState.currentHotmailAccountId = null;
  1890. if (selectMailProvider.value === 'hotmail-api') {
  1891. nextState.email = null;
  1892. }
  1893. }
  1894. syncLatestState(nextState);
  1895. refreshHotmailSelectionUI();
  1896. showToast(
  1897. isUsedMode
  1898. ? `已清空 ${response.deletedCount || 0} 个已用 Hotmail 账号`
  1899. : `已删除全部 ${response.deletedCount || 0} 个 Hotmail 账号`,
  1900. 'success',
  1901. 2200
  1902. );
  1903. }
  1904. function syncPasswordToggleLabel() {
  1905. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  1906. show: '显示密码',
  1907. hide: '隐藏密码',
  1908. });
  1909. }
  1910. function syncVpsUrlToggleLabel() {
  1911. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  1912. show: '显示 CPA 地址',
  1913. hide: '隐藏 CPA 地址',
  1914. });
  1915. }
  1916. function syncVpsPasswordToggleLabel() {
  1917. syncToggleButtonLabel(btnToggleVpsPassword, inputVpsPassword, {
  1918. show: '显示管理密钥',
  1919. hide: '隐藏管理密钥',
  1920. });
  1921. }
  1922. async function maybeTakeoverAutoRun(actionLabel) {
  1923. if (!isAutoRunPausedPhase()) {
  1924. return true;
  1925. }
  1926. const confirmed = await openConfirmModal({
  1927. title: '接管自动',
  1928. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  1929. confirmLabel: '确认接管',
  1930. confirmVariant: 'btn-primary',
  1931. });
  1932. if (!confirmed) {
  1933. return false;
  1934. }
  1935. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  1936. return true;
  1937. }
  1938. async function handleSkipStep(step) {
  1939. if (isAutoRunPausedPhase()) {
  1940. const takeoverResponse = await chrome.runtime.sendMessage({
  1941. type: 'TAKEOVER_AUTO_RUN',
  1942. source: 'sidepanel',
  1943. payload: {},
  1944. });
  1945. if (takeoverResponse?.error) {
  1946. throw new Error(takeoverResponse.error);
  1947. }
  1948. }
  1949. const response = await chrome.runtime.sendMessage({
  1950. type: 'SKIP_STEP',
  1951. source: 'sidepanel',
  1952. payload: { step },
  1953. });
  1954. if (response?.error) {
  1955. throw new Error(response.error);
  1956. }
  1957. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  1958. }
  1959. // ============================================================
  1960. // Button Handlers
  1961. // ============================================================
  1962. document.querySelectorAll('.step-btn').forEach(btn => {
  1963. btn.addEventListener('click', async () => {
  1964. try {
  1965. const step = Number(btn.dataset.step);
  1966. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  1967. return;
  1968. }
  1969. if (step === 3) {
  1970. if (inputPassword.value !== (latestState?.customPassword || '')) {
  1971. await chrome.runtime.sendMessage({
  1972. type: 'SAVE_SETTING',
  1973. source: 'sidepanel',
  1974. payload: { customPassword: inputPassword.value },
  1975. });
  1976. syncLatestState({ customPassword: inputPassword.value });
  1977. }
  1978. let email = inputEmail.value.trim();
  1979. if (selectMailProvider.value === 'hotmail-api') {
  1980. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1981. if (response?.error) {
  1982. throw new Error(response.error);
  1983. }
  1984. } else if (usesGeneratedAliasMailProvider(selectMailProvider.value)) {
  1985. const emailPrefix = inputEmailPrefix.value.trim();
  1986. if (!emailPrefix) {
  1987. showToast('请先填写 2925 邮箱前缀。', 'warn');
  1988. return;
  1989. }
  1990. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
  1991. if (response?.error) {
  1992. throw new Error(response.error);
  1993. }
  1994. } else {
  1995. let email = inputEmail.value.trim();
  1996. if (!email) {
  1997. if (isCustomEmailGeneratorSelected()) {
  1998. showToast('当前邮箱生成方式为自定义邮箱,请先填写注册邮箱后再执行第 3 步。', 'warn');
  1999. return;
  2000. }
  2001. try {
  2002. email = await fetchGeneratedEmail({ showFailureToast: false });
  2003. } catch (err) {
  2004. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  2005. return;
  2006. }
  2007. }
  2008. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  2009. if (response?.error) {
  2010. throw new Error(response.error);
  2011. }
  2012. }
  2013. } else {
  2014. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  2015. if (response?.error) {
  2016. throw new Error(response.error);
  2017. }
  2018. }
  2019. } catch (err) {
  2020. showToast(err.message, 'error');
  2021. }
  2022. });
  2023. });
  2024. btnFetchEmail.addEventListener('click', async () => {
  2025. if (selectMailProvider.value === 'hotmail-api' || isCustomEmailGeneratorSelected()) {
  2026. return;
  2027. }
  2028. await fetchGeneratedEmail().catch(() => { });
  2029. });
  2030. btnToggleHotmailList?.addEventListener('click', () => {
  2031. setHotmailListExpanded(!hotmailListExpanded);
  2032. });
  2033. btnHotmailUsageGuide?.addEventListener('click', async () => {
  2034. await openConfirmModal({
  2035. title: '使用教程',
  2036. message: '由于第三方服务接口结构不同,所以暂时无法使用,如果您的token可以直连微软,请测试本地功能,详细功能请看项目根目录的readme文件',
  2037. confirmLabel: '确定',
  2038. confirmVariant: 'btn-primary',
  2039. });
  2040. });
  2041. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  2042. if (hotmailActionInFlight) return;
  2043. hotmailActionInFlight = true;
  2044. btnClearUsedHotmailAccounts.disabled = true;
  2045. try {
  2046. await deleteHotmailAccountsByMode('used');
  2047. } catch (err) {
  2048. showToast(err.message, 'error');
  2049. } finally {
  2050. hotmailActionInFlight = false;
  2051. updateHotmailListViewport();
  2052. }
  2053. });
  2054. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  2055. if (hotmailActionInFlight) return;
  2056. hotmailActionInFlight = true;
  2057. btnDeleteAllHotmailAccounts.disabled = true;
  2058. try {
  2059. await deleteHotmailAccountsByMode('all');
  2060. } catch (err) {
  2061. showToast(err.message, 'error');
  2062. } finally {
  2063. hotmailActionInFlight = false;
  2064. updateHotmailListViewport();
  2065. }
  2066. });
  2067. btnAddHotmailAccount?.addEventListener('click', async () => {
  2068. if (hotmailActionInFlight) return;
  2069. const email = inputHotmailEmail.value.trim();
  2070. const clientId = inputHotmailClientId.value.trim();
  2071. const refreshToken = inputHotmailRefreshToken.value.trim();
  2072. if (!email) {
  2073. showToast('请先填写 Hotmail 邮箱。', 'warn');
  2074. return;
  2075. }
  2076. if (!clientId) {
  2077. showToast('请先填写微软应用客户端 ID。', 'warn');
  2078. return;
  2079. }
  2080. if (!refreshToken) {
  2081. showToast('请先填写刷新令牌(refresh token)。', 'warn');
  2082. return;
  2083. }
  2084. hotmailActionInFlight = true;
  2085. btnAddHotmailAccount.disabled = true;
  2086. try {
  2087. const response = await chrome.runtime.sendMessage({
  2088. type: 'UPSERT_HOTMAIL_ACCOUNT',
  2089. source: 'sidepanel',
  2090. payload: {
  2091. email,
  2092. clientId,
  2093. password: inputHotmailPassword.value,
  2094. refreshToken,
  2095. },
  2096. });
  2097. if (response?.error) {
  2098. throw new Error(response.error);
  2099. }
  2100. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  2101. clearHotmailForm();
  2102. } catch (err) {
  2103. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  2104. } finally {
  2105. hotmailActionInFlight = false;
  2106. btnAddHotmailAccount.disabled = false;
  2107. }
  2108. });
  2109. btnImportHotmailAccounts?.addEventListener('click', async () => {
  2110. if (hotmailActionInFlight) return;
  2111. if (typeof parseHotmailImportText !== 'function') {
  2112. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  2113. return;
  2114. }
  2115. const rawText = inputHotmailImport.value.trim();
  2116. if (!rawText) {
  2117. showToast('请先粘贴账号导入内容。', 'warn');
  2118. return;
  2119. }
  2120. const parsedAccounts = parseHotmailImportText(rawText);
  2121. if (!parsedAccounts.length) {
  2122. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  2123. return;
  2124. }
  2125. hotmailActionInFlight = true;
  2126. btnImportHotmailAccounts.disabled = true;
  2127. try {
  2128. for (const account of parsedAccounts) {
  2129. const response = await chrome.runtime.sendMessage({
  2130. type: 'UPSERT_HOTMAIL_ACCOUNT',
  2131. source: 'sidepanel',
  2132. payload: account,
  2133. });
  2134. if (response?.error) {
  2135. throw new Error(response.error);
  2136. }
  2137. }
  2138. inputHotmailImport.value = '';
  2139. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  2140. } catch (err) {
  2141. showToast(`批量导入失败:${err.message}`, 'error');
  2142. } finally {
  2143. hotmailActionInFlight = false;
  2144. btnImportHotmailAccounts.disabled = false;
  2145. }
  2146. });
  2147. hotmailAccountsList?.addEventListener('click', async (event) => {
  2148. const actionButton = event.target.closest('[data-account-action]');
  2149. if (!actionButton || hotmailActionInFlight) {
  2150. return;
  2151. }
  2152. const accountId = actionButton.dataset.accountId;
  2153. const action = actionButton.dataset.accountAction;
  2154. if (!accountId || !action) {
  2155. return;
  2156. }
  2157. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  2158. hotmailActionInFlight = true;
  2159. actionButton.disabled = true;
  2160. try {
  2161. if (action === 'copy-email') {
  2162. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  2163. await copyTextToClipboard(targetAccount.email);
  2164. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  2165. } else if (action === 'select') {
  2166. const response = await chrome.runtime.sendMessage({
  2167. type: 'SELECT_HOTMAIL_ACCOUNT',
  2168. source: 'sidepanel',
  2169. payload: { accountId },
  2170. });
  2171. if (response?.error) throw new Error(response.error);
  2172. syncLatestState({ currentHotmailAccountId: response.account.id });
  2173. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  2174. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  2175. } else if (action === 'toggle-used') {
  2176. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  2177. const response = await chrome.runtime.sendMessage({
  2178. type: 'PATCH_HOTMAIL_ACCOUNT',
  2179. source: 'sidepanel',
  2180. payload: {
  2181. accountId,
  2182. updates: { used: !targetAccount.used },
  2183. },
  2184. });
  2185. if (response?.error) throw new Error(response.error);
  2186. applyHotmailAccountMutation(response.account);
  2187. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  2188. } else if (action === 'verify') {
  2189. const response = await chrome.runtime.sendMessage({
  2190. type: 'VERIFY_HOTMAIL_ACCOUNT',
  2191. source: 'sidepanel',
  2192. payload: { accountId },
  2193. });
  2194. if (response?.error) throw new Error(response.error);
  2195. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  2196. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  2197. } else if (action === 'test') {
  2198. const response = await chrome.runtime.sendMessage({
  2199. type: 'TEST_HOTMAIL_ACCOUNT',
  2200. source: 'sidepanel',
  2201. payload: { accountId },
  2202. });
  2203. if (response?.error) throw new Error(response.error);
  2204. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  2205. if (response.latestCode) {
  2206. await copyTextToClipboard(response.latestCode);
  2207. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  2208. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  2209. } else if (response.latestSubject) {
  2210. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  2211. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  2212. } else {
  2213. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  2214. }
  2215. } else if (action === 'delete') {
  2216. const confirmed = await openConfirmModal({
  2217. title: '删除账号',
  2218. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  2219. confirmLabel: '确认删除',
  2220. confirmVariant: 'btn-danger',
  2221. });
  2222. if (!confirmed) {
  2223. return;
  2224. }
  2225. const response = await chrome.runtime.sendMessage({
  2226. type: 'DELETE_HOTMAIL_ACCOUNT',
  2227. source: 'sidepanel',
  2228. payload: { accountId },
  2229. });
  2230. if (response?.error) throw new Error(response.error);
  2231. showToast('Hotmail 账号已删除', 'success', 1800);
  2232. }
  2233. } catch (err) {
  2234. showToast(err.message, 'error');
  2235. } finally {
  2236. hotmailActionInFlight = false;
  2237. actionButton.disabled = false;
  2238. }
  2239. });
  2240. btnTogglePassword.addEventListener('click', () => {
  2241. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  2242. syncPasswordToggleLabel();
  2243. });
  2244. btnToggleVpsUrl.addEventListener('click', () => {
  2245. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  2246. syncVpsUrlToggleLabel();
  2247. });
  2248. btnToggleVpsPassword.addEventListener('click', () => {
  2249. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  2250. syncVpsPasswordToggleLabel();
  2251. });
  2252. btnMailLogin?.addEventListener('click', async () => {
  2253. const config = getMailProviderLoginConfig();
  2254. if (!config) {
  2255. return;
  2256. }
  2257. try {
  2258. await chrome.tabs.create({ url: config.url, active: true });
  2259. } catch (err) {
  2260. showToast(`打开${config.label}失败:${err.message}`, 'error');
  2261. }
  2262. });
  2263. localCpaStep9ModeButtons.forEach((button) => {
  2264. button.addEventListener('click', () => {
  2265. const nextMode = button.dataset.localCpaStep9Mode;
  2266. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  2267. return;
  2268. }
  2269. setLocalCpaStep9Mode(nextMode);
  2270. markSettingsDirty(true);
  2271. saveSettings({ silent: true }).catch(() => { });
  2272. });
  2273. });
  2274. hotmailServiceModeButtons.forEach((button) => {
  2275. button.addEventListener('click', () => {
  2276. if (button.disabled) {
  2277. return;
  2278. }
  2279. const nextMode = button.dataset.hotmailServiceMode;
  2280. if (getSelectedHotmailServiceMode() === normalizeHotmailServiceMode(nextMode)) {
  2281. return;
  2282. }
  2283. setHotmailServiceMode(nextMode);
  2284. updateMailProviderUI();
  2285. markSettingsDirty(true);
  2286. saveSettings({ silent: true }).catch(() => { });
  2287. });
  2288. });
  2289. btnSaveSettings.addEventListener('click', async () => {
  2290. if (!settingsDirty) {
  2291. showToast('配置已是最新', 'info', 1400);
  2292. return;
  2293. }
  2294. await saveSettings({ silent: false }).catch(() => { });
  2295. });
  2296. btnStop.addEventListener('click', async () => {
  2297. btnStop.disabled = true;
  2298. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  2299. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  2300. });
  2301. btnConfigMenu?.addEventListener('click', (event) => {
  2302. event.stopPropagation();
  2303. toggleConfigMenu();
  2304. });
  2305. configMenu?.addEventListener('click', (event) => {
  2306. event.stopPropagation();
  2307. });
  2308. btnExportSettings?.addEventListener('click', async () => {
  2309. if (configActionInFlight || settingsSaveInFlight) {
  2310. return;
  2311. }
  2312. await exportSettingsFile();
  2313. });
  2314. btnImportSettings?.addEventListener('click', async () => {
  2315. if (configActionInFlight || settingsSaveInFlight) {
  2316. return;
  2317. }
  2318. closeConfigMenu();
  2319. if (inputImportSettingsFile) {
  2320. inputImportSettingsFile.value = '';
  2321. inputImportSettingsFile.click();
  2322. }
  2323. });
  2324. inputImportSettingsFile?.addEventListener('change', async () => {
  2325. const file = inputImportSettingsFile.files?.[0] || null;
  2326. await importSettingsFromFile(file);
  2327. });
  2328. autoStartModal?.addEventListener('click', (event) => {
  2329. if (event.target === autoStartModal) {
  2330. resolveModalChoice(null);
  2331. }
  2332. });
  2333. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  2334. // Auto Run
  2335. btnAutoRun.addEventListener('click', async () => {
  2336. try {
  2337. const totalRuns = getRunCountValue();
  2338. let mode = 'restart';
  2339. const autoRunSkipFailures = inputAutoSkipFailures.checked;
  2340. const fallbackThreadIntervalMinutes = normalizeAutoRunThreadIntervalMinutes(
  2341. inputAutoSkipFailuresThreadIntervalMinutes.value
  2342. );
  2343. inputAutoSkipFailuresThreadIntervalMinutes.value = String(fallbackThreadIntervalMinutes);
  2344. if (shouldOfferAutoModeChoice()) {
  2345. const startStep = getFirstUnfinishedStep();
  2346. const runningStep = getRunningSteps()[0] ?? null;
  2347. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  2348. if (!choice) {
  2349. return;
  2350. }
  2351. mode = choice;
  2352. }
  2353. if (shouldWarnAutoRunFallbackRisk(totalRuns, autoRunSkipFailures)
  2354. && !isAutoRunFallbackRiskPromptDismissed()) {
  2355. const result = await openAutoRunFallbackRiskConfirmModal(totalRuns, fallbackThreadIntervalMinutes);
  2356. if (!result.confirmed) {
  2357. return;
  2358. }
  2359. if (result.dismissPrompt) {
  2360. setAutoRunFallbackRiskPromptDismissed(true);
  2361. }
  2362. }
  2363. btnAutoRun.disabled = true;
  2364. inputRunCount.disabled = true;
  2365. const delayEnabled = inputAutoDelayEnabled.checked;
  2366. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  2367. inputAutoDelayMinutes.value = String(delayMinutes);
  2368. btnAutoRun.innerHTML = delayEnabled
  2369. ? '<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> 计划中...'
  2370. : '<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> 运行中...';
  2371. const response = await chrome.runtime.sendMessage({
  2372. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  2373. source: 'sidepanel',
  2374. payload: {
  2375. totalRuns,
  2376. delayMinutes,
  2377. autoRunSkipFailures,
  2378. mode,
  2379. },
  2380. });
  2381. if (response?.error) {
  2382. throw new Error(response.error);
  2383. }
  2384. } catch (err) {
  2385. setDefaultAutoRunButton();
  2386. inputRunCount.disabled = false;
  2387. showToast(err.message, 'error');
  2388. }
  2389. });
  2390. btnAutoContinue.addEventListener('click', async () => {
  2391. const email = inputEmail.value.trim();
  2392. if (!email) {
  2393. showToast(
  2394. isCustomEmailGeneratorSelected() ? '请先填写自定义注册邮箱。' : '请先获取或粘贴邮箱。',
  2395. 'warn'
  2396. );
  2397. return;
  2398. }
  2399. autoContinueBar.style.display = 'none';
  2400. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  2401. });
  2402. btnAutoRunNow?.addEventListener('click', async () => {
  2403. try {
  2404. btnAutoRunNow.disabled = true;
  2405. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  2406. } catch (err) {
  2407. showToast(err.message, 'error');
  2408. } finally {
  2409. btnAutoRunNow.disabled = false;
  2410. }
  2411. });
  2412. btnAutoCancelSchedule?.addEventListener('click', async () => {
  2413. try {
  2414. btnAutoCancelSchedule.disabled = true;
  2415. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  2416. showToast('已取消倒计时计划。', 'info', 1800);
  2417. } catch (err) {
  2418. showToast(err.message, 'error');
  2419. } finally {
  2420. btnAutoCancelSchedule.disabled = false;
  2421. }
  2422. });
  2423. // Reset
  2424. btnReset.addEventListener('click', async () => {
  2425. const confirmed = await openConfirmModal({
  2426. title: '重置流程',
  2427. message: '确认重置全部步骤和数据吗?',
  2428. confirmLabel: '确认重置',
  2429. confirmVariant: 'btn-danger',
  2430. });
  2431. if (!confirmed) {
  2432. return;
  2433. }
  2434. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  2435. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  2436. syncAutoRunState({
  2437. autoRunning: false,
  2438. autoRunPhase: 'idle',
  2439. autoRunCurrentRun: 0,
  2440. autoRunTotalRuns: 1,
  2441. autoRunAttemptRun: 0,
  2442. scheduledAutoRunAt: null,
  2443. });
  2444. displayOauthUrl.textContent = '等待中...';
  2445. displayOauthUrl.classList.remove('has-value');
  2446. displayLocalhostUrl.textContent = '等待中...';
  2447. displayLocalhostUrl.classList.remove('has-value');
  2448. inputEmail.value = '';
  2449. displayStatus.textContent = '就绪';
  2450. statusBar.className = 'status-bar';
  2451. logArea.innerHTML = '';
  2452. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2453. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2454. setDefaultAutoRunButton();
  2455. applyAutoRunStatus(currentAutoRun);
  2456. markSettingsDirty(false);
  2457. updateStopButtonState(false);
  2458. updateButtonStates();
  2459. updateProgressCounter();
  2460. renderHotmailAccounts();
  2461. });
  2462. // Clear log
  2463. btnClearLog.addEventListener('click', () => {
  2464. logArea.innerHTML = '';
  2465. });
  2466. // Save settings on change
  2467. inputEmail.addEventListener('change', async () => {
  2468. if (selectMailProvider.value === 'hotmail-api') {
  2469. return;
  2470. }
  2471. const email = inputEmail.value.trim();
  2472. inputEmail.value = email;
  2473. try {
  2474. if (email) {
  2475. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  2476. if (response?.error) {
  2477. throw new Error(response.error);
  2478. }
  2479. } else {
  2480. await setRuntimeEmailState(null);
  2481. }
  2482. } catch (err) {
  2483. showToast(err.message, 'error');
  2484. }
  2485. });
  2486. inputEmail.addEventListener('input', updateButtonStates);
  2487. inputVpsUrl.addEventListener('input', () => {
  2488. markSettingsDirty(true);
  2489. scheduleSettingsAutoSave();
  2490. });
  2491. inputVpsUrl.addEventListener('blur', () => {
  2492. saveSettings({ silent: true }).catch(() => { });
  2493. });
  2494. inputVpsPassword.addEventListener('input', () => {
  2495. markSettingsDirty(true);
  2496. scheduleSettingsAutoSave();
  2497. });
  2498. inputVpsPassword.addEventListener('blur', () => {
  2499. saveSettings({ silent: true }).catch(() => { });
  2500. });
  2501. [inputHotmailRemoteBaseUrl, inputHotmailLocalBaseUrl].forEach((input) => {
  2502. input?.addEventListener('input', () => {
  2503. markSettingsDirty(true);
  2504. scheduleSettingsAutoSave();
  2505. });
  2506. input?.addEventListener('blur', () => {
  2507. saveSettings({ silent: true }).catch(() => { });
  2508. });
  2509. });
  2510. inputPassword.addEventListener('input', () => {
  2511. markSettingsDirty(true);
  2512. updateButtonStates();
  2513. scheduleSettingsAutoSave();
  2514. });
  2515. inputPassword.addEventListener('blur', () => {
  2516. saveSettings({ silent: true }).catch(() => { });
  2517. });
  2518. selectMailProvider.addEventListener('change', async () => {
  2519. const previousProvider = latestState?.mailProvider || '';
  2520. const nextProvider = selectMailProvider.value;
  2521. updateMailProviderUI();
  2522. const leavingHotmail = previousProvider === 'hotmail-api'
  2523. && nextProvider !== 'hotmail-api'
  2524. && isCurrentEmailManagedByHotmail();
  2525. const leavingGeneratedAlias = previousProvider !== nextProvider
  2526. && usesGeneratedAliasMailProvider(previousProvider)
  2527. && isCurrentEmailManagedByGeneratedAlias(previousProvider);
  2528. if (leavingHotmail || leavingGeneratedAlias) {
  2529. await clearRegistrationEmail({ silent: true }).catch(() => { });
  2530. }
  2531. markSettingsDirty(true);
  2532. saveSettings({ silent: true }).catch(() => { });
  2533. });
  2534. selectEmailGenerator.addEventListener('change', () => {
  2535. updateMailProviderUI();
  2536. clearRegistrationEmail({ silent: true }).catch(() => { });
  2537. markSettingsDirty(true);
  2538. saveSettings({ silent: true }).catch(() => { });
  2539. });
  2540. selectPanelMode.addEventListener('change', () => {
  2541. updatePanelModeUI();
  2542. markSettingsDirty(true);
  2543. saveSettings({ silent: true }).catch(() => { });
  2544. });
  2545. selectCfDomain.addEventListener('change', () => {
  2546. if (selectCfDomain.disabled) {
  2547. return;
  2548. }
  2549. markSettingsDirty(true);
  2550. saveSettings({ silent: true }).catch(() => { });
  2551. });
  2552. btnCfDomainMode.addEventListener('click', async () => {
  2553. try {
  2554. if (!cloudflareDomainEditMode) {
  2555. setCloudflareDomainEditMode(true, { clearInput: true });
  2556. return;
  2557. }
  2558. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  2559. if (!newDomain) {
  2560. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  2561. inputCfDomain.focus();
  2562. return;
  2563. }
  2564. const { domains } = getCloudflareDomainsFromState();
  2565. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  2566. } catch (err) {
  2567. showToast(err.message, 'error');
  2568. }
  2569. });
  2570. inputCfDomain.addEventListener('keydown', (event) => {
  2571. if (event.key === 'Enter') {
  2572. event.preventDefault();
  2573. btnCfDomainMode.click();
  2574. }
  2575. });
  2576. inputSub2ApiUrl.addEventListener('input', () => {
  2577. markSettingsDirty(true);
  2578. scheduleSettingsAutoSave();
  2579. });
  2580. inputSub2ApiUrl.addEventListener('blur', () => {
  2581. saveSettings({ silent: true }).catch(() => { });
  2582. });
  2583. inputSub2ApiEmail.addEventListener('input', () => {
  2584. markSettingsDirty(true);
  2585. scheduleSettingsAutoSave();
  2586. });
  2587. inputSub2ApiEmail.addEventListener('blur', () => {
  2588. saveSettings({ silent: true }).catch(() => { });
  2589. });
  2590. inputSub2ApiPassword.addEventListener('input', () => {
  2591. markSettingsDirty(true);
  2592. scheduleSettingsAutoSave();
  2593. });
  2594. inputSub2ApiPassword.addEventListener('blur', () => {
  2595. saveSettings({ silent: true }).catch(() => { });
  2596. });
  2597. inputSub2ApiGroup.addEventListener('input', () => {
  2598. markSettingsDirty(true);
  2599. scheduleSettingsAutoSave();
  2600. });
  2601. inputSub2ApiGroup.addEventListener('blur', () => {
  2602. saveSettings({ silent: true }).catch(() => { });
  2603. });
  2604. inputEmailPrefix.addEventListener('input', () => {
  2605. markSettingsDirty(true);
  2606. scheduleSettingsAutoSave();
  2607. });
  2608. inputEmailPrefix.addEventListener('blur', () => {
  2609. saveSettings({ silent: true }).catch(() => {});
  2610. });
  2611. inputInbucketMailbox.addEventListener('input', () => {
  2612. markSettingsDirty(true);
  2613. scheduleSettingsAutoSave();
  2614. });
  2615. inputInbucketMailbox.addEventListener('blur', () => {
  2616. saveSettings({ silent: true }).catch(() => { });
  2617. });
  2618. inputInbucketHost.addEventListener('input', () => {
  2619. markSettingsDirty(true);
  2620. scheduleSettingsAutoSave();
  2621. });
  2622. inputInbucketHost.addEventListener('blur', () => {
  2623. saveSettings({ silent: true }).catch(() => { });
  2624. });
  2625. inputRunCount.addEventListener('input', () => {
  2626. updateFallbackThreadIntervalInputState();
  2627. });
  2628. inputRunCount.addEventListener('blur', () => {
  2629. inputRunCount.value = String(getRunCountValue());
  2630. updateFallbackThreadIntervalInputState();
  2631. });
  2632. inputAutoSkipFailures.addEventListener('change', async () => {
  2633. if (inputAutoSkipFailures.checked && !isAutoSkipFailuresPromptDismissed()) {
  2634. const result = await openAutoSkipFailuresConfirmModal();
  2635. if (!result.confirmed) {
  2636. inputAutoSkipFailures.checked = false;
  2637. updateFallbackThreadIntervalInputState();
  2638. return;
  2639. }
  2640. if (result.dismissPrompt) {
  2641. setAutoSkipFailuresPromptDismissed(true);
  2642. }
  2643. }
  2644. updateFallbackThreadIntervalInputState();
  2645. markSettingsDirty(true);
  2646. saveSettings({ silent: true }).catch(() => { });
  2647. });
  2648. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('input', () => {
  2649. markSettingsDirty(true);
  2650. scheduleSettingsAutoSave();
  2651. });
  2652. inputAutoSkipFailuresThreadIntervalMinutes.addEventListener('blur', () => {
  2653. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  2654. normalizeAutoRunThreadIntervalMinutes(inputAutoSkipFailuresThreadIntervalMinutes.value)
  2655. );
  2656. saveSettings({ silent: true }).catch(() => { });
  2657. });
  2658. inputAutoDelayEnabled.addEventListener('change', () => {
  2659. updateAutoDelayInputState();
  2660. markSettingsDirty(true);
  2661. saveSettings({ silent: true }).catch(() => { });
  2662. });
  2663. inputAutoDelayMinutes.addEventListener('input', () => {
  2664. markSettingsDirty(true);
  2665. scheduleSettingsAutoSave();
  2666. });
  2667. inputAutoDelayMinutes.addEventListener('blur', () => {
  2668. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  2669. saveSettings({ silent: true }).catch(() => { });
  2670. });
  2671. function syncAutoStepDelayInputs() {
  2672. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(inputAutoStepDelaySeconds.value);
  2673. }
  2674. inputAutoStepDelaySeconds.addEventListener('input', () => {
  2675. markSettingsDirty(true);
  2676. scheduleSettingsAutoSave();
  2677. });
  2678. inputAutoStepDelaySeconds.addEventListener('blur', () => {
  2679. syncAutoStepDelayInputs();
  2680. saveSettings({ silent: true }).catch(() => { });
  2681. });
  2682. // ============================================================
  2683. // Listen for Background broadcasts
  2684. // ============================================================
  2685. chrome.runtime.onMessage.addListener((message) => {
  2686. switch (message.type) {
  2687. case 'LOG_ENTRY':
  2688. appendLog(message.payload);
  2689. if (message.payload.level === 'error') {
  2690. showToast(message.payload.message, 'error');
  2691. }
  2692. break;
  2693. case 'STEP_STATUS_CHANGED': {
  2694. const { step, status } = message.payload;
  2695. updateStepUI(step, status);
  2696. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  2697. syncLatestState(state);
  2698. syncAutoRunState(state);
  2699. updateStatusDisplay(latestState);
  2700. updateButtonStates();
  2701. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  2702. syncPasswordField(state);
  2703. if (state.oauthUrl) {
  2704. displayOauthUrl.textContent = state.oauthUrl;
  2705. displayOauthUrl.classList.add('has-value');
  2706. }
  2707. if (state.localhostUrl) {
  2708. displayLocalhostUrl.textContent = state.localhostUrl;
  2709. displayLocalhostUrl.classList.add('has-value');
  2710. }
  2711. }
  2712. }
  2713. ).catch(() => { });
  2714. break;
  2715. }
  2716. case 'AUTO_RUN_RESET': {
  2717. // Full UI reset for next run
  2718. syncLatestState({
  2719. oauthUrl: null,
  2720. localhostUrl: null,
  2721. email: null,
  2722. password: null,
  2723. stepStatuses: STEP_DEFAULT_STATUSES,
  2724. logs: [],
  2725. scheduledAutoRunAt: null,
  2726. });
  2727. displayOauthUrl.textContent = '等待中...';
  2728. displayOauthUrl.classList.remove('has-value');
  2729. displayLocalhostUrl.textContent = '等待中...';
  2730. displayLocalhostUrl.classList.remove('has-value');
  2731. inputEmail.value = '';
  2732. displayStatus.textContent = '就绪';
  2733. statusBar.className = 'status-bar';
  2734. logArea.innerHTML = '';
  2735. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2736. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2737. applyAutoRunStatus(currentAutoRun);
  2738. updateProgressCounter();
  2739. updateButtonStates();
  2740. renderHotmailAccounts();
  2741. break;
  2742. }
  2743. case 'DATA_UPDATED': {
  2744. syncLatestState(message.payload);
  2745. if (message.payload.email !== undefined) {
  2746. inputEmail.value = message.payload.email || '';
  2747. }
  2748. if (message.payload.password !== undefined) {
  2749. inputPassword.value = message.payload.password || '';
  2750. }
  2751. if (message.payload.localCpaStep9Mode !== undefined) {
  2752. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  2753. }
  2754. if (message.payload.oauthUrl !== undefined) {
  2755. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  2756. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  2757. }
  2758. if (message.payload.localhostUrl !== undefined) {
  2759. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  2760. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  2761. }
  2762. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  2763. renderHotmailAccounts();
  2764. if (selectMailProvider.value === 'hotmail-api') {
  2765. inputEmail.value = getCurrentHotmailEmail();
  2766. }
  2767. }
  2768. if (message.payload.autoRunSkipFailures !== undefined) {
  2769. inputAutoSkipFailures.checked = Boolean(message.payload.autoRunSkipFailures);
  2770. updateFallbackThreadIntervalInputState();
  2771. }
  2772. if (message.payload.autoRunDelayEnabled !== undefined) {
  2773. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  2774. updateAutoDelayInputState();
  2775. }
  2776. if (message.payload.autoRunDelayMinutes !== undefined) {
  2777. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  2778. }
  2779. if (message.payload.autoRunFallbackThreadIntervalMinutes !== undefined) {
  2780. inputAutoSkipFailuresThreadIntervalMinutes.value = String(
  2781. normalizeAutoRunThreadIntervalMinutes(message.payload.autoRunFallbackThreadIntervalMinutes)
  2782. );
  2783. updateFallbackThreadIntervalInputState();
  2784. }
  2785. if (message.payload.autoStepDelaySeconds !== undefined) {
  2786. inputAutoStepDelaySeconds.value = formatAutoStepDelayInputValue(message.payload.autoStepDelaySeconds);
  2787. }
  2788. break;
  2789. }
  2790. case 'AUTO_RUN_STATUS': {
  2791. syncLatestState({
  2792. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(message.payload.phase),
  2793. autoRunPhase: message.payload.phase,
  2794. autoRunCurrentRun: message.payload.currentRun,
  2795. autoRunTotalRuns: message.payload.totalRuns,
  2796. autoRunAttemptRun: message.payload.attemptRun,
  2797. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  2798. });
  2799. applyAutoRunStatus(message.payload);
  2800. updateStatusDisplay(latestState);
  2801. updateButtonStates();
  2802. break;
  2803. }
  2804. }
  2805. });
  2806. // ============================================================
  2807. // Theme Toggle
  2808. // ============================================================
  2809. const btnTheme = document.getElementById('btn-theme');
  2810. function setTheme(theme) {
  2811. document.documentElement.setAttribute('data-theme', theme);
  2812. localStorage.setItem('multipage-theme', theme);
  2813. }
  2814. function initTheme() {
  2815. const saved = localStorage.getItem('multipage-theme');
  2816. if (saved) {
  2817. setTheme(saved);
  2818. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  2819. setTheme('dark');
  2820. }
  2821. }
  2822. btnTheme.addEventListener('click', () => {
  2823. const current = document.documentElement.getAttribute('data-theme');
  2824. setTheme(current === 'dark' ? 'light' : 'dark');
  2825. });
  2826. document.addEventListener('click', (event) => {
  2827. if (!configMenuOpen) {
  2828. return;
  2829. }
  2830. if (configMenuShell?.contains(event.target)) {
  2831. return;
  2832. }
  2833. closeConfigMenu();
  2834. });
  2835. document.addEventListener('keydown', (event) => {
  2836. if (event.key === 'Escape' && configMenuOpen) {
  2837. closeConfigMenu();
  2838. }
  2839. });
  2840. // ============================================================
  2841. // Init
  2842. // ============================================================
  2843. initializeManualStepActions();
  2844. initTheme();
  2845. initHotmailListExpandedState();
  2846. updateSaveButtonState();
  2847. updateConfigMenuControls();
  2848. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  2849. initializeReleaseInfo().catch((err) => {
  2850. console.error('Failed to initialize release info:', err);
  2851. });
  2852. restoreState().then(() => {
  2853. syncPasswordToggleLabel();
  2854. syncVpsUrlToggleLabel();
  2855. syncVpsPasswordToggleLabel();
  2856. updatePanelModeUI();
  2857. updateButtonStates();
  2858. updateStatusDisplay(latestState);
  2859. });