sidepanel.js 105 KB

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