-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
178 lines (152 loc) · 5.06 KB
/
index.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import fs from "fs";
import { promisify } from "util";
import path from "path";
import B2 from "backblaze-b2";
import { customAlphabet } from "nanoid";
const nanoid = customAlphabet(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
10
);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const env = process.env;
export default function(name, { id = env.B2_ID, key = env.B2_KEY } = {}) {
const b2 = new B2({ applicationKeyId: id, applicationKey: key });
let bucket = {};
const bucketProm = new Promise(async (done, fail) => {
try {
const auth = await b2.authorize(); // must authorize first
const baseURL = auth.data.downloadUrl + "/file/" + name + "/";
const res = await b2.getBucket({ bucketName: name });
const raw = res.data.buckets[0];
// const list = await b2.listBuckets();
// const raw = list.data.buckets.find(b => b.bucketName === name);
bucket = { ...raw, baseURL };
done(bucket);
} catch (error) {
console.error("AUTH", error.request ? error.request.res : error);
fail(error);
}
});
const info = () => bucketProm;
const list = async prefix => {
// Ignore leading slash like "/" or "/data"
if (prefix) prefix = prefix.replace(/^\//, "");
const { bucketId, baseURL } = await info();
// Transform from the B2 format to the normalized File definition
const toFile = file => ({
name: file.fileName,
type: file.contentType,
size: file.contentLength,
url: baseURL + file.fileName,
timestamp: new Date(file.uploadTimestamp)
});
const files = [];
let next = null;
do {
const res = await b2.listFileNames({
bucketId,
prefix,
startFileName: next,
maxFileCount: 10000
});
files.push(...res.data.files.map(toFile));
next = res.data.nextFileName;
} while (next);
return files;
};
const count = async prefix => {
// Ignore leading slash like "/" or "/data"
if (prefix) prefix = prefix.replace(/^\//, "");
const { bucketId } = await info();
const res = await b2.listFileNames({
bucketId,
prefix,
maxFileCount: 10000
});
return res.data.files.length;
};
const file = async remote => {
remote = remote.name || remote;
remote = remote.replace(/^\//, "");
const files = await list();
return files.find(file => file.name === remote);
};
const exists = async remote => {
remote = remote.name || remote;
remote = remote.replace(/^\//, "");
const files = await list();
return Boolean(files.find(file => file.name === remote));
};
const read = async remote => {
// Allow to pass an object with the full file description
remote = remote.name || remote;
remote = remote.replace(/^\//, "");
// Ignore any leading slash
remote = remote.replace(/^\//, "");
const { bucketId } = await info();
const down = await b2.downloadFileByName({
bucketName: name,
fileName: remote,
responseType: "arraybuffer"
});
return down.data.toString();
};
const download = async (remote, local) => {
// Allow to pass an object with the full file description
remote = remote.name || remote;
remote = remote.replace(/^\//, "");
// Ignore any leading slash
remote = remote.replace(/^\//, "");
local = local || "./" + remote;
const { bucketId } = await info();
const down = await b2.downloadFileByName({
bucketName: name,
fileName: remote,
responseType: "arraybuffer"
});
await writeFile(local, down.data);
return path.resolve(process.cwd(), local);
};
const upload = async (local, remote) => {
const ext = local.split(".").pop();
remote = remote ? remote.name || remote : nanoid() + "." + ext;
if (remote.endsWith("/")) remote = remote + nanoid() + "." + ext;
remote = remote.replace(/^\//, "");
const { bucketId } = await info();
const [res, data] = await Promise.all([
b2.getUploadUrl({ bucketId }),
readFile(local)
]);
const { authorizationToken, uploadUrl } = res.data;
const uploaded = await b2.uploadFile({
fileName: remote,
uploadUrl,
uploadAuthToken: authorizationToken,
data
});
return {
name: uploaded.data.fileName,
type: uploaded.data.contentType,
size: uploaded.data.contentLength,
url: bucket.baseURL + uploaded.data.fileName,
timestamp: new Date(uploaded.data.uploadTimestamp)
};
};
const remove = async remote => {
// Allow to pass an object with the full remote description
remote = remote.name || remote;
const { bucketId } = await info();
const remoteFile = file(remote);
while (await exists(remote)) {
const res = await b2.listFileNames({ bucketId });
const toDelete = res.data.files.find(f => f.fileName === remote);
await b2.deleteFileVersion({
fileId: toDelete.fileId,
fileName: toDelete.fileName
});
}
return remoteFile;
};
return { info, list, count, exists, upload, read, download, remove };
}