webdav.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 fetch(this.path(folder, proxyUrl), {
  16. method: "MKCOL",
  17. headers: this.headers(),
  18. });
  19. console.log("[WebDav] check", res.status, res.statusText);
  20. return [201, 200, 404, 301, 302, 307, 308].includes(res.status);
  21. } catch (e) {
  22. console.error("[WebDav] failed to check", e);
  23. }
  24. return false;
  25. },
  26. async get(key: string) {
  27. const res = await fetch(this.path(fileName, proxyUrl), {
  28. method: "GET",
  29. headers: this.headers(),
  30. });
  31. console.log("[WebDav] get key = ", key, res.status, res.statusText);
  32. return await res.text();
  33. },
  34. async set(key: string, value: string) {
  35. const res = await fetch(this.path(fileName, proxyUrl), {
  36. method: "PUT",
  37. headers: this.headers(),
  38. body: value,
  39. });
  40. console.log("[WebDav] set key = ", key, res.status, res.statusText);
  41. },
  42. headers() {
  43. const auth = btoa(config.username + ":" + config.password);
  44. return {
  45. authorization: `Basic ${auth}`,
  46. };
  47. },
  48. path(path: string, proxyUrl: string = "") {
  49. if (!path.endsWith("/")) {
  50. path += "/";
  51. }
  52. if (path.startsWith("/")) {
  53. path = path.slice(1);
  54. }
  55. if (proxyUrl.length > 0 && !proxyUrl.endsWith("/")) {
  56. proxyUrl += "/";
  57. }
  58. let url = new URL(proxyUrl + "/api/webdav/" + path);
  59. // add query params
  60. url.searchParams.append("endpoint", config.endpoint);
  61. return url + path;
  62. },
  63. };
  64. }