sidepanel.js 46 KB

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