webdav.ts 2.3 KB

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