-
Notifications
You must be signed in to change notification settings - Fork 3
/
Uploader.js
66 lines (60 loc) · 2.01 KB
/
Uploader.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
const fetch = require('node-fetch');
const FormData = require("form-data");
const https = require("https");
const fs = require("fs");
class Uploader {
constructor(client, forceReady = false) {
this.client = client;
this.ready = forceReady;
if (client.configuration) {
this.url = client.configuration.features.autumn.url;
this.ready = true;
return this;
}
this.client.on("ready", () => {
this.url = client.configuration.features.autumn.url;
this.ready = true;
});
return this;
}
#uploadRaw(file, fileName, tag="attachments") {
if (!this.ready) throw new Error("Client is not ready yet. Login it with client.login() first.");
return new Promise((res, rej) => {
if (!fileName) rej("Filename can't be empty");
const form = new FormData({
maxDataSize: Infinity
});
form.append("file", file, {
filename: fileName,
name: "file"
});
fetch(this.url + "/" + tag, {
method: "POST",
body: form
}).then(response => response.json()).then(json => {
res(json.id);
});
});
}
uploadFile(filePath, name=null, tag="attachments") {
if (!this.ready) throw new Error("Client is not ready yet. Login it with client.login() first.");
return new Promise(async (res, rej) => {
if (!filePath) rej("File path can't be empty");
let stream = fs.createReadStream(filePath);
res(await this.#uploadRaw(stream, name || filePath, tag));
});
}
uploadUrl(url, fileName, tag="attachments") {
if (!this.ready) throw new Error("Client is not ready yet. Login it with client.login() first.");
return new Promise((res) => {
https.get(url, async (response) => {
res(await this.#uploadRaw(response, fileName, tag));
})
});
}
upload(file, fileName, tag="attachments") {
if (!this.ready) throw new Error("Client is not ready yet. Login it with client.login() first.");
return this.#uploadRaw(file, fileName, tag);
}
}
module.exports = Uploader;