ChatGPT-Next-Web/app/store/sync.ts

114 lines
2.7 KiB
TypeScript
Raw Normal View History

2023-06-27 16:34:01 +00:00
import { Updater } from "../typing";
2023-09-12 18:51:02 +00:00
import { ApiPath, StoreKey } from "../constant";
import { createPersistStore } from "../utils/store";
import {
AppState,
getLocalAppState,
2023-09-12 18:51:02 +00:00
GetStoreState,
mergeAppState,
setLocalAppState,
} from "../utils/sync";
import { downloadAs, readFromFile } from "../utils";
import { showToast } from "../components/ui-lib";
import Locale from "../locales";
2023-09-12 18:51:02 +00:00
import { createSyncClient, ProviderType } from "../utils/cloud";
import { corsPath } from "../utils/cors";
2023-06-27 16:34:01 +00:00
export interface WebDavConfig {
server: string;
username: string;
password: string;
}
2023-09-12 18:51:02 +00:00
export type SyncStore = GetStoreState<typeof useSyncStore>;
export const useSyncStore = createPersistStore(
{
2023-09-12 18:51:02 +00:00
provider: ProviderType.WebDAV,
useProxy: true,
proxyUrl: corsPath(ApiPath.Cors),
webdav: {
endpoint: "",
username: "",
password: "",
2023-06-27 16:34:01 +00:00
},
2023-09-12 18:51:02 +00:00
upstash: {
endpoint: "",
username: "",
apiKey: "",
},
lastSyncTime: 0,
2023-09-12 18:51:02 +00:00
lastProvider: "",
},
(set, get) => ({
2023-09-12 18:51:02 +00:00
coundSync() {
const config = get()[get().provider];
return Object.values(config).every((c) => c.toString().length > 0);
},
markSyncTime() {
set({ lastSyncTime: Date.now(), lastProvider: get().provider });
},
export() {
const state = getLocalAppState();
const fileName = `Backup-${new Date().toLocaleString()}.json`;
downloadAs(JSON.stringify(state), fileName);
},
async import() {
const rawContent = await readFromFile();
try {
const remoteState = JSON.parse(rawContent) as AppState;
const localState = getLocalAppState();
mergeAppState(localState, remoteState);
setLocalAppState(localState);
location.reload();
} catch (e) {
console.error("[Import]", e);
showToast(Locale.Settings.Sync.ImportFailed);
}
},
2023-09-12 18:51:02 +00:00
getClient() {
const provider = get().provider;
const client = createSyncClient(provider, get());
return client;
},
2023-09-12 18:51:02 +00:00
async sync() {
const localState = getLocalAppState();
const provider = get().provider;
const config = get()[provider];
const client = this.getClient();
2023-09-12 18:51:02 +00:00
try {
const remoteState = JSON.parse(
await client.get(config.username),
) as AppState;
mergeAppState(localState, remoteState);
setLocalAppState(localState);
} catch (e) {
console.log("[Sync] failed to get remoate state", e);
}
2023-09-12 18:51:02 +00:00
await client.set(config.username, JSON.stringify(localState));
2023-09-12 18:51:02 +00:00
this.markSyncTime();
},
2023-09-12 18:51:02 +00:00
async check() {
const client = this.getClient();
return await client.check();
},
}),
{
name: StoreKey.Sync,
version: 1,
},
2023-06-27 16:34:01 +00:00
);