sync.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { Updater } from "../typing";
  2. import { StoreKey } from "../constant";
  3. import { createPersistStore } from "../utils/store";
  4. import {
  5. AppState,
  6. getLocalAppState,
  7. mergeAppState,
  8. setLocalAppState,
  9. } from "../utils/sync";
  10. import { downloadAs, readFromFile } from "../utils";
  11. import { showToast } from "../components/ui-lib";
  12. import Locale from "../locales";
  13. export interface WebDavConfig {
  14. server: string;
  15. username: string;
  16. password: string;
  17. }
  18. export interface SyncStore {
  19. webDavConfig: WebDavConfig;
  20. lastSyncTime: number;
  21. update: Updater<WebDavConfig>;
  22. check: () => Promise<boolean>;
  23. path: (path: string) => string;
  24. headers: () => { Authorization: string };
  25. }
  26. export const useSyncStore = createPersistStore(
  27. {
  28. webDavConfig: {
  29. server: "",
  30. username: "",
  31. password: "",
  32. },
  33. lastSyncTime: 0,
  34. },
  35. (set, get) => ({
  36. webDavConfig: {
  37. server: "",
  38. username: "",
  39. password: "",
  40. },
  41. lastSyncTime: 0,
  42. export() {
  43. const state = getLocalAppState();
  44. const fileName = `Backup-${new Date().toLocaleString()}.json`;
  45. downloadAs(JSON.stringify(state), fileName);
  46. },
  47. async import() {
  48. const rawContent = await readFromFile();
  49. try {
  50. const remoteState = JSON.parse(rawContent) as AppState;
  51. const localState = getLocalAppState();
  52. mergeAppState(localState, remoteState);
  53. setLocalAppState(localState);
  54. location.reload();
  55. } catch (e) {
  56. console.error("[Import]", e);
  57. showToast(Locale.Settings.Sync.ImportFailed);
  58. }
  59. },
  60. async check() {
  61. try {
  62. const res = await fetch(this.path(""), {
  63. method: "PROFIND",
  64. headers: this.headers(),
  65. });
  66. console.log(res);
  67. return res.status === 207;
  68. } catch (e) {
  69. console.error("[Sync] ", e);
  70. return false;
  71. }
  72. },
  73. path(path: string) {
  74. let url = get().webDavConfig.server;
  75. if (!url.endsWith("/")) {
  76. url += "/";
  77. }
  78. if (path.startsWith("/")) {
  79. path = path.slice(1);
  80. }
  81. return url + path;
  82. },
  83. headers() {
  84. const auth = btoa(
  85. [get().webDavConfig.username, get().webDavConfig.password].join(":"),
  86. );
  87. return {
  88. Authorization: `Basic ${auth}`,
  89. };
  90. },
  91. }),
  92. {
  93. name: StoreKey.Sync,
  94. version: 1,
  95. },
  96. );