import { addNotification } from "$lib/Notification/store"; import { options } from "$lib/Notification/options"; import root from "$lib/Utility/root"; import settings from "$stores/settings"; import settingsSyncPulled from "$stores/settingsSyncPulled"; import settingsSyncTimes from "$stores/settingsSyncTimes"; import locale from "$stores/locale"; import { get } from "svelte/store"; import type { CommandPaletteAction } from "./actions"; export const syncActions = ( identityId: number, syncEnabled: boolean, ): CommandPaletteAction[] => { if (identityId <= 0) return []; const l = get(locale)(); const actions: CommandPaletteAction[] = [ { name: l.commandPalette?.sync?.pushNow ?? "Push Settings Now", url: "#", preventDefault: true, tags: ["settings", "sync", "push", "upload", "remote"], onClick: () => { settings.setKey("settingsSync", true); fetch(root(`/api/configuration`), { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(get(settings)), }) .then((response) => { if (!response.ok) return; addNotification( options({ heading: get(locale)().settings.settingsSync.title, description: get(locale)().commandPalette?.sync?.pushedDescription ?? "Pushed local configuration to remote", }), ); settingsSyncTimes.update((times) => ({ ...times, lastPush: new Date(), })); }) .catch((error) => console.error("Settings sync push failed", error)); }, }, { name: l.commandPalette?.sync?.pullNow ?? "Pull Settings Now", url: "#", preventDefault: true, tags: ["settings", "sync", "pull", "download", "remote"], onClick: () => { settings.setKey("settingsSync", true); fetch(root(`/api/configuration?id=${identityId}`)) .then((response) => { if (!response.ok) return; return response.json().then((data) => { if (!data?.configuration) { addNotification( options({ heading: get(locale)().settings.settingsSync.title, description: get(locale)().commandPalette?.sync?.noRemoteFound ?? "No remote configuration found", }), ); return; } settings.set(data.configuration); settingsSyncPulled.set(true); settingsSyncTimes.set({ lastPull: new Date(), lastPush: new Date(`${data.updated_at}Z`), }); addNotification( options({ heading: get(locale)().notifications?.pulledRemote ?? "Pulled remote configuration", }), ); }); }) .catch((error) => console.error("Settings sync pull failed", error)); }, }, ]; if (syncEnabled) actions.push({ name: l.commandPalette?.sync?.disable ?? "Disable Settings Sync", url: "#", preventDefault: true, tags: ["settings", "sync", "disable", "off", "stop"], onClick: () => { settings.setKey("settingsSync", false); addNotification( options({ heading: get(locale)().notifications?.syncDisabled ?? "Settings sync disabled", }), ); }, }); return actions; };