-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
166 lines (135 loc) · 5.03 KB
/
index.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
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
require('dotenv').config()
var events = require('events')
const fetch = require('node-fetch')
const express = require(`express`)
const expressWs = require(`@wll8/express-ws`)
var WebSocketClient = require('websocket').client;
const { app } = expressWs(express())
const PORT = process.env.SERVER_PORT || 7089
let lastPlayingState = {}
// Connect to spotify WS and create event
const spotifyWs = new WebSocketClient()
spotifyWs.on('connect', function (connection) {
console.log('[SpotifyWS] Connected')
connection.on('message', function (message) {
if (message.type === 'utf8') {
const msgData = JSON.parse(message.utf8Data)
if (msgData.type == 'updatedSong') {
try {
lastPlayingState = {
meta: {
source: "spotify",
url: `https://open.spotify.com/track/${msgData.id}`,
image: msgData.albumArt,
preview: msgData.preview
},
progress: msgData.progress,
title: msgData.name,
artist: msgData.artist,
album: msgData.album
}
} catch (e) { }
spotifyEvent.emit('updatedSong')
}
}
})
})
app.set('view engine', 'ejs');
app.use(express.static('public'))
app.get('/', (req, res) => {
res.status(200).send('Hello World!')
})
app.get('/playing/img', async (req, res) => {
res.setHeader('cache-control', 'public, max-age=0, must-revalidate')
res.setHeader('content-type', 'image/svg+xml; charset=utf-8')
res.status(200).send(await require('./templates/playing_img')(lastPlayingState, req.query))
})
function widgetHandler(req, res) {
res.setHeader('cache-control', 'public, max-age=0, must-revalidate')
res.setHeader('content-type', 'text/html; charset=utf-8')
res.status(200).render('widget', {
lastPlayingState: lastPlayingState,
analyticsScript: process.env.ANALYTICS_SCRIPT || ''
})
}
app.get('/widget', async (req, res) => widgetHandler(req, res))
app.get('/widget.html', async (req, res) => widgetHandler(req, res))
app.get('/playing/badge', async (req, res) => {
res.setHeader('cache-control', 'public, max-age=0, must-revalidate')
res.setHeader('content-type', 'image/svg+xml; charset=utf-8')
const replaceCharacters = (str) => {
const replacements = {
' ': '_',
'-': '--',
'_': '__',
};
return str.replace(/[-_ ]/g, (character) => {
return replacements[character] || character;
});
};
const newArtist = replaceCharacters(lastPlayingState.artist);
const newTitle = replaceCharacters(lastPlayingState.title);
// Use badge from img.shields.io
const badgeURL = `https://img.shields.io/badge/${encodeURIComponent(newArtist + ' - ' + newTitle)}-1ed760?&style=for-the-badge&logo=spotify&logoColor=white`
// Download badge from URL and send it
const badge = await fetch(badgeURL).then(res => res.buffer())
res.status(200).send(badge)
})
spotifyWs.connect(`ws://${process.env.SPTWSS_URL}/`)
var spotifyEvent = new events.EventEmitter()
app.ws(`/playing`, (ws, req) => {
function sendPlayingSong() {
if (ws.readyState == 3) {
ws.close()
return
}
ws.send(JSON.stringify({
success: true,
type: "player",
data: lastPlayingState
}))
}
sendPlayingSong()
/* ws.send(JSON.stringify({
success: true,
type: "player",
data: {
meta: {
source: "spotify",
url: "https://open.spotify.com/track/463KSxKSERdabrLZUA7MxF",
image: "https://i.scdn.co/image/ab67616d0000b27363b0b35f599f4b1a3cdd82e2"
},
progress: {
playing: true,
current: 113356,
duration: 193266
},
title: "Feelwitchu",
artist: "Tennyson",
album: "Rot"
}
})) */
spotifyEvent.on('updatedSong', sendPlayingSong)
})
app.get('/playing', async (req, res) => {
res.setHeader('cache-control', 'public, max-age=0, must-revalidate')
res.setHeader('content-type', 'application/json; charset=utf-8')
res.status(200).send(JSON.stringify({
success: true,
data: lastPlayingState
}))
})
// Every second increment lastPlayingState progress
setInterval(function () {
try {
if (lastPlayingState.progress.playing) {
lastPlayingState.progress.current += 1000
// If going over song duration, stays at the end instead of incrementing
if (lastPlayingState.progress.current >= lastPlayingState.progress.duration) {
lastPlayingState.progress.current = lastPlayingState.progress.duration
}
}
} catch (e) { }
}, 1000)
app.listen(PORT)
console.log(`[Server] Listening on :${PORT}`)