Merge branch 'master' into docker

This commit is contained in:
Sebastian Fudalej authored and GitHub committed 2021-09-25 13:02:12 +02:00
commit 31bac16737
17 files changed
+975 -2032

No files matched your search

+202 -26
View File
@@ -8,7 +8,13 @@ Backend server for radio-rolnik
Get track metadata
`GET` `/track/:id` get track by track id
---
#### `GET` `/track/:id` get track
Get track by track id
`RESPONSE`
```javascript
{
@@ -31,50 +37,220 @@ Get track metadata
}
```
### `/status`
---
Get currently playing track
#### `POST` `/batch` get tracks
`GET` `/status` get track, with additional metadata
Get multiple tracks by track id
`BODY`
```javascript
{
track: TrackID,
progress: Number
tids: [TrackID...]
}
```
### `/history`
Get previous and next tracks
`GET` `/history/next` next track
`RESPONSE`
```javascript
{
track: TrackID,
timestamp: Date
}
```
`GET` `/history/previous` next track
```javascript
{
tracks: [TrackID...],
timestamps: [Date...]
}
[
TrackID...
]
```
### `/search`
Search for tracks
`GET` `/search` general search
---
#### `GET` `/search/track` track search
Get a list of Track ids
`QUERY`
```javascript
{
tracks: [TrackID...],
query: String
}
```
`RESPONSE`
```javascript
{
tids: [TrackID...],
total: Number
}
```
### `/vote`
Get and update vote values for tracks
---
#### `GET` `/vote/:id` get stats
Get stats of a track.
When access token is present, also get user's vote value
`HEADERS`
```javascript
{
authorization: String
}
```
`RESPONSE`
```javascript
{
up: Number,
down: Number,
rank: Number,
cast: String // user's vote value for track. Only if authorized
}
```
---
#### `POST` `/vote/batch` get multiple stats
Get stats of multiple tracks.
When access token is present, also get user's vote value per TrackID
`HEADERS`
```javascript
{
authorization: String
}
```
`BODY`
```javascript
{
tids: [TrackID...]
}
```
`RESPONSE`
```javascript
[
{
up: Number,
down: Number,
rank: Number,
cast: String // user's vote value for track. Only if authorized
}...
]
```
---
#### `PATCH` `/vote/:tid` change vote value
Changes user's vote for a track
`HEADERS`
```javascript
{
authorization: String
}
```
`BODY`
```javascript
{
value: String // 'up', 'down', '', 'report'
}
```
`RESPONSE`
```javascript
true || false
```
### `/login`
Login and fetch access token
---
#### `GET` `/login/token` get stats
Exchange Facebook login code for an access token
`QUERY`
```javascript
{
code: String
}
```
`RESPONSE`
```html
<body>
Logowanie...
</body>
<script>
window.onload = function () {
opener.exit('<ACCESS TOKEN>')
}
</script>
```
---
## .env
Enviroment variables required
### Ports
```ini
portHttp=3010
portWs=3020
```
### Spotify API
```ini
spotifyClientId=ID
spotifyClientSecret=SECRET
```
### Facebok API
```ini
fbAppId=ID
fbSecret=SECRET
```
### Mongo DB
```ini
dbHost=IP
dbPort=PORT
dbName=DB
dbAuth=COLL
dbUser=USER
dbPass=PASSWORD
```
### Other
```ini
timeValid=monday
```
+2
View File
@@ -11,6 +11,8 @@ class Track {
this.explicit = data.explicit
this.banned = data.banned ?? false
}
static idMinLength = 22
}
export default Track
+138 -136
View File
@@ -1,143 +1,48 @@
import dotenv from 'dotenv'
import mongoose from 'mongoose'
import Jwt from 'jsonwebtoken'
dotenv.config()
import {
getTrack,
putTrack,
countTrackVotes,
getUserVote,
updateUserVote,
countAllVotes,
getUser,
putUser,
getQuery,
setQuery,
} from './mongo.js'
import { byId } from './spotify.js'
import { byId, byQuery } from './spotify.js'
import Track from './Track.js'
import { Track as TrackModel } from './models/Track.js'
import Vote from './models/Vote.js'
import { DbError } from './errors.js'
const { dbHost, dbPort, dbName, dbAuth, dbUser, dbPass } = process.env
mongoose.connect(`mongodb://${dbHost}:${dbPort}/${dbName}`, {
user: dbUser,
pass: dbPass,
authSource: 'admin',
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
const database = mongoose.connection
database.on('error', (err) => {
throw err
})
database.once('open', () => {
console.info(`db: connected`)
})
// #### #### #### ####
// #### Tracks
function getTrack(id) {
return new Promise((resolve, reject) => {
TrackModel.findOne({ id })
.then((track) => {
if (track === null) return reject(new Error(`Tracks: ${id} not found`))
resolve(track)
})
.catch((err) => {
reject(err)
})
})
/**
* Get Track placement in Top
* @param {String} tid Track id
* @returns {Number} Track's # (>0)
*/
function getTrackRank(tid) {
const rank = topList.indexOf(tid)
if (rank === -1) return rank
else return rank + 1
}
function putTrack(track) {
return new Promise((resolve, reject) => {
TrackModel.create(track).then((tdata) => {
resolve(tdata)
})
})
}
// #### #### #### ####
// #### Votes
const timeValid = (() => {
switch (process.env.timeValid) {
default:
case 'monday':
var monday = new Date()
monday.setHours(0, 0, 0)
monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7))
return monday
case 'date':
let date = new Date(...JSON.parse(process.env.valid_date))
return date
}
})()
function getVotes(tid) {
return new Promise((resolve, reject) => {
Vote.find({ tid, createdAt: { $gt: timeValid } })
.then((votes) => {
resolve(votes)
})
.catch((err) => reject(err))
})
}
function countVotes(tid) {
return new Promise((resolve, reject) => {
getVotes(tid).then((votes) => {
let up = 0,
down = 0
for (let vote of votes) {
vote.value == 'up' && up++
vote.value == 'down' && down++
}
resolve({
up,
down,
})
})
})
}
function getUserVote(tid, uid) {
return new Promise((resolve, reject) => {
Vote.findOne({ tid, uid, createdAt: { $gt: timeValid } })
.then((vote) => resolve(vote))
.catch((err) => reject(err))
})
}
function updateUserVote(tid, uid, value) {
return new Promise((resolve, reject) => {
// check if vote already exists
getUserVote(tid, uid).then((vote) => {
if (vote) {
// vote exists
if (vote.value != value) {
// new value is different
Vote.updateOne({ _id: vote._id }, { value }).then((newVote) => {
// updated vote
resolve(!!newVote.ok)
})
} else {
// unchanged value
resolve(true)
}
} else {
// create new vote
Vote.create({ uid, tid, value }).then((newVote) => {
// created vote
resolve(!!newVote)
})
}
})
})
}
var topList = [],
lastTop = -1
const db = {
/**
* Methods for Track data
*/
tracks: {
/**
* Get track by id.
* DB first, then online
* @param {String} id Track id
* @returns {Promise<Track>} Track object
*/
get: (id) => {
return new Promise((resolve, reject) => {
// query db first
@@ -151,21 +56,118 @@ const db = {
resolve(track)
})
.catch((spotifyErr) => {
console.error(spotifyErr)
reject(new Error(`Could not retrieve track`))
reject(
new DbError('DbErrorNotFound', `Could not retrieve track`)
)
})
})
})
},
put: putTrack,
},
votes: {
getTrack: (tid) => {},
getTrackStats: countVotes,
getUser: (uid) => {},
/**
* Get Track's stats.
* @param {String} tid Track id
* @returns {Promise<{}>} Votes up and down, rank
*/
getTrackStats: (tid) => {
return new Promise((resolve, reject) => {
countTrackVotes(tid)
.then((stats) => {
resolve({ ...stats, rank: getTrackRank(tid) })
})
.catch((err) => reject(err))
})
},
getUserTrack: getUserVote,
putUserTrack: updateUserVote,
},
users: {
getUser: getUser,
newUser: putUser,
/**
* Verify token content
* @param {String} jwt
* @returns {Promise<{}>} Decoded token content (User data)
*/
verifyJwt: (jwt) => {
return new Promise((resolve, reject) => {
Jwt.verify(jwt ?? '', process.env.fbSecret, (err, decoded) => {
if (err) return reject(err)
resolve(decoded)
})
})
},
},
top: {
/**
* Current Top tracks
* @type {Array} Array of Track ids
*/
get list() {
return topList
},
/**
* Last date topList was updated
* @type {Number} Date().now
*/
get lastCount() {
return lastTop
},
/**
* Get current Top tracks
* @returns {Promise<[]>} Array of Track ids
*/
get: () => {
return new Promise((resolve, reject) => {
let now = new Date().getTime()
if (now - lastTop > 1e3) {
countAllVotes()
.then((top) => {
topList = top
lastTop = now
resolve(top)
})
.catch((err) => reject(err))
} else resolve(topList)
})
},
getTrackRank: getTrackRank,
},
search: {
query: (query) => {
return new Promise((resolve, reject) => {
const market = 'PL'
getQuery(query, market)
.then((search) => {
if (search === null) {
byQuery(query)
.then(({ tids, total }) => {
const out = {
query,
tids,
total,
market,
}
resolve(out)
setQuery(out)
})
.catch((err) => reject(err))
} else {
resolve({
query: search.query,
tids: search.tids,
total: search.total,
market: search.market,
})
}
})
.catch((err) => reject(err))
})
},
},
}
export default db
+8
View File
@@ -0,0 +1,8 @@
class DbError extends Error {
constructor(name, message, ...args) {
super(message, ...args)
this.name = name ?? 'DbError'
}
}
export { DbError }
+23 -11
View File
@@ -4,11 +4,12 @@ import cookieParser from 'cookie-parser'
import { createServer } from 'http'
import { broadcast } from './socket.js'
import db from './db.js'
import track from './routes/track.js'
import history from './routes/history.js'
import search from './routes/search.js'
import vote from './routes/vote.js'
import login from './routes/login.js'
dotenv.config()
@@ -21,9 +22,9 @@ app.use(cookieParser())
app.set('port', process.env.portHttp)
app.use('/track', track)
app.use('/history', history)
app.use('/search', search)
app.use('/vote', vote)
app.use('/login', login)
www.listen(process.env.portHttp)
@@ -32,18 +33,29 @@ www.on('error', function (error) {
throw error
}
console.log(`Error: port ${process.env.portHttp}: ${error.code}`)
console.info(`Error: port ${process.env.portHttp}: ${error.code}`)
})
www.on('listening', function () {
console.log(`www: listening on ${process.env.portHttp}`)
console.info(`www: listening on ${process.env.portHttp}`)
})
setInterval(() => {
broadcast({
cat: 'status',
trackid: '2FBP8xsTWbJv3zjc1Dix0c',
progress: 20e3 + new Date().getMilliseconds(),
paused: false,
})
var i = 0
setInterval(async () => {
broadcast([
{
cat: 'status',
trackid: db.top.list[i],
progress: 20e3 + new Date().getMilliseconds(),
paused: false,
},
{
cat: 'top',
trackids: await db.top.get(),
timestamp: db.top.lastCount,
},
])
i++
if (i >= db.top.list.length) i = 0
}, 10e3)
+19
View File
@@ -0,0 +1,19 @@
import mongoose from 'mongoose'
const search = new mongoose.Schema(
{
query: String,
market: String,
tids: Array,
total: Number,
},
{
collection: 'search',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const Search = mongoose.model('Search', search)
export default Search
export { Search as Vote, search as vote }
+21
View File
@@ -0,0 +1,21 @@
import mongoose from 'mongoose'
const user = new mongoose.Schema(
{
id: String,
name: String,
accessToken: String,
tokenExpires: Date,
banned: Boolean,
perms: Number,
},
{
collection: 'users',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const User = mongoose.model('User', user)
export default User
export { User, user }
+289
View File
@@ -0,0 +1,289 @@
import dotenv from 'dotenv'
import mongoose from 'mongoose'
dotenv.config()
import TrackModel from './models/Track.js'
import Vote from './models/Vote.js'
import User from './models/User.js'
import Search from './models/Search.js'
const { dbHost, dbPort, dbName, dbAuth, dbUser, dbPass } = process.env
mongoose.connect(`mongodb://${dbHost}:${dbPort}/${dbName}`, {
user: dbUser,
pass: dbPass,
authSource: dbAuth,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
const database = mongoose.connection
database.on('error', (err) => {
throw err
})
database.once('open', () => {
console.info(`db: connected`)
})
// #### Tracks #### #### #### #### #### #### #### ####
/**
* Fetch track data from database
* @param {String} id track id
* @returns {Promise<{}>} track data
*/
function getTrack(id) {
return new Promise((resolve, reject) => {
TrackModel.findOne({ id })
.then((track) => {
if (track === null) return reject(new Error(`Tracks: ${id} not found`))
resolve(track)
})
.catch((err) => reject(err))
})
}
/**
* Add track to database
* @param {Track} track new track
* @returns {Object} tdata
*/
function putTrack(track) {
return new Promise((resolve, reject) => {
TrackModel.create(track)
.then((tdata) => {
resolve(tdata)
})
.catch((err) => reject(err))
})
}
export { getTrack, putTrack }
// #### Votes #### #### #### ######## #### #### ####
/**
* Date range for valid tracks.
* Oldest a vote can be
* @type Date
*/
const timeValid = (() => {
switch (process.env.timeValid) {
default:
case 'monday':
var monday = new Date()
monday.setHours(0, 0, 0)
monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7))
return monday
case 'date':
let date = new Date(...JSON.parse(process.env.valid_date))
return date
}
})()
/**
* Fetch all valid votes for a track
* @param {String} tid track id
* @returns {Promise<[]>} array of votes
*/
function getVotes(tid) {
return new Promise((resolve, reject) => {
Vote.find({ tid, createdAt: { $gt: timeValid } })
.then((votes) => {
resolve(votes)
})
.catch((err) => reject(err))
})
}
/**
* Get and count all votes for a track
* @param {String} tid
* @returns
*/
function countTrackVotes(tid) {
return new Promise((resolve, reject) => {
getVotes(tid)
.then((votes) => {
let up = 0,
down = 0
for (let vote of votes) {
vote.value == 'up' && up++
vote.value == 'down' && down++
}
resolve({
up,
down,
})
})
.catch((err) => reject(err))
})
}
/**
* Get User's vote value for a track
* @param {String} tid Track id
* @param {String} uid User id
* @returns {Promise<{}>} user's Vote object
*/
function getUserVote(tid, uid) {
return new Promise((resolve, reject) => {
Vote.findOne({
tid,
uid,
$or: [{ value: 'up' }, { value: 'down' }],
createdAt: { $gt: timeValid },
})
.then((vote) => resolve(vote))
.catch((err) => reject(err))
})
}
/**
* Update User's vote value for a track
* @param {String} tid Track id
* @param {String} uid User id
* @param {('up'|'down'|'report'|'')} value new vote value
* @returns {Promise<boolean>} vote updated?
*/
function updateUserVote(tid, uid, value) {
return new Promise((resolve, reject) => {
// check if vote already exists
getUserVote(tid, uid)
.then((vote) => {
if (vote && (vote ?? {}).value != 'report') {
// vote exists
if (vote.value != value) {
// new value is different
Vote.updateOne({ _id: vote._id }, { value })
.then((newVote) => {
// updated vote
resolve(!!newVote.ok)
})
.catch((err) => reject(err))
} else {
// unchanged value
resolve(true)
}
} else {
// create new vote
Vote.create({ uid, tid, value })
.then((newVote) => {
// created vote
resolve(!!newVote)
})
.catch((err) => reject(err))
}
})
.catch((err) => reject(err))
})
}
/**
* Count votes per track and sort
* @returns {Promise<[]>} sorted array of Track ids
*/
function countAllVotes() {
return new Promise((resolve, reject) => {
Vote.find({
createdAt: { $gt: timeValid },
$or: [{ value: 'up' }, { value: 'down' }],
})
.then((votes) => {
let results = {}
for (let { tid, value } of votes) {
value = { up: 1, down: -1 }[value]
results[tid] ?? (results[tid] = 0)
results[tid] += value
}
const keysSorted = Object.keys(results).sort(function (a, b) {
return results[b] - results[a]
})
resolve(keysSorted)
})
.catch((err) => reject(err))
})
}
export {
timeValid,
getVotes,
countTrackVotes,
getUserVote,
updateUserVote,
countAllVotes,
}
// #### Users #### #### #### #### #### #### #### ####
/**
* Get User's data
* @param {String} id
* @returns {Promise<{}>} User data
*/
function getUser(id) {
return new Promise((resolve, reject) => {
User.findOne({ id })
.then((user) => resolve(user))
.catch((err) => reject(err))
})
}
/**
* Create a new User
* @param {Object} user User data
* @param {String} user.id User's id
* @param {String} user.name User's display name
* @returns
*/
function putUser({ id, name, accessToken, tokenExpires }) {
return new Promise((resolve, reject) => {
User.create({
id,
name,
accessToken,
tokenExpires,
banned: false,
perms: 0,
})
.then((user) => resolve(user))
.catch((err) => reject(err))
})
}
export { getUser, putUser }
// #### Search #### #### #### #### #### #### #### ####
function getQuery(query, market) {
return new Promise((resolve, reject) => {
Search.findOne({
query,
market,
createdAt: { $gt: new Date(new Date() - 36e5 * 24 * 2) },
})
.then((search) => resolve(search))
.catch((err) => reject(err))
})
}
function setQuery(data) {
return new Promise((resolve, reject) => {
Search.create(data)
.then((search) => resolve(search))
.catch((err) => reject(err))
})
}
export { getQuery, setQuery }
-1755
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -29,8 +29,11 @@
"cookie-parser": "^1.4.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"got": "^11.8.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.13.9",
"nodemon": "^2.0.13",
"spotify-to-yt": "^1.0.5",
"spotify-web-api-node": "^5.0.2",
"ws": "^8.2.2"
}
-17
View File
@@ -1,17 +0,0 @@
import express from 'express'
const router = express.Router()
router.get('/', (req, res) => {
res.send('Get tracks history information (IDs only)')
})
router.get('/next', (req, res) => {
res.send('next in queue')
})
router.get('/previous', (req, res) => {
res.send('x previous tracks')
})
export default router
+69
View File
@@ -0,0 +1,69 @@
import dotenv from 'dotenv'
import express from 'express'
import got from 'got'
import Jwt from 'jsonwebtoken'
import db from '../db.js'
dotenv.config()
const router = express.Router()
const appId = process.env.fbAppId,
secret = process.env.fbSecret
router.get('/token', ({ query: { code } }, res) => {
if (code === undefined) return res.status(400).end('Facebook code required')
if (code.length < 1)
return res.status(400).end('Facebook code needs to be of non zero length')
got(
`https://graph.facebook.com/v12.0/oauth/access_token?client_id=${appId}&redirect_uri=${'https://radio.rolniknysa.pl/api/login/token'}&client_secret=${secret}&code=${code}`
)
.json()
.then(({ access_token, expires_in }) => {
got(`https://graph.facebook.com/me?access_token=${access_token}`)
.json()
.then(({ name, id }) => {
const jwt = Jwt.sign(
{
name,
id,
},
secret
)
res.end(
`<body>Logowanie...</body><script>window.onload=function(){opener.exit(${JSON.stringify(
{ jwt }
)})}</script>`
)
db.users
.getUser(id)
.then((user) => {
if (user === null)
db.users.newUser({
name,
id,
accessToken: access_token,
tokenExpires: new Date(
new Date().getTime() + expires_in * 1e3
),
})
})
.catch((err) => console.error(err))
})
.catch((err) => {
res
.status(400)
.end('There was an error processing your profile information')
console.error(err)
})
})
.catch((err) => {
res.status(400).end('There was an error requesting an access token')
console.error(err)
})
})
export default router
+13 -11
View File
@@ -1,20 +1,22 @@
import express from 'express'
import { byQuery } from '../spotify.js'
import db from '../db.js'
const router = express.Router()
router.get('/', (req, res) => {
res.send('Query search')
})
router.get('/track/:query?', ({ params: { query } }, res) => {
if (query === undefined) return res.status(400).end('Track ID required')
if (query.length < 1) return res.status(400).end('Track ID invalid')
router.get('/track/:query', (req, res) => {
byQuery(req.params.query).then(({ tracks, total }) => {
res.send({
tracks,
total,
let time = process.hrtime()
db.search
.query(query)
.then(({ tids, total }) =>
res.send({ tids, total, elapsed: process.hrtime(time) })
)
.catch((err) => {
res.status(500).end('There was an error retrieving track data')
console.error(err)
})
})
})
export default router
+21 -13
View File
@@ -1,28 +1,36 @@
import express from 'express'
import { byId } from '../spotify.js'
import db from '../db.js'
import Track from '../Track.js'
const router = express.Router()
router.get('/', (req, res) => {
res.send('Get track metadata.')
router.post('/batch/', ({ body: { tids } }, res) => {
if (tids === undefined) return res.status(400).end('Track ids array required')
if (tids.length < 1) return res.end([])
Promise.all(tids.map((tid) => db.tracks.get(tid)))
.then((tracks) => res.send(tracks))
.catch((err) => {
res.status(500).end('There was an error fetching tracks ')
console.error(err)
})
})
router.get('/:id', (req, res) => {
if (req.query.votes) {
return res.send({
set: 'down',
up: 20,
down: 10,
})
}
router.get('/:id?', ({ params: { id } }, res) => {
if (id === undefined) return res.status(400).end('Track ID required')
if (id.length < Track.idMinLength)
return res.status(400).end('Track ID too short')
db.tracks
.get(req.params.id)
.get(id)
.then((track) => res.send(track))
.catch((err) => {
res.status(400).end()
if ((err.name = 'DbErrorNotFound'))
return res.status(404).end(err.message)
else res.status(500).end('There was an error fetching track data')
console.error(err)
})
})
+119 -18
View File
@@ -1,29 +1,130 @@
import express from 'express'
import db from '../db.js'
import Track from '../Track.js'
const router = express.Router()
router.get('/', (req, res) => {
res.send('Vote for track.')
})
// get multiple track stats
router.post(
'/batch/',
async ({ body: { tids }, headers: { authorization } }, res) => {
var udata = false
router.get('/:id/', ({ params }, res) => {
db.votes.getTrackStats(params.id).then((stats) => {
res.send(stats)
})
})
if (authorization) {
if (authorization.length < 1)
return res.status(400).end('Access token empty')
router.get('/:id/cast', ({ params, query }, res) => {
db.votes.getUserTrack(params.id, query.uid).then((vote) => {
res.send(vote ? vote.value : '')
})
})
try {
udata = await db.users.verifyJwt(authorization)
} catch (err) {
return res.status(400).end('Access token invalid')
}
}
router.patch('/:id/', ({ params, body }, res) => {
db.votes.putUserTrack(params.id, body.uid, body.value).then((vote) => {
res.end(JSON.stringify(vote))
})
})
if (tids === undefined)
return res.status(400).end('List of Track ids required')
if (tids.length < 1) return res.end([])
Promise.all([
Promise.all(tids.map((tid) => db.votes.getTrackStats(tid))),
udata &&
Promise.all(tids.map((tid) => db.votes.getUserTrack(tid, udata.id))),
])
.then(([stats, votes]) => {
if (udata && votes)
stats = stats.map((stat, i) => ({
...stat,
cast: votes[i]?.value ?? '',
}))
res.send(stats)
})
.catch((err) => {
res.status(500).end('There was an error while fetching some stats')
console.error(err)
})
}
)
// get tracks stats
router.get(
'/:tid/',
async ({ params: { tid }, headers: { authorization } }, res) => {
var udata = false
if (authorization) {
if (authorization.length < 1)
return res.status(400).end('Access token empty')
try {
udata = await db.users.verifyJwt(authorization)
} catch (err) {
return res.status(400).end('Access token invalid')
}
}
if (tid === undefined) return res.status(400).end('Track ID required')
if (tid.length < Track.idMinLength)
return res.status(400).end('Track ID too short')
Promise.all([
db.votes.getTrackStats(tid),
udata && db.votes.getUserTrack(tid, udata.id),
])
.then(([stats, vote]) => {
// attatch user's vote if authorized
if (udata) stats.cast = vote ? vote.value : '' // null vote counts as empty
res.send(stats)
})
.catch((err) => {
res.status(500).end('There was an error getting stats')
console.error(err)
})
}
)
// update users vote
router.patch(
'/:tid/',
({ params: { tid }, body: { value }, headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Access token required')
if (authorization.length < 1)
return res.status(400).end('Access token invalid')
if (tid === undefined) return res.status(400).end('Track ID required')
if (tid.length < Track.idMinLength)
return res.status(400).end('Track ID too short')
if (value === undefined) return res.status(400).end('Vote value required')
if (!['up', 'down', '', 'report'].includes(value))
return res.status(400).end('Invalid vote value')
db.users
.verifyJwt(authorization)
.then(({ id }) => {
db.votes
.putUserTrack(tid, id, value)
.then((ok) => {
res.end(ok.toString())
console.info(`vote# ${id} ${value} ${tid}`)
})
.catch((err) => {
res.status(500).end('There was an error updating your vote')
console.error(err)
})
})
.catch((err) => {
res.end('false')
console.error(err)
})
}
)
export default router
+10 -14
View File
@@ -1,12 +1,13 @@
import dotenv from 'dotenv'
import WebSocket, { WebSocketServer } from 'ws'
import db from './db.js'
dotenv.config()
const port = process.env.portWs,
wss = new WebSocketServer({ port: port })
console.log('ws: listening on ' + port)
console.info('ws: listening on ' + port)
function broadcast(data) {
wss.clients.forEach((client) => {
@@ -16,8 +17,8 @@ function broadcast(data) {
})
}
wss.on('connection', function connection(ws) {
console.log('connected')
wss.on('connection', async function connection(ws, req) {
console.info(`socket # ${req.headers['x-real-ip']} + `)
function send(data) {
ws.send(JSON.stringify(data))
@@ -35,11 +36,8 @@ wss.on('connection', function connection(ws) {
},
{
cat: 'top',
trackids: [
'0VdSlJ7owUK1MuS8Kp7LdE',
'5svu5mLA4U2kdxPj1tLJ2I',
'6BfbSHE9ytCTF910g3wNdj',
],
trackids: await db.top.get(),
timestamp: db.top.lastCount,
},
{
cat: 'status',
@@ -49,13 +47,11 @@ wss.on('connection', function connection(ws) {
},
])
ws.on('message', (message) => {
console.log('received: %s', message)
})
ws.on('message', (message) => console.info('received: %s', message))
ws.on('close', (message) => {
console.log('disconnected')
})
ws.on('close', (message) =>
console.info(`socket # ${req.headers['x-real-ip']} - `)
)
})
export { wss, broadcast }
+38 -31
View File
@@ -7,59 +7,66 @@ const spotify = new SpotifyWebApi({
clientSecret: '13858e98eb264cf78251072f2ea5e96d',
})
spotify.clientCredentialsGrant().then(
function (data) {
console.log('Spotify: access token granted')
function grantToken() {
spotify
.clientCredentialsGrant()
.then(
function ({ body: { access_token, expires_in } }) {
console.info('spotify: access token granted ' + expires_in)
// Save the access token so that it's used in future calls
spotify.setAccessToken(data.body['access_token'])
},
function (err) {
throw err
}
)
spotify.setAccessToken(access_token)
setTimeout(grantToken, expires_in * 1e3)
},
function (err) {
throw err
}
)
.catch((err) => {
console.error(err)
})
}
grantToken()
function byId(id) {
return new Promise((resolve, reject) => {
if (typeof id != 'string')
return reject(new Error('Incorrect id, must by type String'))
if (id.length < 22) return reject(new Error('Id too short'))
if (id.length < Track.idMinLength) return reject(new Error('Id too short'))
spotify
.getTrack(id)
.then(({ body }) => {
let tdata = {
...body,
title: body.name,
artists: body.artists.map((a) => a.name),
album: {
name: body.album.name,
art: body.album.images[0].url,
year: body.album.release_date.slice(0, 4),
},
duration: body.duration_ms,
}
resolve(new Track(tdata))
})
.catch((err) => {
reject(err)
resolve(
new Track({
...body,
title: body.name,
artists: body.artists.map((a) => a.name),
album: {
name: body.album.name,
art: body.album.images[0].url,
year: body.album.release_date.slice(0, 4),
},
duration: body.duration_ms,
})
)
})
.catch((err) => reject(err))
})
}
function byQuery(query) {
return new Promise((resolve, reject) => {
spotify
.searchTracks(query)
.searchTracks(query, { market: 'PL' })
.then((response) => {
resolve({
tracks: response.body.tracks.items.map((tdata) => tdata.id),
tids: response.body.tracks.items.map((tdata) => tdata.id),
total: response.body.tracks.total,
})
})
.catch((err) => {
reject(err)
})
.catch((err) => reject(err))
})
}