sidepanel.js 113 KB

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