Filter playlists, group artist tracks and improve playback and cache controls
Build and Publish / Build and Publish Docker Image (push) Successful in 2m46s
Build and Publish / Build and Publish Docker Image (push) Successful in 2m46s
This commit is contained in:
1 parent
2b8dad2139
commit
656466b176
41 files changed
+2156
-1130
No files matched your search
+31
-2
@@ -303,6 +303,30 @@ translations! {
|
||||
player_offline_used: "Audio and artwork" , "Аудио и обложки";
|
||||
player_offline_limit: "Cache limit" , "Лимит кеша";
|
||||
player_offline_saved: "Saved music" , "Сохранённая музыка";
|
||||
player_offline_open_cache: "Open cache" , "Открыть кеш";
|
||||
player_offline_back_settings: "Back to settings" , "Назад к настройкам";
|
||||
player_offline_cache_search: "Search titles and artists" , "Поиск по трекам и артистам";
|
||||
player_offline_sort: "Sort by" , "Сортировка";
|
||||
player_offline_download_date: "Download date" , "Дата загрузки";
|
||||
player_offline_last_played: "Last played" , "Последнее прослушивание";
|
||||
player_offline_play_count: "Plays" , "Прослушивания";
|
||||
player_offline_bitrate: "Bitrate" , "Битрейт";
|
||||
player_offline_ascending: "Ascending order" , "По возрастанию";
|
||||
player_offline_descending: "Descending order" , "По убыванию";
|
||||
player_offline_manage_storage: "Manage storage" , "Освободить место";
|
||||
player_offline_cleanup_scope: "Date filters apply to all saved music, including tracks outside the search results." , "Очистка по дате охватывает все сохранённые треки, включая те, которые не попали в результаты поиска.";
|
||||
player_offline_remove_by: "Removal criterion" , "Критерий удаления";
|
||||
player_offline_downloaded_before: "Downloaded before" , "Загружены до";
|
||||
player_offline_played_before: "Last played before" , "Последнее прослушивание до";
|
||||
player_offline_never_cleanup: "For tracks with no plays, the download date is used." , "Для треков без прослушиваний используется дата загрузки.";
|
||||
player_offline_cutoff: "Cutoff date" , "Дата отсечения";
|
||||
player_offline_preview_removal: "Preview removal" , "Проверить перед удалением";
|
||||
player_offline_will_free: "Space to free" , "Освободится";
|
||||
player_offline_remove_confirm: "Remove saved music?" , "Удалить сохранённую музыку?";
|
||||
player_offline_saved_all: "All saved tracks on this device" , "Все сохранённые треки на этом устройстве";
|
||||
player_offline_pages: "Saved music pages" , "Страницы сохранённой музыки";
|
||||
player_offline_previous_page: "Previous page" , "Предыдущая страница";
|
||||
player_offline_next_page: "Next page" , "Следующая страница";
|
||||
player_offline_empty: "No music saved on this device yet." , "На этом устройстве пока нет сохранённой музыки.";
|
||||
player_offline_empty_uploads: "None of your uploads are saved on this device." , "На этом устройстве пока нет треков из ваших загрузок.";
|
||||
player_offline_empty_followed: "No music by your followed artists is saved on this device." , "На этом устройстве пока нет музыки артистов, на которых вы подписаны.";
|
||||
@@ -310,8 +334,6 @@ translations! {
|
||||
player_offline_page_missing: "This page is unavailable offline." , "Эта страница недоступна в офлайн-режиме.";
|
||||
player_offline_open_catalog: "Open saved catalog" , "Открыть сохранённый каталог";
|
||||
player_offline_clear: "Clear cache" , "Очистить кеш";
|
||||
player_offline_show_more: "Show more tracks" , "Показать ещё треки";
|
||||
player_offline_confirm_clear: "Remove all saved music from this device?" , "Удалить всю сохранённую музыку с этого устройства?";
|
||||
player_offline_remove: "Remove from this device" , "Удалить с устройства";
|
||||
player_offline_save: "Save for offline listening" , "Сохранить для офлайна";
|
||||
player_offline_available: "Saved on this device" , "Сохранено на устройстве";
|
||||
@@ -348,6 +370,9 @@ translations! {
|
||||
player_likes_playlist: "Liked songs" , "Мне нравится";
|
||||
player_listened: "listened" , "прослушано";
|
||||
player_search_placeholder: "Search artists, releases, tracks, podcasts..." , "Поиск артистов, релизов, треков, подкастов...";
|
||||
player_playlist_search: "Search this playlist" , "Поиск по плейлисту";
|
||||
player_clear_playlist_search: "Clear playlist search" , "Очистить поиск по плейлисту";
|
||||
player_playlist_no_matches: "No matching tracks" , "Подходящих треков нет";
|
||||
player_search_similar_to: "Search similar to:" , "Поиск похожих на:";
|
||||
player_find_similar: "Find similar tracks" , "Найти похожие треки";
|
||||
player_similarity_failed: "Similarity search failed" , "Не удалось найти похожие треки";
|
||||
@@ -446,6 +471,10 @@ translations! {
|
||||
player_queue_empty: "Queue is empty" , "Очередь пуста";
|
||||
player_shuffle: "Shuffle" , "Перемешать";
|
||||
player_repeat: "Repeat" , "Повтор";
|
||||
player_pause: "Pause" , "Пауза";
|
||||
player_seek: "Playback position" , "Позиция воспроизведения";
|
||||
player_mute: "Mute" , "Выключить звук";
|
||||
player_unmute: "Unmute" , "Включить звук";
|
||||
player_volume: "Volume" , "Громкость";
|
||||
player_appears_on: "Appears on" , "Участвует в";
|
||||
player_top_tracks: "Popular tracks" , "Популярные треки";
|
||||
|
||||
@@ -8,6 +8,13 @@ async fn artist_credits_include_visible_features_and_count_each_track_once() ->
|
||||
.max_connections(1)
|
||||
.connect(&std::env::var("FURU_ARTIST_TEST_DATABASE_URL")?)
|
||||
.await?;
|
||||
let schema = format!("artist_{}", uuid::Uuid::new_v4().simple());
|
||||
sqlx::raw_sql(&format!(
|
||||
"BEGIN; CREATE SCHEMA {schema}; SET LOCAL search_path TO {schema}, public;
|
||||
CREATE COLLATION furumusic_unicode (provider=icu, locale='und', deterministic=true);"
|
||||
))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::raw_sql(
|
||||
r#"
|
||||
CREATE TEMP TABLE furumusic__artist (
|
||||
@@ -82,5 +89,21 @@ async fn artist_credits_include_visible_features_and_count_each_track_once() ->
|
||||
let cards = helpers::artist_cards(&pool, rows.into(), "medium").await?;
|
||||
assert_eq!((cards[0].release_count, cards[0].track_count), (0, 1));
|
||||
assert_eq!((cards[1].release_count, cards[1].track_count), (1, 3));
|
||||
|
||||
// Rank titles by their best recording, retaining every version even below the 50-title cutoff.
|
||||
sqlx::raw_sql(
|
||||
r#"UPDATE furumusic__track SET title = 'За дверью' WHERE id = 20;
|
||||
INSERT INTO furumusic__track (id,title,release_id,lastfm_rating,lastfm_playcount) VALUES
|
||||
(100,'ЗА ДВЕРЬЮ',10,90,100), (101,' за Дверью ',10,90,120);
|
||||
INSERT INTO furumusic__track (id,title,release_id,lastfm_rating)
|
||||
SELECT id, 'Song ' || id, 10, 10 FROM generate_series(1000,1049) id;"#,
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
let popular = load_artist_detail(&pool, 2).await?.unwrap().top_tracks;
|
||||
let ids: Vec<_> = popular.iter().map(|track| track.id).collect();
|
||||
let expected: Vec<_> = [101, 100, 20].into_iter().chain(1000..1049).collect();
|
||||
assert_eq!(ids, expected);
|
||||
sqlx::query("ROLLBACK").execute(&pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
+27
-29
@@ -4087,28 +4087,18 @@ async fn load_artist_detail(
|
||||
let featured_tracks = build_track_items(featured_rows, pool).await?;
|
||||
|
||||
let top_tracks = sqlx::query_as::<_, PlaylistTrackRow>(
|
||||
r#"SELECT * FROM (
|
||||
SELECT DISTINCT ON (lower(t.title::text))
|
||||
NULL::bigint AS playlist_track_id,
|
||||
t.id, t.title::text as title, t.track_number, t.disc_number,
|
||||
t.duration_seconds, t.cover_file_id,
|
||||
r.cover_file_id as release_cover_file_id,
|
||||
r.id as release_id,
|
||||
r.title::text as release_title,
|
||||
r.year as release_year,
|
||||
COALESCE(mf.uploader_name, 'UFO')::text AS uploader_name,
|
||||
mf.audio_format,
|
||||
mf.audio_bitrate,
|
||||
mf.audio_sample_rate,
|
||||
mf.audio_bit_depth,
|
||||
mf.file_size_bytes,
|
||||
t.lastfm_listeners,
|
||||
t.lastfm_playcount,
|
||||
t.lastfm_rating,
|
||||
t.lastfm_updated_at
|
||||
r#"WITH ranked AS (
|
||||
SELECT t.id,
|
||||
lower(trim(regexp_replace(normalize(t.title::text, NFKC) COLLATE furumusic_unicode,
|
||||
'[[:space:]]+', ' ', 'g'))) AS title_key,
|
||||
row_number() OVER (
|
||||
ORDER BY COALESCE(t.lastfm_rating, 0) DESC,
|
||||
COALESCE(t.lastfm_playcount, 0) DESC,
|
||||
COALESCE(t.lastfm_listeners, 0) DESC,
|
||||
r.year DESC NULLS LAST, t.track_number NULLS LAST, t.id
|
||||
) AS rank
|
||||
FROM furumusic__track t
|
||||
JOIN furumusic__release r ON r.id = t.release_id
|
||||
LEFT JOIN furumusic__media_file mf ON mf.id = t.audio_file_id
|
||||
WHERE t.is_hidden = false
|
||||
AND r.is_hidden = false
|
||||
AND t.id IN (
|
||||
@@ -4119,15 +4109,23 @@ async fn load_artist_detail(
|
||||
JOIN furumusic__track rt ON rt.release_id = ra.release_id
|
||||
WHERE ra.artist_id = $1
|
||||
)
|
||||
ORDER BY lower(t.title::text), COALESCE(t.lastfm_rating, 0) DESC
|
||||
) deduped
|
||||
ORDER BY COALESCE(lastfm_rating, 0) DESC,
|
||||
COALESCE(lastfm_playcount, 0) DESC,
|
||||
COALESCE(lastfm_listeners, 0) DESC,
|
||||
release_year DESC NULLS LAST,
|
||||
track_number NULLS LAST,
|
||||
id
|
||||
LIMIT 50"#,
|
||||
), top_titles AS (
|
||||
SELECT title_key, min(rank) AS first_rank
|
||||
FROM ranked GROUP BY title_key ORDER BY first_rank LIMIT 50
|
||||
)
|
||||
SELECT NULL::bigint AS playlist_track_id,
|
||||
t.id, t.title::text AS title, t.track_number, t.disc_number,
|
||||
t.duration_seconds, t.cover_file_id, r.cover_file_id AS release_cover_file_id,
|
||||
r.id AS release_id, r.title::text AS release_title, r.year AS release_year,
|
||||
COALESCE(mf.uploader_name, 'UFO')::text AS uploader_name,
|
||||
mf.audio_format, mf.audio_bitrate, mf.audio_sample_rate, mf.audio_bit_depth, mf.file_size_bytes,
|
||||
t.lastfm_listeners, t.lastfm_playcount, t.lastfm_rating, t.lastfm_updated_at
|
||||
FROM top_titles
|
||||
JOIN ranked USING (title_key)
|
||||
JOIN furumusic__track t ON t.id = ranked.id
|
||||
JOIN furumusic__release r ON r.id = t.release_id
|
||||
LEFT JOIN furumusic__media_file mf ON mf.id = t.audio_file_id
|
||||
ORDER BY top_titles.first_rank, ranked.rank"#,
|
||||
)
|
||||
.bind(artist_id)
|
||||
.fetch_all(pool)
|
||||
|
||||
@@ -53,6 +53,8 @@
|
||||
return {id, content_id:t.content_id, title:t.title, artists, featured_artists:featured,
|
||||
release_id:releaseId, release_title:releaseTitle, release_year:year, track_number:t.track_number ?? null,
|
||||
disc_number:t.disc_number ?? null, duration_seconds:t.duration_seconds || 0, cover_url:coverKey(t.cover_url),
|
||||
audio_format:t.audio_format ?? metadata.audio_format, audio_bitrate:t.audio_bitrate ?? metadata.audio_bitrate,
|
||||
audio_sample_rate:t.audio_sample_rate ?? metadata.audio_sample_rate, audio_bit_depth:t.audio_bit_depth ?? metadata.audio_bit_depth,
|
||||
uploader_name:'Federation', offline_remote:true, has_lyrics:false, stream_url:BASE + 'stream/' + id,
|
||||
offline_release:{artists:releaseArtists,release_type:key.release_type || ''}};
|
||||
}
|
||||
@@ -175,9 +177,15 @@
|
||||
return {tracks, bytes:bytes || 0};
|
||||
}
|
||||
async list() {
|
||||
const [rows, plays] = await Promise.all([this.all('tracks'), this.all('plays')]);
|
||||
const tx = (await this.db()).transaction(['tracks','plays','files']);
|
||||
const files = tx.objectStore('files');
|
||||
const [rows, plays, fileKeys, fileInfo] = await Promise.all([
|
||||
requests(tx.objectStore('tracks').getAll()), requests(tx.objectStore('plays').getAll()),
|
||||
requests(files.getAllKeys()), requests(files.getAll()),
|
||||
]);
|
||||
const mime = new Map(fileKeys.map((key,i) => [key, fileInfo[i].mime]));
|
||||
const counts = new Map(plays.map(p => [p.id, p]));
|
||||
return rows.map(r => ({...r.track, bytes:r.bytes, downloaded_at:r.downloaded_at,
|
||||
return rows.map(r => ({...r.track, bytes:r.bytes, audio_mime:mime.get(r.file), downloaded_at:r.downloaded_at,
|
||||
last_played_at:counts.get(r.id)?.last_played_at || null, play_count:counts.get(r.id)?.play_count || 0}));
|
||||
}
|
||||
async has(value) {
|
||||
@@ -406,16 +414,93 @@
|
||||
if (!activeNames.has(name)) await dir.removeEntry(name);
|
||||
}
|
||||
}
|
||||
async remove(trackId) {
|
||||
const id = OfflineCatalog.trackId(trackId);
|
||||
if (!id) return;
|
||||
await navigator.locks.request(this.name, async () => {
|
||||
await this.write(['tracks','plays','pending','lyrics','meta'], get => {
|
||||
get('tracks').delete(id); get('plays').delete(id); get('pending').delete(id); get('lyrics').delete(id);
|
||||
get('meta').put(crypto.randomUUID(),'revision');
|
||||
});
|
||||
await this.prune(await this.directory());
|
||||
previewCleanup(criteria = {}) {
|
||||
return this._cleanup(criteria, null);
|
||||
}
|
||||
removeMany(ids, criteria = {}) {
|
||||
if (!Array.isArray(ids)) throw new TypeError('Expected selected track IDs');
|
||||
const selected = new Set(ids.map(trackId).filter(Boolean));
|
||||
return navigator.locks.request(this.name, () => this._cleanup(criteria, selected));
|
||||
}
|
||||
async remove(value) {
|
||||
const id = trackId(value);
|
||||
if (id) await navigator.locks.request(this.name, () => this._cleanup({}, new Set([id]), true));
|
||||
}
|
||||
async _cleanup(criteria, selected, cancelUnstored = false) {
|
||||
for (const [field, cutoff] of Object.entries(criteria)) {
|
||||
if (!['downloadedBefore','lastPlayedBefore'].includes(field) || !Number.isFinite(cutoff))
|
||||
throw new TypeError('Invalid offline cleanup cutoff');
|
||||
}
|
||||
const deleting = selected !== null;
|
||||
const db = await this.db();
|
||||
const tx = db.transaction(deleting ? stores : ['tracks','plays','files','assets'], deleting ? 'readwrite' : 'readonly');
|
||||
const get = name => tx.objectStore(name);
|
||||
const finished = new Promise((resolve,reject) => {
|
||||
tx.oncomplete = resolve;
|
||||
tx.onabort = () => reject(tx.error || new DOMException('Cleanup aborted','AbortError'));
|
||||
});
|
||||
let ids, bytes, discardedFiles;
|
||||
try {
|
||||
const [rows, activity, used] = await Promise.all([
|
||||
requests(get('tracks').getAll()), requests(get('plays').getAll()),
|
||||
deleting ? requests(get('meta').get('bytes')) : 0,
|
||||
]);
|
||||
const lastPlay = new Map(activity.map(p => [p.id, p.last_played_at]));
|
||||
const retainedFiles = new Set(), retainedAssets = new Set(), retainedReleases = new Set();
|
||||
const files = new Set(), assets = new Set(), releases = new Set();
|
||||
ids = [];
|
||||
for (const row of rows) {
|
||||
const lastUsed = lastPlay.get(row.id) ?? row.downloaded_at;
|
||||
const matches = (!deleting || selected.has(row.id))
|
||||
&& (criteria.downloadedBefore === undefined || row.downloaded_at < criteria.downloadedBefore)
|
||||
&& (criteria.lastPlayedBefore === undefined || lastUsed < criteria.lastPlayedBefore);
|
||||
if (matches) ids.push(row.id);
|
||||
(matches ? files : retainedFiles).add(row.file);
|
||||
(matches ? releases : retainedReleases).add(row.track.release_id);
|
||||
for (const key of row.assets) (matches ? assets : retainedAssets).add(key);
|
||||
}
|
||||
const fileKeys = [...files].filter(key => !retainedFiles.has(key));
|
||||
const assetKeys = [...assets].filter(key => !retainedAssets.has(key));
|
||||
// OPFS holds the audio. These reads access file descriptors and Blob sizes only.
|
||||
const [fileInfo, artwork] = await Promise.all([
|
||||
Promise.all(fileKeys.map(key => requests(get('files').get(key)))),
|
||||
Promise.all(assetKeys.map(key => requests(get('assets').get(key)))),
|
||||
]);
|
||||
discardedFiles = fileInfo.filter(Boolean);
|
||||
bytes = discardedFiles.reduce((n,f) => n + f.bytes, 0) + artwork.reduce((n,a) => n + (a?.size || 0), 0);
|
||||
if (deleting) {
|
||||
// Reading plays and checking cutoffs in this same write transaction protects a newly played track.
|
||||
for (const id of cancelUnstored ? selected : ids) {
|
||||
for (const name of ['tracks','plays','pending','lyrics']) get(name).delete(id);
|
||||
}
|
||||
for (const key of fileKeys) get('files').delete(key);
|
||||
for (const key of assetKeys) get('assets').delete(key);
|
||||
for (const id of releases) if (!retainedReleases.has(id)) get('meta').delete('release/'+id);
|
||||
if (ids.length) {
|
||||
get('meta').put(Math.max(0,(used || 0) - bytes),'bytes');
|
||||
get('meta').put(crypto.randomUUID(),'revision');
|
||||
}
|
||||
}
|
||||
await finished;
|
||||
} catch (error) {
|
||||
try { tx.abort(); } catch { /* already completed or aborted */ }
|
||||
await finished.catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
// Commit the index first so an interrupted removal can only leave an unreferenced file.
|
||||
if (deleting && discardedFiles.length) {
|
||||
try {
|
||||
const dir = await this.directory();
|
||||
for (const file of discardedFiles) {
|
||||
try { await dir.removeEntry(file.name); }
|
||||
catch (error) { if (error.name !== 'NotFoundError') throw error; }
|
||||
}
|
||||
} catch (error) {
|
||||
this._reconciled = false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return {ids, count:ids.length, bytes};
|
||||
}
|
||||
async clear() {
|
||||
await navigator.locks.request(this.name, async () => {
|
||||
|
||||
+10
-4
@@ -18,7 +18,7 @@ fn episode_routes_accept_encoded_colons_and_reject_invalid_ids() {
|
||||
|
||||
#[test]
|
||||
fn renders_podcast_navigation_and_views() {
|
||||
let html = crate::player::PlayerPageTemplate {
|
||||
let player = crate::player::PlayerPageTemplate {
|
||||
t: crate::i18n::Translations::for_lang(crate::i18n::Lang::En),
|
||||
guest: false,
|
||||
account_id: 1,
|
||||
@@ -26,9 +26,8 @@ fn renders_podcast_navigation_and_views() {
|
||||
downloads_enabled: true,
|
||||
torrent_downloads_enabled: true,
|
||||
youtube_downloads_enabled: true,
|
||||
}
|
||||
.render()
|
||||
.unwrap();
|
||||
};
|
||||
let html = player.render().unwrap();
|
||||
assert_eq!(
|
||||
html.matches("href=\"#podcasts\" class=\"podcast-nav\"").count(),
|
||||
2
|
||||
@@ -41,6 +40,13 @@ fn renders_podcast_navigation_and_views() {
|
||||
);
|
||||
if std::env::var_os("FURU_PODCAST_RENDER_FIXTURE").is_some() {
|
||||
std::fs::write("target/podcast-player-fixture.html", html).unwrap();
|
||||
let shared = crate::player::PlayerPageTemplate {
|
||||
guest: true,
|
||||
account_id: 0,
|
||||
share_token: "playlist-filter-test".into(),
|
||||
..player
|
||||
};
|
||||
std::fs::write("target/shared-player-fixture.html", shared.render().unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user