-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
94 lines (76 loc) · 2.1 KB
/
app.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
89
90
91
92
93
94
const axios = require('axios')
const express = require('express')
const path = require('path')
const app = express()
const port = 3000
app.set('view engine', 'ejs')
app.use('/static', express.static(path.join(__dirname, 'public')))
app.get('/', (req, res) => {
res.render('index')
})
async function getEmoteUrl(emoteName, n, format) {
const response = await axios.post('https://7tv.io/v3/gql', {
query: `
query Emotes($emoteName: String!) {
emotes(query: $emoteName) {
count
max_page
items {
name
tags
animated
host {
url
}
}
}
}
`,
variables: {
emoteName,
},
})
const nthItem = response.data.data.emotes.items[n > 0 ? n - 1 : 0]
return `https:${nthItem.host.url}/4x.${format || 'webp'}`
}
app.get('/:emoteName', async (req, res) => {
try {
const { emoteName } = req.params
const { format } = req.query
let emoteUrl = await getEmoteUrl(emoteName, 1, format ?? 'png')
const pngResponse = await axios.get(emoteUrl, {
validateStatus: (status) =>
(status >= 200 && status < 300) || status === 403,
})
if (pngResponse.status === 200) {
return res.redirect(emoteUrl)
}
emoteUrl = await getEmoteUrl(emoteName, 1, 'gif')
await axios.get(emoteUrl)
res.redirect(emoteUrl)
} catch (e) {
res.status(404).send('Emote not found')
}
})
app.get('/:emoteName/:n', async (req, res) => {
try {
const { emoteName, n } = req.params
const { format } = req.query
let emoteUrl = await getEmoteUrl(emoteName, n, format ?? 'png')
const pngResponse = await axios.get(emoteUrl, {
validateStatus: (status) =>
(status >= 200 && status < 300) || status === 403,
})
if (pngResponse.status === 200) {
return res.redirect(emoteUrl)
}
emoteUrl = await getEmoteUrl(emoteName, n, 'gif')
await axios.get(emoteUrl)
res.redirect(emoteUrl)
} catch (e) {
res.status(404).send('Emote not found')
}
})
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`)
})