-
Notifications
You must be signed in to change notification settings - Fork 1
/
uploader.js
80 lines (74 loc) · 2.03 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const fetch = require("@replit/node-fetch");
const FormData = require("form-data");
const fs = require("fs");
const https = require("https");
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;
}
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 stats = fs.statSync(fileName);
let stream = fs.createReadStream(fileName);
const formData = new FormData();
formData.append("file", stream);
fetch(this.url + "/" + tag, {
method: "POST",
headers: {
"Content-Lenght": stats.size,
"x-session-token": this.client.api.auth.headers["X-Session-Token"],
},
body: formData,
})
.then((response) => response.json())
.then((json) => {
res(json.id);
});
});
}
image(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) => {
const form = new FormData();
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);
});
});
}
online(url) {
return new Promise((res) => {
https.get(url, async (response) => {
res(await this.image(response, "image"));
});
});
}
}
module.exports = Uploader;