sidepanel.js 105 KB

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