webdav.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { STORAGE_KEY } from "@/app/constant";
  2. import { SyncStore } from "@/app/store/sync";
  3. export type WebDAVConfig = SyncStore["webdav"];
  4. export type WebDavClient = ReturnType<typeof createWebDavClient>;
  5. export function createWebDavClient(store: SyncStore) {
  6. const folder = STORAGE_KEY;
  7. const fileName = `${folder}/backup.json`;
  8. const config = store.webdav;
  9. const proxyUrl =
  10. store.useProxy && store.proxyUrl.length > 0 ? store.proxyUrl : undefined;
  11. return {
  12. async check() {
  13. try {
  14. const res = await fetch(this.path(folder, proxyUrl), {
  15. method: "MKCOL",
  16. headers: this.headers(),
  17. });
  18. console.log("[WebDav] check", res.status, res.statusText);
  19. return [201, 200, 404, 301, 302, 307, 308].includes(res.status);
  20. } catch (e) {
  21. console.error("[WebDav] failed to check", e);
  22. }
  23. return false;
  24. },
  25. async get(key: string) {
  26. const res = await fetch(this.path(fileName, proxyUrl), {
  27. method: "GET",
  28. headers: this.headers(),
  29. });
  30. console.log("[WebDav] get key = ", key, res.status, res.statusText);
  31. return await res.text();
  32. },
  33. async set(key: string, value: string) {
  34. const res = await fetch(this.path(fileName, proxyUrl), {
  35. method: "PUT",
  36. headers: this.headers(),
  37. body: value,
  38. });
  39. console.log("[WebDav] set key = ", key, res.status, res.statusText);
  40. },
  41. headers() {
  42. const auth = btoa(config.username + ":" + config.password);
  43. return {
  44. authorization: `Basic ${auth}`,
  45. };
  46. },
  47. path(path: string, proxyUrl: string = "") {
  48. if (!path.endsWith("/")) {
  49. path += "/";
  50. }
  51. if (path.startsWith("/")) {
  52. path = path.slice(1);
  53. }
  54. if (proxyUrl.length > 0 && !proxyUrl.endsWith("/")) {
  55. proxyUrl += "/";
  56. }
  57. let url = new URL(proxyUrl + "/api/webdav/" + path);
  58. // add query params
  59. url.searchParams.append("endpoint", config.endpoint);
  60. return url + path;
  61. },
  62. };
  63. }