Merge pull request #17 from Maathias/optimisation

refactor: move fetching to Track
This commit was merged in pull request #17.
This commit is contained in:
Mateusz Pstrucha authored and GitHub committed 2021-11-03 23:02:29 +01:00
commit 4ceb4694cc
13 files changed
+303 -232

No files matched your search

+43 -68
View File
@@ -21,13 +21,6 @@ class Track {
constructor(tdata) {
Object.assign(this, tdata)
this.stats = {
up: -1,
down: -1,
rank: -1,
cast: '',
}
// this.getVote()
}
@@ -97,14 +90,16 @@ class Track {
* @returns {Promise} stats object
*/
getStats() {
return new Promise((resolve, reject) => {
getStats(this.id)
.then((stats) => {
this.stats = stats
resolve(stats)
})
.catch((err) => reject(err))
})
if (this._stats) return this._stats
else
return (this._stats = new Promise((resolve, reject) => {
getStats(this.id)
.then((stats) => {
this.stats = stats
resolve(this)
})
.catch((err) => reject(err))
}))
}
}
@@ -132,13 +127,11 @@ function getStats(id) {
* @returns {Track} Track object
*/
function get(id) {
return new Promise((resolve, reject) => {
if (typeof Tracks[id] === 'undefined') {
download(id)
.then((track) => resolve(track))
.catch((err) => reject(err))
} else resolve(Tracks[id])
})
if (typeof Tracks[id] === 'undefined') {
Tracks[id] = download(id)
}
return Tracks[id]
}
/**
@@ -147,35 +140,13 @@ function get(id) {
* @returns {Array} Array of Tracks
*/
function getMultiple(ids = []) {
return new Promise((resolve, reject) => {
let missing = ids.filter((id) => !Tracks[id]) // filter tracks missing from cache
let missing = ids.filter((id) => !Tracks[id]) // filter tracks missing from cache
// if none are missing, resolve from cache
if (missing.length < 1) return resolve(ids.map((id) => Tracks[id]))
else {
// fetch missing tracks
downloadMultiple(ids)
.then((tracks) => {
tracks.map((track) => (Tracks[track.id] = track)) // add to cache
return resolve(ids.map((id) => Tracks[id])) // resolve from cache
})
.catch((err) => reject(err))
}
})
}
function getMultipleStats(tids) {
return new Promise((resolve, reject) => {
ky.post('/api/vote/batch', {
json: { tids },
headers: { authorization: credentials.token },
})
.json()
.then((stats) => {
resolve(stats)
})
.catch((err) => reject(err))
})
// if none are missing, return from cache
if (missing.length < 1) return ids.map((id) => Tracks[id])
else {
return downloadMultiple(missing)
}
}
/**
@@ -188,24 +159,35 @@ function download(id) {
ky.get('/api/track/' + id)
.json()
.then((track) => {
Tracks[track.id] = new Track(track)
resolve(Tracks[track.id])
resolve(new Track(track))
})
.catch((err) => reject(err))
})
}
function downloadMultiple(tids) {
return new Promise((resolve, reject) => {
ky.post('/api/track/batch', {
json: { tids },
let promises = {}
// prepare promises
// store res, rej
tids.forEach((tid) => {
Tracks[tid] = new Promise((resolve, reject) => {
promises[tid] = { resolve, reject }
})
.json()
.then((tracks) => {
resolve(tracks.map((tdata) => new Track(tdata)))
})
.catch((err) => reject(err))
})
ky.post('/api/track/batch', {
json: { tids },
})
.json()
.then((tracks) => {
tracks.forEach((tdata) => {
promises[tdata.id].resolve(new Track(tdata))
})
})
.catch((err) => console.error(err))
return tids.map((tid) => Tracks[tid])
}
/**
@@ -222,11 +204,4 @@ function search(query) {
})
}
export {
Tracks as tracks,
get,
getMultiple,
getMultipleStats,
search,
getStats,
}
export { Tracks as tracks, get, getMultiple, search, getStats }
+12 -11
View File
@@ -2,12 +2,17 @@ import { useContext } from 'react'
import Track, { Tracklist } from '../Track/Track'
import { getMultiple } from '../../Cache'
import PlayingContext from '../../contexts/Playing'
import './History.css'
import './playing.css'
function History({ next, tracks, paused }) {
const playing = useContext(PlayingContext)
const { tid } = useContext(PlayingContext)
getMultiple(tracks.map(([tid]) => tid))
return (
<div className="wrapper history">
@@ -15,24 +20,24 @@ function History({ next, tracks, paused }) {
{next && (
<div className="history-section next">
<span className="header">Następny:</span>
<Track track={next} timestamp=">" />
<Track tid={next} timestamp=">" />
</div>
)}
{!paused && (
<div className="history-section now">
<span className="header">Gra teraz:</span>
<Track track={playing} timestamp="~" />
<Track tid={tid} timestamp="~" />
</div>
)}
<div className="history-section previous">
<span className="header">Poprzednie:</span>
{tracks.map((track) => {
let time = track.timestamp ? new Date(track.timestamp) : '-:-'
{tracks.map(([tid, timestamp]) => {
let time = timestamp ? new Date(timestamp) : '-:-'
if (track.timestamp) {
if (timestamp) {
let h = time.getHours(),
m = time.getMinutes()
@@ -43,11 +48,7 @@ function History({ next, tracks, paused }) {
}
return (
<Track
key={track.id + '_' + track.timestamp}
track={track}
timestamp={time}
/>
<Track key={tid + '_' + timestamp} tid={tid} timestamp={time} />
)
})}
+30
View File
@@ -0,0 +1,30 @@
.now > .track {
height: 4em;
align-items: center;
}
.now > .track .track-timestamp {
display: none;
}
.now > .track .track-icons {
display: none;
}
.now > .track .track-section-a {
width: auto;
}
.now > .track .track-section-b {
flex-wrap: wrap;
}
.now > .track .track-image {
width: 4em;
height: 4em;
}
.now > .track .track-title {
width: 100%;
font-size: 1.2em;
}
+20 -18
View File
@@ -15,7 +15,7 @@ import admin from '../../Admin'
var last
function Info() {
function Info({ top }) {
const { id } = useParams(),
[track, setTrack] = useState({
title: '-',
@@ -28,8 +28,8 @@ function Info() {
{ setModalLogin } = useContext(ModalLoginContext),
playing = useContext(PlayingContext)
if (!id) last = playing.id ?? ''
else last = id
if (id) last = id
if (!last) last = id ?? playing.id ?? top ?? ''
useEffect(() => {
setMeta(`Pobieranie... ${last}`)
@@ -53,24 +53,33 @@ function Info() {
if (!id && last) return <Redirect to={`/utwor/${last}`} />
function vote(value) {
if (!credentials.token) return setModalLogin(true)
if (!credentials.token) return setModalLogin(true) // prompt for login
if (track.stats.cast === value) return // ignore vote
setMeta('Zmienianie głosu...')
track
.setVote(value)
.then((ok) => {
track
.getStats()
.then(() => {
// http ok, vote accepted?
ok
? setMeta(`Zmieniono głos na ${{ up: '👍', down: '👎' }[value]}`)
: setMeta('Głos nie został zmieniony')
})
.catch((err) =>
.catch((err) => {
// http error on update stats
setMeta('Wystąpił błąd przy aktualizacji statystyk utworu')
)
console.error(err)
})
})
.catch((err) => {
// http error on send
setMeta('Wystąpił błąd podczas wysyłania głosu')
console.error(err)
})
.catch((err) => setMeta('Wystąpił błąd podczas wysyłania głosu'))
}
function report() {
@@ -78,22 +87,15 @@ function Info() {
setModalReport(false)
}
const total = track.stats.up + track.stats.down,
percent =
total > 0
? (track.stats.up / (track.stats.up + track.stats.down)) * 100
: 50
console.log(track.stats)
const total = track.stats.total,
percent = total > 0 ? (track.stats.up / total) * 100 : 50
document.setTitle(track.title)
return (
<div className="wrapper info">
{/* <Image
images={track.album.art}
fallback={def}
className="info-image"
alt="album cover"
/> */}
<img
src={track.album.art ? track.album.art[0].url : def}
className="info-image"
+8 -48
View File
@@ -17,7 +17,6 @@ import Search from '../Search/Search'
import Settings, { defaults } from '../Settings/Settings'
import Modal from '../Modal/Modal'
import { get, getMultiple, getMultipleStats } from '../../Cache'
import { addEvent } from '../../socket'
import { promptLogin } from '../../Auth'
@@ -56,62 +55,23 @@ function Main() {
useEffect(() => {
addEvent('status', ({ tid, progress, duration, paused, timestamp }) => {
if (tid === null) return
get(tid)
.then((track) => {
track.timestamp = timestamp // insert timestamp
console.info('status: update', tid)
setPlaying(track)
setElapsed([progress, duration])
setPaused(paused)
})
.catch((err) => {
console.error(err)
setPaused(true)
})
setPlaying({ tid, timestamp })
setElapsed([progress, duration])
setPaused(paused)
})
addEvent('next', ({ tid }) => {
if (tid == null) return setNext(null)
get(tid)
.then((track) => {
setNext(track)
})
.catch((err) => console.error(err))
})
addEvent('next', ({ tid }) => setNext(tid))
addEvent('previous', ({ combo, push }) => {
if (push) {
return get(push).then((track) =>
setPrevious((prev) => [track, ...prev])
)
}
let tids = combo.map((pair) => pair[0]),
timestamps = combo.map((pair) => pair[1])
getMultiple(tids)
.then((tracks) => {
// insert timestamps to tracks
tracks.map((track, i) => (track.timestamp = timestamps[i]))
setPrevious(tracks)
})
.catch((err) => console.error(err))
})
addEvent('previous', ({ combo }) => setPrevious(combo))
addEvent('top', ({ tids, timestamp }) => {
Promise.all([getMultiple(tids), getMultipleStats(tids)])
.then(([tracks, stats]) => {
tracks.map((track, i) => (track.stats = stats[i]))
setTop(tracks)
setTopDate(new Date(timestamp))
})
.catch((err) => console.error(err))
setTop(tids)
setTopDate(new Date(timestamp))
})
}, []) // eslint-disable-line
// save settings on change
useEffect(() => {
console.info('settings changed', settings)
localStorage('settings', settings)
}, [settings])
@@ -135,7 +95,7 @@ function Main() {
</Route>
<Route path="/utwor/:id?">
<Info />
<Info top={top[0]} />
</Route>
<Route path="/top">
+7
View File
@@ -19,3 +19,10 @@
margin: 1em;
color: #000a;
}
.search[data-results='0'] {
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
+10 -15
View File
@@ -26,18 +26,13 @@ function Search() {
search(query)
.then(({ tids, total, elapsed }) => {
getMultiple(tids)
.then((tids) => {
setResults(tids)
setMeta(
`Znaleziono ${total} utworów (${(
elapsed[0] +
elapsed[1] / 1e9
).toPrecision(2)}s)`
)
})
.catch((err) => {
setMeta(`Wystąpił błąd podczas pobierania utworów`)
})
setResults(tids)
setMeta(
`Znaleziono ${total} utworów (${(
elapsed[0] +
elapsed[1] / 1e9
).toPrecision(2)}s)`
)
})
.catch((err) => {
setMeta(`Wystąpił błąd podczas wyszukiwania`)
@@ -57,7 +52,7 @@ function Search() {
}, []) // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="wrapper search">
<div className="wrapper search" data-results={results.length}>
<h2>Wyszukaj utwór</h2>
<input
className="search-input"
@@ -82,8 +77,8 @@ function Search() {
</span>
)}
<Tracklist>
{results.map((track) => {
return <Track key={track.id} track={track} />
{results.map((tid) => {
return <Track key={tid} tid={tid} />
})}
</Tracklist>
</div>
+28 -18
View File
@@ -9,29 +9,35 @@ import SettingsContext from '../../contexts/Settings'
import './Status.css'
import def from '../../media/default.png'
import { get } from '../../Cache'
function Status({ progress: [progress, duration], paused }) {
const {
id,
title = '-',
artists = ['-'],
album = {},
} = useContext(PlayingContext),
[elapsed, setElapsed] = useState(),
const { tid } = useContext(PlayingContext),
{ settings } = useContext(SettingsContext)
const step = 1e3,
tread = step / duration
const [elapsed, setElapsed] = useState(),
[track, setTrack] = useState({})
if (tid)
get(tid).then((tdata) => {
setTrack(tdata)
})
const step = 1e3,
tread = step / track?.duration
// update theme color based on track
useEffect(() => {
if (!settings.hueFromArt) setDefault()
else if (album.art) setColor(album.art[1].url, 1)
}, [album.art, settings.hueFromArt])
else if (track?.album?.art) setColor(track?.album?.art[1]?.url, 1)
}, [track?.album?.art, settings.hueFromArt])
// update progress on track change
useEffect(() => {
setElapsed(progress ? progress / duration : 0)
}, [progress, duration])
}, [progress, duration, tid])
// animate progress bar
useEffect(
(anim) => {
if (!paused) {
@@ -53,19 +59,23 @@ function Status({ progress: [progress, duration], paused }) {
return (
<Link
className={['status', paused ? 'paused' : ''].join(' ')}
to={`/utwor/${id}`}
className={['status', paused || !tid ? 'paused' : ''].join(' ')}
to={`/utwor/${tid}`}
>
<img
className="status-image"
alt="album cover"
src={album.art ? album.art[1].url : def}
src={track?.album?.art ? track?.album?.art[1]?.url : def}
/>
<span className="status-track">{title}</span>
<span className="status-artist">{artists.join(', ')}</span>
<span className="status-track">{track?.title}</span>
<span className="status-artist">{track?.artists?.join(', ')}</span>
<i
className={`icon-${
socket.readyState === socket.OPEN ? 'info' : 'unlink'
track.id
? socket.readyState === socket.OPEN
? 'info'
: 'unlink'
: 'spin4 animate-spin'
}`}
></i>
<div
+16
View File
@@ -6,3 +6,19 @@
text-align: center;
font-weight: bold;
}
.top-more {
text-align: center;
padding: 0.5em 1em;
background-color: var(--light);
border-radius: 5px;
margin: 1em auto;
cursor: pointer;
transition: 0.1s;
color: #333;
width: 60%;
}
.top-more:hover {
width: 75%;
}
+26 -14
View File
@@ -1,33 +1,45 @@
import { useState } from 'react'
import { getMultiple } from '../../Cache'
import Track, { Tracklist } from '../Track/Track'
import './Top.css'
function Top({ tracks, timestamp }) {
const date = timestamp ?? new Date(),
weekName = [
'Niedziela',
'Poniedziałek',
'Wtorek',
'Środa',
'Czwartek',
'Piątek',
'Sobota',
][date.getDay()],
day = date.toLocaleTimeString('pl-PL', {
const locale = 'pl-PL',
date = timestamp ?? new Date(),
weekName = date.toLocaleDateString(locale, { weekday: 'long' }),
day = date.toLocaleTimeString(locale, {
hour: '2-digit',
minute: '2-digit',
})
}),
limit = 25
const [more, setMore] = useState(0)
getMultiple(tracks.slice(0, limit + more))
return (
<div className="wrapper top">
<span className="top-header">
TOP: {weekName} {timestamp ? day : '-'}
</span>
<Tracklist>
{tracks.map((track, rank) => {
return <Track key={track.id} track={track} displayRank={true} />
{tracks.slice(0, limit + more).map((tid, i) => {
return <Track key={tid} tid={tid} rank={i + 1} />
})}
</Tracklist>
{tracks.length - limit - more > 0 && (
<div
className="top-more"
onClick={(e) => {
setMore((m) => m + 10)
}}
>
Pokaż więcej ({tracks.length - limit - more})
</div>
)}
</div>
)
}
+11 -14
View File
@@ -41,6 +41,7 @@
white-space: nowrap;
display: flex;
flex-direction: row;
align-items: center;
margin-right: 1em;
}
@@ -49,6 +50,14 @@
cursor: pointer;
}
.track:nth-child(-n + 21) .track-rank {
color: var(--dark);
border-radius: 100%;
margin: 0 0.5em;
background-color: var(--light);
filter: drop-shadow(0 0 2px #6665);
}
.track-rank:before {
content: '#';
}
@@ -60,14 +69,14 @@
}
.track-title {
padding: 0px 10px;
margin: 0px 10px;
font-weight: bold;
text-decoration: none;
color: inherit;
}
.track-artist {
padding: 0px 10px;
margin: 0px 10px;
color: #333;
}
@@ -99,18 +108,6 @@
background-color: hsla(var(--deg), 35%, 22%, 71%);
}
/* .track-more:before {
content: '';
width: 100%;
height: 100%;
position: absolute;
background-color: var(--dark);
filter: blur(2px);
z-index: -1;
left: 0;
top: 0;
} */
.track.open > .track-more {
left: 0;
}
+49 -26
View File
@@ -2,10 +2,13 @@ import { useState, createContext, useContext } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { credentials } from '../../Auth'
import { get } from '../../Cache'
import ModalLoginContext from '../../contexts/ModalLogin'
import './Track.css'
import './loading.css'
import def from '../../media/default.png'
const TracklistContext = createContext({})
@@ -21,18 +24,23 @@ function Tracklist({ children }) {
)
}
function Track({ track, timestamp, displayRank = false }) {
const {
id,
title = '-',
artists = ['-'],
album = {},
stats = {},
} = track ?? {},
history = useHistory(),
tracklist = useContext(TracklistContext),
function Track({ tid, timestamp, rank }) {
const history = useHistory()
const tracklist = useContext(TracklistContext),
{ setModalLogin } = useContext(ModalLoginContext)
const [track, setTrack] = useState({})
get(tid)
.then((tdata) => {
setTrack(tdata)
if (!tdata.stats) tdata.getStats().then((ntdata) => setTrack(ntdata))
})
.catch((err) => {
setTrack(err)
})
function vote(value) {
if (!credentials.token) return setModalLogin(true)
@@ -43,46 +51,61 @@ function Track({ track, timestamp, displayRank = false }) {
}
function info() {
history.push(`/utwor/${id}`)
history.push(`/utwor/${tid}`)
}
return (
<div
className={['track', tracklist.active === id ? 'open' : ''].join(' ')}
id={id}
className={[
'track',
tracklist.active === tid ? 'open' : '',
track.id ? 'loaded' : 'loading',
track instanceof Error ? 'failed' : '',
].join(' ')}
id={tid}
>
<div
className={
'track-section-a ' + (timestamp || displayRank ? '' : 'empty')
}
className={'track-section-a ' + (timestamp || rank ? '' : 'empty')}
onClick={() => info()}
>
{timestamp && <span className="track-timestamp">{timestamp}</span>}
{displayRank && <span className="track-rank">{stats.rank}</span>}
{rank && (
<span className="track-rank" data-votes={track?.stats?.total}>
{rank}
</span>
)}
<img
className="track-image"
src={album.art ? album.art[2].url : def}
src={track.album?.art ? track.album?.art[2].url : def}
alt="album cover"
/>
</div>
<div className="track-section-b" onClick={() => info()}>
<span className="track-title">{title}</span>
<span className="track-artist">{artists.join(', ')}</span>
{track instanceof Error ? (
<>
<span className="track-title">{tid}</span>
<span className="track-artist">Wystąpił błąd {track.message}</span>
</>
) : (
<>
<span className="track-title">{track.title}</span>
<span className="track-artist">{track.artists?.join(', ')}</span>
</>
)}
</div>
<div className="track-icons">
<i
className="icon-ellipsis-vert"
onClick={() => {
tracklist.setActive(id)
}}
onClick={() => tracklist.setActive(tid)}
></i>
</div>
<div className="track-more">
<div
className="track-more-button"
data-set={stats.cast === 'up'}
data-set={track.stats?.cast === 'up'}
onClick={(e) => vote('up')}
>
<i className="icon-thumbs-up"></i>
@@ -90,13 +113,13 @@ function Track({ track, timestamp, displayRank = false }) {
<div
className="track-more-button"
data-set={stats.cast === 'down'}
data-set={track.stats?.cast === 'down'}
onClick={(e) => vote('down')}
>
<i className="icon-thumbs-down"></i>
</div>
<Link to={`/utwor/${id}`} className="track-more-button">
<Link to={`/utwor/${tid}`} className="track-more-button">
<i className="icon-info"></i>
</Link>
+43
View File
@@ -0,0 +1,43 @@
@keyframes shine {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(100%);
}
}
.track.loading:not(.failed):after {
content: '';
top: 0;
transform: translateX(100%);
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
animation: shine 1.5s infinite;
pointer-events: none;
background: linear-gradient(
to right,
rgba(255, 255, 255, 0) 0%,
rgba(255, 255, 255, 0.4) 50%,
rgba(128, 186, 232, 0) 99%,
rgba(125, 185, 232, 0) 100%
);
}
.track.loading {
background-color: #eee5;
}
.track.loading:not(.failed) > .track-section-b > * {
width: 5em;
background-color: #6666;
height: 1em;
}
.track.failed {
background-color: #eaa5;
}