forked from thoriqazzikraa/whatsapp-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetcher.js
More file actions
84 lines (79 loc) · 2.37 KB
/
Copy pathfetcher.js
File metadata and controls
84 lines (79 loc) · 2.37 KB
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
const fetch = require('node-fetch')
const { fromBuffer } = require('file-type')
const fs = require('fs-extra')
const FormData = require('form-data')
/**
* Fetch JSON from URL.
* @param {String} url
* @param {Object} options
*/
const fetchJson = (url, options) => {
return new Promise((resolve, reject) => {
return fetch(url, options)
.then((response) => response.json())
.then((json) => resolve(json))
.catch((err) => reject(err))
})
}
/**
* Fetch text from URL.
* @param {String} url
* @param {Object} options
*/
const fetchText = (url, options) => {
return new Promise((resolve, reject) => {
return fetch(url, options)
.then((response) => response.text())
.then((text) => resolve(text))
.catch((err) => reject(err))
})
}
/**
* Convert media to buffer.
* @param {String} url
* @param {Object} options
* @returns {Buffer}
*/
const toBuffer = (url, options) => {
return new Promise((resolve, reject) => {
return fetch(url, options)
.then((response) => response.buffer())
.then((buffer) => resolve(buffer))
.catch((err) => reject(err))
})
}
/**
* Upload images to telegra.ph server.
* @param {Buffer} buffData
* @param {String} fileName
*/
const uploadImages = (buffData, fileName) => {
return new Promise(async (resolve, reject) => {
const { ext } = await fromBuffer(buffData)
const filePath = `temp/${fileName}.${ext}`
fs.writeFile(filePath, buffData, { encoding: 'base64' }, (err) => {
if (err) return reject(err)
console.log('Uploading image to telegra.ph server...')
const fileData = fs.readFileSync(filePath)
const form = new FormData()
form.append('file', fileData, `${fileName}.${ext}`)
fetch('https://telegra.ph/upload', {
method: 'POST',
body: form
})
.then((response) => response.json())
.then((result) => {
if (result.error) return reject(result.error)
resolve('https://telegra.ph' + result[0].src)
})
.then(() => fs.unlinkSync(filePath))
.catch((err) => reject(err))
})
})
}
module.exports = {
fetchJson,
fetchText,
uploadImages,
toBuffer
}