sidepanel.js 103 KB

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