-
Notifications
You must be signed in to change notification settings - Fork 14
/
util.js
76 lines (69 loc) · 1.81 KB
/
util.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
const fs = require('fs')
const fsp = require('fs-path')
const download = require('image-downloader')
const fetch = require('node-fetch')
const upsertDirectory = (path) => {
if (!fs.existsSync(path)){
fs.mkdir(path, { recursive: true }, (err) => {
if (err) throw err;
});
}
}
const downloadImage = async (url, dir, filename) => {
const opt = {
url,
dest: `${dir}/${filename}`,
extractFilename: false
}
download.image(opt)
.then(({ filename }) => {
return true
})
.catch((err) => {
console.error(err)
return false
})
}
const downloadVideo = async (url, dir, filename) => {
const opt = {
url,
dest: `${dir}/${filename}`
}
const response = await fetch(opt.url);
const buffer = await response.buffer();
fs.writeFile(opt.dest, buffer, () => true);
}
const storeData = (path, data) => {
try {
fsp.writeFileSync(path, JSON.stringify(data))
} catch (err) {
console.error(err)
}
}
const loadData = (path) => {
try {
const data = fs.readFileSync(path, 'utf8')
return JSON.parse(data)
} catch (err) {
console.error(err)
return false
}
}
const updateData = function(path, id, value, mediaName) {
const data = fs.readFileSync(path, 'utf8')
const content = JSON.parse(data)
if(mediaName == "discord"){
content.forEach((s) => s.id === id && (s.send_discord = value))
}else if(mediaName == "telegram"){
content.forEach((s) => s.id === id && (s.send_telegram = value))
}
fsp.writeFileSync(path, JSON.stringify(content))
};
module.exports = {
storeData,
loadData,
updateData,
downloadImage,
downloadVideo,
upsertDirectory
}