-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
315 lines (258 loc) · 9.95 KB
/
server.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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import betterSqlite3 from "better-sqlite3";
import { readFileSync } from 'fs';
import { createServer } from 'https';
import mpvAPI from "node-mpv";
import SpotifyToYoutube from 'spotify-to-youtube';
import { parse } from "spotify-uri";
import SpotifyWebApi from 'spotify-web-api-node';
import { WebSocket, WebSocketServer } from "ws";
import ytdl from "ytdl-core";
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const spotifyApi = new SpotifyWebApi({
clientId: "745eb77e7f074d938c34f5371de297c1",
clientSecret: "755400b349f541e4aa84660ecf34fa85"
});
const spotifyToYoutube = SpotifyToYoutube(spotifyApi)
// client credentials grant
async function grantCredentials() {
try {
const data = await spotifyApi.clientCredentialsGrant().catch(console.error)
spotifyApi.setAccessToken(data.body['access_token']);
setTimeout(grantCredentials, data.body['expires_in'] * 1000);
} catch (e) {
console.log("Spotify grant credentials error: " + e)
}
}
grantCredentials()
// HELPER FUNCTIONS
async function convertAnyURLToYouTubeURL(url) {
let ytUrl;
if (url.includes("youtube.com") || url.includes("youtu.be")) {
ytUrl = url
} else if (url.includes("spotify")) {
ytUrl = await spotifyToYoutube(parse(url).id).catch(console.error)
}
return ytUrl;
}
// SQLITE
console.log("connecting to database");
const db = betterSqlite3("nearer.db");
db.pragma(`journal_mode = WAL`);
db.exec(`CREATE TABLE IF NOT EXISTS queue
( id INTEGER PRIMARY KEY,
srcUrl TEXT,
playUrl TEXT,
title TEXT,
length INTEGER,
thumbnail TEXT,
queuedBy TEXT,
queuedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
skipped INTEGER DEFAULT 0)`);
db.exec(`CREATE TABLE IF NOT EXISTS log
( id INTEGER PRIMARY KEY,
type TEXT,
data TEXT,
user TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`)
// STATE
console.log(`initializing player state`)
var playerState = {
playing: true,
loading: false,
time: 0,
volume: 0.2,
currentSong: null
}
// MPV
console.log("initializing mpv");
const mpvPlayer = new mpvAPI({ "audio-only": true }, ['--no-video'])
mpvPlayer.start()
.then(() => {
console.log("MPV initialized successfully. setting up other servers")
mpvPlayer.on("stopped", function () {
console.log(new Date(), "player stop (song ended?)")
next();
})
mpvPlayer.on("timeposition", function (time) {
console.log("timeposition")
setTime(parseInt(time))
})
mpvPlayer.on('statuschange', mpvStatus => {
console.log('mpvstatus', mpvStatus);
})
// TODO: put back
// // send time position every second
// setInterval(() => {
// if (playerState.playing) {
// mpvPlayer.getTimePosition().then((time) => {
// setTime(parseInt(time))
// }).catch(console.error)
// }
// }, 1000)
// EVENT HELPERS
async function storeInLog(type, data, user) {
const timestamp = new Date().toISOString();
const stmt = db.prepare("INSERT INTO log (type, data, user, timestamp) VALUES (?, ?, ?, ?)");
stmt.run(type, data, user, timestamp);
broadcast("log", { entry: { type, data, user, timestamp } });
}
// EVENT HANDLERS
async function enqueueSong(srcUrl, queuedBy) {
console.log(`${queuedBy} added ${srcUrl} to queue`)
try {
const ytUrl = await convertAnyURLToYouTubeURL(srcUrl);
const info = await ytdl.getInfo(ytUrl)
const title = info.videoDetails.title
const length = info.videoDetails.lengthSeconds
const thumbnail = info.videoDetails.thumbnails[0].url
// const format = ytdl.chooseFormat(ytdl.filterFormats(info.formats, "audioonly"), { quality: "highestaudio" });
// const playUrl = format.url; // TODO: just use youtube url
const playUrl = ytUrl;
console.log("queueing ", ytUrl)
// store in queue
const stmt = db.prepare("INSERT INTO queue (srcUrl, playUrl, title, length, thumbnail, queuedBy) VALUES (?, ?, ?, ?, ?, ?)");
const res = stmt.run(srcUrl, playUrl, title, length, thumbnail, queuedBy);
storeInLog("enqueueSong", title, queuedBy)
if (!playerState.currentSong) {
next();
}
broadcast("queued", { song: { id: res.lastInsertRowid, srcUrl, playUrl, title, length, thumbnail, queuedBy } });
} catch (e) {
console.log(e)
broadcast("failed", { url: srcUrl })
}
}
async function enqueuePlaylist(playlistURL, queuedBy) {
// convert playlist url to playlist id
const playlist_id = await spotifyApi.getPlaylist(playlistURL).then(data => data.body.id)
await spotifyApi.getPlaylistTracks(playlist_id, {
limit: 100 // check if .next is null to see if theres another page
})
.then(data => data.body.items.map(item => item.track.uri)) // get track uris
.then(uris => uris.forEach(uri => enqueue(uri, queuedBy)))
.catch(() => console.error(`Failed to queue playlist ${playlist_id}`))
}
async function enqueue(ytOrSongOrPlaylistURL, queuedBy) {
if (ytOrSongOrPlaylistURL.includes('spotify.com/playlist')) {
await enqueuePlaylist(ytOrSongOrPlaylistURL, queuedBy)
} else {
await enqueueSong(ytOrSongOrPlaylistURL, queuedBy)
}
}
async function play() {
playerState.playing = true;
await mpvPlayer.play().catch(console.error)
broadcast("playing", { playing: true });
}
async function pause() {
playerState.playing = false;
await mpvPlayer.pause().catch(console.error)
broadcast("playing", { playing: false });
}
async function setVolume(volume) {
playerState.volume = volume;
await mpvPlayer.volume(volume * 100).catch(console.error)
broadcast("volume", { volume });
}
function setCurrentSong(currentSong) {
playerState.currentSong = currentSong;
broadcast("currentSong", { currentSong });
}
function setLoading(loading) {
playerState.loading = loading;
broadcast("loading", { loading });
}
function setTime(time) {
playerState.time = time;
broadcast("time", { time });
}
async function next() {
console.log(new Date(), "next() called")
const newCurrentSong = playerState?.currentSong ?
db.prepare("SELECT * FROM queue WHERE id > ? ORDER BY id ASC LIMIT 1").get(playerState?.currentSong?.id) :
db.prepare("SELECT * FROM queue ORDER BY id DESC LIMIT 1").get();
if (!newCurrentSong) {
setCurrentSong(null)
setTime(0);
await mpvPlayer.pause().catch(console.error);
return;
}
setLoading(true)
setCurrentSong(newCurrentSong)
setTime(0);
console.log(new Date(), "loading song...", newCurrentSong.playUrl)
await mpvPlayer.load(newCurrentSong.playUrl).catch(console.error)
console.log(new Date(), "playing song...", newCurrentSong.playUrl)
await mpvPlayer.play().catch(console.error)
console.log(new Date(), "song loaded and playing")
setLoading(false);
}
// WEBSOCKET
console.log("starting websocket server at port 3002");
const server = createServer({
cert: readFileSync('/etc/letsencrypt/live/nearer.blacker.caltech.edu/cert.pem'),
key: readFileSync('/etc/letsencrypt/live/nearer.blacker.caltech.edu/privkey.pem')
});
const wss = new WebSocketServer({ server });
// broadcast function
const broadcast = (type, data) => {
console.log("broadcasting", type, JSON.stringify(data))
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ type, ...(data || {}) }));
}
});
};
// server
var timeout;
wss.on("connection", (ws) => {
console.log("client connected");
// get last 10 songs from queue and send it along the initial player state
const queue = db.prepare("SELECT * FROM queue ORDER BY id DESC LIMIT 10").all()
const log = db.prepare("SELECT * FROM log ORDER BY id DESC LIMIT 10").all()
// send initial data
ws.send(JSON.stringify({ type: "init", queue, log, playerState }));
ws.on("message", async function (data) {
const message = JSON.parse(decodeURIComponent(data));
switch (message.type) {
case "enqueue":
enqueue(message.url, message.user);
break;
case "play":
storeInLog("play", null, message.user)
await play().catch(console.error);
break;
case "pause":
storeInLog("pause", null, message.user)
await pause().catch(console.error);
break;
case "skip":
storeInLog("skip", playerState.currentSong.title, message.user)
next();
break;
case "volume":
// debounce logging to 0.5s
clearTimeout(timeout);
timeout = setTimeout(() => {
storeInLog("volume", message.volume, message.user)
}, 500)
await setVolume(message.volume).catch(console.error);
break;
}
});
});
server.listen(8080);
console.log("server listening at 8080")
})
.catch((error) => {
console.error("MPV Failed to initialize. Aborting.");
console.error(error);
})
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
console.log(reason.stack)
// application specific logging, throwing an error, or other logic here
});