sidepanel.js 85 KB

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