jukebox
All repositories: gitoria
9.3 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, safeKey } from './util.hl'import { cache, dropOrderCache } from './state.hl'import { showOf } from './dups.hl'import { jbCount } from './plays.hl'static maxLimit = 200static defaultLimit = 50static sortField = (sort) => {if (sort == 'title') { return 'sortTitle' }if (sort == 'album') { return 'sortAlbum' }if (sort == 'plays') { return 'sortTitle' }return 'sortArtist'}// the lean rows { id, pc } of all songs in one orderstatic orderList = (sort) => {field = sortField(sort)// plays is sorted in memory from the title index; it must not share that index's cache slot,// or a counted play (which drops this cache) and a title browse overwrite each otherkey = sort == 'plays' ? 'plays' : fieldlist = cache.lists[key]if (list != null) { return list }let out = []// a song with copies is listed once (its first copy), with the highest play count of the groupfor (r of songsTable.range(field, null, null)) {w = showOf(r.id, r.playCount)if (w.shown) { out.push({ id = r.id pc = w.plays }) }}// the most played first, by a counting sort over the play counts (the index of playCount sorts the numbers as text: 9 before 12)if (sort == 'plays') {let top = 0for (r of out) { if (r.pc > top) { top = r.pc } }buckets = []let b = 0while (b <= top) {buckets.push([])b = b + 1}for (r of out) { buckets[r.pc].push(r) }sorted = []let k = topwhile (k >= 0) {for (r of buckets[k]) { sorted.push(r) }k = k - 1}out = sorted}lists = cache.listslists[key] = outcache.lists = listsreturn out}// ---- what the API shows of a song / album / artist --------------------------------------------------------------static publicSong = (s) => {w = showOf(s.id, s.playCount)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 = w.plays filePlays = s.playCount jukeboxPlays = jbCount(s.id) copies = w.copies 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 | plays), 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) {w = showOf(s.id, s.playCount)if (!w.shown || w.plays < 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 = []words = []for (t of fold(q).split(' ')) {if (t != '') { words.push(t) }}for (t of words) { terms.push(t) }// artists and albums are matched on their index keys, where a comma is character 2keyTerms = []for (t of words) { keyTerms.push(safeKey(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 (!showOf(s.id, s.playCount).shown) { 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 keyTerms) {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 keyTerms) {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}
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre