webdav.ts 2.0 KB

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