refactor(logging): route frontend console calls through the logger
TRACES: | DR-204 484 ungated `console.*` calls across 63 non-test frontend files shipped to end users with no way to turn them off. Mechanical substitution, no control flow, error handling or message semantics changed: console.log / console.debug -> log.debug console.info -> log.info console.warn -> log.warn console.error -> log.error Hand-written `"[Scope] …"` prefixes are dropped where the logger's scope now carries them; scope names that already existed are preserved verbatim (`[Auth]`, `[VideoPlayer]`, `[PiP]`, …) and inferred from the filename where a file had none. `src/routes/player/[id]/+page.svelte` keeps its `NextEpisode` and `AutoPlay` sub-scopes as separate loggers rather than flattening them into the page scope. `grep -rn 'console\.' src/` now matches nothing outside the tests and the facade itself.
This commit is contained in:
@@ -19,6 +19,9 @@ import type {
|
||||
PlaylistEntry,
|
||||
PlaylistCreatedResult,
|
||||
} from "./types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("RepositoryClient");
|
||||
|
||||
/**
|
||||
* Repository client - thin wrapper over Rust HybridRepository
|
||||
@@ -39,14 +42,14 @@ export class RepositoryClient {
|
||||
accessToken: string,
|
||||
serverId: string
|
||||
): Promise<string> {
|
||||
console.log("[RepositoryClient] Creating Rust repository...");
|
||||
log.debug("Creating Rust repository...");
|
||||
this.handle = await commands.repositoryCreate(serverUrl, userId, accessToken, serverId);
|
||||
|
||||
// Store for URL construction
|
||||
this._serverUrl = serverUrl;
|
||||
this._accessToken = accessToken;
|
||||
|
||||
console.log("[RepositoryClient] Repository created with handle:", this.handle);
|
||||
log.debug("Repository created with handle:", this.handle);
|
||||
return this.handle;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
import { haptics } from "$lib/utils/haptics";
|
||||
import { toast } from "$lib/stores/toast";
|
||||
import { favoriteOverrides } from "$lib/stores/favorites";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("FavoriteButton");
|
||||
|
||||
interface Props {
|
||||
itemId: string;
|
||||
@@ -78,7 +81,7 @@
|
||||
isAnimating = false;
|
||||
}, 600);
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle favorite:", error);
|
||||
log.error("Failed to toggle favorite:", error);
|
||||
toast.show("Failed to update favorites", "error");
|
||||
isAnimating = false;
|
||||
} finally {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { downloads, type DownloadInfo } from "$lib/stores/downloads";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("DownloadItem");
|
||||
|
||||
interface Props {
|
||||
download: DownloadInfo;
|
||||
@@ -69,7 +72,7 @@
|
||||
// Refresh to update UI
|
||||
await downloads.refresh(download.userId);
|
||||
} catch (error) {
|
||||
console.error("Failed to pause download:", error);
|
||||
log.error("Failed to pause download:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +82,7 @@
|
||||
// Refresh to update UI
|
||||
await downloads.refresh(download.userId);
|
||||
} catch (error) {
|
||||
console.error("Failed to resume download:", error);
|
||||
log.error("Failed to resume download:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +92,7 @@
|
||||
// Refresh to update UI
|
||||
await downloads.refresh(download.userId);
|
||||
} catch (error) {
|
||||
console.error("Failed to cancel download:", error);
|
||||
log.error("Failed to cancel download:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +102,7 @@
|
||||
// Refresh to update UI
|
||||
await downloads.refresh(download.userId);
|
||||
} catch (error) {
|
||||
console.error("Failed to delete download:", error);
|
||||
log.error("Failed to delete download:", error);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import { downloads } from "$lib/stores/downloads";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("AlbumDownloadButton");
|
||||
|
||||
interface Props {
|
||||
albumId: string;
|
||||
@@ -60,7 +63,7 @@
|
||||
try {
|
||||
const userId = $auth.user?.id;
|
||||
if (!userId) {
|
||||
console.error("No user ID found");
|
||||
log.error("No user ID found");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -95,7 +98,7 @@
|
||||
await downloads.refresh(userId);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Album download operation failed:", error);
|
||||
log.error("Album download operation failed:", error);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides, resolveIsFavorite } from "$lib/stores/favorites";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("ArtistDetailView");
|
||||
|
||||
interface Props {
|
||||
artist: MediaItem;
|
||||
@@ -47,7 +50,7 @@
|
||||
});
|
||||
albums = albumsResult.items.filter(item => item.kind === "album");
|
||||
} catch (e) {
|
||||
console.warn("Failed to load albums:", e);
|
||||
log.warn("Failed to load albums:", e);
|
||||
} finally {
|
||||
albumsLoading = false;
|
||||
}
|
||||
@@ -62,7 +65,7 @@
|
||||
});
|
||||
topTracks = tracksResult.items.filter(item => item.kind === "track");
|
||||
} catch (e) {
|
||||
console.warn("Failed to load tracks:", e);
|
||||
log.warn("Failed to load tracks:", e);
|
||||
} finally {
|
||||
tracksLoading = false;
|
||||
}
|
||||
@@ -82,14 +85,14 @@
|
||||
.slice(0, 6);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Failed to load related artists:", e);
|
||||
log.warn("Failed to load related artists:", e);
|
||||
} finally {
|
||||
artistsLoading = false;
|
||||
}
|
||||
|
||||
singlesLoading = false;
|
||||
} catch (e) {
|
||||
console.error("Error loading artist content:", e);
|
||||
log.error("Error loading artist content:", e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
<script lang="ts">
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isServerReachable } from "$lib/stores/connectivity";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("ClearHistoryButton");
|
||||
|
||||
interface Props {
|
||||
/** Series or season id to clear. */
|
||||
@@ -51,7 +54,7 @@
|
||||
await auth.getRepository().clearWatchHistory(itemId);
|
||||
onCleared?.();
|
||||
} catch (e) {
|
||||
console.error("Failed to clear watch history:", e);
|
||||
log.error("Failed to clear watch history:", e);
|
||||
alert(
|
||||
`Could not clear watch history: ${e instanceof Error ? e.message : String(e)}`
|
||||
);
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import DownloadButtonCore from "./DownloadButtonCore.svelte";
|
||||
import type { DownloadState } from "./DownloadButtonCore.svelte";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("DownloadButton");
|
||||
|
||||
/**
|
||||
* Single audio track download button
|
||||
@@ -39,7 +42,7 @@
|
||||
});
|
||||
|
||||
async function handleClick() {
|
||||
console.log("🖱️ Download button clicked! Current status:", status);
|
||||
log.debug("🖱️ Download button clicked! Current status:", status);
|
||||
if (isProcessing) return;
|
||||
|
||||
isProcessing = true;
|
||||
@@ -63,25 +66,25 @@
|
||||
// Start download
|
||||
const userId = $auth.user?.id;
|
||||
if (!userId) {
|
||||
console.error("No user ID found");
|
||||
log.error("No user ID found");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const repo = auth.getRepository();
|
||||
|
||||
console.log("🎯 Starting download for item:", itemId);
|
||||
log.debug("🎯 Starting download for item:", itemId);
|
||||
|
||||
// Get stream URL
|
||||
const streamUrl = await repo.getAudioStreamUrl(itemId);
|
||||
console.log(" Stream URL obtained:", streamUrl?.substring(0, 50) + "...");
|
||||
log.debug(" Stream URL obtained:", streamUrl?.substring(0, 50) + "...");
|
||||
if (!streamUrl) {
|
||||
throw new Error("Failed to get stream URL");
|
||||
}
|
||||
|
||||
// Get target directory
|
||||
const targetDir = await commands.storageGetPath();
|
||||
console.log(" Target directory:", targetDir);
|
||||
log.debug(" Target directory:", targetDir);
|
||||
|
||||
// Queue and start download in single atomic operation
|
||||
const downloadId = await commands.downloadItemAndStart({
|
||||
@@ -93,16 +96,16 @@
|
||||
artistName: artistName || null,
|
||||
albumName: albumName || null,
|
||||
});
|
||||
console.log(" Download queued and started with ID:", downloadId);
|
||||
log.debug(" Download queued and started with ID:", downloadId);
|
||||
|
||||
// Refresh downloads list
|
||||
await downloads.refresh(userId);
|
||||
} catch (e) {
|
||||
console.error("❌ Failed to start download:", e);
|
||||
log.error("❌ Failed to start download:", e);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Download operation failed:", error);
|
||||
log.error("Download operation failed:", error);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||
import { useOfflineFilterReload } from "$lib/composables/useOfflineFilterReload";
|
||||
import type { Genre, MediaItem, ItemType } from "$lib/api/types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("GenericGenreBrowser");
|
||||
|
||||
/**
|
||||
* Generic genre browser supporting Movies, Music Albums, and TV Series
|
||||
@@ -92,7 +95,7 @@
|
||||
genres = result.sort((a, b) => a.name.localeCompare(b.name));
|
||||
applyFilter();
|
||||
} catch (e) {
|
||||
console.error("Failed to load genres:", e);
|
||||
log.error("Failed to load genres:", e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
@@ -115,7 +118,7 @@
|
||||
});
|
||||
genreItems = result.items;
|
||||
} catch (e) {
|
||||
console.error("Failed to load genre items:", e);
|
||||
log.error("Failed to load genre items:", e);
|
||||
} finally {
|
||||
loadingItems = false;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
import TrackList from "./TrackList.svelte";
|
||||
import AlphabetScrollBar from "./AlphabetScrollBar.svelte";
|
||||
import { excludePodcasts } from "$lib/utils/podcastFilter";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("GenericMediaListPage");
|
||||
|
||||
/**
|
||||
* Generic media list page supporting Albums, Artists, Playlists, and Tracks
|
||||
@@ -154,7 +157,7 @@
|
||||
items = excludePodcasts(result.items);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Failed to load ${config.itemType}:`, e);
|
||||
log.error(`Failed to load ${config.itemType}:`, e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides, resolveIsFavorite } from "$lib/stores/favorites";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("MediaCard");
|
||||
|
||||
interface Props {
|
||||
item: MediaItem | Library;
|
||||
@@ -171,7 +174,7 @@
|
||||
media.albumName ?? undefined
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[MediaCard] Failed to queue download:", err);
|
||||
log.error("Failed to queue download:", err);
|
||||
queueError = "Failed to queue";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
import LibraryGrid from "./LibraryGrid.svelte";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("PersonDetailView");
|
||||
|
||||
interface Props {
|
||||
person: MediaItem;
|
||||
@@ -34,7 +37,7 @@
|
||||
movies = result.items.filter(item => item.kind === "movie");
|
||||
series = result.items.filter(item => item.kind === "series");
|
||||
} catch (e) {
|
||||
console.error("Failed to load filmography:", e);
|
||||
log.error("Failed to load filmography:", e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
import FavoriteButton from "$lib/components/FavoriteButton.svelte";
|
||||
import { favoriteOverrides } from "$lib/stores/favorites";
|
||||
import { formatDuration } from "$lib/utils/duration";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("PlaylistDetail");
|
||||
|
||||
interface Props {
|
||||
playlist: MediaItem;
|
||||
@@ -40,7 +43,7 @@
|
||||
const repo = auth.getRepository();
|
||||
entries = await repo.getPlaylistItems(playlist.id);
|
||||
} catch (e) {
|
||||
console.error("[PlaylistDetail] Failed to load items:", e);
|
||||
log.error("Failed to load items:", e);
|
||||
toast.error("Failed to load playlist items");
|
||||
} finally {
|
||||
loading = false;
|
||||
@@ -62,7 +65,7 @@
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[PlaylistDetail] Failed to play all:", e);
|
||||
log.error("Failed to play all:", e);
|
||||
toast.error("Failed to play playlist");
|
||||
}
|
||||
}
|
||||
@@ -82,7 +85,7 @@
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[PlaylistDetail] Failed to shuffle play:", e);
|
||||
log.error("Failed to shuffle play:", e);
|
||||
toast.error("Failed to shuffle playlist");
|
||||
}
|
||||
}
|
||||
@@ -100,7 +103,7 @@
|
||||
playlist.name = trimmed;
|
||||
toast.success("Playlist renamed");
|
||||
} catch (e) {
|
||||
console.error("[PlaylistDetail] Failed to rename:", e);
|
||||
log.error("Failed to rename:", e);
|
||||
toast.error("Failed to rename playlist");
|
||||
editName = playlist.name;
|
||||
} finally {
|
||||
@@ -115,7 +118,7 @@
|
||||
toast.success("Playlist deleted");
|
||||
goto("/library");
|
||||
} catch (e) {
|
||||
console.error("[PlaylistDetail] Failed to delete:", e);
|
||||
log.error("Failed to delete:", e);
|
||||
toast.error("Failed to delete playlist");
|
||||
} finally {
|
||||
showDeleteConfirm = false;
|
||||
@@ -129,7 +132,7 @@
|
||||
entries = entries.filter(e => e.playlistItemId !== entry.playlistItemId);
|
||||
toast.success("Track removed");
|
||||
} catch (e) {
|
||||
console.error("[PlaylistDetail] Failed to remove track:", e);
|
||||
log.error("Failed to remove track:", e);
|
||||
toast.error("Failed to remove track");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import type { MediaItem, MediaKind, Person } from "$lib/api/types";
|
||||
import MediaCard from "./MediaCard.svelte";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("RelatedItemsSection");
|
||||
|
||||
interface Props {
|
||||
currentItemId: string;
|
||||
@@ -57,7 +60,7 @@
|
||||
return; // Success - return early
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Failed to load similar items from API:", e);
|
||||
log.warn("Failed to load similar items from API:", e);
|
||||
// Fall through to genre-based loading
|
||||
}
|
||||
}
|
||||
@@ -78,7 +81,7 @@
|
||||
|
||||
items = result.items.filter(item => item.id !== currentItemId);
|
||||
} catch (e) {
|
||||
console.warn("Failed to load related items by genre:", e);
|
||||
log.warn("Failed to load related items by genre:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +97,7 @@
|
||||
const artistAlbums = result.items.filter(item => item.id !== currentItemId);
|
||||
items = [...items, ...artistAlbums];
|
||||
} catch (e) {
|
||||
console.warn("Failed to load albums by artist:", e);
|
||||
log.warn("Failed to load albums by artist:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +109,7 @@
|
||||
relatedItems = uniqueItems;
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : "Failed to load related items";
|
||||
console.error("Error loading related items:", e);
|
||||
log.error("Error loading related items:", e);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { QUALITY_PRESETS, type QualityPreset } from "$lib/api/quality-presets";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("SeasonDownloadButton");
|
||||
|
||||
interface Props {
|
||||
seasonId: string;
|
||||
@@ -46,11 +49,11 @@
|
||||
try {
|
||||
const userId = $auth.user?.id;
|
||||
if (!userId) {
|
||||
console.error("No user ID found");
|
||||
log.error("No user ID found");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("📺 Starting season download for:", seasonName, "quality:", quality);
|
||||
log.debug("📺 Starting season download for:", seasonName, "quality:", quality);
|
||||
|
||||
// Get target directory
|
||||
const targetDir = await commands.storageGetPath();
|
||||
@@ -67,7 +70,7 @@
|
||||
quality
|
||||
);
|
||||
|
||||
console.log(`✅ Queued ${downloadIds.length} episodes for download`);
|
||||
log.debug(`✅ Queued ${downloadIds.length} episodes for download`);
|
||||
|
||||
// Pin the season item
|
||||
await downloads.pinItem(seasonId);
|
||||
@@ -77,9 +80,9 @@
|
||||
// rest as slots free up.
|
||||
const handle = auth.getRepository().getHandle();
|
||||
await commands.enqueueVideoDownloads(handle, downloadIds, targetDir);
|
||||
console.log(" Episodes enqueued; backend pump will start them");
|
||||
log.debug(" Episodes enqueued; backend pump will start them");
|
||||
} catch (error) {
|
||||
console.error("Failed to start season download:", error);
|
||||
log.error("Failed to start season download:", error);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { QUALITY_PRESETS, type QualityPreset } from "$lib/api/quality-presets";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("SeriesDownloadButton");
|
||||
|
||||
interface Props {
|
||||
seriesId: string;
|
||||
@@ -40,11 +43,11 @@
|
||||
try {
|
||||
const userId = $auth.user?.id;
|
||||
if (!userId) {
|
||||
console.error("No user ID found");
|
||||
log.error("No user ID found");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("📺 Starting series download for:", seriesName, "quality:", quality);
|
||||
log.debug("📺 Starting series download for:", seriesName, "quality:", quality);
|
||||
|
||||
// Get target directory
|
||||
const targetDir = await commands.storageGetPath();
|
||||
@@ -59,7 +62,7 @@
|
||||
quality
|
||||
);
|
||||
|
||||
console.log(` Queued ${downloadIds.length} episodes for download`);
|
||||
log.debug(` Queued ${downloadIds.length} episodes for download`);
|
||||
|
||||
// Pin the series item
|
||||
await downloads.pinItem(seriesId);
|
||||
@@ -69,9 +72,9 @@
|
||||
// rest as slots free up.
|
||||
const handle = auth.getRepository().getHandle();
|
||||
await commands.enqueueVideoDownloads(handle, downloadIds, targetDir);
|
||||
console.log(" Episodes enqueued; backend pump will start them");
|
||||
log.debug(" Episodes enqueued; backend pump will start them");
|
||||
} catch (error) {
|
||||
console.error("Failed to start series download:", error);
|
||||
log.error("Failed to start series download:", error);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
import AddToPlaylistModal from "$lib/components/playlist/AddToPlaylistModal.svelte";
|
||||
import { calculateMenuPosition, type MenuPosition } from "$lib/utils/menuPosition";
|
||||
import { formatDuration } from "$lib/utils/duration";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("TrackList");
|
||||
|
||||
/** Queue context for remote transfer - what type of queue is this? */
|
||||
export type QueueContext =
|
||||
@@ -55,7 +58,7 @@
|
||||
|
||||
// If this is an album, use the backend album command (more efficient)
|
||||
if (context && context.type === "album") {
|
||||
console.log(`[TrackList] Playing track: "${track.name}" (ID: ${track.id}, index in list: ${index})`);
|
||||
log.debug(`Playing track: "${track.name}" (ID: ${track.id}, index in list: ${index})`);
|
||||
await playerController.playAlbumTrack({
|
||||
albumId: context.albumId,
|
||||
albumName: context.albumName,
|
||||
@@ -91,7 +94,7 @@
|
||||
// Queue will auto-update from Rust backend event
|
||||
} catch (e) {
|
||||
const errorMessage = e instanceof Error ? e.message : 'Unknown error';
|
||||
console.error("Failed to play track:", errorMessage);
|
||||
log.error("Failed to play track:", errorMessage);
|
||||
toast.error(`Failed to play track: ${errorMessage}`, 5000);
|
||||
} finally {
|
||||
isPlayingTrack = null;
|
||||
@@ -145,9 +148,9 @@
|
||||
try {
|
||||
// Queue store now handles everything in Rust - just pass the track
|
||||
await queue.addToQueue(track, position);
|
||||
console.log(`Added "${track.name}" to queue (${position})`);
|
||||
log.debug(`Added "${track.name}" to queue (${position})`);
|
||||
} catch (e) {
|
||||
console.error("Failed to add to queue:", e);
|
||||
log.error("Failed to add to queue:", e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { QUALITY_PRESETS, type QualityPreset } from "$lib/api/quality-presets";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("VideoDownloadButton");
|
||||
|
||||
interface Props {
|
||||
itemId: string;
|
||||
@@ -57,17 +60,17 @@
|
||||
try {
|
||||
const userId = $auth.user?.id;
|
||||
if (!userId) {
|
||||
console.error("No user ID found");
|
||||
log.error("No user ID found");
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = auth.getRepository();
|
||||
|
||||
console.log("🎬 Starting video download for item:", itemId, "quality:", quality);
|
||||
log.debug("🎬 Starting video download for item:", itemId, "quality:", quality);
|
||||
|
||||
// Get stream URL based on quality
|
||||
const streamUrl = await repo.getVideoDownloadUrl(itemId, quality);
|
||||
console.log(" Stream URL obtained");
|
||||
log.debug(" Stream URL obtained");
|
||||
|
||||
// Get target directory
|
||||
const targetDir = await commands.storageGetPath();
|
||||
@@ -85,7 +88,7 @@
|
||||
filePath = `videos/${safeName}.mp4`;
|
||||
}
|
||||
|
||||
console.log(" File path:", filePath);
|
||||
log.debug(" File path:", filePath);
|
||||
|
||||
// Queue download with video metadata
|
||||
const downloadId = await downloads.downloadVideo(
|
||||
@@ -101,16 +104,16 @@
|
||||
episodeNumber,
|
||||
seasonNumber
|
||||
);
|
||||
console.log(" Download queued with ID:", downloadId);
|
||||
log.debug(" Download queued with ID:", downloadId);
|
||||
|
||||
// Pin the item metadata
|
||||
await downloads.pinItem(itemId);
|
||||
|
||||
// Actually start the download
|
||||
await commands.startDownload(downloadId, streamUrl, targetDir);
|
||||
console.log(" Download started");
|
||||
log.debug(" Download started");
|
||||
} catch (error) {
|
||||
console.error("Failed to start video download:", error);
|
||||
log.error("Failed to start video download:", error);
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { syncService } from "$lib/services/syncService";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("WatchedToggleButton");
|
||||
|
||||
interface Props {
|
||||
/** Episode, season or series id. */
|
||||
@@ -81,7 +84,7 @@
|
||||
} catch (e) {
|
||||
// Put the button back where it was — the change did not happen.
|
||||
optimistic = null;
|
||||
console.error("Failed to change watched state:", e);
|
||||
log.error("Failed to change watched state:", e);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@
|
||||
import VolumeControl from "./VolumeControl.svelte";
|
||||
import CachedImage from "../common/CachedImage.svelte";
|
||||
import { currentQueueItem } from "$lib/stores/queue";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("AudioPlayer");
|
||||
|
||||
interface Props {
|
||||
media: MediaItem | null;
|
||||
@@ -130,7 +133,7 @@
|
||||
queue.skipTo(index);
|
||||
await playerController.skipTo(index);
|
||||
} catch (e) {
|
||||
console.error("Failed to skip to queue item:", e);
|
||||
log.error("Failed to skip to queue item:", e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -38,6 +38,9 @@
|
||||
import CastButton from "$lib/components/sessions/CastButton.svelte";
|
||||
import VolumeControl from "./VolumeControl.svelte";
|
||||
import CachedImage from "../common/CachedImage.svelte";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("MiniPlayer");
|
||||
|
||||
interface Props {
|
||||
media: MediaItem | null;
|
||||
@@ -159,7 +162,7 @@
|
||||
await playerController.seek(newPosition);
|
||||
haptics.tap();
|
||||
} catch (err) {
|
||||
console.error("Failed to seek:", err);
|
||||
log.error("Failed to seek:", err);
|
||||
toast.show("Failed to seek", "error");
|
||||
}
|
||||
}
|
||||
@@ -230,7 +233,7 @@
|
||||
// Vertical swipe
|
||||
if (Math.abs(diffY) > swipeThreshold && diffY > 0) {
|
||||
// Swiped up - Open full player
|
||||
console.log("[MiniPlayer] Swipe-up detected, expanding player");
|
||||
log.debug("Swipe-up detected, expanding player");
|
||||
haptics.tap();
|
||||
onExpand?.();
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { queue } from "$lib/stores/queue";
|
||||
import CachedImage from "../common/CachedImage.svelte";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("QueueView");
|
||||
|
||||
interface Props {
|
||||
items: MediaItem[];
|
||||
@@ -82,7 +85,7 @@
|
||||
// Sync with backend
|
||||
await playerController.moveInQueue(fromIndex, toIndex);
|
||||
} catch (e) {
|
||||
console.error("Failed to move queue item:", e);
|
||||
log.error("Failed to move queue item:", e);
|
||||
// The store already updated optimistically, refresh if needed
|
||||
}
|
||||
}
|
||||
@@ -109,7 +112,7 @@
|
||||
queue.removeFromQueue(index);
|
||||
await playerController.removeFromQueue(index);
|
||||
} catch (err) {
|
||||
console.error("Failed to remove from queue:", err);
|
||||
log.error("Failed to remove from queue:", err);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -75,6 +75,9 @@
|
||||
planHandoffReturn,
|
||||
type BackgroundAudioState,
|
||||
} from "./backgroundAudioHandoff";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("VideoPlayer");
|
||||
|
||||
interface Props {
|
||||
media: MediaItem | null;
|
||||
@@ -287,11 +290,11 @@
|
||||
// TRACES: UR-021 | IR-016, JA-009 | DR-024
|
||||
const audioTracks = $derived(() => {
|
||||
if (!media || !media.mediaStreams) {
|
||||
console.log("[VideoPlayer] No media or mediaStreams available");
|
||||
log.debug("No media or mediaStreams available");
|
||||
return [];
|
||||
}
|
||||
const tracks = media.mediaStreams.filter(stream => stream.kind === "audio");
|
||||
console.log("[VideoPlayer] Found audio tracks:", tracks.length, tracks);
|
||||
log.debug("Found audio tracks:", tracks.length, tracks);
|
||||
return tracks;
|
||||
});
|
||||
|
||||
@@ -304,7 +307,7 @@
|
||||
if (preference.audioTrackDisplayTitle) {
|
||||
const match = tracks.find(t => t.displayTitle === preference.audioTrackDisplayTitle);
|
||||
if (match) {
|
||||
console.log("[VideoPlayer] Matched audio track by display title:", match.displayTitle);
|
||||
log.debug("Matched audio track by display title:", match.displayTitle);
|
||||
return match.index;
|
||||
}
|
||||
}
|
||||
@@ -313,14 +316,14 @@
|
||||
if (preference.audioTrackLanguage) {
|
||||
const match = tracks.find(t => t.language === preference.audioTrackLanguage);
|
||||
if (match) {
|
||||
console.log("[VideoPlayer] Matched audio track by language:", match.language);
|
||||
log.debug("Matched audio track by language:", match.language);
|
||||
return match.index;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to default track
|
||||
const defaultTrack = tracks.find(t => t.isDefault) || tracks[0];
|
||||
console.log("[VideoPlayer] Using default/first audio track:", defaultTrack.displayTitle || defaultTrack.language);
|
||||
log.debug("Using default/first audio track:", defaultTrack.displayTitle || defaultTrack.language);
|
||||
return defaultTrack.index;
|
||||
}
|
||||
|
||||
@@ -335,15 +338,15 @@
|
||||
const preference = await commands.storageGetSeriesAudioPreference(userId, media.seriesId);
|
||||
|
||||
if (preference) {
|
||||
console.log("[VideoPlayer] Loaded series audio preference:", preference);
|
||||
log.debug("Loaded series audio preference:", preference);
|
||||
const matchedIndex = findBestAudioTrack(preference);
|
||||
if (matchedIndex !== null) {
|
||||
selectedAudioTrackIndex = matchedIndex;
|
||||
console.log("[VideoPlayer] Applied series audio preference, track index:", matchedIndex);
|
||||
log.debug("Applied series audio preference, track index:", matchedIndex);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[VideoPlayer] Failed to load series audio preference:", err);
|
||||
log.warn("Failed to load series audio preference:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,11 +358,11 @@
|
||||
// TRACES: UR-020 | DR-176 | UT-168
|
||||
const subtitleTracks = $derived(() => {
|
||||
if (!media || !media.mediaStreams) {
|
||||
console.log("[VideoPlayer] No media or mediaStreams available for subtitles");
|
||||
log.debug("No media or mediaStreams available for subtitles");
|
||||
return [];
|
||||
}
|
||||
const tracks = subtitleStreamsOf(media.mediaStreams);
|
||||
console.log("[VideoPlayer] Found subtitle tracks:", tracks.length, tracks);
|
||||
log.debug("Found subtitle tracks:", tracks.length, tracks);
|
||||
return tracks;
|
||||
});
|
||||
|
||||
@@ -547,7 +550,7 @@
|
||||
if (isHlsStream && Hls.isSupported()) {
|
||||
// Clean up existing HLS instance if any - CRITICAL for preventing dual audio
|
||||
if (hls) {
|
||||
console.log('[VideoPlayer] Cleaning up existing HLS instance');
|
||||
log.debug('Cleaning up existing HLS instance');
|
||||
// Detach from media element first to stop all audio/video
|
||||
hls.detachMedia();
|
||||
// Stop loading and flush buffers
|
||||
@@ -571,7 +574,7 @@
|
||||
setTimeout(() => {
|
||||
if (!videoElement) return;
|
||||
|
||||
console.log('[VideoPlayer] Creating new HLS instance for:', currentStreamUrl);
|
||||
log.debug('Creating new HLS instance for:', currentStreamUrl);
|
||||
|
||||
// Create new HLS instance
|
||||
hls = new Hls({
|
||||
@@ -599,14 +602,14 @@
|
||||
|
||||
// Listen for media attached event
|
||||
hls.on(Hls.Events.MEDIA_ATTACHED, () => {
|
||||
console.log('[VideoPlayer] HLS.js attached to video element');
|
||||
log.debug('HLS.js attached to video element');
|
||||
// Load the HLS stream
|
||||
hls!.loadSource(currentStreamUrl);
|
||||
});
|
||||
|
||||
// Listen for manifest parsed event
|
||||
hls.on(Hls.Events.MANIFEST_PARSED, () => {
|
||||
console.log('[VideoPlayer] HLS manifest parsed, ready to play');
|
||||
log.debug('HLS manifest parsed, ready to play');
|
||||
});
|
||||
|
||||
// On the Android WebView the element's own `canplay` may not fire for
|
||||
@@ -623,7 +626,7 @@
|
||||
if (canplayFallbackTimeout) clearTimeout(canplayFallbackTimeout);
|
||||
canplayFallbackTimeout = setTimeout(() => {
|
||||
if (!isMediaReady && videoElement && videoElement.readyState >= 2) {
|
||||
console.warn('[VideoPlayer] HLS canplay fallback - revealing video (readyState:', videoElement.readyState, ')');
|
||||
log.warn('HLS canplay fallback - revealing video (readyState:', videoElement.readyState, ')');
|
||||
markMediaReady();
|
||||
}
|
||||
}, 5000);
|
||||
@@ -633,7 +636,7 @@
|
||||
|
||||
// Handle errors
|
||||
hls.on(Hls.Events.ERROR, (event, data) => {
|
||||
console.error('[VideoPlayer] HLS error:', data);
|
||||
log.error('HLS error:', data);
|
||||
if (data.fatal) {
|
||||
// Is this the stream ending or the stream breaking? Jellyfin's
|
||||
// transcoded HLS doesn't always emit #EXT-X-ENDLIST, so both arrive
|
||||
@@ -650,25 +653,25 @@
|
||||
attempts: hlsFatalRecoveryAttempts,
|
||||
})) {
|
||||
case 'ended':
|
||||
console.log('[VideoPlayer] Fatal network error near end of stream - treating as ended');
|
||||
log.debug('Fatal network error near end of stream - treating as ended');
|
||||
notifyEnded();
|
||||
break;
|
||||
case 'retry':
|
||||
console.error('[VideoPlayer] Fatal network error, trying to recover (attempt', hlsFatalRecoveryAttempts, ')');
|
||||
log.error('Fatal network error, trying to recover (attempt', hlsFatalRecoveryAttempts, ')');
|
||||
hls!.startLoad();
|
||||
break;
|
||||
case 'giveUp':
|
||||
console.error('[VideoPlayer] Fatal network error, max recovery attempts reached');
|
||||
log.error('Fatal network error, max recovery attempts reached');
|
||||
hls!.destroy();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case Hls.ErrorTypes.MEDIA_ERROR:
|
||||
console.error('[VideoPlayer] Fatal media error, trying to recover');
|
||||
log.error('Fatal media error, trying to recover');
|
||||
hls!.recoverMediaError();
|
||||
break;
|
||||
default:
|
||||
console.error('[VideoPlayer] Unrecoverable HLS error');
|
||||
log.error('Unrecoverable HLS error');
|
||||
hls!.destroy();
|
||||
break;
|
||||
}
|
||||
@@ -678,7 +681,7 @@
|
||||
|
||||
// Cleanup on effect re-run
|
||||
return () => {
|
||||
console.log('[VideoPlayer] Effect cleanup: destroying HLS instance');
|
||||
log.debug('Effect cleanup: destroying HLS instance');
|
||||
if (hls) {
|
||||
hls.detachMedia();
|
||||
hls.stopLoad();
|
||||
@@ -691,11 +694,11 @@
|
||||
};
|
||||
} else if (isHlsStream && videoElement.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
// Native HLS support (Safari)
|
||||
console.log('[VideoPlayer] Using native HLS support');
|
||||
log.debug('Using native HLS support');
|
||||
videoElement.src = currentStreamUrl;
|
||||
} else {
|
||||
// Not an HLS stream, use regular video element
|
||||
console.log('[VideoPlayer] Using regular video element for non-HLS stream');
|
||||
log.debug('Using regular video element for non-HLS stream');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -704,24 +707,24 @@
|
||||
if (videoElement) {
|
||||
videoElement.muted = false;
|
||||
videoElement.volume = 1.0;
|
||||
console.log("[VideoPlayer] Video element configured: muted=", videoElement.muted, "volume=", videoElement.volume);
|
||||
log.debug("Video element configured: muted=", videoElement.muted, "volume=", videoElement.volume);
|
||||
|
||||
// DIAGNOSTIC: Check if video has audio tracks
|
||||
if ((videoElement as any).audioTracks) {
|
||||
console.log("[VideoPlayer] Audio tracks count:", (videoElement as any).audioTracks.length);
|
||||
log.debug("Audio tracks count:", (videoElement as any).audioTracks.length);
|
||||
|
||||
// Set initial audio track (prefer default track)
|
||||
if (selectedAudioTrackIndex === null && audioTracks().length > 0) {
|
||||
const defaultTrack = audioTracks().find(t => t.isDefault);
|
||||
selectedAudioTrackIndex = defaultTrack ? defaultTrack.index : audioTracks()[0].index;
|
||||
console.log("[VideoPlayer] Selected default audio track:", selectedAudioTrackIndex);
|
||||
log.debug("Selected default audio track:", selectedAudioTrackIndex);
|
||||
}
|
||||
}
|
||||
if ((videoElement as any).mozHasAudio !== undefined) {
|
||||
console.log("[VideoPlayer] mozHasAudio:", (videoElement as any).mozHasAudio);
|
||||
log.debug("mozHasAudio:", (videoElement as any).mozHasAudio);
|
||||
}
|
||||
if ((videoElement as any).webkitAudioDecodedByteCount !== undefined) {
|
||||
console.log("[VideoPlayer] webkitAudioDecodedByteCount:", (videoElement as any).webkitAudioDecodedByteCount);
|
||||
log.debug("webkitAudioDecodedByteCount:", (videoElement as any).webkitAudioDecodedByteCount);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -749,7 +752,7 @@
|
||||
return;
|
||||
}
|
||||
untrack(() => {
|
||||
console.log("[VideoPlayer] Initial position changed, seeking to:", pos);
|
||||
log.debug("Initial position changed, seeking to:", pos);
|
||||
lastAppliedInitialPosition = pos;
|
||||
if (videoElement) {
|
||||
videoElement.currentTime = pos;
|
||||
@@ -775,7 +778,7 @@
|
||||
selectedQuality = settings.streamingQuality ?? "original";
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn("[VideoPlayer] Failed to load streaming qualities:", err);
|
||||
log.warn("Failed to load streaming qualities:", err);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -808,8 +811,8 @@
|
||||
// Initialize player via Rust - Rust will decide which backend to use based on platform
|
||||
if (media && currentStreamUrl) {
|
||||
try {
|
||||
console.log("[VideoPlayer] Initializing player for:", media.name);
|
||||
console.log("[VideoPlayer] Stream URL:", currentStreamUrl);
|
||||
log.debug("Initializing player for:", media.name);
|
||||
log.debug("Stream URL:", currentStreamUrl);
|
||||
|
||||
// Resolve subtitle URLs for the native (ExoPlayer) path. These must be
|
||||
// in hand *before* the play request: ExoPlayer sideloads subtitles as
|
||||
@@ -827,7 +830,7 @@
|
||||
sentSubtitleTracks = mediaSourceId
|
||||
? await resolveSubtitleTracks(media.mediaStreams, (index) => getSubtitleUrl(index))
|
||||
: [];
|
||||
console.log(`[VideoPlayer] Sending ${sentSubtitleTracks.length} subtitle tracks to the backend`);
|
||||
log.debug(`Sending ${sentSubtitleTracks.length} subtitle tracks to the backend`);
|
||||
|
||||
// Call Rust backend to start playback
|
||||
// Rust will choose ExoPlayer (Android), libmpv (Linux), or tell us to use HTML5
|
||||
@@ -847,7 +850,7 @@
|
||||
// Rust tells us which backend it's using
|
||||
useHtml5Element = response.useHtml5Element;
|
||||
backendChosen = true;
|
||||
console.log(`[VideoPlayer] Backend: ${response.backend}, useHtml5Element: ${useHtml5Element}`);
|
||||
log.debug(`Backend: ${response.backend}, useHtml5Element: ${useHtml5Element}`);
|
||||
|
||||
// Rust reported a native backend (Android/ExoPlayer). Honour it only if
|
||||
// the user opted into the experimental native path; otherwise fall back
|
||||
@@ -858,13 +861,13 @@
|
||||
// just started, or ExoPlayer and the <video> element both decode the
|
||||
// same stream and the audio doubles.
|
||||
if (!useHtml5Element && !$experimentalNativeVideo) {
|
||||
console.log("[VideoPlayer] Native backend available but experimentalNativeVideo is off - using HTML5");
|
||||
log.debug("Native backend available but experimentalNativeVideo is off - using HTML5");
|
||||
useHtml5Element = true;
|
||||
try {
|
||||
await commands.playerStop();
|
||||
didStopBackendEarly = true;
|
||||
} catch (err) {
|
||||
console.warn("[VideoPlayer] Failed to stop native backend:", err);
|
||||
log.warn("Failed to stop native backend:", err);
|
||||
}
|
||||
} else if (!useHtml5Element) {
|
||||
// Native path: clear the opaque layers between the viewport and the
|
||||
@@ -872,7 +875,7 @@
|
||||
// Paired with disableNativeVideoCompositing() in the teardown path —
|
||||
// leaving this on renders the rest of the app over a transparent
|
||||
// window.
|
||||
console.log("[VideoPlayer] Using native ExoPlayer video surface");
|
||||
log.debug("Using native ExoPlayer video surface");
|
||||
enableNativeVideoCompositing();
|
||||
}
|
||||
|
||||
@@ -880,14 +883,14 @@
|
||||
// For transcoded content, we need to keep the backend running to handle seeking/audio track switching
|
||||
if (useHtml5Element && !needsTranscoding && !didStopBackendEarly) {
|
||||
try {
|
||||
console.log("[VideoPlayer] Using HTML5 for direct stream - stopping backend player to prevent dual audio");
|
||||
log.debug("Using HTML5 for direct stream - stopping backend player to prevent dual audio");
|
||||
await commands.playerStop();
|
||||
didStopBackendEarly = true; // Track that we stopped the backend
|
||||
} catch (err) {
|
||||
console.warn("[VideoPlayer] Failed to stop backend player:", err);
|
||||
log.warn("Failed to stop backend player:", err);
|
||||
}
|
||||
} else if (useHtml5Element && needsTranscoding) {
|
||||
console.log("[VideoPlayer] Using HTML5 for transcoded stream - keeping backend for seeking/transcoding decisions");
|
||||
log.debug("Using HTML5 for transcoded stream - keeping backend for seeking/transcoding decisions");
|
||||
// Backend is kept running but should not play audio since HTML5 element handles playback
|
||||
didStartNativePlayback = true; // Track that we need to stop backend on unmount
|
||||
}
|
||||
@@ -972,12 +975,12 @@
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to initialize player:", err);
|
||||
log.error("Failed to initialize player:", err);
|
||||
if (backendChosen) {
|
||||
// The backend already accepted the item; a later error (e.g. event
|
||||
// subscription) must not silently switch the seek/controls path to
|
||||
// HTML5 while the native backend keeps playing.
|
||||
console.warn("[VideoPlayer] Backend already initialized - keeping native mode despite error");
|
||||
log.warn("Backend already initialized - keeping native mode despite error");
|
||||
} else {
|
||||
// Fallback to HTML5 on error
|
||||
useHtml5Element = true;
|
||||
@@ -1042,8 +1045,8 @@
|
||||
// Flattened to a single string on purpose: the Android WebView console
|
||||
// bridge stringifies objects as "[object Object]" in logcat, which made
|
||||
// this whole payload useless when diagnosing over adb.
|
||||
console.log(
|
||||
`[VideoPlayer Debug] t=${videoElement.currentTime.toFixed(2)}` +
|
||||
log.debug(
|
||||
`Debug t=${videoElement.currentTime.toFixed(2)}` +
|
||||
` display=${currentTime.toFixed(2)}` +
|
||||
` readyState=${videoElement.readyState}` +
|
||||
` networkState=${videoElement.networkState}` +
|
||||
@@ -1111,7 +1114,7 @@
|
||||
|
||||
// Clean up HLS.js instance - prevent dual audio on unmount
|
||||
if (hls) {
|
||||
console.log("[VideoPlayer] Destroying HLS.js instance on unmount");
|
||||
log.debug("Destroying HLS.js instance on unmount");
|
||||
hls.detachMedia(); // Detach from video element first
|
||||
hls.stopLoad(); // Stop loading and flush buffers
|
||||
hls.destroy();
|
||||
@@ -1129,10 +1132,10 @@
|
||||
// Skip if we already stopped the backend early (non-transcoded + HTML5)
|
||||
if (didStartNativePlayback && !didStopBackendEarly) {
|
||||
try {
|
||||
console.log("[VideoPlayer] Stopping backend player on component unmount");
|
||||
log.debug("Stopping backend player on component unmount");
|
||||
await commands.playerStop();
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to stop backend player:", err);
|
||||
log.error("Failed to stop backend player:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1187,20 +1190,20 @@
|
||||
}
|
||||
|
||||
function handleLoadedMetadata() {
|
||||
console.log("[VideoPlayer] loadedmetadata event");
|
||||
log.debug("loadedmetadata event");
|
||||
// Intrinsic dimensions are known now, which is what PiP sizes its window
|
||||
// from — before this they are 0 and the ratio would be rejected. (DR-160)
|
||||
reportPipVideoState();
|
||||
console.log("[VideoPlayer] Video element duration:", videoElement?.duration);
|
||||
console.log("[VideoPlayer] Media item runTimeTicks:", media?.runTimeTicks);
|
||||
console.log("[VideoPlayer] Needs transcoding:", needsTranscoding);
|
||||
log.debug("Video element duration:", videoElement?.duration);
|
||||
log.debug("Media item runTimeTicks:", media?.runTimeTicks);
|
||||
log.debug("Needs transcoding:", needsTranscoding);
|
||||
|
||||
// For direct streams without runTimeTicks, use video element's duration
|
||||
if (videoElement && videoElement.duration && !isNaN(videoElement.duration) && videoElement.duration !== Infinity) {
|
||||
const newDuration = videoElement.duration;
|
||||
console.log("[VideoPlayer] Setting videoDuration to:", newDuration);
|
||||
log.debug("Setting videoDuration to:", newDuration);
|
||||
videoDuration = newDuration;
|
||||
console.log("[VideoPlayer] videoDuration state is now:", videoDuration);
|
||||
log.debug("videoDuration state is now:", videoDuration);
|
||||
}
|
||||
|
||||
// Tell the Rust controller the media is loaded and its duration (mirrors the
|
||||
@@ -1209,8 +1212,8 @@
|
||||
|
||||
// Use setTimeout to log the derived value after reactive updates
|
||||
setTimeout(() => {
|
||||
console.log("[VideoPlayer] Derived duration value:", duration);
|
||||
console.log("[VideoPlayer] Duration source:", media?.runTimeTicks ? "runTimeTicks" : "video element");
|
||||
log.debug("Derived duration value:", duration);
|
||||
log.debug("Duration source:", media?.runTimeTicks ? "runTimeTicks" : "video element");
|
||||
}, 0);
|
||||
}
|
||||
|
||||
@@ -1251,15 +1254,15 @@
|
||||
el.volume = 1.0;
|
||||
if (shouldPlay) await el.play();
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to resume after background audio:", err);
|
||||
log.error("Failed to resume after background audio:", err);
|
||||
}
|
||||
};
|
||||
|
||||
if (el.readyState >= 1 /* HAVE_METADATA */) {
|
||||
console.log("[VideoPlayer] Applying foreground seek to:", (seekOffset + seekTo).toFixed(1));
|
||||
log.debug("Applying foreground seek to:", (seekOffset + seekTo).toFixed(1));
|
||||
await doSeek();
|
||||
} else {
|
||||
console.log("[VideoPlayer] Deferring foreground seek until loadedmetadata:", (seekOffset + seekTo).toFixed(1));
|
||||
log.debug("Deferring foreground seek until loadedmetadata:", (seekOffset + seekTo).toFixed(1));
|
||||
el.addEventListener("loadedmetadata", () => { void doSeek(); }, { once: true });
|
||||
}
|
||||
return true;
|
||||
@@ -1267,7 +1270,7 @@
|
||||
|
||||
function markMediaReady() {
|
||||
if (isMediaReady) return;
|
||||
console.log("[VideoPlayer] Marking media ready");
|
||||
log.debug("Marking media ready");
|
||||
isMediaReady = true;
|
||||
// A handoff return can be revealed here (not via canplay) — apply its seek.
|
||||
void applyPendingForegroundSeek();
|
||||
@@ -1275,14 +1278,14 @@
|
||||
|
||||
async function handleCanPlay() {
|
||||
// Media is ready to play - transition from Loading to Playing state (DR-001)
|
||||
console.log("[VideoPlayer] canplay event fired - media is ready");
|
||||
log.debug("canplay event fired - media is ready");
|
||||
isMediaReady = true;
|
||||
|
||||
// Ensure video is unmuted and at max volume (critical for Android)
|
||||
if (videoElement) {
|
||||
videoElement.muted = false;
|
||||
videoElement.volume = 1.0;
|
||||
console.log("[VideoPlayer] Video unmuted on canplay, volume: 1.0");
|
||||
log.debug("Video unmuted on canplay, volume: 1.0");
|
||||
}
|
||||
|
||||
// Returning from background audio: resume the <video> at the position native
|
||||
@@ -1294,7 +1297,7 @@
|
||||
|
||||
// Seek to initial position if resuming playback
|
||||
if (initialPosition && initialPosition > 0 && !hasPerformedInitialSeek && videoElement) {
|
||||
console.log("[VideoPlayer] Seeking to initial position:", initialPosition);
|
||||
log.debug("Seeking to initial position:", initialPosition);
|
||||
hasPerformedInitialSeek = true;
|
||||
lastAppliedInitialPosition = initialPosition; // mark this value as applied so the change-effect ignores it
|
||||
|
||||
@@ -1325,7 +1328,7 @@
|
||||
await videoElement.play();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to seek to initial position:", err);
|
||||
log.error("Failed to seek to initial position:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1335,7 +1338,7 @@
|
||||
const error = video.error;
|
||||
|
||||
// Log comprehensive error details
|
||||
console.error("[VideoPlayer] Video error event:", {
|
||||
log.error("Video error event:", {
|
||||
code: error?.code,
|
||||
message: error?.message,
|
||||
networkState: video.networkState,
|
||||
@@ -1354,28 +1357,28 @@
|
||||
|
||||
const errorCode = error?.code || 0;
|
||||
const msg = errorMessages[errorCode] || `Unknown error (code ${errorCode})`;
|
||||
console.error("[VideoPlayer] Error interpretation:", msg);
|
||||
log.error("Error interpretation:", msg);
|
||||
|
||||
// Log additional debugging info
|
||||
console.error("[VideoPlayer] Stream URL:", currentStreamUrl);
|
||||
console.error("[VideoPlayer] Needs transcoding:", needsTranscoding);
|
||||
log.error("Stream URL:", currentStreamUrl);
|
||||
log.error("Needs transcoding:", needsTranscoding);
|
||||
|
||||
// Network state meanings: 0=EMPTY, 1=IDLE, 2=LOADING, 3=NO_SOURCE
|
||||
const networkStates = ["NETWORK_EMPTY", "NETWORK_IDLE", "NETWORK_LOADING", "NETWORK_NO_SOURCE"];
|
||||
console.error("[VideoPlayer] Network state:", networkStates[video.networkState] || video.networkState);
|
||||
log.error("Network state:", networkStates[video.networkState] || video.networkState);
|
||||
|
||||
// Ready state meanings: 0=NOTHING, 1=METADATA, 2=CURRENT_DATA, 3=FUTURE_DATA, 4=ENOUGH_DATA
|
||||
const readyStates = ["HAVE_NOTHING", "HAVE_METADATA", "HAVE_CURRENT_DATA", "HAVE_FUTURE_DATA", "HAVE_ENOUGH_DATA"];
|
||||
console.error("[VideoPlayer] Ready state:", readyStates[video.readyState] || video.readyState);
|
||||
log.error("Ready state:", readyStates[video.readyState] || video.readyState);
|
||||
}
|
||||
|
||||
function handleWaiting() {
|
||||
console.log("[VideoPlayer] waiting event - buffering");
|
||||
log.debug("waiting event - buffering");
|
||||
isBuffering = true;
|
||||
}
|
||||
|
||||
function handlePlaying() {
|
||||
console.log("[VideoPlayer] playing event - playback resumed");
|
||||
log.debug("playing event - playback resumed");
|
||||
isBuffering = false;
|
||||
// Safety net: if we reached `playing` we are definitely renderable, even if
|
||||
// `canplay`/hls FRAG_BUFFERED were missed on this WebView.
|
||||
@@ -1383,9 +1386,9 @@
|
||||
}
|
||||
|
||||
function handleLoadStart() {
|
||||
console.log("[VideoPlayer] loadstart event - starting to load:", currentStreamUrl);
|
||||
console.log("[VideoPlayer] Video element readyState:", videoElement?.readyState);
|
||||
console.log("[VideoPlayer] Video element networkState:", videoElement?.networkState);
|
||||
log.debug("loadstart event - starting to load:", currentStreamUrl);
|
||||
log.debug("Video element readyState:", videoElement?.readyState);
|
||||
log.debug("Video element networkState:", videoElement?.networkState);
|
||||
|
||||
// Clear any existing fallback timeout
|
||||
if (canplayFallbackTimeout) {
|
||||
@@ -1395,12 +1398,12 @@
|
||||
// Set up a fallback timeout in case canplay event never fires
|
||||
canplayFallbackTimeout = setTimeout(() => {
|
||||
if (!isMediaReady && videoElement) {
|
||||
console.warn("[VideoPlayer] canplay event did not fire within 5 seconds");
|
||||
console.log("[VideoPlayer] Fallback check - readyState:", videoElement.readyState, "networkState:", videoElement.networkState);
|
||||
log.warn("canplay event did not fire within 5 seconds");
|
||||
log.debug("Fallback check - readyState:", videoElement.readyState, "networkState:", videoElement.networkState);
|
||||
|
||||
// Check if video is actually ready despite event not firing
|
||||
if (videoElement.readyState >= 3) { // HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA
|
||||
console.log("[VideoPlayer] Video appears ready (readyState >= 3), forcing media ready state");
|
||||
log.debug("Video appears ready (readyState >= 3), forcing media ready state");
|
||||
markMediaReady();
|
||||
}
|
||||
}
|
||||
@@ -1430,7 +1433,7 @@
|
||||
jrayActors = actors;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[VideoPlayer] JRay lookup failed:", err);
|
||||
log.warn("JRay lookup failed:", err);
|
||||
if (token === jrayRequestId) jrayActors = [];
|
||||
}
|
||||
}
|
||||
@@ -1508,8 +1511,8 @@
|
||||
// reason. Log the element state so an unexplained pause/resume loop can be
|
||||
// attributed from an adb capture instead of guessed at.
|
||||
const el = videoElement;
|
||||
console.log(
|
||||
`[VideoPlayer] pause event — t=${el ? el.currentTime.toFixed(2) : "?"}` +
|
||||
log.debug(
|
||||
`pause event — t=${el ? el.currentTime.toFixed(2) : "?"}` +
|
||||
` readyState=${el?.readyState}` +
|
||||
` networkState=${el?.networkState}` +
|
||||
` seeking=${el?.seeking}` +
|
||||
@@ -1553,7 +1556,7 @@
|
||||
try {
|
||||
await playerController.toggle();
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to toggle playback:", err);
|
||||
log.error("Failed to toggle playback:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1595,7 +1598,7 @@
|
||||
isDraggingSeekBar = false;
|
||||
|
||||
try {
|
||||
console.log("[VideoPlayer] Seeking to:", targetTime.toFixed(2));
|
||||
log.debug("Seeking to:", targetTime.toFixed(2));
|
||||
|
||||
// Optimistic display; the primitive updates currentTime/seekOffset as it
|
||||
// completes (reloadSource drives the stream URL via the adapter bridge).
|
||||
@@ -1617,9 +1620,9 @@
|
||||
startTimeUpdates();
|
||||
}
|
||||
|
||||
console.log("[VideoPlayer] Seek completed at:", currentTime.toFixed(2), "offset:", seekOffset);
|
||||
log.debug("Seek completed at:", currentTime.toFixed(2), "offset:", seekOffset);
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Seek failed:", err);
|
||||
log.error("Seek failed:", err);
|
||||
} finally {
|
||||
isSeeking = false;
|
||||
isDraggingSeekBar = false;
|
||||
@@ -1654,12 +1657,12 @@
|
||||
|
||||
function toggleBackgroundAudio() {
|
||||
backgroundAudioOn = !backgroundAudioOn;
|
||||
console.log("[VideoPlayer] Background-audio toggle ->", backgroundAudioOn);
|
||||
log.debug("Background-audio toggle ->", backgroundAudioOn);
|
||||
// Arm/disarm native background-audio mode AND flip auto-PiP the other way,
|
||||
// so exactly one background behavior is active.
|
||||
const armed = setBackgroundAudioEnabled(backgroundAudioOn);
|
||||
if (!armed) {
|
||||
console.warn("[VideoPlayer] Background audio NOT armed natively (no bridge)");
|
||||
log.warn("Background audio NOT armed natively (no bridge)");
|
||||
}
|
||||
setAutoEnterEnabled(!backgroundAudioOn);
|
||||
}
|
||||
@@ -1675,7 +1678,7 @@
|
||||
// if the element is mid-teardown — which shipped audio starting from 0:00.
|
||||
const pos = computeHandoffPosition(currentTime, 0);
|
||||
const wasPlaying = isPlaying;
|
||||
console.log("[VideoPlayer] Background-audio handoff at position:", pos.toFixed(1));
|
||||
log.debug("Background-audio handoff at position:", pos.toFixed(1));
|
||||
handoffState = { active: true, wasPlaying };
|
||||
try {
|
||||
if (!media) return;
|
||||
@@ -1716,7 +1719,7 @@
|
||||
videoElement.load();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Background-audio handoff failed:", err);
|
||||
log.error("Background-audio handoff failed:", err);
|
||||
handoffState = { ...initialHandoffState };
|
||||
}
|
||||
}
|
||||
@@ -1734,7 +1737,7 @@
|
||||
try {
|
||||
// Absolute position the native audio reached (base offset applied in Rust).
|
||||
const pos = await commands.playerExitBackgroundAudio();
|
||||
console.log("[VideoPlayer] Returning from background audio at:", pos.toFixed(1));
|
||||
log.debug("Returning from background audio at:", pos.toFixed(1));
|
||||
|
||||
isMediaReady = false;
|
||||
// The foreground seek below (pendingForegroundSeek/handleCanPlay) OWNS the
|
||||
@@ -1837,7 +1840,7 @@
|
||||
await Promise.resolve();
|
||||
currentStreamUrl = targetUrl;
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Background-audio return failed:", err);
|
||||
log.error("Background-audio return failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1856,7 +1859,7 @@
|
||||
// WebKitGTK rejects when the gesture isn't recognised as user-activated;
|
||||
// the immersive call below is what matters on Android, so don't let a
|
||||
// rejection here abort it.
|
||||
console.warn("[VideoPlayer] requestFullscreen rejected:", err);
|
||||
log.warn("requestFullscreen rejected:", err);
|
||||
});
|
||||
enterImmersive();
|
||||
isFullscreen = true;
|
||||
@@ -1906,7 +1909,7 @@
|
||||
});
|
||||
pendingSeekTarget = newTime;
|
||||
|
||||
console.log("[VideoPlayer] Relative seek:", {
|
||||
log.debug("Relative seek:", {
|
||||
offset: `${seconds > 0 ? "+" : ""}${seconds}s`,
|
||||
from: currentTime.toFixed(2),
|
||||
to: newTime.toFixed(2),
|
||||
@@ -2092,7 +2095,7 @@
|
||||
}
|
||||
|
||||
async function selectAudioTrack(streamIndex: number, arrayIndex: number) {
|
||||
console.log("[VideoPlayer] Selecting audio track - streamIndex:", streamIndex, "arrayIndex:", arrayIndex);
|
||||
log.debug("Selecting audio track - streamIndex:", streamIndex, "arrayIndex:", arrayIndex);
|
||||
const previousTrackIndex = selectedAudioTrackIndex;
|
||||
selectedAudioTrackIndex = streamIndex;
|
||||
showAudioTrackMenu = false;
|
||||
@@ -2113,7 +2116,7 @@
|
||||
startTimeUpdates();
|
||||
}
|
||||
|
||||
console.log("[VideoPlayer] Successfully changed audio track");
|
||||
log.debug("Successfully changed audio track");
|
||||
|
||||
// Save series audio preference for future episodes
|
||||
if (media && media.seriesId) {
|
||||
@@ -2132,14 +2135,14 @@
|
||||
selectedTrack.language || null,
|
||||
streamIndex
|
||||
);
|
||||
console.log("[VideoPlayer] Saved series audio preference:", selectedTrack.displayTitle || selectedTrack.language);
|
||||
log.debug("Saved series audio preference:", selectedTrack.displayTitle || selectedTrack.language);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[VideoPlayer] Failed to save series audio preference:", err);
|
||||
log.warn("Failed to save series audio preference:", err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to change audio track:", err);
|
||||
log.error("Failed to change audio track:", err);
|
||||
// Revert to previous track on error
|
||||
selectedAudioTrackIndex = previousTrackIndex;
|
||||
}
|
||||
@@ -2177,9 +2180,9 @@
|
||||
if (videoElement && !videoElement.paused) {
|
||||
startTimeUpdates();
|
||||
}
|
||||
console.log("[VideoPlayer] Streaming quality changed:", quality);
|
||||
log.debug("Streaming quality changed:", quality);
|
||||
} catch (err) {
|
||||
console.error("[VideoPlayer] Failed to change streaming quality:", err);
|
||||
log.error("Failed to change streaming quality:", err);
|
||||
selectedQuality = previous;
|
||||
} finally {
|
||||
changingQuality = false;
|
||||
@@ -2210,7 +2213,7 @@
|
||||
const trackStreamIndex = parseInt(track.getAttribute("data-stream-index") || "-1");
|
||||
if (trackStreamIndex === streamIndex && track.track) {
|
||||
track.track.mode = "showing";
|
||||
console.log("[VideoPlayer] Enabled subtitle track:", streamIndex);
|
||||
log.debug("Enabled subtitle track:", streamIndex);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -2230,7 +2233,7 @@
|
||||
* TRACES: UR-020 | DR-023, IR-016 | UT-147
|
||||
*/
|
||||
async function selectSubtitle(streamIndex: number | null) {
|
||||
console.log("[VideoPlayer] Selecting subtitle - streamIndex:", streamIndex);
|
||||
log.debug("Selecting subtitle - streamIndex:", streamIndex);
|
||||
selectedSubtitleIndex = streamIndex;
|
||||
showSubtitleMenu = false;
|
||||
|
||||
@@ -2242,9 +2245,9 @@
|
||||
try {
|
||||
const indexToUse = nativeSubtitleArrayIndex(sentSubtitleTracks, streamIndex);
|
||||
await commands.playerSetSubtitleTrack(indexToUse);
|
||||
console.log("[VideoPlayer] Native backend subtitle track changed - streamIndex:", streamIndex, "position:", indexToUse);
|
||||
log.debug("Native backend subtitle track changed - streamIndex:", streamIndex, "position:", indexToUse);
|
||||
} catch (error) {
|
||||
console.error("[VideoPlayer] Failed to set subtitle track:", error);
|
||||
log.error("Failed to set subtitle track:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
import { toast } from "$lib/stores/toast";
|
||||
import CreatePlaylistModal from "./CreatePlaylistModal.svelte";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("AddToPlaylist");
|
||||
|
||||
interface Props {
|
||||
isOpen?: boolean;
|
||||
@@ -39,7 +42,7 @@
|
||||
playlists = result.items;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[AddToPlaylist] Failed to load playlists:", e);
|
||||
log.error("Failed to load playlists:", e);
|
||||
toast.error("Failed to load playlists");
|
||||
} finally {
|
||||
loading = false;
|
||||
@@ -54,7 +57,7 @@
|
||||
toast.success(`Added to "${playlist.name}"`);
|
||||
onClose?.();
|
||||
} catch (e) {
|
||||
console.error("[AddToPlaylist] Failed to add:", e);
|
||||
log.error("Failed to add:", e);
|
||||
toast.error("Failed to add to playlist");
|
||||
} finally {
|
||||
adding = null;
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import { goto } from "$app/navigation";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { toast } from "$lib/stores/toast";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("CreatePlaylist");
|
||||
|
||||
interface Props {
|
||||
isOpen?: boolean;
|
||||
@@ -27,7 +30,7 @@
|
||||
onClose?.();
|
||||
goto(`/library/${result.id}`);
|
||||
} catch (e) {
|
||||
console.error("[CreatePlaylist] Failed:", e);
|
||||
log.error("Failed:", e);
|
||||
toast.error("Failed to create playlist");
|
||||
} finally {
|
||||
creating = false;
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
import { playbackPosition } from "$lib/stores/player";
|
||||
import { lmsSync, isLmsSession, macForSession } from "$lib/stores/lmsSync";
|
||||
import type { Session } from "$lib/api/types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("SessionPicker");
|
||||
|
||||
interface Props {
|
||||
isOpen?: boolean;
|
||||
@@ -41,7 +44,7 @@
|
||||
onClose();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to select session:", error);
|
||||
log.error("Failed to select session:", error);
|
||||
// Error is already stored in playbackMode store
|
||||
}
|
||||
}
|
||||
@@ -67,7 +70,7 @@
|
||||
await lmsSync.fuseZone(masterMac, zoneMac);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle LMS zone:", error);
|
||||
log.error("Failed to toggle LMS zone:", error);
|
||||
// Error is surfaced via the lmsSync store
|
||||
}
|
||||
}
|
||||
@@ -79,7 +82,7 @@
|
||||
onClose();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to transfer to local:", error);
|
||||
log.error("Failed to transfer to local:", error);
|
||||
// Error is already stored in playbackMode store
|
||||
}
|
||||
}
|
||||
@@ -91,7 +94,7 @@
|
||||
onClose();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to disconnect:", error);
|
||||
log.error("Failed to disconnect:", error);
|
||||
// Error is already stored in playbackMode store
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
*/
|
||||
|
||||
import type { AdapterHost, PlayerAdapter, PlayerLoadOptions } from "./types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Html5PlayerAdapter");
|
||||
|
||||
/**
|
||||
* Narrow seam the owning component provides so the adapter can execute the
|
||||
@@ -110,7 +113,7 @@ export class Html5PlayerAdapter implements PlayerAdapter {
|
||||
// play promise while the element keeps trying. Surfacing it would report
|
||||
// an error roughly once a second for the duration of the stall.
|
||||
if (isPlayInterruptedError(err)) {
|
||||
console.debug("[Html5PlayerAdapter] play() interrupted by pause (stall recovery)");
|
||||
log.debug("play() interrupted by pause (stall recovery)");
|
||||
} else {
|
||||
this.host.onError(`play() failed: ${err}`);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import type { AdapterHost } from "./types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("rustReportHost");
|
||||
|
||||
const POSITION_REPORT_INTERVAL_MS = 250;
|
||||
|
||||
@@ -37,7 +40,7 @@ export async function reportState(
|
||||
try {
|
||||
await commands.playerReportState(state, mediaId);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report state:", err);
|
||||
log.warn("Failed to report state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +57,7 @@ export async function reportPosition(
|
||||
try {
|
||||
await commands.playerReportPosition(position, Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report position:", err);
|
||||
log.warn("Failed to report position:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +65,7 @@ export async function reportMediaLoaded(duration: number): Promise<void> {
|
||||
try {
|
||||
await commands.playerReportMediaLoaded(Number.isFinite(duration) ? duration : 0);
|
||||
} catch (err) {
|
||||
console.warn("[rustReportHost] Failed to report media loaded:", err);
|
||||
log.warn("Failed to report media loaded:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +88,7 @@ export function createRustReportHost(
|
||||
onPosition: (position, duration) => void reportPosition(position, duration),
|
||||
onMediaLoaded: (duration) => void reportMediaLoaded(duration),
|
||||
onEnded: view.onEnded ?? (() => {}),
|
||||
onError: view.onError ?? ((message) => console.warn("[rustReportHost] adapter error:", message)),
|
||||
onError: view.onError ?? ((message) => log.warn("adapter error:", message)),
|
||||
onStreamUrlChanged: view.onStreamUrlChanged ?? (() => {}),
|
||||
onBuffering: view.onBuffering ?? (() => {}),
|
||||
onReady: view.onReady ?? (() => {}),
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("deviceId");
|
||||
|
||||
let cachedDeviceId: string | null = null;
|
||||
|
||||
@@ -34,7 +37,7 @@ export async function getDeviceId(): Promise<string> {
|
||||
cachedDeviceId = deviceId;
|
||||
return deviceId;
|
||||
} catch (e) {
|
||||
console.error("[deviceId] Failed to get device ID from backend:", e);
|
||||
log.error("Failed to get device ID from backend:", e);
|
||||
throw new Error("Failed to initialize device ID: " + String(e));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ import { commands } from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isConnected } from "$lib/stores/connectivity";
|
||||
import { setFavorite } from "$lib/stores/favorites";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Favorites");
|
||||
|
||||
/**
|
||||
* Toggle the favorite status of an item.
|
||||
@@ -59,7 +62,7 @@ export async function toggleFavorite(
|
||||
// 3. Mark as synced
|
||||
await commands.storageMarkSynced(userId, itemId);
|
||||
} catch (error) {
|
||||
console.error("Failed to sync favorite to server:", error);
|
||||
log.error("Failed to sync favorite to server:", error);
|
||||
// Favorite is stored locally and will be synced later
|
||||
// via sync queue (when implemented)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("ImageCache");
|
||||
|
||||
/**
|
||||
* Statistics about the thumbnail cache
|
||||
@@ -48,7 +51,7 @@ export async function getCachedImageUrl(
|
||||
return convertFileSrc(cachedPath);
|
||||
}
|
||||
} catch (e) {
|
||||
console.debug("Failed to check thumbnail cache:", e);
|
||||
log.debug("Failed to check thumbnail cache:", e);
|
||||
}
|
||||
|
||||
// Build server URL
|
||||
@@ -63,7 +66,7 @@ export async function getCachedImageUrl(
|
||||
// Trigger background caching (fire and forget)
|
||||
commands.thumbnailSave(itemId, imageType, tag, serverImageUrl).catch((e) => {
|
||||
// Silently fail - caching is best-effort
|
||||
console.debug("Background thumbnail cache failed:", e);
|
||||
log.debug("Background thumbnail cache failed:", e);
|
||||
});
|
||||
|
||||
// Return server URL for immediate display
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
|
||||
import { commands } from '$lib/api/bindings';
|
||||
import type { NetworkType } from '$lib/api/bindings';
|
||||
import { createLogger } from '$lib/utils/logger';
|
||||
|
||||
const log = createLogger('NetworkType');
|
||||
|
||||
/** The Android bridge, present only in the Android WebView. */
|
||||
interface AndroidNetworkTypeBridge {
|
||||
@@ -62,7 +65,7 @@ export async function reportNetworkState(): Promise<void> {
|
||||
} catch (error) {
|
||||
// Never let network reporting break the UI — the gate fails closed on
|
||||
// the Rust side, so a missed report at worst delays a queued download.
|
||||
console.warn('[NetworkType] Failed to report network state:', error);
|
||||
log.warn('Failed to report network state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +106,7 @@ export async function areDownloadsAllowed(): Promise<boolean> {
|
||||
try {
|
||||
return await commands.getDownloadsAllowed();
|
||||
} catch (error) {
|
||||
console.warn('[NetworkType] Failed to query download gate:', error);
|
||||
log.warn('Failed to query download gate:', error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@ import { goto } from "$app/navigation";
|
||||
import { cancelAutoplayCountdown } from "$lib/api/autoplay";
|
||||
import { nextEpisode } from "$lib/stores/nextEpisode";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("NextEpisode");
|
||||
|
||||
/** Guard against double-navigation */
|
||||
let isNavigating = false;
|
||||
@@ -46,11 +49,11 @@ export async function cancelAutoPlay() {
|
||||
*/
|
||||
function navigateToEpisode(episode: MediaItem) {
|
||||
if (isNavigating) {
|
||||
console.warn("[NextEpisode] Already navigating, skipping duplicate navigation to", episode.id);
|
||||
log.warn("Already navigating, skipping duplicate navigation to", episode.id);
|
||||
return;
|
||||
}
|
||||
isNavigating = true;
|
||||
console.log("[NextEpisode] Navigating to next episode:", episode.id, episode.name);
|
||||
log.debug("Navigating to next episode:", episode.id, episode.name);
|
||||
nextEpisode.hidePopup();
|
||||
goto(`/player/${episode.id}?restart=true`, { replaceState: true }).finally(() => {
|
||||
isNavigating = false;
|
||||
|
||||
@@ -17,6 +17,9 @@ import { writable, type Writable } from "svelte/store";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isConnected } from "$lib/stores/connectivity";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("OfflineCatalog");
|
||||
|
||||
/**
|
||||
* When true (and offline), library grids reveal greyed-out versions of media
|
||||
@@ -58,7 +61,7 @@ async function pushCatalogVisibility(connected: boolean, showCatalog: boolean):
|
||||
try {
|
||||
await commands.setShowServerCatalog(include);
|
||||
} catch (err) {
|
||||
console.warn("[OfflineCatalog] Failed to set catalog visibility:", err);
|
||||
log.warn("Failed to set catalog visibility:", err);
|
||||
// The backend is still on the old gate, so forget that we sent this —
|
||||
// otherwise the next identical transition is skipped as a no-op and the
|
||||
// frontend and backend disagree about the filter for the rest of the
|
||||
@@ -115,12 +118,12 @@ export async function syncCatalog(): Promise<void> {
|
||||
syncInProgress = true;
|
||||
try {
|
||||
const result = await commands.syncFullCatalog(handle);
|
||||
console.info(
|
||||
`[OfflineCatalog] Synced ${result.itemsCached} items (${result.librariesFailed} libraries failed)`
|
||||
log.info(
|
||||
`Synced ${result.itemsCached} items (${result.librariesFailed} libraries failed)`
|
||||
);
|
||||
await refreshSyncStatus();
|
||||
} catch (err) {
|
||||
console.warn("[OfflineCatalog] Full catalog sync failed:", err);
|
||||
log.warn("Full catalog sync failed:", err);
|
||||
} finally {
|
||||
syncInProgress = false;
|
||||
}
|
||||
@@ -136,12 +139,12 @@ export async function resumeQueued(): Promise<void> {
|
||||
try {
|
||||
const result = await commands.resumeQueuedDownloads(handle);
|
||||
if (result.resolved > 0 || result.failed > 0) {
|
||||
console.info(
|
||||
`[OfflineCatalog] Resumed queued downloads: ${result.resolved} resolved, ${result.failed} failed`
|
||||
log.info(
|
||||
`Resumed queued downloads: ${result.resolved} resolved, ${result.failed} failed`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("[OfflineCatalog] Failed to resume queued downloads:", err);
|
||||
log.warn("Failed to resume queued downloads:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +154,7 @@ export async function refreshSyncStatus(): Promise<void> {
|
||||
const status = await commands.catalogSyncStatus();
|
||||
lastCatalogSync.set(status.lastSyncedAt ?? null);
|
||||
} catch (err) {
|
||||
console.debug("[OfflineCatalog] Failed to fetch sync status:", err);
|
||||
log.debug("Failed to fetch sync status:", err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
*/
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("capabilities");
|
||||
|
||||
export interface PlaybackCapabilities {
|
||||
/** Audio renders through a webview `<audio>` element, not a native backend. */
|
||||
@@ -52,7 +55,7 @@ export async function getPlaybackCapabilities(): Promise<PlaybackCapabilities> {
|
||||
};
|
||||
return cached;
|
||||
} catch (err) {
|
||||
console.warn("[capabilities] player_get_capabilities failed:", err);
|
||||
log.warn("player_get_capabilities failed:", err);
|
||||
// Do NOT cache the fallback — a later call should get the real answer.
|
||||
return FALLBACK;
|
||||
} finally {
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("PlaybackReporting");
|
||||
|
||||
/**
|
||||
* Record the start of playback **locally**, with the context it started from.
|
||||
@@ -32,8 +35,8 @@ export async function reportPlaybackStart(
|
||||
const positionMs = Math.floor(positionSeconds * 1000);
|
||||
const userId = auth.getUserId();
|
||||
|
||||
console.log(
|
||||
"[PlaybackReporting] reportPlaybackStart - itemId:",
|
||||
log.debug(
|
||||
"reportPlaybackStart - itemId:",
|
||||
itemId,
|
||||
"positionSeconds:",
|
||||
positionSeconds,
|
||||
@@ -47,7 +50,7 @@ export async function reportPlaybackStart(
|
||||
try {
|
||||
await commands.storageUpdatePlaybackContext(userId, itemId, positionMs, contextType, contextId);
|
||||
} catch (e) {
|
||||
console.error("[PlaybackReporting] Failed to update playback context:", e);
|
||||
log.error("Failed to update playback context:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,7 +79,7 @@ export async function reportPlaybackProgress(
|
||||
|
||||
// Reduce logging for frequent progress updates
|
||||
if (Math.floor(positionSeconds) % 30 === 0) {
|
||||
console.log("[PlaybackReporting] reportPlaybackProgress - itemId:", itemId, "position:", positionSeconds);
|
||||
log.debug("reportPlaybackProgress - itemId:", itemId, "position:", positionSeconds);
|
||||
}
|
||||
|
||||
// Update local DB only (progress updates are frequent, don't report to server)
|
||||
@@ -84,7 +87,7 @@ export async function reportPlaybackProgress(
|
||||
try {
|
||||
await commands.storageUpdatePlaybackProgress(userId, itemId, positionMs);
|
||||
} catch (e) {
|
||||
console.error("[PlaybackReporting] Failed to update local progress:", e);
|
||||
log.error("Failed to update local progress:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,14 +104,14 @@ export async function reportPlaybackStopped(itemId: string, positionSeconds: num
|
||||
const positionMs = Math.floor(positionSeconds * 1000);
|
||||
const userId = auth.getUserId();
|
||||
|
||||
console.log("[PlaybackReporting] reportPlaybackStopped - itemId:", itemId, "positionSeconds:", positionSeconds);
|
||||
log.debug("reportPlaybackStopped - itemId:", itemId, "positionSeconds:", positionSeconds);
|
||||
|
||||
// Update local DB first (always works, even offline)
|
||||
if (userId) {
|
||||
try {
|
||||
await commands.storageUpdatePlaybackProgress(userId, itemId, positionMs);
|
||||
} catch (e) {
|
||||
console.error("[PlaybackReporting] Failed to update local progress:", e);
|
||||
log.error("Failed to update local progress:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +123,7 @@ export async function reportPlaybackStopped(itemId: string, positionSeconds: num
|
||||
const repo = auth.getRepository();
|
||||
await repo.reportPlaybackStopped(itemId, positionMs);
|
||||
} catch (e) {
|
||||
console.warn("[PlaybackReporting] Stop-report did not reach the server; queued for sync:", e);
|
||||
log.warn("Stop-report did not reach the server; queued for sync:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,14 +136,14 @@ export async function reportPlaybackStopped(itemId: string, positionSeconds: num
|
||||
export async function markAsPlayed(itemId: string): Promise<void> {
|
||||
const userId = auth.getUserId();
|
||||
|
||||
console.log("[PlaybackReporting] markAsPlayed - itemId:", itemId);
|
||||
log.debug("markAsPlayed - itemId:", itemId);
|
||||
|
||||
// Update local DB first
|
||||
if (userId) {
|
||||
try {
|
||||
await commands.storageMarkPlayed(userId, itemId);
|
||||
} catch (e) {
|
||||
console.error("[PlaybackReporting] Failed to mark as played in local DB:", e);
|
||||
log.error("Failed to mark as played in local DB:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,6 +156,6 @@ export async function markAsPlayed(itemId: string): Promise<void> {
|
||||
await repo.reportPlaybackStopped(itemId, item.durationMs);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[PlaybackReporting] Failed to report as played:", e);
|
||||
log.error("Failed to report as played:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ import { preloadUpcomingTracks } from "$lib/services/preload";
|
||||
import { playerController } from "$lib/player";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { get } from "svelte/store";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("playerEvents");
|
||||
|
||||
// PlayerStatusEvent and SleepTimerMode are generated by tauri-specta and
|
||||
// imported from $lib/api/bindings — they are the authoritative shapes emitted
|
||||
@@ -34,7 +37,7 @@ let isInitialized = false;
|
||||
*/
|
||||
export async function initPlayerEvents(): Promise<void> {
|
||||
if (isInitialized) {
|
||||
console.warn("Player events already initialized");
|
||||
log.warn("Player events already initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -43,9 +46,9 @@ export async function initPlayerEvents(): Promise<void> {
|
||||
handlePlayerEvent(event.payload);
|
||||
});
|
||||
isInitialized = true;
|
||||
console.log("Player event listener initialized");
|
||||
log.debug("Player event listener initialized");
|
||||
} catch (e) {
|
||||
console.error("Failed to initialize player events:", e);
|
||||
log.error("Failed to initialize player events:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,7 +101,7 @@ function handlePlayerEvent(event: PlayerStatusEvent): void {
|
||||
|
||||
case "buffering":
|
||||
// Could show buffering indicator in UI
|
||||
console.debug(`Buffering: ${event.percent}%`);
|
||||
log.debug(`Buffering: ${event.percent}%`);
|
||||
break;
|
||||
|
||||
case "error":
|
||||
@@ -196,7 +199,7 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
|
||||
// When local playback starts, ensure mode is set to local
|
||||
const mode = get(playbackMode);
|
||||
if (mode.mode !== "local") {
|
||||
console.log("Setting playback mode to local");
|
||||
log.debug("Setting playback mode to local");
|
||||
playbackMode.setMode("local");
|
||||
}
|
||||
|
||||
@@ -215,7 +218,7 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
|
||||
// Trigger preloading of upcoming tracks in the background
|
||||
preloadUpcomingTracks().catch((e) => {
|
||||
// Preload failures are non-critical, already logged in the service
|
||||
console.debug("[playerEvents] Preload failed (non-critical):", e);
|
||||
log.debug("Preload failed (non-critical):", e);
|
||||
});
|
||||
} else if (state === "paused" && currentItem) {
|
||||
// Keep current position and duration from store. The same track is
|
||||
@@ -240,7 +243,7 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
|
||||
// When local playback stops, revert to idle mode
|
||||
const currentMode = get(playbackMode);
|
||||
if (currentMode.mode === "local") {
|
||||
console.log("Setting playback mode to idle");
|
||||
log.debug("Setting playback mode to idle");
|
||||
playbackMode.setMode("idle");
|
||||
}
|
||||
|
||||
@@ -254,7 +257,7 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
|
||||
function handleMediaLoaded(duration: number): void {
|
||||
// Media is now loaded and ready
|
||||
// The state_changed event will handle setting the playing state
|
||||
console.debug(`Media loaded, duration: ${duration}s`);
|
||||
log.debug(`Media loaded, duration: ${duration}s`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -268,7 +271,7 @@ async function handlePlaybackEnded(): Promise<void> {
|
||||
try {
|
||||
await commands.playerOnPlaybackEnded(null, null);
|
||||
} catch (e) {
|
||||
console.error("[playerEvents] Failed to handle playback ended:", e);
|
||||
log.error("Failed to handle playback ended:", e);
|
||||
// Fallback: set idle state on error
|
||||
player.setIdle();
|
||||
}
|
||||
@@ -287,18 +290,18 @@ async function handlePlaybackEnded(): Promise<void> {
|
||||
* TRACES: UR-004, UR-040 | DR-130
|
||||
*/
|
||||
async function handleError(message: string, recoverable: boolean): Promise<void> {
|
||||
console.error(`Playback error (recoverable: ${recoverable}): ${message}`);
|
||||
log.error(`Playback error (recoverable: ${recoverable}): ${message}`);
|
||||
|
||||
if (recoverable) {
|
||||
try {
|
||||
if (await commands.playerRecoverStream()) {
|
||||
console.log("Stream re-opened after a recoverable error - not stopping");
|
||||
log.debug("Stream re-opened after a recoverable error - not stopping");
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// Fall through to the normal stop: a failed recovery attempt is still an
|
||||
// error, and leaving the player running would strand it mid-failure.
|
||||
console.error("Stream recovery attempt failed:", e);
|
||||
log.error("Stream recovery attempt failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,9 +311,9 @@ async function handleError(message: string, recoverable: boolean): Promise<void>
|
||||
// This also reports playback stopped to Jellyfin server
|
||||
try {
|
||||
await commands.playerStop();
|
||||
console.log("Backend player stopped after error");
|
||||
log.debug("Backend player stopped after error");
|
||||
} catch (e) {
|
||||
console.error("Failed to stop player after error:", e);
|
||||
log.error("Failed to stop player after error:", e);
|
||||
// Continue with state cleanup even if stop fails
|
||||
}
|
||||
|
||||
@@ -359,7 +362,7 @@ function handleControlCommand(action: string, position: number | null): void {
|
||||
void adapter.pause();
|
||||
break;
|
||||
default:
|
||||
console.warn("[playerEvents] Unknown control command:", action);
|
||||
log.warn("Unknown control command:", action);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
import { commands } from '$lib/api/bindings';
|
||||
import type { CacheConfig } from '$lib/api/bindings';
|
||||
import { auth } from '$lib/stores/auth';
|
||||
import { createLogger } from '$lib/utils/logger';
|
||||
|
||||
const log = createLogger('Preload');
|
||||
|
||||
interface PreloadOptions {
|
||||
/** Enable debug logging */
|
||||
@@ -28,17 +31,17 @@ export async function preloadUpcomingTracks(options: PreloadOptions = {}): Promi
|
||||
const userId = overrideUserId || auth.getUserId();
|
||||
|
||||
if (!userId) {
|
||||
if (debug) console.log('[Preload] No active user session, skipping preload');
|
||||
if (debug) log.debug('No active user session, skipping preload');
|
||||
return;
|
||||
}
|
||||
|
||||
if (debug) console.log('[Preload] Triggering preload for user:', userId);
|
||||
if (debug) log.debug('Triggering preload for user:', userId);
|
||||
|
||||
// downloadBasePath is currently unused in the backend
|
||||
const result = await commands.playerPreloadUpcoming(userId, '/downloads');
|
||||
|
||||
if (debug) {
|
||||
console.log('[Preload] Result:', {
|
||||
log.debug('Result:', {
|
||||
queued: result.queuedCount,
|
||||
alreadyDownloaded: result.alreadyDownloaded,
|
||||
skipped: result.skipped
|
||||
@@ -47,12 +50,12 @@ export async function preloadUpcomingTracks(options: PreloadOptions = {}): Promi
|
||||
|
||||
// Log meaningful results
|
||||
if (result.queuedCount > 0) {
|
||||
console.log(`[Preload] Queued ${result.queuedCount} track(s) for background download`);
|
||||
log.debug(`Queued ${result.queuedCount} track(s) for background download`);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fail silently - preloading is a background optimization
|
||||
// Don't interrupt the user's playback experience
|
||||
console.warn('[Preload] Failed to preload upcoming tracks:', error);
|
||||
log.warn('Failed to preload upcoming tracks:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ import { auth } from "$lib/stores/auth";
|
||||
// hand-written mirror — the mirror had already drifted (it predates `itemName`),
|
||||
// and a drifted duplicate is how a field silently stops reaching the UI.
|
||||
import type { SyncQueueItem } from "$lib/api/bindings";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("SyncService");
|
||||
export type { SyncQueueItem };
|
||||
|
||||
export type SyncOperation =
|
||||
@@ -42,14 +45,14 @@ class SyncService {
|
||||
* Start the sync service (lifecycle managed by Rust backend)
|
||||
*/
|
||||
start(): void {
|
||||
console.log("[SyncService] Started");
|
||||
log.debug("Started");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the sync service (lifecycle managed by Rust backend)
|
||||
*/
|
||||
stop(): void {
|
||||
console.log("[SyncService] Stopped");
|
||||
log.debug("Stopped");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,7 +77,7 @@ class SyncService {
|
||||
payload ? JSON.stringify(payload) : null
|
||||
);
|
||||
|
||||
console.log(`[SyncService] Queued ${operation} for item ${itemId}, id: ${id}`);
|
||||
log.debug(`Queued ${operation} for item ${itemId}, id: ${id}`);
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -155,7 +158,7 @@ class SyncService {
|
||||
*/
|
||||
async cleanup(daysOld: number = 7): Promise<number> {
|
||||
const deleted = await commands.syncCleanupCompleted(daysOld);
|
||||
console.log(`[SyncService] Cleaned up ${deleted} old completed operations`);
|
||||
log.debug(`Cleaned up ${deleted} old completed operations`);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@@ -194,7 +197,7 @@ class SyncService {
|
||||
const userId = auth.getUserId();
|
||||
if (userId) {
|
||||
await commands.syncClearUser(userId);
|
||||
console.log("[SyncService] Cleared sync queue for user");
|
||||
log.debug("Cleared sync queue for user");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+42
-39
@@ -13,6 +13,9 @@ import type { User, AuthResult } from "$lib/api/types";
|
||||
import type { Session, AuthServerInfo as ServerInfo } from "$lib/api/bindings";
|
||||
import { connectivity } from "./connectivity";
|
||||
import { getDeviceId, clearCache as clearDeviceIdCache } from "$lib/services/deviceId";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Auth");
|
||||
|
||||
interface AuthState {
|
||||
isAuthenticated: boolean;
|
||||
@@ -70,7 +73,7 @@ function createAuthStore() {
|
||||
|
||||
try {
|
||||
unlistenSessionVerified = await listen<{ user: User }>("auth:session-verified", (event) => {
|
||||
console.log("[Auth] Session verified:", event.payload.user.name);
|
||||
log.debug("Session verified:", event.payload.user.name);
|
||||
update((s) => ({
|
||||
...s,
|
||||
sessionVerified: true,
|
||||
@@ -80,12 +83,12 @@ function createAuthStore() {
|
||||
}));
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[Auth] Failed to listen to session-verified event:", e);
|
||||
log.error("Failed to listen to session-verified event:", e);
|
||||
}
|
||||
|
||||
try {
|
||||
unlistenNeedsReauth = await listen<{ reason: string }>("auth:needs-reauth", (event) => {
|
||||
console.log("[Auth] Session needs re-authentication:", event.payload.reason);
|
||||
log.debug("Session needs re-authentication:", event.payload.reason);
|
||||
update((s) => ({
|
||||
...s,
|
||||
sessionVerified: false,
|
||||
@@ -95,17 +98,17 @@ function createAuthStore() {
|
||||
}));
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[Auth] Failed to listen to needs-reauth event:", e);
|
||||
log.error("Failed to listen to needs-reauth event:", e);
|
||||
}
|
||||
|
||||
try {
|
||||
unlistenNetworkError = await listen<{ message: string }>("auth:network-error", (event) => {
|
||||
console.log("[Auth] Network error during verification:", event.payload.message);
|
||||
log.debug("Network error during verification:", event.payload.message);
|
||||
// Network errors don't trigger re-auth - just log them
|
||||
update((s) => ({ ...s, isVerifying: false }));
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("[Auth] Failed to listen to network-error event:", e);
|
||||
log.error("Failed to listen to network-error event:", e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +147,7 @@ function createAuthStore() {
|
||||
void (async () => {
|
||||
try {
|
||||
const securityStatus = await commands.storageGetSecurityStatus();
|
||||
console.log("[Auth] Security status:", securityStatus);
|
||||
log.debug("Security status:", securityStatus);
|
||||
if (!securityStatus.usingKeyring) {
|
||||
update((s) => ({
|
||||
...s,
|
||||
@@ -153,17 +156,17 @@ function createAuthStore() {
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[Auth] Failed to get security status:", error);
|
||||
log.warn("Failed to get security status:", error);
|
||||
}
|
||||
})();
|
||||
|
||||
// Initialize auth manager and get session
|
||||
console.log("[Auth] Initializing auth manager...");
|
||||
log.debug("Initializing auth manager...");
|
||||
const session = await commands.authInitialize();
|
||||
console.log("[Auth] Session retrieval result:", session ? "Session found" : "No session found");
|
||||
log.debug("Session retrieval result:", session ? "Session found" : "No session found");
|
||||
|
||||
if (session) {
|
||||
console.log("[Auth] Restoring session for user:", session.username, "on server:", session.serverUrl);
|
||||
log.debug("Restoring session for user:", session.username, "on server:", session.serverUrl);
|
||||
|
||||
// Create RepositoryClient for cache-first access. This IS required before
|
||||
// we mark authenticated — the first screen (library overview) reads
|
||||
@@ -184,9 +187,9 @@ function createAuthStore() {
|
||||
session.userId,
|
||||
deviceId
|
||||
);
|
||||
console.log("[Auth] Rust player configured for automatic playback reporting");
|
||||
log.debug("Rust player configured for automatic playback reporting");
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to configure Rust player:", error);
|
||||
log.error("Failed to configure Rust player:", error);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -205,7 +208,7 @@ function createAuthStore() {
|
||||
});
|
||||
|
||||
// Start connectivity monitoring early to avoid appearing offline on startup
|
||||
console.log("[Auth] Starting early connectivity monitoring...");
|
||||
log.debug("Starting early connectivity monitoring...");
|
||||
connectivity.startMonitoring(session.serverUrl, {
|
||||
onServerReconnected: () => {
|
||||
// Retry session verification when server becomes reachable
|
||||
@@ -214,10 +217,10 @@ function createAuthStore() {
|
||||
// Lazy import to avoid an auth <-> offlineCatalog import cycle.
|
||||
import("$lib/services/offlineCatalog")
|
||||
.then((m) => m.onReconnected())
|
||||
.catch((err) => console.warn("[Auth] Catalog reconnect failed:", err));
|
||||
.catch((err) => log.warn("Catalog reconnect failed:", err));
|
||||
},
|
||||
}).catch((error) => {
|
||||
console.error("[Auth] Failed to start connectivity monitoring:", error);
|
||||
log.error("Failed to start connectivity monitoring:", error);
|
||||
});
|
||||
|
||||
// Start background session verification — fire-and-forget. This is
|
||||
@@ -228,14 +231,14 @@ function createAuthStore() {
|
||||
try {
|
||||
const verifyDeviceId = await getDeviceId();
|
||||
await commands.authStartVerification(verifyDeviceId);
|
||||
console.log("[Auth] Background verification started");
|
||||
log.debug("Background verification started");
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to start verification:", error);
|
||||
log.error("Failed to start verification:", error);
|
||||
}
|
||||
})();
|
||||
} else {
|
||||
// No stored session
|
||||
console.log("[Auth] No active session found");
|
||||
log.debug("No active session found");
|
||||
set({
|
||||
isAuthenticated: false,
|
||||
isLoading: false,
|
||||
@@ -250,7 +253,7 @@ function createAuthStore() {
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to initialize:", error);
|
||||
log.error("Failed to initialize:", error);
|
||||
update((s) => ({
|
||||
...s,
|
||||
isLoading: false,
|
||||
@@ -269,15 +272,15 @@ function createAuthStore() {
|
||||
update((s) => ({ ...s, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
console.log("[Auth] Connecting to server:", serverUrl);
|
||||
log.debug("Connecting to server:", serverUrl);
|
||||
const serverInfo = await commands.authConnectToServer(serverUrl);
|
||||
console.log("[Auth] Connected to server:", serverInfo.name, serverInfo.version);
|
||||
console.log("[Auth] Normalized URL:", serverInfo.normalizedUrl);
|
||||
log.debug("Connected to server:", serverInfo.name, serverInfo.version);
|
||||
log.debug("Normalized URL:", serverInfo.normalizedUrl);
|
||||
|
||||
update((s) => ({ ...s, isLoading: false }));
|
||||
return serverInfo;
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to connect to server:", error);
|
||||
log.error("Failed to connect to server:", error);
|
||||
update((s) => ({
|
||||
...s,
|
||||
isLoading: false,
|
||||
@@ -297,11 +300,11 @@ function createAuthStore() {
|
||||
|
||||
try {
|
||||
const deviceId = await getDeviceId();
|
||||
console.log("[Auth] Logging in as:", username);
|
||||
log.debug("Logging in as:", username);
|
||||
|
||||
const authResult = await commands.authLogin(serverUrl, username, password, deviceId);
|
||||
|
||||
console.log("[Auth] Login successful:", authResult.user);
|
||||
log.debug("Login successful:", authResult.user);
|
||||
|
||||
// Save to storage
|
||||
await commands.storageSaveServer(authResult.serverId, serverName, serverUrl, null);
|
||||
@@ -340,9 +343,9 @@ function createAuthStore() {
|
||||
authResult.user.id,
|
||||
playerDeviceId
|
||||
);
|
||||
console.log("[Auth] Rust player configured for playback reporting");
|
||||
log.debug("Rust player configured for playback reporting");
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to configure Rust player:", error);
|
||||
log.error("Failed to configure Rust player:", error);
|
||||
}
|
||||
|
||||
// Update state
|
||||
@@ -364,12 +367,12 @@ function createAuthStore() {
|
||||
const verifyDeviceId = await getDeviceId();
|
||||
await commands.authStartVerification(verifyDeviceId);
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to start verification:", error);
|
||||
log.error("Failed to start verification:", error);
|
||||
}
|
||||
|
||||
return authResult;
|
||||
} catch (error) {
|
||||
console.error("[Auth] Login failed:", error);
|
||||
log.error("Login failed:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
update((s) => ({ ...s, isLoading: false, error: errorMessage }));
|
||||
throw error;
|
||||
@@ -384,11 +387,11 @@ function createAuthStore() {
|
||||
|
||||
try {
|
||||
const deviceId = await getDeviceId();
|
||||
console.log("[Auth] Re-authenticating...");
|
||||
log.debug("Re-authenticating...");
|
||||
|
||||
const authResult = await commands.authReauthenticate(password, deviceId);
|
||||
|
||||
console.log("[Auth] Re-authentication successful");
|
||||
log.debug("Re-authentication successful");
|
||||
|
||||
// Update storage
|
||||
await commands.storageSaveUser(
|
||||
@@ -417,7 +420,7 @@ function createAuthStore() {
|
||||
playerDeviceId
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to reconfigure player:", error);
|
||||
log.error("Failed to reconfigure player:", error);
|
||||
}
|
||||
|
||||
// Update state
|
||||
@@ -432,7 +435,7 @@ function createAuthStore() {
|
||||
|
||||
return authResult;
|
||||
} catch (error) {
|
||||
console.error("[Auth] Re-authentication failed:", error);
|
||||
log.error("Re-authentication failed:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
update((s) => ({ ...s, isLoading: false, error: errorMessage }));
|
||||
throw error;
|
||||
@@ -456,7 +459,7 @@ function createAuthStore() {
|
||||
try {
|
||||
await commands.playerDisableJellyfin();
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to disable player reporting:", error);
|
||||
log.error("Failed to disable player reporting:", error);
|
||||
}
|
||||
|
||||
// Clear repository
|
||||
@@ -481,7 +484,7 @@ function createAuthStore() {
|
||||
// Clear device ID cache on logout
|
||||
clearDeviceIdCache();
|
||||
} catch (error) {
|
||||
console.error("[Auth] Logout error (continuing anyway):", error);
|
||||
log.error("Logout error (continuing anyway):", error);
|
||||
set(initialState);
|
||||
clearDeviceIdCache();
|
||||
}
|
||||
@@ -501,7 +504,7 @@ function createAuthStore() {
|
||||
try {
|
||||
return await commands.authGetSession();
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to get current session:", error);
|
||||
log.error("Failed to get current session:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -536,10 +539,10 @@ function createAuthStore() {
|
||||
async function retryVerification() {
|
||||
try {
|
||||
const deviceId = await getDeviceId();
|
||||
console.log("[Auth] Retrying session verification after reconnection");
|
||||
log.debug("Retrying session verification after reconnection");
|
||||
await commands.authStartVerification(deviceId);
|
||||
} catch (error) {
|
||||
console.error("[Auth] Failed to retry verification:", error);
|
||||
log.error("Failed to retry verification:", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ import { writable, derived } from "svelte/store";
|
||||
import { browser } from "$app/environment";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("ConnectivityStore");
|
||||
|
||||
export interface ConnectivityState {
|
||||
/** Browser's navigator.onLine status */
|
||||
@@ -76,7 +79,7 @@ function createConnectivityStore() {
|
||||
update((s) => ({ ...s, isOnline: true }));
|
||||
// Device regained network — ask the backend to re-verify the server now.
|
||||
checkServerReachable().catch((err) => {
|
||||
console.debug("[ConnectivityStore] Recheck after 'online' failed:", err);
|
||||
log.debug("Recheck after 'online' failed:", err);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -85,7 +88,7 @@ function createConnectivityStore() {
|
||||
// decide whether the server is actually reachable.
|
||||
update((s) => ({ ...s, isOnline: false }));
|
||||
checkServerReachable().catch((err) => {
|
||||
console.debug("[ConnectivityStore] Recheck after 'offline' failed:", err);
|
||||
log.debug("Recheck after 'offline' failed:", err);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -132,7 +135,7 @@ function createConnectivityStore() {
|
||||
|
||||
return isReachable;
|
||||
} catch (error) {
|
||||
console.error("[ConnectivityStore] Failed to check server:", error);
|
||||
log.error("Failed to check server:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -145,7 +148,7 @@ function createConnectivityStore() {
|
||||
isMonitoring = true;
|
||||
|
||||
try {
|
||||
console.log("[ConnectivityStore] Starting monitoring for:", url);
|
||||
log.debug("Starting monitoring for:", url);
|
||||
|
||||
// Set the server URL
|
||||
await commands.connectivitySetServerUrl(url);
|
||||
@@ -163,10 +166,10 @@ function createConnectivityStore() {
|
||||
isChecking: status.isChecking,
|
||||
}));
|
||||
|
||||
console.log("[ConnectivityStore] Started monitoring. Initial status:",
|
||||
log.debug("Started monitoring. Initial status:",
|
||||
status.isServerReachable ? "ONLINE" : "OFFLINE");
|
||||
} catch (error) {
|
||||
console.error("[ConnectivityStore] Failed to start monitoring:", error);
|
||||
log.error("Failed to start monitoring:", error);
|
||||
update((s) => ({
|
||||
...s,
|
||||
isServerReachable: false,
|
||||
@@ -185,9 +188,9 @@ function createConnectivityStore() {
|
||||
await commands.connectivityStopMonitoring();
|
||||
isMonitoring = false;
|
||||
eventHandlers = {};
|
||||
console.log("[ConnectivityStore] Stopped monitoring");
|
||||
log.debug("Stopped monitoring");
|
||||
} catch (error) {
|
||||
console.error("[ConnectivityStore] Failed to stop monitoring:", error);
|
||||
log.error("Failed to stop monitoring:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +201,7 @@ function createConnectivityStore() {
|
||||
try {
|
||||
await commands.connectivitySetServerUrl(url);
|
||||
} catch (error) {
|
||||
console.error("[ConnectivityStore] Failed to set server URL:", error);
|
||||
log.error("Failed to set server URL:", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+45
-42
@@ -3,6 +3,9 @@
|
||||
import { writable, derived, get } from 'svelte/store';
|
||||
import { commands } from '$lib/api/bindings';
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
|
||||
import { createLogger } from '$lib/utils/logger';
|
||||
|
||||
const log = createLogger('Downloads');
|
||||
|
||||
// Event listener state
|
||||
let unlistenFn: UnlistenFn | null = null;
|
||||
@@ -103,7 +106,7 @@ function createDownloadsStore() {
|
||||
async function refreshDownloads(userId: string, statusFilter?: string[]): Promise<void> {
|
||||
// If a refresh is already in progress, queue this request instead
|
||||
if (refreshInProgress) {
|
||||
console.debug('🔄 Refresh already in progress, queuing request for user:', userId);
|
||||
log.debug('🔄 Refresh already in progress, queuing request for user:', userId);
|
||||
pendingRefreshRequest = { userId, statusFilter };
|
||||
return;
|
||||
}
|
||||
@@ -111,13 +114,13 @@ function createDownloadsStore() {
|
||||
refreshInProgress = true;
|
||||
|
||||
try {
|
||||
console.log('🔄 Refreshing downloads for user:', userId);
|
||||
log.debug('🔄 Refreshing downloads for user:', userId);
|
||||
const response = (await commands.getDownloads(
|
||||
userId,
|
||||
statusFilter ?? null
|
||||
)) as unknown as { downloads: DownloadInfo[]; stats: DownloadStats };
|
||||
console.log(' Got', response.downloads.length, 'downloads from backend');
|
||||
console.log(' Stats:', response.stats);
|
||||
log.debug(' Got', response.downloads.length, 'downloads from backend');
|
||||
log.debug(' Stats:', response.stats);
|
||||
|
||||
update((state) => {
|
||||
const downloadsMap: Record<number, DownloadInfo> = {};
|
||||
@@ -133,7 +136,7 @@ function createDownloadsStore() {
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh downloads:', error);
|
||||
log.error('Failed to refresh downloads:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
refreshInProgress = false;
|
||||
@@ -164,7 +167,7 @@ function createDownloadsStore() {
|
||||
albumName?: string
|
||||
): Promise<number> {
|
||||
try {
|
||||
console.log('📥 downloadItem called:', { itemId, userId, filePath, itemName, artistName, albumName });
|
||||
log.debug('📥 downloadItem called:', { itemId, userId, filePath, itemName, artistName, albumName });
|
||||
const downloadId = await commands.downloadItem({
|
||||
itemId,
|
||||
userId,
|
||||
@@ -176,16 +179,16 @@ function createDownloadsStore() {
|
||||
albumName: albumName ?? null,
|
||||
expectedSize: null
|
||||
});
|
||||
console.log(' Got download ID from backend:', downloadId);
|
||||
log.debug(' Got download ID from backend:', downloadId);
|
||||
|
||||
// Fetch download info and add to store
|
||||
console.log(' Refreshing downloads...');
|
||||
log.debug(' Refreshing downloads...');
|
||||
await refreshDownloads(userId);
|
||||
console.log(' Refresh complete. Store state:', get({ subscribe }));
|
||||
log.debug(' Refresh complete. Store state:', get({ subscribe }));
|
||||
|
||||
return downloadId;
|
||||
} catch (error) {
|
||||
console.error('Failed to queue download:', error);
|
||||
log.error('Failed to queue download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -206,16 +209,16 @@ function createDownloadsStore() {
|
||||
basePath: string
|
||||
): Promise<number[]> {
|
||||
try {
|
||||
console.log('📥 downloadAlbum called:', { albumId, userId, basePath });
|
||||
log.debug('📥 downloadAlbum called:', { albumId, userId, basePath });
|
||||
const downloadIds = await commands.downloadAlbum(handle, albumId, userId, basePath);
|
||||
console.log(' Got download IDs from backend:', downloadIds);
|
||||
log.debug(' Got download IDs from backend:', downloadIds);
|
||||
|
||||
// Refresh downloads
|
||||
await refreshDownloads(userId);
|
||||
|
||||
return downloadIds;
|
||||
} catch (error) {
|
||||
console.error('Failed to queue album download:', error);
|
||||
log.error('Failed to queue album download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -237,7 +240,7 @@ function createDownloadsStore() {
|
||||
seasonNumber?: number
|
||||
): Promise<number> {
|
||||
try {
|
||||
console.log('🎬 downloadVideo called:', {
|
||||
log.debug('🎬 downloadVideo called:', {
|
||||
itemId,
|
||||
userId,
|
||||
filePath,
|
||||
@@ -258,14 +261,14 @@ function createDownloadsStore() {
|
||||
episodeNumber: episodeNumber ?? null,
|
||||
seasonNumber: seasonNumber ?? null
|
||||
});
|
||||
console.log(' Got download ID from backend:', downloadId);
|
||||
log.debug(' Got download ID from backend:', downloadId);
|
||||
|
||||
// Refresh downloads
|
||||
await refreshDownloads(userId);
|
||||
|
||||
return downloadId;
|
||||
} catch (error) {
|
||||
console.error('Failed to queue video download:', error);
|
||||
log.error('Failed to queue video download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -281,7 +284,7 @@ function createDownloadsStore() {
|
||||
qualityPreset?: string
|
||||
): Promise<number[]> {
|
||||
try {
|
||||
console.log('📺 downloadSeries called:', {
|
||||
log.debug('📺 downloadSeries called:', {
|
||||
seriesId,
|
||||
seriesName,
|
||||
userId,
|
||||
@@ -295,14 +298,14 @@ function createDownloadsStore() {
|
||||
basePath,
|
||||
qualityPreset ?? null
|
||||
);
|
||||
console.log(' Queued', downloadIds.length, 'episodes for download');
|
||||
log.debug(' Queued', downloadIds.length, 'episodes for download');
|
||||
|
||||
// Refresh downloads
|
||||
await refreshDownloads(userId);
|
||||
|
||||
return downloadIds;
|
||||
} catch (error) {
|
||||
console.error('Failed to queue series download:', error);
|
||||
log.error('Failed to queue series download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -320,7 +323,7 @@ function createDownloadsStore() {
|
||||
qualityPreset?: string
|
||||
): Promise<number[]> {
|
||||
try {
|
||||
console.log('📺 downloadSeason called:', {
|
||||
log.debug('📺 downloadSeason called:', {
|
||||
seasonId,
|
||||
seriesName,
|
||||
seasonName,
|
||||
@@ -336,14 +339,14 @@ function createDownloadsStore() {
|
||||
basePath,
|
||||
qualityPreset ?? null
|
||||
);
|
||||
console.log(' Queued', downloadIds.length, 'episodes for download');
|
||||
log.debug(' Queued', downloadIds.length, 'episodes for download');
|
||||
|
||||
// Refresh downloads
|
||||
await refreshDownloads(userId);
|
||||
|
||||
return downloadIds;
|
||||
} catch (error) {
|
||||
console.error('Failed to queue season download:', error);
|
||||
log.error('Failed to queue season download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -355,7 +358,7 @@ function createDownloadsStore() {
|
||||
try {
|
||||
await commands.pinItem(itemId);
|
||||
} catch (error) {
|
||||
console.error('Failed to pin item:', error);
|
||||
log.error('Failed to pin item:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -367,7 +370,7 @@ function createDownloadsStore() {
|
||||
try {
|
||||
await commands.unpinItem(itemId);
|
||||
} catch (error) {
|
||||
console.error('Failed to unpin item:', error);
|
||||
log.error('Failed to unpin item:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -379,7 +382,7 @@ function createDownloadsStore() {
|
||||
try {
|
||||
return await commands.isItemPinned(itemId);
|
||||
} catch (error) {
|
||||
console.error('Failed to check pin status:', error);
|
||||
log.error('Failed to check pin status:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
@@ -391,7 +394,7 @@ function createDownloadsStore() {
|
||||
try {
|
||||
await commands.pauseDownload(downloadId);
|
||||
} catch (error) {
|
||||
console.error('Failed to pause download:', error);
|
||||
log.error('Failed to pause download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -403,7 +406,7 @@ function createDownloadsStore() {
|
||||
try {
|
||||
await commands.resumeDownload(downloadId);
|
||||
} catch (error) {
|
||||
console.error('Failed to resume download:', error);
|
||||
log.error('Failed to resume download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -415,7 +418,7 @@ function createDownloadsStore() {
|
||||
try {
|
||||
await commands.cancelDownload(downloadId);
|
||||
} catch (error) {
|
||||
console.error('Failed to cancel download:', error);
|
||||
log.error('Failed to cancel download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -431,7 +434,7 @@ function createDownloadsStore() {
|
||||
return { ...state, downloads: remaining };
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to delete download:', error);
|
||||
log.error('Failed to delete download:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
@@ -448,14 +451,14 @@ function createDownloadsStore() {
|
||||
update((state) => {
|
||||
const download = state.downloads[downloadId];
|
||||
if (!download) {
|
||||
console.log(' Download not in store:', downloadId);
|
||||
log.debug(' Download not in store:', downloadId);
|
||||
return state;
|
||||
}
|
||||
|
||||
const updatedDownload = { ...download, ...updates };
|
||||
const newDownloads = { ...state.downloads, [downloadId]: updatedDownload };
|
||||
|
||||
console.log(' Store updated for download', downloadId, ':', updates);
|
||||
log.debug(' Store updated for download', downloadId, ':', updates);
|
||||
// No count calculation - stats remain as-is until next refresh
|
||||
return {
|
||||
downloads: newDownloads,
|
||||
@@ -515,30 +518,30 @@ export const audioDownloads = derived(downloads, ($d) =>
|
||||
*/
|
||||
export async function initDownloadEvents(): Promise<void> {
|
||||
if (isEventsInitialized) {
|
||||
console.warn('Download events already initialized');
|
||||
log.warn('Download events already initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('🎧 Setting up download event listener...');
|
||||
log.debug('🎧 Setting up download event listener...');
|
||||
unlistenFn = await listen<DownloadEvent>('download-event', (event) => {
|
||||
const payload = event.payload;
|
||||
console.log('📬 Received download event:', payload.type, 'for download:', payload.downloadId);
|
||||
console.log(' Full event payload:', JSON.stringify(payload));
|
||||
log.debug('📬 Received download event:', payload.type, 'for download:', payload.downloadId);
|
||||
log.debug(' Full event payload:', JSON.stringify(payload));
|
||||
|
||||
// Update the store based on event type
|
||||
downloads.subscribe((state) => {
|
||||
const download = state.downloads[payload.downloadId];
|
||||
console.log(' Current download state:', download ? download.status : 'NOT IN STORE');
|
||||
log.debug(' Current download state:', download ? download.status : 'NOT IN STORE');
|
||||
})(); // Immediately unsubscribe after reading
|
||||
|
||||
handleDownloadEvent(payload);
|
||||
});
|
||||
|
||||
isEventsInitialized = true;
|
||||
console.log('✅ Download event listener registered successfully');
|
||||
log.debug('✅ Download event listener registered successfully');
|
||||
} catch (err) {
|
||||
console.error('❌ Failed to register download event listener:', err);
|
||||
log.error('❌ Failed to register download event listener:', err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,7 +602,7 @@ function handleDownloadEvent(payload: DownloadEvent): void {
|
||||
payload.downloadId,
|
||||
payload.totalBytes || download.fileSize || download.bytesDownloaded,
|
||||
payload.filePath || download.filePath
|
||||
).catch((err) => console.error('Failed to persist download completion:', err));
|
||||
).catch((err) => log.error('Failed to persist download completion:', err));
|
||||
|
||||
updateDownloadInStore(payload.downloadId, {
|
||||
status: 'completed',
|
||||
@@ -616,7 +619,7 @@ function handleDownloadEvent(payload: DownloadEvent): void {
|
||||
commands.markDownloadFailed(
|
||||
payload.downloadId,
|
||||
payload.error || 'Unknown error'
|
||||
).catch((err) => console.error('Failed to persist download failure:', err));
|
||||
).catch((err) => log.error('Failed to persist download failure:', err));
|
||||
|
||||
updateDownloadInStore(payload.downloadId, {
|
||||
status: 'failed',
|
||||
@@ -654,7 +657,7 @@ function handleDownloadEvent(payload: DownloadEvent): void {
|
||||
* Helper to update a download in the store.
|
||||
*/
|
||||
function updateDownloadInStore(downloadId: number, updates: Partial<DownloadInfo>): void {
|
||||
console.log(' updateDownloadInStore:', downloadId, updates);
|
||||
log.debug(' updateDownloadInStore:', downloadId, updates);
|
||||
downloads.updateDownload(downloadId, updates);
|
||||
}
|
||||
|
||||
@@ -662,6 +665,6 @@ function updateDownloadInStore(downloadId: number, updates: Partial<DownloadInfo
|
||||
* Helper to remove a download from the store.
|
||||
*/
|
||||
function removeDownloadFromStore(downloadId: number): void {
|
||||
console.log(' removeDownloadFromStore:', downloadId);
|
||||
log.debug(' removeDownloadFromStore:', downloadId);
|
||||
downloads.removeDownload(downloadId);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
filterSupersededResumeItems,
|
||||
filterInProgressNextUpItems,
|
||||
} from "./continueWatchingFilter";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("HomeStore");
|
||||
|
||||
interface HomeState {
|
||||
heroItems: MediaItem[];
|
||||
@@ -103,7 +106,7 @@ function createHomeStore() {
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to load home sections";
|
||||
update(s => ({ ...s, isLoading: false, error: message }));
|
||||
console.error("Failed to load home sections:", error);
|
||||
log.error("Failed to load home sections:", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-10
@@ -7,6 +7,9 @@ import type { Library, MediaItem, SearchResult, Genre } from "$lib/api/types";
|
||||
import type { SearchOptions } from "$lib/api/bindings";
|
||||
import type { SearchScope } from "$lib/utils/searchScope";
|
||||
import { auth } from "./auth";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("LibraryStore");
|
||||
|
||||
/**
|
||||
* Payload of the backend `search-event` (mirrors Rust `SearchUpdateEvent`).
|
||||
@@ -84,16 +87,16 @@ function createLibraryStore() {
|
||||
const startTime = performance.now();
|
||||
const repo = auth.getRepository();
|
||||
|
||||
console.log("📚 [LibraryStore] Loading libraries...");
|
||||
log.debug("📚 Loading libraries...");
|
||||
|
||||
const libraries = await repo.getLibraries();
|
||||
|
||||
const loadTime = Math.round(performance.now() - startTime);
|
||||
|
||||
if (loadTime < 100) {
|
||||
console.log(`🚀 [LibraryStore] CACHE HIT! Loaded ${libraries.length} libraries in ${loadTime}ms (instant)`);
|
||||
log.debug(`🚀 CACHE HIT! Loaded ${libraries.length} libraries in ${loadTime}ms (instant)`);
|
||||
} else {
|
||||
console.log(`⏳ [LibraryStore] Loaded ${libraries.length} libraries in ${loadTime}ms (from server)`);
|
||||
log.debug(`⏳ Loaded ${libraries.length} libraries in ${loadTime}ms (from server)`);
|
||||
}
|
||||
|
||||
update((s) => ({
|
||||
@@ -120,7 +123,7 @@ function createLibraryStore() {
|
||||
const startTime = performance.now();
|
||||
const repo = auth.getRepository();
|
||||
|
||||
console.log(`📚 [LibraryStore] Loading items for parent: ${parentId.substring(0, 8)}...`);
|
||||
log.debug(`📚 Loading items for parent: ${parentId.substring(0, 8)}...`);
|
||||
|
||||
const result = await repo.getItems(parentId, {
|
||||
startIndex: options.startIndex ?? 0,
|
||||
@@ -134,9 +137,9 @@ function createLibraryStore() {
|
||||
const loadTime = Math.round(performance.now() - startTime);
|
||||
|
||||
if (loadTime < 100) {
|
||||
console.log(`🚀 [LibraryStore] CACHE HIT! Loaded ${result.items.length} items in ${loadTime}ms (instant)`);
|
||||
log.debug(`🚀 CACHE HIT! Loaded ${result.items.length} items in ${loadTime}ms (instant)`);
|
||||
} else {
|
||||
console.log(`⏳ [LibraryStore] Loaded ${result.items.length} items in ${loadTime}ms (from server)`);
|
||||
log.debug(`⏳ Loaded ${result.items.length} items in ${loadTime}ms (from server)`);
|
||||
}
|
||||
|
||||
update((s) => ({
|
||||
@@ -202,11 +205,11 @@ function createLibraryStore() {
|
||||
const repo = auth.getRepository();
|
||||
const item = await repo.getItem(itemId);
|
||||
|
||||
console.log(`[LibraryStore] loadItem(${itemId}): ${item.name} (${item.kind})`);
|
||||
console.log(`[LibraryStore] - Has people? ${item.people ? `YES (${item.people.length})` : 'NO'}`);
|
||||
log.debug(`loadItem(${itemId}): ${item.name} (${item.kind})`);
|
||||
log.debug(`- Has people? ${item.people ? `YES (${item.people.length})` : 'NO'}`);
|
||||
if (item.people && item.people.length > 0) {
|
||||
item.people.forEach((p, i) => {
|
||||
console.log(`[LibraryStore] [${i}] ${p.name} (type: "${p.type}", id: "${p.id}")`);
|
||||
log.debug(` [${i}] ${p.name} (type: "${p.type}", id: "${p.id}")`);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -319,7 +322,7 @@ function createLibraryStore() {
|
||||
update((s) => ({ ...s, genres }));
|
||||
return genres;
|
||||
} catch (error) {
|
||||
console.error("Failed to load genres:", error);
|
||||
log.error("Failed to load genres:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,9 @@ import { writable, get } from "svelte/store";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import type { Session } from "$lib/api/types";
|
||||
import type { LmsSyncGroup } from "$lib/api/bindings";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("LmsSync");
|
||||
|
||||
const LMS_DEVICE_PREFIX = "lms-";
|
||||
|
||||
@@ -51,7 +54,7 @@ function createLmsSyncStore() {
|
||||
update((s) => ({ ...s, groups, error: null }));
|
||||
} catch (error) {
|
||||
// The plugin may not be installed; treat as "no groups" rather than fatal.
|
||||
console.warn("[LmsSync] Failed to load sync groups:", error);
|
||||
log.warn("Failed to load sync groups:", error);
|
||||
update((s) => ({ ...s, groups: [] }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ import { writable, derived } from "svelte/store";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { auth } from "./auth";
|
||||
import { buildHeroMix } from "$lib/utils/heroMix";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("MoviesStore");
|
||||
|
||||
/** A single "by genre" row: the genre name plus the movies in it. */
|
||||
export interface GenreRow {
|
||||
@@ -91,7 +94,7 @@ function createMoviesStore() {
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to load movie sections";
|
||||
update(s => ({ ...s, isLoading: false, error: message }));
|
||||
console.error("Failed to load movie sections:", error);
|
||||
log.error("Failed to load movie sections:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +123,7 @@ function createMoviesStore() {
|
||||
});
|
||||
return { id: genre.id, name: genre.name, items: result.items };
|
||||
} catch (e) {
|
||||
console.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
log.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
return { id: genre.id, name: genre.name, items: [] };
|
||||
}
|
||||
})
|
||||
@@ -133,7 +136,7 @@ function createMoviesStore() {
|
||||
|
||||
update(s => ({ ...s, genreRows }));
|
||||
} catch (e) {
|
||||
console.warn("Failed to load movie genre rows:", e);
|
||||
log.warn("Failed to load movie genre rows:", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,9 @@ import { auth } from "./auth";
|
||||
import { excludePodcasts } from "$lib/utils/podcastFilter";
|
||||
import { selectDiverseGenres, sampleAcross } from "$lib/utils/genreDiversity";
|
||||
import { buildHeroMix } from "$lib/utils/heroMix";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("MusicStore");
|
||||
|
||||
/** A single "by genre" row: the genre name plus the albums in it. */
|
||||
export interface GenreRow {
|
||||
@@ -124,7 +127,7 @@ function createMusicStore() {
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to load music sections";
|
||||
update(s => ({ ...s, isLoading: false, error: message }));
|
||||
console.error("Failed to load music sections:", error);
|
||||
log.error("Failed to load music sections:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +146,7 @@ function createMusicStore() {
|
||||
// HACK: drop the "Podcasts" folder that lives in the music library.
|
||||
return { id: genre.id, name: genre.name, items: excludePodcasts(result.items) };
|
||||
} catch (e) {
|
||||
console.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
log.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
return { id: genre.id, name: genre.name, items: [] };
|
||||
}
|
||||
}
|
||||
@@ -205,7 +208,7 @@ function createMusicStore() {
|
||||
|
||||
update(s => ({ ...s, genreRows }));
|
||||
} catch (e) {
|
||||
console.warn("Failed to load music genre rows:", e);
|
||||
log.warn("Failed to load music genre rows:", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ import { commands, events } from "$lib/api/bindings";
|
||||
import { sessions, selectedSession } from "./sessions";
|
||||
import { auth } from "./auth";
|
||||
import { ticksToSeconds } from "$lib/utils/playbackUnits";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("PlaybackMode");
|
||||
|
||||
export type PlaybackMode = "local" | "remote" | "idle";
|
||||
|
||||
@@ -59,7 +62,7 @@ function createPlaybackModeStore() {
|
||||
// authoritative mode.
|
||||
sessions.selectSession(remoteSessionId);
|
||||
} catch (error) {
|
||||
console.error("Failed to get playback mode:", error);
|
||||
log.error("Failed to get playback mode:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +84,7 @@ function createPlaybackModeStore() {
|
||||
sessionId: string | null | undefined,
|
||||
currentPosition?: number,
|
||||
): Promise<void> {
|
||||
console.log("[PlaybackMode] Transferring to remote session:", sessionId);
|
||||
log.debug("Transferring to remote session:", sessionId);
|
||||
update((s) => ({ ...s, isTransferring: true, transferError: null }));
|
||||
|
||||
let aborted = false;
|
||||
@@ -104,12 +107,12 @@ function createPlaybackModeStore() {
|
||||
|
||||
// Rust handles everything - just wait for it to complete
|
||||
// It includes its own 5-second timeout for track loading
|
||||
console.log("[PlaybackMode] About to invoke playback_mode_transfer_to_remote with sessionId:", sessionId, "position:", positionOverride);
|
||||
log.debug("About to invoke playback_mode_transfer_to_remote with sessionId:", sessionId, "position:", positionOverride);
|
||||
await commands.playbackModeTransferToRemote(sessionId ?? "", positionOverride);
|
||||
console.log("[PlaybackMode] Invoke completed successfully");
|
||||
log.debug("Invoke completed successfully");
|
||||
|
||||
if (aborted) {
|
||||
console.log("[PlaybackMode] Transfer was cancelled");
|
||||
log.debug("Transfer was cancelled");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -122,10 +125,10 @@ function createPlaybackModeStore() {
|
||||
isTransferring: false,
|
||||
}));
|
||||
|
||||
console.log("[PlaybackMode] Successfully transferred to remote");
|
||||
log.debug("Successfully transferred to remote");
|
||||
} catch (error) {
|
||||
if (aborted) {
|
||||
console.log("[PlaybackMode] Transfer was cancelled");
|
||||
log.debug("Transfer was cancelled");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -135,7 +138,7 @@ function createPlaybackModeStore() {
|
||||
isTransferring: false,
|
||||
transferError: message,
|
||||
}));
|
||||
console.error("Transfer to remote failed:", error);
|
||||
log.error("Transfer to remote failed:", error);
|
||||
throw error;
|
||||
} finally {
|
||||
currentTransferAbort = null;
|
||||
@@ -154,7 +157,7 @@ function createPlaybackModeStore() {
|
||||
* Will be fully migrated to Rust after Phase 3.
|
||||
*/
|
||||
async function transferToLocal(): Promise<void> {
|
||||
console.log("[PlaybackMode] Transferring to local");
|
||||
log.debug("Transferring to local");
|
||||
update((s) => ({ ...s, isTransferring: true, transferError: null }));
|
||||
|
||||
let aborted = false;
|
||||
@@ -195,7 +198,7 @@ function createPlaybackModeStore() {
|
||||
const itemId = (nowPlaying as any).id || (nowPlaying as any).Id;
|
||||
const itemName = (nowPlaying as any).name || (nowPlaying as any).Name;
|
||||
|
||||
console.log("[PlaybackMode] Current remote item:", itemName, "position:", positionSeconds, "id:", itemId);
|
||||
log.debug("Current remote item:", itemName, "position:", positionSeconds, "id:", itemId);
|
||||
|
||||
if (!itemId) {
|
||||
throw new Error("Cannot transfer: remote item has no ID");
|
||||
@@ -246,10 +249,10 @@ function createPlaybackModeStore() {
|
||||
isTransferring: false,
|
||||
}));
|
||||
|
||||
console.log("[PlaybackMode] Successfully transferred to local");
|
||||
log.debug("Successfully transferred to local");
|
||||
} catch (error) {
|
||||
if (aborted) {
|
||||
console.log("[PlaybackMode] Transfer was cancelled");
|
||||
log.debug("Transfer was cancelled");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -259,7 +262,7 @@ function createPlaybackModeStore() {
|
||||
isTransferring: false,
|
||||
transferError: message,
|
||||
}));
|
||||
console.error("Transfer to local failed:", error);
|
||||
log.error("Transfer to local failed:", error);
|
||||
throw error;
|
||||
} finally {
|
||||
// Always lower the Rust transferring flag so it can't stick on if any step
|
||||
@@ -268,7 +271,7 @@ function createPlaybackModeStore() {
|
||||
try {
|
||||
await commands.playbackModeSetTransferring(false);
|
||||
} catch (e) {
|
||||
console.warn("[PlaybackMode] Failed to clear transferring flag:", e);
|
||||
log.warn("Failed to clear transferring flag:", e);
|
||||
}
|
||||
currentTransferAbort = null;
|
||||
// Reconcile to the authoritative Rust mode in case a step above threw and
|
||||
@@ -294,9 +297,9 @@ function createPlaybackModeStore() {
|
||||
if (event.payload.type === "remote_disconnect_requested") {
|
||||
const currentState = get({ subscribe });
|
||||
if (currentState.mode === "remote") {
|
||||
console.log("[PlaybackMode] Lockscreen requested disconnect; transferring to local");
|
||||
log.debug("Lockscreen requested disconnect; transferring to local");
|
||||
transferToLocal().catch((e) =>
|
||||
console.error("[PlaybackMode] Lockscreen-triggered transfer failed:", e),
|
||||
log.error("Lockscreen-triggered transfer failed:", e),
|
||||
);
|
||||
}
|
||||
return;
|
||||
@@ -331,7 +334,7 @@ function createPlaybackModeStore() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[PlaybackMode] Backend mode changed →", mode, remoteSessionId);
|
||||
log.debug("Backend mode changed →", mode, remoteSessionId);
|
||||
update((s) => ({ ...s, mode, remoteSessionId }));
|
||||
// Keep the selected session in step so the merged UI stores follow, but
|
||||
// only touch the selection when it actually differs — re-selecting the
|
||||
@@ -352,10 +355,10 @@ function createPlaybackModeStore() {
|
||||
if (currentState.mode === "remote" && currentState.remoteSessionId && !currentState.isTransferring) {
|
||||
if (!session || session.id !== currentState.remoteSessionId || !session.supportsMediaControl) {
|
||||
consecutiveMisses++;
|
||||
console.warn(`[PlaybackMode] Remote session miss ${consecutiveMisses}/${DISCONNECT_THRESHOLD}`);
|
||||
log.warn(`Remote session miss ${consecutiveMisses}/${DISCONNECT_THRESHOLD}`);
|
||||
|
||||
if (consecutiveMisses >= DISCONNECT_THRESHOLD) {
|
||||
console.warn("[PlaybackMode] Remote session lost after sustained disconnection");
|
||||
log.warn("Remote session lost after sustained disconnection");
|
||||
consecutiveMisses = 0;
|
||||
update((s) => ({
|
||||
...s,
|
||||
@@ -367,7 +370,7 @@ function createPlaybackModeStore() {
|
||||
} else {
|
||||
// Session is healthy, reset counter
|
||||
if (consecutiveMisses > 0) {
|
||||
console.log("[PlaybackMode] Remote session recovered after", consecutiveMisses, "misses");
|
||||
log.debug("Remote session recovered after", consecutiveMisses, "misses");
|
||||
}
|
||||
consecutiveMisses = 0;
|
||||
}
|
||||
@@ -389,7 +392,7 @@ function createPlaybackModeStore() {
|
||||
*/
|
||||
function cancelTransfer(): void {
|
||||
if (currentTransferAbort) {
|
||||
console.log("[PlaybackMode] Cancelling transfer");
|
||||
log.debug("Cancelling transfer");
|
||||
currentTransferAbort();
|
||||
}
|
||||
}
|
||||
@@ -399,11 +402,11 @@ function createPlaybackModeStore() {
|
||||
* This stops controlling the remote device and returns to idle/local state
|
||||
*/
|
||||
async function disconnect(): Promise<void> {
|
||||
console.log("[PlaybackMode] Disconnecting from remote session");
|
||||
log.debug("Disconnecting from remote session");
|
||||
|
||||
const currentState = get({ subscribe });
|
||||
if (currentState.mode !== "remote") {
|
||||
console.log("[PlaybackMode] Not in remote mode, nothing to disconnect");
|
||||
log.debug("Not in remote mode, nothing to disconnect");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -420,10 +423,10 @@ function createPlaybackModeStore() {
|
||||
transferError: null,
|
||||
}));
|
||||
|
||||
console.log("[PlaybackMode] Successfully disconnected");
|
||||
log.debug("Successfully disconnected");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to disconnect";
|
||||
console.error("[PlaybackMode] Disconnect failed:", error);
|
||||
log.error("Disconnect failed:", error);
|
||||
update((s) => ({
|
||||
...s,
|
||||
transferError: message,
|
||||
|
||||
@@ -10,6 +10,9 @@ import { writable, derived, get } from "svelte/store";
|
||||
import { commands, events } from "$lib/api/bindings";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Queue");
|
||||
|
||||
export type RepeatMode = "off" | "all" | "one";
|
||||
|
||||
@@ -72,7 +75,7 @@ function createQueueStore() {
|
||||
async function syncFromRust(): Promise<void> {
|
||||
try {
|
||||
const rustQueue = (await commands.playerGetQueue()) as unknown as QueueChangedEvent;
|
||||
console.log("[Queue] Synced from Rust - items:", rustQueue.items.length);
|
||||
log.debug("Synced from Rust - items:", rustQueue.items.length);
|
||||
set({
|
||||
items: rustQueue.items,
|
||||
currentIndex: rustQueue.currentIndex,
|
||||
@@ -82,7 +85,7 @@ function createQueueStore() {
|
||||
hasPrevious: rustQueue.hasPrevious,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[Queue] Failed to sync from Rust:", error);
|
||||
log.error("Failed to sync from Rust:", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
-23
@@ -4,6 +4,9 @@
|
||||
import { writable, derived } from "svelte/store";
|
||||
import { commands, events } from "$lib/api/bindings";
|
||||
import type { Session } from "$lib/api/types";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Sessions");
|
||||
|
||||
interface SessionsState {
|
||||
sessions: Session[];
|
||||
@@ -28,9 +31,9 @@ function createSessionsStore() {
|
||||
events.playerStatusEvent.listen((event) => {
|
||||
if (event.payload.type === "sessions_updated") {
|
||||
const sessions = event.payload.sessions as unknown as Session[];
|
||||
console.log(`[Sessions] Received ${sessions.length} sessions from backend`);
|
||||
log.debug(`Received ${sessions.length} sessions from backend`);
|
||||
sessions.forEach((s, i) => {
|
||||
console.log(`[Sessions] Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`);
|
||||
log.debug(`Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`);
|
||||
});
|
||||
update((s) => ({
|
||||
...s,
|
||||
@@ -50,9 +53,9 @@ function createSessionsStore() {
|
||||
|
||||
const sessions = await commands.sessionsPollNow();
|
||||
|
||||
console.log(`[Sessions] Manual refresh returned ${sessions.length} sessions`);
|
||||
log.debug(`Manual refresh returned ${sessions.length} sessions`);
|
||||
sessions.forEach((s, i) => {
|
||||
console.log(`[Sessions] Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`);
|
||||
log.debug(`Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`);
|
||||
});
|
||||
|
||||
update((s) => ({
|
||||
@@ -69,7 +72,7 @@ function createSessionsStore() {
|
||||
isLoading: false,
|
||||
error: message,
|
||||
}));
|
||||
console.error("Failed to fetch sessions:", error);
|
||||
log.error("Failed to fetch sessions:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +93,7 @@ function createSessionsStore() {
|
||||
// Refresh after command to get updated state
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
console.error("Failed to send play/pause command:", error);
|
||||
log.error("Failed to send play/pause command:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -103,7 +106,7 @@ function createSessionsStore() {
|
||||
await commands.remoteSendCommand(sessionId ?? "", "Stop");
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
console.error("Failed to send stop command:", error);
|
||||
log.error("Failed to send stop command:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -116,7 +119,7 @@ function createSessionsStore() {
|
||||
await commands.remoteSendCommand(sessionId ?? "", "NextTrack");
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
console.error("Failed to send next track command:", error);
|
||||
log.error("Failed to send next track command:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -129,7 +132,7 @@ function createSessionsStore() {
|
||||
await commands.remoteSendCommand(sessionId ?? "", "PreviousTrack");
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
console.error("Failed to send previous track command:", error);
|
||||
log.error("Failed to send previous track command:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -142,7 +145,7 @@ function createSessionsStore() {
|
||||
await commands.remoteSessionSeek(sessionId ?? "", positionTicks);
|
||||
// Don't refresh immediately for seek to avoid UI lag
|
||||
} catch (error) {
|
||||
console.error("Failed to send seek command:", error);
|
||||
log.error("Failed to send seek command:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -155,7 +158,7 @@ function createSessionsStore() {
|
||||
await commands.remoteSessionSetVolume(sessionId ?? "", volume);
|
||||
// Don't refresh immediately for volume to avoid UI lag
|
||||
} catch (error) {
|
||||
console.error("Failed to send volume command:", error);
|
||||
log.error("Failed to send volume command:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -168,7 +171,7 @@ function createSessionsStore() {
|
||||
await commands.remoteSendCommand(sessionId ?? "", "ToggleMute");
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle mute:", error);
|
||||
log.error("Failed to toggle mute:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -181,20 +184,20 @@ function createSessionsStore() {
|
||||
itemIds: string[],
|
||||
startIndex = 0
|
||||
): Promise<void> {
|
||||
console.log("[SESSIONS] ========== playOnSession called ==========");
|
||||
console.log("[SESSIONS] sessionId:", sessionId);
|
||||
console.log("[SESSIONS] itemIds array:", itemIds);
|
||||
console.log("[SESSIONS] itemIds.length:", itemIds.length);
|
||||
console.log("[SESSIONS] itemIds JSON:", JSON.stringify(itemIds));
|
||||
console.log("[SESSIONS] startIndex:", startIndex);
|
||||
console.log("[SESSIONS] About to call commands.remotePlayOnSession");
|
||||
log.debug("========== playOnSession called ==========");
|
||||
log.debug("sessionId:", sessionId);
|
||||
log.debug("itemIds array:", itemIds);
|
||||
log.debug("itemIds.length:", itemIds.length);
|
||||
log.debug("itemIds JSON:", JSON.stringify(itemIds));
|
||||
log.debug("startIndex:", startIndex);
|
||||
log.debug("About to call commands.remotePlayOnSession");
|
||||
try {
|
||||
// Use Rust player's Jellyfin client for remote playback
|
||||
const result = await commands.remotePlayOnSession(sessionId ?? "", itemIds, startIndex);
|
||||
console.log("[SESSIONS] invoke succeeded, result:", result);
|
||||
log.debug("invoke succeeded, result:", result);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
console.error("[SESSIONS] Failed to play on session:", error);
|
||||
log.error("Failed to play on session:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -242,10 +245,10 @@ export const controllableSessions = derived(
|
||||
sessions,
|
||||
($sessions) => {
|
||||
const controllable = $sessions.sessions.filter((s) => s.supportsRemoteControl);
|
||||
console.log(`[Sessions] Filtering ${$sessions.sessions.length} total sessions, ${controllable.length} are controllable`);
|
||||
log.debug(`Filtering ${$sessions.sessions.length} total sessions, ${controllable.length} are controllable`);
|
||||
$sessions.sessions.forEach((s, i) => {
|
||||
const status = s.supportsRemoteControl ? "✓ CONTROLLABLE" : "✗ NOT CONTROLLABLE";
|
||||
console.log(`[Sessions] ${status}: ${s.deviceName} (id=${s.id}, supportsRemoteControl=${s.supportsRemoteControl})`);
|
||||
log.debug(` ${status}: ${s.deviceName} (id=${s.id}, supportsRemoteControl=${s.supportsRemoteControl})`);
|
||||
});
|
||||
return controllable;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
filterSupersededResumeItems,
|
||||
filterInProgressNextUpItems,
|
||||
} from "./continueWatchingFilter";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("TvStore");
|
||||
|
||||
/** A single "by genre" row: the genre name plus the series in it. */
|
||||
export interface GenreRow {
|
||||
@@ -114,7 +117,7 @@ function createTvStore() {
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to load TV sections";
|
||||
update(s => ({ ...s, isLoading: false, error: message }));
|
||||
console.error("Failed to load TV sections:", error);
|
||||
log.error("Failed to load TV sections:", error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,7 +146,7 @@ function createTvStore() {
|
||||
});
|
||||
return { id: genre.id, name: genre.name, items: result.items };
|
||||
} catch (e) {
|
||||
console.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
log.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
return { id: genre.id, name: genre.name, items: [] };
|
||||
}
|
||||
})
|
||||
@@ -156,7 +159,7 @@ function createTvStore() {
|
||||
|
||||
update(s => ({ ...s, genreRows }));
|
||||
} catch (e) {
|
||||
console.warn("Failed to load TV genre rows:", e);
|
||||
log.warn("Failed to load TV genre rows:", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,10 @@
|
||||
* Unsupported (no-op) on every non-Android platform.
|
||||
*/
|
||||
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("BgAudio");
|
||||
|
||||
interface AndroidBackgroundAudioBridge {
|
||||
setEnabled(enabled: boolean): void;
|
||||
}
|
||||
@@ -44,15 +48,15 @@ export function setBackgroundAudioEnabled(enabled: boolean): boolean {
|
||||
// before/without the bridge existing. Silently no-oping here leaves the UI
|
||||
// showing "armed" while native never learns — and the handoff then never
|
||||
// fires on lock. Report it so callers can retry.
|
||||
console.warn("[BgAudio] setEnabled: bridge missing, native NOT armed");
|
||||
log.warn("setEnabled: bridge missing, native NOT armed");
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
b.setEnabled(enabled);
|
||||
console.log("[BgAudio] setEnabled ->", enabled);
|
||||
log.debug("setEnabled ->", enabled);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.warn("[BgAudio] Failed to set enabled:", err);
|
||||
log.warn("Failed to set enabled:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
* Provides tactile feedback for user actions
|
||||
*/
|
||||
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Haptics");
|
||||
|
||||
type HapticStyle = "light" | "medium" | "heavy" | "success" | "warning" | "error";
|
||||
|
||||
/**
|
||||
@@ -28,7 +32,7 @@ export function haptic(style: HapticStyle = "medium") {
|
||||
navigator.vibrate(patterns[style]);
|
||||
} catch (error) {
|
||||
// Silently fail if vibration is not supported or blocked
|
||||
console.debug("Haptic feedback not available:", error);
|
||||
log.debug("Haptic feedback not available:", error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
* already does the right thing and these calls are no-ops.
|
||||
*/
|
||||
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("Immersive");
|
||||
|
||||
interface AndroidImmersiveBridge {
|
||||
enter(): void;
|
||||
exit(): void;
|
||||
@@ -38,7 +42,7 @@ export function isImmersiveSupported(): boolean {
|
||||
try {
|
||||
return bridge()?.isSupported() ?? false;
|
||||
} catch (err) {
|
||||
console.warn("[Immersive] isSupported check failed:", err);
|
||||
log.warn("isSupported check failed:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -48,7 +52,7 @@ export function enterImmersive(): void {
|
||||
try {
|
||||
bridge()?.enter();
|
||||
} catch (err) {
|
||||
console.error("[Immersive] Failed to hide the system bars:", err);
|
||||
log.error("Failed to hide the system bars:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +67,6 @@ export function exitImmersive(): void {
|
||||
try {
|
||||
bridge()?.exit();
|
||||
} catch (err) {
|
||||
console.error("[Immersive] Failed to restore the system bars:", err);
|
||||
log.error("Failed to restore the system bars:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
* so there is no HTML5 fallback to reach for.
|
||||
*/
|
||||
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("PiP");
|
||||
|
||||
interface AndroidPictureInPictureBridge {
|
||||
enterPip(): void;
|
||||
isSupported(): boolean;
|
||||
@@ -41,7 +45,7 @@ export function isPipSupported(): boolean {
|
||||
try {
|
||||
return bridge()?.isSupported() ?? false;
|
||||
} catch (err) {
|
||||
console.warn("[PiP] isSupported check failed:", err);
|
||||
log.warn("isSupported check failed:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -54,7 +58,7 @@ export function canEnterPip(): boolean {
|
||||
try {
|
||||
return bridge()?.canEnterPip() ?? false;
|
||||
} catch (err) {
|
||||
console.warn("[PiP] canEnterPip check failed:", err);
|
||||
log.warn("canEnterPip check failed:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -64,7 +68,7 @@ export function enterPip(): void {
|
||||
try {
|
||||
bridge()?.enterPip();
|
||||
} catch (err) {
|
||||
console.error("[PiP] Failed to enter picture-in-picture:", err);
|
||||
log.error("Failed to enter picture-in-picture:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +86,7 @@ export function setAutoEnterEnabled(enabled: boolean): void {
|
||||
try {
|
||||
bridge()?.setAutoEnterEnabled(enabled);
|
||||
} catch (err) {
|
||||
console.warn("[PiP] Failed to set auto-enter:", err);
|
||||
log.warn("Failed to set auto-enter:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +119,6 @@ export function setHtml5VideoState(
|
||||
try {
|
||||
bridge()?.setHtml5VideoState(active, Math.round(width), Math.round(height), playing);
|
||||
} catch (err) {
|
||||
console.warn("[PiP] Failed to report HTML5 video state:", err);
|
||||
log.warn("Failed to report HTML5 video state:", err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,10 @@
|
||||
* document exists, and a page load wipes any inline style native had set.
|
||||
*/
|
||||
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("SafeArea");
|
||||
|
||||
/** Window insets in CSS pixels, one per edge. */
|
||||
export interface SafeAreaInsets {
|
||||
top: number;
|
||||
@@ -135,7 +139,7 @@ export function readNativeInsets(): SafeAreaInsets | null {
|
||||
try {
|
||||
return parseNativeInsets(bridge.get());
|
||||
} catch (err) {
|
||||
console.warn("[SafeArea] AndroidInsets bridge unusable:", err);
|
||||
log.warn("AndroidInsets bridge unusable:", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
*/
|
||||
|
||||
import { nativeVideoActive } from "$lib/stores/nativeVideo";
|
||||
import { createLogger } from "$lib/utils/logger";
|
||||
|
||||
const log = createLogger("videoSurface");
|
||||
|
||||
interface AndroidVideoSurfaceBridge {
|
||||
setTransparent(transparent: boolean): void;
|
||||
@@ -50,7 +53,7 @@ export function isNativeSurfaceBridgeAvailable(): boolean {
|
||||
try {
|
||||
return bridge()?.isSupported() ?? false;
|
||||
} catch (err) {
|
||||
console.warn("[videoSurface] isSupported check failed:", err);
|
||||
log.warn("isSupported check failed:", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -73,17 +76,17 @@ export function enableNativeVideoCompositing(): void {
|
||||
// correctly behind a WebView that never stopped painting its own opaque
|
||||
// background. That ambiguity is what DR-172 was left holding. MainActivity's
|
||||
// console bridge forwards this to logcat under the JellyTauWeb tag.
|
||||
console.error(
|
||||
"[videoSurface] AndroidVideoSurface bridge is MISSING - the webview will " +
|
||||
log.error(
|
||||
"AndroidVideoSurface bridge is MISSING - the webview will " +
|
||||
"stay opaque and native video will play as audio with no picture"
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
androidVideoSurface.setTransparent(true);
|
||||
console.log("[videoSurface] compositing enabled (setTransparent(true) sent)");
|
||||
log.debug("compositing enabled (setTransparent(true) sent)");
|
||||
} catch (err) {
|
||||
console.warn("[videoSurface] setTransparent(true) failed:", err);
|
||||
log.warn("setTransparent(true) failed:", err);
|
||||
nativeVideoActive.set(false);
|
||||
}
|
||||
}
|
||||
@@ -93,7 +96,7 @@ export function disableNativeVideoCompositing(): void {
|
||||
try {
|
||||
bridge()?.setTransparent(false);
|
||||
} catch (err) {
|
||||
console.warn("[videoSurface] setTransparent(false) failed:", err);
|
||||
log.warn("setTransparent(false) failed:", err);
|
||||
}
|
||||
// Always clear the page layer, even if the bridge call failed, so the app is
|
||||
// never left rendering over a transparent window.
|
||||
|
||||
Reference in New Issue
Block a user