/
webdav.ts
88 lines (76 loc) · 2.21 KB
/
webdav.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { AuthType, createClient, FileStat, WebDAVClient } from "webdav/web";
import FileSystem, { File, FileReader, FileWriter } from "../filesystem";
import { joinPath } from "../utils";
import { WebDAVFileReader, WebDAVFileWriter } from "./rw";
export default class WebDAVFileSystem implements FileSystem {
client: WebDAVClient;
url: string;
basePath: string = "/";
constructor(
authType: AuthType | WebDAVClient,
url?: string,
username?: string,
password?: string
) {
if (typeof authType === "object") {
this.client = authType;
this.basePath = joinPath(url || "");
this.url = username!;
} else {
this.url = url!;
this.client = createClient(url!, {
authType,
username,
password,
});
}
}
async verify(): Promise<void> {
await this.client.getQuota();
return Promise.resolve();
}
open(file: File): Promise<FileReader> {
return Promise.resolve(
new WebDAVFileReader(this.client, joinPath(file.path, file.name))
);
}
openDir(path: string): Promise<FileSystem> {
return Promise.resolve(
new WebDAVFileSystem(this.client, joinPath(this.basePath, path), this.url)
);
}
create(path: string): Promise<FileWriter> {
return Promise.resolve(
new WebDAVFileWriter(this.client, joinPath(this.basePath, path))
);
}
createDir(path: string): Promise<void> {
return this.client.createDirectory(joinPath(this.basePath, path));
}
async delete(path: string): Promise<void> {
return this.client.deleteFile(joinPath(this.basePath, path));
}
async list(): Promise<File[]> {
const dir = (await this.client.getDirectoryContents(
this.basePath
)) as FileStat[];
const ret: File[] = [];
dir.forEach((item: FileStat) => {
if (item.type !== "file") {
return;
}
ret.push({
name: item.basename,
path: this.basePath,
digest: item.etag || "",
size: item.size,
createtime: new Date(item.lastmod).getTime(),
updatetime: new Date(item.lastmod).getTime(),
});
});
return Promise.resolve(ret);
}
getDirUrl(): Promise<string> {
return Promise.resolve(this.url + this.basePath);
}
}