webdav.ts 2.0 KB

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