@trippnology/mixshell 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +294 -2
- package/assets/mixshell-screenshot.png +0 -0
- package/package.json +73 -5
- package/src/alsa-pulse.conf +20 -0
- package/src/alsa-setup.js +15 -0
- package/src/components/browser.js +193 -0
- package/src/components/config.js +168 -0
- package/src/components/durations.js +151 -0
- package/src/components/library.js +679 -0
- package/src/components/mediakeys.js +222 -0
- package/src/components/mpris.js +309 -0
- package/src/components/player.js +412 -0
- package/src/components/playlist.js +335 -0
- package/src/components/session.js +96 -0
- package/src/constants.js +164 -0
- package/src/engines/ffmpeg.js +601 -0
- package/src/engines/index.js +14 -0
- package/src/engines/webaudio.js +317 -0
- package/src/index.js +188 -0
- package/src/mediakeys/macos-nowplaying.js +227 -0
- package/src/ui/app.js +56 -0
- package/src/ui/artPane.js +314 -0
- package/src/ui/confirmPrompt.js +34 -0
- package/src/ui/constants.js +133 -0
- package/src/ui/controller.js +1641 -0
- package/src/ui/dom.js +9 -0
- package/src/ui/goToPrompt.js +105 -0
- package/src/ui/index.html +78 -0
- package/src/ui/libraryPanel.js +415 -0
- package/src/ui/listView.js +209 -0
- package/src/ui/onboarding.js +353 -0
- package/src/ui/playlistPanel.js +207 -0
- package/src/ui/settingsPanel.js +473 -0
- package/src/ui/shortcuts.js +30 -0
- package/src/ui/splash.js +302 -0
- package/src/ui/style.css +532 -0
- package/src/ui/subtabs.js +31 -0
- package/src/ui/visualizer/bars.js +74 -0
- package/src/ui/visualizer/circles.js +64 -0
- package/src/ui/visualizer/color.js +61 -0
- package/src/ui/visualizer/cube.js +105 -0
- package/src/ui/visualizer/grid.js +68 -0
- package/src/ui/visualizer/index.js +65 -0
- package/src/ui/visualizer/onset.js +130 -0
- package/src/ui/visualizer/spectrum.js +34 -0
- package/src/ui/visualizer/vu.js +71 -0
- package/src/ui/visualizer/waveform.js +58 -0
- package/src/utils/audioAnalyzer.js +362 -0
- package/src/utils/audioDevices.js +222 -0
- package/src/utils/cellart.js +75 -0
- package/src/utils/debug.js +7 -0
- package/src/utils/durationProbe.js +48 -0
- package/src/utils/folderArt.js +46 -0
- package/src/utils/format.js +20 -0
- package/src/utils/id3.js +84 -0
- package/src/utils/pathInput.js +76 -0
- package/src/utils/playlistIO.js +176 -0
- package/src/utils/terminalGraphics.js +47 -0
|
@@ -0,0 +1,679 @@
|
|
|
1
|
+
// Media library backend (issues/023): SQLite index over the configured
|
|
2
|
+
// library directories, an append-only play log, and the query surface the
|
|
3
|
+
// library panel renders from. Synchronous better-sqlite3 calls, prepared
|
|
4
|
+
// statements, no ORM; scanning is async with bounded parse concurrency and
|
|
5
|
+
// batched write transactions.
|
|
6
|
+
|
|
7
|
+
import { EventEmitter } from 'node:events';
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { setImmediate as nextTask } from 'node:timers/promises';
|
|
11
|
+
|
|
12
|
+
import Database from 'better-sqlite3';
|
|
13
|
+
|
|
14
|
+
import { isAudioFile, LIBRARY_DB_FILE } from '../constants.js';
|
|
15
|
+
import { DBG } from '../utils/debug.js';
|
|
16
|
+
import { fallbackMetadata, readMetadata } from '../utils/id3.js';
|
|
17
|
+
|
|
18
|
+
// Panel view set and the smart-view → method map (the panel renders the
|
|
19
|
+
// row label from the view, tracks from the method).
|
|
20
|
+
export const LIBRARY_VIEWS = [
|
|
21
|
+
{ key: 'artists', label: 'Artists' },
|
|
22
|
+
{ key: 'albums', label: 'Albums' },
|
|
23
|
+
{ key: 'genres', label: 'Genres' },
|
|
24
|
+
{ key: 'years', label: 'Years' },
|
|
25
|
+
{ key: 'mostplayed', label: 'Most Played' },
|
|
26
|
+
{ key: 'recentadded', label: 'Recently Added' },
|
|
27
|
+
{ key: 'recentplayed', label: 'Recently Played' },
|
|
28
|
+
{ key: 'favourites', label: 'Favourites' },
|
|
29
|
+
{ key: 'search', label: 'Search' },
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
export const LIB_SMART = {
|
|
33
|
+
mostplayed: 'mostPlayed',
|
|
34
|
+
recentadded: 'recentlyAdded',
|
|
35
|
+
recentplayed: 'recentlyPlayed',
|
|
36
|
+
favourites: 'favourites',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Most Played time windows (issues/032). 'all' reads the denormalised
|
|
40
|
+
// play_count; the rest aggregate the plays log over a cutoff computed in
|
|
41
|
+
// JS (local time for the year boundary). Order is the cycle order.
|
|
42
|
+
export const PLAY_WINDOWS = [
|
|
43
|
+
{ key: 'all', label: 'All time' },
|
|
44
|
+
{ key: 'year', label: 'This year' },
|
|
45
|
+
{ key: '30d', label: '30 days' },
|
|
46
|
+
{ key: '7d', label: '7 days' },
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
// Track-sort allowlist (issues/033): key → { label, natural, col, pre?, ties? }.
|
|
50
|
+
// Columns are `t.`-prefixed so the built fragments order both #tracks and
|
|
51
|
+
// the windowed mostPlayed JOIN (both alias tracks as t). Callers pass one
|
|
52
|
+
// of these keys — never interpolate a caller-supplied string into SQL.
|
|
53
|
+
// `natural` is the direction a sort cycle lands on (Play count/Recently
|
|
54
|
+
// added open descending, Year newest-first).
|
|
55
|
+
export const TRACK_SORTS = {
|
|
56
|
+
title: { label: 'Title', natural: 'asc', col: 't.title COLLATE NOCASE' },
|
|
57
|
+
artist: {
|
|
58
|
+
label: 'Artist',
|
|
59
|
+
natural: 'asc',
|
|
60
|
+
col: 't.artist COLLATE NOCASE',
|
|
61
|
+
ties: ', t.album COLLATE NOCASE, CAST(t.track AS INTEGER)',
|
|
62
|
+
},
|
|
63
|
+
album: {
|
|
64
|
+
label: 'Album',
|
|
65
|
+
natural: 'asc',
|
|
66
|
+
col: 't.album COLLATE NOCASE',
|
|
67
|
+
ties: ', CAST(t.track AS INTEGER), t.title COLLATE NOCASE',
|
|
68
|
+
},
|
|
69
|
+
year: {
|
|
70
|
+
label: 'Year',
|
|
71
|
+
natural: 'desc',
|
|
72
|
+
pre: 't.year IS NULL, ',
|
|
73
|
+
col: 't.year',
|
|
74
|
+
},
|
|
75
|
+
track: {
|
|
76
|
+
label: 'Track No',
|
|
77
|
+
natural: 'asc',
|
|
78
|
+
col: 'CAST(t.track AS INTEGER)',
|
|
79
|
+
},
|
|
80
|
+
playcount: { label: 'Play count', natural: 'desc', col: 't.play_count' },
|
|
81
|
+
added: { label: 'Recently added', natural: 'desc', col: 't.added_at' },
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// Group-sort allowlist (issues/033): Name · Count. Count falls back to the
|
|
85
|
+
// name order for ties so equal-sized groups never shuffle between renders.
|
|
86
|
+
export const GROUP_SORTS = {
|
|
87
|
+
name: { label: 'Name', natural: 'asc', col: 'value COLLATE NOCASE' },
|
|
88
|
+
count: {
|
|
89
|
+
label: 'Count',
|
|
90
|
+
natural: 'desc',
|
|
91
|
+
col: 'count',
|
|
92
|
+
ties: ', value COLLATE NOCASE',
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// Years group: 'Name' is the numeric year with NULLs last (the existing
|
|
97
|
+
// convention) rather than the string-collated sentinel value.
|
|
98
|
+
const YEARS_SORTS = {
|
|
99
|
+
name: { pre: 'year IS NULL, ', col: 'year' },
|
|
100
|
+
count: { col: 'count', ties: ', year IS NULL, year' },
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// ORDER BY fragment for a sort entry: the direction suffixes the primary
|
|
104
|
+
// column only; `pre` (NULL guard) and `ties` stay unsuffixed. Track
|
|
105
|
+
// fragments end in `, t.path` so the order is always deterministic. Lookup
|
|
106
|
+
// only — no caller string ever reaches the SQL.
|
|
107
|
+
const fragment = (entry, dir) =>
|
|
108
|
+
`${entry.pre ?? ''}${entry.col}${dir === 'desc' ? ' DESC' : ''}${entry.ties ?? ''}`;
|
|
109
|
+
|
|
110
|
+
// Fragment for a caller sort spec, or null when absent/unknown — callers
|
|
111
|
+
// fall back to their built-in default order then.
|
|
112
|
+
function trackOrder(sort) {
|
|
113
|
+
const entry = TRACK_SORTS[sort?.key];
|
|
114
|
+
return entry ? `${fragment(entry, sort?.dir)}, t.path` : null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Grouping view key → tracks column. Years is handled separately (NULL
|
|
118
|
+
// sorting + the 'Unknown' sentinel).
|
|
119
|
+
const GROUP_COLUMNS = {
|
|
120
|
+
artists: 'album_artist',
|
|
121
|
+
albums: 'album',
|
|
122
|
+
genres: 'genre',
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
// Empty genre tags group under this sentinel; tracksWhere maps it back.
|
|
126
|
+
const UNKNOWN = 'Unknown';
|
|
127
|
+
|
|
128
|
+
// `t.`-prefixed so the windowed mostPlayed query can join tracks against
|
|
129
|
+
// the plays table without ambiguous bare columns.
|
|
130
|
+
const TRACK_COLUMNS = `
|
|
131
|
+
t.path,
|
|
132
|
+
t.title,
|
|
133
|
+
t.artist,
|
|
134
|
+
t.album_artist AS albumArtist,
|
|
135
|
+
t.album,
|
|
136
|
+
t.genre,
|
|
137
|
+
t.year,
|
|
138
|
+
t.track,
|
|
139
|
+
t.duration,
|
|
140
|
+
t.has_art AS hasArt,
|
|
141
|
+
t.play_count AS playCount,
|
|
142
|
+
t.first_played AS firstPlayed,
|
|
143
|
+
t.last_played AS lastPlayed,
|
|
144
|
+
t.added_at AS addedAt,
|
|
145
|
+
t.favourite AS favourite
|
|
146
|
+
`;
|
|
147
|
+
|
|
148
|
+
// Parse concurrency and upsert batch size for scans.
|
|
149
|
+
const SCAN_CONCURRENCY = 4;
|
|
150
|
+
const SCAN_BATCH = 50;
|
|
151
|
+
// Progress events per scan (files between emissions).
|
|
152
|
+
const SCAN_PROGRESS_STEP = 25;
|
|
153
|
+
// Entries/files between event-loop yields. The walk and stat passes are
|
|
154
|
+
// synchronous; without yielding they starve the UI render loop for the
|
|
155
|
+
// whole pass, freezing the screen on whatever was painted when the scan
|
|
156
|
+
// started (issues/031).
|
|
157
|
+
const SCAN_YIELD = 50;
|
|
158
|
+
|
|
159
|
+
export class Library extends EventEmitter {
|
|
160
|
+
// `config` supplies libraryDirs for scan(); `dbPath` and `parse` are
|
|
161
|
+
// injectable for tests.
|
|
162
|
+
constructor({
|
|
163
|
+
config = null,
|
|
164
|
+
dbPath = LIBRARY_DB_FILE,
|
|
165
|
+
parse = readMetadata,
|
|
166
|
+
} = {}) {
|
|
167
|
+
super();
|
|
168
|
+
this.config = config;
|
|
169
|
+
this.parse = parse;
|
|
170
|
+
this.scanning = false;
|
|
171
|
+
|
|
172
|
+
this.db = new Database(dbPath);
|
|
173
|
+
this.db.pragma('journal_mode = WAL');
|
|
174
|
+
this.db.pragma('synchronous = NORMAL');
|
|
175
|
+
this.db.exec(`
|
|
176
|
+
CREATE TABLE IF NOT EXISTS tracks (
|
|
177
|
+
path TEXT PRIMARY KEY,
|
|
178
|
+
title TEXT NOT NULL DEFAULT '',
|
|
179
|
+
artist TEXT NOT NULL DEFAULT '',
|
|
180
|
+
album_artist TEXT NOT NULL DEFAULT '',
|
|
181
|
+
album TEXT NOT NULL DEFAULT '',
|
|
182
|
+
genre TEXT NOT NULL DEFAULT '',
|
|
183
|
+
year INTEGER,
|
|
184
|
+
track TEXT NOT NULL DEFAULT '',
|
|
185
|
+
duration REAL NOT NULL DEFAULT 0,
|
|
186
|
+
mtime_ms INTEGER NOT NULL DEFAULT 0,
|
|
187
|
+
size INTEGER NOT NULL DEFAULT 0,
|
|
188
|
+
has_art INTEGER NOT NULL DEFAULT 0,
|
|
189
|
+
play_count INTEGER NOT NULL DEFAULT 0,
|
|
190
|
+
first_played INTEGER,
|
|
191
|
+
last_played INTEGER,
|
|
192
|
+
added_at INTEGER NOT NULL DEFAULT 0,
|
|
193
|
+
favourite INTEGER NOT NULL DEFAULT 0
|
|
194
|
+
);
|
|
195
|
+
CREATE TABLE IF NOT EXISTS plays (
|
|
196
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
197
|
+
path TEXT NOT NULL,
|
|
198
|
+
played_at INTEGER NOT NULL
|
|
199
|
+
);
|
|
200
|
+
CREATE INDEX IF NOT EXISTS idx_plays_path_time ON plays (path, played_at);
|
|
201
|
+
CREATE INDEX IF NOT EXISTS idx_plays_time ON plays (played_at);
|
|
202
|
+
`);
|
|
203
|
+
|
|
204
|
+
// Schema bump (issues/045): databases created before the favourite
|
|
205
|
+
// flag gain the column in place, keeping their play logs. The
|
|
206
|
+
// CREATE TABLE above already covers fresh databases.
|
|
207
|
+
if (
|
|
208
|
+
!this.db
|
|
209
|
+
.pragma('table_info(tracks)')
|
|
210
|
+
.some((col) => col.name === 'favourite')
|
|
211
|
+
) {
|
|
212
|
+
this.db.exec(
|
|
213
|
+
'ALTER TABLE tracks ADD COLUMN favourite INTEGER NOT NULL DEFAULT 0',
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
this.stmts = {
|
|
218
|
+
getTrack: this.db.prepare(
|
|
219
|
+
'SELECT path, mtime_ms, size FROM tracks WHERE path = ?',
|
|
220
|
+
),
|
|
221
|
+
upsertTrack: this.db.prepare(`
|
|
222
|
+
INSERT INTO tracks (
|
|
223
|
+
path, title, artist, album_artist, album, genre, year, track,
|
|
224
|
+
duration, mtime_ms, size, has_art, added_at
|
|
225
|
+
) VALUES (
|
|
226
|
+
@path, @title, @artist, @albumArtist, @album, @genre, @year, @track,
|
|
227
|
+
@duration, @mtimeMs, @size, @hasArt, @addedAt
|
|
228
|
+
)
|
|
229
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
230
|
+
title = excluded.title,
|
|
231
|
+
artist = excluded.artist,
|
|
232
|
+
album_artist = excluded.album_artist,
|
|
233
|
+
album = excluded.album,
|
|
234
|
+
genre = excluded.genre,
|
|
235
|
+
year = excluded.year,
|
|
236
|
+
track = excluded.track,
|
|
237
|
+
duration = excluded.duration,
|
|
238
|
+
mtime_ms = excluded.mtime_ms,
|
|
239
|
+
size = excluded.size,
|
|
240
|
+
has_art = excluded.has_art
|
|
241
|
+
`),
|
|
242
|
+
// NOTE (issues/045): `favourite` is deliberately absent from the
|
|
243
|
+
// upsert — a rescan must never reset the user's stars.
|
|
244
|
+
ensureTrack: this.db.prepare(`
|
|
245
|
+
INSERT OR IGNORE INTO tracks (path, title, added_at)
|
|
246
|
+
VALUES (?, ?, ?)
|
|
247
|
+
`),
|
|
248
|
+
addPlay: this.db.prepare(
|
|
249
|
+
'INSERT INTO plays (path, played_at) VALUES (?, ?)',
|
|
250
|
+
),
|
|
251
|
+
bumpPlay: this.db.prepare(`
|
|
252
|
+
UPDATE tracks SET
|
|
253
|
+
play_count = play_count + 1,
|
|
254
|
+
first_played = COALESCE(first_played, ?),
|
|
255
|
+
last_played = ?
|
|
256
|
+
WHERE path = ?
|
|
257
|
+
`),
|
|
258
|
+
// Paths still on disk (JSON array) — everything else gets pruned.
|
|
259
|
+
pruneMissing: this.db.prepare(
|
|
260
|
+
'DELETE FROM tracks WHERE path NOT IN (SELECT value FROM json_each(?))',
|
|
261
|
+
),
|
|
262
|
+
// Indexed tracks under one scan root (settings dir list, issues/031).
|
|
263
|
+
countForRoot: this.db.prepare(
|
|
264
|
+
"SELECT COUNT(*) AS n FROM tracks WHERE path LIKE ? ESCAPE '\\'",
|
|
265
|
+
),
|
|
266
|
+
// Export labels for playlist files (issues/028), one path each.
|
|
267
|
+
trackInfo: this.db.prepare(
|
|
268
|
+
'SELECT path, title, artist, duration FROM tracks WHERE path = ?',
|
|
269
|
+
),
|
|
270
|
+
// Duration cache reads (issues/046): one batched query for the
|
|
271
|
+
// playlist totals header. Only rows with a real duration come
|
|
272
|
+
// back — a miss is an "unknown" track, never a guess.
|
|
273
|
+
durationsByPaths: this.db.prepare(`
|
|
274
|
+
SELECT path, duration FROM tracks
|
|
275
|
+
WHERE duration > 0 AND path IN (SELECT value FROM json_each(?))
|
|
276
|
+
`),
|
|
277
|
+
// Duration cache writes (issues/046): fill only empty durations —
|
|
278
|
+
// a learned value (as-played or ffmpeg header pass) must never
|
|
279
|
+
// clobber what the scan parsed from the tags. Staleness is the
|
|
280
|
+
// scan's job: an mtime/size change re-parses and overwrites.
|
|
281
|
+
setDurationIfUnknown: this.db.prepare(
|
|
282
|
+
'UPDATE tracks SET duration = ? WHERE path = ? AND duration = 0',
|
|
283
|
+
),
|
|
284
|
+
// Favourite flag (issues/045).
|
|
285
|
+
getFavourite: this.db.prepare(
|
|
286
|
+
'SELECT favourite FROM tracks WHERE path = ?',
|
|
287
|
+
),
|
|
288
|
+
setFavourite: this.db.prepare(
|
|
289
|
+
'UPDATE tracks SET favourite = ? WHERE path = ?',
|
|
290
|
+
),
|
|
291
|
+
favouritePaths: this.db.prepare(
|
|
292
|
+
'SELECT path FROM tracks WHERE favourite = 1',
|
|
293
|
+
),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
get dirs() {
|
|
298
|
+
return this.config?.get('libraryDirs') ?? [];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// True once at least one library directory is configured — the panel's
|
|
302
|
+
// empty state branches on it.
|
|
303
|
+
isConfigured() {
|
|
304
|
+
return this.dirs.length > 0;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// --- Queries ---------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
// [{ value, count }] for a grouping view. NULL years group under the
|
|
310
|
+
// 'Unknown' sentinel; tracksWhere maps it back to IS NULL. `sort` is a
|
|
311
|
+
// { key, dir } spec looked up in the allowlists (issues/033).
|
|
312
|
+
groupBy(key, sort = {}) {
|
|
313
|
+
const sorts = key === 'years' ? YEARS_SORTS : GROUP_SORTS;
|
|
314
|
+
const order = fragment(sorts[sort.key] ?? sorts.name, sort.dir);
|
|
315
|
+
if (key === 'years') {
|
|
316
|
+
return this.db
|
|
317
|
+
.prepare(
|
|
318
|
+
`SELECT year AS value, COUNT(*) AS count
|
|
319
|
+
FROM tracks GROUP BY year
|
|
320
|
+
ORDER BY ${order}`,
|
|
321
|
+
)
|
|
322
|
+
.all()
|
|
323
|
+
.map((row) => ({
|
|
324
|
+
value: row.value === null ? UNKNOWN : row.value,
|
|
325
|
+
count: row.count,
|
|
326
|
+
}));
|
|
327
|
+
}
|
|
328
|
+
const column = GROUP_COLUMNS[key];
|
|
329
|
+
if (!column) return [];
|
|
330
|
+
return this.db
|
|
331
|
+
.prepare(
|
|
332
|
+
`SELECT COALESCE(NULLIF(${column}, ''), '${UNKNOWN}') AS value,
|
|
333
|
+
COUNT(*) AS count
|
|
334
|
+
FROM tracks GROUP BY value
|
|
335
|
+
ORDER BY ${order}`,
|
|
336
|
+
)
|
|
337
|
+
.all();
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Tracks for a drilled-in group. Sentinels round-trip from groupBy().
|
|
341
|
+
tracksWhere(key, value, sort) {
|
|
342
|
+
let where;
|
|
343
|
+
const params = [];
|
|
344
|
+
if (key === 'years') {
|
|
345
|
+
if (value === UNKNOWN) {
|
|
346
|
+
where = 'year IS NULL';
|
|
347
|
+
} else {
|
|
348
|
+
where = 'year = ?';
|
|
349
|
+
params.push(value);
|
|
350
|
+
}
|
|
351
|
+
} else if (key === 'genres' && value === UNKNOWN) {
|
|
352
|
+
where = "(genre IS NULL OR genre = '')";
|
|
353
|
+
} else {
|
|
354
|
+
const column = GROUP_COLUMNS[key];
|
|
355
|
+
if (!column) return [];
|
|
356
|
+
where = `COALESCE(NULLIF(${column}, ''), '${UNKNOWN}') = ?`;
|
|
357
|
+
params.push(value);
|
|
358
|
+
}
|
|
359
|
+
return this.#tracks(`WHERE ${where}`, params, trackOrder(sort));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
search(query, sort) {
|
|
363
|
+
const like = `%${query.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
|
364
|
+
return this.#tracks(
|
|
365
|
+
`WHERE title LIKE ? ESCAPE '\\'
|
|
366
|
+
OR artist LIKE ? ESCAPE '\\'
|
|
367
|
+
OR album LIKE ? ESCAPE '\\'`,
|
|
368
|
+
[like, like, like],
|
|
369
|
+
trackOrder(sort),
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
mostPlayed(window = 'all', sort) {
|
|
374
|
+
// 'all' (and any unknown key) reads the denormalised counter; the
|
|
375
|
+
// time windows (issues/032) aggregate the plays log — plays for
|
|
376
|
+
// pruned files drop out of the inner join. A sort spec (issues/033)
|
|
377
|
+
// overrides the play-count order in both shapes.
|
|
378
|
+
const now = Date.now();
|
|
379
|
+
const cutoff =
|
|
380
|
+
window === 'year'
|
|
381
|
+
? new Date(new Date(now).getFullYear(), 0, 1).getTime()
|
|
382
|
+
: window === '30d'
|
|
383
|
+
? now - 30 * 86400000
|
|
384
|
+
: window === '7d'
|
|
385
|
+
? now - 7 * 86400000
|
|
386
|
+
: null;
|
|
387
|
+
if (cutoff === null) {
|
|
388
|
+
return this.#tracks(
|
|
389
|
+
'WHERE t.play_count > 0',
|
|
390
|
+
[],
|
|
391
|
+
trackOrder(sort) ?? 't.play_count DESC, t.last_played DESC',
|
|
392
|
+
200,
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
const order = trackOrder(sort) ?? 'windowPlays DESC, MAX(p.played_at) DESC';
|
|
396
|
+
return this.db
|
|
397
|
+
.prepare(`
|
|
398
|
+
SELECT ${TRACK_COLUMNS}, COUNT(*) AS windowPlays
|
|
399
|
+
FROM plays p
|
|
400
|
+
JOIN tracks t ON t.path = p.path
|
|
401
|
+
WHERE p.played_at >= ?
|
|
402
|
+
GROUP BY t.path
|
|
403
|
+
ORDER BY ${order}
|
|
404
|
+
LIMIT 200
|
|
405
|
+
`)
|
|
406
|
+
.all(cutoff);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
recentlyAdded(limit = 100, sort) {
|
|
410
|
+
return this.#tracks(
|
|
411
|
+
'',
|
|
412
|
+
[],
|
|
413
|
+
trackOrder(sort) ?? 'added_at DESC, path',
|
|
414
|
+
limit,
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
recentlyPlayed(limit = 100, sort) {
|
|
419
|
+
return this.#tracks(
|
|
420
|
+
'WHERE last_played IS NOT NULL',
|
|
421
|
+
[],
|
|
422
|
+
trackOrder(sort) ?? 'last_played DESC',
|
|
423
|
+
limit,
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
favourites(sort) {
|
|
428
|
+
return this.#tracks('WHERE t.favourite = 1', [], trackOrder(sort));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
#tracks(where, params = [], order, limit) {
|
|
432
|
+
const parts = [`SELECT ${TRACK_COLUMNS} FROM tracks t`];
|
|
433
|
+
if (where) parts.push(where);
|
|
434
|
+
parts.push(
|
|
435
|
+
`ORDER BY ${order ?? `album COLLATE NOCASE, CAST(track AS INTEGER), title COLLATE NOCASE`}`,
|
|
436
|
+
);
|
|
437
|
+
let sql = parts.join('\n');
|
|
438
|
+
if (limit !== undefined) sql += `\nLIMIT ?`;
|
|
439
|
+
return this.db
|
|
440
|
+
.prepare(sql)
|
|
441
|
+
.all(...params, ...(limit !== undefined ? [limit] : []));
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// --- Play log ----------------------------------------------------------------
|
|
445
|
+
|
|
446
|
+
// Count a play on track start. Files never scanned still count: a
|
|
447
|
+
// minimal row (filename as title) is created so the counters stick.
|
|
448
|
+
recordPlay(trackPath, when = Date.now()) {
|
|
449
|
+
this.db.transaction(() => {
|
|
450
|
+
this.stmts.ensureTrack.run(trackPath, path.basename(trackPath), when);
|
|
451
|
+
this.stmts.addPlay.run(trackPath, when);
|
|
452
|
+
this.stmts.bumpPlay.run(when, when, trackPath);
|
|
453
|
+
})();
|
|
454
|
+
this.emit('updated');
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// --- Favourites ---------------------------------------------------------------
|
|
458
|
+
|
|
459
|
+
// Flip the star flag (issues/045) and return the new state (true =
|
|
460
|
+
// starred) for toasts. Files never scanned are indexed first (filename
|
|
461
|
+
// bootstrap, like recordPlay) so the flag is never silently lost; a
|
|
462
|
+
// rescan upsert does not touch the column.
|
|
463
|
+
toggleFavourite(trackPath) {
|
|
464
|
+
const starred = this.db.transaction(() => {
|
|
465
|
+
this.stmts.ensureTrack.run(
|
|
466
|
+
trackPath,
|
|
467
|
+
path.basename(trackPath),
|
|
468
|
+
Date.now(),
|
|
469
|
+
);
|
|
470
|
+
const next = this.stmts.getFavourite.get(trackPath)?.favourite ? 0 : 1;
|
|
471
|
+
this.stmts.setFavourite.run(next, trackPath);
|
|
472
|
+
return next === 1;
|
|
473
|
+
})();
|
|
474
|
+
this.emit('updated');
|
|
475
|
+
return starred;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// Paths of every starred track — the browser/playlist panels mark
|
|
479
|
+
// rows from this set without touching per-row queries.
|
|
480
|
+
favouritePaths() {
|
|
481
|
+
return this.stmts.favouritePaths.all().map((row) => row.path);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// --- Duration cache (issues/046) ----------------------------------------------
|
|
485
|
+
|
|
486
|
+
// path → seconds for every known path with a real duration. One
|
|
487
|
+
// prepared statement over the whole path set — the playlist totals
|
|
488
|
+
// header recomputes per render and per-path gets would add up.
|
|
489
|
+
durationsByPaths(paths) {
|
|
490
|
+
const byPath = new Map();
|
|
491
|
+
for (const row of this.stmts.durationsByPaths.all(JSON.stringify(paths))) {
|
|
492
|
+
byPath.set(row.path, row.duration);
|
|
493
|
+
}
|
|
494
|
+
return byPath;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// Remember durations learned outside the scan (as-played, issues/046
|
|
498
|
+
// ffmpeg header pass). Unscanned files get the filename bootstrap row
|
|
499
|
+
// first (recordPlay precedent) so the value is never lost; known
|
|
500
|
+
// durations are left alone (see setDurationIfUnknown). One transaction
|
|
501
|
+
// and one 'updated' per batch — the background pass can drain a
|
|
502
|
+
// hundred queue entries without churning the UI.
|
|
503
|
+
learnDurations(entries) {
|
|
504
|
+
let changed = 0;
|
|
505
|
+
this.db.transaction(() => {
|
|
506
|
+
for (const { path: trackPath, seconds } of entries) {
|
|
507
|
+
if (!(seconds > 0)) continue;
|
|
508
|
+
this.stmts.ensureTrack.run(
|
|
509
|
+
trackPath,
|
|
510
|
+
path.basename(trackPath),
|
|
511
|
+
Date.now(),
|
|
512
|
+
);
|
|
513
|
+
changed += this.stmts.setDurationIfUnknown.run(
|
|
514
|
+
seconds,
|
|
515
|
+
trackPath,
|
|
516
|
+
).changes;
|
|
517
|
+
}
|
|
518
|
+
})();
|
|
519
|
+
if (changed > 0) this.emit('updated');
|
|
520
|
+
return changed;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// --- Scanning ------------------------------------------------------------------
|
|
524
|
+
|
|
525
|
+
// Incremental scan of the given roots (default: configured libraryDirs).
|
|
526
|
+
// Files whose mtime + size match the index are not re-parsed; vanished
|
|
527
|
+
// files are pruned. Emits scanProgress(done, total), scanDone and
|
|
528
|
+
// updated. Concurrent scans collapse into the running one.
|
|
529
|
+
async scan(dirs = this.dirs) {
|
|
530
|
+
if (this.scanning) return;
|
|
531
|
+
this.scanning = true;
|
|
532
|
+
try {
|
|
533
|
+
const files = [];
|
|
534
|
+
for (const dir of dirs) {
|
|
535
|
+
await this.#walk(dir, files);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// Stat pass: keep unchanged files, queue the rest for parsing.
|
|
539
|
+
const seen = new Set();
|
|
540
|
+
const changed = [];
|
|
541
|
+
let checked = 0;
|
|
542
|
+
for (const filePath of files) {
|
|
543
|
+
if (++checked % SCAN_YIELD === 0) await nextTask();
|
|
544
|
+
let stat;
|
|
545
|
+
try {
|
|
546
|
+
stat = fs.statSync(filePath);
|
|
547
|
+
} catch {
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
seen.add(filePath);
|
|
551
|
+
const mtimeMs = Math.floor(stat.mtimeMs);
|
|
552
|
+
const row = this.stmts.getTrack.get(filePath);
|
|
553
|
+
if (row && row.mtime_ms === mtimeMs && row.size === stat.size) {
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
changed.push({ path: filePath, mtimeMs, size: stat.size });
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const total = files.length;
|
|
560
|
+
this.emit('scanProgress', 0, total);
|
|
561
|
+
|
|
562
|
+
// Parse pass: bounded concurrency, batched write transactions.
|
|
563
|
+
const upsertTx = this.db.transaction((rows) => {
|
|
564
|
+
for (const row of rows) this.stmts.upsertTrack.run(row);
|
|
565
|
+
});
|
|
566
|
+
const now = Date.now();
|
|
567
|
+
let batch = [];
|
|
568
|
+
let done = 0;
|
|
569
|
+
let failed = 0;
|
|
570
|
+
let next = 0;
|
|
571
|
+
const worker = async () => {
|
|
572
|
+
while (next < changed.length) {
|
|
573
|
+
if (!this.db.open) return; // closed mid-scan (quit) — stop quietly
|
|
574
|
+
const file = changed[next++];
|
|
575
|
+
// A throwing parse must not reject Promise.all mid-scan; index
|
|
576
|
+
// the file with filename-bootstrapped tags and count it.
|
|
577
|
+
let meta;
|
|
578
|
+
try {
|
|
579
|
+
meta = await this.parse(file.path);
|
|
580
|
+
} catch (error) {
|
|
581
|
+
DBG(`scan parse error: ${file.path}: ${error?.message ?? error}`);
|
|
582
|
+
meta = fallbackMetadata(file.path);
|
|
583
|
+
failed++;
|
|
584
|
+
}
|
|
585
|
+
batch.push({
|
|
586
|
+
path: file.path,
|
|
587
|
+
title: meta.title,
|
|
588
|
+
artist: meta.artist,
|
|
589
|
+
albumArtist: meta.albumArtist,
|
|
590
|
+
album: meta.album,
|
|
591
|
+
genre: meta.genre,
|
|
592
|
+
year: Number(meta.year) || null,
|
|
593
|
+
track: meta.trackNumber,
|
|
594
|
+
duration: meta.duration,
|
|
595
|
+
mtimeMs: file.mtimeMs,
|
|
596
|
+
size: file.size,
|
|
597
|
+
hasArt:
|
|
598
|
+
Array.isArray(meta.images) && meta.images.length > 0 ? 1 : 0,
|
|
599
|
+
addedAt: now,
|
|
600
|
+
});
|
|
601
|
+
if (batch.length >= SCAN_BATCH) {
|
|
602
|
+
upsertTx(batch);
|
|
603
|
+
batch = [];
|
|
604
|
+
}
|
|
605
|
+
done++;
|
|
606
|
+
if (done % SCAN_PROGRESS_STEP === 0 || done === changed.length) {
|
|
607
|
+
this.emit('scanProgress', done, total);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
await Promise.all(
|
|
612
|
+
Array.from(
|
|
613
|
+
{ length: Math.min(SCAN_CONCURRENCY, changed.length) },
|
|
614
|
+
worker,
|
|
615
|
+
),
|
|
616
|
+
);
|
|
617
|
+
if (batch.length > 0) upsertTx(batch);
|
|
618
|
+
|
|
619
|
+
// Prune rows for files no longer under any root (full scans only —
|
|
620
|
+
// v1 always scans every configured dir). Single DELETE — atomic.
|
|
621
|
+
this.stmts.pruneMissing.run(JSON.stringify([...seen]));
|
|
622
|
+
|
|
623
|
+
this.emit('scanDone', { total, indexed: this.count(), failed });
|
|
624
|
+
this.emit('updated');
|
|
625
|
+
} finally {
|
|
626
|
+
this.scanning = false;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async #walk(dir, out) {
|
|
631
|
+
let entries;
|
|
632
|
+
try {
|
|
633
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
634
|
+
} catch {
|
|
635
|
+
return; // unreadable/missing root — skip, don't fail the scan
|
|
636
|
+
}
|
|
637
|
+
let walked = 0;
|
|
638
|
+
for (const entry of entries) {
|
|
639
|
+
const fullPath = path.join(dir, entry.name);
|
|
640
|
+
if (entry.isDirectory()) {
|
|
641
|
+
await this.#walk(fullPath, out);
|
|
642
|
+
} else if (entry.isFile() && isAudioFile(entry.name)) {
|
|
643
|
+
out.push(fullPath);
|
|
644
|
+
}
|
|
645
|
+
if (++walked % SCAN_YIELD === 0) await nextTask();
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
count() {
|
|
650
|
+
return this.db.prepare('SELECT COUNT(*) AS n FROM tracks').get().n;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// Metadata for playlist export labels (issues/028): one row per known
|
|
654
|
+
// path, nothing for unscanned files — the caller falls back to the
|
|
655
|
+
// filename bootstrap. Path is the primary key, so per-path gets are
|
|
656
|
+
// index lookups; hundreds of entries stay sub-millisecond.
|
|
657
|
+
trackInfoByPaths(paths) {
|
|
658
|
+
const byPath = new Map();
|
|
659
|
+
for (const trackPath of paths) {
|
|
660
|
+
const row = this.stmts.trackInfo.get(trackPath);
|
|
661
|
+
if (row) byPath.set(row.path, row);
|
|
662
|
+
}
|
|
663
|
+
return byPath;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Indexed tracks under a scan root. Prefix includes a trailing separator
|
|
667
|
+
// (unless the root already ends with one, e.g. '/') so '/music' does not
|
|
668
|
+
// count tracks indexed under '/music2'; LIKE metacharacters in the path
|
|
669
|
+
// are escaped against the ESCAPE '\' clause.
|
|
670
|
+
countForRoot(dir) {
|
|
671
|
+
const escaped = dir.replace(/[\\%_]/g, (char) => `\\${char}`);
|
|
672
|
+
const prefix = dir.endsWith(path.sep) ? escaped : `${escaped}${path.sep}`;
|
|
673
|
+
return this.stmts.countForRoot.get(`${prefix}%`).n;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
close() {
|
|
677
|
+
if (this.db.open) this.db.close();
|
|
678
|
+
}
|
|
679
|
+
}
|