Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b8dad2139 |
No files matched your search
@@ -10,6 +10,16 @@
|
||||
- Desktop/mobile lyrics view following playback, individual track previews,
|
||||
availability icons, and local version editing in the admin track editor.
|
||||
|
||||
## v0.16.0 — 2026-11-24
|
||||
|
||||
- Added opt-in offline listening to the web player. Starting a music track saves
|
||||
the recording on this device with its catalog entries, available artwork and lyrics.
|
||||
Saved music can be searched, played and browsed through artist and release pages.
|
||||
- The account menu shows cache usage and switches the player to local playback.
|
||||
Server outages activate offline listening automatically until the instance returns.
|
||||
- Cache management includes individual removal and a logarithmic size limit from
|
||||
100 MB to 512 GB, initially 3 GB. Downloads pause when the cache fills.
|
||||
|
||||
## v0.15.3 — 2026-11-24
|
||||
|
||||
- Listening by day can display a calendar heatmap shaded by daily play count.
|
||||
|
||||
Generated
+1
-1
@@ -2062,7 +2062,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
|
||||
|
||||
[[package]]
|
||||
name = "furumusic"
|
||||
version = "0.15.3"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "furumusic"
|
||||
version = "0.15.3"
|
||||
version = "0.16.0"
|
||||
edition = "2024"
|
||||
description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL"
|
||||
|
||||
|
||||
+19
-5
@@ -74,15 +74,29 @@ fn authenticated_user_from_user(user: User) -> Option<AuthenticatedUser> {
|
||||
|
||||
/// Return the signed-in identity, including an account awaiting approval.
|
||||
pub async fn get_session_identity(session: &Session, db: &Database) -> Option<User> {
|
||||
let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??;
|
||||
User::get_by_id(db, user_id).await.ok()?
|
||||
checked_session_identity(session, db).await.ok().flatten()
|
||||
}
|
||||
|
||||
/// Offline-capable routes must distinguish an expired login from a storage outage.
|
||||
pub(crate) async fn checked_session_identity(
|
||||
session: &Session,
|
||||
db: &Database,
|
||||
) -> cot::Result<Option<User>> {
|
||||
let Some(user_id) = session
|
||||
.get::<i64>(SESSION_USER_ID)
|
||||
.await
|
||||
.map_err(cot::Error::internal)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(User::get_by_id(db, user_id).await?)
|
||||
}
|
||||
|
||||
/// Return a session user only when access to the instance has been granted.
|
||||
pub async fn get_session_user(session: &Session, db: &Database) -> Option<AuthenticatedUser> {
|
||||
let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??;
|
||||
let user = User::get_by_id(db, user_id).await.ok()??;
|
||||
authenticated_user_from_user(user)
|
||||
get_session_identity(session, db)
|
||||
.await
|
||||
.and_then(authenticated_user_from_user)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -288,6 +288,35 @@ translations! {
|
||||
player_my_playlists: "My playlists" , "Мои плейлисты";
|
||||
player_pinned: "Pinned" , "Закреплено";
|
||||
player_account_menu: "Account menu" , "Меню аккаунта";
|
||||
player_offline_listening: "Offline listening" , "Офлайн-прослушивание";
|
||||
player_offline_disabled: "Offline listening is off" , "Офлайн-режим выключен";
|
||||
player_offline_online: "Online" , "Онлайн";
|
||||
player_offline_manual: "Offline" , "Офлайн";
|
||||
player_offline_auto: "Offline · automatic" , "Офлайн · автоматически";
|
||||
player_offline_manage: "Manage" , "Управление";
|
||||
player_offline_manage_label: "Manage offline music" , "Управление офлайн-музыкой";
|
||||
player_offline_cache_only: "Use saved music only" , "Только сохранённая музыка";
|
||||
player_offline_enable: "Save music on this device" , "Сохранять музыку на устройстве";
|
||||
player_offline_preparing: "Preparing offline listening…" , "Готовим плеер для офлайн-прослушивания…";
|
||||
player_offline_hint: "Played tracks are saved automatically. You can also save a track from its menu." , "Прослушанные треки сохраняются автоматически. Трек также можно сохранить через его меню.";
|
||||
player_offline_unsupported: "This browser cannot store music offline." , "Этот браузер не поддерживает сохранение музыки офлайн.";
|
||||
player_offline_used: "Audio and artwork" , "Аудио и обложки";
|
||||
player_offline_limit: "Cache limit" , "Лимит кеша";
|
||||
player_offline_saved: "Saved music" , "Сохранённая музыка";
|
||||
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." , "На этом устройстве пока нет музыки артистов, на которых вы подписаны.";
|
||||
player_offline_start: "Play a track online to add it to your offline library." , "Включите трек онлайн, чтобы сохранить его для прослушивания офлайн.";
|
||||
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" , "Сохранено на устройстве";
|
||||
player_offline_saving: "Saving music…" , "Сохраняется музыка…";
|
||||
player_offline_devices: "Devices are unavailable offline." , "Устройства недоступны в офлайн-режиме.";
|
||||
player_featured_only_artists: "Featured only" , "Только фиты";
|
||||
player_release: "Release" , "Релиз";
|
||||
player_album_cover: "Album cover" , "Обложка альбома";
|
||||
|
||||
+26
-5
@@ -14,6 +14,7 @@ mod lyrics;
|
||||
mod media_paths;
|
||||
mod metrics;
|
||||
mod music;
|
||||
mod offline;
|
||||
mod oidc;
|
||||
mod player;
|
||||
mod podcasts;
|
||||
@@ -85,18 +86,28 @@ async fn render_player(
|
||||
i18n: I18n,
|
||||
share_token: String,
|
||||
) -> cot::Result<cot::response::Response> {
|
||||
let guest = auth::get_session_user(&session, &db).await.is_none();
|
||||
let identity = auth::checked_session_identity(&session, &db).await?;
|
||||
let user = identity.as_ref().filter(|user| user.is_active());
|
||||
let guest = user.is_none();
|
||||
if guest && share_token.is_empty() {
|
||||
if auth::get_session_identity(&session, &db).await.is_some() {
|
||||
return Html::new(PendingTemplate { t: i18n.t }.render()?).into_response();
|
||||
if identity.is_some() {
|
||||
let mut response = Html::new(PendingTemplate { t: i18n.t }.render()?).into_response()?;
|
||||
offline::identify(&mut response, 0);
|
||||
return Ok(response);
|
||||
}
|
||||
return Ok(auth::redirect("/login"));
|
||||
}
|
||||
let (config, _) = AppConfig::load_with_db(&db).await;
|
||||
Html::new(
|
||||
let account_id = user.map_or(0, User::id_val);
|
||||
if !guest {
|
||||
metrics::record_active_user(account_id);
|
||||
}
|
||||
let is_member_shell = !guest && share_token.is_empty();
|
||||
let mut response = Html::new(
|
||||
player::PlayerPageTemplate {
|
||||
t: i18n.t,
|
||||
guest,
|
||||
account_id,
|
||||
share_token,
|
||||
downloads_enabled: !guest && config.downloads_enabled,
|
||||
torrent_downloads_enabled: !guest
|
||||
@@ -108,7 +119,12 @@ async fn render_player(
|
||||
}
|
||||
.render()?,
|
||||
)
|
||||
.into_response()
|
||||
.into_response()?;
|
||||
response.headers_mut().insert("Cache-Control", "private, no-store".parse().unwrap());
|
||||
if is_member_shell {
|
||||
offline::identify(&mut response, account_id);
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
#[derive(Debug, Template)]
|
||||
@@ -299,6 +315,11 @@ impl App for FuruApp {
|
||||
),
|
||||
Route::with_handler_and_name("/share/{token}", get(share_handler), "share"),
|
||||
Route::with_handler_and_name("/auth/status", get(access_status), "access_status"),
|
||||
Route::with_handler_and_name("/offline-worker.js", get(offline::worker), "offline_worker"),
|
||||
Route::with_handler_and_name("/offline-catalog.js", get(offline::catalog), "offline_catalog"),
|
||||
Route::with_handler_and_name("/offline-probe", get(offline::probe), "offline_probe"),
|
||||
Route::with_handler_and_name("/player.webmanifest", get(offline::manifest), "player_manifest"),
|
||||
Route::with_handler_and_name("/player-icon.svg", get(offline::icon), "player_icon"),
|
||||
Route::with_handler_and_name(
|
||||
"/metrics",
|
||||
get({
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use cot::Body;
|
||||
use cot::db::Database;
|
||||
use cot::http::{HeaderValue, Response, StatusCode};
|
||||
use cot::session::Session;
|
||||
|
||||
pub(crate) const CATALOG: &str = include_str!("player/offline-catalog.js");
|
||||
|
||||
fn asset(content_type: &'static str, body: &'static str) -> cot::Result<Response<Body>> {
|
||||
Ok(Response::builder()
|
||||
.header("Content-Type", content_type)
|
||||
.header("Cache-Control", "no-cache")
|
||||
.header("X-Content-Type-Options", "nosniff")
|
||||
.body(Body::fixed(body))
|
||||
.expect("valid offline asset"))
|
||||
}
|
||||
|
||||
pub(crate) fn identify(response: &mut Response<Body>, account_id: i64) {
|
||||
response.headers_mut().insert(
|
||||
"X-Furumusic-Player-Account",
|
||||
HeaderValue::from_str(&account_id.to_string()).expect("numeric account id"),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) async fn worker() -> cot::Result<Response<Body>> {
|
||||
asset(
|
||||
"text/javascript; charset=utf-8",
|
||||
include_str!("player/offline-worker.js"),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn catalog() -> cot::Result<Response<Body>> {
|
||||
asset("text/javascript; charset=utf-8", CATALOG)
|
||||
}
|
||||
|
||||
pub(crate) async fn manifest() -> cot::Result<Response<Body>> {
|
||||
asset(
|
||||
"application/manifest+json",
|
||||
include_str!("player/player.webmanifest"),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn icon() -> cot::Result<Response<Body>> {
|
||||
asset("image/svg+xml", include_str!("player/player-icon.svg"))
|
||||
}
|
||||
|
||||
pub(crate) async fn probe(session: Session, db: Database) -> cot::Result<Response<Body>> {
|
||||
let identity = crate::auth::checked_session_identity(&session, &db).await?;
|
||||
let user = identity.filter(|user| user.is_active());
|
||||
let mut response = Response::builder()
|
||||
.header("Cache-Control", "private, no-store")
|
||||
.status(if user.is_some() {
|
||||
StatusCode::NO_CONTENT
|
||||
} else {
|
||||
StatusCode::UNAUTHORIZED
|
||||
})
|
||||
.body(Body::empty())
|
||||
.expect("valid reachability response");
|
||||
identify(&mut response, user.map_or(0, |u| u.id_val()));
|
||||
Ok(response)
|
||||
}
|
||||
@@ -1669,12 +1669,23 @@ struct LastfmCallbackQuery {
|
||||
pub struct PlayerPageTemplate {
|
||||
pub t: &'static Translations,
|
||||
pub guest: bool,
|
||||
pub account_id: i64,
|
||||
pub share_token: String,
|
||||
pub downloads_enabled: bool,
|
||||
pub torrent_downloads_enabled: bool,
|
||||
pub youtube_downloads_enabled: bool,
|
||||
}
|
||||
|
||||
impl PlayerPageTemplate {
|
||||
fn alpine(&self) -> &'static str {
|
||||
include_str!("vendor/alpine-3.17.5.min.js")
|
||||
}
|
||||
|
||||
fn offline_catalog(&self) -> &'static str {
|
||||
crate::offline::CATALOG
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod page_template_tests {
|
||||
use super::*;
|
||||
@@ -1685,6 +1696,7 @@ mod page_template_tests {
|
||||
let disabled = PlayerPageTemplate {
|
||||
t: Translations::for_lang(Lang::En),
|
||||
guest: false,
|
||||
account_id: 1,
|
||||
share_token: String::new(),
|
||||
downloads_enabled: false,
|
||||
torrent_downloads_enabled: false,
|
||||
@@ -1698,6 +1710,7 @@ mod page_template_tests {
|
||||
let enabled = PlayerPageTemplate {
|
||||
t: Translations::for_lang(Lang::En),
|
||||
guest: false,
|
||||
account_id: 1,
|
||||
share_token: String::new(),
|
||||
downloads_enabled: true,
|
||||
torrent_downloads_enabled: true,
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
/* Shared by the player and its service worker. A track becomes visible only after
|
||||
* the complete OPFS file is closed and its IndexedDB transaction commits. */
|
||||
(() => {
|
||||
'use strict';
|
||||
const BASE = '/api/player/';
|
||||
const DEFAULT_LIMIT = 3_000_000_000;
|
||||
const MAX_LIMIT = 512_000_000_000;
|
||||
const stores = ['tracks', 'files', 'assets', 'meta', 'plays', 'lyrics', 'pending'];
|
||||
const requests = request => new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
const validId = value => Number.isSafeInteger(value) && value > 0;
|
||||
const positiveId = value => validId(Number(value)) ? Number(value) : null;
|
||||
// Server IDs are sequential. Keep browser-only IDs in the upper half of the safe integer range.
|
||||
const syntheticBase = 2 ** 52;
|
||||
const normalized = value => String(value || '').normalize('NFKC').trim().toLowerCase();
|
||||
const contentToken = id => typeof id === 'string' && /^b3:[a-f\d]{64}$/.test(id) ? id.slice(3) : null;
|
||||
const remoteMedia = id => BASE + 'federation/cache/' + contentToken(id);
|
||||
function trackId(value) {
|
||||
const id = value?.id ?? value;
|
||||
const token = typeof id === 'string' && id.startsWith('fed:') && contentToken(id.slice(4));
|
||||
return token ? syntheticBase + parseInt(token.slice(0,13),16) : positiveId(id);
|
||||
}
|
||||
async function metadataId(type, key) {
|
||||
const hash = new DataView(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([type,key]))));
|
||||
return syntheticBase + (hash.getUint32(0) & 0xfffff) * 2 ** 32 + hash.getUint32(4);
|
||||
}
|
||||
function preparedRemote(t) {
|
||||
return !!contentToken(t?.content_id) && t.id === 'fed:' + t.content_id &&
|
||||
t.federated_cache === true && t.stream_url === remoteMedia(t.content_id);
|
||||
}
|
||||
async function remoteDescriptor(t) {
|
||||
const metadata = t._federationTrack?.metadata || {};
|
||||
const credit = async a => {
|
||||
const name = (typeof a === 'string' ? a : a?.name) || 'Unknown artist';
|
||||
const key = normalized(a?.key?.normalized_name || name);
|
||||
const id = positiveId(a?.local_id ?? a?.id) || await metadataId('artist',key);
|
||||
return {id,name};
|
||||
};
|
||||
const primary = t.artists?.length ? t.artists : ['Unknown artist'];
|
||||
const artists = await Promise.all(primary.map(credit));
|
||||
const featured = await Promise.all((t.featured_artists || []).map(credit));
|
||||
const key = metadata.release?.key || t.release_key || {};
|
||||
const releaseTitle = t.release_title || metadata.release?.title || t.title;
|
||||
const year = t.release_year ?? key.year ?? null;
|
||||
const names = key.primary_artists?.length ? key.primary_artists : artists.map(a => a.name);
|
||||
const releaseArtists = await Promise.all(names.map(name => artists.find(a => normalized(a.name) === normalized(name)) || credit(name)));
|
||||
const releaseId = positiveId(t.release_id || metadata.release?.local_id) || await metadataId('release',[
|
||||
normalized(key.normalized_title || releaseTitle), names.map(normalized).sort(), year, key.release_type || '',
|
||||
]);
|
||||
const id = trackId(t);
|
||||
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),
|
||||
uploader_name:'Federation', offline_remote:true, has_lyrics:false, stream_url:BASE + 'stream/' + id,
|
||||
offline_release:{artists:releaseArtists,release_type:key.release_type || ''}};
|
||||
}
|
||||
const quotaError = () => new DOMException('Offline cache limit reached', 'QuotaExceededError');
|
||||
const trackMissing = () => new DOMException('Recording is no longer available', 'NotFoundError');
|
||||
const json = (data, status = 200) => Response.json(data, {status});
|
||||
const missing = () => json({error:'Unavailable offline'}, 404);
|
||||
function coverKey(url) {
|
||||
if (typeof url !== 'string') return null;
|
||||
// Serve the saved thumbnail for all resolutions of the same artwork.
|
||||
const match = url.match(/^\/api\/player\/cover\/(\d+)(?:\/(?:small|medium|large))?$/);
|
||||
if (match) return BASE + 'cover/' + match[1] + '/medium';
|
||||
return /^\/api\/player\/playlists\/\d+\/cover\?v=[a-f\d]+$/i.test(url) ? url : null;
|
||||
}
|
||||
function releaseInfo(release, track) {
|
||||
return {
|
||||
id: track.release_id, title: release?.title || track.release_title,
|
||||
year: release?.year ?? track.release_year, release_type: release?.release_type || '',
|
||||
artists: (release?.artists || track.artists || []).map(({id,name}) => ({id,name})),
|
||||
cover_url: release?.cover_url || track.cover_url,
|
||||
uploaders: (release?.uploaders || []).map(({name,track_count}) => ({name,track_count})),
|
||||
track_count: release?.tracks?.length ?? release?.track_count,
|
||||
};
|
||||
}
|
||||
function validTrack(track) {
|
||||
return track && validId(track.id) && validId(track.release_id) && !!track.title &&
|
||||
Array.isArray(track.artists) && track.stream_url === BASE + 'stream/' + track.id;
|
||||
}
|
||||
function contentKey(track) {
|
||||
return /^b3:[\da-f]{64}$/.test(track.content_id) ? track.content_id : 'track:' + track.id;
|
||||
}
|
||||
function binary(file, request, mime) {
|
||||
const headers = new Headers({'Content-Type':mime || file.type || 'application/octet-stream', 'Accept-Ranges':'bytes'});
|
||||
const range = request.headers.get('Range');
|
||||
let start = 0, end = file.size - 1;
|
||||
if (range) {
|
||||
const parts = /^bytes=(\d*)-(\d*)$/i.exec(range);
|
||||
if (parts && (parts[1] || parts[2])) {
|
||||
if (parts[1]) {
|
||||
start = Number(parts[1]);
|
||||
if (parts[2]) end = Math.min(end, Number(parts[2]));
|
||||
} else {
|
||||
start = Math.max(0, file.size - Number(parts[2]));
|
||||
}
|
||||
} else {
|
||||
start = file.size;
|
||||
}
|
||||
if (!Number.isSafeInteger(start) || start > end || start >= file.size) {
|
||||
headers.set('Content-Range', 'bytes */' + file.size);
|
||||
return new Response(null, {status:416, headers});
|
||||
}
|
||||
headers.set('Content-Range', 'bytes ' + start + '-' + end + '/' + file.size);
|
||||
}
|
||||
headers.set('Content-Length', String(end - start + 1));
|
||||
const body = request.method === 'HEAD' ? null : range ? file.slice(start, end + 1) : file;
|
||||
return new Response(body, {status:range ? 206 : 200, headers});
|
||||
}
|
||||
function summarizePlaylist(pl) {
|
||||
const {id, title, kind, is_own, is_saved, is_public, owner_name, description, cover_url, cover_urls} = pl;
|
||||
return {id, title, kind, is_own, is_saved, is_public, owner_name, description, cover_url, cover_urls};
|
||||
}
|
||||
|
||||
class OfflineCatalog {
|
||||
static trackId(value) { return trackId(value); }
|
||||
static canSave(track) {
|
||||
return !!track && !track.podcast && !track.federation_pending && (positiveId(track.id) !== null || preparedRemote(track));
|
||||
}
|
||||
constructor(account) {
|
||||
if (!/^\d+$/.test(String(account)) || !positiveId(account)) throw new TypeError('Missing offline account');
|
||||
this.name = 'furumusic-offline-v1-' + Number(account);
|
||||
this.account = Number(account);
|
||||
this._database = null;
|
||||
this._reconciled = false;
|
||||
}
|
||||
async db() {
|
||||
if (!this._database) {
|
||||
const opening = indexedDB.open(this.name, 1);
|
||||
opening.onupgradeneeded = () => {
|
||||
const db = opening.result;
|
||||
db.createObjectStore('tracks', {keyPath:'id'}).createIndex('file', 'file');
|
||||
for (const name of ['files','assets','meta','plays','lyrics']) db.createObjectStore(name);
|
||||
db.createObjectStore('pending', {keyPath:'id'}).createIndex('queued','queued');
|
||||
};
|
||||
this._database = requests(opening).then(db => {
|
||||
db.onversionchange = () => { db.close(); this._database = null; };
|
||||
return db;
|
||||
}).catch(error => { this._database = null; throw error; });
|
||||
}
|
||||
return this._database;
|
||||
}
|
||||
async read(store, key) {
|
||||
const tx = (await this.db()).transaction(store);
|
||||
return requests(tx.objectStore(store).get(key));
|
||||
}
|
||||
async all(store) {
|
||||
const tx = (await this.db()).transaction(store);
|
||||
return requests(tx.objectStore(store).getAll());
|
||||
}
|
||||
async write(names, work) {
|
||||
const tx = (await this.db()).transaction(names, 'readwrite');
|
||||
const finished = new Promise((resolve,reject) => {
|
||||
tx.oncomplete = resolve;
|
||||
tx.onabort = () => reject(tx.error || new DOMException('Database transaction aborted','AbortError'));
|
||||
});
|
||||
try {
|
||||
work(name => tx.objectStore(name));
|
||||
} catch (error) {
|
||||
tx.abort();
|
||||
await finished.catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
await finished;
|
||||
}
|
||||
async directory() {
|
||||
return (await navigator.storage.getDirectory()).getDirectoryHandle(this.name, {create:true});
|
||||
}
|
||||
async stats() {
|
||||
const tx = (await this.db()).transaction(['tracks','meta']);
|
||||
const [tracks, bytes] = await Promise.all([requests(tx.objectStore('tracks').count()), requests(tx.objectStore('meta').get('bytes'))]);
|
||||
return {tracks, bytes:bytes || 0};
|
||||
}
|
||||
async list() {
|
||||
const [rows, plays] = await Promise.all([this.all('tracks'), this.all('plays')]);
|
||||
const counts = new Map(plays.map(p => [p.id, p]));
|
||||
return rows.map(r => ({...r.track, bytes:r.bytes, 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) {
|
||||
const id = trackId(value);
|
||||
return id !== null && Boolean(await this.read('tracks',id));
|
||||
}
|
||||
async enqueue(track) {
|
||||
if (!OfflineCatalog.canSave(track)) return;
|
||||
const id = trackId(track);
|
||||
const entry = preparedRemote(track) ? await remoteDescriptor(track) : {id, content_id:track.content_id || null};
|
||||
await this.write(['pending','tracks'], get => {
|
||||
const tracks = get('tracks'), queue = get('pending');
|
||||
const existing = tracks.get(id);
|
||||
existing.onsuccess = () => {
|
||||
if (existing.result && (!track.content_id || existing.result.track.content_id === track.content_id)) return;
|
||||
const item = queue.get(id);
|
||||
item.onsuccess = () => queue.put({...entry, queued:item.result?.queued ?? Date.now()});
|
||||
};
|
||||
});
|
||||
}
|
||||
async pending() {
|
||||
const tx = (await this.db()).transaction('pending');
|
||||
return requests(tx.objectStore('pending').index('queued').getAll());
|
||||
}
|
||||
async dequeue(value) {
|
||||
const id = trackId(value);
|
||||
if (id) await this.write(['pending'], get => get('pending').delete(id));
|
||||
}
|
||||
async touch(track) {
|
||||
const id = trackId(track);
|
||||
if (!id) return;
|
||||
await this.write(['plays'], get => {
|
||||
const store = get('plays'), req = store.get(id);
|
||||
req.onsuccess = () => store.put({id, last_played_at:Date.now(), play_count:(req.result?.play_count || 0)+1}, id);
|
||||
});
|
||||
}
|
||||
async observe(raw, value) {
|
||||
const url = new URL(raw, location.origin);
|
||||
if (url.origin !== location.origin || value == null) return;
|
||||
const route = url.pathname.slice(BASE.length);
|
||||
let key = route, data;
|
||||
if (!url.pathname.startsWith(BASE)) return;
|
||||
if (route === 'me' && Number(value.id) === this.account) data = value;
|
||||
else if (['likes','follows','pins','state'].includes(route)) data = value;
|
||||
else if (route === 'playlists' && Array.isArray(value)) data = value.map(summarizePlaylist);
|
||||
else if (/^playlists\/-?\d+$/.test(route) && Array.isArray(value.tracks)) {
|
||||
data = {...summarizePlaylist(value), members:value.tracks.map(t => ({id:t.id, content_id:t.content_id,
|
||||
playlist_track_id:t.playlist_track_id, sort_key:t.sort_key}))};
|
||||
} else if (route === 'artists' && Array.isArray(value.items)) {
|
||||
// Only the compact image references are needed to hydrate a track saved later.
|
||||
const mine = url.searchParams.get('mine') === 'true';
|
||||
return this.write(['meta'], get => {
|
||||
for (const a of value.items) {
|
||||
if (a.image_url) get('meta').put(a.image_url, 'artist-image/' + a.id);
|
||||
if (mine) get('meta').put(true, 'mine/' + a.id);
|
||||
}
|
||||
});
|
||||
} else if (/^artists\/\d+$/.test(route) && value.image_url) {
|
||||
key = 'artist-image/' + value.id;
|
||||
data = value.image_url;
|
||||
} else return;
|
||||
// In the window, snapshots may come from Alpine reactive proxies.
|
||||
const plain = JSON.parse(JSON.stringify(data));
|
||||
await this.write(['meta'], get => get('meta').put(plain, key));
|
||||
}
|
||||
async save(track, options = {}) {
|
||||
if (!OfflineCatalog.canSave(track)) throw new TypeError('This track is not available to save');
|
||||
const id = trackId(track);
|
||||
if (preparedRemote(track)) track = await remoteDescriptor(track);
|
||||
return navigator.locks.request(this.name, {signal:options.signal}, () => this._save(id, track, options));
|
||||
}
|
||||
async _save(id, input, options) {
|
||||
const {signal} = options;
|
||||
const fetcher = options.fetch || fetch;
|
||||
const limit = Math.min(MAX_LIMIT, options.limitBytes ?? DEFAULT_LIMIT);
|
||||
if (!Number.isFinite(limit) || limit <= 0) throw quotaError();
|
||||
const get = (path, init) => fetcher(path, {...init, signal, cache:'no-store', credentials:'same-origin', redirect:'error'});
|
||||
const dir = await this.directory();
|
||||
if (!this._reconciled) {
|
||||
await this.prune(dir);
|
||||
this._reconciled = true;
|
||||
}
|
||||
if (options.playlist?.tracks) await this.observe(BASE+'playlists/'+options.playlist.id,options.playlist);
|
||||
const previous = await this.read('tracks', id);
|
||||
if (previous && (!input.content_id || previous.track.content_id === input.content_id)) return this.dequeue(id);
|
||||
if (input.offline_remote && (id !== trackId('fed:'+input.content_id) || previous)) throw new Error('Conflicting offline recording ID');
|
||||
|
||||
let track = input;
|
||||
if (!validTrack(track) || !Object.hasOwn(track,'content_id') || typeof track.has_lyrics !== 'boolean') {
|
||||
const res = await get(BASE + 'tracks-by-ids', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({ids:[id]})});
|
||||
if ([404,410].includes(res.status)) throw trackMissing();
|
||||
if (!res.ok) throw new Error('Cannot load track metadata ('+res.status+')');
|
||||
track = (await res.json()).find(t => t.id === id);
|
||||
if (!track) throw trackMissing();
|
||||
}
|
||||
if (!validTrack(track)) throw new Error('Incomplete offline track metadata');
|
||||
// Strip transient player state, federated URLs and Alpine proxies.
|
||||
track = JSON.parse(JSON.stringify(track));
|
||||
const remote = track.offline_remote, remoteRelease = track.offline_release;
|
||||
delete track.offline_release;
|
||||
delete track.queued;
|
||||
const fileKey = contentKey(track);
|
||||
let file = await this.read('files', fileKey);
|
||||
const used = (await this.stats()).bytes;
|
||||
let remaining = limit - used;
|
||||
let newName;
|
||||
let addedBytes = 0;
|
||||
try {
|
||||
if (!file) {
|
||||
if (remaining <= 0 || track.file_size_bytes > remaining) throw quotaError();
|
||||
const res = await get(remote ? remoteMedia(track.content_id) : track.stream_url);
|
||||
if ([404,410].includes(res.status)) throw trackMissing();
|
||||
// Media elements often receive 206; only a complete fresh download is suitable here.
|
||||
const mime = (res.headers.get('Content-Type') || '').split(';')[0].trim();
|
||||
if (res.status !== 200 || !res.body || res.headers.has('Content-Range') || /text\/|json|xml/i.test(mime)) {
|
||||
throw new Error('Cannot download a complete audio file ('+res.status+')');
|
||||
}
|
||||
const headerLength = res.headers.get('Content-Length');
|
||||
const expected = Number(headerLength) || Number(track.file_size_bytes) || null;
|
||||
if (expected > remaining) throw quotaError();
|
||||
newName = 'audio-' + crypto.randomUUID();
|
||||
const target = await dir.getFileHandle(newName, {create:true});
|
||||
const writer = await target.createWritable();
|
||||
const reader = res.body.getReader();
|
||||
let bytes = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
signal?.throwIfAborted();
|
||||
const {value, done} = await reader.read();
|
||||
if (done) break;
|
||||
bytes += value.byteLength;
|
||||
if (bytes > remaining) throw quotaError();
|
||||
await writer.write(value);
|
||||
}
|
||||
if (!bytes || (expected && expected !== bytes)) throw new Error('Incomplete audio file');
|
||||
await writer.close();
|
||||
} catch (error) {
|
||||
await Promise.allSettled([reader.cancel(),writer.abort()]);
|
||||
throw error;
|
||||
} finally { reader.releaseLock(); }
|
||||
file = {name:newName, bytes, mime};
|
||||
addedBytes += bytes;
|
||||
remaining -= bytes;
|
||||
}
|
||||
const optional = async path => {
|
||||
try {
|
||||
const res = await get(path);
|
||||
return res.ok ? await res.json() : null;
|
||||
} catch (error) { signal?.throwIfAborted(); return null; }
|
||||
};
|
||||
const release = releaseInfo(options.release?.id === track.release_id ? options.release :
|
||||
await this.read('meta','release/'+track.release_id) || (track.release_id < syntheticBase ? await optional(BASE+'releases/'+track.release_id) : null) || remoteRelease, track);
|
||||
const lyrics = remote ? await optional(BASE+'federation/tracks/lyrics?content_id='+encodeURIComponent(track.content_id)) :
|
||||
track.has_lyrics ? await optional(BASE+'lyrics/'+id) : null;
|
||||
track.has_lyrics = Boolean(lyrics?.versions?.length);
|
||||
const artistImages = {}, imageUrls = new Set([track.cover_url, release.cover_url]);
|
||||
const credits = new Set([...track.artists,...(track.featured_artists || []),...release.artists].map(a => a.id));
|
||||
for (const credit of credits) {
|
||||
const url = await this.read('meta', 'artist-image/'+credit);
|
||||
if (url) { artistImages[credit] = url; imageUrls.add(url); }
|
||||
}
|
||||
const keys = [], assets = new Map();
|
||||
for (const url of imageUrls) {
|
||||
const key = coverKey(url);
|
||||
if (!key || keys.includes(key)) continue;
|
||||
if (!(await this.read('assets', key))) {
|
||||
if (remaining <= 0) continue;
|
||||
try {
|
||||
const res = await get(key);
|
||||
if (!res.ok || !res.headers.get('Content-Type')?.startsWith('image/')) continue;
|
||||
const blob = await res.blob();
|
||||
if (!blob.size || blob.size > remaining) continue;
|
||||
assets.set(key,blob);
|
||||
addedBytes += blob.size;
|
||||
remaining -= blob.size;
|
||||
} catch { signal?.throwIfAborted(); continue; }
|
||||
}
|
||||
keys.push(key);
|
||||
}
|
||||
if (!keys.includes(coverKey(track.cover_url))) track.cover_url = null;
|
||||
if (!keys.includes(coverKey(release.cover_url))) release.cover_url = track.cover_url;
|
||||
for (const [artist, url] of Object.entries(artistImages)) if (!keys.includes(coverKey(url))) delete artistImages[artist];
|
||||
signal?.throwIfAborted();
|
||||
const row = {id,file:fileKey,bytes:file.bytes,track,release,assets:keys,artistImages,downloaded_at:Date.now()};
|
||||
await this.write(['tracks','files','assets','meta','lyrics','pending'], getStore => {
|
||||
getStore('tracks').put(row);
|
||||
getStore('files').put(file,fileKey);
|
||||
getStore('meta').put(release,'release/'+track.release_id);
|
||||
getStore('meta').put(used + addedBytes,'bytes');
|
||||
getStore('meta').put(crypto.randomUUID(),'revision');
|
||||
if (lyrics) getStore('lyrics').put(lyrics, id);
|
||||
else getStore('lyrics').delete(id);
|
||||
getStore('pending').delete(id);
|
||||
for (const [key,blob] of assets) getStore('assets').put(blob,key);
|
||||
});
|
||||
newName = null;
|
||||
if (previous) await this.prune(dir);
|
||||
} finally {
|
||||
if (newName) await dir.removeEntry(newName).catch(() => {});
|
||||
}
|
||||
}
|
||||
async prune(dir) {
|
||||
const rows = await this.all('tracks');
|
||||
const usedFiles = new Set(rows.map(row => row.file));
|
||||
const usedAssets = new Set(rows.flatMap(row => row.assets));
|
||||
const activeNames = new Set();
|
||||
const db = await this.db();
|
||||
const tx = db.transaction(['files','assets']);
|
||||
const [fileKeys, files, assetKeys, assets] = await Promise.all([
|
||||
requests(tx.objectStore('files').getAllKeys()), requests(tx.objectStore('files').getAll()),
|
||||
requests(tx.objectStore('assets').getAllKeys()), requests(tx.objectStore('assets').getAll()),
|
||||
]);
|
||||
await this.write(['files','assets','meta'], get => {
|
||||
let bytes = 0;
|
||||
fileKeys.forEach((key,i) => {
|
||||
if (usedFiles.has(key)) { activeNames.add(files[i].name); bytes += files[i].bytes; }
|
||||
else get('files').delete(key);
|
||||
});
|
||||
assetKeys.forEach((key,i) => {
|
||||
if (usedAssets.has(key)) bytes += assets[i].size;
|
||||
else get('assets').delete(key);
|
||||
});
|
||||
get('meta').put(bytes,'bytes');
|
||||
});
|
||||
for await (const [name] of dir.entries()) {
|
||||
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());
|
||||
});
|
||||
}
|
||||
async clear() {
|
||||
await navigator.locks.request(this.name, async () => {
|
||||
await this.write(stores, get => { for (const store of stores) get(store).clear(); });
|
||||
const root = await navigator.storage.getDirectory();
|
||||
try { await root.removeEntry(this.name, {recursive:true}); }
|
||||
catch (error) { if (error.name !== 'NotFoundError') throw error; }
|
||||
});
|
||||
}
|
||||
|
||||
async catalog() {
|
||||
const revision = await this.read('meta','revision');
|
||||
if (this._catalog && this._revision === revision) return this._catalog;
|
||||
const rows = await this.all('tracks');
|
||||
const tracks = rows.map(row => row.track);
|
||||
const artists = new Map(), releases = new Map();
|
||||
for (const row of rows) {
|
||||
const t = row.track;
|
||||
const release = releases.get(t.release_id) || {...row.release, tracks:[]};
|
||||
release.tracks.push(t);
|
||||
releases.set(release.id, release);
|
||||
for (const a of [...t.artists, ...(t.featured_artists || []), ...row.release.artists]) {
|
||||
if (!validId(a?.id)) continue;
|
||||
const artist = artists.get(a.id) || {id:a.id,name:a.name,image_url:null,
|
||||
releases:new Map(), top_tracks:new Map(), featured_tracks:new Map()};
|
||||
if (row.artistImages[a.id]) artist.image_url = row.artistImages[a.id];
|
||||
if (row.release.artists.some(credit => credit.id === a.id)) artist.releases.set(release.id,release);
|
||||
if (t.artists.some(credit => credit.id === a.id)) artist.top_tracks.set(t.id,t);
|
||||
else if (t.featured_artists?.some(credit => credit.id === a.id)) artist.featured_tracks.set(t.id,t);
|
||||
artists.set(a.id,artist);
|
||||
}
|
||||
}
|
||||
for (const release of releases.values()) {
|
||||
release.tracks.sort((a,b) => (a.disc_number ?? 1)-(b.disc_number ?? 1) ||
|
||||
(a.track_number ?? Infinity)-(b.track_number ?? Infinity) || a.id-b.id);
|
||||
}
|
||||
const card = r => ({id:r.id,title:r.title,release_type:r.release_type,year:r.year,
|
||||
cover_url:r.cover_url,track_count:r.tracks.length,artists:r.artists.map(a => a.name),uploaders:r.uploaders});
|
||||
const artistCards = new Map();
|
||||
for (const artist of artists.values()) {
|
||||
artist.releases = [...artist.releases.values()].sort((a,b) => (b.year||0)-(a.year||0)).map(card);
|
||||
artist.top_tracks = [...artist.top_tracks.values()].sort((a,b) => (b.lastfm_rating||0)-(a.lastfm_rating||0));
|
||||
artist.featured_tracks = [...artist.featured_tracks.values()];
|
||||
const credited = [...artist.top_tracks,...artist.featured_tracks];
|
||||
const recorded = new Set(credited.map(contentKey));
|
||||
artist.total_track_count = recorded.size;
|
||||
artist.track_content_ids = [...new Set(credited.map(t => t.content_id).filter(Boolean))];
|
||||
artist.total_play_count = 0;
|
||||
artist.image_url ||= artist.releases.find(r => r.cover_url)?.cover_url || credited.find(t => t.cover_url)?.cover_url || null;
|
||||
artistCards.set(artist.id,{id:artist.id,name:artist.name,image_url:artist.image_url,release_count:artist.releases.length,track_count:recorded.size});
|
||||
}
|
||||
this._revision = revision;
|
||||
this._catalog = {tracks, artists, artistCards, releases, releaseCards:[...releases.values()].map(card)};
|
||||
return this._catalog;
|
||||
}
|
||||
async playlist(id, tracks) {
|
||||
const byId = new Map(tracks.map(t => [t.id,t])), byContent = new Map(tracks.map(t => [contentKey(t),t]));
|
||||
const saved = await this.read('meta','playlists/'+id);
|
||||
if (!saved && id !== -1) return null;
|
||||
let items;
|
||||
if (id === -1) {
|
||||
const likes = await this.read('meta','likes');
|
||||
const ids = likes?.track_ids;
|
||||
const allowed = new Set(ids || []);
|
||||
const seen = new Set();
|
||||
const ordered = [...(saved?.members || []).map(m => m.id), ...(ids || [])];
|
||||
items = [];
|
||||
for (const id of ordered) {
|
||||
const t = byId.get(id);
|
||||
if (!t || (ids && !allowed.has(id)) || seen.has(contentKey(t))) continue;
|
||||
seen.add(contentKey(t)); items.push(t);
|
||||
}
|
||||
} else {
|
||||
items = saved.members.flatMap(m => {
|
||||
const track = byId.get(m.id) || byContent.get(m.content_id);
|
||||
return track ? [{...track, playlist_track_id:m.playlist_track_id ?? null, sort_key:m.sort_key}] : [];
|
||||
});
|
||||
}
|
||||
const covers = [...new Set(items.map(t => t.cover_url).filter(Boolean))].slice(0,4);
|
||||
const pl = saved ? summarizePlaylist(saved) : {id,kind:'likes',title:'Likes',is_own:true};
|
||||
return {...pl, cover_urls:covers, cover_url:covers[0] || null, track_count:items.length, tracks:items};
|
||||
}
|
||||
async respond(request) {
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== location.origin || !url.pathname.startsWith(BASE)) return null;
|
||||
const path = url.pathname.slice(BASE.length);
|
||||
if (path === 'tracks-by-ids' && request.method === 'POST') {
|
||||
const {ids} = await request.json().catch(() => ({}));
|
||||
if (!Array.isArray(ids)) return json({error:'Expected track IDs'},400);
|
||||
const rows = await Promise.all(ids.slice(0,500).map(trackId).filter(Boolean).map(id => this.read('tracks',id)));
|
||||
return json(rows.filter(Boolean).map(row => row.track));
|
||||
}
|
||||
if (!['GET','HEAD'].includes(request.method)) return null;
|
||||
let m;
|
||||
if ((m = /^(?:stream\/(\d+)|federation\/cache\/([a-f\d]{64}))$/.exec(path))) {
|
||||
const key = m[1] ? (await this.read('tracks',Number(m[1])))?.file : 'b3:'+m[2];
|
||||
const file = key && await this.read('files', key);
|
||||
if (!file) return missing();
|
||||
try {
|
||||
const handle = await (await this.directory()).getFileHandle(file.name);
|
||||
return binary(await handle.getFile(),request,file.mime);
|
||||
} catch(error) {
|
||||
if (error.name === 'NotFoundError') return missing();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const art = coverKey(url.pathname + url.search);
|
||||
if (art) {
|
||||
const blob = await this.read('assets', art);
|
||||
return blob ? binary(blob,request) : missing();
|
||||
}
|
||||
if ((m = /^lyrics\/(\d+)$/.exec(path))) {
|
||||
const row = await this.read('tracks', Number(m[1]));
|
||||
return row ? json(await this.read('lyrics',row.id) || {content_id:row.track.content_id,versions:[]}) : missing();
|
||||
}
|
||||
if (path === 'federation/tracks/lyrics') {
|
||||
const id = trackId('fed:'+url.searchParams.get('content_id'));
|
||||
return json(id && await this.read('lyrics',id) || {versions:[]});
|
||||
}
|
||||
if (/^playlists\/-?\d+\/federation-tracks$/.test(path)) return json([]);
|
||||
if (['me','likes','pins','follows','state','tracks/content/like'].includes(path)) {
|
||||
const data = await this.read('meta', path);
|
||||
if (path === 'me') return data ? json(data) : json({id:this.account,name:'',role:'user',stats:{}});
|
||||
if (path === 'state') return json(data || {queue:[],current_track_id:null,position_ms:0,volume:0.7});
|
||||
if (path === 'tracks/content/like') return json({content_ids:[]});
|
||||
const catalog = await this.catalog();
|
||||
if (path === 'likes') {
|
||||
const ids = new Set(catalog.tracks.map(t => t.id));
|
||||
return json({track_ids:(data?.track_ids || []).filter(id => ids.has(id))});
|
||||
}
|
||||
if (path === 'follows') {
|
||||
const artists = (data?.artist_ids || []).map(id => catalog.artistCards.get(id)).filter(Boolean);
|
||||
return json({artist_ids:artists.map(a => a.id),artists});
|
||||
}
|
||||
const local = [];
|
||||
for (const pin of (data || [])) {
|
||||
if ((pin.kind === 'artist' && catalog.artists.has(pin.id)) ||
|
||||
(pin.kind === 'release' && catalog.releases.has(pin.id)) ||
|
||||
(pin.kind === 'playlist' && (await this.playlist(pin.id,catalog.tracks))?.tracks.length)) local.push(pin);
|
||||
}
|
||||
return json(local);
|
||||
}
|
||||
if (!/^(?:artists(?:\/\d+)?|releases\/\d+|search|playlists(?:\/-?\d+)?)$/.test(path)) return null;
|
||||
const cat = await this.catalog();
|
||||
if (path === 'artists') {
|
||||
let list = [...cat.artistCards.values()].sort((a,b) => (!a.release_count)-(!b.release_count) || a.name.localeCompare(b.name));
|
||||
if (url.searchParams.get('mine') === 'true') {
|
||||
const owned = await Promise.all(list.map(a => this.read('meta','mine/'+a.id)));
|
||||
list = list.filter((_,i) => owned[i]);
|
||||
}
|
||||
const page = positiveId(url.searchParams.get('page')) || 1;
|
||||
const per_page = Math.min(500, positiveId(url.searchParams.get('limit')) || 80);
|
||||
return json({page,per_page,total:list.length,has_more:page*per_page<list.length,items:list.slice((page-1)*per_page,page*per_page)});
|
||||
}
|
||||
if ((m = /^(artists|releases)\/(\d+)$/.exec(path))) {
|
||||
const entry = cat[m[1]].get(Number(m[2]));
|
||||
return entry ? json(entry) : missing();
|
||||
}
|
||||
if (path === 'search') {
|
||||
const q = (url.searchParams.get('q') || '').trim().toLocaleLowerCase(), limit = positiveId(url.searchParams.get('limit')) || 10;
|
||||
const scores = {artists:{},releases:{},tracks:{}};
|
||||
function search(kind, rows, text) {
|
||||
return rows.filter(row => {
|
||||
const [primary,...rest] = text(row).map(value => String(value || '').toLocaleLowerCase());
|
||||
const words = q.split(/\s+/).filter(Boolean), all = [primary,...rest].join(' ');
|
||||
if (!words.length || !words.every(word => all.includes(word))) return false;
|
||||
scores[kind][row.id] = primary === q ? 100 : primary.includes(q) ? 80 : 50;
|
||||
return true;
|
||||
}).sort((a,b) => scores[kind][b.id]-scores[kind][a.id]).slice(0,limit);
|
||||
}
|
||||
const artists = search('artists',[...cat.artistCards.values()],a => [a.name]);
|
||||
const releases = search('releases',cat.releaseCards,r => [r.title,...r.artists]);
|
||||
const tracks = search('tracks',cat.tracks,t => [t.title,...t.artists.map(a => a.name),t.release_title,...(t.featured_artists||[]).map(a=>a.name)]);
|
||||
return json({scores,artists,releases,tracks,podcasts:[]});
|
||||
}
|
||||
if ((m = /^playlists\/(-?\d+)$/.exec(path))) {
|
||||
const pl = await this.playlist(Number(m[1]),cat.tracks);
|
||||
return pl ? json(pl) : missing();
|
||||
}
|
||||
const ids = (await this.read('meta','playlists') || []).map(p => p.id);
|
||||
if (!ids.includes(-1)) ids.unshift(-1);
|
||||
const pl = await Promise.all(ids.map(id => this.playlist(id,cat.tracks)));
|
||||
return json(pl.filter(p => p && p.track_count).map(({tracks,...card}) => card));
|
||||
}
|
||||
}
|
||||
globalThis.OfflineCatalog = OfflineCatalog;
|
||||
})();
|
||||
@@ -0,0 +1,333 @@
|
||||
/* global OfflineCatalog */
|
||||
importScripts('/offline-catalog.js');
|
||||
|
||||
const CACHE = 'furumusic-player-shell-v1';
|
||||
const SETTINGS = '/__furumusic_offline__/settings';
|
||||
const SHELL = '/__furumusic_offline__/player';
|
||||
const ASSETS = ['/player.webmanifest', '/player-icon.svg'];
|
||||
const ACCOUNT = 'X-Furumusic-Player-Account';
|
||||
const ORIGIN = self.location.origin;
|
||||
const BINDINGS = '/__furumusic_offline__/client/';
|
||||
const bound = new Map();
|
||||
let statePromise;
|
||||
let serial = Promise.resolve();
|
||||
let network = new AbortController();
|
||||
let repo;
|
||||
|
||||
function catalog(account) {
|
||||
if (!repo || String(repo.account) !== account) repo = new OfflineCatalog(account);
|
||||
return repo;
|
||||
}
|
||||
|
||||
function exclusive(work) {
|
||||
const operation = serial.then(work);
|
||||
serial = operation.catch(() => {});
|
||||
return operation;
|
||||
}
|
||||
|
||||
function settings() {
|
||||
if (!statePromise) {
|
||||
statePromise = caches.open(CACHE).then(cache => cache.match(SETTINGS)).then(r => r ? r.json() : null);
|
||||
}
|
||||
return statePromise;
|
||||
}
|
||||
|
||||
async function broadcast(type, state) {
|
||||
const windows = await self.clients.matchAll({ type:'window', includeUncontrolled:true });
|
||||
for (const client of windows) {
|
||||
if (isPlayer(client.url)) client.postMessage({ type, account:state.account, mode:state.mode });
|
||||
}
|
||||
}
|
||||
|
||||
async function save(state) {
|
||||
const cache = await caches.open(CACHE);
|
||||
if (state) await cache.put(SETTINGS, Response.json(state));
|
||||
else await cache.delete(SETTINGS);
|
||||
statePromise = Promise.resolve(state);
|
||||
network.abort();
|
||||
network = new AbortController();
|
||||
if (state) await broadcast('offline-mode', state);
|
||||
}
|
||||
|
||||
async function forget(state) {
|
||||
if (!state) return;
|
||||
const cache = await caches.open(CACHE);
|
||||
await cache.delete(SHELL);
|
||||
await save(null);
|
||||
// Notify pages before waiting for the catalog write lock. Downloads can hold
|
||||
// that lock while their authorization response is still pending.
|
||||
await broadcast('offline-purge', { account:state.account, mode:'disabled' });
|
||||
await catalog(state.account).clear();
|
||||
repo = undefined;
|
||||
}
|
||||
|
||||
function isPlayer(url) {
|
||||
if (!url) return false;
|
||||
const loc = new URL(url);
|
||||
return loc.origin === ORIGIN && loc.pathname === '/';
|
||||
}
|
||||
|
||||
async function bind(id, account) {
|
||||
if (!id || bound.get(id) === account) return;
|
||||
bound.set(id, account);
|
||||
await (await caches.open(CACHE)).put(BINDINGS + id, new Response(account));
|
||||
}
|
||||
|
||||
async function accountFor(id) {
|
||||
if (!id) return null;
|
||||
if (!bound.has(id)) {
|
||||
const response = await (await caches.open(CACHE)).match(BINDINGS + id);
|
||||
if (response) bound.set(id, await response.text());
|
||||
}
|
||||
return bound.get(id);
|
||||
}
|
||||
|
||||
async function cleanBindings(keep = '') {
|
||||
const cache = await caches.open(CACHE);
|
||||
const clients = new Set((await self.clients.matchAll({type:'window', includeUncontrolled:true})).map(c => c.id));
|
||||
for (const request of await cache.keys()) {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
if (!pathname.startsWith(BINDINGS)) continue;
|
||||
const id = pathname.slice(BINDINGS.length);
|
||||
if (id !== keep && !clients.has(id)) { await cache.delete(request); bound.delete(id); }
|
||||
}
|
||||
}
|
||||
|
||||
function isOffline(state) {
|
||||
return state?.mode === 'manual' || state?.mode === 'auto';
|
||||
}
|
||||
|
||||
function validShell(response, account) {
|
||||
return response.status === 200 && response.headers.get(ACCOUNT) === account &&
|
||||
response.headers.get('Content-Type')?.startsWith('text/html');
|
||||
}
|
||||
|
||||
function probeAccount(response) {
|
||||
const id = response.headers.get(ACCOUNT);
|
||||
if (response.status === 204 && /^[1-9]\d*$/.test(id)) return id;
|
||||
return response.status === 401 && id === '0' ? id : null;
|
||||
}
|
||||
|
||||
async function verifySession(request) {
|
||||
const signal = requestSignal(request, 3500);
|
||||
try {
|
||||
const response = await fetch('/offline-probe', {
|
||||
credentials:'same-origin', cache:'no-store', redirect:'manual', signal:signal.signal,
|
||||
});
|
||||
return probeAccount(response);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
signal.clear();
|
||||
}
|
||||
}
|
||||
|
||||
async function configure({ account, mode }, sourceId) {
|
||||
account = String(account);
|
||||
if (!/^[1-9]\d*$/.test(account) || !['manual','auto','online','disabled'].includes(mode)) {
|
||||
throw Error('Invalid offline settings');
|
||||
}
|
||||
const current = await settings();
|
||||
const cache = await caches.open(CACHE);
|
||||
const caller = await accountFor(sourceId);
|
||||
if ((caller && caller !== account) || (isOffline(current) && current.account !== account)) {
|
||||
throw Error('Account changed');
|
||||
}
|
||||
if (mode === 'disabled') {
|
||||
if (current?.account === account) {
|
||||
await cache.delete(SHELL);
|
||||
await save({ account, mode });
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
if (current?.account !== account || current.mode === 'disabled' || !await cache.match(SHELL)) {
|
||||
if (mode !== 'online') throw Error('Save the player online first');
|
||||
const shell = await fetch('/', {cache:'no-store', credentials:'same-origin', redirect:'manual'});
|
||||
if (!validShell(shell, account)) throw Error('Could not verify this account');
|
||||
if (current && current.account !== account) await forget(current);
|
||||
await cache.addAll(ASSETS);
|
||||
await cache.put(SHELL, shell);
|
||||
}
|
||||
if (current?.account !== account || current.mode !== mode) await save({ account, mode });
|
||||
await bind(sourceId, account);
|
||||
return mode;
|
||||
}
|
||||
|
||||
self.addEventListener('install', event => event.waitUntil(self.skipWaiting()));
|
||||
self.addEventListener('activate', event => event.waitUntil(cleanBindings().then(() => self.clients.claim())));
|
||||
self.addEventListener('message', event => {
|
||||
if (!isPlayer(event.source?.url)) return;
|
||||
if (event.data?.type === 'offline-client' && /^[1-9]\d*$/.test(String(event.data.account))) {
|
||||
event.waitUntil(bind(event.source.id, String(event.data.account)));
|
||||
return;
|
||||
}
|
||||
if (event.data?.type !== 'offline-config') return;
|
||||
const reply = event.ports[0];
|
||||
event.waitUntil(exclusive(() => configure(event.data, event.source.id))
|
||||
.then(mode => { reply?.postMessage({ ok:true, mode }); },
|
||||
e => { reply?.postMessage({ ok:false, error:e.message }); }));
|
||||
});
|
||||
|
||||
function unavailable() {
|
||||
return Response.json({ error:'Unavailable offline' }, { status:503, headers:{'Cache-Control':'no-store'} });
|
||||
}
|
||||
|
||||
async function local(request, state, rootNavigation) {
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== ORIGIN) return Response.error();
|
||||
const cache = await caches.open(CACHE);
|
||||
if (rootNavigation) {
|
||||
const shell = await cache.match(SHELL);
|
||||
if (!shell || !validShell(shell, state.account)) return unavailable();
|
||||
const html = (await shell.text()).replace('data-offline-mode="online"', 'data-offline-mode="' + state.mode + '"');
|
||||
return new Response(html, {headers:{'Content-Type':'text/html; charset=utf-8', 'Cache-Control':'private, no-store', [ACCOUNT]:state.account}});
|
||||
}
|
||||
if (ASSETS.includes(url.pathname)) return await cache.match(url.pathname) || unavailable();
|
||||
if (request.mode === 'navigate') return unavailable();
|
||||
const read = ['GET','HEAD'].includes(request.method) ||
|
||||
(request.method === 'POST' && url.pathname === '/api/player/tracks-by-ids');
|
||||
if (read && url.pathname.startsWith('/api/')) {
|
||||
try {
|
||||
return await catalog(state.account).respond(request) || unavailable();
|
||||
} catch {
|
||||
return unavailable();
|
||||
}
|
||||
}
|
||||
return unavailable();
|
||||
}
|
||||
|
||||
// A mode change cuts off requests already waiting for headers and in-flight audio streams.
|
||||
function requestSignal(request, timeout) {
|
||||
const controller = new AbortController();
|
||||
const signals = [network.signal, request.signal];
|
||||
let signal;
|
||||
const abort = () => controller.abort();
|
||||
if (AbortSignal.any) {
|
||||
signal = AbortSignal.any([...signals, controller.signal]);
|
||||
} else {
|
||||
signal = controller.signal;
|
||||
for (const source of signals) {
|
||||
if (source.aborted) controller.abort();
|
||||
else source.addEventListener('abort', abort, { once:true });
|
||||
}
|
||||
}
|
||||
const timer = timeout ? setTimeout(() => controller.abort(), timeout) : null;
|
||||
return { signal, clear() {
|
||||
clearTimeout(timer);
|
||||
if (!AbortSignal.any) for (const source of signals) source.removeEventListener('abort', abort);
|
||||
} };
|
||||
}
|
||||
|
||||
function fallback(request, state, rootNavigation) {
|
||||
return exclusive(async () => {
|
||||
const now = await settings();
|
||||
if (now === state && state.mode === 'online') await save({account:state.account, mode:'auto'});
|
||||
return settings();
|
||||
}).then(now => now?.account === state.account && isOffline(now)
|
||||
? local(request, now, rootNavigation) : unavailable());
|
||||
}
|
||||
|
||||
async function handle(event) {
|
||||
const {request} = event;
|
||||
const url = new URL(request.url);
|
||||
const sameOrigin = url.origin === ORIGIN;
|
||||
const rootNavigation = request.mode === 'navigate' && isPlayer(request.url);
|
||||
const auth = sameOrigin && (url.pathname === '/logout' || url.pathname === '/auth/oidc/callback' ||
|
||||
(url.pathname === '/login' && request.method === 'POST'));
|
||||
const state = await settings();
|
||||
if (!state) return fetch(request);
|
||||
const source = event.clientId && await self.clients.get(event.clientId);
|
||||
const player = rootNavigation || isPlayer(source?.url) || (!source && isPlayer(request.referrer));
|
||||
if (rootNavigation) event.waitUntil(cleanBindings(event.resultingClientId));
|
||||
if (isOffline(state) && sameOrigin && ASSETS.includes(url.pathname)) return local(request, state, false);
|
||||
if (auth) {
|
||||
if (player && isOffline(state)) return unavailable();
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(request);
|
||||
return response;
|
||||
} finally {
|
||||
let changed = url.pathname === '/logout';
|
||||
if (!changed && response && response.status < 400) {
|
||||
const identity = await verifySession(request);
|
||||
// A rejected login also returns 200. Keep existing downloads when
|
||||
// the session still belongs to their owner.
|
||||
changed = identity === null ? response.type === 'opaqueredirect' || response.redirected : identity !== state.account;
|
||||
}
|
||||
if (changed) {
|
||||
await exclusive(async () => { if ((await settings())?.account === state.account) await forget(state); });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!player) return fetch(request);
|
||||
if (state.mode === 'disabled' && !rootNavigation) return fetch(request);
|
||||
if (!rootNavigation && source && (await accountFor(source.id)) !== state.account) return unavailable();
|
||||
const probe = sameOrigin && url.pathname === '/offline-probe' && request.method === 'GET';
|
||||
if (isOffline(state) && !(probe && state.mode === 'auto')) {
|
||||
if (rootNavigation) await bind(event.resultingClientId, state.account);
|
||||
return local(request, state, rootNavigation);
|
||||
}
|
||||
const savedAudio = /^\/api\/player\/(?:stream\/\d+|federation\/cache\/[a-f\d]{64})$/.test(url.pathname);
|
||||
if (state.mode === 'online' && sameOrigin && ['GET','HEAD'].includes(request.method) &&
|
||||
savedAudio && url.searchParams.get('saved') === '1') {
|
||||
const saved = await catalog(state.account).respond(request).catch(() => null);
|
||||
if (saved && (saved.ok || saved.status === 416)) return saved;
|
||||
}
|
||||
|
||||
const timed = state.mode !== 'disabled' && (rootNavigation || probe || url.pathname === '/api/player/me');
|
||||
const signal = requestSignal(request, timed ? 3500 : 0);
|
||||
let response;
|
||||
try {
|
||||
// The queue lookup is a read with a JSON body; retain it for a local retry.
|
||||
const queueLookup = sameOrigin && request.method === 'POST' && url.pathname === '/api/player/tracks-by-ids';
|
||||
response = await fetch(queueLookup ? request.clone() : request, {signal:signal.signal});
|
||||
} catch {
|
||||
if (request.signal.aborted || state.mode === 'disabled' || probe || !sameOrigin) return Response.error();
|
||||
if (rootNavigation) await bind(event.resultingClientId, state.account);
|
||||
return fallback(request, state, rootNavigation);
|
||||
} finally {
|
||||
signal.clear();
|
||||
}
|
||||
if (([502,503,504].includes(response.status) || (rootNavigation && response.status >= 500)) &&
|
||||
!probe && state.mode === 'online' && sameOrigin) {
|
||||
if (rootNavigation) await bind(event.resultingClientId, state.account);
|
||||
return fallback(request, state, rootNavigation);
|
||||
}
|
||||
// Intermediaries and older API handlers may return a login page/401 during
|
||||
// an outage. Only our session endpoint or a labeled player page identifies an account.
|
||||
const checkAuth = sameOrigin && (response.status === 401 ||
|
||||
(rootNavigation && (response.type === 'opaqueredirect' || response.redirected ||
|
||||
(response.ok && !validShell(response, state.account)))) ||
|
||||
(probe && probeAccount(response) !== state.account));
|
||||
if (checkAuth) {
|
||||
const label = rootNavigation && response.ok ? response.headers.get(ACCOUNT) : null;
|
||||
const identity = probe ? probeAccount(response) : /^\d+$/.test(label) ? label : await verifySession(request);
|
||||
if (identity === state.account && !rootNavigation) return response;
|
||||
if (identity === null || identity === state.account) {
|
||||
if (probe) return unavailable();
|
||||
if (state.mode === 'disabled') return response;
|
||||
if (rootNavigation) await bind(event.resultingClientId, state.account);
|
||||
return fallback(request, state, rootNavigation);
|
||||
}
|
||||
// Revocation aborts the previous account's streams. Detach this verified
|
||||
// response first, so the login redirect or new account page still reaches the window.
|
||||
const reply = response.type === 'opaqueredirect' ? Response.redirect(ORIGIN + '/login', 302) :
|
||||
new Response(response.body && ![204,205,304].includes(response.status) && request.method !== 'HEAD' ? await response.blob() : null, {
|
||||
headers:response.headers, status:response.status, statusText:response.statusText,
|
||||
});
|
||||
await exclusive(async () => { if ((await settings())?.account === state.account) await forget(state); });
|
||||
return reply;
|
||||
}
|
||||
if (rootNavigation && state.mode === 'online' && validShell(response, state.account)) {
|
||||
await bind(event.resultingClientId, state.account);
|
||||
const copy = response.clone();
|
||||
event.waitUntil(exclusive(async () => {
|
||||
if (await settings() === state) await (await caches.open(CACHE)).put(SHELL, copy);
|
||||
}));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
self.addEventListener('fetch', event => {
|
||||
if (['https:','http:'].includes(new URL(event.request.url).protocol)) event.respondWith(handle(event));
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<rect width="64" height="64" rx="14" fill="#111827"/>
|
||||
<path d="M27 15v31.5a9 9 0 1 1-5-8.1V22l27-6v24.5a9 9 0 1 1-5-8.1V15.9L27 20.5" fill="#67e8f9"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 223 B |
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"id": "/",
|
||||
"name": "Furumusic",
|
||||
"short_name": "Furumusic",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#121212",
|
||||
"theme_color": "#121212",
|
||||
"icons": [{ "src": "/player-icon.svg", "sizes": "any", "type": "image/svg+xml" }]
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
(()=>{var bt=!1,Et=!1,B=[],vt=-1,Fe=!1,wt=!1;function gr(e){ai(e)}function xr(){wt=!0}function yr(){wt=!1,br()}function ai(e){B.includes(e)||(B.push(e),e._x_schedulerPriority!==void 0&&(Fe=!0)),br()}function ue(e){let t=B.indexOf(e);t!==-1&&t>vt&&B.splice(t,1)}function br(){if(!Et&&!bt){if(wt)return;bt=!0,queueMicrotask(ci)}}function ci(){bt=!1,Et=!0;for(let e=0;e<B.length;e++)Fe&&li(e),B[e](),vt=e;B.length=0,vt=-1,Fe=!1,Et=!1}function li(e){let t=new Map,r=B.slice(e).sort((n,i)=>fi(n,i,t));for(let n=0;n<r.length;n++)B[e+n]=r[n];Fe=!1}function fi(e,t,r){return yt(e)?yt(t)?_r(e._x_schedulerPriority.el,r)-_r(t._x_schedulerPriority.el,r)||e._x_schedulerPriority.order-t._x_schedulerPriority.order:-1:yt(t)?1:0}function yt(e){return e._x_schedulerPriority!==void 0}function _r(e,t){if(t.has(e))return t.get(e);let r=0,n=e;for(;e;)r++,e._x_teleportBack?e=e._x_teleportBack:typeof ShadowRoot=="function"&&e.parentNode instanceof ShadowRoot?e=e.parentNode.host:e=e.parentElement;return t.set(n,r),r}var D,P,H,At,ui=0,St=!0;function Er(e){St=!1,e(),St=!0}function vr(e){D=e.reactive,H=e.release,P=t=>e.effect(t,{scheduler:r=>{St?gr(r):r()}}),At=e.raw}function Tt(e){P=e}function wr(e){let t=()=>{};return[(n,i)=>{let o=i?.priority==="structural"?ui++:void 0,s=P(n);return o!==void 0&&s!==void 0&&(s._x_schedulerPriority={el:e,order:o}),e._x_effects||(e._x_effects=new Set,e._x_runEffects=()=>{e._x_effects.forEach(a=>a())}),e._x_effects.add(s),t=()=>{s!==void 0&&(e._x_effects.delete(s),H(s))},s},()=>{t()}]}function Ve(e,t){let r=!0,n,i,o=P(()=>{let s=e(),a=JSON.stringify(s);if(!r&&(typeof s=="object"||s!==n)){let c=typeof n=="object"?JSON.parse(i):n;queueMicrotask(()=>{t(s,c)})}n=s,i=a,r=!1});return()=>{ue(o),H(o)}}async function Sr(e){xr();try{await e(),await Promise.resolve()}finally{yr()}}var Ar=[],Tr=[],Or=[];function Nr(e){Or.push(e)}function de(e,t){typeof t=="function"?(e._x_cleanups||(e._x_cleanups=[]),e._x_cleanups.push(t)):(t=e,Tr.push(t))}function Be(e){Ar.push(e)}function He(e,t,r){e._x_attributeCleanups||(e._x_attributeCleanups={}),e._x_attributeCleanups[t]||(e._x_attributeCleanups[t]=[]),e._x_attributeCleanups[t].push(r)}function Ot(e,t){e._x_attributeCleanups&&Object.entries(e._x_attributeCleanups).forEach(([r,n])=>{(t===void 0||t.includes(r))&&(n.forEach(i=>i()),delete e._x_attributeCleanups[r])})}function Cr(e){for(e._x_effects?.forEach(ue);e._x_cleanups?.length;)e._x_cleanups.pop()()}var Ue=new MutationObserver(qe),Nt=!1;function we(){Ue.observe(document,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0}),Nt=!0}function Ct(){di(),Ue.disconnect(),Nt=!1}var Z=[];function di(){let e=Ue.takeRecords();Z.push(()=>e.length>0&&qe(e));let t=Z.length;queueMicrotask(()=>{if(Z.length===t)for(;Z.length>0;)Z.shift()()})}function Rr(){for(;Z.length>0;)Z.shift()();let e=Ue.takeRecords();e.length>0&&qe(e)}function h(e){if(!Nt)return e();Ct();try{return e()}finally{we()}}var Rt=!1,$e=[];function Dr(){Rt=!0}function Mr(){Rt=!1,qe($e),$e=[]}function qe(e){if(Rt){$e=$e.concat(e);return}let t=[],r=new Set,n=new Map,i=new Map;for(let o=0;o<e.length;o++)if(!e[o].target._x_ignoreMutationObserver&&(e[o].type==="childList"&&(e[o].removedNodes.forEach(s=>{s.nodeType===1&&s._x_marker&&r.add(s)}),e[o].addedNodes.forEach(s=>{if(s.nodeType===1){if(r.has(s)){r.delete(s);return}s._x_marker||t.push(s)}})),e[o].type==="attributes")){let s=e[o].target,a=e[o].attributeName,c=e[o].oldValue,l=()=>{n.has(s)||n.set(s,[]),n.get(s).push({name:a,value:s.getAttribute(a)})},f=()=>{i.has(s)||i.set(s,[]),i.get(s).push(a)};s.hasAttribute(a)&&c===null?l():s.hasAttribute(a)?(f(),l()):f()}i.forEach((o,s)=>{Ot(s,o)}),n.forEach((o,s)=>{Ar.forEach(a=>a(s,o))});for(let o of r)t.some(s=>s.contains(o))||Tr.forEach(s=>s(o));for(let o of t)o.isConnected&&Or.forEach(s=>s(o));t=null,r=null,n=null,i=null}function ze(e){return L(U(e))}function I(e,t,r){return e._x_dataStack=[t,...U(r||e)],()=>{e._x_dataStack=e._x_dataStack.filter(n=>n!==t)}}function U(e){return e._x_dataStack?e._x_dataStack:typeof ShadowRoot=="function"&&e instanceof ShadowRoot?U(e.host):e.parentNode?U(e.parentNode):[]}function L(e){return new Proxy({objects:e},pi)}function kr(e,t){return e===null||e===Object.prototype?null:Object.prototype.hasOwnProperty.call(e,t)?e:kr(Object.getPrototypeOf(e),t)}var pi={ownKeys({objects:e}){return Array.from(new Set(e.flatMap(t=>Object.keys(t))))},has({objects:e},t){return t==Symbol.unscopables?!1:e.some(r=>Object.prototype.hasOwnProperty.call(r,t)||Reflect.has(r,t))},get({objects:e},t,r){return t=="toJSON"?hi:Reflect.get(e.find(n=>Reflect.has(n,t))||{},t,r)},set({objects:e},t,r,n){let i;for(let s of e)if(i=kr(s,t),i)break;i||(i=e[e.length-1]);let o=Object.getOwnPropertyDescriptor(i,t);return o?.set&&o?.get?o.set.call(n,r)||!0:Reflect.set(i,t,r)}};function hi(){return Reflect.ownKeys(this).reduce((t,r)=>(t[r]=Reflect.get(this,r),t),{})}function pe(e,t=()=>{}){let r=i=>typeof i=="object"&&!Array.isArray(i)&&i!==null,n=(i,o="")=>{Object.entries(Object.getOwnPropertyLine truncated
|
||||
|
||||
${r?'Expression: "'+r+`"
|
||||
|
||||
`:""}`,t),setTimeout(()=>{throw e},0)}var he=!0;function We(e){let t=he;he=!1;let r=e();return he=t,r}function M(e,t,r={}){let n;return x(e,t)(i=>n=i,r),n}function x(...e){return Fr(...e)}var Fr=()=>{};function Vr(e){Fr=e}var $r;function Br(e){$r=e}function Hr(e,t){let r={};G(r,e);let n=[r,...U(e)],i=typeof t=="function"?xi(n,t):bi(n,t,e);return Ir.bind(null,e,t,i)}function xi(e,t){return(r=()=>{},{scope:n={},params:i=[],context:o}={})=>{if(!he){Se(r,t,L([n,...e]),i);return}let s=t.apply(L([n,...e]),i);Se(r,s)}}var kt={};function yi(e,t){if(kt[e])return kt[e];let r=Object.getPrototypeOf(async function(){}).constructor,n=/^[\n\s]*if.*\(.*\)/.test(e.trim())||/^(let|const)\s/.test(e.trim())?`(async()=>{ ${e} })()`:e,o=(()=>{try{let s=new r(["__self","scope"],`with (scope) { __self.result = ${n} }; __self.finished = true; return __self.result;`);return Object.defineProperty(s,"name",{value:`[Alpine] ${e}`}),s}catch(s){return Y(s,t,e),Promise.resolve()}})();return kt[e]=o,o}function bi(e,t,r){let n=yi(t,r);return(i=()=>{},{scope:o={},params:s=[],context:a}={})=>{n.result=void 0,n.finished=!1;let c=L([o,...e]);if(typeof n=="function"){let l=n.call(a,n,c).catch(f=>Y(f,r,t));n.finished?(Se(i,n.result,c,s,r),n.result=void 0):l.then(f=>{Se(i,f,c,s,r)}).catch(f=>Y(f,r,t)).finally(()=>n.result=void 0)}}}function Se(e,t,r,n,i){if(he&&typeof t=="function"){let o=t.apply(r,n);o instanceof Promise?o.then(s=>Se(e,s,r,n)).catch(s=>Y(s,i,t)):e(o)}else typeof t=="object"&&t instanceof Promise?t.then(o=>e(o)):e(t)}function Ur(...e){return $r(...e)}function qr(e,t,r={}){let n={};G(n,e);let i=[n,...U(e)],o=L([r.scope??{},...i]),s=r.params??[];if(t.includes("await")){let a=Object.getPrototypeOf(async function(){}).constructor,c=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(async()=>{ ${t} })()`:t;return new a(["scope"],`with (scope) { let __result = ${c}; return __result }`).call(r.context,o)}else{let a=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(()=>{ ${t} })()`:t,l=new Function(["scope"],`with (scope) { let __result = ${a}; return __result }`).call(r.context,o);return typeof l=="function"&&he?l.apply(o,s):l}}var Lt="x-";function N(e=""){return Lt+e}function zr(e){Lt=e}var Ge={};function p(e,t){return Ge[e]=t,{before(r){if(!Ge[r]){console.warn(String.raw`Cannot find directive \`${r}\`. \`${e}\` will use the default order of execution`);return}let n=Q.indexOf(r);Q.splice(n>=0?n:Q.indexOf("DEFAULT"),0,e)}}}function Kr(e){return Object.keys(Ge).includes(e)}function ee(e,t,r){if(t=Array.from(t),e._x_virtualDirectives){let o=Object.entries(e._x_virtualDirectives).map(([a,c])=>({name:a,value:c})),s=jt(o);o=o.map(a=>s.find(c=>c.name===a.name)?{name:`x-bind:${a.name}`,value:`"${a.value}"`}:a),t=t.concat(o)}let n={};return t.map(Yr((o,s)=>n[o]=s)).filter(Xr).map(vi(n,r)).sort(wi).map(o=>Ei(e,o))}function jt(e){return Array.from(e).map(Yr()).filter(t=>!Xr(t))}var Pt=!1,Ae=new Map,Wr=Symbol();function Gr(e){Pt=!0;let t=Symbol();Wr=t,Ae.set(t,[]);let r=()=>{for(;Ae.get(t).length;)Ae.get(t).shift()();Ae.delete(t)},n=()=>{Pt=!1,r()};e(r),n()}function Mt(e){let t=[],r=a=>t.push(a),[n,i]=wr(e);return t.push(i),[{Alpine:q,effect:n,cleanup:r,evaluateLater:x.bind(x,e),evaluate:M.bind(M,e)},()=>t.forEach(a=>a())]}function Ei(e,t){let r=()=>{},n=Ge[t.type]||r,[i,o]=Mt(e);He(e,t.original,o);let s=()=>{e._x_ignore||e._x_ignoreSelf||(n.inline&&n.inline(e,t,i),n=n.bind(n,e,t,i),Pt?Ae.get(Wr).push(n):n())};return s.runCleanups=o,s}var Ye=(e,t)=>({name:r,value:n})=>(r.startsWith(e)&&(r=r.replace(e,t)),{name:r,value:n}),Je=e=>e;function Yr(e=()=>{}){return({name:t,value:r})=>{let{name:n,value:i}=Jr.reduce((o,s)=>s(o),{name:t,value:r});return n!==t&&e(n,t),{name:n,value:i}}}var Jr=[];function me(e){Jr.push(e)}function Xr({name:e}){return Zr().test(e)}var Zr=()=>new RegExp(`^${Lt}([^:^.]+)\\b`);function vi(e,t){return({name:r,value:n})=>{r===n&&(n="");let i=r.match(Zr()),o=r.match(/:([a-zA-Z0-9\-_:]+)/),s=r.match(/\.[^.\]]+(?=[^\]]*$)/g)||[],a=t||e[r]||r;return{type:i?i[1]:null,value:o?o[1]:null,modifiers:s.map(c=>c.replace(".","")),expression:n,original:a}}}var It="DEFAULT",Q=["ignore","ref","id","data","anchor","bind","init","for","model","modelable","transition","show","if",It,"teleport"];function wi(e,t){let r=Q.indexOf(e.type)===-1?It:e.type,n=Q.indexOf(t.type)===-1?It:t.type;return Q.indexOf(r)-Q.indexOf(n)}function j(e,t){if(typeof ShadowRoot=="function"&&e instanceof ShadowRoot){Array.from(e.children).forEach(i=>j(i,t));return}let r=!1;if(t(e,()=>r=!0),r)return;let n=e.firstElementChild;for(;n;)j(n,t,!1),n=n.nextElementSibling}var C=!1;function w(e,t=()=>{}){return(...r)=>C?t(...r):e(...r)}function Qr(e){return(...t)=>C&&e(...t)}var en=[];function F(e){en.push(e)}function tn(e,t){en.forEach(r=>r(e,t)),C=!0,nn(()=>{S(t,(r,n)=>{n(r,()=>{})})}),C=!1}var Xe=!1;function rn(e,t){t._x_dataStack||(t._x_dataStack=e._x_dataStack),C=!0,Xe=!0,nn(()=>{Si(t)}),C=!1,Xe=!1}function Si(e){let t=!1;S(e,(n,i)=>{j(n,(oLine truncated
|
||||
/*! Bundled license information:
|
||||
|
||||
@vue/shared/dist/shared.esm-bundler.js:
|
||||
(**
|
||||
* @vue/shared v3.5.41
|
||||
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||
* @license MIT
|
||||
**)
|
||||
|
||||
@vue/reactivity/dist/reactivity.esm-bundler.js:
|
||||
(**
|
||||
* @vue/reactivity v3.5.41
|
||||
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||
* @license MIT
|
||||
**)
|
||||
*/
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
# MIT License
|
||||
|
||||
Copyright © 2019-2025 Caleb Porzio and contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -21,6 +21,7 @@ fn renders_podcast_navigation_and_views() {
|
||||
let html = crate::player::PlayerPageTemplate {
|
||||
t: crate::i18n::Translations::for_lang(crate::i18n::Lang::En),
|
||||
guest: false,
|
||||
account_id: 1,
|
||||
share_token: String::new(),
|
||||
downloads_enabled: true,
|
||||
torrent_downloads_enabled: true,
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="{{ t.lang.code() }}">
|
||||
<html lang="{{ t.lang.code() }}"{% block html_attrs %}{% endblock html_attrs %}>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
@@ -1,8 +1,23 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block html_attrs %} data-offline-account="{% if !guest && share_token.is_empty() %}{{ account_id }}{% endif %}" data-offline-mode="online"{% endblock html_attrs %}
|
||||
{% block title %}{{ t.site_name }}{% endblock title %}
|
||||
|
||||
{% block head_extra %}
|
||||
{% if !guest && share_token.is_empty() %}
|
||||
<link rel="manifest" href="/player.webmanifest">
|
||||
<meta name="theme-color" content="#121212">
|
||||
<script>
|
||||
if ('serviceWorker' in navigator) {
|
||||
const bindOfflineAccount = () => navigator.serviceWorker.controller?.postMessage({
|
||||
type:'offline-client', account:document.documentElement.dataset.offlineAccount
|
||||
});
|
||||
bindOfflineAccount();
|
||||
navigator.serviceWorker.addEventListener('controllerchange', bindOfflineAccount);
|
||||
}
|
||||
</script>
|
||||
<script>{{ self.offline_catalog()|safe }}</script>
|
||||
{% endif %}
|
||||
{% include "player/styles.html" %}
|
||||
{% include "player/podcast_styles.html" %}
|
||||
{% include "player/sidebar_styles.html" %}
|
||||
@@ -14,6 +29,7 @@
|
||||
{% include "player/shell.html" %}
|
||||
{% include "player/modals.html" %}
|
||||
{% include "player/lyrics_modal.html" %}
|
||||
{% include "player/offline_scripts.html" %}
|
||||
{% include "player/podcast_scripts.html" %}
|
||||
{% include "player/lyrics_scripts.html" %}
|
||||
{% include "player/lyrics_search_scripts.html" %}
|
||||
@@ -23,4 +39,5 @@
|
||||
{% include "player/track_actions_scripts.html" %}
|
||||
{% include "player/playlist_header_scripts.html" %}
|
||||
{% include "player/scripts.html" %}
|
||||
<script>{{ self.alpine()|safe }}</script>
|
||||
{% endblock body %}
|
||||
@@ -1,5 +1,21 @@
|
||||
{% if share_token.is_empty() %}
|
||||
<section class="offline-account" aria-label="{{ t.player_offline_listening }}" x-data="{get offline() { return $store.offline }}" @keydown.space.stop>
|
||||
<div class="offline-account-summary">
|
||||
<div aria-live="polite">
|
||||
<strong x-text="!offline.enabled ? '{{ t.player_offline_disabled }}' : offline.manual ? '{{ t.player_offline_manual }}' : offline.active ? '{{ t.player_offline_auto }}' : '{{ t.player_offline_online }}'"></strong>
|
||||
<small x-show="offline.enabled || offline.bytes" x-text="'{{ t.player_offline_used }} · ' + offline.formatBytes(offline.bytes)"></small>
|
||||
</div>
|
||||
<button type="button" class="offline-manage" title="{{ t.player_offline_manage_label }}" aria-label="{{ t.player_offline_manage_label }}"
|
||||
@click="$store.user.openSettings('offline-settings-title')">{{ t.player_offline_manage }}</button>
|
||||
</div>
|
||||
<button type="button" role="switch" class="offline-switch-row" x-show="offline.enabled" x-cloak
|
||||
:aria-checked="offline.manual" :disabled="offline.busy" @click="offline.setManual(!offline.manual)">
|
||||
<span>{{ t.player_offline_cache_only }}</span><span class="offline-switch" aria-hidden="true"></span>
|
||||
</button>
|
||||
</section>
|
||||
{% endif %}
|
||||
<div class="account-action-list">
|
||||
<a href="#listening" :aria-current="$store.library.view === 'listening' ? 'page' : null"
|
||||
<a data-online-only href="#listening" :aria-current="$store.library.view === 'listening' ? 'page' : null"
|
||||
@click="$store.user.menuOpen = false">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20V12M9 20V6M14 20V3M19 20V9"/></svg>
|
||||
{{ t.player_my_listening }}
|
||||
@@ -13,11 +29,11 @@
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h9m4 0h3M4 12h2m4 0h10M4 18h8m4 0h4"/><circle cx="15" cy="6" r="2"/><circle cx="8" cy="12" r="2"/><circle cx="14" cy="18" r="2"/></svg>
|
||||
{{ t.nav_settings }}
|
||||
</button>
|
||||
<a href="/admin/" x-show="$store.user.profile?.role === 'admin'" x-cloak>
|
||||
<a data-online-only href="/admin/" x-show="$store.user.profile?.role === 'admin'" x-cloak>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 4.5 6v5c0 4.5 3.2 8 7.5 10 4.3-2 7.5-5.5 7.5-10V6z"/><path d="m9 12 2 2 4-4"/></svg>
|
||||
{{ t.player_admin_panel }}
|
||||
</a>
|
||||
<a href="/logout">
|
||||
<a data-online-only href="/logout">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4H5v16h4m5-4 4-4-4-4m-5 4h9"/></svg>
|
||||
{{ t.player_log_out }}
|
||||
</a>
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<p class="empty-state" x-show="!$store.follows.artists.length">{{ t.player_no_followed_artists }}</p>
|
||||
<p class="empty-state" x-show="!$store.follows.artists.length" x-text="$store.offline.active ? '{{ t.player_offline_empty_followed }}' : '{{ t.player_no_followed_artists }}'"></p>
|
||||
</div>
|
||||
</template>
|
||||
<template x-if="$store.library.view === 'playlists'">
|
||||
@@ -34,7 +34,7 @@
|
||||
</a>
|
||||
{% include "player/pin_button.html" %}
|
||||
<template x-if="pl.kind === 'user' && pl.is_own">
|
||||
<div class="collection-options">
|
||||
<div data-online-only class="collection-options">
|
||||
<button type="button" class="collection-more" x-ref="more" @click="menuId = menuId === pl.id ? null : pl.id" :aria-expanded="menuId === pl.id" aria-label="{{ t.player_more_actions }}">⋯</button>
|
||||
<div class="collection-popup" x-show="menuId === pl.id" x-cloak>
|
||||
<button @click="menuId = null; $store.playlists.startRename(pl)">{{ t.player_rename }}</button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<header class="collection-heading">
|
||||
<h1 class="section-title">{{ t.player_global_library }}</h1>
|
||||
<button data-member-only type="button" class="release-action-btn secondary" x-show="$store.library.view === 'playlists'"
|
||||
<button data-online-only data-member-only type="button" class="release-action-btn secondary" x-show="$store.library.view === 'playlists'"
|
||||
@click="$store.playlists.showCreate()"><span aria-hidden="true">+</span> {{ t.player_new_playlist }}</button>
|
||||
</header>
|
||||
<nav class="collection-tabs" aria-label="{{ t.player_global_library }}">
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
|
||||
<!-- Create / Rename Playlist Modal -->
|
||||
<template x-if="$store.playlists.modal">
|
||||
<div class="modal-overlay" @click.self="$store.playlists.modal = null">
|
||||
<div data-online-only class="modal-overlay" @click.self="$store.playlists.modal = null">
|
||||
<div class="modal-box">
|
||||
<h3 x-text="$store.playlists.modal.mode === 'create' ? '{{ t.player_new_playlist }}' : '{{ t.player_rename_playlist }}'"></h3>
|
||||
<input type="text" x-model="$store.playlists.modal.title" placeholder="{{ t.player_playlist_name }}"
|
||||
@@ -70,7 +70,7 @@
|
||||
|
||||
<!-- Add to Playlist Modal -->
|
||||
<template x-if="$store.playlists.picker">
|
||||
<div class="modal-overlay" @click.self="$store.playlists.picker = null">
|
||||
<div data-online-only class="modal-overlay" @click.self="$store.playlists.picker = null">
|
||||
<div class="modal-box">
|
||||
<h3>{{ t.player_add_to_playlist }}</h3>
|
||||
<div class="modal-playlist-list">
|
||||
@@ -91,7 +91,7 @@
|
||||
|
||||
<!-- Download Manager Modal -->
|
||||
<template x-if="$store.torrents.modal">
|
||||
<div class="modal-overlay" @click.self="$store.torrents.close()">
|
||||
<div data-online-only class="modal-overlay" @click.self="$store.torrents.close()">
|
||||
<div class="modal-box torrent-modal"
|
||||
:class="{ 'youtube-mode': $store.torrents.sourceTab === 'youtube' }">
|
||||
<div class="torrent-modal-head">
|
||||
@@ -971,11 +971,13 @@
|
||||
|
||||
<!-- User Settings Modal -->
|
||||
<template x-if="$store.user.settingsOpen">
|
||||
<div class="modal-overlay" @click.self="$store.user.closeSettings()">
|
||||
<dialog class="modal-overlay user-settings-overlay" aria-labelledby="user-settings-title"
|
||||
x-init="$nextTick(() => { if ($el.isConnected) { $el.showModal(); document.getElementById($store.user.settingsFocus)?.focus() } })"
|
||||
@cancel.prevent="$store.user.closeSettings()" @click.self="$store.user.closeSettings()" @keydown.space.stop>
|
||||
<div class="modal-box user-settings-modal">
|
||||
<div class="user-settings-head">
|
||||
<div>
|
||||
<h3>User settings</h3>
|
||||
<h3 id="user-settings-title" tabindex="-1">{{ t.nav_settings }}</h3>
|
||||
<p>Personal services, listening history and trusted devices.</p>
|
||||
</div>
|
||||
<button class="mobile-list-action" @click="$store.user.closeSettings()" title="{{ t.player_close }}">
|
||||
@@ -986,7 +988,8 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section class="user-settings-section">
|
||||
{% if !guest && share_token.is_empty() %}{% include "player/offline_settings.html" %}{% endif %}
|
||||
<section class="user-settings-section" data-online-only>
|
||||
<div class="user-settings-section-head">
|
||||
<div>
|
||||
<h4>{{ t.player_interface_language }}</h4>
|
||||
@@ -997,7 +1000,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="user-settings-section">
|
||||
<section class="user-settings-section" data-online-only>
|
||||
<div class="user-settings-section-head">
|
||||
<div>
|
||||
<h4>Last.fm</h4>
|
||||
@@ -1012,6 +1015,7 @@
|
||||
</section>
|
||||
|
||||
<section class="user-settings-section user-settings-devices">
|
||||
<p data-offline-only>{{ t.player_offline_devices }}</p>
|
||||
<div class="user-settings-section-head">
|
||||
<div>
|
||||
<h4>Connected devices</h4>
|
||||
@@ -1105,7 +1109,7 @@
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,365 @@
|
||||
<script>
|
||||
document.addEventListener('alpine:init', () => {
|
||||
const account = document.documentElement.dataset.offlineAccount || '';
|
||||
const prefKey = 'furumusic.offline.' + account;
|
||||
const stateKey = prefKey + '.playback';
|
||||
const initialMode = document.documentElement.dataset.offlineMode;
|
||||
const minLimit = 100e6, defaultLimit = 3e9, maxLimit = 512e9;
|
||||
const labels = {
|
||||
unavailable:['Offline storage is unavailable in this browser.', 'Офлайн-хранилище недоступно в этом браузере.'],
|
||||
setup:['Connect to the server to finish setting up offline listening.', 'Для подготовки офлайн-режима нужно подключиться к серверу.'],
|
||||
storage:['Could not save to this device.', 'Не удалось сохранить данные на этом устройстве.'],
|
||||
full:['Cache full. Increase the limit or remove saved music.', 'Кеш заполнен. Увеличьте лимит или удалите сохранённую музыку.'],
|
||||
download:['Download paused. The track stays in the download queue.', 'Загрузка приостановлена. Трек остаётся в очереди.'],
|
||||
};
|
||||
const label = key => labels[key][document.documentElement.lang.startsWith('ru') ? 1 : 0];
|
||||
const read = key => { try { return JSON.parse(localStorage.getItem(key)) || {}; } catch { return {}; } };
|
||||
const prefs = read(prefKey);
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
let repo, probeTimer, probing, transfer, draining, retryTimer;
|
||||
let wakeQueue = false, blocked = false, retryDelay = 5000;
|
||||
let revision = 0, listVersion = 0, lastSuccess = Date.now(), channel;
|
||||
function catalog() { return repo || (repo = new globalThis.OfflineCatalog(account)); }
|
||||
function eligible(track) {
|
||||
return globalThis.OfflineCatalog?.canSave(track) === true;
|
||||
}
|
||||
function sendConfig(worker, mode) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!worker) return reject(new Error('No offline worker'));
|
||||
const ports = new MessageChannel();
|
||||
const timeout = setTimeout(() => end(new Error('Offline worker did not respond')), 20000);
|
||||
function end(error, result) {
|
||||
clearTimeout(timeout);
|
||||
ports.port1.close();
|
||||
if (error) reject(error); else resolve(result);
|
||||
}
|
||||
ports.port1.onmessage = event => end(event.data?.ok ? null : new Error(event.data?.error || 'Offline setup failed'), event.data);
|
||||
worker.postMessage({type:'offline-config', account, mode}, [ports.port2]);
|
||||
});
|
||||
}
|
||||
async function getWorker(register) {
|
||||
const sw = navigator.serviceWorker;
|
||||
if (sw.controller) return sw.controller;
|
||||
if (register) await sw.register('/offline-worker.js', {scope:'/'});
|
||||
const registration = await sw.getRegistration('/');
|
||||
if (!registration) throw new Error('Offline worker not installed');
|
||||
const active = registration.active || (await sw.ready).active;
|
||||
return active;
|
||||
}
|
||||
function waitForControl() {
|
||||
const sw = navigator.serviceWorker;
|
||||
if (sw.controller) return Promise.resolve();
|
||||
return new Promise((resolve, reject) => {
|
||||
function finish() {
|
||||
clearTimeout(timer);
|
||||
sw.removeEventListener('controllerchange', finish);
|
||||
if (sw.controller) resolve(); else reject(new Error('Offline worker not controlling this page'));
|
||||
}
|
||||
const timer = setTimeout(finish, 8000);
|
||||
sw.addEventListener('controllerchange', finish);
|
||||
if (sw.controller) finish();
|
||||
});
|
||||
}
|
||||
|
||||
Alpine.store('offline', {
|
||||
enabled: !!account && (prefs.enabled === true || ['manual','auto'].includes(initialMode)),
|
||||
manual: !!account && (initialMode === 'manual' || prefs.enabled && prefs.manual === true),
|
||||
active: false, automatic:false, busy:false, saving:false, bytes:0, items:[], error:'',
|
||||
limitBytes: Math.max(minLimit, Math.min(maxLimit, Number(prefs.limitBytes) || defaultLimit)),
|
||||
supported: !!(account && window.isSecureContext && navigator.serviceWorker && navigator.storage?.getDirectory &&
|
||||
navigator.locks?.request && globalThis.FileSystemFileHandle?.prototype.createWritable && window.indexedDB && globalThis.OfflineCatalog),
|
||||
|
||||
init() {
|
||||
if (!this.supported) return;
|
||||
this.active = this.enabled && (this.manual || initialMode === 'auto' || !navigator.onLine);
|
||||
this.automatic = this.active && !this.manual;
|
||||
document.documentElement.classList.toggle('offline-active', this.active);
|
||||
if (this.enabled || prefs.used) this.refresh();
|
||||
if ('BroadcastChannel' in window) {
|
||||
channel = new BroadcastChannel(prefKey);
|
||||
channel.onmessage = ({data}) => {
|
||||
if (data === 'cache') {
|
||||
if (this.active) window.dispatchEvent(new CustomEvent('furumusic:offline-catalog'));
|
||||
else this.refresh();
|
||||
}
|
||||
if (data === 'queue') this.drain();
|
||||
};
|
||||
}
|
||||
window.addEventListener('storage', event => {
|
||||
if (event.key !== prefKey) return;
|
||||
const current = read(prefKey);
|
||||
if (current.limitBytes && current.limitBytes !== this.limitBytes) {
|
||||
this.limitBytes = current.limitBytes;
|
||||
transfer?.abort();
|
||||
}
|
||||
blocked = false;
|
||||
if (this.enabled && !this.active) this.drain();
|
||||
});
|
||||
navigator.serviceWorker.addEventListener('message', ({data}) => {
|
||||
if (String(data?.account) !== account) return;
|
||||
if (data.type === 'offline-purge') {
|
||||
localStorage.removeItem(prefKey);
|
||||
localStorage.removeItem(stateKey);
|
||||
this.enabled = this.manual = this.active = false;
|
||||
this.items = []; this.bytes = 0;
|
||||
this.stopTraffic();
|
||||
location.replace('/');
|
||||
} else if (data.type === 'offline-mode' && !this.busy) {
|
||||
this.enabled = data.mode !== 'disabled';
|
||||
this.manual = data.mode === 'manual';
|
||||
this.apply(data.mode);
|
||||
this.persist();
|
||||
}
|
||||
});
|
||||
window.addEventListener('offline', () => this.lost());
|
||||
window.addEventListener('online', () => this.probe());
|
||||
document.addEventListener('visibilitychange', () => { if (!document.hidden) this.probe(); });
|
||||
if (this.enabled) {
|
||||
this.scheduleProbe();
|
||||
if (!this.active) this.drain();
|
||||
else if (!this.manual && navigator.onLine) this.probe();
|
||||
}
|
||||
},
|
||||
persist() {
|
||||
localStorage.setItem(prefKey, JSON.stringify({enabled:this.enabled, manual:this.manual, used:true, limitBytes:this.limitBytes}));
|
||||
},
|
||||
formatBytes(value) {
|
||||
const bytes = Math.max(0, Number(value) || 0);
|
||||
const step = bytes >= 1e9 ? 3 : bytes >= 1e6 ? 2 : bytes >= 1000 ? 1 : 0;
|
||||
return new Intl.NumberFormat(document.documentElement.lang, {style:'unit',unit:['byte','kilobyte','megabyte','gigabyte'][step],maximumFractionDigits:2}).format(bytes / 1000 ** step);
|
||||
},
|
||||
async refresh() {
|
||||
const version = ++listVersion;
|
||||
try {
|
||||
const [stats, records] = await Promise.all([catalog().stats(), catalog().list()]);
|
||||
if (version !== listVersion) return;
|
||||
this.bytes = stats.bytes;
|
||||
this.items = records.map(t => ({...t, artist: t.artist || (t.artists || []).map(a => a.name || a).join(', ')}));
|
||||
} catch { this.error = label('storage'); }
|
||||
},
|
||||
isSaved(track) {
|
||||
const id = globalThis.OfflineCatalog?.trackId(track);
|
||||
return !!track && this.items.some(t => t.id === id || (track.content_id && t.content_id === track.content_id));
|
||||
},
|
||||
async setEnabled(on) {
|
||||
if (this.busy || !!on === this.enabled) return;
|
||||
if (!this.supported) { this.error = label('unavailable'); return; }
|
||||
this.busy = true;
|
||||
this.error = '';
|
||||
++revision;
|
||||
try {
|
||||
if (on) {
|
||||
// Keep the permission request within the user's activation. Best-effort storage is usable too.
|
||||
const persistent = navigator.storage.persist?.().catch(() => false);
|
||||
const worker = await getWorker(true);
|
||||
await sendConfig(worker, 'online');
|
||||
await waitForControl();
|
||||
await persistent;
|
||||
this.enabled = true;
|
||||
this.manual = false;
|
||||
this.persist();
|
||||
await this.captureLibrary();
|
||||
await this.refresh();
|
||||
this.apply('online');
|
||||
const player = Alpine.store('player');
|
||||
if (player?.isPlaying && !player._cachePlayCounted) {
|
||||
player._cachePlayCounted = true;
|
||||
this.played(player.currentTrack);
|
||||
}
|
||||
} else {
|
||||
this.stopTraffic();
|
||||
await sendConfig(await getWorker(false), 'disabled');
|
||||
this.enabled = this.manual = false;
|
||||
this.persist();
|
||||
this.apply('disabled');
|
||||
}
|
||||
} catch { this.error = label('setup'); }
|
||||
finally { this.busy = false; this.scheduleProbe(); }
|
||||
},
|
||||
async setManual(manual) {
|
||||
if (!this.enabled || this.busy || !!manual === this.manual) return;
|
||||
this.busy = true; this.error = '';
|
||||
++revision;
|
||||
this.stopTraffic();
|
||||
try {
|
||||
const mode = manual ? 'manual' : 'auto';
|
||||
await sendConfig(await getWorker(false), mode);
|
||||
this.manual = !!manual;
|
||||
this.persist();
|
||||
this.apply(mode);
|
||||
} catch { this.error = label('setup'); }
|
||||
finally { this.busy = false; this.scheduleProbe(); }
|
||||
if (!this.manual) this.probe();
|
||||
},
|
||||
stopTraffic() {
|
||||
clearTimeout(probeTimer);
|
||||
clearTimeout(retryTimer);
|
||||
probing?.abort();
|
||||
transfer?.abort();
|
||||
},
|
||||
async lost() {
|
||||
if (!this.enabled || this.manual || this.active || this.busy) return;
|
||||
const version = revision;
|
||||
transfer?.abort();
|
||||
try {
|
||||
const worker = await getWorker(false);
|
||||
if (version !== revision || this.manual) return;
|
||||
await sendConfig(worker, 'auto');
|
||||
if (version === revision) this.apply('auto');
|
||||
} catch { if (version === revision) this.apply('auto'); }
|
||||
},
|
||||
scheduleProbe() {
|
||||
clearTimeout(probeTimer);
|
||||
if (!this.enabled || this.manual) return;
|
||||
probeTimer = setTimeout(() => this.probe(), this.active ? 5000 : 15000);
|
||||
},
|
||||
networkResult(ok) {
|
||||
if (!this.enabled || this.active || this.busy) return;
|
||||
if (ok) lastSuccess = Date.now();
|
||||
else this.probe(true);
|
||||
},
|
||||
async probe(force = false) {
|
||||
if (!this.enabled || this.manual || this.busy || probing) return;
|
||||
if (!navigator.onLine) { await this.lost(); this.scheduleProbe(); return; }
|
||||
if (!force && !this.active && Date.now() - lastSuccess < 8000) { this.scheduleProbe(); return; }
|
||||
const version = revision;
|
||||
const abort = probing = new AbortController();
|
||||
const timeout = setTimeout(() => abort.abort(), 4000);
|
||||
try {
|
||||
const res = await nativeFetch('/offline-probe', {cache:'no-store', signal:abort.signal, redirect:'error'});
|
||||
if (version !== revision || this.manual || !this.enabled) return;
|
||||
const identity = res.headers.get('X-Furumusic-Player-Account');
|
||||
if ((res.status === 401 && identity === '0') || (res.status === 204 && identity && identity !== account)) {
|
||||
location.replace('/'); return;
|
||||
}
|
||||
if (res.status !== 204 || identity !== account) throw new Error('Unreachable');
|
||||
lastSuccess = Date.now();
|
||||
if (this.active) {
|
||||
await sendConfig(await getWorker(false), 'online');
|
||||
if (version === revision) this.apply('online');
|
||||
}
|
||||
} catch { if (version === revision) await this.lost(); }
|
||||
finally { clearTimeout(timeout); if (probing === abort) probing = null; this.scheduleProbe(); }
|
||||
},
|
||||
apply(mode) {
|
||||
const active = mode === 'manual' || mode === 'auto';
|
||||
const changed = active !== this.active;
|
||||
this.active = active; this.automatic = mode === 'auto';
|
||||
document.documentElement.classList.toggle('offline-active', active);
|
||||
if (active) { clearTimeout(retryTimer); transfer?.abort(); }
|
||||
this.scheduleProbe();
|
||||
if (changed) {
|
||||
window.dispatchEvent(new CustomEvent('furumusic:offline-mode', {detail:{active}}));
|
||||
}
|
||||
if (!active && this.enabled) this.drain();
|
||||
},
|
||||
async captureLibrary() {
|
||||
const user = Alpine.store('user'), playlists = Alpine.store('playlists'), library = Alpine.store('library');
|
||||
if (user?.profile) await catalog().observe('/api/player/me', user.profile);
|
||||
if (playlists?.list?.length) await catalog().observe('/api/player/playlists', playlists.list);
|
||||
if (library?.currentPlaylist) await catalog().observe('/api/player/playlists/'+library.currentPlaylist.id, library.currentPlaylist);
|
||||
// Fields that may have loaded before the opt-in, including playlist membership.
|
||||
await Promise.allSettled(['/api/player/me','/api/player/playlists','/api/player/likes','/api/player/follows','/api/player/pins'].map(async path => {
|
||||
const response = await playerFetch(path);
|
||||
if (response.ok) await catalog().observe(path, await response.json());
|
||||
}));
|
||||
},
|
||||
observe(url, response) {
|
||||
if (!this.enabled || this.active || !response.ok ||
|
||||
!/^\/api\/player\/(?:me|likes|follows|pins|playlists(?:\/-?\d+)?|artists(?:\/\d+)?)$/.test(url.pathname)) return;
|
||||
response.clone().json().then(value => catalog().observe(url.href, value)).catch(() => {});
|
||||
},
|
||||
localResponse(request) { return catalog().respond(request); },
|
||||
async played(track) {
|
||||
if (!this.enabled || !eligible(track)) return;
|
||||
try {
|
||||
await catalog().touch(track);
|
||||
if (!this.active) await this.saveTrack(track);
|
||||
} catch { this.error = label('storage'); }
|
||||
},
|
||||
async saveTrack(track) {
|
||||
if (!this.enabled || this.active || !eligible(track)) return;
|
||||
try {
|
||||
await catalog().enqueue(track);
|
||||
channel?.postMessage('queue');
|
||||
this.drain();
|
||||
} catch { this.error = label('storage'); }
|
||||
},
|
||||
async drain() {
|
||||
if (blocked || !this.enabled || this.active || !this.supported) return;
|
||||
if (draining) { wakeQueue = true; return; }
|
||||
clearTimeout(retryTimer);
|
||||
draining = true;
|
||||
const run = async () => {
|
||||
while (this.enabled && !this.active && !blocked) {
|
||||
const [track] = await catalog().pending();
|
||||
if (!track || this.active || !this.enabled) break;
|
||||
transfer = new AbortController();
|
||||
this.saving = true;
|
||||
try {
|
||||
await catalog().save(track, {signal:transfer.signal, limitBytes:this.limitBytes,
|
||||
fetch:window.fetch.bind(window),
|
||||
playlist:Alpine.store('library')?.currentPlaylist,
|
||||
release:Alpine.store('library')?.currentRelease});
|
||||
retryDelay = 5000;
|
||||
this.error = ''; channel?.postMessage('cache'); await this.refresh();
|
||||
} catch (err) {
|
||||
if (!transfer.signal.aborted) {
|
||||
if (err.name === 'QuotaExceededError') { blocked = true; this.error = label('full'); }
|
||||
else if (err.name === 'NotFoundError') {
|
||||
await catalog().dequeue(track.id);
|
||||
continue;
|
||||
} else {
|
||||
this.error = label('download');
|
||||
retryTimer = setTimeout(() => this.drain(), retryDelay);
|
||||
retryDelay = Math.min(retryDelay * 2, 300000);
|
||||
}
|
||||
}
|
||||
break;
|
||||
} finally { transfer = null; this.saving = false; }
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (navigator.locks) await navigator.locks.request(prefKey + '.queue', {ifAvailable:true}, lock => lock && run());
|
||||
else await run();
|
||||
} catch { this.error = label('storage'); }
|
||||
finally {
|
||||
draining = false;
|
||||
if (wakeQueue) { wakeQueue = false; this.drain(); }
|
||||
}
|
||||
},
|
||||
setLimit(bytes) {
|
||||
if (!Number.isFinite(bytes)) return;
|
||||
this.limitBytes = Math.round(Math.max(minLimit, Math.min(maxLimit, bytes)));
|
||||
transfer?.abort(); blocked = false; this.error = '';
|
||||
this.persist();
|
||||
this.drain();
|
||||
},
|
||||
async removeTrack(id) {
|
||||
transfer?.abort();
|
||||
try {
|
||||
await catalog().remove(id);
|
||||
blocked = false; this.error = ''; await this.refresh(); channel?.postMessage('cache');
|
||||
if (this.active) window.dispatchEvent(new CustomEvent('furumusic:offline-catalog'));
|
||||
this.drain();
|
||||
} catch { this.error = label('storage'); }
|
||||
},
|
||||
async clearCache() {
|
||||
transfer?.abort();
|
||||
try {
|
||||
await catalog().clear();
|
||||
const profile = Alpine.store('user')?.profile;
|
||||
if (this.enabled && profile) await catalog().observe('/api/player/me', profile);
|
||||
localStorage.removeItem(stateKey);
|
||||
this.error = ''; blocked = false; await this.refresh(); channel?.postMessage('cache');
|
||||
if (this.enabled && !this.active) await this.captureLibrary();
|
||||
if (this.active) window.dispatchEvent(new CustomEvent('furumusic:offline-catalog'));
|
||||
} catch { this.error = label('storage'); }
|
||||
},
|
||||
saveState(state) {
|
||||
if (this.enabled) { try { localStorage.setItem(stateKey, JSON.stringify(state)); } catch {} }
|
||||
},
|
||||
state() { return read(stateKey); },
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,64 @@
|
||||
<section class="user-settings-section offline-settings" aria-labelledby="offline-settings-title" @keydown.space.stop
|
||||
x-data="{
|
||||
get offline() { return $store.offline }, min: 100000000, max: 512000000000, draft: null, visibleTracks: 30,
|
||||
marks: [100000000,1000000000,10000000000,100000000000,512000000000],
|
||||
position(bytes) { return 100 * Math.log(Math.max(this.min, bytes) / this.min) / Math.log(this.max / this.min) },
|
||||
bytesAt(position) {
|
||||
const bytes = this.min * Math.pow(this.max / this.min, Number(position) / 100);
|
||||
return Math.min(this.max, Math.max(this.min, Math.round(bytes)));
|
||||
}
|
||||
}">
|
||||
<div class="user-settings-section-head">
|
||||
<h4 id="offline-settings-title" tabindex="-1">{{ t.player_offline_listening }}</h4>
|
||||
<button type="button" class="offline-switch-row" role="switch" aria-label="{{ t.player_offline_enable }}"
|
||||
:aria-checked="offline.enabled" :disabled="offline.busy || (!offline.supported && !offline.enabled)"
|
||||
@click="offline.setEnabled(!offline.enabled)">
|
||||
<span class="offline-switch" aria-hidden="true"></span>
|
||||
</button>
|
||||
</div>
|
||||
<p role="status" x-text="offline.busy && !offline.enabled ? '{{ t.player_offline_preparing }}' : offline.supported ? '{{ t.player_offline_hint }}' : '{{ t.player_offline_unsupported }}'"></p>
|
||||
<div class="offline-limit" x-show="offline.enabled" x-cloak>
|
||||
<div class="offline-limit-label">
|
||||
<label for="offline-limit">{{ t.player_offline_limit }}</label>
|
||||
<output for="offline-limit" x-text="offline.formatBytes(draft ?? offline.limitBytes)"></output>
|
||||
</div>
|
||||
<div class="offline-scale">
|
||||
<div class="offline-scale-marks" aria-hidden="true">
|
||||
<template x-for="mark in marks" :key="mark">
|
||||
<span :style="{left: position(mark) + '%'}" x-text="offline.formatBytes(mark)"></span>
|
||||
</template>
|
||||
</div>
|
||||
<input id="offline-limit" type="range" min="0" max="100" step="0.5"
|
||||
:value="position(offline.limitBytes)" :aria-valuetext="offline.formatBytes(draft ?? offline.limitBytes)"
|
||||
@input="draft = bytesAt($el.value)" @change="offline.setLimit(bytesAt($el.value)); draft = null">
|
||||
</div>
|
||||
</div>
|
||||
<p role="status" x-show="offline.saving" x-cloak>{{ t.player_offline_saving }}</p>
|
||||
<p class="offline-error" role="alert" x-show="offline.error" x-text="offline.error"></p>
|
||||
<template x-if="offline.enabled || offline.items.length">
|
||||
<div class="offline-saved">
|
||||
<div class="offline-saved-summary">
|
||||
<div><strong>{{ t.player_offline_saved }}</strong>
|
||||
<small x-text="formatArtistCount(offline.items.length, 'tracks') + ' · ' + offline.formatBytes(offline.bytes)"></small>
|
||||
</div>
|
||||
<button type="button" class="offline-manage" x-show="offline.items.length" :disabled="offline.busy"
|
||||
@click="if (window.confirm('{{ t.player_offline_confirm_clear }}')) offline.clearCache()">{{ t.player_offline_clear }}</button>
|
||||
</div>
|
||||
<p x-show="!offline.items.length">{{ t.player_offline_empty }}</p>
|
||||
<ul class="offline-saved-list" x-show="offline.items.length" aria-label="{{ t.player_offline_saved }}">
|
||||
<template x-for="track in offline.items.slice(0, visibleTracks)" :key="track.id">
|
||||
<li><div><strong x-text="track.title"></strong><small x-text="track.artist"></small></div>
|
||||
<span class="offline-track-size" x-text="offline.formatBytes(track.bytes)"></span>
|
||||
<button type="button" :disabled="offline.busy"
|
||||
:aria-label="'{{ t.player_offline_remove }} · ' + track.title" title="{{ t.player_offline_remove }}"
|
||||
@click="offline.removeTrack(track.id)">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="M3 6h18M9 6V3h6v3M6 6l1 15h10l1-15M10 10v7m4-7v7"/></svg>
|
||||
</button>
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
<button type="button" class="offline-manage" x-show="offline.items.length > visibleTracks"
|
||||
@click="visibleTracks += 30">{{ t.player_offline_show_more }}</button>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
@@ -0,0 +1,54 @@
|
||||
html:not(.offline-active) [data-offline-only], html.offline-active [data-online-only],
|
||||
.offline-active :is(.device-popover,.user-settings-devices) > :not([data-offline-only]) {display:none !important}
|
||||
.offline-account {padding:8px 8px 9px; border-bottom:1px solid var(--border-color); margin-bottom:3px}
|
||||
.offline-account-summary,.offline-limit-label,.offline-saved-summary {display:flex; justify-content:space-between; align-items:center; gap:8px}
|
||||
.offline-account-summary > div,.offline-saved-summary > div,.offline-saved-list li > div {min-width:0}
|
||||
.offline-account strong,.offline-saved-summary strong {display:block; font-size:13px; font-weight:600; line-height:1.3}
|
||||
.offline-account small,.offline-saved small,.offline-track-size {display:block; color:var(--text-subdued); font-size:12px; font-variant-numeric:tabular-nums}
|
||||
.offline-manage,.offline-switch-row,.offline-saved-list button {border:0; border-radius:6px; color:var(--text-secondary); background:transparent; font:inherit; cursor:pointer}
|
||||
.offline-manage {flex:none; padding:6px; font-size:12px; text-decoration:underline; text-underline-offset:3px}
|
||||
.offline-manage:is(:hover,:focus-visible),.offline-saved-list button:is(:hover,:focus-visible) {background:var(--bg-active); color:var(--text-primary)}
|
||||
.offline-switch-row {display:flex; align-items:center; justify-content:space-between; gap:8px; min-height:30px; padding:0; text-align:left}
|
||||
.offline-account .offline-switch-row {width:100%; margin-top:3px; font-size:12px}
|
||||
.offline-switch-row:focus-visible,.offline-manage:focus-visible,.offline-saved-list button:focus-visible,.offline-scale input:focus-visible {outline:2px solid var(--accent); outline-offset:2px}
|
||||
.offline-switch-row:disabled,.offline-saved button:disabled {opacity:.5; cursor:default}
|
||||
.offline-switch {position:relative; display:block; flex:none; width:32px; height:18px; border-radius:99px; background:var(--bg-active); border:1px solid var(--text-subdued)}
|
||||
.offline-switch::before {content:""; position:absolute; top:2px; left:2px; width:12px; height:12px; border-radius:50%; background:var(--text-secondary); transition:transform .12s}
|
||||
[aria-checked="true"] > .offline-switch {background:var(--accent); border-color:var(--accent)}
|
||||
[aria-checked="true"] > .offline-switch::before {background:var(--bg-primary); transform:translateX(14px)}
|
||||
.offline-settings .user-settings-section-head {align-items:center}
|
||||
.user-settings-overlay {width:100%; height:100%; max-width:none; max-height:none; margin:0; border:0; padding:0; color:var(--text-primary)}
|
||||
.user-settings-overlay:not([open]) {display:none}
|
||||
.user-settings-overlay::backdrop {background:transparent}
|
||||
.user-settings-overlay h3:focus {outline:none}
|
||||
.offline-settings .user-settings-section-head button {padding-inline:5px; min-width:44px; min-height:38px; justify-content:center}
|
||||
.offline-settings h4:focus {outline:none}
|
||||
.offline-limit {margin:16px 0 0}
|
||||
.offline-limit label,.offline-limit output {font-size:13px}
|
||||
.offline-limit output {font-variant-numeric:tabular-nums; color:var(--text-secondary)}
|
||||
.offline-scale {margin:10px 0 0}
|
||||
.offline-scale-marks {position:relative; margin-inline:8px; height:17px; color:var(--text-subdued); font-size:10px; font-variant-numeric:tabular-nums}
|
||||
.offline-scale-marks span {position:absolute; transform:translateX(-50%); white-space:nowrap}
|
||||
.offline-scale-marks span:first-of-type {transform:none}
|
||||
.offline-scale-marks span:last-of-type {transform:translateX(-100%)}
|
||||
.offline-scale input {display:block; width:100%; height:20px; margin:0; accent-color:var(--accent)}
|
||||
.offline-saved {margin-top:16px}
|
||||
.offline-saved-list {list-style:none; margin:8px 0 0; padding:0; max-height:min(28dvh,220px); overflow:auto; overscroll-behavior:contain; scrollbar-width:thin}
|
||||
.offline-saved-list li {display:grid; grid-template-columns:minmax(0,1fr) auto auto; align-items:center; gap:8px; min-height:40px; border-top:1px solid var(--border-color)}
|
||||
.offline-saved-list strong,.offline-saved-list small {display:block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap}
|
||||
.offline-saved-list strong {font-size:13px; font-weight:500}
|
||||
.offline-saved-list button {display:grid; place-items:center; width:36px; height:36px}
|
||||
.offline-saved-list svg,.offline-topbar-state svg {width:17px; height:17px; flex:none}
|
||||
.offline-settings .offline-error {color:var(--error, #edadaa)}
|
||||
.offline-topbar-state {display:inline-flex; align-items:center; gap:5px; flex:none; color:var(--text-secondary); font-size:12px; font-weight:600}
|
||||
.offline-devices-note {padding:9px; color:var(--text-secondary); font-size:13px}
|
||||
@media(max-width:600px) {
|
||||
.offline-account .offline-switch-row,.offline-manage,.offline-saved-list button {min-height:40px}
|
||||
.offline-topbar-state span {position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%)}
|
||||
}
|
||||
@media(max-width:360px) {
|
||||
.offline-scale-marks span:nth-last-of-type(2) {transform:translateX(-100%)}
|
||||
}
|
||||
@media(prefers-reduced-motion: reduce) {
|
||||
.offline-switch::before {transition:none}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<button data-member-only type="button" class="release-action-btn secondary collection-pin" x-show="target" x-cloak
|
||||
<button data-online-only data-member-only type="button" class="release-action-btn secondary collection-pin" x-show="target" x-cloak
|
||||
:aria-pressed="$store.pins.has(target)" :disabled="$store.pins.busy" @click.stop="$store.pins.toggle(target)"
|
||||
:aria-label="$store.pins.has(target) ? '{{ t.player_sidebar_unpin }}' : '{{ t.player_sidebar_pin }}'"
|
||||
:title="$store.pins.has(target) ? '{{ t.player_sidebar_unpin }}' : '{{ t.player_sidebar_pin }}'">
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
</div>
|
||||
<p class="playlist-heading-description" x-show="playlist.description" x-text="playlist.description"></p>
|
||||
{% if !guest %}
|
||||
<div class="playlist-heading-edit-actions" x-show="$store.playlists.canEditCurrent()" x-cloak>
|
||||
<div data-online-only class="playlist-heading-edit-actions" x-show="$store.playlists.canEditCurrent()" x-cloak>
|
||||
<button type="button" class="release-action-btn secondary playlist-edit-toggle" x-ref="edit"
|
||||
:disabled="editing && (header.busy || !header.canSave)"
|
||||
@click="$store.playlists.toggleEditCurrent()">
|
||||
@@ -61,7 +61,7 @@
|
||||
</div>
|
||||
{% if !guest %}
|
||||
<div class="playlist-heading-pin" x-show="target">{% include "player/pin_button.html" %}</div>
|
||||
<fieldset class="playlist-cover-editor" id="playlist-cover-editor" x-ref="coverEditor"
|
||||
<fieldset data-online-only class="playlist-cover-editor" id="playlist-cover-editor" x-ref="coverEditor"
|
||||
x-show="editing && header.pickerOpen" x-cloak :disabled="header.busy" aria-label="{{ t.player_playlist_cover }}"
|
||||
@pointerdown.window.capture="if (header.pickerOpen && !$el.contains($event.target) && !$refs.coverToggle.contains($event.target)) header.pickerOpen = false"
|
||||
@focusin.window="if (header.pickerOpen && !$el.contains($event.target) && !$refs.coverToggle.contains($event.target)) header.pickerOpen = false"
|
||||
|
||||
@@ -426,6 +426,7 @@
|
||||
});
|
||||
},
|
||||
checkpoint(player, completed = false, unloading = false) {
|
||||
if (Alpine.store('offline')?.active) return;
|
||||
const track = player.currentTrack;
|
||||
if (!track?.podcast) return;
|
||||
const payload = {
|
||||
|
||||
+178
-41
@@ -1,4 +1,3 @@
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js"></script>
|
||||
<script>
|
||||
const GUEST = {{ guest }};
|
||||
const SHARE_TOKEN = "{{ share_token }}";
|
||||
@@ -11,11 +10,30 @@ function redirectOnUnauthorized(status) {
|
||||
}
|
||||
|
||||
const playerFetch = window.fetch.bind(window);
|
||||
function playerOffline() { return window.Alpine?.store('offline')?.active === true; }
|
||||
function playbackSource(track) {
|
||||
const offline = Alpine.store('offline');
|
||||
if (!offline?.enabled || !offline.isSaved(track)) return track.stream_url;
|
||||
const remoteToken = track.federated_cache && track.content_id?.match(/^b3:([a-f0-9]{64})$/)?.[1];
|
||||
return track.stream_url === '/api/player/stream/' + track.id ||
|
||||
(remoteToken && track.stream_url === '/api/player/federation/cache/' + remoteToken)
|
||||
? track.stream_url + '?saved=1' : track.stream_url;
|
||||
}
|
||||
window.fetch = async (input, init) => {
|
||||
const response = await playerFetch(input, init);
|
||||
const url = new URL(input instanceof Request ? input.url : input, window.location.href);
|
||||
const offline = window.Alpine?.store('offline');
|
||||
if (offline?.active && !(offline.automatic && url.origin === location.origin && url.pathname === '/offline-probe')) {
|
||||
if (url.origin === location.origin && url.pathname.startsWith('/api/player/')) {
|
||||
const request = new Request(input instanceof Request ? input : url.href, init);
|
||||
const local = await offline.localResponse(request);
|
||||
if (local) return local;
|
||||
}
|
||||
return new Response(null, {status:503});
|
||||
}
|
||||
const response = await playerFetch(input, init);
|
||||
if (url.origin === window.location.origin && url.pathname.startsWith('/api/')) {
|
||||
redirectOnUnauthorized(response.status);
|
||||
if ((init?.method || input?.method || 'GET').toUpperCase() === 'GET') offline?.observe(url, response);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
@@ -549,6 +567,7 @@ document.addEventListener('alpine:init', () => {
|
||||
accessStatus: "anonymous",
|
||||
menuOpen: false,
|
||||
settingsOpen: false,
|
||||
settingsFocus: 'user-settings-title',
|
||||
lastfm: { configured: false, connected: false, username: null, reauth_required: false, last_error: null },
|
||||
lastfmBusy: false,
|
||||
|
||||
@@ -592,6 +611,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async loadLastfm() {
|
||||
if (playerOffline()) return;
|
||||
try {
|
||||
const res = await fetch('/api/player/lastfm/status');
|
||||
if (!res.ok) throw new Error('failed');
|
||||
@@ -651,15 +671,22 @@ document.addEventListener('alpine:init', () => {
|
||||
}
|
||||
},
|
||||
|
||||
openSettings() {
|
||||
openSettings(heading = 'user-settings-title') {
|
||||
this.settingsFocus = heading;
|
||||
this.menuOpen = false;
|
||||
this.settingsOpen = true;
|
||||
this.loadLastfm();
|
||||
Alpine.store('devices')?.loadFedDevices();
|
||||
if (!playerOffline()) {
|
||||
this.loadLastfm();
|
||||
Alpine.store('devices')?.loadFedDevices();
|
||||
}
|
||||
},
|
||||
|
||||
closeSettings() {
|
||||
this.settingsOpen = false;
|
||||
Alpine.nextTick(() => {
|
||||
const triggers = document.querySelectorAll('.sidebar-account-trigger, .mobile-account-chip');
|
||||
Array.from(triggers).find(button => button.getClientRects().length)?.focus({preventScroll:true});
|
||||
});
|
||||
},
|
||||
|
||||
initials() {
|
||||
@@ -761,6 +788,12 @@ document.addEventListener('alpine:init', () => {
|
||||
this.next();
|
||||
});
|
||||
|
||||
audio.addEventListener('playing', () => {
|
||||
if (!this._cachePlayCounted && Alpine.store('offline')?.enabled) {
|
||||
this._cachePlayCounted = true;
|
||||
Alpine.store('offline').played(this.currentTrack);
|
||||
}
|
||||
});
|
||||
audio.addEventListener('play', () => {
|
||||
this.isPlaying = true;
|
||||
if (!this._playbackStartedAt) this._playbackStartedAt = Math.floor(Date.now() / 1000);
|
||||
@@ -857,6 +890,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_maybePrefetchNext() {
|
||||
if (playerOffline()) return;
|
||||
if (this.currentTrack?.podcast) return;
|
||||
if (this.progress < 90 || !this.isPlaying) return;
|
||||
const queue = Alpine.store('queue');
|
||||
@@ -876,6 +910,8 @@ document.addEventListener('alpine:init', () => {
|
||||
_playLocal(track, options = {}) {
|
||||
if (this.currentTrack?.podcast) Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed);
|
||||
this._recordHistory('replaced');
|
||||
this._cachePlayCounted = false;
|
||||
this._offlineSession = playerOffline() || !!track.offline_remote;
|
||||
this.currentTrack = track;
|
||||
this._historyTrack = track;
|
||||
this._prefetchedQueueKey = null;
|
||||
@@ -883,19 +919,12 @@ document.addEventListener('alpine:init', () => {
|
||||
this._localSourceTrackId = track.id;
|
||||
this._historyRecorded = false;
|
||||
this._resetPlaybackTracking();
|
||||
audio.src = track.stream_url;
|
||||
audio.src = playbackSource(track);
|
||||
const seekSeconds = Number(options.position_seconds || 0);
|
||||
this.currentTime = seekSeconds;
|
||||
this.duration = Number(track.duration_seconds || 0);
|
||||
this.progress = this.duration > 0 ? seekSeconds / this.duration * 100 : 0;
|
||||
if (seekSeconds > 0) {
|
||||
const onLoaded = () => {
|
||||
audio.currentTime = seekSeconds;
|
||||
this._lastAudioTime = audio.currentTime || 0;
|
||||
audio.removeEventListener('loadedmetadata', onLoaded);
|
||||
};
|
||||
audio.addEventListener('loadedmetadata', onLoaded);
|
||||
}
|
||||
this._seekOnLoad(seekSeconds);
|
||||
if (options.paused) {
|
||||
audio.pause();
|
||||
this.isPlaying = false;
|
||||
@@ -905,11 +934,52 @@ document.addEventListener('alpine:init', () => {
|
||||
this._updateMediaSession();
|
||||
},
|
||||
|
||||
_seekOnLoad(seconds) {
|
||||
if (this._pendingSeek) audio.removeEventListener('loadedmetadata', this._pendingSeek);
|
||||
this._pendingSeek = null;
|
||||
if (seconds <= 0) return;
|
||||
this._pendingSeek = () => {
|
||||
audio.currentTime = seconds;
|
||||
this._lastAudioTime = audio.currentTime || 0;
|
||||
this._pendingSeek = null;
|
||||
};
|
||||
audio.addEventListener('loadedmetadata', this._pendingSeek, {once:true});
|
||||
},
|
||||
|
||||
_pauseLocal() {
|
||||
audio.pause();
|
||||
this.isPlaying = false;
|
||||
},
|
||||
|
||||
useOfflineCatalog(saved) {
|
||||
const byId = new Map(saved.map(t => [Number(t.id), t]));
|
||||
const byContent = new Map(saved.filter(t => t.content_id).map(t => [t.content_id, t]));
|
||||
const lookup = t => t && (byId.get(OfflineCatalog.trackId(t)) || byContent.get(t.content_id));
|
||||
const queue = Alpine.store('queue');
|
||||
queue.tracks = queue.tracks.map(lookup).filter(Boolean);
|
||||
const previous = this.currentTrack;
|
||||
const cached = lookup(previous);
|
||||
if (cached) {
|
||||
queue.syncCurrentIndexToTrack(cached);
|
||||
if (!this._offlineSession || this._localSourceTrackId !== cached.id) {
|
||||
const counted = this._cachePlayCounted;
|
||||
this._playLocal(cached, {paused:!this.isPlaying, position_seconds:this.currentTime});
|
||||
this._cachePlayCounted = counted;
|
||||
}
|
||||
} else if (previous) {
|
||||
this._offlineSession = true;
|
||||
this._seekOnLoad(0);
|
||||
this._pauseLocal();
|
||||
audio.removeAttribute('src');
|
||||
audio.load();
|
||||
this.currentTrack = this._historyTrack = this._localSourceTrackId = null;
|
||||
this.currentTime = this.progress = this.duration = 0;
|
||||
if ('mediaSession' in navigator) navigator.mediaSession.metadata = null;
|
||||
}
|
||||
if (!cached) queue.currentIndex = -1;
|
||||
Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||||
},
|
||||
|
||||
pause() {
|
||||
if (this._shouldSendRemote()) {
|
||||
this.isPlaying = false;
|
||||
@@ -1186,7 +1256,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_devicePlaybackStatePayload() {
|
||||
if (this.currentTrack?.podcast) return null;
|
||||
if (this.currentTrack?.podcast || this._offlineSession) return null;
|
||||
const queue = Alpine.store('queue');
|
||||
const track = this.currentTrack || queue?.tracks?.[queue.currentIndex] || null;
|
||||
if (!track && (!queue || queue.tracks.length === 0)) return null;
|
||||
@@ -1365,19 +1435,23 @@ document.addEventListener('alpine:init', () => {
|
||||
navigator.mediaSession.setActionHandler('seekto', (d) => { if (d.seekTime != null) this.seek(d.seekTime); });
|
||||
},
|
||||
|
||||
_buildStatePayload() {
|
||||
_buildStatePayload(forDeviceCache = false) {
|
||||
const queue = Alpine.store('queue');
|
||||
const localQueue = queue.tracks.filter(track => Number.isInteger(Number(track.id)));
|
||||
const currentLocalId = this.currentTrack && Number.isInteger(Number(this.currentTrack.id))
|
||||
? Number(this.currentTrack.id)
|
||||
: null;
|
||||
const idFor = track => {
|
||||
if (!track) return null;
|
||||
if (forDeviceCache && globalThis.OfflineCatalog) return OfflineCatalog.trackId(track);
|
||||
return !track.offline_remote && Number.isInteger(Number(track.id)) ? Number(track.id) : null;
|
||||
};
|
||||
const ids = queue.tracks.map(idFor).filter(id => id !== null);
|
||||
const currentLocalId = idFor(this.currentTrack);
|
||||
if (forDeviceCache && currentLocalId !== null && !ids.includes(currentLocalId)) ids.unshift(currentLocalId);
|
||||
return {
|
||||
current_track_id: currentLocalId,
|
||||
position_ms: Math.floor(this.currentTime * 1000),
|
||||
queue: localQueue.map(track => Number(track.id)),
|
||||
queue: ids,
|
||||
queue_position: currentLocalId == null
|
||||
? 0
|
||||
: Math.max(0, localQueue.findIndex(track => Number(track.id) === currentLocalId)),
|
||||
: Math.max(0, ids.indexOf(currentLocalId)),
|
||||
shuffle: this.shuffle,
|
||||
repeat_mode: this.repeatMode,
|
||||
volume: this.volume,
|
||||
@@ -1385,6 +1459,8 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_saveState() {
|
||||
if (!GUEST && this.currentTrack && Alpine.store('offline')?.enabled) Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||||
if (playerOffline() || this._offlineSession) return;
|
||||
if (this.currentTrack?.podcast) { Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed); return; }
|
||||
if (GUEST) return;
|
||||
const queue = Alpine.store('queue');
|
||||
@@ -1398,6 +1474,8 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_saveStateSync() {
|
||||
if (!GUEST && this.currentTrack && Alpine.store('offline')?.enabled) Alpine.store('offline').saveState(this._buildStatePayload(true));
|
||||
if (playerOffline() || this._offlineSession) return;
|
||||
if (this.currentTrack?.podcast) { Alpine.store('podcasts')?.checkpoint(this, !!this.currentTrack.podcast_completed, true); return; }
|
||||
if (GUEST) return;
|
||||
const queue = Alpine.store('queue');
|
||||
@@ -1410,9 +1488,15 @@ document.addEventListener('alpine:init', () => {
|
||||
async _restoreState() {
|
||||
if (GUEST) return;
|
||||
try {
|
||||
const res = await fetch('/api/player/state');
|
||||
if (!res.ok) return;
|
||||
const state = await res.json();
|
||||
const offline = playerOffline();
|
||||
const initialTrack = this.currentTrack;
|
||||
let state;
|
||||
if (offline) state = Alpine.store('offline').state();
|
||||
else {
|
||||
const res = await fetch('/api/player/state');
|
||||
if (!res.ok || playerOffline()) return;
|
||||
state = await res.json();
|
||||
}
|
||||
this.shuffle = state.shuffle || false;
|
||||
this.repeatMode = state.repeat_mode || 'off';
|
||||
this._setVolumeLocal(typeof state.volume === 'number' ? state.volume : 0.7);
|
||||
@@ -1427,6 +1511,7 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
if (tracksRes.ok) {
|
||||
const tracks = await tracksRes.json();
|
||||
if (playerOffline() !== offline || this.currentTrack !== initialTrack) return;
|
||||
if (tracks.length > 0) {
|
||||
const queue = Alpine.store('queue');
|
||||
queue.tracks = tracks;
|
||||
@@ -1440,20 +1525,15 @@ document.addEventListener('alpine:init', () => {
|
||||
if (currentTrack) {
|
||||
this.currentTrack = currentTrack;
|
||||
this._historyTrack = currentTrack;
|
||||
this._offlineSession = offline;
|
||||
this._cachePlayCounted = false;
|
||||
queue.syncCurrentIndexToTrack(currentTrack);
|
||||
this._localSourceTrackId = currentTrack.id;
|
||||
this._historyRecorded = false;
|
||||
this._resetPlaybackTracking();
|
||||
audio.src = currentTrack.stream_url;
|
||||
audio.src = playbackSource(currentTrack);
|
||||
// Seek to saved position once metadata is loaded
|
||||
const seekMs = state.position_ms || 0;
|
||||
if (seekMs > 0) {
|
||||
const onLoaded = () => {
|
||||
audio.currentTime = seekMs / 1000;
|
||||
audio.removeEventListener('loadedmetadata', onLoaded);
|
||||
};
|
||||
audio.addEventListener('loadedmetadata', onLoaded);
|
||||
}
|
||||
this._seekOnLoad((state.position_ms || 0) / 1000);
|
||||
this._updateMediaSession();
|
||||
}
|
||||
}
|
||||
@@ -1464,7 +1544,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_recordHistory(endedReason, unloading = false) {
|
||||
if (GUEST) return;
|
||||
if (GUEST || playerOffline() || this._offlineSession) return;
|
||||
const track = this._historyTrack;
|
||||
if (this._historyRecorded || !track || !this._playbackStartedAt) return;
|
||||
if (!Number.isInteger(Number(track.id)) || track.federated_cache) return;
|
||||
@@ -1486,6 +1566,7 @@ document.addEventListener('alpine:init', () => {
|
||||
// Retry the captured event, never the next track. The server deduplicates by listen_id.
|
||||
const send = async () => {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
if (playerOffline()) return;
|
||||
try {
|
||||
const response = await fetch('/api/player/history', {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'}, body, keepalive: true,
|
||||
@@ -1547,6 +1628,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_sendNowPlaying() {
|
||||
if (playerOffline() || this._offlineSession) return;
|
||||
if (GUEST) return;
|
||||
if (this._nowPlayingSent || !this.currentTrack) return;
|
||||
if (!Number.isInteger(Number(this.currentTrack.id)) || this.currentTrack.federated_cache) {
|
||||
@@ -1635,6 +1717,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async heartbeat() {
|
||||
if (playerOffline()) return;
|
||||
try {
|
||||
const res = await fetch('/api/player/devices/heartbeat', {
|
||||
method: 'POST',
|
||||
@@ -1647,6 +1730,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async poll() {
|
||||
if (playerOffline()) return;
|
||||
try {
|
||||
const res = await fetch('/api/player/devices/poll', {
|
||||
method: 'POST',
|
||||
@@ -1655,6 +1739,7 @@ document.addEventListener('alpine:init', () => {
|
||||
});
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
if (playerOffline()) return;
|
||||
if (data.playback_state) this._lastPlaybackState = data.playback_state;
|
||||
this._apply(data);
|
||||
if (this.open || (++this._fedRefreshTick % 10 === 0)) {
|
||||
@@ -1680,6 +1765,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
_apply(data) {
|
||||
if (playerOffline()) return;
|
||||
const previousJamId = this.currentJamId;
|
||||
this.activeDeviceId = data.active_device_id || null;
|
||||
this.devices = Array.isArray(data.devices) ? data.devices : [];
|
||||
@@ -1748,6 +1834,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
hasJoinedJam() {
|
||||
if (playerOffline()) return false;
|
||||
return this.jams.some(jam => jam.is_member);
|
||||
},
|
||||
|
||||
@@ -1784,6 +1871,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
shouldPlayJamLocally() {
|
||||
if (playerOffline()) return false;
|
||||
return this.jamLocalPlayback && this.canPlayJamLocally();
|
||||
},
|
||||
|
||||
@@ -1814,7 +1902,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
isActive() {
|
||||
if (GUEST) return true;
|
||||
if (GUEST || playerOffline()) return true;
|
||||
if (this.isControllingRemoteJam()) return false;
|
||||
return !this.activeDeviceId || this.activeDeviceId === this.id;
|
||||
},
|
||||
@@ -1859,6 +1947,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
async loadFedDevices() {
|
||||
if (playerOffline()) return;
|
||||
try {
|
||||
const res = await fetch('/api/player/fed-devices');
|
||||
if (!res.ok) {
|
||||
@@ -2658,6 +2747,10 @@ document.addEventListener('alpine:init', () => {
|
||||
if (GUEST) return;
|
||||
if (this._hashNav) return;
|
||||
const hash = location.hash || '#artists';
|
||||
if (playerOffline() && (/^#(?:listening|podcasts?|artistfed|releasefed|similar|share)(?:[/?]|$)/.test(hash) ||
|
||||
(hash.startsWith('#search?') && new URLSearchParams(hash.slice(8)).get('mode') === 'lyrics'))) {
|
||||
return this.openCollectionView('offline_unavailable', hash, options);
|
||||
}
|
||||
const listening = hash.match(/^#listening(?:\/(history))?(?:\?(.*))?$/);
|
||||
if (listening) {
|
||||
return this.openListening(listening[1] || 'overview', {
|
||||
@@ -2903,7 +2996,9 @@ document.addEventListener('alpine:init', () => {
|
||||
if (version !== this._navigationVersion) return;
|
||||
this.currentArtist = artist;
|
||||
this.startArtistFederation(this.currentArtist.name);
|
||||
} catch {}
|
||||
} catch {
|
||||
if (playerOffline() && version === this._navigationVersion) this.view = 'offline_unavailable';
|
||||
}
|
||||
if (version === this._navigationVersion) this._afterNavigation(options);
|
||||
},
|
||||
|
||||
@@ -2984,6 +3079,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
startArtistFederation(name) {
|
||||
if (playerOffline()) return;
|
||||
this.artistFederation = { loading: true, error: '', releases: [], tracks: [] };
|
||||
const source = new EventSource(
|
||||
`/api/player/federation/artists/events?name=${encodeURIComponent(name)}`
|
||||
@@ -3359,7 +3455,10 @@ document.addEventListener('alpine:init', () => {
|
||||
}
|
||||
this.startReleaseFederation(this.currentRelease);
|
||||
} catch {
|
||||
if (version === this._navigationVersion) this.releaseUnavailable = true;
|
||||
if (version === this._navigationVersion) {
|
||||
this.releaseUnavailable = true;
|
||||
if (playerOffline()) this.view = 'offline_unavailable';
|
||||
}
|
||||
}
|
||||
if (version === this._navigationVersion) this._afterNavigation(options);
|
||||
},
|
||||
@@ -3396,6 +3495,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
startReleaseFederation(release) {
|
||||
if (playerOffline()) return;
|
||||
const artistName = release?.artists?.[0]?.name;
|
||||
const artists = (release?.artists || []).map(artist => artist.name);
|
||||
const key = release?.federationRelease?.key ||
|
||||
@@ -3516,6 +3616,7 @@ document.addEventListener('alpine:init', () => {
|
||||
}
|
||||
this.currentPlaylist = playlist;
|
||||
if (navigation) this._afterNavigation(navigation);
|
||||
if (playerOffline()) return;
|
||||
const federationResponse = await fetch(`/api/player/playlists/${id}/federation-tracks`);
|
||||
if (federationResponse.ok) {
|
||||
const references = await federationResponse.json();
|
||||
@@ -3537,7 +3638,10 @@ document.addEventListener('alpine:init', () => {
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (current() && navigation && !this.currentPlaylist) this._afterNavigation(navigation);
|
||||
if (current() && navigation && !this.currentPlaylist) {
|
||||
if (playerOffline()) this.view = 'offline_unavailable';
|
||||
this._afterNavigation(navigation);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -3824,6 +3928,7 @@ document.addEventListener('alpine:init', () => {
|
||||
},
|
||||
|
||||
startFederationSearch(query) {
|
||||
if (playerOffline()) { this.stopFederationSearch(); return; }
|
||||
this._cancelFederationSearch?.();
|
||||
this.unifiedSearch = { artists: [], releases: [], tracks: [], podcasts: [] };
|
||||
this.failedFederationArtwork = new Set();
|
||||
@@ -6932,6 +7037,34 @@ document.addEventListener('alpine:init', () => {
|
||||
this.picker = null;
|
||||
},
|
||||
});
|
||||
|
||||
let catalogRevision = 0;
|
||||
async function refreshCatalog() {
|
||||
const version = ++catalogRevision;
|
||||
const library = Alpine.store('library'), offline = Alpine.store('offline');
|
||||
library.cancelPendingSearch();
|
||||
library.stopFederationSearch();
|
||||
library.stopArtistFederation();
|
||||
library.stopReleaseFederation();
|
||||
library._resetArtistList('all');
|
||||
library._hashNav = false;
|
||||
if (offline.active) {
|
||||
library.searchMode = 'normal';
|
||||
Alpine.store('playlists').stopEdit();
|
||||
}
|
||||
library._navigateFromHash({fromHash:true});
|
||||
for (const name of ['playlists','likes','follows','pins']) Alpine.store(name)?.reload();
|
||||
if (offline.active) {
|
||||
await offline.refresh();
|
||||
if (offline.active && catalogRevision === version) Alpine.store('player').useOfflineCatalog(offline.items);
|
||||
} else {
|
||||
Alpine.store('devices').heartbeat();
|
||||
Alpine.store('devices').poll();
|
||||
Alpine.store('user').loadLastfm();
|
||||
}
|
||||
}
|
||||
window.addEventListener('furumusic:offline-mode', refreshCatalog);
|
||||
window.addEventListener('furumusic:offline-catalog', refreshCatalog);
|
||||
});
|
||||
|
||||
function installConnectionFetchMonitor() {
|
||||
@@ -6943,7 +7076,8 @@ function installConnectionFetchMonitor() {
|
||||
const tracked = isTrackedPlayerRequest(args[0]);
|
||||
try {
|
||||
const response = await nativeFetch(...args);
|
||||
if (tracked) {
|
||||
if (tracked && !playerOffline()) {
|
||||
Alpine.store('offline')?.networkResult(response.status < 500);
|
||||
if (response.status >= 500) {
|
||||
Alpine.store('connection')?.recordFailure();
|
||||
} else {
|
||||
@@ -6952,7 +7086,10 @@ function installConnectionFetchMonitor() {
|
||||
}
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (tracked) Alpine.store('connection')?.recordFailure();
|
||||
if (tracked && !playerOffline() && error?.name !== 'AbortError') {
|
||||
Alpine.store('connection')?.recordFailure();
|
||||
Alpine.store('offline')?.networkResult(false);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
+41
-25
@@ -64,7 +64,7 @@
|
||||
<path d="M4 4.5A2.5 2.5 0 016.5 2H20v20H6.5A2.5 2.5 0 014 19.5z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="connection-alert"
|
||||
<div class="connection-alert" data-online-only
|
||||
x-show="$store.connection.disconnected"
|
||||
x-cloak
|
||||
:title="$store.connection.message()"
|
||||
@@ -78,6 +78,13 @@
|
||||
</svg>
|
||||
<span class="connection-alert-text">{{ t.player_connection_lost }}</span>
|
||||
</div>
|
||||
{% if !guest %}
|
||||
<span class="offline-topbar-state" data-offline-only role="status"
|
||||
:title="$store.offline.manual ? '{{ t.player_offline_cache_only }}' : '{{ t.player_offline_auto }}'">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M4 12V4h16v8m-5-4-4 4-2-2M4 15h16l1 5H3z"/></svg>
|
||||
<span>{{ t.player_offline_manual }}</span>
|
||||
</span>
|
||||
{% endif %}
|
||||
{% if guest %}
|
||||
<div class="guest-account">
|
||||
<strong>{{ t.guest_label }}</strong>
|
||||
@@ -93,7 +100,7 @@
|
||||
@focusout="if (!$el.contains($event.relatedTarget)) expanded=false"
|
||||
@resize.window="measure()">
|
||||
<div class="search-field">
|
||||
<button class="search-icon search-mode-toggle" type="button" @pointerdown.prevent @click="$store.library.toggleSearchMode(); $refs.searchInput.focus()" :aria-pressed="$store.library.searchMode==='lyrics'" :aria-label="$store.lyricsSearch.text($store.library.searchMode==='lyrics'?'normal':'lyrics')" :title="$store.lyricsSearch.text($store.library.searchMode==='lyrics'?'normal':'lyrics')">
|
||||
<button :disabled="$store.offline?.active" class="search-icon search-mode-toggle" type="button" @pointerdown.prevent @click="$store.library.toggleSearchMode(); $refs.searchInput.focus()" :aria-pressed="$store.library.searchMode==='lyrics'" :aria-label="$store.lyricsSearch.text($store.library.searchMode==='lyrics'?'normal':'lyrics')" :title="$store.lyricsSearch.text($store.library.searchMode==='lyrics'?'normal':'lyrics')">
|
||||
<svg x-show="$store.library.searchMode!=='lyrics'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
|
||||
<svg x-show="$store.library.searchMode==='lyrics'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M5 5h11M5 10h8M5 15h5M18 13v7M18 13l3-1"/><circle cx="15.5" cy="20" r="2.5"/></svg>
|
||||
</button>
|
||||
@@ -114,7 +121,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{% if downloads_enabled %}
|
||||
<button class="torrent-import-btn"
|
||||
<button class="torrent-import-btn" data-online-only
|
||||
@click="$store.torrents.open()"
|
||||
title="{{ t.player_import_torrent }}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
@@ -149,6 +156,12 @@
|
||||
{% include "player/collection.html" %}
|
||||
{% endif %}
|
||||
{% include "player/listening.html" %}
|
||||
<template x-if="$store.library.view === 'offline_unavailable'">
|
||||
<div class="empty-state" role="status">
|
||||
<p>{{ t.player_offline_page_missing }}</p>
|
||||
<a class="artist-link" href="#artists">{{ t.player_offline_open_catalog }}</a>
|
||||
</div>
|
||||
</template>
|
||||
<template x-if="$store.library.view === 'search'">
|
||||
<div>
|
||||
<div class="search-similarity-heading"
|
||||
@@ -283,7 +296,7 @@
|
||||
<span class="track-album">{% include "player/search_track_release.html" %}</span>
|
||||
<div class="track-actions">
|
||||
{% include "player/track_row_badges.html" %}
|
||||
<button data-member-only class="like-btn" :class="{ liked: $store.library.searchTrackLiked(track) }" @click.stop="track.federation_only ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)" title="{{ t.player_like }}">
|
||||
<button data-online-only data-member-only class="like-btn" :class="{ liked: $store.library.searchTrackLiked(track) }" @click.stop="track.federation_only ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)" title="{{ t.player_like }}">
|
||||
<svg viewBox="0 0 24 24" :fill="$store.library.searchTrackLiked(track) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
|
||||
</button>
|
||||
<button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}">
|
||||
@@ -341,7 +354,7 @@
|
||||
<template x-if="!artist.image_url">
|
||||
<span class="placeholder-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 10-16 0"/></svg></span>
|
||||
</template>
|
||||
<button data-member-only class="artist-follow-card-btn"
|
||||
<button data-online-only data-member-only class="artist-follow-card-btn"
|
||||
:class="{ followed: $store.follows.has(artist.id) }"
|
||||
@click.stop="$store.follows.toggle(artist.id)"
|
||||
:title="$store.follows.has(artist.id) ? '{{ t.player_unfollow_artist }}' : '{{ t.player_follow_artist }}'">
|
||||
@@ -361,7 +374,9 @@
|
||||
</div>
|
||||
<template x-if="!$store.library.loading && $store.library.artists.length === 0">
|
||||
<div class="empty-state">
|
||||
<p x-text="$store.library.view === 'my_uploads' ? '{{ t.player_no_uploaded_tracks }}' : '{{ t.artists_empty }}'"></p>
|
||||
<p x-show="$store.library.view === 'my_uploads'" x-text="$store.offline.active ? '{{ t.player_offline_empty_uploads }}' : '{{ t.player_no_uploaded_tracks }}'"></p>
|
||||
<p x-show="$store.library.view === 'artists'" x-text="$store.offline.active ? '{{ t.player_offline_empty }}' : '{{ t.artists_empty }}'"></p>
|
||||
<p data-offline-only>{{ t.player_offline_start }}</p>
|
||||
</div>
|
||||
</template>
|
||||
<template x-if="$store.library.loading && $store.library.artists.length === 0">
|
||||
@@ -423,7 +438,7 @@
|
||||
</svg>
|
||||
<span>{{ t.player_listen }}</span>
|
||||
</button>
|
||||
<button data-member-only class="release-action-btn secondary artist-follow-action"
|
||||
<button data-online-only data-member-only class="release-action-btn secondary artist-follow-action"
|
||||
x-show="$store.library.currentArtist.id"
|
||||
:class="{ followed: $store.follows.has($store.library.currentArtist.id) }"
|
||||
@click="$store.follows.toggle($store.library.currentArtist.id)"
|
||||
@@ -497,7 +512,7 @@
|
||||
<span></span>
|
||||
<div class="track-actions">
|
||||
{% include "player/track_row_badges.html" %}
|
||||
<button data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
|
||||
<button data-online-only data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
|
||||
<svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
|
||||
</button>
|
||||
<button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}">
|
||||
@@ -623,7 +638,7 @@
|
||||
</div>
|
||||
<span></span>
|
||||
<span class="track-actions">
|
||||
<button class="like-btn"
|
||||
<button data-online-only class="like-btn"
|
||||
:class="{ liked: $store.library.federationIsLiked(track) }"
|
||||
@click.stop="$store.library.toggleFederationLike(track)"
|
||||
title="{{ t.player_like }}">
|
||||
@@ -692,7 +707,7 @@
|
||||
<span></span>
|
||||
<div class="track-actions">
|
||||
{% include "player/track_row_badges.html" %}
|
||||
<button data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
|
||||
<button data-online-only data-member-only class="like-btn" :class="{ liked: $store.likes.has(track.id) }" @click.stop="$store.likes.toggle(track.id)" title="{{ t.player_like }}">
|
||||
<svg viewBox="0 0 24 24" :fill="$store.likes.has(track.id) ? 'currentColor' : 'none'" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 000-7.78z"/></svg>
|
||||
</button>
|
||||
<button class="track-action-btn queue-insert-btn queue-next-btn" @click.stop="$store.queue.addNextInQueue([track])" title="{{ t.player_play_next }}">
|
||||
@@ -747,7 +762,7 @@
|
||||
</div>
|
||||
<div class="release-title-row">
|
||||
<div class="release-title" x-text="$store.library.currentRelease.title"></div>
|
||||
<button class="like-btn like-btn-lg release-title-like"
|
||||
<button data-online-only class="like-btn like-btn-lg release-title-like"
|
||||
:class="{ liked: $store.library.isMixedReleaseLiked($store.library.currentRelease) }"
|
||||
@click.stop="$store.library.toggleMixedReleaseLike($store.library.currentRelease)"
|
||||
title="{{ t.player_like }}">
|
||||
@@ -775,7 +790,7 @@
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
|
||||
{{ t.player_info }}
|
||||
</button>
|
||||
<button data-member-only class="release-action-btn secondary release-share-btn"
|
||||
<button data-online-only data-member-only class="release-action-btn secondary release-share-btn"
|
||||
x-show="!$store.library.currentRelease.federated"
|
||||
@click.stop="$store.sharing.copyRelease($store.library.currentRelease, $event.currentTarget)"
|
||||
title="{{ t.player_share }}"
|
||||
@@ -857,7 +872,7 @@
|
||||
<span></span>
|
||||
<div class="track-actions">
|
||||
{% include "player/track_row_badges.html" %}
|
||||
<button data-member-only class="like-btn"
|
||||
<button data-online-only data-member-only class="like-btn"
|
||||
:class="{ liked: track.federation_pending ? $store.library.federationIsLiked(track._federationTrack) : $store.likes.has(track.id) }"
|
||||
@click.stop="track.federation_pending ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)"
|
||||
title="{{ t.player_like }}">
|
||||
@@ -908,7 +923,7 @@
|
||||
@dragover.prevent="$store.playlists.dragOver($event, idx)"
|
||||
@dragleave="$event.currentTarget.classList.remove('drag-over')"
|
||||
@drop.prevent="$event.currentTarget.classList.remove('drag-over'); $store.playlists.dropOn(idx)">
|
||||
<button data-member-only class="playlist-track-remove"
|
||||
<button data-online-only data-member-only class="playlist-track-remove"
|
||||
x-show="$store.playlists.isEditingCurrent()"
|
||||
x-cloak
|
||||
@click.stop="$store.playlists.removeCurrentTrack(track, idx)"
|
||||
@@ -951,7 +966,7 @@
|
||||
</template>
|
||||
</span>
|
||||
<div class="track-info playlist-track-info">
|
||||
<button data-member-only class="playlist-drag-handle"
|
||||
<button data-online-only data-member-only class="playlist-drag-handle"
|
||||
x-show="$store.playlists.isEditingCurrent() && !!track.playlist_track_id"
|
||||
x-cloak
|
||||
@mousedown.stop
|
||||
@@ -971,7 +986,7 @@
|
||||
<span></span>
|
||||
<div class="track-actions">
|
||||
{% include "player/track_row_badges.html" %}
|
||||
<button data-member-only class="like-btn"
|
||||
<button data-online-only data-member-only class="like-btn"
|
||||
:class="{ liked: track.federation_pending ? $store.library.federationIsLiked(track._federationTrack) : $store.likes.has(track.id) }"
|
||||
@click.stop="track.federation_pending ? $store.library.toggleFederationLike(track._federationTrack) : $store.likes.toggle(track.id)"
|
||||
title="{{ t.player_like }}">
|
||||
@@ -1000,7 +1015,7 @@
|
||||
<div class="queue-header">
|
||||
<h3>{{ t.player_queue }}</h3>
|
||||
<div class="queue-header-actions">
|
||||
<button data-member-only class="queue-share-btn" @click="$store.sharing.copyQueue($event.currentTarget)" :disabled="$store.queue.tracks.length === 0" title="{{ t.player_share_queue }}" aria-label="{{ t.player_share_queue }}">
|
||||
<button data-online-only data-member-only class="queue-share-btn" @click="$store.sharing.copyQueue($event.currentTarget)" :disabled="$store.queue.tracks.length === 0" title="{{ t.player_share_queue }}" aria-label="{{ t.player_share_queue }}">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9"/></svg>
|
||||
</button>
|
||||
<button class="queue-clear-btn" @click="$store.queue.clear()">{{ t.player_clear }}</button>
|
||||
@@ -1137,8 +1152,8 @@
|
||||
<div class="player-track-info">
|
||||
<div class="player-track-title-row">
|
||||
<div class="player-track-title" x-text="$store.player.currentTrack.title"></div>
|
||||
<div class="player-current-actions" data-member-only>
|
||||
<button class="like-btn player-current-like"
|
||||
<div class="player-current-actions" data-member-only data-online-only>
|
||||
<button data-online-only class="like-btn player-current-like"
|
||||
:class="{ liked: $store.likes.has($store.player.currentTrack.id) }"
|
||||
@click.stop="$store.likes.toggle($store.player.currentTrack.id)"
|
||||
title="{{ t.player_like }}"
|
||||
@@ -1227,7 +1242,7 @@
|
||||
<span class="player-time" x-text="formatTime($store.player.duration)"></span>
|
||||
</div>
|
||||
<a class="player-version-chip"
|
||||
href="https://github.com/house-of-vanity/furumusic"
|
||||
data-online-only href="https://github.com/house-of-vanity/furumusic"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="Furumusic on GitHub">v{{ t.app_version() }}</a>
|
||||
@@ -1262,7 +1277,7 @@
|
||||
</button>
|
||||
<div class="device-picker" @click.outside="$store.devices.open = false">
|
||||
<template x-if="$store.devices.remoteHintVisible">
|
||||
<button data-member-only class="remote-playback-hint"
|
||||
<button data-online-only data-member-only class="remote-playback-hint"
|
||||
type="button"
|
||||
@click="$store.devices.dismissRemoteHint()"
|
||||
x-transition
|
||||
@@ -1272,16 +1287,16 @@
|
||||
</button>
|
||||
</template>
|
||||
<button data-member-only class="queue-toggle-btn device-toggle-btn"
|
||||
:class="{ active: $store.devices.isActive() }"
|
||||
@click="$store.devices.toggle()"
|
||||
:title="$store.devices.activeLabel()"
|
||||
:class="{ active: !$store.offline.active && $store.devices.isActive() }"
|
||||
@click="$store.offline?.active ? $store.devices.open = !$store.devices.open : $store.devices.toggle()"
|
||||
:title="$store.offline.active ? '{{ t.player_offline_devices }}' : $store.devices.activeLabel()"
|
||||
aria-label="Devices">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<rect x="3" y="4" width="18" height="12" rx="2"/>
|
||||
<path d="M8 20h8"/>
|
||||
<path d="M12 16v4"/>
|
||||
</svg>
|
||||
<span class="jam-member-squares"
|
||||
<span data-online-only class="jam-member-squares"
|
||||
x-show="$store.devices.activeJamMembers().length > 0"
|
||||
x-cloak>
|
||||
<template x-for="member in $store.devices.activeJamMembers().slice(0, 8)" :key="'device-jam-member-' + member.user_id">
|
||||
@@ -1290,6 +1305,7 @@
|
||||
</span>
|
||||
</button>
|
||||
<div class="device-popover" x-show="$store.devices.open" x-transition x-cloak>
|
||||
<p class="offline-devices-note" data-offline-only>{{ t.player_offline_devices }}</p>
|
||||
<div class="device-section-label">Web players</div>
|
||||
<template x-for="device in $store.devices.webDevices()" :key="device.id">
|
||||
<button data-member-only class="device-row"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg>
|
||||
{{ t.player_global_library }}
|
||||
</a>
|
||||
<a href="#podcasts" class="podcast-nav" :aria-current="['podcasts','podcast_detail'].includes($store.library.view) ? 'page' : null">
|
||||
<a data-online-only href="#podcasts" class="podcast-nav" :aria-current="['podcasts','podcast_detail'].includes($store.library.view) ? 'page' : null">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="2" width="6" height="13" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3M8 22h8"/></svg>
|
||||
<span x-text="$store.podcasts.text('podcasts')"></span>
|
||||
</a>
|
||||
@@ -42,7 +42,7 @@
|
||||
<span class="music-shortcut-title" x-text="item.title"></span>
|
||||
</a>
|
||||
<template x-if="$store.pins.items.length">
|
||||
<div class="shortcut-pin-actions" @keydown.space.stop>
|
||||
<div data-online-only class="shortcut-pin-actions" @keydown.space.stop>
|
||||
<button type="button" class="shortcut-pin-grip" x-show="$store.pins.items.length > 1"
|
||||
:aria-label="'{{ t.player_reorder_pin }} · ' + item.title"
|
||||
title="{{ t.player_reorder_hint }}" aria-description="{{ t.player_reorder_hint }}"
|
||||
|
||||
@@ -113,6 +113,7 @@
|
||||
.mobile-account-control { display: none; position: relative; flex: 0 0 auto; }
|
||||
.mobile-account-control .mobile-account-chip { width: 42px; padding: 0; justify-content: center; }
|
||||
.mobile-account-control .mobile-account-popover { top: calc(100% + 6px); right: 0; width: min(240px, calc(100vw - 24px)); }
|
||||
.sidebar-account-popover, .mobile-account-control .mobile-account-popover {max-height:calc(100dvh - var(--player-bar-space) - 72px);overflow-y:auto;overscroll-behavior:contain}
|
||||
.mobile-library-backdrop { color: var(--text-primary); padding: 0; border: 0; margin: 0; width: 100%; height: 100%; max-width: none; max-height: none; }
|
||||
.mobile-library-backdrop::backdrop { background: transparent; }
|
||||
.mobile-library-drawer .music-nav { padding: 4px 2px; overflow: visible; }
|
||||
@@ -121,4 +122,5 @@
|
||||
.mobile-account-control { display: block; }
|
||||
.account-action-list > * { min-height: 44px; }
|
||||
}
|
||||
{% include "player/offline_styles.css" %}
|
||||
</style>
|
||||
@@ -10,7 +10,7 @@
|
||||
{{ t.player_track_info }}
|
||||
</button>
|
||||
{% if !guest %}
|
||||
<button type="button" data-action="like" :hidden="!menu.historyItem || !menu.localId" @click="menu.run('like')" :aria-pressed="$store.likes.has(menu.localId)">
|
||||
<button data-online-only type="button" data-action="like" :hidden="!menu.historyItem || !menu.localId" @click="menu.run('like')" :aria-pressed="$store.likes.has(menu.localId)">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.7 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.7 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8z"/></svg>
|
||||
{{ t.player_like }}
|
||||
</button>
|
||||
@@ -24,20 +24,28 @@
|
||||
{{ t.player_add_to_queue }}
|
||||
</button>
|
||||
{% if !guest %}
|
||||
<button type="button" data-action="playlist" @click="menu.run('playlist')">
|
||||
<button data-online-only type="button" data-action="playlist" @click="menu.run('playlist')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 5h15M3 11h12M3 17h7m8-3v8m-4-4h8"/></svg>
|
||||
{{ t.player_add_to_playlist }}
|
||||
</button>
|
||||
<button type="button" data-action="similar" :hidden="!$store.library.similarityTrackId(menu.track)" @click="menu.run('similar')">
|
||||
<button data-online-only type="button" data-action="similar" :hidden="!$store.library.similarityTrackId(menu.track)" @click="menu.run('similar')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M6 10h2l1-3 2 6 1-3h2"/></svg>
|
||||
{{ t.player_find_similar }}
|
||||
</button>
|
||||
<button type="button" data-action="share" :hidden="!menu.localId" @click="menu.run('share')">
|
||||
<button data-online-only type="button" data-action="share" :hidden="!menu.localId" @click="menu.run('share')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m9 10.5 6.5-4m-6.5 7 6.5 4"/></svg>
|
||||
{{ t.player_share_track }}
|
||||
</button>
|
||||
{% if share_token.is_empty() %}
|
||||
<button type="button" data-online-only data-action="offline"
|
||||
:hidden="!menu.localId || !$store.offline.enabled" :disabled="$store.offline.isSaved(menu.track) || $store.offline.busy"
|
||||
@click="menu.run('offline')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v10m-4-4 4 4 4-4M4 14h16l1 6H3z"/></svg>
|
||||
<span x-text="$store.offline.isSaved(menu.track) ? '{{ t.player_offline_available }}' : '{{ t.player_offline_save }}'"></span>
|
||||
</button>
|
||||
{% endif %}
|
||||
<button type="button" data-action="download" :hidden="!menu.localId" @click="menu.run('download')">
|
||||
{% endif %}
|
||||
<button data-online-only type="button" data-action="download" :hidden="!menu.localId" @click="menu.run('download')">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12m-5-5 5 5 5-5M4 16v4h16v-4"/></svg>
|
||||
{{ t.track_download }}
|
||||
</button>
|
||||
|
||||
@@ -63,6 +63,7 @@ document.addEventListener('alpine:init', () => {
|
||||
: Alpine.store('playlists').showFederationPicker(track._federationTrack);
|
||||
case 'share': return Alpine.store('sharing').copyTrack(track, anchor);
|
||||
case 'download': return library.downloadTrack(track);
|
||||
case 'offline': return Alpine.store('offline').saveTrack(track);
|
||||
case 'similar': return library.searchSimilar(track);
|
||||
case 'like': return Alpine.store('likes').toggle(localId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// Exercise the same OPFS/IndexedDB implementation used by the service worker.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
|
||||
(async () => {
|
||||
const browser = await chromium.launch({headless:true, ...(process.env.CHROME_PATH ? {executablePath:process.env.CHROME_PATH} : {})});
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.route('http://localhost:17455/**', route => route.fulfill(route.request().url().endsWith('.js')
|
||||
? {contentType:'application/javascript',body:fs.readFileSync('src/player/offline-catalog.js','utf8')}
|
||||
: {contentType:'text/html',body:'<script src="/offline-catalog.js"></script>'}));
|
||||
await page.goto('http://localhost:17455/');
|
||||
const results = await page.evaluate(async () => {
|
||||
const repo = new OfflineCatalog(1), peerTab = new OfflineCatalog('1'), otherAccount = new OfflineCatalog(2);
|
||||
const api = '/api/player/', artist = {id:11,name:'Guest Singer'}, owner = {id:12,name:'Band'};
|
||||
const tracks = [21,22,23].map((id,index) => ({id,title:'Song '+id,content_id:'b3:'+(id===23?'2':'1').repeat(64),
|
||||
artists:[owner],featured_artists:[artist],release_id:id===22?38:37,release_title:'Album '+index,
|
||||
stream_url:api+'stream/'+id,cover_url:api+'cover/13/small',file_size_bytes:6,has_lyrics:true}));
|
||||
const requests = [], bytes = new Uint8Array([0,1,2,3,4,5]);
|
||||
async function online(url, options = {}) {
|
||||
requests.push(url);
|
||||
if (url.startsWith(api+'stream/')) return new Response(bytes,{headers:{'Content-Type':'audio/mpeg','Content-Length':'6'}});
|
||||
if (url === api+'tracks-by-ids') return Response.json(tracks.filter(t => JSON.parse(options.body).ids.includes(t.id)));
|
||||
if (url.startsWith(api+'releases/')) return Response.json({title:'Studio album', artists:[owner],cover_url:api+'cover/13/large'});
|
||||
if (url.startsWith(api+'lyrics/')) return Response.json({versions:[{plain_text:'First line'}]});
|
||||
if (url.startsWith(api+'cover/')) return new Response(new Uint8Array([1]),{headers:{'Content-Type':'image/jpeg'}});
|
||||
throw new Error('Unexpected URL: '+url);
|
||||
}
|
||||
const read = (path, init) => repo.respond(new Request(location.origin+api+path,init));
|
||||
const get = async (path,init) => (await read(path,init)).json();
|
||||
await repo.observe(api+'me',{id:1,name:'One'});
|
||||
await repo.observe(api+'likes',{track_ids:[21,22,23]});
|
||||
await repo.observe(api+'artists?mine=true',{items:[{id:12,image_url:api+'cover/14/medium'}]});
|
||||
await repo.observe(api+'playlists',[{id:9,kind:'user',title:'Mix',is_own:true}]);
|
||||
await repo.observe(api+'playlists/9',{id:9,kind:'user',title:'Mix',tracks:[tracks[1],{id:999},tracks[0]]});
|
||||
await Promise.all([repo.touch(21),peerTab.touch(21),repo.enqueue(tracks[0]),peerTab.enqueue(tracks[0])]);
|
||||
const queueBefore = await repo.pending();
|
||||
await Promise.all([repo.save(queueBefore[0],{fetch:online,limitBytes:100}),peerTab.save(tracks[1],{fetch:online,limitBytes:100})]);
|
||||
const queueAfter = await repo.pending();
|
||||
const afterSave = await repo.list();
|
||||
const beforeRemove = await repo.stats();
|
||||
const accountSeparated = await otherAccount.stats();
|
||||
const catalog = (await get('artists')).items;
|
||||
const featured = await get('artists/11');
|
||||
const release = await get('releases/37');
|
||||
const unlikedCopy = (await get('playlists/-1')).tracks;
|
||||
const playlist = (await get('playlists/9')).tracks;
|
||||
const search = await get('search?q=song+band');
|
||||
const lyrics = await get('lyrics/21');
|
||||
const cover = await read('cover/14/large');
|
||||
const range = await read('stream/21',{headers:{Range:'bytes=2-4'}});
|
||||
const rangeBytes = [...new Uint8Array(await range.arrayBuffer())];
|
||||
const suffix = await read('stream/21',{headers:{Range:'bytes=-2'}});
|
||||
const suffixBytes = [...new Uint8Array(await suffix.arrayBuffer())];
|
||||
const invalidRange = await read('stream/21',{headers:{Range:'bytes=6-8'}});
|
||||
const head = await read('stream/21',{method:'HEAD'});
|
||||
let error;
|
||||
try { await repo.save(tracks[2],{fetch:online,limitBytes:8}); } catch(e) {error = e.name;}
|
||||
let truncated;
|
||||
try {
|
||||
await repo.save(tracks[2],{fetch:(path,options) => path.includes('/stream/') ? new Response(new Uint8Array([1])) : online(path,options)});
|
||||
} catch {truncated = true;}
|
||||
const files = [];
|
||||
for await (const name of (await repo.directory()).keys()) files.push(name);
|
||||
await repo.remove(21);
|
||||
const afterRemove = await repo.stats();
|
||||
const remainingBytes = [...new Uint8Array(await (await read('stream/22')).arrayBuffer())];
|
||||
await repo.clear();
|
||||
const token = 'f'.repeat(64), content = 'b3:'+token, endpoint = api+'federation/cache/'+token;
|
||||
const federated = {id:'fed:'+content,content_id:content,title:'Remote song',stream_url:endpoint,
|
||||
artists:[{name:'Remote band'}],featured_artists:[{id:artist.id,name:artist.name}],release_title:'Remote album',
|
||||
release_key:{normalized_title:'remote album',primary_artists:['remote band'],year:2014},federated_cache:true};
|
||||
const rejected = OfflineCatalog.canSave({...federated,stream_url:'https://example.org/untrusted'});
|
||||
await repo.touch(federated);
|
||||
await repo.enqueue(federated);
|
||||
const [queued] = await peerTab.pending();
|
||||
await peerTab.save(queued,{fetch:async path => {
|
||||
if (path === endpoint) return new Response(bytes,{headers:{'Content-Type':'audio/wav','Content-Length':'6'}});
|
||||
if (path.includes('federation/tracks/lyrics?')) return Response.json({versions:[{plain_text:'Remote words'}]});
|
||||
throw new Error('Unexpected remote path '+path);
|
||||
}});
|
||||
const [local] = await repo.list();
|
||||
const savedView = await get('releases/'+local.release_id);
|
||||
const remoteDetails = {
|
||||
rejected,identity:OfflineCatalog.trackId(federated.id) === local.id,
|
||||
available:await repo.has(federated),plays:local.play_count, found:(await get('search?q=remote+song')).tracks.length,
|
||||
artistCount:(await get('artists/'+local.artists[0].id)).total_track_count,
|
||||
featureCount:(await get('artists/'+artist.id)).featured_tracks.length,
|
||||
navigable:savedView.tracks[0].stream_url === api+'stream/'+local.id,
|
||||
lyrics:(await get('lyrics/'+local.id)).versions[0].plain_text,
|
||||
bytes:(await (await read('federation/cache/'+token)).arrayBuffer()).byteLength,
|
||||
};
|
||||
await repo.remove(federated.id);
|
||||
let notFound;
|
||||
try { await repo.save({id:999},{fetch:online}); } catch(e) {notFound = e.name;}
|
||||
return {queueBefore:queueBefore.length,queueAfter:queueAfter.length,afterSave,beforeRemove,accountSeparated,catalog,
|
||||
guests:featured.featured_tracks.map(t=>t.id),albumTracks:release.tracks.map(t=>t.id),unlikedCopy:unlikedCopy.length,
|
||||
playlist:playlist.map(t => t.id),results:search.tracks.length,lyrics,cover:cover.status,
|
||||
range:[range.status,range.headers.get('Content-Range'),rangeBytes],suffix:suffixBytes,
|
||||
invalidRange:invalidRange.status,head:[head.status,head.headers.get('Content-Length'),(await head.arrayBuffer()).byteLength],
|
||||
error,truncated,files:files.length,afterRemove,remainingBytes,cleared:await repo.stats(),
|
||||
mediaRequests:requests.filter(path => path.includes('/stream/')).length,remoteDetails,notFound};
|
||||
});
|
||||
assert.equal(results.queueBefore,1);
|
||||
assert.equal(results.queueAfter,0);
|
||||
assert.equal(results.afterSave.find(t=>t.id===21).play_count,2);
|
||||
assert.ok(results.afterSave.every(t => t.downloaded_at>0));
|
||||
assert.deepEqual(results.beforeRemove,{tracks:2,bytes:8});
|
||||
assert.deepEqual(results.accountSeparated,{tracks:0,bytes:0});
|
||||
assert.deepEqual(results.catalog.map(a=>[a.id,a.release_count]),[[12,2],[11,0]]);
|
||||
assert.deepEqual(results.guests,[21,22]);
|
||||
assert.deepEqual(results.albumTracks,[21]);
|
||||
assert.equal(results.unlikedCopy,1);
|
||||
assert.deepEqual(results.playlist,[22,21]);
|
||||
assert.equal(results.results,2);
|
||||
assert.equal(results.lyrics.versions[0].plain_text,'First line');
|
||||
assert.equal(results.cover,200);
|
||||
assert.deepEqual(results.range,[206,'bytes 2-4/6',[2,3,4]]);
|
||||
assert.deepEqual(results.suffix,[4,5]);
|
||||
assert.equal(results.invalidRange,416);
|
||||
assert.deepEqual(results.head,[200,'6',0]);
|
||||
assert.equal(results.error,'QuotaExceededError');
|
||||
assert.equal(results.truncated,true);
|
||||
assert.equal(results.files,1);
|
||||
assert.deepEqual(results.remainingBytes,[0,1,2,3,4,5]);
|
||||
assert.deepEqual(results.afterRemove,{tracks:1,bytes:8});
|
||||
assert.deepEqual(results.cleared,{tracks:0,bytes:0});
|
||||
assert.equal(results.mediaRequests,1);
|
||||
assert.deepEqual(results.remoteDetails,{rejected:false,identity:true,available:true,plays:1,found:1,artistCount:1,featureCount:1,
|
||||
navigable:true,lyrics:'Remote words',bytes:6});
|
||||
assert.equal(results.notFound,'NotFoundError');
|
||||
console.log('Offline catalog, federated media, OPFS ranges, indexing, quotas, persistent queue, shared files and account isolation passed.');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => { console.error(error); process.exitCode=1; });
|
||||
@@ -0,0 +1,148 @@
|
||||
// Render with FURU_PODCAST_RENDER_FIXTURE=1 cargo test renders_podcast_navigation_and_views.
|
||||
// The server hosts the real member shell and SW. Chromium plays actual PCM audio.
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const assert = require('node:assert/strict');
|
||||
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const player = path.resolve(__dirname, '../src/player');
|
||||
const html = fs.readFileSync('target/podcast-player-fixture.html','utf8');
|
||||
const rate = 8000, seconds = 24, wav = Buffer.alloc(44 + rate * 2 * seconds);
|
||||
wav.write('RIFF'); wav.writeUInt32LE(wav.length-8,4); wav.write('WAVEfmt ',8);
|
||||
wav.writeUInt32LE(16,16); wav.writeUInt16LE(1,20); wav.writeUInt16LE(1,22);
|
||||
wav.writeUInt32LE(rate,24); wav.writeUInt32LE(rate*2,28); wav.writeUInt16LE(2,32);
|
||||
wav.writeUInt16LE(16,34); wav.write('data',36); wav.writeUInt32LE(wav.length-44,40);
|
||||
const artist = {id:7,name:'Offline band',image_url:null,release_count:1,track_count:2};
|
||||
const tracks = [1,2].map(id => ({id,content_id:'b3:'+String(id).repeat(64),title:'Recording '+id,
|
||||
release_id:9,release_title:'Offline album',release_year:2010,artists:[{id:7,name:artist.name}],featured_artists:[],
|
||||
cover_url:null,track_number:id,duration_seconds:seconds,stream_url:'/api/player/stream/'+id,file_size_bytes:wav.length,
|
||||
has_lyrics:true,audio_format:'WAV'}));
|
||||
const release = {id:9,title:'Offline album',year:2010,artists:[artist],tracks,release_type:'Album',uploaders:[]};
|
||||
const token = 'd'.repeat(64), remoteUrl = '/api/player/federation/cache/'+token;
|
||||
const prepared = {id:'fed:b3:'+token,content_id:'b3:'+token,title:'Federated recording',release_title:'Remote release',
|
||||
artists:[{name:'Remote artist'}],duration_seconds:seconds,stream_url:remoteUrl,federated_cache:true};
|
||||
const text = {versions:[{id:'v1',label:'Words',plain_text:'Words from the saved recording'}]};
|
||||
const assets = {'/offline-worker.js':'text/javascript','/offline-catalog.js':'text/javascript',
|
||||
'/player.webmanifest':'application/manifest+json','/player-icon.svg':'image/svg+xml'};
|
||||
|
||||
(async () => {
|
||||
assert.ok(html.includes('data-offline-account="1"'),'render the current member player fixture first');
|
||||
let down = false;
|
||||
const log = [];
|
||||
const server = http.createServer(async (req,res) => {
|
||||
const p = new URL(req.url,'http://localhost').pathname;
|
||||
log.push({p,method:req.method,range:req.headers.range});
|
||||
res.setHeader('Cache-Control','no-store');
|
||||
if (p in assets) { res.setHeader('Content-Type',assets[p]); return res.end(fs.readFileSync(path.join(player,p.slice(1)))); }
|
||||
if (down) {res.writeHead(503); return res.end();}
|
||||
if (p === '/') { res.setHeader('X-Furumusic-Player-Account','1'); res.setHeader('Content-Type','text/html'); return res.end(html); }
|
||||
if (p === '/offline-probe') {res.writeHead(204,{'X-Furumusic-Player-Account':'1'}); return res.end();}
|
||||
if (p.includes('/stream/') || p === remoteUrl) {
|
||||
const range = /^bytes=(\d+)-(\d*)$/.exec(req.headers.range || '');
|
||||
const first = range ? Number(range[1]) : 0, last = range && range[2] ? Math.min(Number(range[2]),wav.length-1) : wav.length-1;
|
||||
if (first>last) {res.writeHead(416); return res.end();}
|
||||
res.setHeader('Content-Type','audio/wav'); res.setHeader('Accept-Ranges','bytes'); res.setHeader('Content-Length',last-first+1);
|
||||
if (range) {res.statusCode=206; res.setHeader('Content-Range',`bytes ${first}-${last}/${wav.length}`);}
|
||||
return res.end(wav.subarray(first,last+1));
|
||||
}
|
||||
if (p.endsWith('/events')) {res.writeHead(204); return res.end();}
|
||||
const results = {
|
||||
'/api/player/me':{id:1,name:'Member',role:'user',stats:{}},
|
||||
'/api/player/artists':{items:[artist],page:1,total:1,per_page:80,has_more:false},
|
||||
'/api/player/artists/7':{...artist,releases:[release],top_tracks:tracks,featured_tracks:[],total_track_count:2},
|
||||
'/api/player/releases/9':release, '/api/player/likes':{track_ids:[1]},
|
||||
'/api/player/follows':{artist_ids:[],artists:[]}, '/api/player/playlists':[], '/api/player/pins':[],
|
||||
'/api/player/state':{queue:[],repeat_mode:'off',volume:.5},'/api/player/lyrics/1':text,
|
||||
'/api/player/federation/tracks/lyrics':text,
|
||||
'/api/player/devices/heartbeat':{active_device_id:null,devices:[],jams:[]},
|
||||
'/api/player/devices/poll':{active_device_id:null,devices:[],commands:[]},
|
||||
};
|
||||
res.setHeader('Content-Type','application/json');
|
||||
if (p === '/api/player/tracks-by-ids') {
|
||||
const body = []; for await (const chunk of req) body.push(chunk);
|
||||
const ids = JSON.parse(Buffer.concat(body).toString()).ids;
|
||||
return res.end(JSON.stringify(ids.map(id => tracks.find(t => t.id === id)).filter(Boolean)));
|
||||
}
|
||||
return res.end(JSON.stringify(results[p] || []));
|
||||
});
|
||||
await new Promise(resolve => server.listen(0,'127.0.0.1',resolve));
|
||||
const base = 'http://127.0.0.1:'+server.address().port;
|
||||
const browser = await chromium.launch({headless:true,...(process.env.CHROME_PATH ? {executablePath:process.env.CHROME_PATH} : {})});
|
||||
const page = await browser.newPage({viewport:{width:1280,height:860}});
|
||||
const errors = [];
|
||||
page.on('pageerror',e=>errors.push(e.message));
|
||||
try {
|
||||
const releaseRow = page.locator('.track-row[data-shared-track-id="1"]');
|
||||
const account = page.locator('.sidebar-account-trigger');
|
||||
const block = page.locator('#sidebar-account-actions .offline-account');
|
||||
await page.goto(base+'/#release/9');
|
||||
await releaseRow.waitFor();
|
||||
assert.equal(await page.evaluate(() => Alpine.store('offline').enabled),false);
|
||||
assert.equal(await page.evaluate(() => navigator.serviceWorker.controller !== null),false);
|
||||
await account.click();
|
||||
await block.locator('.offline-manage').click();
|
||||
await page.locator('.offline-settings [role=switch]').click();
|
||||
await page.waitForFunction(() => Alpine.store('offline').enabled && !Alpine.store('offline').busy);
|
||||
assert.equal(await page.evaluate(() => Alpine.store('offline').items.length),0);
|
||||
await page.locator('.user-settings-head button').click();
|
||||
await releaseRow.dblclick();
|
||||
await page.waitForFunction(() => Alpine.store('player').isPlaying && Alpine.store('player').currentTime > .1);
|
||||
await page.waitForFunction(() => Alpine.store('offline').items.some(t=>t.id===1));
|
||||
assert.equal(await page.evaluate(() => Alpine.store('offline').bytes),wav.length);
|
||||
await account.click();
|
||||
await block.getByRole('switch').click();
|
||||
await page.waitForFunction(() => Alpine.store('offline').manual && Alpine.store('offline').active);
|
||||
const baseline = log.length;
|
||||
down = true;
|
||||
await page.goto(base+'/#artist/7');
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => Alpine.store('offline').active && Alpine.store('library').currentArtist?.id === 7);
|
||||
assert.deepEqual(await page.evaluate(() => Alpine.store('library').currentArtist.releases.map(r=>[r.id,r.track_count])),[[9,1]]);
|
||||
await page.goto(base+'/#release/9');
|
||||
await releaseRow.waitFor();
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),1);
|
||||
await releaseRow.dblclick();
|
||||
await page.waitForFunction(() => Alpine.store('player').isPlaying && Alpine.store('player').currentTime > .3);
|
||||
const offlineDetails = await page.evaluate(async () => {
|
||||
const response = await fetch('/api/player/stream/1',{headers:{Range:'bytes=0-3'}});
|
||||
return [response.status,await response.text(),(await (await fetch('/api/player/lyrics/1')).json()).versions[0].plain_text];
|
||||
});
|
||||
assert.deepEqual(offlineDetails,[206,'RIFF',text.versions[0].plain_text]);
|
||||
const network = log.slice(baseline).filter(r => !['/offline-worker.js','/offline-catalog.js'].includes(r.p));
|
||||
assert.deepEqual(network,[], 'manual mode and cold reload performed no origin requests');
|
||||
await account.click();
|
||||
await block.getByRole('switch').click();
|
||||
await page.waitForFunction(() => !Alpine.store('offline').manual && Alpine.store('offline').automatic);
|
||||
await page.waitForFunction(() => Alpine.store('offline').automatic);
|
||||
down = false;
|
||||
await page.waitForFunction(() => !Alpine.store('offline').active, null, {timeout:15000});
|
||||
assert.ok(log.slice(baseline).some(r => r.p === '/offline-probe'));
|
||||
down = true;
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => Alpine.store('offline').automatic && Alpine.store('library').currentRelease?.id === 9);
|
||||
assert.equal(await page.locator('.track-row[data-shared-track-id]').count(),1);
|
||||
down = false;
|
||||
await page.waitForFunction(() => !Alpine.store('offline').active,null,{timeout:15000});
|
||||
await page.evaluate(track => Alpine.store('player').play(track),prepared);
|
||||
await page.waitForFunction(() => Alpine.store('offline').items.some(t=>t.offline_remote));
|
||||
await page.evaluate(() => Alpine.store('offline').setManual(true));
|
||||
await page.waitForFunction(() => {
|
||||
const p = Alpine.store('player');
|
||||
return p.currentTrack?.offline_remote && p.isPlaying && p.currentTime > .1;
|
||||
});
|
||||
const remoteArtist = await page.evaluate(() => Alpine.store('player').currentTrack.artists[0].id);
|
||||
await page.goto(base+'/#artist/'+remoteArtist);
|
||||
await page.waitForFunction(() => Alpine.store('library').currentArtist?.name === 'Remote artist');
|
||||
assert.deepEqual(await page.evaluate(() => Alpine.store('library').currentArtist.releases.map(r=>r.title)),['Remote release']);
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('Real player opt-in, local/federated WAV playback, offline navigation, cold reload and recovery passed.');
|
||||
} catch (error) {
|
||||
const state = await page.evaluate(() => {
|
||||
const offline = window.Alpine?.store('offline'), p = window.Alpine?.store('player');
|
||||
return {url:location.hash, enabled:offline?.enabled,active:offline?.active,error:offline?.error,
|
||||
busy:offline?.busy,saved:offline?.items?.length,playing:p?.isPlaying,track:p?.currentTrack?.id};
|
||||
}).catch(()=>({}));
|
||||
console.error({state,errors,recent:log.slice(-7)});
|
||||
throw error;
|
||||
} finally { await browser.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
})().catch(e=>{console.error(e); process.exitCode=1;});
|
||||
@@ -0,0 +1,148 @@
|
||||
// Real service worker and Cache Storage. The HTTP fixture records every origin request.
|
||||
const assert = require('node:assert/strict');
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const player = path.join(__dirname, '..', 'src', 'player');
|
||||
const catalog = fs.readFileSync(path.join(player, 'offline-catalog.js'), 'utf8');
|
||||
|
||||
(async () => {
|
||||
let account = '17', unavailable = false, authOutage = false, hangingRequest;
|
||||
const log = [];
|
||||
const server = http.createServer((req,res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
log.push([req.method, url.pathname]);
|
||||
res.setHeader('Cache-Control','no-store');
|
||||
if (url.pathname === '/offline-worker.js' || url.pathname === '/offline-catalog.js') {
|
||||
res.setHeader('Content-Type','text/javascript');
|
||||
return res.end(fs.readFileSync(path.join(player,url.pathname.slice(1))));
|
||||
}
|
||||
if (url.pathname === '/api/hanging') { hangingRequest(); return; }
|
||||
if (unavailable) { res.statusCode = 503; return res.end(); }
|
||||
if (authOutage && url.pathname === '/api/player/me') { res.statusCode = 401; return res.end(); }
|
||||
if (authOutage && url.pathname === '/offline-probe') { res.statusCode = 500; return res.end(); }
|
||||
if (url.pathname === '/logout') { account = ''; return res.end('logged out'); }
|
||||
if (url.pathname === '/offline-probe') {
|
||||
res.setHeader('X-Furumusic-Player-Account',account || '0');
|
||||
res.statusCode = account ? 204 : 401;
|
||||
return res.end();
|
||||
}
|
||||
if (url.pathname === '/') {
|
||||
res.setHeader('Content-Type','text/html');
|
||||
if (!account) return res.end('<title>Login</title>');
|
||||
res.setHeader('X-Furumusic-Player-Account',account);
|
||||
return res.end('<html data-offline-mode="online" data-offline-account="'+account+'"><title>Player</title><script>'+catalog+'</script></html>');
|
||||
}
|
||||
if (url.pathname === '/api/player/me') {
|
||||
res.setHeader('Content-Type','application/json');
|
||||
return res.end(JSON.stringify({id:Number(account),name:'Network'}));
|
||||
}
|
||||
return res.end('public');
|
||||
});
|
||||
await new Promise(resolve => server.listen(0,'127.0.0.1',resolve));
|
||||
const base = 'http://127.0.0.1:'+server.address().port;
|
||||
const browser = await chromium.launch({headless:true,...(process.env.CHROME_PATH ? {executablePath:process.env.CHROME_PATH} : {})});
|
||||
try {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
await page.goto(base);
|
||||
await page.evaluate(async () => {
|
||||
await navigator.serviceWorker.register('/offline-worker.js');
|
||||
await navigator.serviceWorker.ready;
|
||||
});
|
||||
await page.waitForFunction(() => !!navigator.serviceWorker.controller);
|
||||
const mode = async (value, id='17') => {
|
||||
const result = await page.evaluate(([value,id]) => new Promise(resolve => {
|
||||
const ports = new MessageChannel();
|
||||
ports.port1.onmessage = ({data}) => resolve(data);
|
||||
navigator.serviceWorker.controller.postMessage({type:'offline-config',account:id,mode:value},[ports.port2]);
|
||||
}),[value,id]);
|
||||
assert.equal(result.ok,true,result.error);
|
||||
};
|
||||
await mode('online');
|
||||
await page.evaluate(async () => {
|
||||
const repo = new OfflineCatalog(17);
|
||||
await repo.observe('/api/player/me',{id:17,name:'Saved'});
|
||||
const file = await (await repo.directory()).getFileHandle('audio.test',{create:true});
|
||||
const stream = await file.createWritable();
|
||||
await stream.write('0123456789');
|
||||
await stream.close();
|
||||
await repo.write(['tracks','files'], get => {
|
||||
const fileId = 'b3:' + 'a'.repeat(64);
|
||||
get('tracks').put({id:42,file:fileId,track:{id:42,title:'Saved track'}});
|
||||
get('files').put({name:'audio.test',mime:'audio/mpeg'},fileId);
|
||||
});
|
||||
});
|
||||
const audio = (p,id) => p.evaluate(async id => {
|
||||
const response = await fetch('/api/player/stream/'+id+'?saved=1',{headers:{Range:'bytes=1-3'}});
|
||||
return [response.status,await response.text()];
|
||||
}, id);
|
||||
assert.deepEqual(await audio(page,42),[206,'123']);
|
||||
await page.evaluate(() => fetch('/login',{method:'POST'}));
|
||||
assert.deepEqual(await audio(page,42),[206,'123'],'same-account sign-in keeps the cache');
|
||||
assert.deepEqual(await audio(page,43),[200,'public']);
|
||||
assert.deepEqual(await page.evaluate(async () => {
|
||||
const response = await fetch('/api/player/federation/cache/'+ 'a'.repeat(64) +'?saved=1', {headers:{Range:'bytes=2-4'}});
|
||||
return [response.status,await response.text()];
|
||||
}),[206,'234']);
|
||||
const guest = await context.newPage();
|
||||
await guest.goto(base+'/share/token');
|
||||
assert.deepEqual(await audio(guest,42),[200,'public'],'guests cannot read member audio');
|
||||
await guest.close();
|
||||
const started = new Promise(resolve => { hangingRequest = resolve; });
|
||||
await page.evaluate(() => { window.old = fetch('/api/hanging').then(r=>r.status).catch(()=>0); });
|
||||
await started;
|
||||
await mode('manual');
|
||||
assert.ok([0,503].includes(await page.evaluate(() => window.old)));
|
||||
const baseline = log.length;
|
||||
const other = await page.context().newPage();
|
||||
await other.goto(base+'/#artists');
|
||||
assert.equal(await other.evaluate(() => document.documentElement.dataset.offlineMode),'manual');
|
||||
assert.equal(await other.evaluate(() => fetch('/api/player/me').then(r=>r.json()).then(p=>p.name)), 'Saved');
|
||||
for (const [url,method] of [['/offline-probe','GET'],['/api/player/history','POST'],['/logout','GET']]) {
|
||||
assert.equal(await page.evaluate(([u,m]) => fetch(u,{method:m}).then(r=>r.status),[url, method]),503);
|
||||
}
|
||||
assert.equal(await page.evaluate(() => fetch(location.origin.replace('127.0.0.1','localhost')+'/external-art',
|
||||
{mode:'no-cors'}).then(()=>true,()=>false)),false);
|
||||
assert.deepEqual(log.slice(baseline).filter(([,p]) => !['/offline-worker.js','/offline-catalog.js'].includes(p)),[]);
|
||||
|
||||
await mode('auto');
|
||||
assert.equal(await page.evaluate(() => fetch('/offline-probe').then(r=>r.status)),204);
|
||||
await mode('online');
|
||||
assert.equal(await page.evaluate(() => fetch('/api/player/me').then(r=>r.json()).then(p=>p.name)), 'Network');
|
||||
authOutage = true;
|
||||
assert.equal(await page.evaluate(() => fetch('/api/player/me').then(r=>r.json()).then(p=>p.name)), 'Saved',
|
||||
'an API 401 with an unavailable session store keeps local data');
|
||||
assert.equal(await page.evaluate(() => fetch('/offline-probe').then(r=>r.status)),503);
|
||||
authOutage = false;
|
||||
await mode('online');
|
||||
unavailable = true;
|
||||
assert.deepEqual(await page.evaluate(async () => {
|
||||
const response = await fetch('/api/player/tracks-by-ids', {method:'POST',body:JSON.stringify({ids:[42]})});
|
||||
return response.json();
|
||||
}), [{id:42,title:'Saved track'}]);
|
||||
await page.reload();
|
||||
assert.equal(await page.evaluate(() => document.documentElement.dataset.offlineMode),'auto');
|
||||
assert.equal(await page.evaluate(() => fetch('/api/player/me').then(r=>r.json()).then(p=>p.name)), 'Saved');
|
||||
unavailable = false;
|
||||
account = '19';
|
||||
const probe = await page.evaluate(() => fetch('/offline-probe').then(async r=>[r.status,r.headers.get('X-Furumusic-Player-Account'),await r.text()]));
|
||||
assert.deepEqual(probe,[204,'19','']);
|
||||
assert.equal(await page.evaluate(() => new OfflineCatalog(17).read('meta','me')),undefined);
|
||||
await page.reload();
|
||||
assert.equal(await page.evaluate(() => document.documentElement.dataset.offlineAccount),'19');
|
||||
await mode('online','19');
|
||||
assert.deepEqual(await audio(other,42),[503,'{"error":"Unavailable offline"}'],'an old open tab cannot use the new account');
|
||||
await other.close();
|
||||
await mode('disabled','19');
|
||||
await page.evaluate(() => fetch('/logout'));
|
||||
await page.reload();
|
||||
assert.equal(await page.title(),'Login');
|
||||
console.log('Offline worker passed cold navigation, network isolation, automatic fallback and account/guest isolation.');
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.closeAllConnections();
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
}
|
||||
})().catch(error => { console.error(error); process.exitCode=1; });
|
||||
@@ -155,11 +155,99 @@ async function checkSidebar(browser, mobile) {
|
||||
await panel.getByRole('button', { name: 'Settings' }).click();
|
||||
await page.locator('.user-settings-modal').waitFor();
|
||||
assert.equal(await panel.isVisible(), false);
|
||||
await checkOfflineControls(page, trigger, panel);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
}
|
||||
|
||||
async function checkOfflineControls(page, trigger, panel) {
|
||||
const modal = page.locator('.user-settings-modal');
|
||||
const section = modal.locator('.offline-settings');
|
||||
const close = modal.locator('.user-settings-head button');
|
||||
const viewport = page.viewportSize();
|
||||
if (viewport.width < 600) await page.setViewportSize({...viewport, width:320});
|
||||
// Exercise the account/settings UI independently of Service Worker registration on this mock origin.
|
||||
await page.evaluate(() => {
|
||||
Object.assign(Alpine.store('offline'), {
|
||||
supported: true,
|
||||
setEnabled(on) { this.enabled = on; },
|
||||
setLimit(bytes) { this.limitBytes = bytes; },
|
||||
setManual(on) {
|
||||
this.manual = this.active = on;
|
||||
document.documentElement.classList.toggle('offline-active', on);
|
||||
},
|
||||
removeTrack(id) { this.items = this.items.filter(track => track.id !== id); },
|
||||
clearCache() { this.items = []; this.bytes = 0; },
|
||||
});
|
||||
});
|
||||
const enable = section.getByRole('switch');
|
||||
await page.waitForFunction(() => document.activeElement?.id === 'user-settings-title');
|
||||
assert.equal(await enable.getAttribute('aria-checked'), 'false');
|
||||
await close.click();
|
||||
await page.waitForFunction(selector => document.activeElement?.matches(selector),
|
||||
viewport.width < 600 ? '.mobile-account-chip' : '.sidebar-account-trigger');
|
||||
await trigger.click();
|
||||
await panel.getByText('Offline listening is off').waitFor();
|
||||
await panel.getByRole('button', {name:'Manage offline music'}).click();
|
||||
await page.waitForFunction(() => document.activeElement?.id === 'offline-settings-title');
|
||||
await enable.click();
|
||||
await section.getByText('No music saved on this device yet.').waitFor();
|
||||
const range = section.getByRole('slider', {name:'Cache limit'});
|
||||
assert.equal(await range.getAttribute('aria-valuetext'), '3 GB');
|
||||
const marks = await section.locator('.offline-scale-marks span').evaluateAll(list =>
|
||||
list.map(node => ({text:node.textContent, start:node.getBoundingClientRect().left, end:node.getBoundingClientRect().right})));
|
||||
assert.deepEqual(marks.map(m => m.text), ['100 MB','1 GB','10 GB','100 GB','512 GB']);
|
||||
assert.ok(marks.every((mark, i) => i === 0 || marks[i-1].end <= mark.start),
|
||||
'scale labels overlap: ' + JSON.stringify(marks));
|
||||
await range.press('Home');
|
||||
assert.equal(await range.getAttribute('aria-valuetext'), '100 MB');
|
||||
let last = 100e6;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await range.press('ArrowRight');
|
||||
const next = await page.evaluate(() => Alpine.store('offline').limitBytes);
|
||||
assert.ok(next > last, 'each keyboard step must change the stored limit');
|
||||
last = next;
|
||||
}
|
||||
await range.press('End');
|
||||
assert.equal(await range.getAttribute('aria-valuetext'), '512 GB');
|
||||
await page.evaluate(() => Object.assign(Alpine.store('offline'), {
|
||||
bytes:3e6, items:[{id:7,title:'One',artist:'Artist',bytes:2e6},{id:8,title:'Two',artist:'Artist',bytes:1e6}],
|
||||
}));
|
||||
await section.getByRole('button', {name:'Remove from this device · One'}).click();
|
||||
assert.equal(await section.locator('.offline-saved-list li').count(), 1);
|
||||
page.once('dialog', dialog => dialog.dismiss());
|
||||
await section.getByRole('button', {name:'Clear cache'}).click();
|
||||
assert.equal(await section.locator('.offline-saved-list li').count(), 1);
|
||||
page.once('dialog', dialog => dialog.accept());
|
||||
await section.getByRole('button', {name:'Clear cache'}).click();
|
||||
await section.getByText('No music saved on this device yet.').waitFor();
|
||||
await close.click();
|
||||
await trigger.click();
|
||||
const manual = panel.getByRole('switch', {name:'Use saved music only'});
|
||||
await manual.click();
|
||||
assert.equal(await manual.getAttribute('aria-checked'), 'true');
|
||||
assert.equal(await panel.getByRole('link', {name:'My listening'}).isVisible(), false);
|
||||
assert.equal(await panel.getByRole('link', {name:'Followed'}).isVisible(), true);
|
||||
await panel.getByRole('button', {name:'Settings'}).click();
|
||||
await modal.getByText('Devices are unavailable offline.').waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await modal.waitFor({state:'hidden'});
|
||||
await page.locator('.device-toggle-btn:visible').click();
|
||||
assert.equal((await page.locator('.device-popover:visible').innerText()).trim(), 'Devices are unavailable offline.');
|
||||
await page.locator('.device-toggle-btn:visible').click();
|
||||
await page.evaluate(() => { Alpine.store('offline').manual = false; });
|
||||
await trigger.click();
|
||||
await panel.getByText('Offline · automatic').waitFor();
|
||||
assert.equal(await manual.getAttribute('aria-checked'), 'false');
|
||||
await page.evaluate(() => {
|
||||
Alpine.store('user').menuOpen = false;
|
||||
Alpine.store('library').view = 'offline_unavailable';
|
||||
});
|
||||
await page.getByText('This page is unavailable offline.').waitFor();
|
||||
assert.equal(await page.getByRole('link', {name:'Open saved catalog'}).getAttribute('href'), '#artists');
|
||||
}
|
||||
|
||||
async function dragShortcut(page, nav, source, destination, touch, cancel = false) {
|
||||
const grip = nav.locator('[data-pin-href="' + source.href + '"] .shortcut-pin-grip');
|
||||
const row = nav.locator('[data-pin-href="' + destination.href + '"]');
|
||||
@@ -349,7 +437,7 @@ async function checkPinActions(browser, mobile) {
|
||||
await checkCollection(browser);
|
||||
await checkPinActions(browser, false);
|
||||
await checkPinActions(browser, true);
|
||||
console.log('Desktop and mobile sidebar navigation, account controls, pin reordering and undo passed.');
|
||||
console.log('Desktop and mobile sidebar navigation, offline storage controls, pin reordering and undo passed.');
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ function setup(hash, fetch) {
|
||||
close() { this.closed = true; }
|
||||
}
|
||||
vm.runInNewContext(librarySource, {
|
||||
location, fetch, EventSource, GUEST: false, URLSearchParams, clearTimeout, setTimeout,
|
||||
location, fetch, EventSource, GUEST: false, playerOffline: () => false, URLSearchParams, clearTimeout, setTimeout,
|
||||
Alpine: { store(_name, value) { library = value; } },
|
||||
history: { replaceState(_state, _title, url) { location.hash = url; replacements.push(url); } },
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ function player(fetchImpl = async () => ({ok:true}), beacon = () => true, guest
|
||||
// Exercise the production methods with audio and network stubs.
|
||||
const methods = template.slice(template.indexOf(' _recordHistory(endedReason'), template.indexOf(' _sendNowPlaying()'));
|
||||
const audio = {currentTime:60};
|
||||
const context = vm.createContext({GUEST:guest, audio, fetch:fetchImpl, navigator:{sendBeacon:beacon}, Blob,
|
||||
const context = vm.createContext({GUEST:guest, playerOffline:() => false, audio, fetch:fetchImpl, navigator:{sendBeacon:beacon}, Blob,
|
||||
globalThis:{crypto:{randomUUID:()=> 'uuid'}}, setTimeout: fn => { fn(); }, console});
|
||||
vm.runInContext('this.methods = {' + methods + '};', context);
|
||||
return Object.assign(context.methods, {
|
||||
@@ -17,6 +17,18 @@ function player(fetchImpl = async () => ({ok:true}), beacon = () => true, guest
|
||||
});
|
||||
}
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
test('an offline listening session stays local after the server returns', async () => {
|
||||
const calls = [];
|
||||
const p = player(async (_, request) => { calls.push(request); return {ok:true}; });
|
||||
p._offlineSession = true;
|
||||
p._recordHistory('finished');
|
||||
await flush();
|
||||
assert.equal(calls.length, 0);
|
||||
p._offlineSession = false;
|
||||
p._recordHistory('finished');
|
||||
await flush();
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
test('switching tracks records short sessions, and completion is not counted twice', async () => {
|
||||
const calls=[]; const p=player(async (_url, options)=> {calls.push(JSON.parse(options.body)); return {ok:true};});
|
||||
p._listenedSeconds=8; p._recordHistory('replaced'); await flush();
|
||||
|
||||
@@ -113,7 +113,7 @@ test('hash routing restores both the podcast list and a selected podcast',()=>{
|
||||
const script=readFileSync(`${__dirname}/../templates/player/scripts.html`,'utf8');
|
||||
const start=script.indexOf(' _navigateFromHash(options = {}) {');const end=script.indexOf(' _scrollElement()',start);
|
||||
const calls=[],location={hash:'#podcasts'};
|
||||
const context=vm.createContext({GUEST:false,location,URLSearchParams,Alpine:{store(){return {enter(options){calls.push(['list',options]);},open(id,options){calls.push(['detail',id,options]);}};}}});
|
||||
const context=vm.createContext({GUEST:false,playerOffline:()=>false,location,URLSearchParams,Alpine:{store(){return {enter(options){calls.push(['list',options]);},open(id,options){calls.push(['detail',id,options]);}};}}});
|
||||
const library=vm.runInContext('({'+script.slice(start,end)+'})',context);library.goArtists=()=>{throw Error('unexpected artist navigation');};
|
||||
library._navigateFromHash({fromHash:true});assert.equal(calls[0][0],'list');assert.equal(calls[0][1].fromHash,true);
|
||||
location.hash='#podcast?id='+encodeURIComponent('pod1:fixture');library._navigateFromHash({fromHash:true});
|
||||
|
||||
Reference in new issue
Block a user