-
Notifications
You must be signed in to change notification settings - Fork 9
/
fileShare.js
88 lines (77 loc) · 2.37 KB
/
fileShare.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
import fetch from 'isomorphic-unfetch'
import { initBot, transcript, reaction } from '../utils'
const uploadToCDN = async files => {
console.log('Generating links for ', files.length, 'file(s)')
const fileURLs = files.map(f => f['url_private'])
return new Promise((resolve, reject) => {
fetch('https://cdn-2moycvmxo.hackclub.dev/api/v1/new', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.SLACK_BOT_TOKEN}`
},
body: JSON.stringify(fileURLs),
})
.then(r => r.json())
.then(resolve)
.catch(reject)
})
}
export default async (bot = initBot(), message) => {
const cdnChannelID = 'C016DEDUL87'
const { ts, channel, files } = message
if (channel != cdnChannelID) {
return
}
const extFlavorOptions = files.map(file => {
try {
return transcript(`fileShare.extensions.${file.filetype}`)
} catch (e) {
return null
}
})
const extFlavor = extFlavorOptions[Math.floor(Math.random() * extFlavorOptions.length)]
if (extFlavor) {
bot.replyInThread(message, { text: extFlavor })
}
try {
const results = {}
await Promise.all([
reaction(bot, 'add', channel, ts, 'beachball'),
uploadToCDN(files)
.then(f => {
results.links = f
})
.catch(e => {
results.error = e
}),
])
if (results.error) {
throw results.error
}
if (results.links) {
await Promise.all([
reaction(bot, 'remove', channel, ts, 'beachball'),
reaction(bot, 'add', channel, ts, 'white_check_mark'),
bot.replyInThread(message, {
text: transcript('fileShare.success', { links: results.links, user: message.user }),
unfurl_media: false,
unfurl_links: false,
}),
])
}
} catch (err) {
const maxFileSize = 100000000 // 100MB in bytes
const fileTooBig = files.filter(f => f.size > maxFileSize).length > 0
if (fileTooBig) {
await bot.replyInThread(message, transcript('fileShare.errorTooBig'))
} else {
await bot.replyInThread(message, transcript('fileShare.errorGeneric'))
}
await Promise.all([
reaction(bot, 'remove', channel, ts, 'beachball'),
reaction(bot, 'add', channel, ts, 'no_entry'),
bot.replyInThread(message, transcript('errors.general', { err })),
])
}
}