webdav.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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, "MKCOL"), {
  15. method: "GET",
  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. if (404 == res.status) {
  39. return "";
  40. }
  41. return await res.text();
  42. },
  43. async set(key: string, value: string) {
  44. const res = await fetch(this.path(fileName, proxyUrl), {
  45. method: "PUT",
  46. headers: this.headers(),
  47. body: value,
  48. });
  49. console.log("[WebDav] set key = ", key, res.status, res.statusText);
  50. },
  51. headers() {
  52. const auth = btoa(config.username + ":" + config.password);
  53. return {
  54. authorization: `Basic ${auth}`,
  55. };
  56. },
  57. path(path: string, proxyUrl: string = "", proxyMethod: string = "") {
  58. if (path.startsWith("/")) {
  59. path = path.slice(1);
  60. }
  61. if (proxyUrl.endsWith("/")) {
  62. proxyUrl = proxyUrl.slice(0, -1);
  63. }
  64. let url;
  65. const pathPrefix = "/api/webdav/";
  66. try {
  67. let u = new URL(proxyUrl + pathPrefix + path);
  68. // add query params
  69. u.searchParams.append("endpoint", config.endpoint);
  70. proxyMethod && u.searchParams.append("proxy_method", proxyMethod);
  71. url = u.toString();
  72. } catch (e) {
  73. url = pathPrefix + path + "?endpoint=" + config.endpoint;
  74. if (proxyMethod) {
  75. url += "&proxy_method=" + proxyMethod;
  76. }
  77. }
  78. return url;
  79. },
  80. };
  81. }