import React, { useCallback, useRef, useState } from 'react'; import { useAtom } from 'jotai'; import { Method } from 'matrix-js-sdk'; import { Box, Button, RadioButton, Text, color } from 'folds'; import { SequenceCard } from '../../../components/sequence-card'; import { SequenceCardStyle } from '../styles.css'; import { SettingTile } from '../../../components/setting-tile'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; import { Settings, settingsAtom } from '../../../state/settings'; import { buildExport, EXPORT_ACCOUNT_DATA, ExportFile, ImportPlanItem, mergeData, parseExport, planImport, } from '../../../utils/dataExport'; import { invalidateDecorationCache } from '../../../hooks/useAvatarDecoration'; const DECORATION_FIELD = 'io.lotus.avatar_decoration'; type Current = { accountData: Record; decoration: string | null; localSettings: Record | null; }; /** * [Gitea #114] "Your data": export the account's Lotus data (settings, * bookmarks, notes, sections, ...) to a file and import it here or on another * account. Import merges: new things are added; for things that differ the * user picks "keep mine" (default) or "use the file's". Message history and * encryption keys have their own exports. */ export function YourDataSection() { const mx = useMatrixClient(); const userId = mx.getSafeUserId(); const [settings, setSettings] = useAtom(settingsAtom); const fileInput = useRef(null); const [pending, setPending] = useState<{ file: ExportFile; plan: ImportPlanItem[] }>(); const [preferFile, setPreferFile] = useState(false); const [message, setMessage] = useState<{ tone: 'ok' | 'error'; text: string }>(); const [busy, setBusy] = useState(false); const readCurrent = useCallback(async (): Promise => { const accountData: Record = {}; EXPORT_ACCOUNT_DATA.forEach(({ type }) => { const c = mx.getAccountData(type as never)?.getContent(); if (c && Object.keys(c).length > 0) accountData[type] = c; }); let decoration: string | null = null; try { const profile = await mx.http.authedRequest>( Method.Get, `/profile/${encodeURIComponent(userId)}`, ); const v = profile[DECORATION_FIELD]; decoration = typeof v === 'string' && v ? v : null; } catch { /* no decoration */ } return { accountData, decoration, localSettings: settings as unknown as Record, }; }, [mx, userId, settings]); const exportData = async () => { setBusy(true); setMessage(undefined); try { const cur = await readCurrent(); const file = buildExport({ userId, ...cur }); const blob = new Blob([JSON.stringify(file, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `lotus-chat-data-${userId.replace(/[^a-z0-9]+/gi, '-')}-${file.exportedAt.slice(0, 10)}.json`; a.click(); URL.revokeObjectURL(url); setMessage({ tone: 'ok', text: 'Exported. Keep the file somewhere safe.' }); } catch { setMessage({ tone: 'error', text: "Couldn't export your data. Please try again." }); } finally { setBusy(false); } }; const chooseFile = async (f: File | undefined) => { if (!f) return; setMessage(undefined); const parsed = parseExport(await f.text()); if (!parsed.ok) { setMessage({ tone: 'error', text: parsed.error }); return; } const plan = planImport(parsed.file, await readCurrent()); setPreferFile(false); setPending({ file: parsed.file, plan }); }; const applyImport = async () => { if (!pending) return; setBusy(true); try { const cur = await readCurrent(); const { file } = pending; await Object.entries(file.accountData).reduce>( async (prev, [type, incoming]) => { await prev; const r = mergeData(cur.accountData[type], incoming, preferFile); if (r.added > 0 || (preferFile && r.conflicts > 0)) { await mx.setAccountData(type as never, r.value as never); } }, Promise.resolve(), ); const deco = file.profile.decoration; if (deco && deco !== cur.decoration && (!cur.decoration || preferFile)) { await mx.http.authedRequest( Method.Put, `/profile/${encodeURIComponent(userId)}/${DECORATION_FIELD}`, undefined, { [DECORATION_FIELD]: deco }, ); invalidateDecorationCache(userId); } if (file.local.settings) { const r = mergeData(cur.localSettings ?? {}, file.local.settings, preferFile); setSettings({ ...settings, ...(r.value as Partial) }); } setPending(undefined); setMessage({ tone: 'ok', text: 'Imported.' }); } catch { setMessage({ tone: 'error', text: "Couldn't finish the import. Nothing else was changed." }); } finally { setBusy(false); } }; const totals = pending?.plan.reduce( (t, p) => ({ added: t.added + p.added, conflicts: t.conflicts + p.conflicts }), { added: 0, conflicts: 0 }, ); return ( Your data Export } /> fileInput.current?.click()} > Import… } /> { chooseFile(e.target.files?.[0]).catch(() => undefined); e.target.value = ''; }} /> {pending && totals && ( {pending.file.userId && pending.file.userId !== userId && ( This file is from {pending.file.userId}. )} {pending.plan.map((p) => ( {p.label}:{' '} {p.added === 0 && p.conflicts === 0 ? 'already up to date' : [p.added > 0 && `${p.added} new`, p.conflicts > 0 && `${p.conflicts} differ`] .filter(Boolean) .join(', ')} ))} {totals.conflicts > 0 && ( {totals.conflicts}{' '} {totals.conflicts === 1 ? 'thing differs' : 'things differ'} from what's here: )} )} {message && ( {message.text} )} ); }