sidepanel.js 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527
  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 selectEmailGenerator = document.getElementById('select-email-generator');
  59. const hotmailSection = document.getElementById('hotmail-section');
  60. const inputHotmailEmail = document.getElementById('input-hotmail-email');
  61. const inputHotmailClientId = document.getElementById('input-hotmail-client-id');
  62. const inputHotmailPassword = document.getElementById('input-hotmail-password');
  63. const inputHotmailRefreshToken = document.getElementById('input-hotmail-refresh-token');
  64. const inputHotmailImport = document.getElementById('input-hotmail-import');
  65. const btnAddHotmailAccount = document.getElementById('btn-add-hotmail-account');
  66. const btnImportHotmailAccounts = document.getElementById('btn-import-hotmail-accounts');
  67. const btnClearUsedHotmailAccounts = document.getElementById('btn-clear-used-hotmail-accounts');
  68. const btnDeleteAllHotmailAccounts = document.getElementById('btn-delete-all-hotmail-accounts');
  69. const btnToggleHotmailList = document.getElementById('btn-toggle-hotmail-list');
  70. const hotmailListShell = document.getElementById('hotmail-list-shell');
  71. const hotmailAccountsList = document.getElementById('hotmail-accounts-list');
  72. const rowEmailPrefix = document.getElementById('row-email-prefix');
  73. const labelEmailPrefix = document.getElementById('label-email-prefix');
  74. const inputEmailPrefix = document.getElementById('input-email-prefix');
  75. const rowInbucketHost = document.getElementById('row-inbucket-host');
  76. const inputInbucketHost = document.getElementById('input-inbucket-host');
  77. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  78. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  79. const rowCfDomain = document.getElementById('row-cf-domain');
  80. const selectCfDomain = document.getElementById('select-cf-domain');
  81. const inputCfDomain = document.getElementById('input-cf-domain');
  82. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  83. const inputRunCount = document.getElementById('input-run-count');
  84. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  85. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  86. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  87. const autoStartModal = document.getElementById('auto-start-modal');
  88. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  89. const autoStartMessage = document.getElementById('auto-start-message');
  90. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  91. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  92. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  93. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  94. const autoHintText = document.querySelector('.auto-hint');
  95. const STEP_DEFAULT_STATUSES = {
  96. 1: 'pending',
  97. 2: 'pending',
  98. 3: 'pending',
  99. 4: 'pending',
  100. 5: 'pending',
  101. 6: 'pending',
  102. 7: 'pending',
  103. 8: 'pending',
  104. 9: 'pending',
  105. };
  106. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  107. const AUTO_DELAY_MIN_MINUTES = 1;
  108. const AUTO_DELAY_MAX_MINUTES = 1440;
  109. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  110. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  111. let latestState = null;
  112. let currentAutoRun = {
  113. autoRunning: false,
  114. phase: 'idle',
  115. currentRun: 0,
  116. totalRuns: 1,
  117. attemptRun: 0,
  118. scheduledAt: null,
  119. };
  120. let settingsDirty = false;
  121. let settingsSaveInFlight = false;
  122. let settingsAutoSaveTimer = null;
  123. let cloudflareDomainEditMode = false;
  124. let modalChoiceResolver = null;
  125. let currentModalActions = [];
  126. let scheduledCountdownTimer = null;
  127. let hotmailActionInFlight = false;
  128. let hotmailListExpanded = false;
  129. let configMenuOpen = false;
  130. let configActionInFlight = false;
  131. 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>';
  132. 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>';
  133. 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>';
  134. const parseHotmailImportText = window.HotmailUtils?.parseHotmailImportText;
  135. const shouldClearHotmailCurrentSelection = window.HotmailUtils?.shouldClearHotmailCurrentSelection;
  136. const upsertHotmailAccountInList = window.HotmailUtils?.upsertHotmailAccountInList;
  137. const filterHotmailAccountsByUsage = window.HotmailUtils?.filterHotmailAccountsByUsage;
  138. const getHotmailBulkActionLabel = window.HotmailUtils?.getHotmailBulkActionLabel;
  139. const getHotmailListToggleLabel = window.HotmailUtils?.getHotmailListToggleLabel;
  140. const HOTMAIL_LIST_EXPANDED_STORAGE_KEY = 'multipage-hotmail-list-expanded';
  141. // ============================================================
  142. // Toast Notifications
  143. // ============================================================
  144. const toastContainer = document.getElementById('toast-container');
  145. const TOAST_ICONS = {
  146. 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>',
  147. 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>',
  148. 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>',
  149. 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>',
  150. };
  151. const LOG_LEVEL_LABELS = {
  152. info: '信息',
  153. ok: '成功',
  154. warn: '警告',
  155. error: '错误',
  156. };
  157. function usesGeneratedAliasMailProvider(provider) {
  158. return provider === '2925';
  159. }
  160. function showToast(message, type = 'error', duration = 4000) {
  161. const toast = document.createElement('div');
  162. toast.className = `toast toast-${type}`;
  163. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  164. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  165. toastContainer.appendChild(toast);
  166. if (duration > 0) {
  167. setTimeout(() => dismissToast(toast), duration);
  168. }
  169. }
  170. function dismissToast(toast) {
  171. if (!toast.parentNode) return;
  172. toast.classList.add('toast-exit');
  173. toast.addEventListener('animationend', () => toast.remove());
  174. }
  175. function resetActionModalButtons() {
  176. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  177. buttons.forEach((button) => {
  178. if (!button) return;
  179. button.hidden = true;
  180. button.disabled = false;
  181. button.onclick = null;
  182. });
  183. currentModalActions = [];
  184. }
  185. function configureActionModalButton(button, action) {
  186. if (!button) return;
  187. if (!action) {
  188. button.hidden = true;
  189. button.onclick = null;
  190. return;
  191. }
  192. button.hidden = false;
  193. button.disabled = false;
  194. button.textContent = action.label;
  195. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  196. button.onclick = () => resolveModalChoice(action.id);
  197. }
  198. function resolveModalChoice(choice) {
  199. if (modalChoiceResolver) {
  200. modalChoiceResolver(choice);
  201. modalChoiceResolver = null;
  202. }
  203. resetActionModalButtons();
  204. if (autoStartModal) {
  205. autoStartModal.hidden = true;
  206. }
  207. }
  208. function openActionModal({ title, message, actions }) {
  209. if (!autoStartModal) {
  210. return Promise.resolve(null);
  211. }
  212. if (modalChoiceResolver) {
  213. resolveModalChoice(null);
  214. }
  215. autoStartTitle.textContent = title;
  216. autoStartMessage.textContent = message;
  217. currentModalActions = actions || [];
  218. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  219. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  220. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  221. autoStartModal.hidden = false;
  222. return new Promise((resolve) => {
  223. modalChoiceResolver = resolve;
  224. });
  225. }
  226. function openAutoStartChoiceDialog(startStep, options = {}) {
  227. const runningStep = Number.isInteger(options.runningStep) ? options.runningStep : null;
  228. const continueMessage = runningStep
  229. ? `继续当前会先等待步骤 ${runningStep} 完成,再按最新进度自动执行。`
  230. : `继续当前会从步骤 ${startStep} 开始自动执行。`;
  231. return openActionModal({
  232. title: '启动自动',
  233. message: `检测到当前已有流程进度。${continueMessage}重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  234. actions: [
  235. { id: null, label: '取消', variant: 'btn-ghost' },
  236. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  237. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  238. ],
  239. });
  240. }
  241. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  242. const choice = await openActionModal({
  243. title,
  244. message,
  245. actions: [
  246. { id: null, label: '取消', variant: 'btn-ghost' },
  247. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  248. ],
  249. });
  250. return choice === 'confirm';
  251. }
  252. function updateConfigMenuControls() {
  253. const disabled = configActionInFlight || settingsSaveInFlight;
  254. const importLocked = disabled
  255. || currentAutoRun.autoRunning
  256. || Object.values(getStepStatuses()).some((status) => status === 'running');
  257. if (btnConfigMenu) {
  258. btnConfigMenu.disabled = disabled;
  259. btnConfigMenu.setAttribute('aria-expanded', String(configMenuOpen));
  260. }
  261. if (configMenu) {
  262. configMenu.hidden = !configMenuOpen;
  263. }
  264. if (btnExportSettings) {
  265. btnExportSettings.disabled = disabled;
  266. }
  267. if (btnImportSettings) {
  268. btnImportSettings.disabled = importLocked;
  269. }
  270. }
  271. function closeConfigMenu() {
  272. configMenuOpen = false;
  273. updateConfigMenuControls();
  274. }
  275. function openConfigMenu() {
  276. configMenuOpen = true;
  277. updateConfigMenuControls();
  278. }
  279. function toggleConfigMenu() {
  280. configMenuOpen ? closeConfigMenu() : openConfigMenu();
  281. }
  282. async function waitForSettingsSaveIdle() {
  283. while (settingsSaveInFlight) {
  284. await new Promise((resolve) => setTimeout(resolve, 50));
  285. }
  286. }
  287. async function flushPendingSettingsBeforeExport() {
  288. clearTimeout(settingsAutoSaveTimer);
  289. await waitForSettingsSaveIdle();
  290. if (settingsDirty) {
  291. await saveSettings({ silent: true });
  292. }
  293. }
  294. async function settlePendingSettingsBeforeImport() {
  295. clearTimeout(settingsAutoSaveTimer);
  296. await waitForSettingsSaveIdle();
  297. }
  298. function downloadTextFile(content, fileName, mimeType = 'application/json;charset=utf-8') {
  299. const blob = new Blob([content], { type: mimeType });
  300. const objectUrl = URL.createObjectURL(blob);
  301. const anchor = document.createElement('a');
  302. anchor.href = objectUrl;
  303. anchor.download = fileName;
  304. document.body.appendChild(anchor);
  305. anchor.click();
  306. anchor.remove();
  307. setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
  308. }
  309. function isDoneStatus(status) {
  310. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  311. }
  312. function getStepStatuses(state = latestState) {
  313. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  314. }
  315. function getFirstUnfinishedStep(state = latestState) {
  316. const statuses = getStepStatuses(state);
  317. for (let step = 1; step <= 9; step++) {
  318. if (!isDoneStatus(statuses[step])) {
  319. return step;
  320. }
  321. }
  322. return null;
  323. }
  324. function getRunningSteps(state = latestState) {
  325. const statuses = getStepStatuses(state);
  326. return Object.entries(statuses)
  327. .filter(([, status]) => status === 'running')
  328. .map(([step]) => Number(step))
  329. .sort((a, b) => a - b);
  330. }
  331. function hasSavedProgress(state = latestState) {
  332. const statuses = getStepStatuses(state);
  333. return Object.values(statuses).some((status) => status !== 'pending');
  334. }
  335. function shouldOfferAutoModeChoice(state = latestState) {
  336. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  337. }
  338. function syncLatestState(nextState) {
  339. const mergedStepStatuses = nextState?.stepStatuses
  340. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  341. : getStepStatuses(latestState);
  342. latestState = {
  343. ...(latestState || {}),
  344. ...(nextState || {}),
  345. stepStatuses: mergedStepStatuses,
  346. };
  347. }
  348. function syncAutoRunState(source = {}) {
  349. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  350. const autoRunning = source.autoRunning !== undefined
  351. ? Boolean(source.autoRunning)
  352. : (source.autoRunPhase !== undefined || source.phase !== undefined
  353. ? ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(phase)
  354. : currentAutoRun.autoRunning);
  355. currentAutoRun = {
  356. autoRunning,
  357. phase,
  358. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  359. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  360. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  361. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  362. };
  363. }
  364. function isAutoRunLockedPhase() {
  365. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'waiting_step' || currentAutoRun.phase === 'retrying';
  366. }
  367. function isAutoRunPausedPhase() {
  368. return currentAutoRun.phase === 'waiting_email';
  369. }
  370. function isAutoRunWaitingStepPhase() {
  371. return currentAutoRun.phase === 'waiting_step';
  372. }
  373. function isAutoRunScheduledPhase() {
  374. return currentAutoRun.phase === 'scheduled';
  375. }
  376. function getAutoRunLabel(payload = currentAutoRun) {
  377. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  378. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  379. }
  380. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  381. if ((payload.totalRuns || 1) > 1) {
  382. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  383. }
  384. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  385. }
  386. function normalizeAutoDelayMinutes(value) {
  387. const numeric = Number(value);
  388. if (!Number.isFinite(numeric)) {
  389. return AUTO_DELAY_DEFAULT_MINUTES;
  390. }
  391. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  392. }
  393. function updateAutoDelayInputState() {
  394. const scheduled = isAutoRunScheduledPhase();
  395. inputAutoDelayEnabled.disabled = scheduled;
  396. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  397. }
  398. function formatCountdown(remainingMs) {
  399. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  400. const hours = Math.floor(totalSeconds / 3600);
  401. const minutes = Math.floor((totalSeconds % 3600) / 60);
  402. const seconds = totalSeconds % 60;
  403. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  404. }
  405. function formatScheduleTime(timestamp) {
  406. return new Date(timestamp).toLocaleString('zh-CN', {
  407. hour12: false,
  408. month: '2-digit',
  409. day: '2-digit',
  410. hour: '2-digit',
  411. minute: '2-digit',
  412. second: '2-digit',
  413. });
  414. }
  415. function stopScheduledCountdownTicker() {
  416. clearInterval(scheduledCountdownTimer);
  417. scheduledCountdownTimer = null;
  418. }
  419. function renderScheduledAutoRunInfo() {
  420. if (!autoScheduleBar) {
  421. return;
  422. }
  423. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  424. autoScheduleBar.style.display = 'none';
  425. return;
  426. }
  427. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  428. autoScheduleBar.style.display = 'flex';
  429. autoScheduleTitle.textContent = '已计划自动运行';
  430. autoScheduleMeta.textContent = remainingMs > 0
  431. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  432. : '倒计时即将结束,正在准备启动...';
  433. }
  434. function syncScheduledCountdownTicker() {
  435. renderScheduledAutoRunInfo();
  436. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  437. stopScheduledCountdownTicker();
  438. return;
  439. }
  440. if (scheduledCountdownTimer) {
  441. return;
  442. }
  443. scheduledCountdownTimer = setInterval(() => {
  444. renderScheduledAutoRunInfo();
  445. updateStatusDisplay(latestState);
  446. }, 1000);
  447. }
  448. function setDefaultAutoRunButton() {
  449. btnAutoRun.disabled = false;
  450. inputRunCount.disabled = false;
  451. 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> 自动';
  452. }
  453. function normalizeCloudflareDomainValue(value = '') {
  454. let normalized = String(value || '').trim().toLowerCase();
  455. if (!normalized) return '';
  456. normalized = normalized.replace(/^@+/, '');
  457. normalized = normalized.replace(/^https?:\/\//, '');
  458. normalized = normalized.replace(/\/.*$/, '');
  459. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  460. return '';
  461. }
  462. return normalized;
  463. }
  464. function normalizeCloudflareDomains(values = []) {
  465. const seen = new Set();
  466. const domains = [];
  467. for (const value of Array.isArray(values) ? values : []) {
  468. const normalized = normalizeCloudflareDomainValue(value);
  469. if (!normalized || seen.has(normalized)) continue;
  470. seen.add(normalized);
  471. domains.push(normalized);
  472. }
  473. return domains;
  474. }
  475. function getCloudflareDomainsFromState() {
  476. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  477. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  478. if (activeDomain && !domains.includes(activeDomain)) {
  479. domains.unshift(activeDomain);
  480. }
  481. return { domains, activeDomain: activeDomain || domains[0] || '' };
  482. }
  483. function renderCloudflareDomainOptions(preferredDomain = '') {
  484. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  485. const { domains, activeDomain } = getCloudflareDomainsFromState();
  486. const selected = preferred || activeDomain;
  487. selectCfDomain.innerHTML = '';
  488. if (domains.length === 0) {
  489. const option = document.createElement('option');
  490. option.value = '';
  491. option.textContent = '请先添加域名';
  492. selectCfDomain.appendChild(option);
  493. selectCfDomain.disabled = true;
  494. selectCfDomain.value = '';
  495. return;
  496. }
  497. for (const domain of domains) {
  498. const option = document.createElement('option');
  499. option.value = domain;
  500. option.textContent = domain;
  501. selectCfDomain.appendChild(option);
  502. }
  503. selectCfDomain.disabled = false;
  504. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  505. }
  506. function setCloudflareDomainEditMode(editing, options = {}) {
  507. const { clearInput = false } = options;
  508. cloudflareDomainEditMode = Boolean(editing);
  509. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  510. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  511. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  512. if (cloudflareDomainEditMode) {
  513. if (clearInput) {
  514. inputCfDomain.value = '';
  515. }
  516. inputCfDomain.focus();
  517. } else if (clearInput) {
  518. inputCfDomain.value = '';
  519. }
  520. }
  521. function collectSettingsPayload() {
  522. const { domains, activeDomain } = getCloudflareDomainsFromState();
  523. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  524. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  525. ) || activeDomain;
  526. return {
  527. panelMode: selectPanelMode.value,
  528. vpsUrl: inputVpsUrl.value.trim(),
  529. vpsPassword: inputVpsPassword.value,
  530. localCpaStep9Mode: getSelectedLocalCpaStep9Mode(),
  531. sub2apiUrl: inputSub2ApiUrl.value.trim(),
  532. sub2apiEmail: inputSub2ApiEmail.value.trim(),
  533. sub2apiPassword: inputSub2ApiPassword.value,
  534. sub2apiGroupName: inputSub2ApiGroup.value.trim(),
  535. customPassword: inputPassword.value,
  536. mailProvider: selectMailProvider.value,
  537. emailGenerator: selectEmailGenerator.value,
  538. emailPrefix: inputEmailPrefix.value.trim(),
  539. inbucketHost: inputInbucketHost.value.trim(),
  540. inbucketMailbox: inputInbucketMailbox.value.trim(),
  541. cloudflareDomain: selectedCloudflareDomain,
  542. cloudflareDomains: domains,
  543. autoRunSkipFailures: inputAutoSkipFailures.checked,
  544. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  545. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  546. };
  547. }
  548. function normalizeLocalCpaStep9Mode(value = '') {
  549. return String(value || '').trim().toLowerCase() === 'bypass'
  550. ? 'bypass'
  551. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  552. }
  553. function getSelectedLocalCpaStep9Mode() {
  554. const activeButton = localCpaStep9ModeButtons.find((button) => button.classList.contains('is-active'));
  555. return normalizeLocalCpaStep9Mode(activeButton?.dataset.localCpaStep9Mode);
  556. }
  557. function setLocalCpaStep9Mode(mode) {
  558. const resolvedMode = normalizeLocalCpaStep9Mode(mode);
  559. localCpaStep9ModeButtons.forEach((button) => {
  560. const active = button.dataset.localCpaStep9Mode === resolvedMode;
  561. button.classList.toggle('is-active', active);
  562. button.setAttribute('aria-pressed', String(active));
  563. });
  564. }
  565. function setSettingsCardLocked(locked) {
  566. if (!settingsCard) {
  567. return;
  568. }
  569. settingsCard.classList.toggle('is-locked', locked);
  570. settingsCard.toggleAttribute('inert', locked);
  571. }
  572. async function setRuntimeEmailState(email) {
  573. const normalizedEmail = String(email || '').trim() || null;
  574. const response = await chrome.runtime.sendMessage({
  575. type: 'SET_EMAIL_STATE',
  576. source: 'sidepanel',
  577. payload: { email: normalizedEmail },
  578. });
  579. if (response?.error) {
  580. throw new Error(response.error);
  581. }
  582. return normalizedEmail;
  583. }
  584. async function clearRegistrationEmail(options = {}) {
  585. const { silent = false } = options;
  586. if (!inputEmail.value.trim() && !latestState?.email) {
  587. return;
  588. }
  589. inputEmail.value = '';
  590. syncLatestState({ email: null });
  591. try {
  592. await setRuntimeEmailState(null);
  593. } catch (err) {
  594. if (!silent) {
  595. showToast(`清空邮箱失败:${err.message}`, 'error');
  596. }
  597. throw err;
  598. }
  599. }
  600. function markSettingsDirty(isDirty = true) {
  601. settingsDirty = isDirty;
  602. updateSaveButtonState();
  603. }
  604. function updateSaveButtonState() {
  605. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  606. updateConfigMenuControls();
  607. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  608. }
  609. function scheduleSettingsAutoSave() {
  610. clearTimeout(settingsAutoSaveTimer);
  611. settingsAutoSaveTimer = setTimeout(() => {
  612. saveSettings({ silent: true }).catch(() => { });
  613. }, 500);
  614. }
  615. async function saveSettings(options = {}) {
  616. const { silent = false } = options;
  617. clearTimeout(settingsAutoSaveTimer);
  618. if (!settingsDirty && !settingsSaveInFlight && silent) {
  619. return;
  620. }
  621. const payload = collectSettingsPayload();
  622. settingsSaveInFlight = true;
  623. updateSaveButtonState();
  624. try {
  625. const response = await chrome.runtime.sendMessage({
  626. type: 'SAVE_SETTING',
  627. source: 'sidepanel',
  628. payload,
  629. });
  630. if (response?.error) {
  631. throw new Error(response.error);
  632. }
  633. syncLatestState(payload);
  634. markSettingsDirty(false);
  635. updatePanelModeUI();
  636. updateMailProviderUI();
  637. updateButtonStates();
  638. if (!silent) {
  639. showToast('配置已保存', 'success', 1800);
  640. }
  641. } catch (err) {
  642. markSettingsDirty(true);
  643. if (!silent) {
  644. showToast(`保存失败:${err.message}`, 'error');
  645. }
  646. throw err;
  647. } finally {
  648. settingsSaveInFlight = false;
  649. updateSaveButtonState();
  650. }
  651. }
  652. function applyAutoRunStatus(payload = currentAutoRun) {
  653. syncAutoRunState(payload);
  654. const runLabel = getAutoRunLabel(currentAutoRun);
  655. const locked = isAutoRunLockedPhase();
  656. const paused = isAutoRunPausedPhase();
  657. const scheduled = isAutoRunScheduledPhase();
  658. const settingsCardLocked = scheduled || locked;
  659. setSettingsCardLocked(settingsCardLocked);
  660. inputRunCount.disabled = currentAutoRun.autoRunning;
  661. btnAutoRun.disabled = currentAutoRun.autoRunning;
  662. btnFetchEmail.disabled = locked || usesGeneratedAliasMailProvider(selectMailProvider.value);
  663. inputEmail.disabled = locked;
  664. inputAutoSkipFailures.disabled = scheduled;
  665. if (currentAutoRun.totalRuns > 0) {
  666. inputRunCount.value = String(currentAutoRun.totalRuns);
  667. }
  668. switch (currentAutoRun.phase) {
  669. case 'scheduled':
  670. autoContinueBar.style.display = 'none';
  671. btnAutoRun.innerHTML = `已计划${runLabel}`;
  672. break;
  673. case 'waiting_step':
  674. autoContinueBar.style.display = 'none';
  675. btnAutoRun.innerHTML = `等待中${runLabel}`;
  676. break;
  677. case 'waiting_email':
  678. autoContinueBar.style.display = 'flex';
  679. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  680. break;
  681. case 'running':
  682. autoContinueBar.style.display = 'none';
  683. btnAutoRun.innerHTML = `运行中${runLabel}`;
  684. break;
  685. case 'retrying':
  686. autoContinueBar.style.display = 'none';
  687. btnAutoRun.innerHTML = `重试中${runLabel}`;
  688. break;
  689. default:
  690. autoContinueBar.style.display = 'none';
  691. setDefaultAutoRunButton();
  692. inputEmail.disabled = false;
  693. if (!locked) {
  694. btnFetchEmail.disabled = usesGeneratedAliasMailProvider(selectMailProvider.value);
  695. }
  696. break;
  697. }
  698. updateAutoDelayInputState();
  699. syncScheduledCountdownTicker();
  700. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  701. updateConfigMenuControls();
  702. }
  703. function initializeManualStepActions() {
  704. document.querySelectorAll('.step-row').forEach((row) => {
  705. const step = Number(row.dataset.step);
  706. const statusEl = row.querySelector('.step-status');
  707. if (!statusEl) return;
  708. const actions = document.createElement('div');
  709. actions.className = 'step-actions';
  710. const manualBtn = document.createElement('button');
  711. manualBtn.type = 'button';
  712. manualBtn.className = 'step-manual-btn';
  713. manualBtn.dataset.step = String(step);
  714. manualBtn.title = '跳过此步';
  715. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  716. 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>';
  717. manualBtn.addEventListener('click', async (event) => {
  718. event.stopPropagation();
  719. try {
  720. await handleSkipStep(step);
  721. } catch (err) {
  722. showToast(err.message, 'error');
  723. }
  724. });
  725. statusEl.parentNode.replaceChild(actions, statusEl);
  726. actions.appendChild(manualBtn);
  727. actions.appendChild(statusEl);
  728. });
  729. }
  730. // ============================================================
  731. // State Restore on load
  732. // ============================================================
  733. function applySettingsState(state) {
  734. syncLatestState(state);
  735. syncAutoRunState(state);
  736. inputEmail.value = state?.email || '';
  737. syncPasswordField(state || {});
  738. inputVpsUrl.value = state?.vpsUrl || '';
  739. inputVpsPassword.value = state?.vpsPassword || '';
  740. setLocalCpaStep9Mode(state?.localCpaStep9Mode);
  741. selectPanelMode.value = state?.panelMode || 'cpa';
  742. inputSub2ApiUrl.value = state?.sub2apiUrl || '';
  743. inputSub2ApiEmail.value = state?.sub2apiEmail || '';
  744. inputSub2ApiPassword.value = state?.sub2apiPassword || '';
  745. inputSub2ApiGroup.value = state?.sub2apiGroupName || '';
  746. selectMailProvider.value = state?.mailProvider || '163';
  747. selectEmailGenerator.value = state?.emailGenerator || 'duck';
  748. inputEmailPrefix.value = state?.emailPrefix || '';
  749. inputInbucketHost.value = state?.inbucketHost || '';
  750. inputInbucketMailbox.value = state?.inbucketMailbox || '';
  751. renderCloudflareDomainOptions(state?.cloudflareDomain || '');
  752. setCloudflareDomainEditMode(false, { clearInput: true });
  753. inputAutoSkipFailures.checked = Boolean(state?.autoRunSkipFailures);
  754. inputAutoDelayEnabled.checked = Boolean(state?.autoRunDelayEnabled);
  755. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state?.autoRunDelayMinutes));
  756. if (state?.autoRunTotalRuns) {
  757. inputRunCount.value = String(state.autoRunTotalRuns);
  758. }
  759. applyAutoRunStatus(state);
  760. markSettingsDirty(false);
  761. updateAutoDelayInputState();
  762. updatePanelModeUI();
  763. updateMailProviderUI();
  764. updateButtonStates();
  765. }
  766. async function restoreState() {
  767. try {
  768. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  769. applySettingsState(state);
  770. if (state.oauthUrl) {
  771. displayOauthUrl.textContent = state.oauthUrl;
  772. displayOauthUrl.classList.add('has-value');
  773. }
  774. if (state.localhostUrl) {
  775. displayLocalhostUrl.textContent = state.localhostUrl;
  776. displayLocalhostUrl.classList.add('has-value');
  777. }
  778. if (state.stepStatuses) {
  779. for (const [step, status] of Object.entries(state.stepStatuses)) {
  780. updateStepUI(Number(step), status);
  781. }
  782. }
  783. if (state.logs) {
  784. for (const entry of state.logs) {
  785. appendLog(entry);
  786. }
  787. }
  788. updateStatusDisplay(latestState);
  789. updateProgressCounter();
  790. } catch (err) {
  791. console.error('Failed to restore state:', err);
  792. }
  793. }
  794. function syncPasswordField(state) {
  795. inputPassword.value = state.customPassword || state.password || '';
  796. }
  797. function getSelectedEmailGenerator() {
  798. return selectEmailGenerator.value === 'cloudflare' ? 'cloudflare' : 'duck';
  799. }
  800. function getEmailGeneratorUiCopy() {
  801. if (getSelectedEmailGenerator() === 'cloudflare') {
  802. return {
  803. buttonLabel: '生成 Cloudflare',
  804. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  805. successVerb: '生成',
  806. label: 'Cloudflare 邮箱',
  807. };
  808. }
  809. return {
  810. buttonLabel: '获取 Duck',
  811. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  812. successVerb: '获取',
  813. label: 'Duck 邮箱',
  814. };
  815. }
  816. function getHotmailAccounts(state = latestState) {
  817. return Array.isArray(state?.hotmailAccounts) ? state.hotmailAccounts : [];
  818. }
  819. function getCurrentHotmailAccount(state = latestState) {
  820. const currentId = state?.currentHotmailAccountId;
  821. return getHotmailAccounts(state).find((account) => account.id === currentId) || null;
  822. }
  823. function getHotmailAccountsByUsage(mode = 'all', state = latestState) {
  824. const accounts = getHotmailAccounts(state);
  825. if (typeof filterHotmailAccountsByUsage === 'function') {
  826. return filterHotmailAccountsByUsage(accounts, mode);
  827. }
  828. if (mode === 'used') {
  829. return accounts.filter((account) => Boolean(account?.used));
  830. }
  831. return accounts.slice();
  832. }
  833. function getHotmailBulkActionText(mode, count) {
  834. if (typeof getHotmailBulkActionLabel === 'function') {
  835. return getHotmailBulkActionLabel(mode, count);
  836. }
  837. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  838. const prefix = mode === 'used' ? '清空已用' : '全部删除';
  839. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  840. return `${prefix}${suffix}`;
  841. }
  842. function getHotmailListToggleText(expanded, count) {
  843. if (typeof getHotmailListToggleLabel === 'function') {
  844. return getHotmailListToggleLabel(expanded, count);
  845. }
  846. const normalizedCount = Number.isFinite(Number(count)) ? Math.max(0, Number(count)) : 0;
  847. const suffix = normalizedCount > 0 ? `(${normalizedCount})` : '';
  848. return `${expanded ? '收起列表' : '展开列表'}${suffix}`;
  849. }
  850. function updateHotmailListViewport() {
  851. const count = getHotmailAccounts().length;
  852. const usedCount = getHotmailAccountsByUsage('used').length;
  853. if (btnClearUsedHotmailAccounts) {
  854. btnClearUsedHotmailAccounts.textContent = getHotmailBulkActionText('used', usedCount);
  855. btnClearUsedHotmailAccounts.disabled = usedCount === 0;
  856. }
  857. if (btnDeleteAllHotmailAccounts) {
  858. btnDeleteAllHotmailAccounts.textContent = getHotmailBulkActionText('all', count);
  859. btnDeleteAllHotmailAccounts.disabled = count === 0;
  860. }
  861. if (btnToggleHotmailList) {
  862. btnToggleHotmailList.textContent = getHotmailListToggleText(hotmailListExpanded, count);
  863. btnToggleHotmailList.setAttribute('aria-expanded', String(hotmailListExpanded));
  864. btnToggleHotmailList.disabled = count === 0;
  865. }
  866. if (hotmailListShell) {
  867. hotmailListShell.classList.toggle('is-expanded', hotmailListExpanded);
  868. hotmailListShell.classList.toggle('is-collapsed', !hotmailListExpanded);
  869. }
  870. }
  871. function setHotmailListExpanded(expanded, options = {}) {
  872. const { persist = true } = options;
  873. hotmailListExpanded = Boolean(expanded);
  874. updateHotmailListViewport();
  875. if (persist) {
  876. localStorage.setItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY, hotmailListExpanded ? '1' : '0');
  877. }
  878. }
  879. function initHotmailListExpandedState() {
  880. const saved = localStorage.getItem(HOTMAIL_LIST_EXPANDED_STORAGE_KEY);
  881. setHotmailListExpanded(saved === '1', { persist: false });
  882. }
  883. function shouldClearCurrentHotmailSelectionLocally(account) {
  884. if (typeof shouldClearHotmailCurrentSelection === 'function') {
  885. return shouldClearHotmailCurrentSelection(account);
  886. }
  887. return Boolean(account) && account.used === true;
  888. }
  889. function upsertHotmailAccountListLocally(accounts, nextAccount) {
  890. if (typeof upsertHotmailAccountInList === 'function') {
  891. return upsertHotmailAccountInList(accounts, nextAccount);
  892. }
  893. const list = Array.isArray(accounts) ? accounts.slice() : [];
  894. if (!nextAccount?.id) return list;
  895. const existingIndex = list.findIndex((account) => account?.id === nextAccount.id);
  896. if (existingIndex === -1) {
  897. list.push(nextAccount);
  898. return list;
  899. }
  900. list[existingIndex] = nextAccount;
  901. return list;
  902. }
  903. function refreshHotmailSelectionUI() {
  904. renderHotmailAccounts();
  905. if (selectMailProvider.value === 'hotmail-api') {
  906. const currentAccount = getCurrentHotmailAccount();
  907. inputEmail.value = currentAccount?.email || latestState?.email || '';
  908. }
  909. }
  910. function applyHotmailAccountMutation(account, options = {}) {
  911. if (!account?.id) return;
  912. const { preserveCurrentSelection = false } = options;
  913. const nextState = {
  914. hotmailAccounts: upsertHotmailAccountListLocally(getHotmailAccounts(), account),
  915. };
  916. if (!preserveCurrentSelection
  917. && latestState?.currentHotmailAccountId === account.id
  918. && shouldClearCurrentHotmailSelectionLocally(account)) {
  919. nextState.currentHotmailAccountId = null;
  920. if (selectMailProvider.value === 'hotmail-api') {
  921. nextState.email = null;
  922. }
  923. }
  924. syncLatestState(nextState);
  925. refreshHotmailSelectionUI();
  926. }
  927. function formatDateTime(timestamp) {
  928. const value = Number(timestamp);
  929. if (!Number.isFinite(value) || value <= 0) {
  930. return '未使用';
  931. }
  932. return new Date(value).toLocaleString('zh-CN', { hour12: false });
  933. }
  934. function getHotmailAvailabilityLabel(account) {
  935. if (account.used) return '已用';
  936. return '可分配';
  937. }
  938. function getHotmailStatusLabel(account) {
  939. if (account.used) return '已用';
  940. switch (account.status) {
  941. case 'authorized':
  942. return '可用';
  943. case 'error':
  944. return '异常';
  945. default:
  946. return '待校验';
  947. }
  948. }
  949. function getHotmailStatusClass(account) {
  950. if (account.used) return 'status-used';
  951. return `status-${account.status || 'pending'}`;
  952. }
  953. function clearHotmailForm() {
  954. inputHotmailEmail.value = '';
  955. inputHotmailClientId.value = '';
  956. inputHotmailPassword.value = '';
  957. inputHotmailRefreshToken.value = '';
  958. }
  959. function renderHotmailAccounts() {
  960. if (!hotmailAccountsList) return;
  961. const accounts = getHotmailAccounts();
  962. const currentId = latestState?.currentHotmailAccountId || '';
  963. if (!accounts.length) {
  964. hotmailAccountsList.innerHTML = '<div class="hotmail-empty">还没有 Hotmail 账号,先添加一条再校验。</div>';
  965. updateHotmailListViewport();
  966. return;
  967. }
  968. hotmailAccountsList.innerHTML = accounts.map((account) => `
  969. <div class="hotmail-account-item${account.id === currentId ? ' is-current' : ''}">
  970. <div class="hotmail-account-top">
  971. <div class="hotmail-account-title-row">
  972. <div class="hotmail-account-email">${escapeHtml(account.email || '(未命名账号)')}</div>
  973. <button
  974. class="hotmail-copy-btn"
  975. type="button"
  976. data-account-action="copy-email"
  977. data-account-id="${escapeHtml(account.id)}"
  978. title="复制邮箱"
  979. aria-label="复制邮箱 ${escapeHtml(account.email || '')}"
  980. >${COPY_ICON}</button>
  981. </div>
  982. <span class="hotmail-status-chip ${escapeHtml(getHotmailStatusClass(account))}">${escapeHtml(getHotmailStatusLabel(account))}</span>
  983. </div>
  984. <div class="hotmail-account-meta">
  985. <span>客户端 ID:${escapeHtml(account.clientId ? `${account.clientId.slice(0, 10)}...` : '未填写')}</span>
  986. <span>刷新令牌:${account.refreshToken ? '已保存' : '未保存'}</span>
  987. <span>分配状态: ${escapeHtml(getHotmailAvailabilityLabel(account))}</span>
  988. <span>上次校验: ${escapeHtml(formatDateTime(account.lastAuthAt))}</span>
  989. <span>上次使用: ${escapeHtml(formatDateTime(account.lastUsedAt))}</span>
  990. </div>
  991. ${account.lastError ? `<div class="hotmail-account-error">${escapeHtml(account.lastError)}</div>` : ''}
  992. <div class="hotmail-account-actions">
  993. <button class="btn btn-outline btn-sm" type="button" data-account-action="select" data-account-id="${escapeHtml(account.id)}">使用此账号</button>
  994. <button class="btn btn-outline btn-sm" type="button" data-account-action="toggle-used" data-account-id="${escapeHtml(account.id)}">${account.used ? '标记未用' : '标记已用'}</button>
  995. <button class="btn btn-primary btn-sm" type="button" data-account-action="verify" data-account-id="${escapeHtml(account.id)}">校验</button>
  996. <button class="btn btn-outline btn-sm" type="button" data-account-action="test" data-account-id="${escapeHtml(account.id)}">复制最新验证码</button>
  997. <button class="btn btn-ghost btn-sm" type="button" data-account-action="delete" data-account-id="${escapeHtml(account.id)}">删除</button>
  998. </div>
  999. </div>
  1000. `).join('');
  1001. updateHotmailListViewport();
  1002. }
  1003. function updateMailProviderUI() {
  1004. const use2925 = selectMailProvider.value === '2925';
  1005. const useGeneratedAlias = usesGeneratedAliasMailProvider(selectMailProvider.value);
  1006. const useInbucket = selectMailProvider.value === 'inbucket';
  1007. const useHotmail = selectMailProvider.value === 'hotmail-api';
  1008. rowEmailPrefix.style.display = useGeneratedAlias ? '' : 'none';
  1009. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  1010. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  1011. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  1012. rowCfDomain.style.display = !useHotmail && !useGeneratedAlias && useCloudflare ? '' : 'none';
  1013. const { domains } = getCloudflareDomainsFromState();
  1014. if (!useHotmail && !useGeneratedAlias && useCloudflare) {
  1015. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  1016. } else {
  1017. setCloudflareDomainEditMode(false, { clearInput: false });
  1018. }
  1019. if (hotmailSection) {
  1020. hotmailSection.style.display = useHotmail ? '' : 'none';
  1021. }
  1022. labelEmailPrefix.textContent = '邮箱前缀';
  1023. inputEmailPrefix.placeholder = '例如 abc';
  1024. selectEmailGenerator.disabled = useHotmail || useGeneratedAlias;
  1025. btnFetchEmail.hidden = useHotmail;
  1026. inputEmail.readOnly = useHotmail || useGeneratedAlias;
  1027. const uiCopy = getEmailGeneratorUiCopy();
  1028. inputEmail.placeholder = useHotmail
  1029. ? '由 Hotmail 账号池自动分配'
  1030. : (use2925 ? '步骤 3 自动生成 2925 邮箱并回填' : uiCopy.placeholder);
  1031. btnFetchEmail.disabled = useGeneratedAlias || isAutoRunLockedPhase();
  1032. if (!btnFetchEmail.disabled) {
  1033. btnFetchEmail.textContent = uiCopy.buttonLabel;
  1034. }
  1035. if (autoHintText) {
  1036. autoHintText.textContent = useHotmail
  1037. ? '请先校验并选择一个 Hotmail 账号'
  1038. : (useGeneratedAlias ? '步骤 3 会自动生成邮箱,无需手动获取' : '先自动获取邮箱,或手动粘贴邮箱后再继续');
  1039. }
  1040. if (useHotmail) {
  1041. const currentAccount = getCurrentHotmailAccount();
  1042. inputEmail.value = currentAccount?.email || latestState?.email || '';
  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 if (usesGeneratedAliasMailProvider(selectMailProvider.value)) {
  1495. const emailPrefix = inputEmailPrefix.value.trim();
  1496. if (!emailPrefix) {
  1497. showToast('请先填写 2925 邮箱前缀。', 'warn');
  1498. return;
  1499. }
  1500. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, emailPrefix } });
  1501. if (response?.error) {
  1502. throw new Error(response.error);
  1503. }
  1504. } else {
  1505. let email = inputEmail.value.trim();
  1506. if (!email) {
  1507. try {
  1508. email = await fetchGeneratedEmail({ showFailureToast: false });
  1509. } catch (err) {
  1510. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  1511. return;
  1512. }
  1513. }
  1514. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  1515. if (response?.error) {
  1516. throw new Error(response.error);
  1517. }
  1518. }
  1519. } else {
  1520. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  1521. if (response?.error) {
  1522. throw new Error(response.error);
  1523. }
  1524. }
  1525. } catch (err) {
  1526. showToast(err.message, 'error');
  1527. }
  1528. });
  1529. });
  1530. btnFetchEmail.addEventListener('click', async () => {
  1531. if (selectMailProvider.value === 'hotmail-api') {
  1532. return;
  1533. }
  1534. await fetchGeneratedEmail().catch(() => { });
  1535. });
  1536. btnToggleHotmailList?.addEventListener('click', () => {
  1537. setHotmailListExpanded(!hotmailListExpanded);
  1538. });
  1539. btnClearUsedHotmailAccounts?.addEventListener('click', async () => {
  1540. if (hotmailActionInFlight) return;
  1541. hotmailActionInFlight = true;
  1542. btnClearUsedHotmailAccounts.disabled = true;
  1543. try {
  1544. await deleteHotmailAccountsByMode('used');
  1545. } catch (err) {
  1546. showToast(err.message, 'error');
  1547. } finally {
  1548. hotmailActionInFlight = false;
  1549. updateHotmailListViewport();
  1550. }
  1551. });
  1552. btnDeleteAllHotmailAccounts?.addEventListener('click', async () => {
  1553. if (hotmailActionInFlight) return;
  1554. hotmailActionInFlight = true;
  1555. btnDeleteAllHotmailAccounts.disabled = true;
  1556. try {
  1557. await deleteHotmailAccountsByMode('all');
  1558. } catch (err) {
  1559. showToast(err.message, 'error');
  1560. } finally {
  1561. hotmailActionInFlight = false;
  1562. updateHotmailListViewport();
  1563. }
  1564. });
  1565. btnAddHotmailAccount?.addEventListener('click', async () => {
  1566. if (hotmailActionInFlight) return;
  1567. const email = inputHotmailEmail.value.trim();
  1568. const clientId = inputHotmailClientId.value.trim();
  1569. const refreshToken = inputHotmailRefreshToken.value.trim();
  1570. if (!email) {
  1571. showToast('请先填写 Hotmail 邮箱。', 'warn');
  1572. return;
  1573. }
  1574. if (!clientId) {
  1575. showToast('请先填写微软应用客户端 ID。', 'warn');
  1576. return;
  1577. }
  1578. if (!refreshToken) {
  1579. showToast('请先填写刷新令牌(refresh token)。', 'warn');
  1580. return;
  1581. }
  1582. hotmailActionInFlight = true;
  1583. btnAddHotmailAccount.disabled = true;
  1584. try {
  1585. const response = await chrome.runtime.sendMessage({
  1586. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1587. source: 'sidepanel',
  1588. payload: {
  1589. email,
  1590. clientId,
  1591. password: inputHotmailPassword.value,
  1592. refreshToken,
  1593. },
  1594. });
  1595. if (response?.error) {
  1596. throw new Error(response.error);
  1597. }
  1598. showToast(`已保存 Hotmail 账号 ${email}`, 'success', 1800);
  1599. clearHotmailForm();
  1600. } catch (err) {
  1601. showToast(`保存 Hotmail 账号失败:${err.message}`, 'error');
  1602. } finally {
  1603. hotmailActionInFlight = false;
  1604. btnAddHotmailAccount.disabled = false;
  1605. }
  1606. });
  1607. btnImportHotmailAccounts?.addEventListener('click', async () => {
  1608. if (hotmailActionInFlight) return;
  1609. if (typeof parseHotmailImportText !== 'function') {
  1610. showToast('导入解析器未加载,请刷新扩展后重试。', 'error');
  1611. return;
  1612. }
  1613. const rawText = inputHotmailImport.value.trim();
  1614. if (!rawText) {
  1615. showToast('请先粘贴账号导入内容。', 'warn');
  1616. return;
  1617. }
  1618. const parsedAccounts = parseHotmailImportText(rawText);
  1619. if (!parsedAccounts.length) {
  1620. showToast('没有解析到有效账号,请检查格式是否为 账号----密码----ID----Token。', 'error');
  1621. return;
  1622. }
  1623. hotmailActionInFlight = true;
  1624. btnImportHotmailAccounts.disabled = true;
  1625. try {
  1626. for (const account of parsedAccounts) {
  1627. const response = await chrome.runtime.sendMessage({
  1628. type: 'UPSERT_HOTMAIL_ACCOUNT',
  1629. source: 'sidepanel',
  1630. payload: account,
  1631. });
  1632. if (response?.error) {
  1633. throw new Error(response.error);
  1634. }
  1635. }
  1636. inputHotmailImport.value = '';
  1637. showToast(`已导入 ${parsedAccounts.length} 条 Hotmail 账号`, 'success', 2200);
  1638. } catch (err) {
  1639. showToast(`批量导入失败:${err.message}`, 'error');
  1640. } finally {
  1641. hotmailActionInFlight = false;
  1642. btnImportHotmailAccounts.disabled = false;
  1643. }
  1644. });
  1645. hotmailAccountsList?.addEventListener('click', async (event) => {
  1646. const actionButton = event.target.closest('[data-account-action]');
  1647. if (!actionButton || hotmailActionInFlight) {
  1648. return;
  1649. }
  1650. const accountId = actionButton.dataset.accountId;
  1651. const action = actionButton.dataset.accountAction;
  1652. if (!accountId || !action) {
  1653. return;
  1654. }
  1655. const targetAccount = getHotmailAccounts().find((account) => account.id === accountId) || null;
  1656. hotmailActionInFlight = true;
  1657. actionButton.disabled = true;
  1658. try {
  1659. if (action === 'copy-email') {
  1660. if (!targetAccount?.email) throw new Error('未找到可复制的邮箱地址。');
  1661. await copyTextToClipboard(targetAccount.email);
  1662. showToast(`已复制 ${targetAccount.email}`, 'success', 1800);
  1663. } else if (action === 'select') {
  1664. const response = await chrome.runtime.sendMessage({
  1665. type: 'SELECT_HOTMAIL_ACCOUNT',
  1666. source: 'sidepanel',
  1667. payload: { accountId },
  1668. });
  1669. if (response?.error) throw new Error(response.error);
  1670. syncLatestState({ currentHotmailAccountId: response.account.id });
  1671. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1672. showToast(`已切换当前 Hotmail 账号为 ${response.account.email}`, 'success', 1800);
  1673. } else if (action === 'toggle-used') {
  1674. if (!targetAccount) throw new Error('未找到目标 Hotmail 账号。');
  1675. const response = await chrome.runtime.sendMessage({
  1676. type: 'PATCH_HOTMAIL_ACCOUNT',
  1677. source: 'sidepanel',
  1678. payload: {
  1679. accountId,
  1680. updates: { used: !targetAccount.used },
  1681. },
  1682. });
  1683. if (response?.error) throw new Error(response.error);
  1684. applyHotmailAccountMutation(response.account);
  1685. showToast(`账号 ${response.account.email} 已${response.account.used ? '标记为已用' : '恢复为未用'}`, 'success', 2200);
  1686. } else if (action === 'verify') {
  1687. const response = await chrome.runtime.sendMessage({
  1688. type: 'VERIFY_HOTMAIL_ACCOUNT',
  1689. source: 'sidepanel',
  1690. payload: { accountId },
  1691. });
  1692. if (response?.error) throw new Error(response.error);
  1693. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1694. showToast(`账号 ${response.account.email} 校验通过`, 'success', 2200);
  1695. } else if (action === 'test') {
  1696. const response = await chrome.runtime.sendMessage({
  1697. type: 'TEST_HOTMAIL_ACCOUNT',
  1698. source: 'sidepanel',
  1699. payload: { accountId },
  1700. });
  1701. if (response?.error) throw new Error(response.error);
  1702. applyHotmailAccountMutation(response.account, { preserveCurrentSelection: true });
  1703. if (response.latestCode) {
  1704. await copyTextToClipboard(response.latestCode);
  1705. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1706. showToast(`已复制最新验证码 ${response.latestCode}${mailbox}`, 'success', 2600);
  1707. } else if (response.latestSubject) {
  1708. const mailbox = response.latestMailbox ? `(${response.latestMailbox})` : '';
  1709. showToast(`最新邮件${mailbox}没有验证码:${response.latestSubject}`, 'warn', 3200);
  1710. } else {
  1711. showToast('当前没有可读取的最新邮件。', 'warn', 2600);
  1712. }
  1713. } else if (action === 'delete') {
  1714. const confirmed = await openConfirmModal({
  1715. title: '删除账号',
  1716. message: '确认删除这个 Hotmail 账号吗?对应 token 也会一起移除。',
  1717. confirmLabel: '确认删除',
  1718. confirmVariant: 'btn-danger',
  1719. });
  1720. if (!confirmed) {
  1721. return;
  1722. }
  1723. const response = await chrome.runtime.sendMessage({
  1724. type: 'DELETE_HOTMAIL_ACCOUNT',
  1725. source: 'sidepanel',
  1726. payload: { accountId },
  1727. });
  1728. if (response?.error) throw new Error(response.error);
  1729. showToast('Hotmail 账号已删除', 'success', 1800);
  1730. }
  1731. } catch (err) {
  1732. showToast(err.message, 'error');
  1733. } finally {
  1734. hotmailActionInFlight = false;
  1735. actionButton.disabled = false;
  1736. }
  1737. });
  1738. btnTogglePassword.addEventListener('click', () => {
  1739. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  1740. syncPasswordToggleLabel();
  1741. });
  1742. btnToggleVpsUrl.addEventListener('click', () => {
  1743. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  1744. syncVpsUrlToggleLabel();
  1745. });
  1746. btnToggleVpsPassword.addEventListener('click', () => {
  1747. inputVpsPassword.type = inputVpsPassword.type === 'password' ? 'text' : 'password';
  1748. syncVpsPasswordToggleLabel();
  1749. });
  1750. localCpaStep9ModeButtons.forEach((button) => {
  1751. button.addEventListener('click', () => {
  1752. const nextMode = button.dataset.localCpaStep9Mode;
  1753. if (getSelectedLocalCpaStep9Mode() === normalizeLocalCpaStep9Mode(nextMode)) {
  1754. return;
  1755. }
  1756. setLocalCpaStep9Mode(nextMode);
  1757. markSettingsDirty(true);
  1758. saveSettings({ silent: true }).catch(() => { });
  1759. });
  1760. });
  1761. btnSaveSettings.addEventListener('click', async () => {
  1762. if (!settingsDirty) {
  1763. showToast('配置已是最新', 'info', 1400);
  1764. return;
  1765. }
  1766. await saveSettings({ silent: false }).catch(() => { });
  1767. });
  1768. btnStop.addEventListener('click', async () => {
  1769. btnStop.disabled = true;
  1770. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  1771. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  1772. });
  1773. btnConfigMenu?.addEventListener('click', (event) => {
  1774. event.stopPropagation();
  1775. toggleConfigMenu();
  1776. });
  1777. configMenu?.addEventListener('click', (event) => {
  1778. event.stopPropagation();
  1779. });
  1780. btnExportSettings?.addEventListener('click', async () => {
  1781. if (configActionInFlight || settingsSaveInFlight) {
  1782. return;
  1783. }
  1784. await exportSettingsFile();
  1785. });
  1786. btnImportSettings?.addEventListener('click', async () => {
  1787. if (configActionInFlight || settingsSaveInFlight) {
  1788. return;
  1789. }
  1790. closeConfigMenu();
  1791. if (inputImportSettingsFile) {
  1792. inputImportSettingsFile.value = '';
  1793. inputImportSettingsFile.click();
  1794. }
  1795. });
  1796. inputImportSettingsFile?.addEventListener('change', async () => {
  1797. const file = inputImportSettingsFile.files?.[0] || null;
  1798. await importSettingsFromFile(file);
  1799. });
  1800. autoStartModal?.addEventListener('click', (event) => {
  1801. if (event.target === autoStartModal) {
  1802. resolveModalChoice(null);
  1803. }
  1804. });
  1805. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  1806. // Auto Run
  1807. btnAutoRun.addEventListener('click', async () => {
  1808. try {
  1809. const totalRuns = Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  1810. let mode = 'restart';
  1811. if (shouldOfferAutoModeChoice()) {
  1812. const startStep = getFirstUnfinishedStep();
  1813. const runningStep = getRunningSteps()[0] ?? null;
  1814. const choice = await openAutoStartChoiceDialog(startStep, { runningStep });
  1815. if (!choice) {
  1816. return;
  1817. }
  1818. mode = choice;
  1819. }
  1820. btnAutoRun.disabled = true;
  1821. inputRunCount.disabled = true;
  1822. const delayEnabled = inputAutoDelayEnabled.checked;
  1823. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  1824. inputAutoDelayMinutes.value = String(delayMinutes);
  1825. btnAutoRun.innerHTML = delayEnabled
  1826. ? '<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> 计划中...'
  1827. : '<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> 运行中...';
  1828. const response = await chrome.runtime.sendMessage({
  1829. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  1830. source: 'sidepanel',
  1831. payload: {
  1832. totalRuns,
  1833. delayMinutes,
  1834. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1835. mode,
  1836. },
  1837. });
  1838. if (response?.error) {
  1839. throw new Error(response.error);
  1840. }
  1841. } catch (err) {
  1842. setDefaultAutoRunButton();
  1843. inputRunCount.disabled = false;
  1844. showToast(err.message, 'error');
  1845. }
  1846. });
  1847. btnAutoContinue.addEventListener('click', async () => {
  1848. const email = inputEmail.value.trim();
  1849. if (!email) {
  1850. showToast('请先获取或粘贴邮箱。', 'warn');
  1851. return;
  1852. }
  1853. autoContinueBar.style.display = 'none';
  1854. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  1855. });
  1856. btnAutoRunNow?.addEventListener('click', async () => {
  1857. try {
  1858. btnAutoRunNow.disabled = true;
  1859. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  1860. } catch (err) {
  1861. showToast(err.message, 'error');
  1862. } finally {
  1863. btnAutoRunNow.disabled = false;
  1864. }
  1865. });
  1866. btnAutoCancelSchedule?.addEventListener('click', async () => {
  1867. try {
  1868. btnAutoCancelSchedule.disabled = true;
  1869. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  1870. showToast('已取消倒计时计划。', 'info', 1800);
  1871. } catch (err) {
  1872. showToast(err.message, 'error');
  1873. } finally {
  1874. btnAutoCancelSchedule.disabled = false;
  1875. }
  1876. });
  1877. // Reset
  1878. btnReset.addEventListener('click', async () => {
  1879. const confirmed = await openConfirmModal({
  1880. title: '重置流程',
  1881. message: '确认重置全部步骤和数据吗?',
  1882. confirmLabel: '确认重置',
  1883. confirmVariant: 'btn-danger',
  1884. });
  1885. if (!confirmed) {
  1886. return;
  1887. }
  1888. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  1889. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES, currentHotmailAccountId: null, email: null });
  1890. syncAutoRunState({
  1891. autoRunning: false,
  1892. autoRunPhase: 'idle',
  1893. autoRunCurrentRun: 0,
  1894. autoRunTotalRuns: 1,
  1895. autoRunAttemptRun: 0,
  1896. scheduledAutoRunAt: null,
  1897. });
  1898. displayOauthUrl.textContent = '等待中...';
  1899. displayOauthUrl.classList.remove('has-value');
  1900. displayLocalhostUrl.textContent = '等待中...';
  1901. displayLocalhostUrl.classList.remove('has-value');
  1902. inputEmail.value = '';
  1903. displayStatus.textContent = '就绪';
  1904. statusBar.className = 'status-bar';
  1905. logArea.innerHTML = '';
  1906. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1907. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1908. setDefaultAutoRunButton();
  1909. applyAutoRunStatus(currentAutoRun);
  1910. markSettingsDirty(false);
  1911. updateStopButtonState(false);
  1912. updateButtonStates();
  1913. updateProgressCounter();
  1914. renderHotmailAccounts();
  1915. });
  1916. // Clear log
  1917. btnClearLog.addEventListener('click', () => {
  1918. logArea.innerHTML = '';
  1919. });
  1920. // Save settings on change
  1921. inputEmail.addEventListener('change', async () => {
  1922. if (selectMailProvider.value === 'hotmail-api') {
  1923. return;
  1924. }
  1925. const email = inputEmail.value.trim();
  1926. inputEmail.value = email;
  1927. try {
  1928. if (email) {
  1929. const response = await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  1930. if (response?.error) {
  1931. throw new Error(response.error);
  1932. }
  1933. } else {
  1934. await setRuntimeEmailState(null);
  1935. }
  1936. } catch (err) {
  1937. showToast(err.message, 'error');
  1938. }
  1939. });
  1940. inputEmail.addEventListener('input', updateButtonStates);
  1941. inputVpsUrl.addEventListener('input', () => {
  1942. markSettingsDirty(true);
  1943. scheduleSettingsAutoSave();
  1944. });
  1945. inputVpsUrl.addEventListener('blur', () => {
  1946. saveSettings({ silent: true }).catch(() => { });
  1947. });
  1948. inputVpsPassword.addEventListener('input', () => {
  1949. markSettingsDirty(true);
  1950. scheduleSettingsAutoSave();
  1951. });
  1952. inputVpsPassword.addEventListener('blur', () => {
  1953. saveSettings({ silent: true }).catch(() => { });
  1954. });
  1955. inputPassword.addEventListener('input', () => {
  1956. markSettingsDirty(true);
  1957. updateButtonStates();
  1958. scheduleSettingsAutoSave();
  1959. });
  1960. inputPassword.addEventListener('blur', () => {
  1961. saveSettings({ silent: true }).catch(() => { });
  1962. });
  1963. selectMailProvider.addEventListener('change', () => {
  1964. updateMailProviderUI();
  1965. markSettingsDirty(true);
  1966. saveSettings({ silent: true }).catch(() => { });
  1967. });
  1968. selectEmailGenerator.addEventListener('change', () => {
  1969. updateMailProviderUI();
  1970. clearRegistrationEmail({ silent: true }).catch(() => { });
  1971. markSettingsDirty(true);
  1972. saveSettings({ silent: true }).catch(() => { });
  1973. });
  1974. selectPanelMode.addEventListener('change', () => {
  1975. updatePanelModeUI();
  1976. markSettingsDirty(true);
  1977. saveSettings({ silent: true }).catch(() => { });
  1978. });
  1979. selectCfDomain.addEventListener('change', () => {
  1980. if (selectCfDomain.disabled) {
  1981. return;
  1982. }
  1983. markSettingsDirty(true);
  1984. saveSettings({ silent: true }).catch(() => { });
  1985. });
  1986. btnCfDomainMode.addEventListener('click', async () => {
  1987. try {
  1988. if (!cloudflareDomainEditMode) {
  1989. setCloudflareDomainEditMode(true, { clearInput: true });
  1990. return;
  1991. }
  1992. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  1993. if (!newDomain) {
  1994. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  1995. inputCfDomain.focus();
  1996. return;
  1997. }
  1998. const { domains } = getCloudflareDomainsFromState();
  1999. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  2000. } catch (err) {
  2001. showToast(err.message, 'error');
  2002. }
  2003. });
  2004. inputCfDomain.addEventListener('keydown', (event) => {
  2005. if (event.key === 'Enter') {
  2006. event.preventDefault();
  2007. btnCfDomainMode.click();
  2008. }
  2009. });
  2010. inputSub2ApiUrl.addEventListener('input', () => {
  2011. markSettingsDirty(true);
  2012. scheduleSettingsAutoSave();
  2013. });
  2014. inputSub2ApiUrl.addEventListener('blur', () => {
  2015. saveSettings({ silent: true }).catch(() => { });
  2016. });
  2017. inputSub2ApiEmail.addEventListener('input', () => {
  2018. markSettingsDirty(true);
  2019. scheduleSettingsAutoSave();
  2020. });
  2021. inputSub2ApiEmail.addEventListener('blur', () => {
  2022. saveSettings({ silent: true }).catch(() => { });
  2023. });
  2024. inputSub2ApiPassword.addEventListener('input', () => {
  2025. markSettingsDirty(true);
  2026. scheduleSettingsAutoSave();
  2027. });
  2028. inputSub2ApiPassword.addEventListener('blur', () => {
  2029. saveSettings({ silent: true }).catch(() => { });
  2030. });
  2031. inputSub2ApiGroup.addEventListener('input', () => {
  2032. markSettingsDirty(true);
  2033. scheduleSettingsAutoSave();
  2034. });
  2035. inputSub2ApiGroup.addEventListener('blur', () => {
  2036. saveSettings({ silent: true }).catch(() => { });
  2037. });
  2038. inputEmailPrefix.addEventListener('input', () => {
  2039. markSettingsDirty(true);
  2040. scheduleSettingsAutoSave();
  2041. });
  2042. inputEmailPrefix.addEventListener('blur', () => {
  2043. saveSettings({ silent: true }).catch(() => {});
  2044. });
  2045. inputInbucketMailbox.addEventListener('input', () => {
  2046. markSettingsDirty(true);
  2047. scheduleSettingsAutoSave();
  2048. });
  2049. inputInbucketMailbox.addEventListener('blur', () => {
  2050. saveSettings({ silent: true }).catch(() => { });
  2051. });
  2052. inputInbucketHost.addEventListener('input', () => {
  2053. markSettingsDirty(true);
  2054. scheduleSettingsAutoSave();
  2055. });
  2056. inputInbucketHost.addEventListener('blur', () => {
  2057. saveSettings({ silent: true }).catch(() => { });
  2058. });
  2059. inputAutoSkipFailures.addEventListener('change', () => {
  2060. markSettingsDirty(true);
  2061. saveSettings({ silent: true }).catch(() => { });
  2062. });
  2063. inputAutoDelayEnabled.addEventListener('change', () => {
  2064. updateAutoDelayInputState();
  2065. markSettingsDirty(true);
  2066. saveSettings({ silent: true }).catch(() => { });
  2067. });
  2068. inputAutoDelayMinutes.addEventListener('input', () => {
  2069. markSettingsDirty(true);
  2070. scheduleSettingsAutoSave();
  2071. });
  2072. inputAutoDelayMinutes.addEventListener('blur', () => {
  2073. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  2074. saveSettings({ silent: true }).catch(() => { });
  2075. });
  2076. // ============================================================
  2077. // Listen for Background broadcasts
  2078. // ============================================================
  2079. chrome.runtime.onMessage.addListener((message) => {
  2080. switch (message.type) {
  2081. case 'LOG_ENTRY':
  2082. appendLog(message.payload);
  2083. if (message.payload.level === 'error') {
  2084. showToast(message.payload.message, 'error');
  2085. }
  2086. break;
  2087. case 'STEP_STATUS_CHANGED': {
  2088. const { step, status } = message.payload;
  2089. updateStepUI(step, status);
  2090. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  2091. syncLatestState(state);
  2092. syncAutoRunState(state);
  2093. updateStatusDisplay(latestState);
  2094. updateButtonStates();
  2095. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  2096. syncPasswordField(state);
  2097. if (state.oauthUrl) {
  2098. displayOauthUrl.textContent = state.oauthUrl;
  2099. displayOauthUrl.classList.add('has-value');
  2100. }
  2101. if (state.localhostUrl) {
  2102. displayLocalhostUrl.textContent = state.localhostUrl;
  2103. displayLocalhostUrl.classList.add('has-value');
  2104. }
  2105. }
  2106. }
  2107. ).catch(() => { });
  2108. break;
  2109. }
  2110. case 'AUTO_RUN_RESET': {
  2111. // Full UI reset for next run
  2112. syncLatestState({
  2113. oauthUrl: null,
  2114. localhostUrl: null,
  2115. email: null,
  2116. password: null,
  2117. stepStatuses: STEP_DEFAULT_STATUSES,
  2118. logs: [],
  2119. scheduledAutoRunAt: null,
  2120. });
  2121. displayOauthUrl.textContent = '等待中...';
  2122. displayOauthUrl.classList.remove('has-value');
  2123. displayLocalhostUrl.textContent = '等待中...';
  2124. displayLocalhostUrl.classList.remove('has-value');
  2125. inputEmail.value = '';
  2126. displayStatus.textContent = '就绪';
  2127. statusBar.className = 'status-bar';
  2128. logArea.innerHTML = '';
  2129. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  2130. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  2131. applyAutoRunStatus(currentAutoRun);
  2132. updateProgressCounter();
  2133. updateButtonStates();
  2134. renderHotmailAccounts();
  2135. break;
  2136. }
  2137. case 'DATA_UPDATED': {
  2138. syncLatestState(message.payload);
  2139. if (message.payload.email !== undefined) {
  2140. inputEmail.value = message.payload.email || '';
  2141. }
  2142. if (message.payload.password !== undefined) {
  2143. inputPassword.value = message.payload.password || '';
  2144. }
  2145. if (message.payload.localCpaStep9Mode !== undefined) {
  2146. setLocalCpaStep9Mode(message.payload.localCpaStep9Mode);
  2147. }
  2148. if (message.payload.oauthUrl !== undefined) {
  2149. displayOauthUrl.textContent = message.payload.oauthUrl || '等待中...';
  2150. displayOauthUrl.classList.toggle('has-value', Boolean(message.payload.oauthUrl));
  2151. }
  2152. if (message.payload.localhostUrl !== undefined) {
  2153. displayLocalhostUrl.textContent = message.payload.localhostUrl || '等待中...';
  2154. displayLocalhostUrl.classList.toggle('has-value', Boolean(message.payload.localhostUrl));
  2155. }
  2156. if (message.payload.currentHotmailAccountId !== undefined || message.payload.hotmailAccounts !== undefined) {
  2157. renderHotmailAccounts();
  2158. if (selectMailProvider.value === 'hotmail-api') {
  2159. const currentAccount = getCurrentHotmailAccount();
  2160. inputEmail.value = currentAccount?.email || latestState?.email || '';
  2161. }
  2162. }
  2163. if (message.payload.autoRunDelayEnabled !== undefined) {
  2164. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  2165. updateAutoDelayInputState();
  2166. }
  2167. if (message.payload.autoRunDelayMinutes !== undefined) {
  2168. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  2169. }
  2170. break;
  2171. }
  2172. case 'AUTO_RUN_STATUS': {
  2173. syncLatestState({
  2174. autoRunning: ['scheduled', 'running', 'waiting_step', 'waiting_email', 'retrying'].includes(message.payload.phase),
  2175. autoRunPhase: message.payload.phase,
  2176. autoRunCurrentRun: message.payload.currentRun,
  2177. autoRunTotalRuns: message.payload.totalRuns,
  2178. autoRunAttemptRun: message.payload.attemptRun,
  2179. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  2180. });
  2181. applyAutoRunStatus(message.payload);
  2182. updateStatusDisplay(latestState);
  2183. updateButtonStates();
  2184. break;
  2185. }
  2186. }
  2187. });
  2188. // ============================================================
  2189. // Theme Toggle
  2190. // ============================================================
  2191. const btnTheme = document.getElementById('btn-theme');
  2192. function setTheme(theme) {
  2193. document.documentElement.setAttribute('data-theme', theme);
  2194. localStorage.setItem('multipage-theme', theme);
  2195. }
  2196. function initTheme() {
  2197. const saved = localStorage.getItem('multipage-theme');
  2198. if (saved) {
  2199. setTheme(saved);
  2200. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  2201. setTheme('dark');
  2202. }
  2203. }
  2204. btnTheme.addEventListener('click', () => {
  2205. const current = document.documentElement.getAttribute('data-theme');
  2206. setTheme(current === 'dark' ? 'light' : 'dark');
  2207. });
  2208. document.addEventListener('click', (event) => {
  2209. if (!configMenuOpen) {
  2210. return;
  2211. }
  2212. if (configMenuShell?.contains(event.target)) {
  2213. return;
  2214. }
  2215. closeConfigMenu();
  2216. });
  2217. document.addEventListener('keydown', (event) => {
  2218. if (event.key === 'Escape' && configMenuOpen) {
  2219. closeConfigMenu();
  2220. }
  2221. });
  2222. // ============================================================
  2223. // Init
  2224. // ============================================================
  2225. initializeManualStepActions();
  2226. initTheme();
  2227. initHotmailListExpandedState();
  2228. updateSaveButtonState();
  2229. updateConfigMenuControls();
  2230. setLocalCpaStep9Mode(DEFAULT_LOCAL_CPA_STEP9_MODE);
  2231. restoreState().then(() => {
  2232. syncPasswordToggleLabel();
  2233. syncVpsUrlToggleLabel();
  2234. syncVpsPasswordToggleLabel();
  2235. updatePanelModeUI();
  2236. updateButtonStates();
  2237. updateStatusDisplay(latestState);
  2238. });