sidepanel.js 116 KB

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