refactor: remove legacy single-root APIs, defer filesystem I/O, enforce POSIX paths

- Remove legacy endpoints: /api/change-folder, /api/index, /api/scan, /api/status,
  /api/playback/resume-positions
- Remove legacy global scanner module-level API from hivescan/scanner.py
- Defer all filesystem validation to background task in server lifespan (macOS-safe)
- CLI and winmain pass raw paths via MEDIAHIVE_ROOTS; no pre-startup validation
- Enforce POSIX paths everywhere (as_posix(), no backslash leakage)
- Remove MEDIAHIVE_PATH and MEDIAHIVE_DEFER_INITIAL_ROOT env vars
- Update frontend api.ts to use per-root resume positions
- Update docs/API.md and docs/multi-index-plan.md
- Fix Python 2 style except clauses in hivescan/utils.py and scanning.py
This commit is contained in:
2026-05-23 22:21:35 +00:00
parent 2f83193ff4
commit 9c75fa4569
25 changed files with 1963 additions and 1150 deletions
+77 -4
View File
@@ -184,7 +184,7 @@
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import type { Movie, Series, MediaItem, EpisodeWithSeries, MatchedPerson, MatchedEpisode, TaskInfo } from './types';
import { playMedia, openFolder, isMpcBeReachable, fetchResumePositions, normalizeMediaPath, getPlayerStatus } from './api';
import { playMedia, openFolder, isMpcBeReachable, fetchResumePositions, normalizeMediaPath, getPlayerStatus, fetchRoots } from './api';
import { useKeyboardNavigation } from './composables/useKeyboardNavigation';
import { useMediaWebSocket } from './composables/useMediaWebSocket';
import Header from './components/Header.vue';
@@ -226,11 +226,53 @@ function normalizeHistoryPath(value: string): string {
}
// WebSocket-driven media index
const { mediaIndex, loading, error, connected: wsConnected, tasks } = useMediaWebSocket();
const { mediaIndex, loading, error, connected: wsConnected, tasks, setActiveRoots } = useMediaWebSocket();
// Active tasks for the debug overlay
const activeTasks = computed<TaskInfo[]>(() => Array.from(tasks.value.values()));
// Poll for active roots and connect WS to them
const rootStatuses = ref<Map<string, { path: string; status: string }>>(new Map());
async function refreshRoots() {
try {
const roots = await fetchRoots();
const newMap = new Map<string, { path: string; status: string }>();
const activeIds: string[] = [];
for (const r of roots) {
newMap.set(r.root_id, { path: r.path, status: r.status });
if (r.status === 'ready' || r.status === 'scanning' || r.status === 'loading') {
activeIds.push(r.root_id);
}
}
rootStatuses.value = newMap;
setActiveRoots(activeIds);
} catch (e) {
console.error('Failed to fetch roots:', e);
}
}
let rootsPollTimer: number | null = null;
function startRootsPolling() {
if (rootsPollTimer !== null) return;
void refreshRoots();
rootsPollTimer = window.setInterval(refreshRoots, 5000);
}
function stopRootsPolling() {
if (rootsPollTimer !== null) {
window.clearInterval(rootsPollTimer);
rootsPollTimer = null;
}
}
onMounted(() => {
startRootsPolling();
});
onUnmounted(() => {
stopRootsPolling();
});
const searchResults = ref<MediaItem[]>([]);
const isSearching = ref(false);
const mpcBeConnected = ref(false);
@@ -609,6 +651,7 @@ function movieToMediaItem(movie: Movie): MediaItem {
type: 'movies',
resolution: resolution,
data: movie,
root_id: movie.root_id,
};
}
@@ -637,6 +680,7 @@ function seriesToMediaItem(series: Series): MediaItem {
showreel_source_sets: reelSourceSets.length > 0 ? reelSourceSets : null,
type: 'series',
data: series,
root_id: series.root_id,
};
}
@@ -1430,10 +1474,34 @@ function reloadPage() {
window.location.reload();
}
function findRootIdForPath(filePath: string): string | null {
if (!mediaIndex.value) return null;
for (const movie of mediaIndex.value.movies) {
for (const torrent of Object.values(movie.torrents || {})) {
if (torrent.playable_file === filePath) return movie.root_id;
}
}
for (const series of mediaIndex.value.series) {
for (const season of series.seasons || []) {
for (const episode of season.episodes || []) {
for (const torrent of Object.values(episode.torrents || {})) {
if (torrent.playable_file === filePath) return series.root_id;
}
}
}
}
return null;
}
async function handlePlay(filePath: string) {
const rootId = findRootIdForPath(filePath);
if (!rootId) {
console.error('Cannot play: unknown root for path', filePath);
return;
}
mpcBeOpeningUntil.value = Date.now() + MPC_BE_OPENING_GRACE_MS;
try {
await playMedia(filePath);
await playMedia(rootId, filePath);
const connected = await tryConnectMpcBe();
if (connected) {
mpcBeConnected.value = true;
@@ -1445,8 +1513,13 @@ async function handlePlay(filePath: string) {
}
async function handleOpenFolder(folderPath: string) {
const rootId = findRootIdForPath(folderPath);
if (!rootId) {
console.error('Cannot open folder: unknown root for path', folderPath);
return;
}
try {
await openFolder(folderPath);
await openFolder(rootId, folderPath);
} catch (e) {
console.error('Failed to open folder:', e);
}
+72 -42
View File
@@ -1,9 +1,22 @@
import type { MediaIndex } from './types';
export interface PlayerStatus {
remote: boolean;
}
export interface RootStatus {
root_id: string;
path: string;
status: string;
error: string | null;
movies: number;
series: number;
}
export interface RootsResponse {
roots: RootStatus[];
}
export function normalizeMediaPath(input: string): string {
return input
.replace(/\\/g, '/')
@@ -71,12 +84,53 @@ export function getVideoSourceAttributes(path: string | null | undefined): Video
}
/**
* Load the media index from the server
* Fetch active roots and their statuses
*/
export async function loadMediaIndex(): Promise<MediaIndex> {
const response = await fetch('/api/index');
export async function fetchRoots(): Promise<RootStatus[]> {
const response = await fetch('/api/roots');
if (!response.ok) {
throw new Error(`Failed to load media index: ${response.statusText}`);
throw new Error(`Failed to load roots: ${response.statusText}`);
}
const data = await response.json();
return data.roots || [];
}
/**
* Fetch merged resume positions from all roots.
*/
export async function fetchResumePositions(): Promise<Record<string, number>> {
try {
const roots = await fetchRoots();
const merged: Record<string, number> = {};
await Promise.all(
roots.map(async (root) => {
const response = await fetch(`/api/roots/${encodeURIComponent(root.root_id)}/playback/resume-positions`);
if (!response.ok) return;
const data = await response.json().catch(() => ({}));
const positions = data?.resume_positions;
if (positions && typeof positions === 'object') {
Object.assign(merged, positions);
}
})
);
return merged;
} catch {
return {};
}
}
/**
* Replace the full root set atomically
*/
export async function replaceRoots(roots: Record<string, string>): Promise<{ accepted: RootStatus[]; failed: unknown[] }> {
const response = await fetch('/api/roots', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ roots }),
});
if (!response.ok) {
const err = await response.json().catch(() => ({ detail: response.statusText }));
throw new Error(err.detail || response.statusText);
}
return response.json();
}
@@ -84,10 +138,10 @@ export async function loadMediaIndex(): Promise<MediaIndex> {
/**
* Play a media file with the system's default player
*/
export async function playMedia(filePath: string): Promise<void> {
export async function playMedia(rootId: string, filePath: string): Promise<void> {
const normalizedPath = normalizeMediaPath(filePath);
try {
const response = await fetch('/api/play', {
const response = await fetch(`/api/roots/${encodeURIComponent(rootId)}/play`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_path: normalizedPath }),
@@ -105,10 +159,10 @@ export async function playMedia(filePath: string): Promise<void> {
/**
* Open a folder in the system file manager
*/
export async function openFolder(folderPath: string): Promise<void> {
export async function openFolder(rootId: string, folderPath: string): Promise<void> {
const normalizedPath = normalizeMediaPath(folderPath);
try {
const response = await fetch('/api/open-folder', {
const response = await fetch(`/api/roots/${encodeURIComponent(rootId)}/open-folder`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ folder_path: normalizedPath }),
@@ -148,18 +202,6 @@ export async function isMpcBeReachable(): Promise<boolean> {
}
}
export async function fetchResumePositions(): Promise<Record<string, number>> {
try {
const response = await fetch('/api/playback/resume-positions');
if (!response.ok) return {};
const data = await response.json().catch(() => ({}));
const resumePositions = data?.resume_positions;
return resumePositions && typeof resumePositions === 'object' ? resumePositions : {};
} catch {
return {};
}
}
/**
* Convert a cover path to a displayable URL.
* Uses FastAPI server for async file serving.
@@ -167,7 +209,7 @@ export async function fetchResumePositions(): Promise<Record<string, number>> {
* The path comes from the server already converted to Windows format (Z:\...)
* Paths starting with '/' are TMDB relative paths that weren't fetched - ignore them
*/
export function getCoverUrl(coverPath: string | null): string {
export function getCoverUrl(coverPath: string | null, rootId?: string | null): string {
if (!coverPath) {
return '';
}
@@ -177,7 +219,7 @@ export function getCoverUrl(coverPath: string | null): string {
}
// Convert relative path to URL path for FastAPI server
// .mediahive/covers/Movies/... -> /media/.mediahive/covers/Movies/...
// .mediahive/covers/Movies/... -> /api/media/{root_id}/.mediahive/covers/Movies/...
let urlPath = coverPath;
// Remove drive letter (Z:) and convert backslashes to forward slashes
@@ -194,30 +236,18 @@ export function getCoverUrl(coverPath: string | null): string {
// Encode URI components but preserve slashes
const encodedPath = urlPath.split('/').map(segment => encodeURIComponent(segment)).join('/');
return `/api/media${encodedPath}`;
const rid = rootId || 'unknown';
return `/api/media/${encodeURIComponent(rid)}${encodedPath}`;
}
/**
* Invoke the native OS folder picker via pywebview, then switch the server's
* media folder in-place and reload the page. Only works inside the packaged
* desktop app.
* Invoke the native OS folder picker via pywebview, then add the selected
* folder to the server's root list. Only works inside the packaged desktop app.
*/
export async function pickFolderAndRestart(): Promise<void> {
export async function pickFolderAndAddRoot(): Promise<string | null> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const api = (window as any).pywebview?.api;
if (!api) return;
if (!api) return null;
const folder: string | null = await api.pick_folder();
if (!folder) return;
const res = await fetch('/api/change-folder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ folder }),
});
if (res.ok) {
// Give the server a moment to complete the background folder switch before reloading
setTimeout(() => window.location.reload(), 500);
} else {
const err = await res.json().catch(() => ({ detail: res.statusText }));
alert(`Failed to change folder: ${err.detail || res.statusText}`);
}
return folder;
}
+4 -4
View File
@@ -472,26 +472,26 @@ function getImageUrl(item: MediaItem): string | undefined {
return undefined;
}
return getCoverUrl(imagePath);
return getCoverUrl(imagePath, item.root_id);
}
function getVideoSources(item: MediaItem): Array<{ src: string; type: string; codecs: string }> {
if (isVideoPath(item.cover_path)) {
return [{ src: getVideoPreviewUrl(getCoverUrl(item.cover_path)), ...getVideoSourceAttributes(item.cover_path) }];
return [{ src: getVideoPreviewUrl(getCoverUrl(item.cover_path, item.root_id)), ...getVideoSourceAttributes(item.cover_path) }];
}
const showreelSourceSets = item.showreel_source_sets;
if (showreelSourceSets && showreelSourceSets.length > 0) {
return showreelSourceSets[0]
.filter(path => isVideoPath(path))
.map(path => ({ src: getVideoPreviewUrl(getCoverUrl(path)), ...getVideoSourceAttributes(path) }));
.map(path => ({ src: getVideoPreviewUrl(getCoverUrl(path, item.root_id)), ...getVideoSourceAttributes(path) }));
}
const showreel = item.showreel_images;
if (showreel && showreel.length > 0) {
return showreel
.filter(path => isVideoPath(path))
.map(path => ({ src: getVideoPreviewUrl(getCoverUrl(path)), ...getVideoSourceAttributes(path) }));
.map(path => ({ src: getVideoPreviewUrl(getCoverUrl(path, item.root_id)), ...getVideoSourceAttributes(path) }));
}
return [];
+252 -9
View File
@@ -62,16 +62,57 @@
<span>Player Open</span>
</div>
<div v-if="isDesktopApp" class="header-settings">
<div class="header-settings">
<button
class="header-settings-btn"
title="Change media folder"
@click="changeFolder"
title="Manage media roots"
@click="showRootsPanel = !showRootsPanel"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
</svg>
</button>
<!-- Roots management dropdown -->
<div v-if="showRootsPanel" class="roots-panel">
<div class="roots-panel-header">
<span class="roots-panel-title">Media Roots</span>
<button class="roots-panel-close" @click="showRootsPanel = false">×</button>
</div>
<div class="roots-list">
<div
v-for="root in roots"
:key="root.root_id"
class="roots-item"
:class="`roots-item--${root.status}`"
>
<div class="roots-item-info">
<span class="roots-item-name">{{ root.name }}</span>
<span class="roots-item-path">{{ root.path }}</span>
</div>
<div class="roots-item-meta">
<span class="roots-item-status">{{ root.status }}</span>
<button
v-if="roots.length > 1"
class="roots-item-remove"
@click="removeRoot(root.root_id)"
title="Remove root"
>
×
</button>
</div>
</div>
</div>
<div class="roots-actions">
<button
v-if="isDesktopApp"
class="roots-add-btn"
@click="addRoot"
>
+ Add Folder
</button>
</div>
</div>
</div>
</header>
</template>
@@ -81,7 +122,14 @@ import { ref, watch, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { navAttrs } from '../composables/useKeyboardNavigation';
import logoUrl from '../assets/mediahive.webp';
import { pickFolderAndRestart } from '../api';
import { fetchRoots, replaceRoots, pickFolderAndAddRoot } from '../api';
interface RootEntry {
root_id: string;
name: string;
path: string;
status: string;
}
const props = defineProps<{
currentView: 'movies' | 'series';
@@ -100,18 +148,68 @@ const router = useRouter();
const searchInputRef = ref<HTMLInputElement | null>(null);
const localSearch = ref(props.searchQuery);
// True only when running inside the packaged pywebview desktop app.
// pywebview injects window.pywebview asynchronously, so we listen for the
// 'pywebviewready' event rather than checking at component creation time.
const isDesktopApp = ref(typeof (window as any).pywebview !== 'undefined');
function _onPywebviewReady() { isDesktopApp.value = true; }
window.addEventListener('pywebviewready', _onPywebviewReady, { once: true });
onUnmounted(() => window.removeEventListener('pywebviewready', _onPywebviewReady));
async function changeFolder() {
await pickFolderAndRestart();
const showRootsPanel = ref(false);
const roots = ref<RootEntry[]>([]);
async function refreshRoots() {
try {
const data = await fetchRoots();
roots.value = data.map(r => ({
root_id: r.root_id,
name: r.path.split('/').pop() || r.path.split('\\').pop() || r.root_id,
path: r.path,
status: r.status,
}));
} catch (e) {
console.error('Failed to fetch roots:', e);
}
}
async function removeRoot(rootId: string) {
const filtered = roots.value.filter(r => r.root_id !== rootId);
const newRoots = Object.fromEntries(filtered.map(r => [r.name, r.path]));
try {
await replaceRoots(newRoots);
await refreshRoots();
} catch (e) {
console.error('Failed to remove root:', e);
alert('Failed to remove root');
}
}
async function addRoot() {
const folder = await pickFolderAndAddRoot();
if (!folder) return;
const name = folder.split('/').pop() || folder.split('\\').pop() || 'media';
// Resolve name collisions
let uniqueName = name;
let suffix = 2;
const currentNames = new Set(roots.value.map(r => r.name));
while (currentNames.has(uniqueName)) {
uniqueName = `${name}${suffix}`;
suffix++;
}
const newRoots = Object.fromEntries(roots.value.map(r => [r.name, r.path]));
newRoots[uniqueName] = folder;
try {
await replaceRoots(newRoots);
await refreshRoots();
showRootsPanel.value = false;
} catch (e) {
console.error('Failed to add root:', e);
alert('Failed to add root');
}
}
watch(showRootsPanel, (visible) => {
if (visible) void refreshRoots();
});
// Check if we're on a detail page
const isDetailPage = computed(() => {
return props.position === 'after-movie-header' || props.position === 'after-series-hero';
@@ -213,4 +311,149 @@ onUnmounted(() => {
background: #22c55e;
box-shadow: 0 0 0 4px rgba(34, 197, 94, 0.18);
}
.header-settings {
position: relative;
}
.roots-panel {
position: absolute;
top: calc(100% + 8px);
right: 0;
width: 320px;
background: rgba(20, 20, 20, 0.95);
backdrop-filter: blur(16px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 16px;
z-index: 1000;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
}
.roots-panel-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.roots-panel-title {
font-weight: 600;
font-size: 0.95rem;
}
.roots-panel-close {
background: none;
border: none;
color: var(--text-secondary);
font-size: 1.2rem;
cursor: pointer;
padding: 0 4px;
}
.roots-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 240px;
overflow-y: auto;
}
.roots-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 10px;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
gap: 8px;
}
.roots-item--ready {
border-left: 3px solid #22c55e;
}
.roots-item--scanning {
border-left: 3px solid #f59e0b;
}
.roots-item--loading {
border-left: 3px solid #3b82f6;
}
.roots-item--error {
border-left: 3px solid #ef4444;
}
.roots-item-info {
display: flex;
flex-direction: column;
min-width: 0;
}
.roots-item-name {
font-size: 0.85rem;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.roots-item-path {
font-size: 0.75rem;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.roots-item-meta {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.roots-item-status {
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-muted);
}
.roots-item-remove {
background: none;
border: none;
color: var(--text-secondary);
font-size: 1rem;
cursor: pointer;
padding: 0 4px;
line-height: 1;
}
.roots-item-remove:hover {
color: #ef4444;
}
.roots-actions {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.roots-add-btn {
width: 100%;
padding: 8px;
background: rgba(255, 255, 255, 0.08);
border: 1px dashed rgba(255, 255, 255, 0.2);
border-radius: 8px;
color: var(--text-primary);
font-size: 0.85rem;
cursor: pointer;
transition: background 0.2s;
}
.roots-add-btn:hover {
background: rgba(255, 255, 255, 0.15);
}
</style>
+1 -1
View File
@@ -47,7 +47,7 @@ const emit = defineEmits<{
}>();
const coverUrl = computed(() => {
return getCoverUrl(props.item.cover_path);
return getCoverUrl(props.item.cover_path, props.item.root_id);
});
const resolution = computed(() => {
+3 -3
View File
@@ -92,16 +92,16 @@ const posterImageUrl = computed(() => {
if (!props.item.cover_path || isVideoPath(props.item.cover_path)) {
return null;
}
return getCoverUrl(props.item.cover_path);
return getCoverUrl(props.item.cover_path, props.item.root_id);
});
const posterVideoUrl = computed(() => {
if (props.item.cover_path && isVideoPath(props.item.cover_path)) {
return getCoverUrl(props.item.cover_path);
return getCoverUrl(props.item.cover_path, props.item.root_id);
}
const fallbackVideo = props.item.showreel_images?.find(path => isVideoPath(path));
return fallbackVideo ? getCoverUrl(fallbackVideo) : null;
return fallbackVideo ? getCoverUrl(fallbackVideo, props.item.root_id) : null;
});
const rating = computed(() => {
+4 -4
View File
@@ -113,7 +113,7 @@
>
<img
v-if="castMember.profile_path && !castMember.profile_path.startsWith('/')"
:src="getCoverUrl(castMember.profile_path)"
:src="getCoverUrl(castMember.profile_path, item.root_id)"
:alt="castMember.name"
class="cast-photo"
>
@@ -341,7 +341,7 @@ watch(collageSlots, async (slots) => {
}, { immediate: true });
function getShowreelUrl(path: string): string {
return getVideoPreviewUrl(getCoverUrl(path));
return getVideoPreviewUrl(getCoverUrl(path, props.item.root_id));
}
function getShowreelSourceAttributes(path: string): VideoSourceAttributes {
@@ -359,7 +359,7 @@ const backdropStyle = computed(() => {
if (props.item.type !== 'movies') return {};
const movie = props.item.data as Movie;
const imagePath = movie.backdrop_path;
const imageUrl = getCoverUrl(imagePath);
const imageUrl = getCoverUrl(imagePath, props.item.root_id);
if (imageUrl) {
return { backgroundImage: `url("${imageUrl}")` };
}
@@ -368,7 +368,7 @@ const backdropStyle = computed(() => {
const synopsisPosterUrl = computed(() => {
if (props.item.type !== 'movies') return null;
return getCoverUrl(props.item.cover_path);
return getCoverUrl(props.item.cover_path, props.item.root_id);
});
const movieGenres = computed(() => {
+4 -4
View File
@@ -502,7 +502,7 @@ function handleEpisodeHover(key: string, isEntering: boolean) {
// Backdrop URL - only use backdrop_path, fall back to collage (handled in template)
const backdropUrl = computed(() => {
if (props.series.info?.backdrop_path) {
return getCoverUrl(props.series.info.backdrop_path);
return getCoverUrl(props.series.info.backdrop_path, props.series.root_id);
}
return null;
});
@@ -523,7 +523,7 @@ const ratingClass = computed(() => {
// Get season poster
function getSeasonPoster(season: Season): string | undefined {
if (season.poster_path) {
return getCoverUrl(season.poster_path);
return getCoverUrl(season.poster_path, props.series.root_id);
}
return undefined;
}
@@ -536,14 +536,14 @@ function getEpisodeVideoSources(episode: Episode): Array<{ src: string; type: st
: [];
return sources.map((path) => ({
src: getVideoPreviewUrl(getCoverUrl(path)),
src: getVideoPreviewUrl(getCoverUrl(path, props.series.root_id)),
...getVideoSourceAttributes(path),
}));
}
// Collage slice style for season posters
function getCollageSliceStyle(season: Season, index: number) {
const posterUrl = season.poster_path ? getCoverUrl(season.poster_path) : null;
const posterUrl = season.poster_path ? getCoverUrl(season.poster_path, props.series.root_id) : null;
const totalSlices = Math.min(seasonsWithPosters.value.length, 5);
const sliceWidth = 100 / totalSlices;
+166 -93
View File
@@ -1,17 +1,24 @@
import { ref, readonly, onUnmounted } from 'vue';
import type { Movie, Series, MediaIndex, TaskInfo, WsMessage } from '../types';
interface RootState {
rootId: string;
ws: WebSocket | null;
movieMap: Map<string, Movie>;
seriesMap: Map<string, Series>;
connected: boolean;
reconnectTimer: ReturnType<typeof setTimeout> | null;
}
/**
* Composable that connects to the MediaHive WebSocket and keeps
* the media index updated in real time.
* Composable that connects to per-root MediaHive WebSockets and keeps
* a merged media index updated in real time.
*
* The server sends:
* The server sends per-root:
* - "init" → full index (movies + series) on connect
* - "upsert" → single item inserted or updated
* - "remove" → single item removed
* - "task" → background task progress
*
* Messages are msgspec-encoded binary JSON with a "type" tag field.
*/
export function useMediaWebSocket() {
const mediaIndex = ref<MediaIndex | null>(null);
@@ -20,17 +27,16 @@ export function useMediaWebSocket() {
const connected = ref(false);
const tasks = ref<Map<string, TaskInfo>>(new Map());
let ws: WebSocket | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
const roots = ref<Map<string, RootState>>(new Map());
let disposed = false;
// Lookup maps for fast upsert / remove
const movieMap = new Map<string, Movie>();
const seriesMap = new Map<string, Series>();
function buildIndex(): MediaIndex {
const movies = Array.from(movieMap.values());
const series = Array.from(seriesMap.values());
const movies: Movie[] = [];
const series: Series[] = [];
for (const state of roots.value.values()) {
movies.push(...state.movieMap.values());
series.push(...state.seriesMap.values());
}
return {
version: 0,
generated_at: new Date().toISOString(),
@@ -43,63 +49,57 @@ export function useMediaWebSocket() {
};
}
function handleMessage(event: MessageEvent) {
try {
// Server sends binary frames (msgspec json bytes)
let text: string;
if (event.data instanceof Blob) {
// Will be handled by the blob reader below
event.data.text().then((t) => processJson(t));
return;
} else if (event.data instanceof ArrayBuffer) {
text = new TextDecoder().decode(event.data);
} else {
text = event.data as string;
function updateMergedState() {
mediaIndex.value = buildIndex();
// Loading is done when at least one root has connected and sent init
let anyConnected = false;
for (const state of roots.value.values()) {
if (state.connected) {
anyConnected = true;
break;
}
processJson(text);
} catch (e) {
console.error('[WS] Failed to handle message:', e);
}
if (anyConnected) {
loading.value = false;
error.value = null;
}
connected.value = anyConnected;
}
function processJson(text: string) {
function processJson(state: RootState, text: string) {
const msg = JSON.parse(text) as WsMessage;
switch (msg.type) {
case 'init': {
movieMap.clear();
seriesMap.clear();
for (const m of msg.data.movies) movieMap.set(m.id, m);
for (const s of msg.data.series) seriesMap.set(s.id, s);
mediaIndex.value = buildIndex();
loading.value = false;
error.value = null;
console.log(`[WS] init: ${movieMap.size} movies, ${seriesMap.size} series`);
state.movieMap.clear();
state.seriesMap.clear();
for (const m of msg.data.movies) state.movieMap.set(m.id, m);
for (const s of msg.data.series) state.seriesMap.set(s.id, s);
updateMergedState();
console.log(`[WS ${state.rootId}] init: ${state.movieMap.size} movies, ${state.seriesMap.size} series`);
break;
}
case 'upsert': {
if (msg.kind === 'movie') {
movieMap.set(msg.item.id, msg.item as Movie);
state.movieMap.set(msg.item.id, msg.item as Movie);
} else {
seriesMap.set(msg.item.id, msg.item as Series);
state.seriesMap.set(msg.item.id, msg.item as Series);
}
// Rebuild the index ref so Vue detects the change
mediaIndex.value = buildIndex();
updateMergedState();
break;
}
case 'remove': {
if (msg.kind === 'movie') {
movieMap.delete(msg.id);
state.movieMap.delete(msg.id);
} else {
seriesMap.delete(msg.id);
state.seriesMap.delete(msg.id);
}
mediaIndex.value = buildIndex();
updateMergedState();
break;
}
case 'task': {
const info = msg.data;
if (info.status === 'completed' || info.status === 'cancelled' || info.status === 'error') {
// Keep finished tasks briefly so the UI can show completion
tasks.value.set(info.id, info);
setTimeout(() => {
tasks.value.delete(info.id);
@@ -108,71 +108,143 @@ export function useMediaWebSocket() {
} else {
tasks.value.set(info.id, info);
}
// Trigger reactivity
tasks.value = new Map(tasks.value);
break;
}
}
}
function connect() {
if (disposed) return;
// Build WS URL relative to current page
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = `${proto}//${location.host}/api/ws`;
console.log(`[WS] Connecting to ${url}...`);
ws = new WebSocket(url);
ws.onopen = () => {
connected.value = true;
error.value = null;
console.log('[WS] Connected');
};
ws.onmessage = handleMessage;
ws.onclose = (ev) => {
connected.value = false;
console.log(`[WS] Closed (code=${ev.code})`);
scheduleReconnect();
};
ws.onerror = (ev) => {
console.error('[WS] Error:', ev);
if (!mediaIndex.value) {
error.value = 'WebSocket connection failed';
function handleMessage(state: RootState, event: MessageEvent) {
try {
let text: string;
if (event.data instanceof Blob) {
event.data.text().then((t) => processJson(state, t));
return;
} else if (event.data instanceof ArrayBuffer) {
text = new TextDecoder().decode(event.data);
} else {
text = event.data as string;
}
};
processJson(state, text);
} catch (e) {
console.error(`[WS ${state.rootId}] Failed to handle message:`, e);
}
}
function scheduleReconnect() {
function connectRoot(rootId: string) {
if (disposed) return;
if (reconnectTimer) clearTimeout(reconnectTimer);
reconnectTimer = setTimeout(() => {
console.log('[WS] Reconnecting...');
connect();
}, 2000);
const existing = roots.value.get(rootId);
if (existing?.ws) {
// Already connecting or connected
return;
}
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = `${proto}//${location.host}/api/roots/${encodeURIComponent(rootId)}/ws`;
const state: RootState = {
rootId,
ws: null,
movieMap: new Map(),
seriesMap: new Map(),
connected: false,
reconnectTimer: null,
};
roots.value.set(rootId, state);
function doConnect() {
if (disposed) return;
console.log(`[WS ${rootId}] Connecting to ${url}...`);
const ws = new WebSocket(url);
state.ws = ws;
ws.onopen = () => {
state.connected = true;
updateMergedState();
console.log(`[WS ${rootId}] Connected`);
};
ws.onmessage = (ev) => handleMessage(state, ev);
ws.onclose = (ev) => {
state.connected = false;
state.ws = null;
updateMergedState();
console.log(`[WS ${rootId}] Closed (code=${ev.code})`);
scheduleReconnect();
};
ws.onerror = (ev) => {
console.error(`[WS ${rootId}] Error:`, ev);
if (!mediaIndex.value) {
error.value = 'WebSocket connection failed';
}
};
}
function scheduleReconnect() {
if (disposed) return;
if (state.reconnectTimer) clearTimeout(state.reconnectTimer);
state.reconnectTimer = setTimeout(() => {
console.log(`[WS ${rootId}] Reconnecting...`);
doConnect();
}, 2000);
}
doConnect();
}
function disconnectRoot(rootId: string) {
const state = roots.value.get(rootId);
if (!state) return;
if (state.reconnectTimer) {
clearTimeout(state.reconnectTimer);
state.reconnectTimer = null;
}
if (state.ws) {
state.ws.onclose = null;
state.ws.close();
state.ws = null;
}
state.connected = false;
roots.value.delete(rootId);
updateMergedState();
}
function setActiveRoots(rootIds: string[]) {
if (disposed) return;
const desired = new Set(rootIds);
const current = new Set(roots.value.keys());
// Add new roots
for (const rid of desired) {
if (!current.has(rid)) {
connectRoot(rid);
}
}
// Remove old roots
for (const rid of current) {
if (!desired.has(rid)) {
disconnectRoot(rid);
}
}
}
function disconnect() {
disposed = true;
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
if (ws) {
ws.onclose = null; // prevent reconnect
ws.close();
ws = null;
for (const state of roots.value.values()) {
if (state.reconnectTimer) {
clearTimeout(state.reconnectTimer);
}
if (state.ws) {
state.ws.onclose = null;
state.ws.close();
}
}
roots.value.clear();
}
// Start the connection
connect();
// Clean up on component unmount
onUnmounted(disconnect);
return {
@@ -181,6 +253,7 @@ export function useMediaWebSocket() {
error: readonly(error),
connected: readonly(connected),
tasks: readonly(tasks),
setActiveRoots,
disconnect,
};
}
+3
View File
@@ -69,6 +69,7 @@ export interface Movie {
showreel_images: string[] | null;
showreel_source_sets: string[][] | null;
torrents: { [key: string]: Torrent };
root_id: string | null;
}
export interface Episode {
@@ -104,6 +105,7 @@ export interface Series {
cover_path: string | null;
backdrop_path: string | null;
seasons: Season[];
root_id: string | null;
}
export interface MediaStats {
@@ -156,6 +158,7 @@ export interface MediaItem {
type: MediaType;
resolution?: string | null;
data: Movie | Series | EpisodeWithSeries;
root_id: string | null;
// Optional search match info - only present in search results
searchMatchInfo?: SearchMatchInfo;
}