sidepanel.js 71 KB

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