feat: voting

This commit is contained in:
Mateusz Pstrucha committed 2021-09-13 21:39:52 +02:00
1 parent ac034b2bc4
commit f7ccbce452
5 files changed
+193 -107

No files matched your search

+47 -15
View File
@@ -5,6 +5,15 @@ var tracks = {}
class Track {
constructor(tdata) {
Object.assign(this, tdata)
this.stats = {
up: -1,
down: -1,
}
this.rank = -1
this.cast = ''
this.getVote()
}
get listen() {
@@ -12,17 +21,18 @@ class Track {
}
get share() {
return `https://radio-rolnik.mtps.pl/utwor/${this.id}`
return `https://${document.location.origin}/utwor/${this.id}`
}
setVote(value) {
return new Promise((resolve, reject) => {
if (value === this.votes.set) return
ky.get(`/api/vote/${this.id}/${value}`)
if (value === this.cast) return
ky.patch(`/api/vote/${this.id}`, { json: { uid: 'mathias', value } })
.json()
.then((ok) => {
if (ok) {
this.votes.set = value
this.cast = value
this.getStats()
}
resolve(ok)
})
@@ -30,22 +40,40 @@ class Track {
})
}
getVotes() {
getVote() {
return new Promise((resolve, reject) => {
getVotes(this.id).then((votes) => {
this.votes = votes
resolve(votes)
})
ky.get(`/api/vote/${this.id}/cast`, { searchParams: { uid: 'mathias' } })
.text()
.then((cast) => {
this.cast = cast
resolve(cast)
})
.catch((err) => {
console.error(err)
})
})
}
getStats() {
return new Promise((resolve, reject) => {
getStats(this.id)
.then((stats) => {
this.stats = stats
resolve(stats)
})
.catch((err) => {
console.error(err)
})
})
}
}
function getVotes(id) {
function getStats(id) {
return new Promise((resolve, reject) => {
ky.get(`/api/track/${id}?votes`)
ky.get(`/api/vote/${id}`)
.json()
.then((votes) => {
resolve(votes)
.then((stats) => {
resolve(stats)
})
.catch((err) => reject(err))
})
@@ -63,7 +91,11 @@ function get(id) {
function getMultiple(ids) {
return new Promise((resolve, reject) => {
Promise.all(ids.map((id) => get(id))).then((tracks) => resolve(tracks))
Promise.all(ids.map((id) => get(id)))
.then((tracks) => resolve(tracks))
.catch((err) => {
console.error(err)
})
})
}
@@ -88,4 +120,4 @@ function search(query) {
})
}
export { tracks, get, getMultiple, search }
export { tracks, get, getMultiple, search, getStats }
-5
View File
@@ -1,5 +0,0 @@
function Home() {
return <div className="home"></div>
}
export default Home
+65 -25
View File
@@ -1,45 +1,75 @@
import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { useContext, useEffect, useState } from 'react'
import { useParams, Redirect } from 'react-router-dom'
import { get } from '../../Cache'
import PlayingContext from '../../contexts/Playing'
import './Info.css'
var last
function Info() {
const { id } = useParams(),
[track, setTrack] = useState({
title: '-',
votes: {},
stats: {},
album: {},
artists: ['-'],
}),
[meta, setMeta] = useState('...')
[meta, setMeta] = useState('...'),
playing = useContext(PlayingContext)
if (!id) last = playing.id ?? ''
else last = id
useEffect(() => {
setMeta(`Pobieranie... ${id}`)
get(id)
setMeta(`Pobieranie... ${last}`)
get(last)
.then((track) => {
setTrack(track)
setMeta(false)
track
.getStats()
.then((stats) => {
track
.getVote()
.then(() => {
setTrack(track)
setMeta(false)
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
})
.catch((err) => {
setMeta(`Wystąpił błąd przy pobieraniu informacji o utworze`)
})
}, [id])
}, [last]) // eslint-disable-line
if (!id && last) return <Redirect to={`/utwor/${last}`} />
function vote(value) {
track
.setVote(value)
.then((ok) =>
ok
? setMeta(`Zmieniono głos na ${{ up: '👎', down: '👍' }[value]}`)
: setMeta('Wystąpił bład przy zmienianiu głosu')
)
.then((ok) => {
track
.getStats()
.then(() => {
ok
? setMeta(`Zmieniono głos na ${{ up: '👍', down: '👎' }[value]}`)
: setMeta('Wystąpił bład przy zmienianiu głosu')
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
}
const percent = (track.votes.up / (track.votes.up + track.votes.down)) * 100
const total = track.stats.up + track.stats.down,
percent =
total > 0
? (track.stats.up / (track.stats.up + track.stats.down)) * 100
: 50
document.title = `${track.title} | radio-rolnik`
document.setTitle(track.title)
return (
<div className="wrapper info">
@@ -53,10 +83,10 @@ function Info() {
<span className="artist">{track.artists[0]}</span>
<div className="info-balance">
<div className="up" style={{ width: `${percent}%` }}>
{track.votes.up}&nbsp;
{track.stats.up}&nbsp;
</div>
<div className="down" style={{ width: `${100 - percent}%` }}>
{track.votes.down}
{track.stats.down}
</div>
</div>
@@ -67,15 +97,16 @@ function Info() {
<div className="buttons">
<i
className="icon-thumbs-up"
data-set={track.votes.set === 'up'}
data-set={track.cast === 'up'}
onClick={(e) => vote('up')}
></i>
<i
className="icon-thumbs-down"
data-set={track.votes.set === 'down'}
data-set={track.cast === 'down'}
onClick={(e) => vote('down')}
></i>
</div>
<div className="buttons">
<i
className="icon-export"
@@ -102,11 +133,20 @@ function Info() {
}}
></i>
</div>
<div>{`${track.title} - ${track.artists.join(', ')} - ${
track.album.name ?? '-'
} (${track.album.year ?? '-'})`}</div>
<div>Liczba głosów: {track.votes.up + track.votes.down}</div>
<div>Miejsce: #{track.votes.rank}</div>
<div>
<span>{track.artists.join(', ')}</span>
</div>
<div>
<span>
{track.album.name ?? '-'} ({track.album.year ?? '-'})
</span>
</div>
<div>Liczba głosów: {total}</div>
<div>Miejsce: #{track.stats.rank}</div>
{track.banned && (
<div>
<span>
+61 -57
View File
@@ -35,8 +35,6 @@ document.setTitle = (prefix, suffix) => {
ga.pageview(document.location.pathname)
}
var fac = new FastAverageColor()
function Main() {
const [playing, setPlaying] = useState({}),
[elapsed, setElapsed] = useState(0),
@@ -47,79 +45,85 @@ function Main() {
useEffect(() => {
addEvent('status', ({ trackid, progress, paused }) => {
get(trackid).then((track) => {
setPlaying(track)
setElapsed(progress)
setPaused(paused)
fac.getColorAsync(track.album.art).then(({ value: [r, g, b] }) => {
let color =
Math.atan2(1.732050808 * (g - b), 2 * r - g - b) * 57.295779513
document.documentElement.style.setProperty('--deg', color + 'deg')
get(trackid)
.then((track) => {
setPlaying(track)
setElapsed(progress)
setPaused(paused)
})
.catch((err) => {
setPaused(true)
})
})
})
addEvent('next', ({ trackid }) => {
get(trackid).then((track) => {
setNext(track)
})
get(trackid)
.then((track) => {
setNext(track)
})
.catch((err) => console.error(err))
})
addEvent('previous', ({ trackids, timestamps }) => {
getMultiple(trackids).then((tracks) => {
// insert timestamps to tracks
tracks.map((track, i) => (track.timestamp = timestamps[i]))
setPrevious(tracks)
})
getMultiple(trackids)
.then((tracks) => {
// insert timestamps to tracks
tracks.map((track, i) => (track.timestamp = timestamps[i]))
setPrevious(tracks)
})
.catch((err) => console.error(err))
})
addEvent('top', ({ trackids }) => {
getMultiple(trackids).then((tracks) => setTop(tracks))
getMultiple(trackids)
.then((tracks) => setTop(tracks))
.catch((err) => console.error(err))
})
}, [])
return (
<PlayingContext.Provider value={playing}>
<div className="main">
<Router>
<Switch>
<Route exact path="/">
<History next={next} tracks={previous} />
</Route>
<GaContext.Provider value={ga}>
<PlayingContext.Provider value={playing}>
<div className="main">
<Router>
<Switch>
<Route exact path="/">
<History next={next} tracks={previous} />
</Route>
<Route path="/utwor/:id">
<Info />
</Route>
<Route path="/utwor/:id?">
<Info />
</Route>
<Route path="/top">
<Top tracks={top} />
</Route>
<Route path="/top">
<Top tracks={top} />
</Route>
<Route path="/wyszukaj/:query?">
<Search />
</Route>
<Route path="/wyszukaj/:query?">
<Search />
</Route>
<Route render={() => <Redirect to="/" />} />
</Switch>
<Nav
buttons={[
{ label: 'Historia', to: '/', icon: 'align-left' },
{ label: 'Wyszukaj', to: '/wyszukaj', icon: 'search' },
{ label: 'Top', to: '/top', icon: 'list-numbered' },
{
label: 'Utwór',
path: '/utwor',
to: `/utwor/${playing.id ?? ''}`,
icon: 'info',
},
{ label: 'Ustawienia', to: '/ustawienia', icon: 'cog-alt' },
]}
/>
<Status progress={elapsed} paused={paused} />
</Router>
</div>
</PlayingContext.Provider>
<Route render={() => <Redirect to="/" />} />
</Switch>
<Nav
buttons={[
{ label: 'Historia', to: '/', icon: 'align-left' },
{ label: 'Wyszukaj', to: '/wyszukaj', icon: 'search' },
{ label: 'Top', to: '/top', icon: 'list-numbered' },
{
label: 'Utwór',
path: '/utwor',
to: `/utwor`,
icon: 'info',
},
{ label: 'Ustawienia', to: '/ustawienia', icon: 'cog-alt' },
]}
/>
<Status progress={elapsed} paused={paused} />
</Router>
</div>
</PlayingContext.Provider>
</GaContext.Provider>
)
}
+20 -5
View File
@@ -1,13 +1,28 @@
import { useState } from 'react'
import { Link } from 'react-router-dom'
import { Link, useHistory } from 'react-router-dom'
import './Track.css'
function Track({ track, timestamp, rank }) {
const [open, setOpen] = useState(false),
{ id, title = '-', artists = ['-'], album = {}, votes = {} } = track ?? {}
{
id,
title = '-',
artists = ['-'],
album = {},
votes = {},
cast = '',
} = track ?? {},
history = useHistory()
function vote(value) {
track.setVote(value).then((ok) => ok && setOpen(false))
track
.setVote(value)
.then((ok) => ok && setOpen(false))
.catch((err) => console.error(err))
}
function info() {
history.push(`/utwor/${id}`)
}
return (
@@ -42,7 +57,7 @@ function Track({ track, timestamp, rank }) {
<div className="track-more-button">
<i
className="icon-thumbs-up"
data-set={votes.set === 'up'}
data-set={cast === 'up'}
onClick={(e) => vote('up')}
></i>
</div>
@@ -50,7 +65,7 @@ function Track({ track, timestamp, rank }) {
<div className="track-more-button">
<i
className="icon-thumbs-down"
data-set={votes.set === 'down'}
data-set={cast === 'down'}
onClick={(e) => vote('down')}
></i>
</div>