voting system revamp

This commit is contained in:
Mateusz Pstrucha committed 2020-09-19 22:00:52 +02:00
1 parent 6ee9c6f6eb
commit 3e2488b03b
4 files changed
+232 -161

No files matched your search

+72 -27
View File
@@ -42,8 +42,8 @@ var Track = mongoose.model('Track', new mongoose.Schema({
uid: String,
tid: String,
flag: String,
comment: String
}, { collection: 'votes', timestamps: { createdAt: 'createdAt', updatedAt: false } })),
comment: String,
}, { collection: 'votes', timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } })),
User = mongoose.model('User', new mongoose.Schema({
id: String,
@@ -93,62 +93,107 @@ module.exports = {
}
},
votes: {
timeValid: 60 * 60 * 12 * 1e3, // ms
add(user, track, flag) {
timeValid: () => {
var monday = new Date();
monday.setHours(0, 0, 0)
monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
return monday
},
add(user, tid, flag) {
return new Promise((resolve, reject) => {
if (typeof user == 'undefined') return reject(new Error("Not authorized"))
this.validUser(user, track.id).then(flags => {
if (flags[flag]) {
reject(new Error("Already voted"))
if (flag == 'report') {
this.report(user, tid)
} else this.validUser(user, tid).then(vote => {
if (vote) {
Vote.updateOne({
_id: vote._id
},
{
flag: flag
}).then(status => {
if (status.ok != 1) pretty.log({
data: "Vote: vote change error",
action: 'error'
})
resolve(vote)
pretty.log(`'${user.name}' changed vote to '${flag}' on '${tid}'`, 2)
})
} else {
Vote.create({
uid: user.id,
tid: track.id,
tid: tid,
flag: flag
}).then(vote => {
resolve(vote)
pretty.log(`'${user.name}' voted '${flag}' on '${track.title}'`)
pretty.log(`'${user.name}' voted '${flag}' on '${tid}'`, 2)
})
}
})
})
},
report(user, tid) {
return new Promise((resolve, reject) => {
if (typeof user == 'undefined') return reject(new Error("Not authorized"))
Vote.create({
uid: user.id,
tid: tid,
flag: 'report',
}).then(vote => {
resolve(vote)
pretty.log(`'${user.name}' reported '${tid}'`, 2)
})
})
},
validUser(user, tid) {
return new Promise((resolve, reject) => {
if (typeof user == 'undefined') reject(new Error(`User not authenticated`))
Vote.find({
Vote.findOne({
uid: user.id,
tid: tid,
$or: [
{ flag: 'up' },
{ flag: 'down' },
{ flag: null }
],
createdAt: {
$gt: new Date(new Date().setHours(0, 0, 0))
$gt: this.timeValid()
}
}, function (err, votes) {
resolve({
up: !!votes.find(vote => vote.flag == 'up'),
down: !!votes.find(vote => vote.flag == 'down'),
report: !!votes.find(vote => vote.flag == 'report')
})
}, function (err, vote) {
resolve(vote)
// resolve({
// up: !!votes.find(vote => vote.flag == 'up'),
// down: !!votes.find(vote => vote.flag == 'down'),
// report: !!votes.find(vote => vote.flag == 'report')
// })
})
})
},
validAll() {
return new Promise((resolve, reject) => {
var monday = new Date();
monday.setHours(0, 0, 0)
monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
Vote.find({
createdAt: {
// $gt: new Date(new Date().getTime() - this.timeValid)
// $gt: new Date(new Date().setHours(0, 0, 0))
$gt: monday
}
$gt: this.timeValid()
},
$or: [
{ flag: 'up' },
{ flag: 'down' }
]
}).then(function (votes) {
let results = {}
for (let vote of votes.map(vote => [vote.tid, vote.flag])) {
if (typeof results[vote[0]] == 'undefined') results[vote[0]] = 0
if (vote[1] == 'up') results[vote[0]] += 1
if (vote[1] == 'down') results[vote[0]] -= 1
for (let vote of votes) {
if (typeof results[vote.tid] == 'undefined') results[vote.tid] = {
total: 0,
up: 0,
down: 0
}
results[vote.tid][vote.flag]++
results[vote.tid].total += { 'up': 1, 'down': -1 }[vote.flag]
}
resolve(results)
})
+73 -62
View File
@@ -22,11 +22,7 @@ class Track {
this.votes = null
this.placement = null
this.flags = {
up: false,
down: false,
report: false
}
this.flag = null
}
_db(data) {
@@ -218,28 +214,40 @@ const Previous = {
values: {},
_serial: 0,
_sentAt: null,
get serial(){ return this._serial},
set serial(value){
get serial() { return this._serial },
set serial(value) {
this._serial = value
if(this._serial - this._sentAt > 5) {
this._changed = true
if (this._serial - this._sentAt > this.threshold) {
this.update()
this.changed = false
return
this._changed = false
}
this.changed = true
},
changed: true,
delay: 10e3,
_changed: true,
delay: 30e3,
threshold: 10,
interval() {
if(this.changed) this.update()
this.changed = false
if (this._changed) {
this.update()
this._changed = false
}
setTimeout(function () { Chart.interval() }, this.delay)
},
async update() {
var values = await db.votes.validAll()
this.values = values
this.tids = (Object.keys(values).sort(function (a, b) { return values[a] - values[b] })).reverse()
for (let tid in values) {
this.values = await db.votes.validAll()
this.tids = []
for (let tid in this.values) {
this.tids.push(tid)
}
this.tids.sort((a, b) => {
return this.values[b].total - this.values[a].total
})
// return console.log(this.tids)
// this.tids = (Object.keys(values).sort(function (a, b) { return values[a] - values[b] })).reverse()
for (let tid in this.values) {
let track = await Tracks.get(tid)
// tracks.get(tid).then(track => {
// track.votes = values[tid]
@@ -249,10 +257,10 @@ const Previous = {
this.tids.splice(this.tids.indexOf(tid), 1)
continue
}
track.votes = values[tid]
track.votes = this.values[tid]
track.placement = this.tids.indexOf(tid) + 1
}
this.changed = false
this._changed = false
this._sentAt = this._serial
server.emit('chart', this.get())
},
@@ -268,31 +276,31 @@ const Previous = {
_online: 0,
_auth: 0,
_authed: {},
get(id){
get(id) {
return {
'online': this._online,
'auth': this._auth
}[id]
},
online(){
online() {
return this._online
},
connect(){
connect() {
this._online++
},
disconnect(){
disconnect() {
this._online--
},
auth(socket){
if(!this._authed[socket.user.id]) this._authed[socket.user.id] = {}
auth(socket) {
if (!this._authed[socket.user.id]) this._authed[socket.user.id] = {}
this._authed[socket.user.id][socket.id] = {
user: socket.user,
socket: socket
}
this._auth++
},
deauth(socket){
if(!socket.user) return
deauth(socket) {
if (!socket.user) return
delete this._authed[socket.user.id][socket.id]
this._auth--
}
@@ -341,7 +349,8 @@ www.on('error', function (error) {
}
pretty.log({
data: `Error: port ${port}: ${error.code}`
data: `Error: port ${port}: ${error.code}`,
action: 'error'
})
});
@@ -384,7 +393,6 @@ www.on('listening', function () {
// }, 5e3)
Chart.interval()
Chart.update()
Previous.update()
// Tracks.get('7GhIk7Il098yCjg4BQjzvb').then(track => {
@@ -404,7 +412,7 @@ server.on('connection', socket => {
socket.on('disconnect', function () {
Stats.disconnect()
if(socket.user) Stats.deauth(socket)
if (socket.user) Stats.deauth(socket)
pretty.log(`Socket: '${socket.id}' disconnected`, 3)
})
@@ -419,12 +427,12 @@ server.on('connection', socket => {
socket.emit('previous', Previous.get())
})
socket.on('clear', function(data){
Stats.deauth(socket)
socket.user = undefined
// socket.emit('auth', { // demand token clear
// clear: true
// })
socket.on('clear', function (data) {
Stats.deauth(socket)
socket.user = undefined
// socket.emit('auth', { // demand token clear
// clear: true
// })
})
socket.on('auth', function (tokens) {
@@ -453,11 +461,12 @@ server.on('connection', socket => {
resp.on('end', () => {
let creds = JSON.parse(data)
if (creds.error) {socket.emit('meta', {
type: 'error',
action: 'auth',
message: `Auth: there was and error with your facebook token: ${creds.error}`
})
if (creds.error) {
socket.emit('meta', {
type: 'error',
action: 'auth',
message: `Auth: there was and error with your facebook token: ${creds.error}`
})
return pretty.log({ data: creds.error.message, action: 'error' })
}
@@ -469,7 +478,7 @@ server.on('connection', socket => {
}).then(user => { // finalize auth
socket.user = new User(user)
socket.emit('auth', socket.user.info())
pretty.log(`Socket: ${socket.id} auth by token.fb as '${socket.user.name}'`, 3)
pretty.log(`Socket: '${socket.id}' auth by token.fb as '${socket.user.name}'`, 3)
Stats.auth(socket)
})
});
@@ -522,36 +531,38 @@ server.on('connection', socket => {
socket.on('flags', function (tid) {
if (!socket.user) return
db.votes.validUser(socket.user, tid).then(flags => {
db.votes.validUser(socket.user, tid).then(vote => {
// let flags = vote ? {
// up: vote.flag == 'up',
// down: vote.flag == 'down',
// report: vote.report
// } : {
// up: false,
// down: false,
// report: false
// }
socket.emit('flags', {
tid: tid,
flags: flags
flags: vote !== null ? vote.flag : null
})
}).catch(err => {
socket.emit('meta', {
type: 'error',
action: 'flags',
message: `Flags: api error for '${data.query}'`
})
throw err
// socket.emit('meta', {
// type: 'error',
// action: 'flags',
// message: `Flags: api error for '${data.query}'`
// })
})
})
socket.on('vote', function (data) {
Tracks.get(data.tid).then(track => {
db.votes.add(socket.user, track, data.flag).then(vote => {
Chart.serial++
}).catch(err => {
socket.emit('meta', {
type: 'error',
action: 'vote',
message: `Vote: ignored: ${err.message}`
})
})
db.votes.add(socket.user, data.tid, data.flag).then(vote => {
Chart.serial++
}).catch(err => {
socket.emit('meta', {
type: 'error',
action: 'vote',
message: `Vote: tid '${data.tid}' not found: ${err.message}`
message: `Vote: ignored: ${err.message}`
})
})
})
+18 -10
View File
@@ -8,12 +8,15 @@
--color-3grey: #525252;
}
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Lato&family=Roboto:wght@400;500&display=swap');
body {
background-color: var(--color-1grey);
color: var(--color-light);
margin: 0rem;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-family: 'Lato', sans-serif;
line-height: 1.3rem;
/* font-weight: 600; */
}
.hidden {
@@ -181,7 +184,8 @@ a:hover {
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
font-size: 1.2rem;
background: inherit;
/* background: inherit; */
text-shadow: 0px 0px 8px black;
}
.track>.icons>div {
@@ -332,7 +336,7 @@ a:hover {
.pane.preview>.buttons>i.clicked {
background: var(--color-primary);
cursor: default;
/* cursor: default; */
}
.pane.preview>.params {
@@ -442,23 +446,27 @@ a:hover {
display: inherit;
}
.chart>.list>.track>.albumart {
margin-left: 1.9rem;
}
.chart>.list>.track::before {
content: counter(number)" ";
position: absolute;
left: .75rem;
top: 1.1rem;
left: .95rem;
top: 1.25rem;
font-size: 1rem;
/* height: 2.6rem; */
/* -webkit-transform: translateX(-50%); */
/* transform: translateY(-50%); */
}
.chart>.list>.track>.albumart {
margin-left: 1.5rem;
.chart>.list>.track:nth-child(n+10)::before {
left: .65rem;
}
.chart>.list>.track:nth-child(n+10)::before {
left: .45rem;
.chart>.list>.track:nth-child(n+100)::before {
left: .4rem;
}
/* Modals */
+69 -62
View File
@@ -51,7 +51,7 @@ class Storage {
}
class Track {
constructor(tdata, flags = { up: false, down: false, report: false }) {
constructor(tdata) {
this.title = tdata.title
this.artists = tdata.artists
this.album = tdata.album.name
@@ -60,7 +60,7 @@ class Track {
this.duration = tdata.duration
this.votes = tdata.votes
this.placement = tdata.placement
this.flags = flags
this.flag = null
this.explicit = tdata.explicit
this.banned = tdata.banned
this.listen = tdata.listen
@@ -87,12 +87,14 @@ class Track {
var iVotes = document.createElement('div'),
iPlayed = document.createElement('div')
iVotes.classList.add('votes')
iVotes.append(this.votes, new Icon('thumbs-up'))
if (this.votes) {
iVotes.classList.add('votes')
iVotes.append(this.votes.total, new Icon('thumbs-up'))
}
iPlayed.classList.add('played')
if (options.played) {
var played = new Date(options.played)
iPlayed.classList.add('played')
iPlayed.append(`${['Nd', 'Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'Sb'][played.getDay()]}, ${played.getHours()}:${played.getMinutes()}`)
}
@@ -130,8 +132,10 @@ class Track {
['Autorzy', this.artists.join(', ')],
['Album', this.album],
['Czas', `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`],
['Top', true],
['Miejsce', this.placement ? `#${this.placement}` : '~'],
['Głosy', this.votes ? this.votes : '~'],
['Punkty', this.votes ? this.votes.total : '~'],
this.votes ? ['Głosy', [new Icon('thumbs-up'), this.votes.up, ' : ', this.votes.down, new Icon('thumbs-down'), `\t${(this.votes.up / (this.votes.up + this.votes.down) * 100).toFixed(1)}%`]] : [],
['Metadane', true],
['ban', this.banned ? new Icon('check') : new Icon('check-empty')],
['explicit', this.explicit ? new Icon('check') : new Icon('check-empty')],
@@ -223,7 +227,8 @@ class Table {
if (column === true) continue
let td = document.createElement('td')
tr.append(td)
td.append(column)
if (column instanceof Array) for (let element of column) td.append(element)
else td.append(column)
}
tbody.append(tr)
}
@@ -254,7 +259,7 @@ class Icon {
pretty = {
info(where, text) {
console.log(`%c# ${where}${'\t'.repeat( 4 - (((where.length+2)-(where.length+2)%4)/4) )}${text}`, 'color: cyan')
console.log(`%c# ${where}${'\t'.repeat(4 - (((where.length + 2) - (where.length + 2) % 4) / 4))}${text}`, 'color: cyan')
}
}
@@ -282,34 +287,27 @@ Tracks = {
})
},
set(track) {
this._list[track.id] = track
this.getFlag(track.id)
if (this._promises[track.id]) {
for (let promise of this._promises[track.id]) {
promise.resolve(track)
}
delete this._promises[track.id]
}
this._list[track.id] = track
this.getFlags(track.id)
},
updateFlags() {
expireFlags() {
for (let track in this._list) {
this.getFlags(track)
track.flag = false
}
},
getFlags(tid) {
getFlag(tid) {
if (Auth.successful) Socket.emit('flags', tid)
},
setFlags(tid, flags) {
this._list[tid].flags = flags
if (Preview.track.id == tid) Preview.flags.reset(flags)
setFlag(tid, flag) {
this._list[tid].flag = flag
if (Preview.track.id == tid) Preview.flags.set(flag)
},
update(tid) {
var el = document.querySelectorAll(`.track.${CSS.escape(tid)}`)
el.forEach(element => {
element.innerHTML = ''
element.append(...element.track.el().children)
});
}
}
Hash = {
@@ -349,7 +347,7 @@ Hash = {
}[this.current]}`
Panes.switch(this.current)
gtag('event', 'pageview', {
'page_path': location.pathname + location.search + location.hash
'page_path': location.pathname + location.hash
});
break;
default:
@@ -359,7 +357,7 @@ Hash = {
document.title = `radio-rolnik - "${track.title}"`
if (Preview.track.id != track.id) Preview.goto(track)
gtag('event', 'pageview', {
'page_path': location.pathname + location.search + location.hash
'page_path': location.pathname + location.hash
});
})
break;
@@ -384,7 +382,10 @@ Vote = {
report(track) {
this._send(track, 'report')
},
_send(track, flag,) {
send(track, flag) {
this._emit(track, flag)
},
_emit(track, flag) {
pretty.info('Vote', `${flag}' on ${track.title}`)
Socket.emit('vote', {
tid: track.id,
@@ -564,42 +565,46 @@ window.onload = function () {
down: document.querySelector('.pane.preview>.buttons>.icon-thumbs-down'),
report: document.querySelector('.pane.preview>.buttons>.icon-flag'),
},
status: {
up: false,
down: false,
report: false,
},
reset(flags) {
if (typeof flags == 'undefined') var flags = Preview.track.flags
this.status = {
up: this.clicked('up', flags.up),
down: this.clicked('down', flags.down),
report: this.clicked('report', flags.report),
}
},
clicked(flag, status = false) {
status: null,
// reset(flag) {
// // if (typeof flag == 'undefined') var flags = Preview.track.flags
// this.status = {
// up: this._clicked('up', flag == 'up'),
// down: this._clicked('down', flag == 'down'),
// }
// },
_clicked(flag, status = false) {
if (status) Elements.flags[flag].classList.add('clicked')
else Elements.flags[flag].classList.remove('clicked')
return status
},
set(flag, status) {
if (this.status[flag]) return
this.clicked(flag, status)
this.status[flag] = true
Vote[flag](Preview.track)
click(flag) {
if (flag !== 'report') {
if (flag === this.status) this.status = null
else this.status = flag
}
this.set(this.status)
Vote.send(Preview.track, this.status)
},
set(flag) {
this._clicked('up', flag == 'up')
this._clicked('down', flag == 'down')
this._clicked('report', flag == 'report')
if (flag != 'report') this.status = flag
}
},
change(track) {
pretty.info('Preview', `change: ${track.title}`)
if (track.id == this.track.id) return
this.track = track
if (track.flag === false) Tracks.getFlag(track.id)
Elements.preview.albumart.style.backgroundImage = `url('${track.albumart}')`
Elements.preview.title.textContent = track.title
Elements.preview.artists.textContent = track.artists.join(', ')
Elements.preview.table.innerHTML = ''
Elements.preview.table.append(...track.tbody().children)
this.flags.reset(track.flags)
this.flags.set(track.flag)
},
goto(track) {
Panes.switch('preview')
@@ -684,7 +689,7 @@ window.onload = function () {
if (ok) {
this.successful = true
Tracks.updateFlags()
Tracks.expireFlags()
Elements.auth.buttons.classList.remove('disabled')
Elements.auth.prof.style.backgroundImage = `url('https://graph.facebook.com/${this.info.id}/picture?type=large')`
@@ -750,12 +755,15 @@ window.onload = function () {
values: {},
serial: null,
async update(tids, values, serial) {
console.log(serial)
if (serial === this.serial) return
pretty.info('Chart', `update, serial '${serial}' vs '${this.serial}'`)
this.tids = tids
this.values = values
this.serial = serial
// return console.log(this)
// tids.map(tid => {
// let track = await tracks.get(tid)
// track.votes = values[tid]
@@ -826,7 +834,7 @@ window.onload = function () {
document.querySelector('.pane.preview>.buttons').addEventListener('click', function (e) {
if (e.target.classList.value.startsWith('icon-')) {
let target = e.target.classList.value.slice(5)
let target = e.target.classList.value.split(' ')[0].slice(5)
switch (target) {
case 'link':
if (navigator.share) {
@@ -857,11 +865,10 @@ window.onload = function () {
})
return
}
Preview.flags.set({
Preview.flags.click({
'thumbs-up': 'up',
'thumbs-down': 'down',
'flag': 'report'
}[target], true)
'thumbs-down': 'down'
}[target])
break
case 'flag':
if (this.classList.contains('disabled')) {
@@ -880,7 +887,7 @@ window.onload = function () {
confirm: {
icon: 'paper-plane',
click: function () {
Preview.flags.set('report', true)
Preview.flags.click('report')
this.modal.destruct()
}
},
@@ -940,14 +947,14 @@ window.onload = function () {
}
// register service worker
if(false)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
pretty.info('ServiceWorker', 'registration successful');
}, function (err) {
pretty.info('ServiceWorker', `registration failed: ${err.message}`);
});
}
if (false)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
pretty.info('ServiceWorker', 'registration successful');
}, function (err) {
pretty.info('ServiceWorker', `registration failed: ${err.message}`);
});
}
// ############ Socket events
@@ -991,7 +998,7 @@ window.onload = function () {
});
Socket.on('flags', function (data) {
Tracks.setFlags(data.tid, data.flags)
Tracks.setFlag(data.tid, data.flags)
});
Socket.on('chart', function (data) {