sidepanel.js 74 KB

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