Merge pull request #13 from Maathias/finishing

Finishing
This commit was merged in pull request #13.
This commit is contained in:
Mateusz Pstrucha authored and GitHub committed 2021-11-03 23:04:22 +01:00
commit a2a22cd4bc
11 files changed
+175 -82

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
node_modules/
*cred.json
.env
.env.*
old/
database
+52 -23
View File
@@ -12,6 +12,11 @@ import {
putUser,
getQuery,
setQuery,
putPrevious,
getPrevious,
countPrevious,
timeValid,
allPrevious,
} from './mongo.js'
import redis from './redis.js'
@@ -32,10 +37,40 @@ function getTrackRank(tid) {
else return rank + 1
}
function parseTop(results) {
return new Promise(async (resolve, reject) => {
for (let tid in results) {
let track = await getTrack(tid)
if (results[tid] < 0) delete results[tid] // remove negative for negative points
if (track.banned) delete results[tid] // remove banned
let count = await countPrevious(tid, timeValid()) // count previous plays
if (count > 0) results[tid] = parseInt(results[tid] / (count + 1)) // halve points for every previous playback
}
const tids = Object.keys(results).sort(function (a, b) {
return results[b] - results[a]
})
resolve(tids)
})
}
function broadcast(cats) {
wsBroadcast(cats.map((cat) => ({ cat, ...current[cat] })))
}
export { getTrackRank, parseTop }
const maxPrevious = 20,
staleTop = 3e3
var topList = await countAllVotes().then((results) => parseTop(results)),
lastTop = -1,
votesSince = 0
const current = {
next: { tid: null },
status: {
@@ -46,16 +81,12 @@ const current = {
timestamp: new Date(),
},
previous: {
combo: [],
combo: (await allPrevious())
.slice(0, maxPrevious)
.map(({ tid, timestamp }) => [tid, timestamp]),
},
}
const maxPrevious = 20
var topList = [],
lastTop = -1,
votesSince = 0
const db = {
/**
* Methods for Track data
@@ -146,6 +177,7 @@ const db = {
get list() {
return topList
},
/**
* Last date topList was updated
* @type {Number} Date().now
@@ -154,9 +186,6 @@ const db = {
return lastTop
},
get changed() {
return
},
/**
* Get current Top tracks
* @returns {Promise<{}>} Array of Track ids and Fresh flag
@@ -165,14 +194,10 @@ const db = {
return new Promise((resolve, reject) => {
let now = new Date().getTime()
if (now - lastTop > 60e3 || votesSince >= 2) {
// update if stale
if (now - lastTop > staleTop || votesSince >= 2) {
countAllVotes()
.then((top) => {
return Promise.all(top.map((tid) => getTrack(tid)))
})
.then((top) => {
return top.filter(({ banned }) => !banned).map(({ id }) => id)
})
.then((results) => parseTop(results))
.then((top) => {
topList = top // update the list
lastTop = now // update list timestamp
@@ -227,17 +252,16 @@ const db = {
},
set status(chunk) {
// console.log(current.status.tid, chunk?.tid)
if (current.status.tid != chunk?.tid && current.status.tid) {
// skip duplicates
let last = current.previous.combo[0] ?? [null]
if (last[0] !== current.status.tid) {
// add new [tid, date]
current.previous.combo.unshift([
current.status.tid,
current.status.timestamp,
])
const { tid, timestamp } = current.status
current.previous.combo.unshift([tid, timestamp])
putPrevious(tid, timestamp)
// pop on overfill
if (current.previous.combo.length > maxPrevious)
@@ -300,6 +324,11 @@ const db = {
})
},
},
previous: {
put: putPrevious,
get: getPrevious,
count: countPrevious,
},
}
export default db
+15
View File
@@ -0,0 +1,15 @@
import dotenv from 'dotenv'
const env = process.env.NODE_ENV,
dotfile = {
production: '.env',
development: '.env.dev',
}[env ?? 'production']
console.info(`env: ${env}`)
const config = dotenv.config({ path: `./${dotfile}` })
if (config.error) throw `enviroment file ${dotfile} not found`
export default config
+14 -15
View File
@@ -1,4 +1,5 @@
import dotenv from 'dotenv'
import env from './env.js'
import express, { json, urlencoded } from 'express'
import cookieParser from 'cookie-parser'
import { createServer } from 'http'
@@ -13,8 +14,6 @@ import login from './routes/login.js'
import player from './routes/player.js'
import admin from './routes/admin.js'
dotenv.config()
var app = express(),
http = createServer(app)
@@ -44,16 +43,16 @@ http.on('listening', function () {
console.info(`http: listening on ${process.env.HTTP_PORT}`)
})
setInterval(async () => {
let { top, fresh } = await db.top.get()
if (fresh) {
db.current.update({
cat: 'top',
content: {
tids: top,
timestamp: db.top.lastCount,
},
})
}
setInterval(() => {
db.top.get().then(({ top, fresh }) => {
if (fresh) {
db.current.update({
cat: 'top',
content: {
tids: top,
timestamp: db.top.lastCount,
},
})
}
})
}, 2e3)
+17
View File
@@ -0,0 +1,17 @@
import mongoose from 'mongoose'
const prev = new mongoose.Schema(
{
tid: String,
timestamp: Date,
},
{
collection: 'previous',
timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' },
}
)
const Prev = mongoose.model('Prev', prev)
export default Prev
export { Prev, prev }
+51 -19
View File
@@ -1,12 +1,10 @@
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'
import Prev from './models/Previous.js'
const {
DB_HOST,
@@ -88,23 +86,35 @@ export { getTrack, putTrack, updateTrack }
* Oldest a vote can be
* @type Date
*/
const timeValid = (() => {
const timeValid = (set) => {
switch (process.env.TOP_TIME_VALID) {
default:
case 'period':
let now = new Date()
return new Date(now.getTime() - process.env.TOP_TIME_VALUE * 1e3)
case 'monday':
case 'period': // constant period
let now = set ?? new Date(),
period = process.env.TOP_TIME_VALUE
if (now.getDay() == 1) {
let saturday = new Date(new Date().setDate(now.getDate() - 2))
saturday.setHours(0, 0, 0, 0)
return saturday
}
return new Date(now.getTime() - period * 1e3)
case 'monday': // beginning of the week
var monday = new Date()
monday.setHours(0, 0, 0)
monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7))
return monday
case 'date':
case 'date': // fixed date
let date = new Date(...JSON.parse(process.env.TOP_TIME_VALUE))
return date
}
})()
}
/**
* Fetch all valid votes for a track
@@ -113,7 +123,7 @@ const timeValid = (() => {
*/
function getVotes(tid) {
return new Promise((resolve, reject) => {
Vote.find({ tid, createdAt: { $gt: timeValid } })
Vote.find({ tid, createdAt: { $gt: timeValid() } })
.then((votes) => {
resolve(votes)
})
@@ -141,6 +151,7 @@ function countTrackVotes(tid) {
resolve({
up,
down,
total: up - down,
})
})
.catch((err) => reject(err))
@@ -159,7 +170,7 @@ function getUserVote(tid, uid) {
tid,
uid,
$or: [{ value: 'up' }, { value: 'down' }],
createdAt: { $gt: timeValid },
createdAt: { $gt: timeValid() },
})
.then((vote) => resolve(vote))
.catch((err) => reject(err))
@@ -210,10 +221,10 @@ function updateUserVote(tid, uid, value) {
* Count votes per track and sort
* @returns {Promise<[]>} sorted array of Track ids
*/
function countAllVotes() {
function countAllVotes(from) {
return new Promise((resolve, reject) => {
Vote.find({
createdAt: { $gt: timeValid },
createdAt: { $gt: timeValid(from), $lt: from ?? new Date() },
$or: [{ value: 'up' }, { value: 'down' }],
})
.then((votes) => {
@@ -226,11 +237,7 @@ function countAllVotes() {
results[tid] += value
}
const keysSorted = Object.keys(results).sort(function (a, b) {
return results[b] - results[a]
})
resolve(keysSorted)
resolve(results)
})
.catch((err) => reject(err))
})
@@ -307,3 +314,28 @@ function setQuery(data) {
}
export { getQuery, setQuery }
// #### Search #### #### #### #### #### #### #### ####
function getPrevious(tid, from = timeValid(), to = new Date()) {
return Prev.findOne({ tid, createdAt: { $gt: from, $lt: to } })
}
function allPrevious(from = timeValid(), to = new Date()) {
return Prev.find({ createdAt: { $gt: from, $lt: to } }).sort({
createdAt: -1,
})
}
function countPrevious(tid, from = timeValid(), to = new Date()) {
return Prev.countDocuments({
tid,
createdAt: { $gt: from, $lt: to ?? new Date() },
})
}
function putPrevious(tid, timestamp) {
return Prev.create({ tid, timestamp })
}
export { getPrevious, allPrevious, countPrevious, putPrevious }
-3
View File
@@ -1,8 +1,5 @@
import dotenv from 'dotenv'
import redis from 'redis'
dotenv.config()
const port = process.env.CACHE_PORT
const hostName = process.env.CACHE_HOST
-3
View File
@@ -1,11 +1,8 @@
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.FB_APPID,
+24 -12
View File
@@ -1,9 +1,7 @@
import dotenv from 'dotenv'
import express from 'express'
import db from '../db.js'
dotenv.config()
import db, { parseTop } from '../db.js'
import { countAllVotes } from '../mongo.js'
const router = express.Router()
@@ -82,15 +80,29 @@ router.put(
}
)
router.get('/get/top/', ({ headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
router.get(
'/get/top/',
({ query: { mode = 'once' }, headers: { authorization } }, res) => {
if (authorization === undefined)
return res.status(401).end('Authorization required')
if (authorization != playerSecret) return res.status(403).end('Token invalid')
if (authorization != playerSecret)
return res.status(403).end('Token invalid')
db.top.get().then(({ top }) => {
res.json(top)
})
})
if (mode === 'once') {
let morning = new Date()
morning.setHours(8, 0, 0, 0)
countAllVotes(morning).then((tids) => {
parseTop(tids).then((tids) => res.json(tids))
})
} else if ((mode = 'rolling')) {
db.top.get().then(({ top }) => {
res.json(top)
})
}
}
)
export default router
+1 -4
View File
@@ -1,9 +1,6 @@
import dotenv from 'dotenv'
import WebSocket, { WebSocketServer } from 'ws'
import db from './db.js'
dotenv.config()
const port = process.env.WS_PORT,
wss = new WebSocketServer({ port: port })
@@ -35,7 +32,7 @@ wss.on('connection', async function connection(ws, req) {
},
{
cat: 'top',
tids: (await db.top.get()).top,
tids: db.top.list,
timestamp: db.top.lastCount,
},
{
-3
View File
@@ -1,10 +1,7 @@
import dotenv from 'dotenv'
import SpotifyWebApi from 'spotify-web-api-node'
import Track from './Track.js'
dotenv.config()
const spotify = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,