-
Notifications
You must be signed in to change notification settings - Fork 0
/
gemdrive.js
95 lines (76 loc) · 2.41 KB
/
gemdrive.js
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
89
90
91
92
93
94
95
async function copy(srcDrive, srcPath, srcToken, dstDrive, dstPath, dstToken) {
const isDir = srcPath.endsWith('/');
if (isDir) {
const tree = {};
return copyDir(srcDrive, srcPath, srcToken, dstDrive, dstPath, dstToken, tree);
}
else {
const srcPathSegments = srcPath.split('/');
const filename = srcPathSegments[srcPathSegments.length - 1];
const dstFilePath = dstPath + filename;
return copyFile(srcDrive, srcPath, srcToken, dstDrive, dstFilePath, dstToken);
}
}
async function makeDir(drive, path, token, recursive) {
const url = drive + path + '?access_token=' + token;
const res = await fetch(url, {
method: 'PUT',
});
}
async function copyDir(srcDrive, srcPath, srcToken, dstDrive, dstPath, dstToken, tree) {
const srcPathSegments = srcPath.split('/');
const dstDirName = srcPathSegments[srcPathSegments.length - 2];
const newDstDir = dstPath + dstDirName + '/';
try {
const recursive = true;
await makeDir(dstDrive, newDstDir, dstToken, true);
}
catch (e) {
console.error(e);
return;
}
const supportsTreeRequests = true;
if (tree.children === undefined) {
let reqFile;
if (supportsTreeRequests) {
reqFile = 'tree.json';
}
else {
reqFile = 'list.json';
}
const reqUrl = srcDrive + '/gemdrive/index' + srcPath + reqFile + '?access_token=' + srcToken
const res = await fetch(reqUrl);
const subtree = await res.json();
if (subtree.children !== undefined) {
tree.children = subtree.children;
}
}
if (tree.children !== undefined) {
for (const [name, item] of Object.entries(tree.children)) {
const childSrcPath = srcPath + name;
const isDir = name.endsWith('/');
if (isDir) {
await copyDir(srcDrive, childSrcPath, srcToken, dstDrive, newDstDir, dstToken, tree.children[name]);
}
else {
const childDstPath = newDstDir + name;
await copyFile(srcDrive, childSrcPath, srcToken, dstDrive, childDstPath, dstToken);
}
}
}
}
async function copyFile(srcDrive, srcPath, srcToken, dstDrive, dstPath, dstToken) {
const reqUrl = dstDrive + '/gemdrive/remote-get?access_token=' + dstToken;
const res = await fetch(reqUrl, {
method: 'POST',
body: JSON.stringify({
source: srcDrive + srcPath + '?access_token=' + srcToken,
destination: dstPath,
preserveAttributes: true,
}),
});
}
export default {
copy,
makeDir,
};