feat(offline): implement Last.fm scrobble queue for offline mode

Research findings:
- Last.fm API supports batch scrobbling (up to 50 tracks)
- Timestamps can be backdated up to 14 days

Implementation:
- Add scrobble_queue table to offline database
- Add queue_scrobble, get_queued_scrobbles, mark_scrobbles_sent commands
- Queue scrobbles when offline instead of skipping
- Flush queue automatically when transitioning to online
- Skip scrobbles older than 14 days (Last.fm limit)
- Cleanup sent scrobbles after 7 days
This commit is contained in:
vicrodh committed 2026-01-15 23:24:24 -06:00
1 parent b4af6f6e9f
commit e7f06fcd2f
5 files changed
+400 -27

No files matched your search

+12 -2
View File
@@ -9,8 +9,8 @@ import { invoke } from '@tauri-apps/api/core';
import { getCurrentWebview } from '@tauri-apps/api/webview';
import { goBack, goForward } from '$lib/stores/navigationStore';
import { loadToastsPreference } from '$lib/stores/toastStore';
import { loadSystemNotificationsPreference } from '$lib/services/playbackService';
import { initOfflineStore, cleanupOfflineStore } from '$lib/stores/offlineStore';
import { loadSystemNotificationsPreference, flushScrobbleQueue } from '$lib/services/playbackService';
import { initOfflineStore, cleanupOfflineStore, onOnlineTransition } from '$lib/stores/offlineStore';
// ============ Theme Management ============
@@ -122,6 +122,16 @@ export function bootstrapApp(): BootstrapResult {
// Initialize offline store (async, fire-and-forget)
initOfflineStore();
// Register callback to flush scrobble queue when transitioning to online
onOnlineTransition(() => {
console.log('[Bootstrap] Online transition detected - flushing scrobble queue');
flushScrobbleQueue().then(({ sent, failed }) => {
if (sent > 0 || failed > 0) {
console.log(`[Bootstrap] Scrobble queue flush complete: ${sent} sent, ${failed} failed`);
}
});
});
return {
cleanup: () => {
cleanupMouse();
+117 -24
View File
@@ -25,7 +25,13 @@ import {
castPause,
castStop
} from '$lib/stores/castStore';
import { isOffline as checkIsOffline } from '$lib/stores/offlineStore';
import {
isOffline as checkIsOffline,
queueScrobble,
getQueuedScrobbles,
markScrobblesSent,
cleanupSentScrobbles
} from '$lib/stores/offlineStore';
// ============ Types ============
@@ -279,38 +285,51 @@ export async function updateLastfmNowPlaying(
durationSecs: number,
trackId: number
): Promise<void> {
// Skip scrobbling when offline
if (checkIsOffline()) {
console.log('Last.fm: Skipping scrobble (offline mode)');
return;
}
// Check if scrobbling is enabled
const scrobblingEnabled = localStorage.getItem('qbz-lastfm-scrobbling') !== 'false';
const sessionKey = localStorage.getItem('qbz-lastfm-session-key');
if (!scrobblingEnabled || !sessionKey) return;
try {
// Update "now playing"
await invoke('lastfm_now_playing', {
artist,
track: title,
album: album || null
});
console.log('Last.fm: Updated now playing');
const isOffline = checkIsOffline();
// Schedule scrobble after 50% of track or 4 minutes (whichever is shorter)
if (scrobbleTimeout) {
clearTimeout(scrobbleTimeout);
// Skip "now playing" update when offline (requires network)
if (!isOffline) {
try {
await invoke('lastfm_now_playing', {
artist,
track: title,
album: album || null
});
console.log('Last.fm: Updated now playing');
} catch (err) {
console.error('Last.fm now playing failed:', err);
}
}
const scrobbleDelay = Math.min(durationSecs * 0.5, 240) * 1000; // in ms
// Schedule scrobble after 50% of track or 4 minutes (whichever is shorter)
if (scrobbleTimeout) {
clearTimeout(scrobbleTimeout);
}
scrobbleTimeout = setTimeout(async () => {
if (lastScrobbledTrackId !== trackId) {
const scrobbleDelay = Math.min(durationSecs * 0.5, 240) * 1000; // in ms
scrobbleTimeout = setTimeout(async () => {
if (lastScrobbledTrackId !== trackId) {
const timestamp = Math.floor(Date.now() / 1000);
// If offline, queue the scrobble for later
if (checkIsOffline()) {
try {
await queueScrobble(artist, title, album || null, timestamp);
lastScrobbledTrackId = trackId;
console.log('Last.fm: Queued scrobble for later (offline)');
} catch (err) {
console.error('Failed to queue scrobble:', err);
}
} else {
// Online - scrobble immediately
try {
const timestamp = Math.floor(Date.now() / 1000);
await invoke('lastfm_scrobble', {
artist,
track: title,
@@ -323,9 +342,83 @@ export async function updateLastfmNowPlaying(
console.error('Last.fm scrobble failed:', err);
}
}
}, scrobbleDelay);
}
}, scrobbleDelay);
}
/**
* Flush queued scrobbles to Last.fm
* Call this when transitioning from offline to online
*/
export async function flushScrobbleQueue(): Promise<{ sent: number; failed: number }> {
// Check if scrobbling is enabled
const scrobblingEnabled = localStorage.getItem('qbz-lastfm-scrobbling') !== 'false';
const sessionKey = localStorage.getItem('qbz-lastfm-session-key');
if (!scrobblingEnabled || !sessionKey) {
return { sent: 0, failed: 0 };
}
// Don't try to flush if still offline
if (checkIsOffline()) {
console.log('Last.fm: Cannot flush queue (still offline)');
return { sent: 0, failed: 0 };
}
try {
const queued = await getQueuedScrobbles(50); // Last.fm batch limit
if (queued.length === 0) {
return { sent: 0, failed: 0 };
}
console.log(`Last.fm: Flushing ${queued.length} queued scrobbles`);
let sent = 0;
let failed = 0;
const sentIds: number[] = [];
// Send scrobbles one by one (could be optimized to batch later)
for (const scrobble of queued) {
// Check if timestamp is too old (>14 days)
const now = Math.floor(Date.now() / 1000);
const fourteenDaysAgo = now - (14 * 24 * 60 * 60);
if (scrobble.timestamp < fourteenDaysAgo) {
console.log(`Last.fm: Skipping old scrobble (>14 days): ${scrobble.artist} - ${scrobble.track}`);
sentIds.push(scrobble.id); // Mark as sent to remove from queue
failed++;
continue;
}
try {
await invoke('lastfm_scrobble', {
artist: scrobble.artist,
track: scrobble.track,
album: scrobble.album,
timestamp: scrobble.timestamp
});
sentIds.push(scrobble.id);
sent++;
console.log(`Last.fm: Flushed scrobble: ${scrobble.artist} - ${scrobble.track}`);
} catch (err) {
console.error(`Last.fm: Failed to flush scrobble: ${scrobble.artist} - ${scrobble.track}`, err);
failed++;
}
}
// Mark successfully sent scrobbles
if (sentIds.length > 0) {
await markScrobblesSent(sentIds);
}
// Cleanup old sent scrobbles
await cleanupSentScrobbles(7);
console.log(`Last.fm: Flush complete - sent: ${sent}, failed: ${failed}`);
return { sent, failed };
} catch (err) {
console.error('Last.fm now playing failed:', err);
console.error('Last.fm: Failed to flush scrobble queue:', err);
return { sent: 0, failed: 0 };
}
}
+79
View File
@@ -53,12 +53,22 @@ let eventUnlisten: UnlistenFn | null = null;
// Listeners
const listeners = new Set<() => void>();
// Callback for online transition (to flush scrobble queue, etc.)
let onOnlineTransitionCallback: (() => void) | null = null;
function notifyListeners(): void {
for (const listener of listeners) {
listener();
}
}
/**
* Register a callback to be called when transitioning from offline to online
*/
export function onOnlineTransition(callback: () => void): void {
onOnlineTransitionCallback = callback;
}
/**
* Subscribe to offline state changes
*/
@@ -93,11 +103,17 @@ export function getOfflineReason(): OfflineReason | null {
*/
async function fetchStatus(): Promise<void> {
try {
const wasOffline = status.isOffline;
const newStatus = await invoke<OfflineStatus>('get_offline_status');
const changed = JSON.stringify(status) !== JSON.stringify(newStatus);
status = newStatus;
if (changed) {
notifyListeners();
// Check for offline -> online transition
if (wasOffline && !newStatus.isOffline && onOnlineTransitionCallback) {
console.log('[Offline] Transitioning to online - triggering callback');
onOnlineTransitionCallback();
}
}
} catch (error) {
console.error('Failed to fetch offline status:', error);
@@ -171,8 +187,14 @@ export async function initOfflineStore(): Promise<void> {
// Listen for backend events (from manual toggle)
eventUnlisten = await listen<OfflineStatus>('offline-status-changed', (event) => {
const wasOffline = status.isOffline;
status = event.payload;
notifyListeners();
// Check for offline -> online transition
if (wasOffline && !event.payload.isOffline && onOnlineTransitionCallback) {
console.log('[Offline] Transitioning to online via event - triggering callback');
onOnlineTransitionCallback();
}
});
initialized = true;
@@ -243,6 +265,63 @@ export async function deletePendingPlaylist(pendingId: number): Promise<void> {
await invoke('delete_pending_playlist', { pendingId });
}
// ============ Scrobble Queue ============
export interface QueuedScrobble {
id: number;
artist: string;
track: string;
album: string | null;
timestamp: number;
createdAt: number;
sent: boolean;
}
/**
* Queue a scrobble for later submission to Last.fm
*/
export async function queueScrobble(
artist: string,
track: string,
album: string | null,
timestamp: number
): Promise<number> {
return invoke<number>('queue_scrobble', {
artist,
track,
album,
timestamp,
});
}
/**
* Get queued scrobbles (up to limit)
*/
export async function getQueuedScrobbles(limit?: number): Promise<QueuedScrobble[]> {
return invoke<QueuedScrobble[]>('get_queued_scrobbles', { limit });
}
/**
* Mark scrobbles as sent after successful Last.fm submission
*/
export async function markScrobblesSent(ids: number[]): Promise<void> {
await invoke('mark_scrobbles_sent', { ids });
}
/**
* Get count of queued (unsent) scrobbles
*/
export async function getQueuedScrobbleCount(): Promise<number> {
return invoke<number>('get_queued_scrobble_count');
}
/**
* Cleanup old sent scrobbles
*/
export async function cleanupSentScrobbles(olderThanDays?: number): Promise<number> {
return invoke<number>('cleanup_sent_scrobbles', { olderThanDays });
}
// ============ State Getter ============
export interface OfflineState {