sidepanel.js 126 KB

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