sidepanel.js 104 KB

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