gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/lib/browse.hl

9.3 KB

  1. // lib/browse.hl — READING THE DATABASE FAST: pages of songs in the three orders, artists, albums, search, shuffle, stats.
  2. // The order lists (song ids with their play count, sorted by title / artist / album) are made once from the sorted
  3. // indexes of the songs table and kept in memory until a scan changes something; a page is a slice of such a list and
  4. // one lookup per row. Nothing here returns more than `maxLimit` rows. No writes (lib/library.hl and lib/catalog.hl write).
  5. import { random } from 'hl:math'
  6. import { songsTable, albumsTable, artistsTable, coversTable } from './db.hl'
  7. import { floor } from 'hl:math'
  8. import { fold, safeKey } from './util.hl'
  9. import { cache, dropOrderCache } from './state.hl'
  10. import { showOf } from './dups.hl'
  11. import { jbCount } from './plays.hl'
  12. static maxLimit = 200
  13. static defaultLimit = 50
  14. static sortField = (sort) => {
  15. if (sort == 'title') { return 'sortTitle' }
  16. if (sort == 'album') { return 'sortAlbum' }
  17. if (sort == 'plays') { return 'sortTitle' }
  18. return 'sortArtist'
  19. }
  20. // the lean rows { id, pc } of all songs in one order
  21. static orderList = (sort) => {
  22. field = sortField(sort)
  23. // plays is sorted in memory from the title index; it must not share that index's cache slot,
  24. // or a counted play (which drops this cache) and a title browse overwrite each other
  25. key = sort == 'plays' ? 'plays' : field
  26. list = cache.lists[key]
  27. if (list != null) { return list }
  28. let out = []
  29. // a song with copies is listed once (its first copy), with the highest play count of the group
  30. for (r of songsTable.range(field, null, null)) {
  31. w = showOf(r.id, r.playCount)
  32. if (w.shown) { out.push({ id = r.id pc = w.plays }) }
  33. }
  34. // the most played first, by a counting sort over the play counts (the index of playCount sorts the numbers as text: 9 before 12)
  35. if (sort == 'plays') {
  36. let top = 0
  37. for (r of out) { if (r.pc > top) { top = r.pc } }
  38. buckets = []
  39. let b = 0
  40. while (b <= top) {
  41. buckets.push([])
  42. b = b + 1
  43. }
  44. for (r of out) { buckets[r.pc].push(r) }
  45. sorted = []
  46. let k = top
  47. while (k >= 0) {
  48. for (r of buckets[k]) { sorted.push(r) }
  49. k = k - 1
  50. }
  51. out = sorted
  52. }
  53. lists = cache.lists
  54. lists[key] = out
  55. cache.lists = lists
  56. return out
  57. }
  58. // ---- what the API shows of a song / album / artist --------------------------------------------------------------
  59. static publicSong = (s) => {
  60. w = showOf(s.id, s.playCount)
  61. return {
  62. id = s.id title = s.title artist = s.artist albumArtist = s.albumArtist album = s.album track = s.track trackTotal = s.trackTotal
  63. disc = s.disc year = s.year genre = s.genre duration = s.duration format = s.format kind = s.kind size = s.size
  64. playCount = 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
  65. }
  66. }
  67. static publicAlbum = (a) => {
  68. 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 }
  69. }
  70. static publicArtist = (a) => {
  71. return { id = a.id name = a.name songCount = a.songCount albumCount = a.albumCount playCount = a.playCount coverId = a.coverId }
  72. }
  73. static clampLimit = (limit) => {
  74. if (limit == null || limit < 1) { return defaultLimit }
  75. return limit > maxLimit ? maxLimit : limit
  76. }
  77. static clampOffset = (offset) => { return offset == null || offset < 0 ? 0 : offset }
  78. // rows ordered by one string field (insertion sort; small lists only: one album, one artist)
  79. static orderedBy = (rows, field) => {
  80. out = []
  81. for (r of rows) {
  82. let j = out.length
  83. out.push(r)
  84. while (j > 0 && out[j - 1][field] > r[field]) {
  85. out[j] = out[j - 1]
  86. j = j - 1
  87. }
  88. out[j] = r
  89. }
  90. return out
  91. }
  92. static page = (total, offset, limit, items) => { return { total = total offset = offset limit = limit items = items } }
  93. // ---- songs ------------------------------------------------------------------------------------------------------
  94. // params: sort (title | artist | album | plays), offset, limit, minPlays, artist (an artist id), album (an album id)
  95. static songsPage = (sort, offset, limit, minPlays, artistId, albumId) => {
  96. off = clampOffset(offset)
  97. lim = clampLimit(limit)
  98. if (albumId != null) {
  99. a = albumsTable.fetch(albumId)
  100. if (a == null) { return page(0, off, lim, []) }
  101. return slicePage(orderedBy(songsTable.find('albumKey', a.key), 'sortAlbum'), off, lim, minPlays)
  102. }
  103. if (artistId != null) {
  104. a = artistsTable.fetch(artistId)
  105. if (a == null) { return page(0, off, lim, []) }
  106. return slicePage(orderedBy(songsTable.find('artistKey', a.key), 'sortArtist'), off, lim, minPlays)
  107. }
  108. list = orderList(sort)
  109. min = minPlays == null ? 0 : minPlays
  110. items = []
  111. let total = 0
  112. for (r of list) {
  113. if (r.pc < min) { continue }
  114. if (total >= off && items.length < lim) {
  115. s = songsTable.fetch(r.id)
  116. if (s != null) { items.push(publicSong(s)) }
  117. }
  118. total = total + 1
  119. }
  120. return page(total, off, lim, items)
  121. }
  122. // a page out of full rows already in order (an album, an artist)
  123. static slicePage = (rows, off, lim, minPlays) => {
  124. min = minPlays == null ? 0 : minPlays
  125. items = []
  126. let total = 0
  127. for (s of rows) {
  128. w = showOf(s.id, s.playCount)
  129. if (!w.shown || w.plays < min) { continue }
  130. if (total >= off && items.length < lim) { items.push(publicSong(s)) }
  131. total = total + 1
  132. }
  133. return page(total, off, lim, items)
  134. }
  135. // `count` random songs (no repeats) among those played at least `minPlays` times
  136. static shuffle = (minPlays, count) => {
  137. lim = clampLimit(count)
  138. min = minPlays == null ? 0 : minPlays
  139. pool = []
  140. for (r of orderList('title')) {
  141. if (r.pc >= min) { pool.push(r.id) }
  142. }
  143. items = []
  144. let left = pool.length
  145. while (items.length < lim && left > 0) {
  146. k = floor(random() * left)
  147. id = pool[k]
  148. pool[k] = pool[left - 1]
  149. left = left - 1
  150. s = songsTable.fetch(id)
  151. if (s != null) { items.push(publicSong(s)) }
  152. }
  153. return page(pool.length, 0, lim, items)
  154. }
  155. // ---- artists and albums -----------------------------------------------------------------------------------------
  156. static artistsPage = (offset, limit) => {
  157. off = clampOffset(offset)
  158. lim = clampLimit(limit)
  159. rows = artistsTable.range('sortName', null, null)
  160. items = []
  161. let i = off
  162. while (i < rows.length && items.length < lim) {
  163. items.push(publicArtist(rows[i]))
  164. i = i + 1
  165. }
  166. return page(rows.length, off, lim, items)
  167. }
  168. static albumsPage = (offset, limit, artistId) => {
  169. off = clampOffset(offset)
  170. lim = clampLimit(limit)
  171. let rows = []
  172. if (artistId != null) {
  173. a = artistsTable.fetch(artistId)
  174. if (a != null) { rows = orderedBy(albumsTable.find('artistKey', a.key), 'sortName') }
  175. } else {
  176. rows = albumsTable.range('sortName', null, null)
  177. }
  178. items = []
  179. let i = off
  180. while (i < rows.length && items.length < lim) {
  181. items.push(publicAlbum(rows[i]))
  182. i = i + 1
  183. }
  184. return page(rows.length, off, lim, items)
  185. }
  186. // ---- search -----------------------------------------------------------------------------------------------------
  187. // every word of q must be in the song's folded artist / title / album / genre text
  188. static searchAll = (q, offset, limit) => {
  189. off = clampOffset(offset)
  190. lim = clampLimit(limit)
  191. terms = []
  192. words = []
  193. for (t of fold(q).split(' ')) {
  194. if (t != '') { words.push(t) }
  195. }
  196. for (t of words) { terms.push(t) }
  197. // artists and albums are matched on their index keys, where a comma is character 2
  198. keyTerms = []
  199. for (t of words) { keyTerms.push(safeKey(t)) }
  200. if (terms.length == 0) { return { q = q songs = page(0, off, lim, []) artists = [] albums = [] } }
  201. items = []
  202. let total = 0
  203. for (s of songsTable.iterate(null, null)) {
  204. let ok = true
  205. for (t of terms) {
  206. if (!s.search.includes(t)) {
  207. ok = false
  208. break
  209. }
  210. }
  211. if (!ok) { continue }
  212. if (!showOf(s.id, s.playCount).shown) { continue }
  213. if (total >= off && items.length < lim) { items.push(publicSong(s)) }
  214. total = total + 1
  215. }
  216. artists = []
  217. for (a of artistsTable.range('sortName', null, null)) {
  218. if (artists.length >= 10) { break }
  219. let ok = true
  220. for (t of keyTerms) {
  221. if (!a.sortName.includes(t)) { ok = false }
  222. }
  223. if (ok) { artists.push(publicArtist(a)) }
  224. }
  225. albums = []
  226. for (a of albumsTable.range('sortName', null, null)) {
  227. if (albums.length >= 10) { break }
  228. let ok = true
  229. for (t of keyTerms) {
  230. if (!a.sortName.includes(t)) { ok = false }
  231. }
  232. if (ok) { albums.push(publicAlbum(a)) }
  233. }
  234. return { q = q songs = page(total, off, lim, items) artists = artists albums = albums }
  235. }
  236. // ---- stats ------------------------------------------------------------------------------------------------------
  237. static libraryStats = () => {
  238. if (cache.stats != null) { return cache.stats }
  239. let songs = 0
  240. let seconds = 0
  241. let bytes = 0
  242. let played1 = 0
  243. let played5 = 0
  244. let withCover = 0
  245. let videos = 0
  246. for (s of songsTable.iterate(null, null)) {
  247. songs = songs + 1
  248. seconds = seconds + (s.duration == null ? 0 : s.duration)
  249. bytes = bytes + (s.size == null ? 0 : s.size)
  250. if (s.playCount >= 1) { played1 = played1 + 1 }
  251. if (s.playCount >= 5) { played5 = played5 + 1 }
  252. if (s.coverId != null) { withCover = withCover + 1 }
  253. if (s.kind == 'video') { videos = videos + 1 }
  254. }
  255. st = { songs = songs artists = artistsTable.count() albums = albumsTable.count() covers = coversTable.count() songsWithCover = withCover
  256. videos = videos playedAtLeast1 = played1 playedAtLeast5 = played5 totalSeconds = seconds totalBytes = bytes }
  257. cache.stats = st
  258. return st
  259. }

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