-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
134 lines (130 loc) · 4.65 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
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const app = express();
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
var sqlite3 = require('sqlite3');
app.use(express.static(path.join(__dirname, 'frontend')));
app.use(bodyParser.json({limit: '50mb'}));
var db = new sqlite3.Database('databases/trackspreview.db');
db.run("CREATE TABLE TracksPreviews (id TEXT PRIMARY KEY, previewUrl text)", (err) => {})
var db_scores = new sqlite3.Database('databases/scores.db');
db_scores.run("CREATE TABLE StreakScores (playlistId TEXT, playerName text, score int)", (err) => {})
let lobbyIndex = 1;
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('createLobby', (callback) => {
console.log("createlobby");
const lobbyId = (lobbyIndex++).toString();
socket.join(lobbyId);
callback({
lobbyId: lobbyId
})
});
socket.on('tracks', (data) => {
const lobbyId = data.lobbyId;
const tracks = data.tracks;
const correct_track_id = data.correct_track_id;
io.to(lobbyId).emit("tracks", {tracks: tracks, correct_track_id: correct_track_id});
})
socket.on('playerJoin', (data) => {
const lobbyId = data.lobbyId;
const playerId = data.playerId;
console.log("playerJoin lobby:", lobbyId, "player:", playerId);
socket.join(lobbyId);
io.to(lobbyId).emit("playerJoin", {playerId: playerId});
});
socket.on('playerGuess', (data) => {
const lobbyId = data.lobbyId;
const playerId = data.playerId;
const guessId = data.guessId;
console.log("playerGuess lobby:", lobbyId, "player:", playerId, "guess:", guessId);
io.to(lobbyId).emit("playerGuess", {playerId: playerId, guessId: guessId});
});
});
function checkInDb(track) {
return new Promise(resolve => {
db.get("SELECT previewUrl from TracksPreviews WHERE id = ?", track.id, (err, data) => {
if (data && data.previewUrl) {
resolve(data.previewUrl)
} else {
resolve(null);
}
})
});
}
function saveInDb(id, previewUrl) {
db.run("INSERT INTO TracksPreviews VALUES (?, ?)", [id, previewUrl], err => {
if (err) {
console.log("Insert error", err)
}
});
}
async function hackFetchPreviewUrl(track) {
// first check in db to avoid too many requests to the embed site (scrapping is frowned upon after all)
let dbPreviewUrl = await checkInDb(track);
if (dbPreviewUrl) {
return dbPreviewUrl;
}
let embedUrl = "https://open.spotify.com/embed/track/" + track.id;
let response = await fetch(embedUrl);
let text = await response.text();
let matched = text.match(/preview_url%22%3A%22(.*)%3Fcid/);
let previewUrl = "";
if (matched && matched.length > 0) {
previewUrl = decodeURIComponent(matched[1]);
}
// Save in db for next time !
saveInDb(track.id, previewUrl);
return previewUrl;
}
app.post('/api/forcesearch', async (req, res) => {
let tracks = req.body.tracks;
// console.log(tracks);
for (var i = 0; i < tracks.length; i++) {
if (!tracks[i].preview_url) {
tracks[i].preview_url = await hackFetchPreviewUrl(tracks[i]);
}
}
res.json({
tracks: tracks
});
});
function loadStreakScoresFromDb(playlistId) {
return new Promise(resolve => {
db_scores.all("SELECT * from StreakScores WHERE playlistId = ? ORDER BY score desc LIMIT 5", playlistId, (err, data) => {
resolve(data);
})
});
}
function saveStreakScoreInDb(playlistId, playerName, score) {
return new Promise(resolve => {
db_scores.run("INSERT INTO StreakScores VALUES (?, ?, ?)", [playlistId, playerName, score], err => {
if (err) {
console.log("Insert error", err)
}
resolve(err);
});
});
}
app.post('/api/savestreakscore/', async (req, res) => {
let playlist_id = req.body.playlist_id;
let err = await saveStreakScoreInDb(req.body.playlist_id, req.body.player_name, req.body.score);
res.json({
err: err
});
});
app.get('/api/loadstreakscores/:playlist_id', async (req, res) => {
let playlistId = req.params.playlist_id;
let streakScores = await loadStreakScoresFromDb(playlistId);
res.json({
streak_scores: streakScores
});
});
server.listen(8000, () => {
console.log('listening on *:8000');
});