webdav.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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;
  58. if (proxyUrl.length > 0 || proxyUrl === "/") {
  59. let u = new URL(proxyUrl + "/api/webdav/" + path);
  60. // add query params
  61. u.searchParams.append("endpoint", config.endpoint);
  62. url = u.toString();
  63. } else {
  64. url = "/api/upstash/" + path + "?endpoint=" + config.endpoint;
  65. }
  66. return url;
  67. },
  68. };
  69. }