Restore a full backup from Settings
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
Settings → Data → Import gets "Restore a full backup" in place of the V1 import row. The zip from "Download backup" is uploaded and replaces the database, every setting and the uploaded files on the running server: - the staged database is upgraded to this schema (newer backups are refused), saved keys are re-encrypted for this server's key, interrupted jobs are marked, and the restoring session is carried over; - a pre-restore snapshot is written, running generations stop, and the file is swapped under the open DB handle (DB.replaceWith); uploads and media are copied into place and background work restarts. The /api/import/v1 endpoint stays for the V1 cutover (docs/MIGRATION.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e0bc7b580e
commit
7125dec3e0
13 changed files with 521 additions and 72 deletions
|
|
@ -79,12 +79,13 @@ export function errorMessage(e: unknown, fallback = 'Something went wrong.'): st
|
|||
return fallback;
|
||||
}
|
||||
|
||||
/** Uploads with progress (fetch cannot report upload progress). */
|
||||
export function uploadWithProgress<T>(url: string, form: FormData, onProgress: (fraction: number) => void): Promise<T> {
|
||||
/** Uploads with progress (fetch cannot report upload progress). A Blob or File is sent as the raw body. */
|
||||
export function uploadWithProgress<T>(url: string, form: FormData | Blob, onProgress: (fraction: number) => void): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('POST', url);
|
||||
xhr.setRequestHeader('X-Requested-With', 'studydesk');
|
||||
if (form instanceof Blob) xhr.setRequestHeader('Content-Type', form.type || 'application/octet-stream');
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress(e.loaded / e.total);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@ import { toast } from 'sonner';
|
|||
import { shareUrl } from '@/features/dialogs';
|
||||
import { TemplateSettings } from '@/features/TemplateSettings';
|
||||
import { WebSearchSettings } from '@/features/WebSearchSettings';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { api, ApiError, errorMessage, uploadWithProgress } from '@/lib/api';
|
||||
import { qk, useRefresh } from '@/lib/queries';
|
||||
import type { AppSettings, ShareAiSettings, ShareListItem, Template } from '@/lib/types';
|
||||
import { copyText, cx, downloadFile, formatBytes, formatDateTime, plural, timeAgo, useDocumentTitle, useTheme } from '@/lib/util';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
|
||||
import { Badge, Button, Callout, ClassDot, EmptyState, Field, IconButton, Input, PageHeader, PageLoading, ProgressBar, Section, Segmented, Select, Skeleton, Switch, useConfirm } from '@/ui';
|
||||
|
||||
const AiSettings = lazy(() => import('@/features/AiSettings'));
|
||||
|
||||
|
|
@ -284,17 +284,19 @@ function ShareAiSafety() {
|
|||
|
||||
/* ------------------------------ data ------------------------------ */
|
||||
|
||||
interface V1Summary {
|
||||
interface RestoreSummary {
|
||||
backupCreatedAt: string | null;
|
||||
classes: number;
|
||||
folders: number;
|
||||
decks: number;
|
||||
cards: number;
|
||||
quizzes: number;
|
||||
questions: number;
|
||||
decks: number;
|
||||
notes: number;
|
||||
documents: number;
|
||||
attempts: number;
|
||||
scheduledCards: number;
|
||||
activityDays: number;
|
||||
skipped: string[];
|
||||
files: number;
|
||||
keysMoved: number;
|
||||
keysUnreadable: number;
|
||||
safetySnapshot: string;
|
||||
stoppedJobs: number;
|
||||
}
|
||||
|
||||
function DataSettings() {
|
||||
|
|
@ -303,10 +305,9 @@ function DataSettings() {
|
|||
const settings = useQuery({ queryKey: qk.settings, queryFn: () => api.get<SettingsResponse>('/api/settings') });
|
||||
const backups = useQuery({ queryKey: ['backups'], queryFn: () => api.get<{ backups: { name: string; size: number; createdAt: number }[]; directory: string }>('/api/backups') });
|
||||
const bundleRef = useRef<HTMLInputElement>(null);
|
||||
const v1Ref = useRef<HTMLInputElement>(null);
|
||||
const restoreRef = useRef<HTMLInputElement>(null);
|
||||
const [busy, setBusy] = useState('');
|
||||
const [v1File, setV1File] = useState<File | null>(null);
|
||||
const [v1Preview, setV1Preview] = useState<V1Summary | null>(null);
|
||||
const [restoreProgress, setRestoreProgress] = useState<number | null>(null);
|
||||
|
||||
const importBundle = async (file: File) => {
|
||||
setBusy('bundle');
|
||||
|
|
@ -322,25 +323,31 @@ function DataSettings() {
|
|||
setBusy('');
|
||||
}
|
||||
};
|
||||
const v1 = async (file: File, preview: boolean) => {
|
||||
setBusy(preview ? 'v1preview' : 'v1');
|
||||
const restore = async (file: File) => {
|
||||
const ok = await confirm({
|
||||
title: 'Restore this backup?',
|
||||
message: `Everything on this server is replaced with ${file.name}: classes, quizzes, flashcards, documents, progress, AI models and every setting. A snapshot of what is here now is saved first under Database snapshots. You stay signed in.`,
|
||||
confirmLabel: 'Replace everything',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
setBusy('restore');
|
||||
setRestoreProgress(0);
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await api.upload<{ summary: V1Summary }>(`/api/import/v1${preview ? '?preview=1' : ''}`, form);
|
||||
if (preview) {
|
||||
setV1File(file);
|
||||
setV1Preview(res.summary);
|
||||
} else {
|
||||
await refresh();
|
||||
setV1File(null);
|
||||
setV1Preview(null);
|
||||
toast.success(`Migrated ${plural(res.summary.classes, 'class', 'classes')} from V1`);
|
||||
}
|
||||
const res = await uploadWithProgress<{ summary: RestoreSummary }>('/api/backup/restore', file, (f) => setRestoreProgress(f));
|
||||
const s = res.summary;
|
||||
const made = s.backupCreatedAt ? ` from ${new Date(s.backupCreatedAt).toLocaleString()}` : '';
|
||||
toast.success(`Backup${made} restored: ${plural(s.classes, 'class', 'classes')}, ${plural(s.quizzes, 'quiz', 'quizzes')}, ${plural(s.decks, 'deck')}, ${plural(s.files, 'file')}.`, {
|
||||
description: s.keysUnreadable ? `${plural(s.keysUnreadable, 'saved API key')} could not be read on this server; enter them again in Settings → AI.` : undefined,
|
||||
duration: 10_000,
|
||||
});
|
||||
// Every screen's data changed: start fresh.
|
||||
setTimeout(() => window.location.assign('/settings/data'), 1500);
|
||||
} catch (e) {
|
||||
toast.error(errorMessage(e));
|
||||
toast.error(e instanceof ApiError && e.status === 413 ? 'The backup is too large to upload here. If a proxy such as Cloudflare limits uploads, restore it on the server instead (see the deployment guide).' : errorMessage(e));
|
||||
} finally {
|
||||
setBusy('');
|
||||
setRestoreProgress(null);
|
||||
}
|
||||
};
|
||||
const sys = settings.data?.system;
|
||||
|
|
@ -385,42 +392,19 @@ function DataSettings() {
|
|||
<div className="p-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<div className="min-w-0 flex-1 basis-64">
|
||||
<div className="text-sm font-medium">Migrate from Study Desk V1</div>
|
||||
<div className="text-[13px] text-ink-3">
|
||||
Upload the V1 database file (<code className="num text-[12px]">study.db</code> from the old container's data folder). Classes, groups, decks, quizzes, attempt history, flashcard schedules and your activity are copied in. The V1 file is only read, never changed.
|
||||
</div>
|
||||
<div className="text-sm font-medium">Restore a full backup</div>
|
||||
<div className="text-[13px] text-ink-3">Replaces everything on this server with a backup zip from "Download backup": content, progress, uploaded files, AI models and all settings. A snapshot of the current database is saved first.</div>
|
||||
</div>
|
||||
<input ref={v1Ref} type="file" accept=".db,.sqlite,.sqlite3,application/octet-stream" hidden onChange={(e) => (e.target.files?.[0] && v1(e.target.files[0], true), (e.target.value = ''))} />
|
||||
<Button icon={<Upload />} loading={busy === 'v1preview'} onClick={() => v1Ref.current?.click()}>
|
||||
Choose study.db
|
||||
<input ref={restoreRef} type="file" accept=".zip,application/zip" hidden onChange={(e) => (e.target.files?.[0] && restore(e.target.files[0]), (e.target.value = ''))} />
|
||||
<Button icon={<Upload />} loading={busy === 'restore'} onClick={() => restoreRef.current?.click()}>
|
||||
Choose backup
|
||||
</Button>
|
||||
</div>
|
||||
{v1Preview && v1File && (
|
||||
<Callout tone="accent" className="mt-3" title={`Found in ${v1File.name}`}>
|
||||
<div className="mt-1 grid grid-cols-2 gap-x-6 gap-y-0.5 text-[13px] sm:grid-cols-3">
|
||||
<span>{plural(v1Preview.classes, 'class', 'classes')}</span>
|
||||
<span>{plural(v1Preview.folders, 'group')} → folders</span>
|
||||
<span>{plural(v1Preview.quizzes, 'quiz', 'quizzes')} · {plural(v1Preview.questions, 'question')}</span>
|
||||
<span>{plural(v1Preview.decks, 'deck')} · {plural(v1Preview.cards, 'card')}</span>
|
||||
<span>{plural(v1Preview.attempts, 'quiz attempt')}</span>
|
||||
<span>{plural(v1Preview.scheduledCards, 'card schedule')}</span>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
loading={busy === 'v1'}
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: 'Migrate this V1 data?', message: 'Everything listed is added as new classes. A snapshot of the current database is taken first. Running the migration twice creates duplicates.', confirmLabel: 'Migrate' })) void v1(v1File, false);
|
||||
}}
|
||||
>
|
||||
Migrate now
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => (setV1Preview(null), setV1File(null))}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</Callout>
|
||||
{restoreProgress !== null && (
|
||||
<div className="mt-3 space-y-1.5">
|
||||
<ProgressBar value={restoreProgress} label="Uploading the backup" />
|
||||
<div className="text-xs text-ink-3">{restoreProgress < 1 ? `Uploading… ${Math.round(restoreProgress * 100)}%` : 'Restoring… this can take a minute for large backups.'}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue