jukebox
All repositories: gitoria
8.0 KB
// lib/browse.hl — READING THE DATABASE FAST: pages of songs in the three orders, artists, albums, search, shuffle, stats.// The order lists (song ids with their play count, sorted by title / artist / album) are made once from the sorted// indexes of the songs table and kept in memory until a scan changes something; a page is a slice of such a list and// one lookup per row. Nothing here returns more than `maxLimit` rows. No writes (lib/library.hl and lib/catalog.hl write).import { random } from 'hl:math'import { songsTable, albumsTable, artistsTable, coversTable } from './db.hl'import { floor } from 'hl:math'import { fold } from './util.hl'import OrderCache from './order-cache.hl'static maxLimit = 200static defaultLimit = 50static cache = new OrderCache()static dropOrderCache = () => {cache.lists = {}cache.stats = null}static sortField = (sort) => {if (sort == 'title') { return 'sortTitle' }if (sort == 'album') { return 'sortAlbum' }return 'sortArtist'}// the lean rows { id, pc } of all songs in one orderstatic orderList = (sort) => {field = sortField(sort)list = cache.lists[field]if (list != null) { return list }out = []for (r of songsTable.range(field, null, null)) { out.push({ id = r.id pc = r.playCount }) }lists = cache.listslists[field] = outcache.lists = listsreturn out}// ---- what the API shows of a song / album / artist --------------------------------------------------------------static publicSong = (s) => {return {id = s.id title = s.title artist = s.artist albumArtist = s.albumArtist album = s.album track = s.track trackTotal = s.trackTotaldisc = s.disc year = s.year genre = s.genre duration = s.duration format = s.format kind = s.kind size = s.sizeplayCount = s.playCount rating = s.rating stars = s.stars popm = s.popm coverId = s.coverId path = s.path addedAt = s.addedAt}}static publicAlbum = (a) => {return { id = a.id name = a.name albumArtist = a.albumArtist year = a.year songCount = a.songCount duration = a.duration playCount = a.playCount coverId = a.coverId folder = a.folder }}static publicArtist = (a) => {return { id = a.id name = a.name songCount = a.songCount albumCount = a.albumCount playCount = a.playCount coverId = a.coverId }}static clampLimit = (limit) => {if (limit == null || limit < 1) { return defaultLimit }return limit > maxLimit ? maxLimit : limit}static clampOffset = (offset) => { return offset == null || offset < 0 ? 0 : offset }// rows ordered by one string field (insertion sort; small lists only: one album, one artist)static orderedBy = (rows, field) => {out = []for (r of rows) {let j = out.lengthout.push(r)while (j > 0 && out[j - 1][field] > r[field]) {out[j] = out[j - 1]j = j - 1}out[j] = r}return out}static page = (total, offset, limit, items) => { return { total = total offset = offset limit = limit items = items } }// ---- songs ------------------------------------------------------------------------------------------------------// params: sort (title | artist | album), offset, limit, minPlays, artist (an artist id), album (an album id)static songsPage = (sort, offset, limit, minPlays, artistId, albumId) => {off = clampOffset(offset)lim = clampLimit(limit)if (albumId != null) {a = albumsTable.fetch(albumId)if (a == null) { return page(0, off, lim, []) }return slicePage(orderedBy(songsTable.find('albumKey', a.key), 'sortAlbum'), off, lim, minPlays)}if (artistId != null) {a = artistsTable.fetch(artistId)if (a == null) { return page(0, off, lim, []) }return slicePage(orderedBy(songsTable.find('artistKey', a.key), 'sortArtist'), off, lim, minPlays)}list = orderList(sort)min = minPlays == null ? 0 : minPlaysitems = []let total = 0for (r of list) {if (r.pc < min) { continue }if (total >= off && items.length < lim) {s = songsTable.fetch(r.id)if (s != null) { items.push(publicSong(s)) }}total = total + 1}return page(total, off, lim, items)}// a page out of full rows already in order (an album, an artist)static slicePage = (rows, off, lim, minPlays) => {min = minPlays == null ? 0 : minPlaysitems = []let total = 0for (s of rows) {if (s.playCount < min) { continue }if (total >= off && items.length < lim) { items.push(publicSong(s)) }total = total + 1}return page(total, off, lim, items)}// `count` random songs (no repeats) among those played at least `minPlays` timesstatic shuffle = (minPlays, count) => {lim = clampLimit(count)min = minPlays == null ? 0 : minPlayspool = []for (r of orderList('title')) {if (r.pc >= min) { pool.push(r.id) }}items = []let left = pool.lengthwhile (items.length < lim && left > 0) {k = floor(random() * left)id = pool[k]pool[k] = pool[left - 1]left = left - 1s = songsTable.fetch(id)if (s != null) { items.push(publicSong(s)) }}return page(pool.length, 0, lim, items)}// ---- artists and albums -----------------------------------------------------------------------------------------static artistsPage = (offset, limit) => {off = clampOffset(offset)lim = clampLimit(limit)rows = artistsTable.range('sortName', null, null)items = []let i = offwhile (i < rows.length && items.length < lim) {items.push(publicArtist(rows[i]))i = i + 1}return page(rows.length, off, lim, items)}static albumsPage = (offset, limit, artistId) => {off = clampOffset(offset)lim = clampLimit(limit)let rows = []if (artistId != null) {a = artistsTable.fetch(artistId)if (a != null) { rows = orderedBy(albumsTable.find('artistKey', a.key), 'sortName') }} else {rows = albumsTable.range('sortName', null, null)}items = []let i = offwhile (i < rows.length && items.length < lim) {items.push(publicAlbum(rows[i]))i = i + 1}return page(rows.length, off, lim, items)}// ---- search -----------------------------------------------------------------------------------------------------// every word of q must be in the song's folded artist / title / album / genre textstatic searchAll = (q, offset, limit) => {off = clampOffset(offset)lim = clampLimit(limit)terms = []for (t of fold(q).split(' ')) {if (t != '') { terms.push(t) }}if (terms.length == 0) { return { q = q songs = page(0, off, lim, []) artists = [] albums = [] } }items = []let total = 0for (s of songsTable.iterate(null, null)) {let ok = truefor (t of terms) {if (!s.search.includes(t)) {ok = falsebreak}}if (!ok) { continue }if (total >= off && items.length < lim) { items.push(publicSong(s)) }total = total + 1}artists = []for (a of artistsTable.range('sortName', null, null)) {if (artists.length >= 10) { break }let ok = truefor (t of terms) {if (!a.sortName.includes(t)) { ok = false }}if (ok) { artists.push(publicArtist(a)) }}albums = []for (a of albumsTable.range('sortName', null, null)) {if (albums.length >= 10) { break }let ok = truefor (t of terms) {if (!a.sortName.includes(t)) { ok = false }}if (ok) { albums.push(publicAlbum(a)) }}return { q = q songs = page(total, off, lim, items) artists = artists albums = albums }}// ---- stats ------------------------------------------------------------------------------------------------------static libraryStats = () => {if (cache.stats != null) { return cache.stats }let songs = 0let seconds = 0let bytes = 0let played1 = 0let played5 = 0let withCover = 0let videos = 0for (s of songsTable.iterate(null, null)) {songs = songs + 1seconds = seconds + (s.duration == null ? 0 : s.duration)bytes = bytes + (s.size == null ? 0 : s.size)if (s.playCount >= 1) { played1 = played1 + 1 }if (s.playCount >= 5) { played5 = played5 + 1 }if (s.coverId != null) { withCover = withCover + 1 }if (s.kind == 'video') { videos = videos + 1 }}st = { songs = songs artists = artistsTable.count() albums = albumsTable.count() covers = coversTable.count() songsWithCover = withCovervideos = videos playedAtLeast1 = played1 playedAtLeast5 = played5 totalSeconds = seconds totalBytes = bytes }cache.stats = streturn st}