sidepanel.js 99 KB

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