-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.ts
228 lines (170 loc) · 8.19 KB
/
app.ts
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { load } from "https://deno.land/[email protected]/dotenv/mod.ts";
const env = await load()
import { Hono } from 'https://deno.land/x/[email protected]/mod.ts'
import { REST } from 'npm:@discordjs/rest@^2.0.0'
import { WebSocketManager } from 'npm:@discordjs/ws@^1.0.0'
import { GatewayDispatchEvents, GatewayIntentBits, Client, GatewayPresenceUpdate, ActivityType, PresenceUpdateStatus } from 'npm:@discordjs/core@^1.0.0'
import 'npm:bufferutil@^4.0.7'
import { makeBadge } from 'npm:badge-maker@^3.3.1'
import logos from './logos.json' assert { type: 'json' }
const { vscode, intellij, spotify, crunchyroll } = logos
const rest = new REST().setToken(env.TOKEN)
const gateway = new WebSocketManager({
token: env.TOKEN,
intents: GatewayIntentBits.Guilds | GatewayIntentBits.GuildPresences,
rest
})
const client = new Client({ rest, gateway })
const presences = new Map<string, GatewayPresenceUpdate>()
client.once(GatewayDispatchEvents.Ready, (e) => {
console.log('Ready!', e.data)
})
client.on(GatewayDispatchEvents.GuildCreate, e => {
for (const presence of e.data.presences) {
presences.set(presence.user.id, presence)
}
})
client.on(GatewayDispatchEvents.PresenceUpdate, e => {
presences.set(e.data.user.id, e.data)
})
gateway.connect()
/**
* Adds a logo and updates positions
* unfortunately, shields' badge-maker library doesn't support their logo system
* so I modify the generated svg to inject the logo
* this only supports the "flat", "flat-square", and "plastic" styles
* so this is skipped for "social" and "for-the-badge"
*/
const injectLogo = (svg: string, logo: string) => {
svg = svg.replace('<text', `<image x="5" y="3" width="14" height="14" xlink:href="data:image/svg+xml;base64,${logo}"/><text`)
// add 17 to the svg's full width in all the places it's in
const fullWidthArr = svg.match(/width="(\d+?)"/)!
svg = svg.replace(new RegExp(fullWidthArr[0], 'g'), `width="${+fullWidthArr[1]+17}"`)
// add 17 to gray part width, fallback for flat-square support
const [,grayWidth] = svg.match(/\)"><rect width="(\d+?)"/) || svg.match(/"><rect width="(\d+?)"/)!
svg = svg.replace(new RegExp(`="${grayWidth}"`, 'g'), `="${+grayWidth+17}"`)
// adds 170 to text positions
svg = svg.replace(/("|xt) x="(\d+?)"/g, (_, start, pos) => `${start} x="${+pos+170}"`)
return svg
}
const colors = { online: 'brightgreen', idle: 'yellow', dnd: 'red', offline: 'lightgray' }
const resolveStyle = (style?: string) =>
style === 'plastic' || style === 'flat' || style === 'flat-square' || style === 'for-the-badge' || style === 'social' ? style : 'flat'
const formatter = new Intl.ListFormat()
const app = new Hono()
app.get('/', c => c.redirect('https://statusbadges.me'))
app.get('/badge/status/:id', c => {
const realStatus = presences.get(c.req.param('id'))?.status ?? PresenceUpdateStatus.Offline
const status = c.req.query('simple') === 'true'
? [PresenceUpdateStatus.Idle, PresenceUpdateStatus.DoNotDisturb].includes(realStatus)
? PresenceUpdateStatus.Online
: realStatus
: realStatus
c.header('Content-Type', 'image/svg+xml; charset=utf-8')
c.header('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate')
return c.body(makeBadge({
label: c.req.query('label') ?? 'currently',
message: status,
labelColor: c.req.query('labelColor') ?? 'gray',
color: c.req.query('color') ?? colors[status],
style: resolveStyle(c.req.query('style'))
}))
})
app.get('/badge/playing/:id', c => {
const activities = presences.get(c.req.param('id'))?.activities
?.filter(a => a.type === ActivityType.Playing && !['Visual Studio Code', 'IntelliJ IDEA Ultimate'].includes(a.name)) ?? []
c.header('Content-Type', 'image/svg+xml; charset=utf-8')
c.header('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate')
return c.body(makeBadge({
label: c.req.query('label') ?? 'playing',
message: formatter.format(activities.map(a => a.name)) || c.req.query('fallback') || 'nothing rn',
labelColor: c.req.query('labelColor') ?? 'gray',
color: c.req.query('color') ?? '#5865f2',
style: resolveStyle(c.req.query('style'))
}))
})
app.get('/badge/vscode/:id', c => {
const activity = presences.get(c.req.param('id'))?.activities?.find(a => a.name === 'Visual Studio Code' && a.details && a.state)
c.header('Content-Type', 'image/svg+xml; charset=utf-8')
c.header('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate')
const style = resolveStyle(c.req.query('style'))
let badge = makeBadge({
label: c.req.query('label') ?? 'coding',
message: activity && activity.details && activity.state
? `${activity.details.replace('Editing ', '')} in ${activity.state.replace(/(Workspace: | \(Workspace\))/g, '').replace('Glitch:', '🎏')}`
: c.req.query('fallback') ?? 'nothing rn',
labelColor: c.req.query('labelColor') ?? 'gray',
color: c.req.query('color') ?? '#23a7f2',
style
})
if (!['social', 'for-the-badge'].includes(style) && c.req.query('hideLogo') !== 'true')
badge = injectLogo(badge, vscode)
return c.body(badge)
})
app.get('/badge/intellij/:id', c => {
const activity = presences.get(c.req.param('id'))?.activities?.find(a => a.name === 'IntelliJ IDEA Ultimate' && a.details && a.state && a.state !== 'Idling')
c.header('Content-Type', 'image/svg+xml; charset=utf-8')
c.header('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate')
const style = resolveStyle(c.req.query('style'))
let badge = makeBadge({
label: c.req.query('label') ?? 'coding',
message: activity && activity.details && activity.state
? `${activity.details.replace('Editing ', '')} in ${activity.state}`
: c.req.query('fallback') ?? 'nothing rn',
labelColor: c.req.query('labelColor') ?? 'gray',
color: c.req.query('color') ?? '#fe315d',
style
})
if (!['social', 'for-the-badge'].includes(style) && c.req.query('hideLogo') !== 'true')
badge = injectLogo(badge, intellij)
return c.body(badge)
})
app.get('/badge/spotify/:id', c => {
const activity = presences.get(c.req.param('id'))?.activities?.find(a => a.type === ActivityType.Listening && a.name === 'Spotify' && a.details && a.state)
c.header('Content-Type', 'image/svg+xml; charset=utf-8')
c.header('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate')
const style = resolveStyle(c.req.query('style'))
let badge = makeBadge({
label: c.req.query('label') ?? 'listening to',
message: activity && activity.details && activity.state
? `${activity.details.replace(/\(.*\)/g, '')} by ${formatter.format(activity.state.split('; '))}`
: c.req.query('fallback') ?? 'nothing rn',
labelColor: c.req.query('labelColor') ?? 'gray',
color: c.req.query('color') ?? '#1db954',
style
})
if (!['social', 'for-the-badge'].includes(style) && c.req.query('hideLogo') !== 'true')
badge = injectLogo(badge, spotify)
return c.body(badge)
})
app.get('/badge/crunchyroll/:id', c => {
const activity = presences.get(c.req.param('id'))?.activities?.find(a => a.type === ActivityType.Watching && a.name === 'Crunchyroll' && a.details)
c.header('Content-Type', 'image/svg+xml; charset=utf-8')
c.header('Cache-Control', 'max-age=0, no-cache, no-store, must-revalidate')
const style = resolveStyle(c.req.query('style'))
let badge = makeBadge({
label: c.req.query('label') ?? 'watching',
message: activity && activity.details
? activity.details
: c.req.query('fallback') ?? 'nothing rn',
labelColor: c.req.query('labelColor') ?? 'gray',
color: c.req.query('color') ?? '#f47521',
style
})
if (!['social', 'for-the-badge'].includes(style) && c.req.query('hideLogo') !== 'true')
badge = injectLogo(badge, crunchyroll)
return c.body(badge)
})
app.get('/presence/:id', c => {
c.header('Access-Control-Allow-Origin', '*')
const presence = presences.get(c.req.param('id'))
if (!presence) return c.json({ status: PresenceUpdateStatus.Offline, client_status: {}, activities: [] })
return c.json({ ...presence, user: undefined })
})
app.get('/openspotify/:id', c => {
const presence = presences.get(c.req.param('id'))
const spotifyActivity = presence?.activities?.find(a => a.name === 'Spotify' && a.type === ActivityType.Listening && a.sync_id)
if (!spotifyActivity) return c.text("This user isn't listening to Spotify.")
return c.redirect(`https://open.spotify.com/track/${spotifyActivity.sync_id}`)
})
Deno.serve({ port: +env.PORT }, app.fetch)