GitHubBackupSettings.tsx 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import {
  5. Github,
  6. Play,
  7. Clock,
  8. CheckCircle,
  9. XCircle,
  10. Loader2,
  11. ExternalLink,
  12. RefreshCw,
  13. Download,
  14. Upload,
  15. Database,
  16. History,
  17. SkipForward,
  18. AlertTriangle,
  19. Trash2,
  20. RotateCcw,
  21. FolderArchive,
  22. } from 'lucide-react';
  23. import { api } from '../api/client';
  24. import type {
  25. GitHubBackupConfig,
  26. GitHubBackupConfigCreate,
  27. GitHubBackupLog,
  28. GitHubBackupStatus,
  29. GitHubBackupTriggerResponse,
  30. GitProviderType,
  31. LocalBackupFile,
  32. LocalBackupPathCheck,
  33. LocalBackupStatus,
  34. ScheduleType,
  35. CloudAccountCounts,
  36. CloudAuthStatus,
  37. Printer,
  38. } from '../api/client';
  39. import { Card, CardContent, CardHeader } from './Card';
  40. import { Button } from './Button';
  41. import { Toggle } from './Toggle';
  42. import { ConfirmModal } from './ConfirmModal';
  43. import { useToast } from '../contexts/ToastContext';
  44. import { formatRelativeTime, parseUTCDate } from '../utils/date';
  45. function formatDateTime(dateStr: string | null): string {
  46. if (!dateStr) return '-';
  47. const date = parseUTCDate(dateStr);
  48. if (!date) return '-';
  49. return date.toLocaleString();
  50. }
  51. interface StatusBadgeProps {
  52. status: string | null;
  53. }
  54. function StatusBadge({ status }: StatusBadgeProps) {
  55. if (!status) return null;
  56. const styles: Record<string, string> = {
  57. success: 'bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400',
  58. failed: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400',
  59. skipped: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  60. running: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  61. };
  62. const icons: Record<string, React.ReactNode> = {
  63. success: <CheckCircle className="w-3 h-3" />,
  64. failed: <XCircle className="w-3 h-3" />,
  65. skipped: <SkipForward className="w-3 h-3" />,
  66. running: <Loader2 className="w-3 h-3 animate-spin" />,
  67. };
  68. return (
  69. <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${styles[status] || 'bg-gray-500/20 text-gray-400'}`}>
  70. {icons[status]}
  71. {status.charAt(0).toUpperCase() + status.slice(1)}
  72. </span>
  73. );
  74. }
  75. const PROVIDER_REPO_URL_I18N_KEY: Record<GitProviderType, string> = {
  76. github: 'backup.repoUrlPlaceholderGitHub',
  77. gitea: 'backup.repoUrlPlaceholderGitea',
  78. forgejo: 'backup.repoUrlPlaceholderForgejo',
  79. gitlab: 'backup.repoUrlPlaceholderGitLab',
  80. };
  81. const PROVIDER_TOKEN_PLACEHOLDER: Record<GitProviderType, string> = {
  82. github: 'ghp_xxxxxxxxxxxx',
  83. gitea: 'your_access_token',
  84. forgejo: 'your_access_token',
  85. gitlab: 'glpat-xxxxxxxxxxxx',
  86. };
  87. interface GitHubBackupAutosaveState {
  88. repository_url: string;
  89. branch: string;
  90. provider: GitProviderType;
  91. allow_insecure_http: boolean;
  92. schedule_enabled: boolean;
  93. schedule_type: ScheduleType;
  94. backup_kprofiles: boolean;
  95. backup_cloud_profiles: boolean;
  96. backup_settings: boolean;
  97. backup_spools: boolean;
  98. backup_archives: boolean;
  99. enabled: boolean;
  100. }
  101. function serializeAutosaveState(state: GitHubBackupAutosaveState): string {
  102. return JSON.stringify(state);
  103. }
  104. function getChangedAutosaveFields(
  105. current: GitHubBackupAutosaveState,
  106. previous: GitHubBackupAutosaveState | null
  107. ): Partial<GitHubBackupAutosaveState> {
  108. if (!previous) {
  109. return current;
  110. }
  111. const changes: Partial<GitHubBackupAutosaveState> = {};
  112. for (const key of Object.keys(current) as Array<keyof GitHubBackupAutosaveState>) {
  113. if (current[key] !== previous[key]) {
  114. changes[key] = current[key] as never;
  115. }
  116. }
  117. return changes;
  118. }
  119. export function GitHubBackupSettings() {
  120. const queryClient = useQueryClient();
  121. const { showToast } = useToast();
  122. const { t } = useTranslation();
  123. // Local state for form
  124. const [repoUrl, setRepoUrl] = useState('');
  125. const [accessToken, setAccessToken] = useState('');
  126. const [branch, setBranch] = useState('main');
  127. const [provider, setProvider] = useState<GitProviderType>('github');
  128. const [scheduleEnabled, setScheduleEnabled] = useState(false);
  129. const [scheduleType, setScheduleType] = useState<ScheduleType>('daily');
  130. const [backupKProfiles, setBackupKProfiles] = useState(true);
  131. const [backupCloudProfiles, setBackupCloudProfiles] = useState(true);
  132. const [backupSettings, setBackupSettings] = useState(false);
  133. const [backupSpools, setBackupSpools] = useState(false);
  134. const [backupArchives, setBackupArchives] = useState(false);
  135. const [allowInsecureHttp, setAllowInsecureHttp] = useState(false);
  136. const [enabled, setEnabled] = useState(true);
  137. // Local backup state
  138. const [isExporting, setIsExporting] = useState(false);
  139. const [isRestoring, setIsRestoring] = useState(false);
  140. const [operationStatus, setOperationStatus] = useState<string>('');
  141. const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);
  142. const [restoreFile, setRestoreFile] = useState<File | null>(null);
  143. const [restoreResult, setRestoreResult] = useState<{ success: boolean; message: string } | null>(null);
  144. const fileInputRef = useRef<HTMLInputElement>(null);
  145. // Scheduled local backup state
  146. const [deleteConfirmFile, setDeleteConfirmFile] = useState<string | null>(null);
  147. const [restoreConfirmFile, setRestoreConfirmFile] = useState<string | null>(null);
  148. const [localBackupPath, setLocalBackupPath] = useState('');
  149. const { data: localBackupStatus, refetch: refetchLocalStatus } = useQuery<LocalBackupStatus>({
  150. queryKey: ['local-backup-status'],
  151. queryFn: api.getLocalBackupStatus,
  152. refetchInterval: (query) => query.state.data?.is_running ? 1000 : 10000,
  153. });
  154. const { data: localBackups, refetch: refetchLocalBackups } = useQuery<LocalBackupFile[]>({
  155. queryKey: ['local-backup-files'],
  156. queryFn: api.getLocalBackups,
  157. refetchInterval: 30000,
  158. });
  159. // Probes the output directory with a real write (#2544). A directory the
  160. // service cannot write to — a NAS share outside the systemd unit's
  161. // ReadWritePaths, typically — otherwise only surfaces as a failed backup at
  162. // 03:00, for however many nights it takes someone to notice. Refetched
  163. // explicitly when the path changes or a backup runs, not polled: it writes.
  164. const { data: localBackupPathCheck, refetch: refetchLocalPathCheck } = useQuery<LocalBackupPathCheck>({
  165. queryKey: ['local-backup-path-check'],
  166. queryFn: api.checkLocalBackupPath,
  167. enabled: localBackupStatus?.enabled === true,
  168. refetchOnWindowFocus: false,
  169. });
  170. // Sync local path state from server
  171. useEffect(() => {
  172. if (localBackupStatus?.path !== undefined) {
  173. setLocalBackupPath(localBackupStatus.path);
  174. }
  175. }, [localBackupStatus?.path]);
  176. const triggerLocalBackupMutation = useMutation({
  177. mutationFn: api.triggerLocalBackup,
  178. onSuccess: (data) => {
  179. if (data.success) {
  180. showToast(t('backup.scheduledBackupComplete'));
  181. } else {
  182. showToast(data.message, 'error');
  183. }
  184. refetchLocalStatus();
  185. refetchLocalBackups();
  186. refetchLocalPathCheck();
  187. },
  188. onError: () => showToast(t('backup.scheduledBackupFailed'), 'error'),
  189. });
  190. const deleteLocalBackupMutation = useMutation({
  191. mutationFn: (filename: string) => api.deleteLocalBackup(filename),
  192. onSuccess: () => {
  193. refetchLocalBackups();
  194. setDeleteConfirmFile(null);
  195. },
  196. });
  197. const restoreLocalBackupMutation = useMutation({
  198. mutationFn: async (filename: string) => {
  199. setRestoreConfirmFile(null);
  200. setIsRestoring(true);
  201. setRestoreResult(null);
  202. setOperationStatus(t('backup.restoring'));
  203. return api.restoreLocalBackup(filename);
  204. },
  205. onSuccess: (data) => {
  206. setIsRestoring(false);
  207. setOperationStatus('');
  208. if (data.success) {
  209. setRestoreResult({ success: true, message: data.message });
  210. showToast(t('backup.backupRestoredRestart'), 'success');
  211. } else {
  212. setRestoreResult({ success: false, message: data.message });
  213. showToast(data.message, 'error');
  214. }
  215. },
  216. onError: (e) => {
  217. setIsRestoring(false);
  218. setOperationStatus('');
  219. const msg = e instanceof Error ? e.message : t('backup.failedToRestore');
  220. setRestoreResult({ success: false, message: msg });
  221. showToast(msg, 'error');
  222. },
  223. });
  224. // Block navigation while backup/restore is in progress
  225. useEffect(() => {
  226. const isOperationInProgress = isExporting || isRestoring;
  227. if (isOperationInProgress) {
  228. const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  229. e.preventDefault();
  230. e.returnValue = 'A backup operation is in progress. Are you sure you want to leave?';
  231. return e.returnValue;
  232. };
  233. window.addEventListener('beforeunload', handleBeforeUnload);
  234. return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  235. }
  236. }, [isExporting, isRestoring]);
  237. // Test connection state
  238. const [testLoading, setTestLoading] = useState(false);
  239. const [testResult, setTestResult] = useState<{
  240. success: boolean;
  241. message: string;
  242. isPrivate: boolean | null;
  243. } | null>(null);
  244. // Inline save-error banner — backend rejection messages (e.g. the
  245. // "repository is not private" guard) are far too long for a toast.
  246. // Cleared on success, on the next save attempt, and when the user starts
  247. // editing the repo URL / token / provider so the banner doesn't persist
  248. // after the user has already addressed the cause.
  249. const [saveError, setSaveError] = useState<string | null>(null);
  250. // Auto-save debounce
  251. const settingsAutoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  252. const tokenAutoSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  253. const initializationTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  254. const lastSavedAutosaveStateRef = useRef<GitHubBackupAutosaveState | null>(null);
  255. const lastTokenScheduledForSaveRef = useRef('');
  256. const [isInitialized, setIsInitialized] = useState(false);
  257. const autoSaveState = useMemo<GitHubBackupAutosaveState>(() => ({
  258. repository_url: repoUrl,
  259. branch,
  260. provider,
  261. allow_insecure_http: allowInsecureHttp,
  262. schedule_enabled: scheduleEnabled,
  263. schedule_type: scheduleType,
  264. backup_kprofiles: backupKProfiles,
  265. backup_cloud_profiles: backupCloudProfiles,
  266. backup_settings: backupSettings,
  267. backup_spools: backupSpools,
  268. backup_archives: backupArchives,
  269. enabled,
  270. }), [repoUrl, branch, provider, allowInsecureHttp, scheduleEnabled, scheduleType, backupKProfiles, backupCloudProfiles, backupSettings, backupSpools, backupArchives, enabled]);
  271. const autoSaveStateFingerprint = useMemo(
  272. () => serializeAutosaveState(autoSaveState),
  273. [autoSaveState]
  274. );
  275. // Queries
  276. const { data: config, isLoading: configLoading } = useQuery<GitHubBackupConfig | null>({
  277. queryKey: ['github-backup-config'],
  278. queryFn: api.getGitHubBackupConfig,
  279. });
  280. const { data: status } = useQuery<GitHubBackupStatus>({
  281. queryKey: ['github-backup-status'],
  282. queryFn: api.getGitHubBackupStatus,
  283. refetchInterval: (query) => query.state.data?.is_running ? 500 : 10000, // Poll fast during backup
  284. });
  285. const { data: logs } = useQuery<GitHubBackupLog[]>({
  286. queryKey: ['github-backup-logs'],
  287. queryFn: () => api.getGitHubBackupLogs(20),
  288. });
  289. const { data: cloudStatus } = useQuery<CloudAuthStatus>({
  290. queryKey: ['cloud-status'],
  291. queryFn: api.getCloudStatus,
  292. });
  293. // How many cloud accounts the backup would actually collect from, across
  294. // both Bambu Cloud and Orca Cloud. Not the same question as `cloudStatus`,
  295. // which is only *this viewer's* Bambu sign-in: with auth enabled every user
  296. // holds their own credentials and the backup collects from all of them, so
  297. // an admin who never signed in to Bambu Cloud personally would otherwise see
  298. // the category disabled while there is plenty to back up (#2717).
  299. const { data: cloudAccounts } = useQuery<CloudAccountCounts>({
  300. queryKey: ['github-backup-cloud-accounts'],
  301. queryFn: api.getGitHubBackupCloudAccounts,
  302. staleTime: 60_000,
  303. });
  304. const connectedCloudAccounts = (cloudAccounts?.bambu ?? 0) + (cloudAccounts?.orca ?? 0);
  305. // Until the count arrives, fall back to the viewer's own Bambu status rather
  306. // than rendering the toggle as unavailable and making it flicker enabled.
  307. const anyCloudConnected = cloudAccounts
  308. ? connectedCloudAccounts > 0
  309. : !!cloudStatus?.is_authenticated;
  310. // Fetch printers and their statuses for K-profile availability
  311. const { data: printers } = useQuery<Printer[]>({
  312. queryKey: ['printers'],
  313. queryFn: api.getPrinters,
  314. });
  315. // Fetch printer statuses from API (not just cache) to get accurate connection status
  316. const printerStatusQueries = useQueries({
  317. queries: (printers ?? []).map(printer => ({
  318. queryKey: ['printerStatus', printer.id],
  319. queryFn: () => api.getPrinterStatus(printer.id),
  320. staleTime: 10000, // Consider stale after 10s
  321. refetchInterval: 30000, // Refresh every 30s
  322. })),
  323. });
  324. const printerStatuses = (printers ?? []).map((printer, index) => ({
  325. printer,
  326. connected: printerStatusQueries[index]?.data?.connected ?? false,
  327. }));
  328. const totalPrinters = printerStatuses.length;
  329. const connectedPrinters = printerStatuses.filter(p => p.connected).length;
  330. const noPrintersConnected = totalPrinters > 0 && connectedPrinters === 0;
  331. const somePrintersDisconnected = connectedPrinters > 0 && connectedPrinters < totalPrinters;
  332. // Initialize form from config
  333. useEffect(() => {
  334. if (initializationTimerRef.current) {
  335. clearTimeout(initializationTimerRef.current);
  336. }
  337. if (config) {
  338. setIsInitialized(false);
  339. lastSavedAutosaveStateRef.current = {
  340. repository_url: config.repository_url,
  341. branch: config.branch,
  342. provider: config.provider ?? 'github',
  343. allow_insecure_http: config.allow_insecure_http ?? false,
  344. schedule_enabled: config.schedule_enabled,
  345. schedule_type: config.schedule_type,
  346. backup_kprofiles: config.backup_kprofiles,
  347. backup_cloud_profiles: config.backup_cloud_profiles,
  348. backup_settings: config.backup_settings,
  349. backup_spools: config.backup_spools,
  350. backup_archives: config.backup_archives,
  351. enabled: config.enabled,
  352. };
  353. setRepoUrl(config.repository_url);
  354. setBranch(config.branch);
  355. setProvider(config.provider ?? 'github');
  356. setScheduleEnabled(config.schedule_enabled);
  357. setScheduleType(config.schedule_type);
  358. setBackupKProfiles(config.backup_kprofiles);
  359. setBackupCloudProfiles(config.backup_cloud_profiles);
  360. setBackupSettings(config.backup_settings);
  361. setBackupSpools(config.backup_spools);
  362. setBackupArchives(config.backup_archives);
  363. setAllowInsecureHttp(config.allow_insecure_http ?? false);
  364. setEnabled(config.enabled);
  365. setAccessToken(''); // Don't show stored token
  366. // Mark as initialized after a tick to avoid auto-save on initial load
  367. initializationTimerRef.current = setTimeout(() => { setIsInitialized(true); }, 100);
  368. } else {
  369. setIsInitialized(false);
  370. lastSavedAutosaveStateRef.current = null;
  371. setAccessToken('');
  372. }
  373. return () => {
  374. if (initializationTimerRef.current) {
  375. clearTimeout(initializationTimerRef.current);
  376. }
  377. };
  378. }, [config]);
  379. // Auto-save function for existing configs
  380. const autoSave = useCallback(async (includeToken: boolean = false) => {
  381. if (!config) return; // Only auto-save if config already exists
  382. try {
  383. if (includeToken && accessToken) {
  384. // Full save with new token
  385. await api.saveGitHubBackupConfig({
  386. ...autoSaveState,
  387. access_token: accessToken,
  388. });
  389. setAccessToken(''); // Clear after save
  390. setSaveError(null);
  391. showToast(t('backup.tokenUpdated'));
  392. lastTokenScheduledForSaveRef.current = '';
  393. } else {
  394. // Update without token
  395. await api.updateGitHubBackupConfig(getChangedAutosaveFields(
  396. autoSaveState,
  397. lastSavedAutosaveStateRef.current
  398. ));
  399. setSaveError(null);
  400. showToast(t('backup.settingsSaved'));
  401. }
  402. lastSavedAutosaveStateRef.current = autoSaveState;
  403. queryClient.invalidateQueries({ queryKey: ['github-backup-config'] });
  404. queryClient.invalidateQueries({ queryKey: ['github-backup-status'] });
  405. } catch (error) {
  406. setSaveError((error as Error).message);
  407. }
  408. }, [config, accessToken, autoSaveState, queryClient, showToast, t]);
  409. const autoSaveRef = useRef(autoSave);
  410. useEffect(() => {
  411. autoSaveRef.current = autoSave;
  412. }, [autoSave]);
  413. // Auto-save effect for existing configs (debounced)
  414. useEffect(() => {
  415. if (!isInitialized || !config) return;
  416. if (
  417. lastSavedAutosaveStateRef.current
  418. && autoSaveStateFingerprint === serializeAutosaveState(lastSavedAutosaveStateRef.current)
  419. ) return;
  420. if (settingsAutoSaveTimerRef.current) {
  421. clearTimeout(settingsAutoSaveTimerRef.current);
  422. }
  423. settingsAutoSaveTimerRef.current = setTimeout(() => {
  424. autoSave(false);
  425. }, 500);
  426. return () => {
  427. if (settingsAutoSaveTimerRef.current) {
  428. clearTimeout(settingsAutoSaveTimerRef.current);
  429. }
  430. };
  431. }, [isInitialized, config, autoSaveStateFingerprint, autoSave]);
  432. // Auto-save token when it changes (with longer debounce)
  433. useEffect(() => {
  434. if (!isInitialized || !config || !accessToken) return;
  435. if (accessToken === lastTokenScheduledForSaveRef.current) return;
  436. lastTokenScheduledForSaveRef.current = accessToken;
  437. if (tokenAutoSaveTimerRef.current) {
  438. clearTimeout(tokenAutoSaveTimerRef.current);
  439. }
  440. tokenAutoSaveTimerRef.current = setTimeout(() => {
  441. autoSaveRef.current(true);
  442. }, 1000);
  443. return () => {
  444. if (tokenAutoSaveTimerRef.current) {
  445. clearTimeout(tokenAutoSaveTimerRef.current);
  446. }
  447. };
  448. }, [isInitialized, accessToken, config]);
  449. // Mutations
  450. const saveConfigMutation = useMutation({
  451. mutationFn: (data: GitHubBackupConfigCreate) => api.saveGitHubBackupConfig(data),
  452. onMutate: () => {
  453. setSaveError(null);
  454. },
  455. onSuccess: () => {
  456. queryClient.invalidateQueries({ queryKey: ['github-backup-config'] });
  457. queryClient.invalidateQueries({ queryKey: ['github-backup-status'] });
  458. showToast(t('backup.githubBackupEnabled'));
  459. setAccessToken('');
  460. setIsInitialized(true);
  461. },
  462. onError: (error: Error) => {
  463. setSaveError(error.message);
  464. },
  465. });
  466. const triggerBackupMutation = useMutation<GitHubBackupTriggerResponse, Error>({
  467. mutationFn: api.triggerGitHubBackup,
  468. onSuccess: (result) => {
  469. queryClient.invalidateQueries({ queryKey: ['github-backup-status'] });
  470. queryClient.invalidateQueries({ queryKey: ['github-backup-logs'] });
  471. if (result.success) {
  472. if (result.files_changed > 0) {
  473. showToast(t('backup.backupCompleteFiles', { count: result.files_changed }));
  474. } else {
  475. showToast(t('backup.backupSkippedNoChanges'));
  476. }
  477. } else {
  478. showToast(t('backup.backupFailed2', { message: result.message }), 'error');
  479. }
  480. },
  481. onError: (error: Error) => {
  482. showToast(t('backup.backupFailed2', { message: error.message }), 'error');
  483. },
  484. });
  485. const clearLogsMutation = useMutation<{ deleted: number; message: string }, Error>({
  486. mutationFn: () => api.clearGitHubBackupLogs(0),
  487. onSuccess: (result) => {
  488. queryClient.invalidateQueries({ queryKey: ['github-backup-logs'] });
  489. showToast(t('backup.clearedLogs', { count: result.deleted }));
  490. },
  491. onError: (error: Error) => {
  492. showToast(t('backup.failedToClearLogs', { message: error.message }), 'error');
  493. },
  494. });
  495. const handleTestConnection = async () => {
  496. setTestLoading(true);
  497. setTestResult(null);
  498. try {
  499. let result;
  500. // If user entered a new token, test with those credentials
  501. if (accessToken) {
  502. if (!repoUrl) {
  503. showToast(t('backup.enterRepoUrl'), 'error');
  504. setTestLoading(false);
  505. return;
  506. }
  507. result = await api.testGitHubConnection(repoUrl, accessToken, provider);
  508. } else if (config?.has_token) {
  509. // Use stored credentials
  510. result = await api.testGitHubStoredConnection();
  511. } else {
  512. showToast(t('backup.enterRepoAndToken'), 'error');
  513. setTestLoading(false);
  514. return;
  515. }
  516. setTestResult({
  517. success: result.success,
  518. message: result.message,
  519. isPrivate: result.is_private,
  520. });
  521. } catch (error) {
  522. setTestResult({ success: false, message: (error as Error).message, isPrivate: null });
  523. } finally {
  524. setTestLoading(false);
  525. }
  526. };
  527. // Initial setup save (only for new configs)
  528. const handleInitialSetup = () => {
  529. if (!repoUrl) {
  530. showToast(t('backup.repoRequired'), 'error');
  531. return;
  532. }
  533. if (!accessToken) {
  534. showToast(t('backup.tokenRequired'), 'error');
  535. return;
  536. }
  537. saveConfigMutation.mutate({
  538. repository_url: repoUrl,
  539. access_token: accessToken,
  540. branch,
  541. provider,
  542. allow_insecure_http: allowInsecureHttp,
  543. schedule_enabled: scheduleEnabled,
  544. schedule_type: scheduleType,
  545. backup_kprofiles: backupKProfiles,
  546. backup_cloud_profiles: backupCloudProfiles,
  547. backup_settings: backupSettings,
  548. backup_spools: backupSpools,
  549. backup_archives: backupArchives,
  550. enabled,
  551. });
  552. };
  553. if (configLoading) {
  554. return (
  555. <div className="flex items-center justify-center py-12">
  556. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  557. </div>
  558. );
  559. }
  560. return (
  561. <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
  562. {/* Left Column - Git Backup */}
  563. <div className="space-y-6">
  564. <Card id="card-backup-github">
  565. <CardHeader>
  566. <div className="flex items-center justify-between">
  567. <div className="flex items-center gap-2">
  568. <Github className="w-5 h-5 text-gray-400" />
  569. <h2 className="text-lg font-semibold text-white">{t('backup.githubBackup')}</h2>
  570. </div>
  571. {config && (
  572. <div className="flex items-center gap-2">
  573. <span className="text-sm text-bambu-gray">{t('backup.enabled')}</span>
  574. <Toggle
  575. checked={enabled}
  576. onChange={setEnabled}
  577. />
  578. </div>
  579. )}
  580. </div>
  581. </CardHeader>
  582. <CardContent className="space-y-4">
  583. <p className="text-sm text-bambu-gray">
  584. {t('backup.githubDescription')}
  585. </p>
  586. {/* Provider Selection */}
  587. <div>
  588. <label htmlFor="git-provider-select" className="block text-sm text-bambu-gray mb-1">{t('backup.provider')}</label>
  589. <select
  590. id="git-provider-select"
  591. value={provider}
  592. onChange={(e) => { setProvider(e.target.value as GitProviderType); setTestResult(null); setSaveError(null); }}
  593. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  594. >
  595. <option value="github">{t('backup.providerGitHub')}</option>
  596. <option value="gitlab">{t('backup.providerGitLab')}</option>
  597. <option value="gitea">{t('backup.providerGitea')}</option>
  598. <option value="forgejo">{t('backup.providerForgejo')}</option>
  599. </select>
  600. </div>
  601. {/* Repository URL */}
  602. <div>
  603. <label className="block text-sm text-bambu-gray mb-1">
  604. {t('backup.repositoryUrl')}
  605. </label>
  606. <input
  607. type="text"
  608. value={repoUrl}
  609. onChange={(e) => { setRepoUrl(e.target.value); setTestResult(null); setSaveError(null); }}
  610. placeholder={t(PROVIDER_REPO_URL_I18N_KEY[provider])}
  611. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  612. />
  613. <label className="flex items-start gap-2 mt-2 cursor-pointer">
  614. <input
  615. type="checkbox"
  616. checked={allowInsecureHttp}
  617. onChange={(e) => { setAllowInsecureHttp(e.target.checked); setTestResult(null); }}
  618. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  619. />
  620. <div>
  621. <span className="text-sm text-white">{t('backup.allowInsecureHttp')}</span>
  622. <p className="text-xs text-bambu-gray">{t('backup.allowInsecureHttpHint')}</p>
  623. </div>
  624. </label>
  625. </div>
  626. {/* Access Token */}
  627. <div>
  628. <label className="block text-sm text-bambu-gray mb-1">
  629. {t('backup.personalAccessToken')} {config?.has_token && <span className="text-green-700 dark:text-green-400">{t('backup.tokenSaved')}</span>}
  630. </label>
  631. <input
  632. type="password"
  633. value={accessToken}
  634. onChange={(e) => { setAccessToken(e.target.value); setTestResult(null); setSaveError(null); }}
  635. placeholder={config?.has_token ? t('backup.enterNewToken') : PROVIDER_TOKEN_PLACEHOLDER[provider]}
  636. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  637. />
  638. <p className="text-xs text-bambu-gray mt-1">
  639. {t('backup.tokenHint')}
  640. </p>
  641. </div>
  642. {/* Branch - inline with schedule */}
  643. <div className="grid grid-cols-2 gap-4">
  644. <div>
  645. <label className="block text-sm text-bambu-gray mb-1">{t('backup.branch')}</label>
  646. <input
  647. type="text"
  648. value={branch}
  649. onChange={(e) => setBranch(e.target.value)}
  650. placeholder="main"
  651. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  652. />
  653. </div>
  654. <div>
  655. <label className="block text-sm text-bambu-gray mb-1">{t('backup.autoBackup')}</label>
  656. <select
  657. value={scheduleEnabled ? scheduleType : 'disabled'}
  658. onChange={(e) => {
  659. if (e.target.value === 'disabled') {
  660. setScheduleEnabled(false);
  661. } else {
  662. setScheduleEnabled(true);
  663. setScheduleType(e.target.value as ScheduleType);
  664. }
  665. }}
  666. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  667. >
  668. <option value="disabled">{t('backup.manualOnly')}</option>
  669. <option value="hourly">{t('backup.hourly')}</option>
  670. <option value="daily">{t('backup.daily')}</option>
  671. <option value="weekly">{t('backup.weekly')}</option>
  672. </select>
  673. </div>
  674. </div>
  675. {/* What to backup */}
  676. <div>
  677. <label className="block text-sm text-bambu-gray mb-2">{t('backup.includeInBackup')}</label>
  678. <div className="space-y-2">
  679. <label className={`flex items-start gap-2 ${noPrintersConnected ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}>
  680. <input
  681. type="checkbox"
  682. checked={backupKProfiles}
  683. onChange={(e) => setBackupKProfiles(e.target.checked)}
  684. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  685. disabled={noPrintersConnected}
  686. />
  687. <div className="flex-1">
  688. <div className="flex items-center gap-2">
  689. <span className={`text-sm ${noPrintersConnected ? 'text-bambu-gray' : 'text-white'}`}>{t('backup.kProfiles')}</span>
  690. {noPrintersConnected && (
  691. <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
  692. <AlertTriangle className="w-3 h-3" />
  693. {t('backup.noPrintersConnected')}
  694. </span>
  695. )}
  696. {somePrintersDisconnected && (
  697. <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
  698. <AlertTriangle className="w-3 h-3" />
  699. {t('backup.printersConnected', { connected: connectedPrinters, total: totalPrinters })}
  700. </span>
  701. )}
  702. </div>
  703. <p className="text-xs text-bambu-gray">{t('backup.kProfilesDescription')}</p>
  704. </div>
  705. </label>
  706. <label className={`flex items-start gap-2 ${!anyCloudConnected ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`}>
  707. <input
  708. type="checkbox"
  709. checked={backupCloudProfiles}
  710. onChange={(e) => setBackupCloudProfiles(e.target.checked)}
  711. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  712. disabled={!anyCloudConnected}
  713. />
  714. <div>
  715. <div className="flex items-center gap-2">
  716. <span className={`text-sm ${anyCloudConnected ? 'text-white' : 'text-bambu-gray'}`}>{t('backup.cloudProfiles')}</span>
  717. {!anyCloudConnected && (
  718. <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
  719. <AlertTriangle className="w-3 h-3" />
  720. {t('backup.cloudLoginRequiredShort')}
  721. </span>
  722. )}
  723. </div>
  724. <p className="text-xs text-bambu-gray">{t('backup.cloudProfilesDescription')}</p>
  725. {/* Say how many accounts are in scope. On a multi-user
  726. install the presets being backed up are other people's,
  727. and the count is the only honest way to show that
  728. without naming them. */}
  729. {connectedCloudAccounts > 0 && (
  730. <p className="text-xs text-bambu-gray mt-0.5">
  731. {t('backup.cloudProfilesAccounts', {
  732. bambu: cloudAccounts?.bambu ?? 0,
  733. orca: cloudAccounts?.orca ?? 0,
  734. })}
  735. </p>
  736. )}
  737. </div>
  738. </label>
  739. <label className="flex items-start gap-2 cursor-pointer">
  740. <input
  741. type="checkbox"
  742. checked={backupSettings}
  743. onChange={(e) => setBackupSettings(e.target.checked)}
  744. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  745. />
  746. <div>
  747. <span className="text-white text-sm">{t('backup.appSettings')}</span>
  748. <p className="text-xs text-bambu-gray">{t('backup.appSettingsDescription')}</p>
  749. </div>
  750. </label>
  751. <label className="flex items-start gap-2 cursor-pointer">
  752. <input
  753. type="checkbox"
  754. checked={backupSpools}
  755. onChange={(e) => setBackupSpools(e.target.checked)}
  756. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  757. />
  758. <div>
  759. <span className="text-white text-sm">{t('backup.spoolInventory')}</span>
  760. <p className="text-xs text-bambu-gray">{t('backup.spoolInventoryDescription')}</p>
  761. </div>
  762. </label>
  763. <label className="flex items-start gap-2 cursor-pointer">
  764. <input
  765. type="checkbox"
  766. checked={backupArchives}
  767. onChange={(e) => setBackupArchives(e.target.checked)}
  768. className="w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  769. />
  770. <div>
  771. <span className="text-white text-sm">{t('backup.printArchives')}</span>
  772. <p className="text-xs text-bambu-gray">{t('backup.printArchivesDescription')}</p>
  773. </div>
  774. </label>
  775. </div>
  776. </div>
  777. {/* Test + Status + Actions */}
  778. <div className="border-t border-bambu-dark-tertiary pt-4 space-y-3">
  779. {/* Status line */}
  780. {status?.configured && (
  781. <div className="flex items-center justify-between text-sm">
  782. <div className="flex items-center gap-2 text-bambu-gray">
  783. {status.last_backup_at ? (
  784. <>
  785. <span>{t('backup.lastBackupAt')} {formatRelativeTime(status.last_backup_at, 'system', t)}</span>
  786. <StatusBadge status={status.last_backup_status} />
  787. </>
  788. ) : (
  789. <span>{t('backup.noBackupsYet')}</span>
  790. )}
  791. </div>
  792. {status.next_scheduled_run && (
  793. <span className="text-bambu-gray">
  794. <Clock className="w-3 h-3 inline mr-1" />
  795. {t('backup.next')} {formatRelativeTime(status.next_scheduled_run, 'system', t)}
  796. </span>
  797. )}
  798. </div>
  799. )}
  800. {/* Save error — inline banner. Keeps long backend rejection
  801. messages (e.g. the "repository is not private" guard)
  802. readable instead of clipped to a toast. */}
  803. {saveError && (
  804. <div className="text-sm text-red-700 dark:text-red-400 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded p-3 flex items-start gap-2">
  805. <XCircle className="w-4 h-4 mt-0.5 shrink-0" />
  806. <div className="flex-1 leading-relaxed whitespace-pre-wrap break-words">{saveError}</div>
  807. <button
  808. type="button"
  809. onClick={() => setSaveError(null)}
  810. className="text-bambu-gray hover:text-white shrink-0"
  811. aria-label={t('common.dismiss', 'Dismiss')}
  812. >
  813. <XCircle className="w-4 h-4" />
  814. </button>
  815. </div>
  816. )}
  817. {/* Test result */}
  818. {testResult && (
  819. <div className="space-y-1.5">
  820. <div className={`text-sm flex items-center gap-1 ${testResult.success ? 'text-green-700 dark:text-green-400' : 'text-red-700 dark:text-red-400'}`}>
  821. {testResult.success ? <CheckCircle className="w-4 h-4" /> : <XCircle className="w-4 h-4" />}
  822. {testResult.message}
  823. </div>
  824. {testResult.success && testResult.isPrivate === true && (
  825. <div className="text-xs flex items-center gap-1 text-green-700 dark:text-green-400">
  826. <CheckCircle className="w-3.5 h-3.5" />
  827. {t('backup.repoIsPrivate', 'Repository is private — safe to back up to.')}
  828. </div>
  829. )}
  830. {testResult.success && testResult.isPrivate === false && (
  831. <div className="text-xs text-red-700 dark:text-red-400 bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded p-2 flex items-start gap-1.5">
  832. <XCircle className="w-4 h-4 mt-0.5 shrink-0" />
  833. <span>
  834. {t(
  835. 'backup.repoIsPublicWarning',
  836. 'Repository is PUBLIC. Bambuddy backups include MQTT credentials, Home Assistant tokens, Prometheus tokens, your Bambu Cloud email, and printer access codes via K-profiles. Saving is blocked until you make the repository private in your provider\'s settings.',
  837. )}
  838. </span>
  839. </div>
  840. )}
  841. {testResult.success && testResult.isPrivate === null && (
  842. <div className="text-xs text-yellow-700 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30 rounded p-2 flex items-start gap-1.5">
  843. <XCircle className="w-4 h-4 mt-0.5 shrink-0" />
  844. <span>
  845. {t(
  846. 'backup.repoVisibilityUnknown',
  847. 'Could not determine repository visibility. Bambuddy refuses to back up to anything not confirmed private; saving will be blocked.',
  848. )}
  849. </span>
  850. </div>
  851. )}
  852. </div>
  853. )}
  854. {/* Action buttons */}
  855. <div className="flex flex-wrap items-center gap-2">
  856. {status?.configured ? (
  857. <>
  858. {(triggerBackupMutation.isPending || status.is_running) ? (
  859. <div className="flex items-center gap-2 text-bambu-green">
  860. <Loader2 className="w-4 h-4 animate-spin" />
  861. <span className="text-sm">{status.progress || t('backup.startingBackup')}</span>
  862. </div>
  863. ) : (
  864. <>
  865. <Button
  866. variant="primary"
  867. size="sm"
  868. onClick={() => triggerBackupMutation.mutate()}
  869. disabled={!config?.enabled}
  870. >
  871. <Play className="w-4 h-4" />
  872. {t('backup.backupNow')}
  873. </Button>
  874. <Button
  875. variant="secondary"
  876. size="sm"
  877. onClick={handleTestConnection}
  878. disabled={testLoading}
  879. >
  880. {testLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
  881. {t('backup.test')}
  882. </Button>
  883. </>
  884. )}
  885. </>
  886. ) : (
  887. <>
  888. <Button
  889. variant="primary"
  890. size="sm"
  891. onClick={handleInitialSetup}
  892. disabled={saveConfigMutation.isPending || !repoUrl || !accessToken}
  893. >
  894. {saveConfigMutation.isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
  895. {t('backup.enableBackup')}
  896. </Button>
  897. <Button
  898. variant="secondary"
  899. size="sm"
  900. onClick={handleTestConnection}
  901. disabled={testLoading || !repoUrl || !accessToken}
  902. >
  903. {testLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
  904. {t('backup.testConnection')}
  905. </Button>
  906. </>
  907. )}
  908. </div>
  909. </div>
  910. </CardContent>
  911. </Card>
  912. {/* Backup History - only show if configured and has logs */}
  913. {logs && logs.length > 0 && (
  914. <Card id="card-backup-history">
  915. <CardHeader>
  916. <div className="flex items-center justify-between">
  917. <div className="flex items-center gap-2">
  918. <History className="w-5 h-5 text-gray-400" />
  919. <h2 className="text-lg font-semibold text-white">{t('backup.history')}</h2>
  920. </div>
  921. <Button
  922. variant="ghost"
  923. size="sm"
  924. onClick={() => clearLogsMutation.mutate()}
  925. disabled={clearLogsMutation.isPending}
  926. >
  927. <Trash2 className="w-4 h-4" />
  928. {t('backup.clear')}
  929. </Button>
  930. </div>
  931. </CardHeader>
  932. <CardContent>
  933. <div className="overflow-x-auto">
  934. <table className="w-full text-sm">
  935. <thead>
  936. <tr className="text-bambu-gray border-b border-bambu-dark-tertiary">
  937. <th className="text-left py-2 px-2">{t('backup.date')}</th>
  938. <th className="text-left py-2 px-2">{t('backup.status')}</th>
  939. <th className="text-left py-2 px-2">{t('backup.commit')}</th>
  940. </tr>
  941. </thead>
  942. <tbody>
  943. {logs.slice(0, 10).map((log) => (
  944. <tr key={log.id} className="border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary">
  945. <td className="py-2 px-2 text-white">{formatDateTime(log.started_at)}</td>
  946. <td className="py-2 px-2"><StatusBadge status={log.status} /></td>
  947. <td className="py-2 px-2">
  948. {log.commit_sha ? (
  949. <a
  950. href={`${config?.repository_url}/commit/${log.commit_sha}`}
  951. target="_blank"
  952. rel="noopener noreferrer"
  953. className="text-bambu-green hover:underline inline-flex items-center gap-1"
  954. >
  955. {log.commit_sha.substring(0, 7)}
  956. <ExternalLink className="w-3 h-3" />
  957. </a>
  958. ) : (
  959. <span className="text-bambu-gray">-</span>
  960. )}
  961. </td>
  962. </tr>
  963. ))}
  964. </tbody>
  965. </table>
  966. </div>
  967. </CardContent>
  968. </Card>
  969. )}
  970. </div>
  971. {/* Right Column - Local Backup */}
  972. <div className="space-y-6">
  973. <Card id="card-backup-local">
  974. <CardHeader>
  975. <div className="flex items-center gap-2">
  976. <Database className="w-5 h-5 text-gray-400" />
  977. <h2 className="text-lg font-semibold text-white">{t('backup.localBackup')}</h2>
  978. </div>
  979. </CardHeader>
  980. <CardContent className="space-y-4">
  981. <p className="text-sm text-bambu-gray">
  982. {t('backup.localBackupDescription')}
  983. </p>
  984. {/* Export */}
  985. <div className="flex items-center justify-between py-3 border-b border-bambu-dark-tertiary">
  986. <div>
  987. <p className="text-white">{t('backup.downloadBackupLabel')}</p>
  988. <p className="text-sm text-bambu-gray">
  989. {t('backup.completeBackupZip')}
  990. </p>
  991. </div>
  992. <Button
  993. variant="secondary"
  994. size="sm"
  995. disabled={isExporting || isRestoring}
  996. onClick={async () => {
  997. setIsExporting(true);
  998. setOperationStatus(t('backup.preparingBackup'));
  999. try {
  1000. setOperationStatus(t('backup.creatingArchive'));
  1001. const { blob, filename } = await api.exportBackup();
  1002. setOperationStatus(t('backup.downloadingFile'));
  1003. const url = URL.createObjectURL(blob);
  1004. const a = document.createElement('a');
  1005. a.href = url;
  1006. a.download = filename;
  1007. a.click();
  1008. URL.revokeObjectURL(url);
  1009. showToast(t('backup.backupDownloaded'));
  1010. } catch (e) {
  1011. showToast(t('backup.failedToCreateBackup', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1012. } finally {
  1013. setIsExporting(false);
  1014. setOperationStatus('');
  1015. }
  1016. }}
  1017. >
  1018. <Download className="w-4 h-4" />
  1019. {t('backup.download')}
  1020. </Button>
  1021. </div>
  1022. {/* Import */}
  1023. <div className="flex items-center justify-between py-3 border-b border-bambu-dark-tertiary">
  1024. <div>
  1025. <p className="text-white">{t('backup.restoreBackup')}</p>
  1026. <p className="text-sm text-bambu-gray">
  1027. {t('backup.restoreDescription')}
  1028. </p>
  1029. <p className="text-xs text-bambu-gray-light mt-1">
  1030. {t('backup.restoreNote')}
  1031. </p>
  1032. </div>
  1033. <input
  1034. ref={fileInputRef}
  1035. type="file"
  1036. accept=".zip"
  1037. className="hidden"
  1038. onChange={(e) => {
  1039. const file = e.target.files?.[0];
  1040. if (file) {
  1041. setRestoreFile(file);
  1042. setShowRestoreConfirm(true);
  1043. }
  1044. e.target.value = '';
  1045. }}
  1046. />
  1047. <Button
  1048. variant="secondary"
  1049. size="sm"
  1050. disabled={isRestoring || isExporting}
  1051. onClick={() => fileInputRef.current?.click()}
  1052. >
  1053. <Upload className="w-4 h-4" />
  1054. {t('backup.restore')}
  1055. </Button>
  1056. </div>
  1057. {/* Restore result message */}
  1058. {restoreResult && (
  1059. <div className={`p-3 rounded-lg ${restoreResult.success ? 'bg-green-50 dark:bg-green-500/10 border border-green-300 dark:border-green-500/30' : 'bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30'}`}>
  1060. <div className="flex items-start gap-2 text-sm">
  1061. {restoreResult.success ? (
  1062. <CheckCircle className="w-4 h-4 text-green-600 dark:text-green-400 mt-0.5 flex-shrink-0" />
  1063. ) : (
  1064. <XCircle className="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  1065. )}
  1066. <div className={restoreResult.success ? 'text-green-800 dark:text-green-200' : 'text-red-800 dark:text-red-200'}>
  1067. {restoreResult.message}
  1068. {restoreResult.success && (
  1069. <div className="mt-2">
  1070. <Button
  1071. size="sm"
  1072. onClick={() => window.location.reload()}
  1073. >
  1074. <RotateCcw className="w-3 h-3" />
  1075. {t('backup.reloadNow')}
  1076. </Button>
  1077. </div>
  1078. )}
  1079. </div>
  1080. </div>
  1081. </div>
  1082. )}
  1083. {/* Warning */}
  1084. <div className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1085. <div className="flex items-start gap-2 text-sm">
  1086. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1087. <div className="text-yellow-800 dark:text-yellow-200">
  1088. <span className="font-medium">{t('backup.restoreReplacesAll')}</span>{' '}
  1089. <span className="text-yellow-800/80 dark:text-yellow-200/70">{t('backup.restoreReplacesAllDetail')}</span>
  1090. </div>
  1091. </div>
  1092. </div>
  1093. </CardContent>
  1094. </Card>
  1095. {/* Scheduled Local Backups */}
  1096. <Card id="card-backup-scheduled">
  1097. <CardHeader>
  1098. <div className="flex items-center justify-between">
  1099. <div className="flex items-center gap-2">
  1100. <FolderArchive className="w-5 h-5 text-gray-400" />
  1101. <h2 className="text-lg font-semibold text-white">{t('backup.scheduledBackup')}</h2>
  1102. </div>
  1103. <Toggle
  1104. checked={localBackupStatus?.enabled ?? false}
  1105. onChange={async (checked) => {
  1106. try {
  1107. await api.updateSettings({ local_backup_enabled: checked });
  1108. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1109. showToast(t('backup.settingsSaved'));
  1110. } catch (e) {
  1111. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1112. }
  1113. refetchLocalStatus();
  1114. }}
  1115. />
  1116. </div>
  1117. </CardHeader>
  1118. <CardContent className="space-y-4">
  1119. <p className="text-sm text-bambu-gray">
  1120. {t('backup.scheduledBackupDescription')}
  1121. </p>
  1122. {localBackupStatus?.enabled && (
  1123. <>
  1124. {/* Schedule + Time + Retention */}
  1125. <div className="grid grid-cols-3 gap-4">
  1126. <div>
  1127. <label className="block text-sm text-bambu-gray mb-1">{t('backup.frequency')}</label>
  1128. <select
  1129. value={localBackupStatus?.schedule ?? 'daily'}
  1130. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1131. onChange={async (e) => {
  1132. try {
  1133. await api.updateSettings({ local_backup_schedule: e.target.value });
  1134. showToast(t('backup.settingsSaved'));
  1135. } catch (e) {
  1136. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1137. }
  1138. refetchLocalStatus();
  1139. }}
  1140. >
  1141. <option value="hourly">{t('backup.hourly')}</option>
  1142. <option value="daily">{t('backup.daily')}</option>
  1143. <option value="weekly">{t('backup.weekly')}</option>
  1144. </select>
  1145. </div>
  1146. {(localBackupStatus?.schedule ?? 'daily') !== 'hourly' && (
  1147. <div>
  1148. <label className="block text-sm text-bambu-gray mb-1">{t('backup.backupTime')}</label>
  1149. <input
  1150. type="time"
  1151. value={localBackupStatus?.time ?? '03:00'}
  1152. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none [color-scheme:dark]"
  1153. onChange={async (e) => {
  1154. try {
  1155. await api.updateSettings({ local_backup_time: e.target.value });
  1156. showToast(t('backup.settingsSaved'));
  1157. } catch (err) {
  1158. showToast(t('backup.failedToSave', { message: err instanceof Error ? err.message : 'Unknown error' }), 'error');
  1159. }
  1160. refetchLocalStatus();
  1161. }}
  1162. />
  1163. <p className="text-xs text-bambu-gray-light mt-1">
  1164. {t('backup.localTimeHint', { tz: localBackupStatus?.timezone || 'UTC' })}
  1165. </p>
  1166. </div>
  1167. )}
  1168. <div>
  1169. <label className="block text-sm text-bambu-gray mb-1">{t('backup.retention')}</label>
  1170. <input
  1171. type="number"
  1172. min={1}
  1173. max={100}
  1174. value={localBackupStatus?.retention ?? 5}
  1175. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1176. onChange={async (e) => {
  1177. const val = Math.max(1, Math.min(100, parseInt(e.target.value) || 5));
  1178. try {
  1179. await api.updateSettings({ local_backup_retention: val });
  1180. showToast(t('backup.settingsSaved'));
  1181. } catch (e) {
  1182. showToast(t('backup.failedToSave', { message: e instanceof Error ? e.message : 'Unknown error' }), 'error');
  1183. }
  1184. refetchLocalStatus();
  1185. }}
  1186. />
  1187. <p className="text-xs text-bambu-gray-light mt-1">{t('backup.retentionDescription')}</p>
  1188. </div>
  1189. </div>
  1190. {/* Output Path */}
  1191. <div>
  1192. <label className="block text-sm text-bambu-gray mb-1">{t('backup.outputPath')}</label>
  1193. <input
  1194. type="text"
  1195. value={localBackupPath}
  1196. onChange={(e) => setLocalBackupPath(e.target.value)}
  1197. className="w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1198. onBlur={async () => {
  1199. try {
  1200. await api.updateSettings({ local_backup_path: localBackupPath });
  1201. showToast(t('backup.settingsSaved'));
  1202. } catch (err) {
  1203. showToast(t('backup.failedToSave', { message: err instanceof Error ? err.message : 'Unknown error' }), 'error');
  1204. }
  1205. refetchLocalStatus();
  1206. refetchLocalBackups();
  1207. refetchLocalPathCheck();
  1208. }}
  1209. onKeyDown={(e) => {
  1210. if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
  1211. }}
  1212. />
  1213. <p className="text-xs text-bambu-gray-light mt-1">
  1214. {localBackupPath
  1215. ? t('backup.outputPathDescription')
  1216. : <>{t('backup.defaultPathLabel')} <code className="text-bambu-gray">{localBackupStatus?.default_path || '...'}</code></>
  1217. }
  1218. </p>
  1219. {/* The directory cannot be written to — say why, and how to fix it (#2544) */}
  1220. {localBackupPathCheck && !localBackupPathCheck.writable && (
  1221. <div className="mt-2 p-3 rounded-lg bg-red-50 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30">
  1222. <div className="flex items-start gap-2 text-sm">
  1223. <AlertTriangle className="w-4 h-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
  1224. <div className="min-w-0 text-red-800 dark:text-red-200">
  1225. <p className="font-medium">{t('backup.pathCheck.title')}</p>
  1226. <p className="mt-1 text-red-800/80 dark:text-red-200/80">
  1227. {t(`backup.pathCheck.${localBackupPathCheck.code}`, {
  1228. path: localBackupPathCheck.path,
  1229. defaultValue: localBackupPathCheck.message,
  1230. })}
  1231. </p>
  1232. {localBackupPathCheck.remedy && (
  1233. <>
  1234. <p className="mt-2 font-medium">{t('backup.pathCheck.howToFix')}</p>
  1235. <pre className="mt-1 p-2 rounded bg-black/10 dark:bg-black/40 text-xs whitespace-pre-wrap break-words">
  1236. {localBackupPathCheck.remedy}
  1237. </pre>
  1238. </>
  1239. )}
  1240. {localBackupPathCheck.detail && (
  1241. <p className="mt-2 text-xs text-red-800/60 dark:text-red-200/60 break-words">
  1242. {localBackupPathCheck.detail}
  1243. </p>
  1244. )}
  1245. </div>
  1246. </div>
  1247. </div>
  1248. )}
  1249. {/* Writable, but only inside the container — the backups die with it */}
  1250. {localBackupPathCheck?.writable && localBackupPathCheck.warning === 'container_ephemeral' && (
  1251. <div className="mt-2 p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1252. <div className="flex items-start gap-2 text-sm">
  1253. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1254. <div className="min-w-0 text-yellow-800 dark:text-yellow-200">
  1255. <p className="font-medium">{t('backup.pathCheck.ephemeralTitle')}</p>
  1256. <p className="mt-1 text-yellow-800/80 dark:text-yellow-200/80">
  1257. {t('backup.pathCheck.container_ephemeral', { path: localBackupPathCheck.path })}
  1258. </p>
  1259. {localBackupPathCheck.remedy && (
  1260. <pre className="mt-1 p-2 rounded bg-black/10 dark:bg-black/40 text-xs whitespace-pre-wrap break-words">
  1261. {localBackupPathCheck.remedy}
  1262. </pre>
  1263. )}
  1264. </div>
  1265. </div>
  1266. </div>
  1267. )}
  1268. </div>
  1269. {/* Status + Run Now */}
  1270. <div className="flex items-center justify-between py-3 border-t border-bambu-dark-tertiary">
  1271. <div className="text-sm">
  1272. {localBackupStatus?.last_backup_at && (
  1273. <div className="flex items-center gap-2 text-bambu-gray">
  1274. <span>{t('backup.lastBackup')}:</span>
  1275. <StatusBadge status={localBackupStatus.last_status} />
  1276. <span>{formatRelativeTime(localBackupStatus.last_backup_at)}</span>
  1277. </div>
  1278. )}
  1279. {localBackupStatus?.next_run && (
  1280. <div className="text-bambu-gray mt-1">
  1281. <span>{t('backup.nextBackup')}: </span>
  1282. <span>{formatDateTime(localBackupStatus.next_run)}</span>
  1283. </div>
  1284. )}
  1285. </div>
  1286. <Button
  1287. variant="secondary"
  1288. size="sm"
  1289. disabled={localBackupStatus?.is_running || triggerLocalBackupMutation.isPending}
  1290. onClick={() => triggerLocalBackupMutation.mutate()}
  1291. >
  1292. {localBackupStatus?.is_running || triggerLocalBackupMutation.isPending ? (
  1293. <Loader2 className="w-4 h-4 animate-spin" />
  1294. ) : (
  1295. <Play className="w-4 h-4" />
  1296. )}
  1297. {localBackupStatus?.is_running ? t('backup.backupRunning') : t('backup.runNow')}
  1298. </Button>
  1299. </div>
  1300. {/* Backup Files List */}
  1301. {localBackups && localBackups.length > 0 && (
  1302. <div className="border-t border-bambu-dark-tertiary pt-3">
  1303. <h3 className="text-sm font-medium text-white mb-2">{t('backup.backupFiles')}</h3>
  1304. <div className="space-y-1">
  1305. {localBackups.map((file) => (
  1306. <div key={file.filename} className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm">
  1307. <div className="flex-1 min-w-0">
  1308. <span className="text-white truncate block">{file.filename}</span>
  1309. <span className="text-bambu-gray text-xs">
  1310. {(file.size / 1024 / 1024).toFixed(1)} MB &middot; {formatDateTime(file.created_at)}
  1311. </span>
  1312. </div>
  1313. <div className="flex items-center gap-1 flex-shrink-0">
  1314. <button
  1315. className="text-bambu-gray hover:text-bambu-green p-1"
  1316. title={t('backup.download')}
  1317. onClick={async () => {
  1318. try {
  1319. const { blob, filename: fname } = await api.downloadLocalBackup(file.filename);
  1320. const url = URL.createObjectURL(blob);
  1321. const a = document.createElement('a');
  1322. a.href = url;
  1323. a.download = fname;
  1324. a.click();
  1325. URL.revokeObjectURL(url);
  1326. } catch {
  1327. showToast(t('backup.scheduledBackupFailed'), 'error');
  1328. }
  1329. }}
  1330. >
  1331. <Download className="w-3.5 h-3.5" />
  1332. </button>
  1333. <button
  1334. className="text-bambu-gray hover:text-yellow-600 dark:hover:text-yellow-400 p-1"
  1335. title={t('backup.restore')}
  1336. onClick={() => setRestoreConfirmFile(file.filename)}
  1337. >
  1338. <RotateCcw className="w-3.5 h-3.5" />
  1339. </button>
  1340. <button
  1341. className="text-bambu-gray hover:text-red-600 dark:hover:text-red-400 p-1"
  1342. onClick={() => setDeleteConfirmFile(file.filename)}
  1343. title={t('backup.deleteBackup')}
  1344. >
  1345. <Trash2 className="w-3.5 h-3.5" />
  1346. </button>
  1347. </div>
  1348. </div>
  1349. ))}
  1350. </div>
  1351. </div>
  1352. )}
  1353. {localBackups && localBackups.length === 0 && (
  1354. <p className="text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary">
  1355. {t('backup.noScheduledBackups')}
  1356. </p>
  1357. )}
  1358. </>
  1359. )}
  1360. </CardContent>
  1361. </Card>
  1362. </div>
  1363. {/* Delete Backup Confirmation Modal */}
  1364. {deleteConfirmFile && (
  1365. <ConfirmModal
  1366. title={t('backup.deleteBackup')}
  1367. message={t('backup.deleteBackupConfirm')}
  1368. confirmText={t('backup.deleteBackup')}
  1369. variant="danger"
  1370. onConfirm={() => deleteLocalBackupMutation.mutate(deleteConfirmFile)}
  1371. onCancel={() => setDeleteConfirmFile(null)}
  1372. />
  1373. )}
  1374. {/* Restore from Scheduled Backup Confirmation Modal */}
  1375. {restoreConfirmFile && (
  1376. <ConfirmModal
  1377. title={t('backup.restoreConfirmTitle')}
  1378. message={t('backup.restoreConfirmMessage', { filename: restoreConfirmFile })}
  1379. confirmText={t('backup.restoreConfirmButton')}
  1380. variant="danger"
  1381. onConfirm={() => restoreLocalBackupMutation.mutate(restoreConfirmFile)}
  1382. onCancel={() => setRestoreConfirmFile(null)}
  1383. />
  1384. )}
  1385. {/* Restore Confirmation Modal */}
  1386. {showRestoreConfirm && restoreFile && (
  1387. <ConfirmModal
  1388. title={t('backup.restoreConfirmTitle')}
  1389. message={t('backup.restoreConfirmMessage', { filename: restoreFile.name })}
  1390. confirmText={t('backup.restoreConfirmButton')}
  1391. variant="danger"
  1392. onConfirm={async () => {
  1393. setShowRestoreConfirm(false);
  1394. setIsRestoring(true);
  1395. setRestoreResult(null);
  1396. try {
  1397. setOperationStatus(t('backup.uploadingFile'));
  1398. const result = await api.importBackup(restoreFile);
  1399. setRestoreResult(result);
  1400. if (result.success) {
  1401. showToast(t('backup.backupRestoredRestart'), 'success');
  1402. } else {
  1403. showToast(result.message, 'error');
  1404. }
  1405. } catch (e) {
  1406. const message = e instanceof Error ? e.message : t('backup.failedToRestore');
  1407. setRestoreResult({ success: false, message });
  1408. showToast(message, 'error');
  1409. } finally {
  1410. setIsRestoring(false);
  1411. setOperationStatus('');
  1412. setRestoreFile(null);
  1413. }
  1414. }}
  1415. onCancel={() => {
  1416. setShowRestoreConfirm(false);
  1417. setRestoreFile(null);
  1418. }}
  1419. />
  1420. )}
  1421. {/* Blocking overlay during backup/restore operations */}
  1422. {(isExporting || isRestoring) && (
  1423. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-[100]">
  1424. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center">
  1425. <div className="flex justify-center mb-4">
  1426. <div className="relative">
  1427. <div className="w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"></div>
  1428. <div className="w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"></div>
  1429. </div>
  1430. </div>
  1431. <h3 className="text-xl font-semibold text-white mb-2">
  1432. {isExporting ? t('backup.creatingBackup') : t('backup.restoringBackup')}
  1433. </h3>
  1434. <p className="text-bambu-gray mb-4">
  1435. {operationStatus || (isExporting ? t('backup.preparing') : t('backup.processing'))}
  1436. </p>
  1437. <div className="p-3 rounded-lg bg-yellow-50 dark:bg-yellow-500/10 border border-yellow-300 dark:border-yellow-500/30">
  1438. <div className="flex items-start gap-2 text-sm">
  1439. <AlertTriangle className="w-4 h-4 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0" />
  1440. <p className="text-yellow-800 dark:text-yellow-200 text-left">
  1441. {t('backup.doNotClosePage')}
  1442. </p>
  1443. </div>
  1444. </div>
  1445. </div>
  1446. </div>
  1447. )}
  1448. </div>
  1449. );
  1450. }