sidepanel.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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 displayOauthUrl = document.getElementById('display-oauth-url');
  13. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  14. const displayStatus = document.getElementById('display-status');
  15. const statusBar = document.getElementById('status-bar');
  16. const inputEmail = document.getElementById('input-email');
  17. const inputPassword = document.getElementById('input-password');
  18. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  19. const btnFetchEmail = document.getElementById('btn-fetch-email');
  20. const btnTogglePassword = document.getElementById('btn-toggle-password');
  21. const btnSaveSettings = document.getElementById('btn-save-settings');
  22. const btnStop = document.getElementById('btn-stop');
  23. const btnReset = document.getElementById('btn-reset');
  24. const stepsProgress = document.getElementById('steps-progress');
  25. const btnAutoRun = document.getElementById('btn-auto-run');
  26. const btnAutoContinue = document.getElementById('btn-auto-continue');
  27. const autoContinueBar = document.getElementById('auto-continue-bar');
  28. const autoScheduleBar = document.getElementById('auto-schedule-bar');
  29. const autoScheduleTitle = document.getElementById('auto-schedule-title');
  30. const autoScheduleMeta = document.getElementById('auto-schedule-meta');
  31. const btnAutoRunNow = document.getElementById('btn-auto-run-now');
  32. const btnAutoCancelSchedule = document.getElementById('btn-auto-cancel-schedule');
  33. const btnClearLog = document.getElementById('btn-clear-log');
  34. const inputVpsUrl = document.getElementById('input-vps-url');
  35. const inputVpsPassword = document.getElementById('input-vps-password');
  36. const selectMailProvider = document.getElementById('select-mail-provider');
  37. const selectEmailGenerator = document.getElementById('select-email-generator');
  38. const rowInbucketHost = document.getElementById('row-inbucket-host');
  39. const inputInbucketHost = document.getElementById('input-inbucket-host');
  40. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  41. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  42. const rowCfDomain = document.getElementById('row-cf-domain');
  43. const selectCfDomain = document.getElementById('select-cf-domain');
  44. const inputCfDomain = document.getElementById('input-cf-domain');
  45. const btnCfDomainMode = document.getElementById('btn-cf-domain-mode');
  46. const inputRunCount = document.getElementById('input-run-count');
  47. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  48. const inputAutoDelayEnabled = document.getElementById('input-auto-delay-enabled');
  49. const inputAutoDelayMinutes = document.getElementById('input-auto-delay-minutes');
  50. const autoStartModal = document.getElementById('auto-start-modal');
  51. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  52. const autoStartMessage = document.getElementById('auto-start-message');
  53. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  54. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  55. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  56. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  57. const STEP_DEFAULT_STATUSES = {
  58. 1: 'pending',
  59. 2: 'pending',
  60. 3: 'pending',
  61. 4: 'pending',
  62. 5: 'pending',
  63. 6: 'pending',
  64. 7: 'pending',
  65. 8: 'pending',
  66. 9: 'pending',
  67. };
  68. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  69. const AUTO_DELAY_MIN_MINUTES = 1;
  70. const AUTO_DELAY_MAX_MINUTES = 1440;
  71. const AUTO_DELAY_DEFAULT_MINUTES = 30;
  72. let latestState = null;
  73. let currentAutoRun = {
  74. autoRunning: false,
  75. phase: 'idle',
  76. currentRun: 0,
  77. totalRuns: 1,
  78. attemptRun: 0,
  79. scheduledAt: null,
  80. };
  81. let settingsDirty = false;
  82. let settingsSaveInFlight = false;
  83. let settingsAutoSaveTimer = null;
  84. let cloudflareDomainEditMode = false;
  85. let modalChoiceResolver = null;
  86. let currentModalActions = [];
  87. let scheduledCountdownTimer = null;
  88. 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>';
  89. 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>';
  90. // ============================================================
  91. // Toast Notifications
  92. // ============================================================
  93. const toastContainer = document.getElementById('toast-container');
  94. const TOAST_ICONS = {
  95. 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>',
  96. 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>',
  97. 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>',
  98. 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>',
  99. };
  100. const LOG_LEVEL_LABELS = {
  101. info: '信息',
  102. ok: '成功',
  103. warn: '警告',
  104. error: '错误',
  105. };
  106. function showToast(message, type = 'error', duration = 4000) {
  107. const toast = document.createElement('div');
  108. toast.className = `toast toast-${type}`;
  109. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  110. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  111. toastContainer.appendChild(toast);
  112. if (duration > 0) {
  113. setTimeout(() => dismissToast(toast), duration);
  114. }
  115. }
  116. function dismissToast(toast) {
  117. if (!toast.parentNode) return;
  118. toast.classList.add('toast-exit');
  119. toast.addEventListener('animationend', () => toast.remove());
  120. }
  121. function resetActionModalButtons() {
  122. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  123. buttons.forEach((button) => {
  124. if (!button) return;
  125. button.hidden = true;
  126. button.disabled = false;
  127. button.onclick = null;
  128. });
  129. currentModalActions = [];
  130. }
  131. function configureActionModalButton(button, action) {
  132. if (!button) return;
  133. if (!action) {
  134. button.hidden = true;
  135. button.onclick = null;
  136. return;
  137. }
  138. button.hidden = false;
  139. button.disabled = false;
  140. button.textContent = action.label;
  141. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  142. button.onclick = () => resolveModalChoice(action.id);
  143. }
  144. function resolveModalChoice(choice) {
  145. if (modalChoiceResolver) {
  146. modalChoiceResolver(choice);
  147. modalChoiceResolver = null;
  148. }
  149. resetActionModalButtons();
  150. if (autoStartModal) {
  151. autoStartModal.hidden = true;
  152. }
  153. }
  154. function openActionModal({ title, message, actions }) {
  155. if (!autoStartModal) {
  156. return Promise.resolve(null);
  157. }
  158. if (modalChoiceResolver) {
  159. resolveModalChoice(null);
  160. }
  161. autoStartTitle.textContent = title;
  162. autoStartMessage.textContent = message;
  163. currentModalActions = actions || [];
  164. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  165. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  166. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  167. autoStartModal.hidden = false;
  168. return new Promise((resolve) => {
  169. modalChoiceResolver = resolve;
  170. });
  171. }
  172. function openAutoStartChoiceDialog(startStep) {
  173. return openActionModal({
  174. title: '启动自动',
  175. message: `检测到当前已有流程进度。继续当前会从步骤 ${startStep} 开始自动执行,重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  176. actions: [
  177. { id: null, label: '取消', variant: 'btn-ghost' },
  178. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  179. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  180. ],
  181. });
  182. }
  183. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  184. const choice = await openActionModal({
  185. title,
  186. message,
  187. actions: [
  188. { id: null, label: '取消', variant: 'btn-ghost' },
  189. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  190. ],
  191. });
  192. return choice === 'confirm';
  193. }
  194. function isDoneStatus(status) {
  195. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  196. }
  197. function getStepStatuses(state = latestState) {
  198. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  199. }
  200. function getFirstUnfinishedStep(state = latestState) {
  201. const statuses = getStepStatuses(state);
  202. for (let step = 1; step <= 9; step++) {
  203. if (!isDoneStatus(statuses[step])) {
  204. return step;
  205. }
  206. }
  207. return null;
  208. }
  209. function hasSavedProgress(state = latestState) {
  210. const statuses = getStepStatuses(state);
  211. return Object.values(statuses).some((status) => status !== 'pending');
  212. }
  213. function shouldOfferAutoModeChoice(state = latestState) {
  214. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  215. }
  216. function syncLatestState(nextState) {
  217. const mergedStepStatuses = nextState?.stepStatuses
  218. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  219. : getStepStatuses(latestState);
  220. latestState = {
  221. ...(latestState || {}),
  222. ...(nextState || {}),
  223. stepStatuses: mergedStepStatuses,
  224. };
  225. }
  226. function syncAutoRunState(source = {}) {
  227. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  228. const autoRunning = source.autoRunning !== undefined
  229. ? Boolean(source.autoRunning)
  230. : (source.autoRunPhase !== undefined || source.phase !== undefined
  231. ? ['scheduled', 'running', 'waiting_email', 'retrying'].includes(phase)
  232. : currentAutoRun.autoRunning);
  233. currentAutoRun = {
  234. autoRunning,
  235. phase,
  236. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  237. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  238. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  239. scheduledAt: source.scheduledAutoRunAt ?? source.scheduledAt ?? currentAutoRun.scheduledAt,
  240. };
  241. }
  242. function isAutoRunLockedPhase() {
  243. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'retrying';
  244. }
  245. function isAutoRunPausedPhase() {
  246. return currentAutoRun.phase === 'waiting_email';
  247. }
  248. function isAutoRunScheduledPhase() {
  249. return currentAutoRun.phase === 'scheduled';
  250. }
  251. function getAutoRunLabel(payload = currentAutoRun) {
  252. if ((payload.phase ?? currentAutoRun.phase) === 'scheduled') {
  253. return (payload.totalRuns || 1) > 1 ? ` (${payload.totalRuns}轮)` : '';
  254. }
  255. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  256. if ((payload.totalRuns || 1) > 1) {
  257. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  258. }
  259. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  260. }
  261. function normalizeAutoDelayMinutes(value) {
  262. const numeric = Number(value);
  263. if (!Number.isFinite(numeric)) {
  264. return AUTO_DELAY_DEFAULT_MINUTES;
  265. }
  266. return Math.min(AUTO_DELAY_MAX_MINUTES, Math.max(AUTO_DELAY_MIN_MINUTES, Math.floor(numeric)));
  267. }
  268. function updateAutoDelayInputState() {
  269. const scheduled = isAutoRunScheduledPhase();
  270. inputAutoDelayEnabled.disabled = scheduled;
  271. inputAutoDelayMinutes.disabled = scheduled || !inputAutoDelayEnabled.checked;
  272. }
  273. function formatCountdown(remainingMs) {
  274. const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000));
  275. const hours = Math.floor(totalSeconds / 3600);
  276. const minutes = Math.floor((totalSeconds % 3600) / 60);
  277. const seconds = totalSeconds % 60;
  278. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  279. }
  280. function formatScheduleTime(timestamp) {
  281. return new Date(timestamp).toLocaleString('zh-CN', {
  282. hour12: false,
  283. month: '2-digit',
  284. day: '2-digit',
  285. hour: '2-digit',
  286. minute: '2-digit',
  287. second: '2-digit',
  288. });
  289. }
  290. function stopScheduledCountdownTicker() {
  291. clearInterval(scheduledCountdownTimer);
  292. scheduledCountdownTimer = null;
  293. }
  294. function renderScheduledAutoRunInfo() {
  295. if (!autoScheduleBar) {
  296. return;
  297. }
  298. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  299. autoScheduleBar.style.display = 'none';
  300. return;
  301. }
  302. const remainingMs = currentAutoRun.scheduledAt - Date.now();
  303. autoScheduleBar.style.display = 'flex';
  304. autoScheduleTitle.textContent = '已计划自动运行';
  305. autoScheduleMeta.textContent = remainingMs > 0
  306. ? `计划于 ${formatScheduleTime(currentAutoRun.scheduledAt)} 开始,剩余 ${formatCountdown(remainingMs)}`
  307. : '倒计时即将结束,正在准备启动...';
  308. }
  309. function syncScheduledCountdownTicker() {
  310. renderScheduledAutoRunInfo();
  311. if (!isAutoRunScheduledPhase() || !Number.isFinite(currentAutoRun.scheduledAt)) {
  312. stopScheduledCountdownTicker();
  313. return;
  314. }
  315. if (scheduledCountdownTimer) {
  316. return;
  317. }
  318. scheduledCountdownTimer = setInterval(() => {
  319. renderScheduledAutoRunInfo();
  320. updateStatusDisplay(latestState);
  321. }, 1000);
  322. }
  323. function setDefaultAutoRunButton() {
  324. btnAutoRun.disabled = false;
  325. inputRunCount.disabled = false;
  326. 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> 自动';
  327. }
  328. function normalizeCloudflareDomainValue(value = '') {
  329. let normalized = String(value || '').trim().toLowerCase();
  330. if (!normalized) return '';
  331. normalized = normalized.replace(/^@+/, '');
  332. normalized = normalized.replace(/^https?:\/\//, '');
  333. normalized = normalized.replace(/\/.*$/, '');
  334. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(normalized)) {
  335. return '';
  336. }
  337. return normalized;
  338. }
  339. function normalizeCloudflareDomains(values = []) {
  340. const seen = new Set();
  341. const domains = [];
  342. for (const value of Array.isArray(values) ? values : []) {
  343. const normalized = normalizeCloudflareDomainValue(value);
  344. if (!normalized || seen.has(normalized)) continue;
  345. seen.add(normalized);
  346. domains.push(normalized);
  347. }
  348. return domains;
  349. }
  350. function getCloudflareDomainsFromState() {
  351. const domains = normalizeCloudflareDomains(latestState?.cloudflareDomains || []);
  352. const activeDomain = normalizeCloudflareDomainValue(latestState?.cloudflareDomain || '');
  353. if (activeDomain && !domains.includes(activeDomain)) {
  354. domains.unshift(activeDomain);
  355. }
  356. return { domains, activeDomain: activeDomain || domains[0] || '' };
  357. }
  358. function renderCloudflareDomainOptions(preferredDomain = '') {
  359. const preferred = normalizeCloudflareDomainValue(preferredDomain);
  360. const { domains, activeDomain } = getCloudflareDomainsFromState();
  361. const selected = preferred || activeDomain;
  362. selectCfDomain.innerHTML = '';
  363. if (domains.length === 0) {
  364. const option = document.createElement('option');
  365. option.value = '';
  366. option.textContent = '请先添加域名';
  367. selectCfDomain.appendChild(option);
  368. selectCfDomain.disabled = true;
  369. selectCfDomain.value = '';
  370. return;
  371. }
  372. for (const domain of domains) {
  373. const option = document.createElement('option');
  374. option.value = domain;
  375. option.textContent = domain;
  376. selectCfDomain.appendChild(option);
  377. }
  378. selectCfDomain.disabled = false;
  379. selectCfDomain.value = domains.includes(selected) ? selected : domains[0];
  380. }
  381. function setCloudflareDomainEditMode(editing, options = {}) {
  382. const { clearInput = false } = options;
  383. cloudflareDomainEditMode = Boolean(editing);
  384. selectCfDomain.style.display = cloudflareDomainEditMode ? 'none' : '';
  385. inputCfDomain.style.display = cloudflareDomainEditMode ? '' : 'none';
  386. btnCfDomainMode.textContent = cloudflareDomainEditMode ? '保存' : '添加';
  387. if (cloudflareDomainEditMode) {
  388. if (clearInput) {
  389. inputCfDomain.value = '';
  390. }
  391. inputCfDomain.focus();
  392. } else if (clearInput) {
  393. inputCfDomain.value = '';
  394. }
  395. }
  396. function collectSettingsPayload() {
  397. const { domains, activeDomain } = getCloudflareDomainsFromState();
  398. const selectedCloudflareDomain = normalizeCloudflareDomainValue(
  399. !cloudflareDomainEditMode ? selectCfDomain.value : activeDomain
  400. ) || activeDomain;
  401. return {
  402. vpsUrl: inputVpsUrl.value.trim(),
  403. vpsPassword: inputVpsPassword.value,
  404. customPassword: inputPassword.value,
  405. mailProvider: selectMailProvider.value,
  406. emailGenerator: selectEmailGenerator.value,
  407. inbucketHost: inputInbucketHost.value.trim(),
  408. inbucketMailbox: inputInbucketMailbox.value.trim(),
  409. cloudflareDomain: selectedCloudflareDomain,
  410. cloudflareDomains: domains,
  411. autoRunSkipFailures: inputAutoSkipFailures.checked,
  412. autoRunDelayEnabled: inputAutoDelayEnabled.checked,
  413. autoRunDelayMinutes: normalizeAutoDelayMinutes(inputAutoDelayMinutes.value),
  414. };
  415. }
  416. function markSettingsDirty(isDirty = true) {
  417. settingsDirty = isDirty;
  418. updateSaveButtonState();
  419. }
  420. function updateSaveButtonState() {
  421. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  422. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  423. }
  424. function scheduleSettingsAutoSave() {
  425. clearTimeout(settingsAutoSaveTimer);
  426. settingsAutoSaveTimer = setTimeout(() => {
  427. saveSettings({ silent: true }).catch(() => { });
  428. }, 500);
  429. }
  430. async function saveSettings(options = {}) {
  431. const { silent = false } = options;
  432. clearTimeout(settingsAutoSaveTimer);
  433. if (!settingsDirty && !settingsSaveInFlight && silent) {
  434. return;
  435. }
  436. const payload = collectSettingsPayload();
  437. settingsSaveInFlight = true;
  438. updateSaveButtonState();
  439. try {
  440. const response = await chrome.runtime.sendMessage({
  441. type: 'SAVE_SETTING',
  442. source: 'sidepanel',
  443. payload,
  444. });
  445. if (response?.error) {
  446. throw new Error(response.error);
  447. }
  448. syncLatestState(payload);
  449. markSettingsDirty(false);
  450. updateMailProviderUI();
  451. updateButtonStates();
  452. if (!silent) {
  453. showToast('配置已保存', 'success', 1800);
  454. }
  455. } catch (err) {
  456. markSettingsDirty(true);
  457. if (!silent) {
  458. showToast(`保存失败:${err.message}`, 'error');
  459. }
  460. throw err;
  461. } finally {
  462. settingsSaveInFlight = false;
  463. updateSaveButtonState();
  464. }
  465. }
  466. function applyAutoRunStatus(payload = currentAutoRun) {
  467. syncAutoRunState(payload);
  468. const runLabel = getAutoRunLabel(currentAutoRun);
  469. const locked = isAutoRunLockedPhase();
  470. const paused = isAutoRunPausedPhase();
  471. const scheduled = isAutoRunScheduledPhase();
  472. inputRunCount.disabled = currentAutoRun.autoRunning;
  473. btnAutoRun.disabled = currentAutoRun.autoRunning;
  474. btnFetchEmail.disabled = locked;
  475. inputEmail.disabled = locked;
  476. inputAutoSkipFailures.disabled = scheduled;
  477. if (currentAutoRun.totalRuns > 0) {
  478. inputRunCount.value = String(currentAutoRun.totalRuns);
  479. }
  480. switch (currentAutoRun.phase) {
  481. case 'scheduled':
  482. autoContinueBar.style.display = 'none';
  483. btnAutoRun.innerHTML = `已计划${runLabel}`;
  484. break;
  485. case 'waiting_email':
  486. autoContinueBar.style.display = 'flex';
  487. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  488. break;
  489. case 'running':
  490. autoContinueBar.style.display = 'none';
  491. btnAutoRun.innerHTML = `运行中${runLabel}`;
  492. break;
  493. case 'retrying':
  494. autoContinueBar.style.display = 'none';
  495. btnAutoRun.innerHTML = `重试中${runLabel}`;
  496. break;
  497. default:
  498. autoContinueBar.style.display = 'none';
  499. setDefaultAutoRunButton();
  500. inputEmail.disabled = false;
  501. if (!locked) {
  502. btnFetchEmail.disabled = false;
  503. }
  504. break;
  505. }
  506. updateAutoDelayInputState();
  507. syncScheduledCountdownTicker();
  508. updateStopButtonState(scheduled || paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  509. }
  510. function initializeManualStepActions() {
  511. document.querySelectorAll('.step-row').forEach((row) => {
  512. const step = Number(row.dataset.step);
  513. const statusEl = row.querySelector('.step-status');
  514. if (!statusEl) return;
  515. const actions = document.createElement('div');
  516. actions.className = 'step-actions';
  517. const manualBtn = document.createElement('button');
  518. manualBtn.type = 'button';
  519. manualBtn.className = 'step-manual-btn';
  520. manualBtn.dataset.step = String(step);
  521. manualBtn.title = '跳过此步';
  522. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  523. 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>';
  524. manualBtn.addEventListener('click', async (event) => {
  525. event.stopPropagation();
  526. try {
  527. await handleSkipStep(step);
  528. } catch (err) {
  529. showToast(err.message, 'error');
  530. }
  531. });
  532. statusEl.parentNode.replaceChild(actions, statusEl);
  533. actions.appendChild(manualBtn);
  534. actions.appendChild(statusEl);
  535. });
  536. }
  537. // ============================================================
  538. // State Restore on load
  539. // ============================================================
  540. async function restoreState() {
  541. try {
  542. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  543. syncLatestState(state);
  544. syncAutoRunState(state);
  545. if (state.oauthUrl) {
  546. displayOauthUrl.textContent = state.oauthUrl;
  547. displayOauthUrl.classList.add('has-value');
  548. }
  549. if (state.localhostUrl) {
  550. displayLocalhostUrl.textContent = state.localhostUrl;
  551. displayLocalhostUrl.classList.add('has-value');
  552. }
  553. if (state.email) {
  554. inputEmail.value = state.email;
  555. }
  556. syncPasswordField(state);
  557. if (state.vpsUrl) {
  558. inputVpsUrl.value = state.vpsUrl;
  559. }
  560. if (state.vpsPassword) {
  561. inputVpsPassword.value = state.vpsPassword;
  562. }
  563. if (state.mailProvider) {
  564. selectMailProvider.value = state.mailProvider;
  565. }
  566. if (state.emailGenerator) {
  567. selectEmailGenerator.value = state.emailGenerator;
  568. }
  569. if (state.inbucketHost) {
  570. inputInbucketHost.value = state.inbucketHost;
  571. }
  572. if (state.inbucketMailbox) {
  573. inputInbucketMailbox.value = state.inbucketMailbox;
  574. }
  575. renderCloudflareDomainOptions(state.cloudflareDomain || '');
  576. setCloudflareDomainEditMode(false, { clearInput: true });
  577. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  578. inputAutoDelayEnabled.checked = Boolean(state.autoRunDelayEnabled);
  579. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(state.autoRunDelayMinutes));
  580. if (state.autoRunTotalRuns) {
  581. inputRunCount.value = String(state.autoRunTotalRuns);
  582. }
  583. if (state.stepStatuses) {
  584. for (const [step, status] of Object.entries(state.stepStatuses)) {
  585. updateStepUI(Number(step), status);
  586. }
  587. }
  588. if (state.logs) {
  589. for (const entry of state.logs) {
  590. appendLog(entry);
  591. }
  592. }
  593. applyAutoRunStatus(state);
  594. markSettingsDirty(false);
  595. updateAutoDelayInputState();
  596. updateStatusDisplay(latestState);
  597. updateProgressCounter();
  598. updateMailProviderUI();
  599. updateButtonStates();
  600. } catch (err) {
  601. console.error('Failed to restore state:', err);
  602. }
  603. }
  604. function syncPasswordField(state) {
  605. inputPassword.value = state.customPassword || state.password || '';
  606. }
  607. function getSelectedEmailGenerator() {
  608. return selectEmailGenerator.value === 'cloudflare' ? 'cloudflare' : 'duck';
  609. }
  610. function getEmailGeneratorUiCopy() {
  611. if (getSelectedEmailGenerator() === 'cloudflare') {
  612. return {
  613. buttonLabel: '生成 Cloudflare',
  614. placeholder: '点击生成 Cloudflare 邮箱,或手动粘贴邮箱',
  615. successVerb: '生成',
  616. label: 'Cloudflare 邮箱',
  617. };
  618. }
  619. return {
  620. buttonLabel: '获取 Duck',
  621. placeholder: '点击获取 DuckDuckGo 邮箱,或手动粘贴邮箱',
  622. successVerb: '获取',
  623. label: 'Duck 邮箱',
  624. };
  625. }
  626. function updateMailProviderUI() {
  627. const useInbucket = selectMailProvider.value === 'inbucket';
  628. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  629. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  630. const useCloudflare = selectEmailGenerator.value === 'cloudflare';
  631. rowCfDomain.style.display = useCloudflare ? '' : 'none';
  632. const { domains } = getCloudflareDomainsFromState();
  633. if (useCloudflare) {
  634. setCloudflareDomainEditMode(cloudflareDomainEditMode || domains.length === 0, { clearInput: false });
  635. } else {
  636. setCloudflareDomainEditMode(false, { clearInput: false });
  637. }
  638. const uiCopy = getEmailGeneratorUiCopy();
  639. inputEmail.placeholder = uiCopy.placeholder;
  640. if (!btnFetchEmail.disabled) {
  641. btnFetchEmail.textContent = uiCopy.buttonLabel;
  642. }
  643. }
  644. async function saveCloudflareDomainSettings(domains, activeDomain, options = {}) {
  645. const { silent = false } = options;
  646. const normalizedDomains = normalizeCloudflareDomains(domains);
  647. const normalizedActiveDomain = normalizeCloudflareDomainValue(activeDomain) || normalizedDomains[0] || '';
  648. const payload = {
  649. cloudflareDomain: normalizedActiveDomain,
  650. cloudflareDomains: normalizedDomains,
  651. };
  652. const response = await chrome.runtime.sendMessage({
  653. type: 'SAVE_SETTING',
  654. source: 'sidepanel',
  655. payload,
  656. });
  657. if (response?.error) {
  658. throw new Error(response.error);
  659. }
  660. syncLatestState({
  661. ...payload,
  662. });
  663. renderCloudflareDomainOptions(normalizedActiveDomain);
  664. setCloudflareDomainEditMode(false, { clearInput: true });
  665. markSettingsDirty(false);
  666. updateMailProviderUI();
  667. if (!silent) {
  668. showToast('Cloudflare 域名已保存', 'success', 1800);
  669. }
  670. }
  671. // ============================================================
  672. // UI Updates
  673. // ============================================================
  674. function updateStepUI(step, status) {
  675. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  676. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  677. syncLatestState({
  678. stepStatuses: {
  679. ...getStepStatuses(),
  680. [step]: status,
  681. },
  682. });
  683. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  684. if (row) {
  685. row.className = `step-row ${status}`;
  686. }
  687. updateButtonStates();
  688. updateProgressCounter();
  689. }
  690. function updateProgressCounter() {
  691. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  692. stepsProgress.textContent = `${completed} / 9`;
  693. }
  694. function updateButtonStates() {
  695. const statuses = getStepStatuses();
  696. const anyRunning = Object.values(statuses).some(s => s === 'running');
  697. const autoLocked = isAutoRunLockedPhase();
  698. const autoScheduled = isAutoRunScheduledPhase();
  699. for (let step = 1; step <= 9; step++) {
  700. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  701. if (!btn) continue;
  702. if (anyRunning || autoLocked || autoScheduled) {
  703. btn.disabled = true;
  704. } else if (step === 1) {
  705. btn.disabled = false;
  706. } else {
  707. const prevStatus = statuses[step - 1];
  708. const currentStatus = statuses[step];
  709. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  710. }
  711. }
  712. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  713. const step = Number(btn.dataset.step);
  714. const currentStatus = statuses[step];
  715. const prevStatus = statuses[step - 1];
  716. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || autoScheduled || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  717. btn.style.display = 'none';
  718. btn.disabled = true;
  719. btn.title = '当前不可跳过';
  720. return;
  721. }
  722. if (step > 1 && !isDoneStatus(prevStatus)) {
  723. btn.style.display = 'none';
  724. btn.disabled = true;
  725. btn.title = `请先完成步骤 ${step - 1}`;
  726. return;
  727. }
  728. btn.style.display = '';
  729. btn.disabled = false;
  730. btn.title = `跳过步骤 ${step}`;
  731. });
  732. btnReset.disabled = anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked;
  733. updateStopButtonState(anyRunning || autoScheduled || isAutoRunPausedPhase() || autoLocked);
  734. }
  735. function updateStopButtonState(active) {
  736. btnStop.disabled = !active;
  737. }
  738. function updateStatusDisplay(state) {
  739. if (!state || !state.stepStatuses) return;
  740. statusBar.className = 'status-bar';
  741. if (isAutoRunScheduledPhase()) {
  742. const remainingMs = Number.isFinite(currentAutoRun.scheduledAt)
  743. ? currentAutoRun.scheduledAt - Date.now()
  744. : 0;
  745. displayStatus.textContent = remainingMs > 0
  746. ? `自动计划中,剩余 ${formatCountdown(remainingMs)}`
  747. : '倒计时即将结束,正在准备启动...';
  748. statusBar.classList.add('scheduled');
  749. return;
  750. }
  751. if (isAutoRunPausedPhase()) {
  752. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  753. statusBar.classList.add('paused');
  754. return;
  755. }
  756. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  757. if (running) {
  758. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  759. statusBar.classList.add('running');
  760. return;
  761. }
  762. if (isAutoRunLockedPhase()) {
  763. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  764. statusBar.classList.add('running');
  765. return;
  766. }
  767. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  768. if (failed) {
  769. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  770. statusBar.classList.add('failed');
  771. return;
  772. }
  773. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  774. if (stopped) {
  775. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  776. statusBar.classList.add('stopped');
  777. return;
  778. }
  779. const lastCompleted = Object.entries(state.stepStatuses)
  780. .filter(([, s]) => isDoneStatus(s))
  781. .map(([k]) => Number(k))
  782. .sort((a, b) => b - a)[0];
  783. if (lastCompleted === 9) {
  784. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  785. statusBar.classList.add('completed');
  786. } else if (lastCompleted) {
  787. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  788. ? `步骤 ${lastCompleted} 已跳过`
  789. : `步骤 ${lastCompleted} 已完成`;
  790. } else {
  791. displayStatus.textContent = '就绪';
  792. }
  793. }
  794. function appendLog(entry) {
  795. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  796. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  797. const line = document.createElement('div');
  798. line.className = `log-line log-${entry.level}`;
  799. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  800. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  801. let html = `<span class="log-time">${time}</span> `;
  802. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  803. if (stepNum) {
  804. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  805. }
  806. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  807. line.innerHTML = html;
  808. logArea.appendChild(line);
  809. logArea.scrollTop = logArea.scrollHeight;
  810. }
  811. function escapeHtml(text) {
  812. const div = document.createElement('div');
  813. div.textContent = text;
  814. return div.innerHTML;
  815. }
  816. async function fetchGeneratedEmail(options = {}) {
  817. const { showFailureToast = true } = options;
  818. const uiCopy = getEmailGeneratorUiCopy();
  819. const defaultLabel = uiCopy.buttonLabel;
  820. btnFetchEmail.disabled = true;
  821. btnFetchEmail.textContent = '...';
  822. try {
  823. const response = await chrome.runtime.sendMessage({
  824. type: 'FETCH_GENERATED_EMAIL',
  825. source: 'sidepanel',
  826. payload: {
  827. generateNew: true,
  828. generator: selectEmailGenerator.value,
  829. },
  830. });
  831. if (response?.error) {
  832. throw new Error(response.error);
  833. }
  834. if (!response?.email) {
  835. throw new Error('未返回可用邮箱。');
  836. }
  837. inputEmail.value = response.email;
  838. showToast(`已${uiCopy.successVerb} ${uiCopy.label}:${response.email}`, 'success', 2500);
  839. return response.email;
  840. } catch (err) {
  841. if (showFailureToast) {
  842. showToast(`${uiCopy.label}${uiCopy.successVerb}失败:${err.message}`, 'error');
  843. }
  844. throw err;
  845. } finally {
  846. btnFetchEmail.disabled = false;
  847. btnFetchEmail.textContent = defaultLabel;
  848. }
  849. }
  850. function syncToggleButtonLabel(button, input, labels) {
  851. if (!button || !input) return;
  852. const isHidden = input.type === 'password';
  853. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  854. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  855. button.title = isHidden ? labels.show : labels.hide;
  856. }
  857. function syncPasswordToggleLabel() {
  858. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  859. show: '显示密码',
  860. hide: '隐藏密码',
  861. });
  862. }
  863. function syncVpsUrlToggleLabel() {
  864. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  865. show: '显示 CPA 地址',
  866. hide: '隐藏 CPA 地址',
  867. });
  868. }
  869. async function maybeTakeoverAutoRun(actionLabel) {
  870. if (!isAutoRunPausedPhase()) {
  871. return true;
  872. }
  873. const confirmed = await openConfirmModal({
  874. title: '接管自动',
  875. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  876. confirmLabel: '确认接管',
  877. confirmVariant: 'btn-primary',
  878. });
  879. if (!confirmed) {
  880. return false;
  881. }
  882. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  883. return true;
  884. }
  885. async function handleSkipStep(step) {
  886. if (isAutoRunPausedPhase()) {
  887. const takeoverResponse = await chrome.runtime.sendMessage({
  888. type: 'TAKEOVER_AUTO_RUN',
  889. source: 'sidepanel',
  890. payload: {},
  891. });
  892. if (takeoverResponse?.error) {
  893. throw new Error(takeoverResponse.error);
  894. }
  895. }
  896. const response = await chrome.runtime.sendMessage({
  897. type: 'SKIP_STEP',
  898. source: 'sidepanel',
  899. payload: { step },
  900. });
  901. if (response?.error) {
  902. throw new Error(response.error);
  903. }
  904. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  905. }
  906. // ============================================================
  907. // Button Handlers
  908. // ============================================================
  909. document.querySelectorAll('.step-btn').forEach(btn => {
  910. btn.addEventListener('click', async () => {
  911. try {
  912. const step = Number(btn.dataset.step);
  913. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  914. return;
  915. }
  916. if (step === 3) {
  917. if (inputPassword.value !== (latestState?.customPassword || '')) {
  918. await chrome.runtime.sendMessage({
  919. type: 'SAVE_SETTING',
  920. source: 'sidepanel',
  921. payload: { customPassword: inputPassword.value },
  922. });
  923. syncLatestState({ customPassword: inputPassword.value });
  924. }
  925. let email = inputEmail.value.trim();
  926. if (!email) {
  927. try {
  928. email = await fetchGeneratedEmail({ showFailureToast: false });
  929. } catch (err) {
  930. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  931. return;
  932. }
  933. }
  934. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  935. if (response?.error) {
  936. throw new Error(response.error);
  937. }
  938. } else {
  939. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  940. if (response?.error) {
  941. throw new Error(response.error);
  942. }
  943. }
  944. } catch (err) {
  945. showToast(err.message, 'error');
  946. }
  947. });
  948. });
  949. btnFetchEmail.addEventListener('click', async () => {
  950. await fetchGeneratedEmail().catch(() => { });
  951. });
  952. btnTogglePassword.addEventListener('click', () => {
  953. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  954. syncPasswordToggleLabel();
  955. });
  956. btnToggleVpsUrl.addEventListener('click', () => {
  957. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  958. syncVpsUrlToggleLabel();
  959. });
  960. btnSaveSettings.addEventListener('click', async () => {
  961. if (!settingsDirty) {
  962. showToast('配置已是最新', 'info', 1400);
  963. return;
  964. }
  965. await saveSettings({ silent: false }).catch(() => { });
  966. });
  967. btnStop.addEventListener('click', async () => {
  968. btnStop.disabled = true;
  969. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  970. showToast(isAutoRunScheduledPhase() ? '正在取消倒计时计划...' : '正在停止当前流程...', 'warn', 2000);
  971. });
  972. autoStartModal?.addEventListener('click', (event) => {
  973. if (event.target === autoStartModal) {
  974. resolveModalChoice(null);
  975. }
  976. });
  977. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  978. // Auto Run
  979. btnAutoRun.addEventListener('click', async () => {
  980. try {
  981. const totalRuns = Math.min(50, Math.max(1, parseInt(inputRunCount.value, 10) || 1));
  982. let mode = 'restart';
  983. if (shouldOfferAutoModeChoice()) {
  984. const startStep = getFirstUnfinishedStep();
  985. const choice = await openAutoStartChoiceDialog(startStep);
  986. if (!choice) {
  987. return;
  988. }
  989. mode = choice;
  990. }
  991. btnAutoRun.disabled = true;
  992. inputRunCount.disabled = true;
  993. const delayEnabled = inputAutoDelayEnabled.checked;
  994. const delayMinutes = normalizeAutoDelayMinutes(inputAutoDelayMinutes.value);
  995. inputAutoDelayMinutes.value = String(delayMinutes);
  996. btnAutoRun.innerHTML = delayEnabled
  997. ? '<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> 计划中...'
  998. : '<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> 运行中...';
  999. const response = await chrome.runtime.sendMessage({
  1000. type: delayEnabled ? 'SCHEDULE_AUTO_RUN' : 'AUTO_RUN',
  1001. source: 'sidepanel',
  1002. payload: {
  1003. totalRuns,
  1004. delayMinutes,
  1005. autoRunSkipFailures: inputAutoSkipFailures.checked,
  1006. mode,
  1007. },
  1008. });
  1009. if (response?.error) {
  1010. throw new Error(response.error);
  1011. }
  1012. } catch (err) {
  1013. setDefaultAutoRunButton();
  1014. inputRunCount.disabled = false;
  1015. showToast(err.message, 'error');
  1016. }
  1017. });
  1018. btnAutoContinue.addEventListener('click', async () => {
  1019. const email = inputEmail.value.trim();
  1020. if (!email) {
  1021. showToast('请先获取或粘贴邮箱。', 'warn');
  1022. return;
  1023. }
  1024. autoContinueBar.style.display = 'none';
  1025. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  1026. });
  1027. btnAutoRunNow?.addEventListener('click', async () => {
  1028. try {
  1029. btnAutoRunNow.disabled = true;
  1030. await chrome.runtime.sendMessage({ type: 'START_SCHEDULED_AUTO_RUN_NOW', source: 'sidepanel', payload: {} });
  1031. } catch (err) {
  1032. showToast(err.message, 'error');
  1033. } finally {
  1034. btnAutoRunNow.disabled = false;
  1035. }
  1036. });
  1037. btnAutoCancelSchedule?.addEventListener('click', async () => {
  1038. try {
  1039. btnAutoCancelSchedule.disabled = true;
  1040. await chrome.runtime.sendMessage({ type: 'CANCEL_SCHEDULED_AUTO_RUN', source: 'sidepanel', payload: {} });
  1041. showToast('已取消倒计时计划。', 'info', 1800);
  1042. } catch (err) {
  1043. showToast(err.message, 'error');
  1044. } finally {
  1045. btnAutoCancelSchedule.disabled = false;
  1046. }
  1047. });
  1048. // Reset
  1049. btnReset.addEventListener('click', async () => {
  1050. const confirmed = await openConfirmModal({
  1051. title: '重置流程',
  1052. message: '确认重置全部步骤和数据吗?',
  1053. confirmLabel: '确认重置',
  1054. confirmVariant: 'btn-danger',
  1055. });
  1056. if (!confirmed) {
  1057. return;
  1058. }
  1059. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  1060. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES });
  1061. syncAutoRunState({ autoRunning: false, autoRunPhase: 'idle', autoRunCurrentRun: 0, autoRunTotalRuns: 1, autoRunAttemptRun: 0, scheduledAutoRunAt: null });
  1062. displayOauthUrl.textContent = '等待中...';
  1063. displayOauthUrl.classList.remove('has-value');
  1064. displayLocalhostUrl.textContent = '等待中...';
  1065. displayLocalhostUrl.classList.remove('has-value');
  1066. inputEmail.value = '';
  1067. displayStatus.textContent = '就绪';
  1068. statusBar.className = 'status-bar';
  1069. logArea.innerHTML = '';
  1070. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1071. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1072. setDefaultAutoRunButton();
  1073. applyAutoRunStatus(currentAutoRun);
  1074. markSettingsDirty(false);
  1075. updateStopButtonState(false);
  1076. updateButtonStates();
  1077. updateProgressCounter();
  1078. });
  1079. // Clear log
  1080. btnClearLog.addEventListener('click', () => {
  1081. logArea.innerHTML = '';
  1082. });
  1083. // Save settings on change
  1084. inputEmail.addEventListener('change', async () => {
  1085. const email = inputEmail.value.trim();
  1086. if (email) {
  1087. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  1088. }
  1089. });
  1090. inputEmail.addEventListener('input', updateButtonStates);
  1091. inputVpsUrl.addEventListener('input', () => {
  1092. markSettingsDirty(true);
  1093. scheduleSettingsAutoSave();
  1094. });
  1095. inputVpsUrl.addEventListener('blur', () => {
  1096. saveSettings({ silent: true }).catch(() => { });
  1097. });
  1098. inputVpsPassword.addEventListener('input', () => {
  1099. markSettingsDirty(true);
  1100. scheduleSettingsAutoSave();
  1101. });
  1102. inputVpsPassword.addEventListener('blur', () => {
  1103. saveSettings({ silent: true }).catch(() => { });
  1104. });
  1105. inputPassword.addEventListener('input', () => {
  1106. markSettingsDirty(true);
  1107. updateButtonStates();
  1108. scheduleSettingsAutoSave();
  1109. });
  1110. inputPassword.addEventListener('blur', () => {
  1111. saveSettings({ silent: true }).catch(() => { });
  1112. });
  1113. selectMailProvider.addEventListener('change', () => {
  1114. updateMailProviderUI();
  1115. markSettingsDirty(true);
  1116. saveSettings({ silent: true }).catch(() => { });
  1117. });
  1118. selectEmailGenerator.addEventListener('change', () => {
  1119. updateMailProviderUI();
  1120. markSettingsDirty(true);
  1121. saveSettings({ silent: true }).catch(() => { });
  1122. });
  1123. selectCfDomain.addEventListener('change', () => {
  1124. if (selectCfDomain.disabled) {
  1125. return;
  1126. }
  1127. markSettingsDirty(true);
  1128. saveSettings({ silent: true }).catch(() => { });
  1129. });
  1130. btnCfDomainMode.addEventListener('click', async () => {
  1131. try {
  1132. if (!cloudflareDomainEditMode) {
  1133. setCloudflareDomainEditMode(true, { clearInput: true });
  1134. return;
  1135. }
  1136. const newDomain = normalizeCloudflareDomainValue(inputCfDomain.value);
  1137. if (!newDomain) {
  1138. showToast('请输入有效的 Cloudflare 域名。', 'warn');
  1139. inputCfDomain.focus();
  1140. return;
  1141. }
  1142. const { domains } = getCloudflareDomainsFromState();
  1143. await saveCloudflareDomainSettings([...domains, newDomain], newDomain);
  1144. } catch (err) {
  1145. showToast(err.message, 'error');
  1146. }
  1147. });
  1148. inputCfDomain.addEventListener('keydown', (event) => {
  1149. if (event.key === 'Enter') {
  1150. event.preventDefault();
  1151. btnCfDomainMode.click();
  1152. }
  1153. });
  1154. inputInbucketMailbox.addEventListener('input', () => {
  1155. markSettingsDirty(true);
  1156. scheduleSettingsAutoSave();
  1157. });
  1158. inputInbucketMailbox.addEventListener('blur', () => {
  1159. saveSettings({ silent: true }).catch(() => { });
  1160. });
  1161. inputInbucketHost.addEventListener('input', () => {
  1162. markSettingsDirty(true);
  1163. scheduleSettingsAutoSave();
  1164. });
  1165. inputInbucketHost.addEventListener('blur', () => {
  1166. saveSettings({ silent: true }).catch(() => { });
  1167. });
  1168. inputAutoSkipFailures.addEventListener('change', () => {
  1169. markSettingsDirty(true);
  1170. saveSettings({ silent: true }).catch(() => { });
  1171. });
  1172. inputAutoDelayEnabled.addEventListener('change', () => {
  1173. updateAutoDelayInputState();
  1174. markSettingsDirty(true);
  1175. saveSettings({ silent: true }).catch(() => { });
  1176. });
  1177. inputAutoDelayMinutes.addEventListener('input', () => {
  1178. markSettingsDirty(true);
  1179. scheduleSettingsAutoSave();
  1180. });
  1181. inputAutoDelayMinutes.addEventListener('blur', () => {
  1182. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(inputAutoDelayMinutes.value));
  1183. saveSettings({ silent: true }).catch(() => { });
  1184. });
  1185. // ============================================================
  1186. // Listen for Background broadcasts
  1187. // ============================================================
  1188. chrome.runtime.onMessage.addListener((message) => {
  1189. switch (message.type) {
  1190. case 'LOG_ENTRY':
  1191. appendLog(message.payload);
  1192. if (message.payload.level === 'error') {
  1193. showToast(message.payload.message, 'error');
  1194. }
  1195. break;
  1196. case 'STEP_STATUS_CHANGED': {
  1197. const { step, status } = message.payload;
  1198. updateStepUI(step, status);
  1199. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  1200. syncLatestState(state);
  1201. syncAutoRunState(state);
  1202. updateStatusDisplay(latestState);
  1203. updateButtonStates();
  1204. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  1205. syncPasswordField(state);
  1206. if (state.oauthUrl) {
  1207. displayOauthUrl.textContent = state.oauthUrl;
  1208. displayOauthUrl.classList.add('has-value');
  1209. }
  1210. if (state.localhostUrl) {
  1211. displayLocalhostUrl.textContent = state.localhostUrl;
  1212. displayLocalhostUrl.classList.add('has-value');
  1213. }
  1214. }
  1215. }
  1216. ).catch(() => { });
  1217. break;
  1218. }
  1219. case 'AUTO_RUN_RESET': {
  1220. // Full UI reset for next run
  1221. syncLatestState({
  1222. oauthUrl: null,
  1223. localhostUrl: null,
  1224. email: null,
  1225. password: null,
  1226. stepStatuses: STEP_DEFAULT_STATUSES,
  1227. logs: [],
  1228. scheduledAutoRunAt: null,
  1229. });
  1230. displayOauthUrl.textContent = '等待中...';
  1231. displayOauthUrl.classList.remove('has-value');
  1232. displayLocalhostUrl.textContent = '等待中...';
  1233. displayLocalhostUrl.classList.remove('has-value');
  1234. inputEmail.value = '';
  1235. displayStatus.textContent = '就绪';
  1236. statusBar.className = 'status-bar';
  1237. logArea.innerHTML = '';
  1238. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  1239. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  1240. applyAutoRunStatus(currentAutoRun);
  1241. updateProgressCounter();
  1242. updateButtonStates();
  1243. break;
  1244. }
  1245. case 'DATA_UPDATED': {
  1246. syncLatestState(message.payload);
  1247. if (message.payload.email) {
  1248. inputEmail.value = message.payload.email;
  1249. }
  1250. if (message.payload.password !== undefined) {
  1251. inputPassword.value = message.payload.password || '';
  1252. }
  1253. if (message.payload.oauthUrl) {
  1254. displayOauthUrl.textContent = message.payload.oauthUrl;
  1255. displayOauthUrl.classList.add('has-value');
  1256. }
  1257. if (message.payload.localhostUrl) {
  1258. displayLocalhostUrl.textContent = message.payload.localhostUrl;
  1259. displayLocalhostUrl.classList.add('has-value');
  1260. }
  1261. if (message.payload.autoRunDelayEnabled !== undefined) {
  1262. inputAutoDelayEnabled.checked = Boolean(message.payload.autoRunDelayEnabled);
  1263. updateAutoDelayInputState();
  1264. }
  1265. if (message.payload.autoRunDelayMinutes !== undefined) {
  1266. inputAutoDelayMinutes.value = String(normalizeAutoDelayMinutes(message.payload.autoRunDelayMinutes));
  1267. }
  1268. break;
  1269. }
  1270. case 'AUTO_RUN_STATUS': {
  1271. syncLatestState({
  1272. autoRunning: ['scheduled', 'running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  1273. autoRunPhase: message.payload.phase,
  1274. autoRunCurrentRun: message.payload.currentRun,
  1275. autoRunTotalRuns: message.payload.totalRuns,
  1276. autoRunAttemptRun: message.payload.attemptRun,
  1277. scheduledAutoRunAt: message.payload.scheduledAt ?? null,
  1278. });
  1279. applyAutoRunStatus(message.payload);
  1280. updateStatusDisplay(latestState);
  1281. updateButtonStates();
  1282. break;
  1283. }
  1284. }
  1285. });
  1286. // ============================================================
  1287. // Theme Toggle
  1288. // ============================================================
  1289. const btnTheme = document.getElementById('btn-theme');
  1290. function setTheme(theme) {
  1291. document.documentElement.setAttribute('data-theme', theme);
  1292. localStorage.setItem('multipage-theme', theme);
  1293. }
  1294. function initTheme() {
  1295. const saved = localStorage.getItem('multipage-theme');
  1296. if (saved) {
  1297. setTheme(saved);
  1298. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  1299. setTheme('dark');
  1300. }
  1301. }
  1302. btnTheme.addEventListener('click', () => {
  1303. const current = document.documentElement.getAttribute('data-theme');
  1304. setTheme(current === 'dark' ? 'light' : 'dark');
  1305. });
  1306. // ============================================================
  1307. // Init
  1308. // ============================================================
  1309. initializeManualStepActions();
  1310. initTheme();
  1311. updateSaveButtonState();
  1312. restoreState().then(() => {
  1313. syncPasswordToggleLabel();
  1314. syncVpsUrlToggleLabel();
  1315. updateButtonStates();
  1316. updateStatusDisplay(latestState);
  1317. });