feat: add cross-device playback and remote control
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped
- native SyncPlay groups with shared queues, ready/buffering and local pause/seek reporting - follow-me prompt that transfers another session's playback to this device - auto-skip intros/recaps and skip-credits for final items - blink:// deep links with timestamped scene sharing via QR - Quick Connect approval and QR onboarding from a phone - Rust WebSocket client with Authorization header for Jellyfin 12, capabilities advertising, live sessions and remote commands
This commit is contained in:
1 parent
cb5ee9b672
commit
5746bf35a5
39 files changed
+3235
-18
No files matched your search
@@ -9,6 +9,7 @@ import React, { useCallback, useState } from "react";
|
||||
import "./appBar.scss";
|
||||
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import { openSyncPlayDialog } from "@/utils/methods/syncPlay";
|
||||
import useHeaderStore from "@/utils/store/header";
|
||||
import useSearchStore from "@/utils/store/search";
|
||||
import BackButton from "../buttons/backButton";
|
||||
@@ -131,6 +132,14 @@ const AppBarContent = () => {
|
||||
data-tauri-drag-region
|
||||
style={{ gap: "0.6em" }}
|
||||
>
|
||||
<Tooltip title="Watch together">
|
||||
<IconButton
|
||||
onClick={openSyncPlayDialog}
|
||||
aria-label="Watch together"
|
||||
>
|
||||
<span className="material-symbols-rounded">groups</span>
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<CastButton />
|
||||
<Tooltip title="Search">
|
||||
<IconButton onClick={toggleSearchDialog} aria-label="Search">
|
||||
|
||||
@@ -18,6 +18,8 @@ import { useNavigate, useRouter } from "@tanstack/react-router";
|
||||
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React, { useCallback, useState } from "react";
|
||||
import QRCodeImage from "@/components/qrCode";
|
||||
import { buildQuickConnectDeepLink } from "@/utils/deepLinks";
|
||||
import useInterval from "@/utils/hooks/useInterval";
|
||||
import { saveUser } from "@/utils/storage/user";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
@@ -244,6 +246,23 @@ const QuickConnectButton = (props: LoadingButtonProps) => {
|
||||
</Typography>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{quickConnectCode && (
|
||||
<>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ mt: 2, opacity: 0.75, textAlign: "center" }}
|
||||
>
|
||||
Or scan this code with Blink on your phone to approve the
|
||||
login.
|
||||
</Typography>
|
||||
<div style={{ marginTop: "1em", background: "#08001f", borderRadius: 12, padding: 8 }}>
|
||||
<QRCodeImage
|
||||
value={buildQuickConnectDeepLink(quickConnectCode)}
|
||||
size={180}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions
|
||||
className="flex flex-row"
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { getCurrent, onOpenUrl } from "@tauri-apps/plugin-deep-link";
|
||||
import React, { useEffect } from "react";
|
||||
import {
|
||||
consumePendingDeepLink,
|
||||
handleDeepLink,
|
||||
} from "@/utils/methods/deepLinks";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
|
||||
const DeepLinkHandler = () => {
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let unlisten: (() => void) | undefined;
|
||||
|
||||
const process = async (urls: string[] | null | undefined) => {
|
||||
for (const url of urls ?? []) {
|
||||
try {
|
||||
await handleDeepLink(url, { api, user, navigate });
|
||||
} catch (error) {
|
||||
console.error("Could not handle deep link", url, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
getCurrent()
|
||||
.then((urls) => {
|
||||
if (!disposed) void process(urls);
|
||||
})
|
||||
.catch((error) => console.warn("Could not read deep links", error));
|
||||
|
||||
onOpenUrl((urls) => {
|
||||
if (!disposed) void process(urls);
|
||||
})
|
||||
.then((stop) => {
|
||||
if (disposed) stop();
|
||||
else unlisten = stop;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("Deep-link listener is unavailable", error);
|
||||
});
|
||||
|
||||
const pending = consumePendingDeepLink();
|
||||
if (pending) void process([pending]);
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
unlisten?.();
|
||||
};
|
||||
}, [api, user?.Id, navigate]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default React.memo(DeepLinkHandler);
|
||||
@@ -0,0 +1,277 @@
|
||||
import {
|
||||
type BaseItemDto,
|
||||
BaseItemKind,
|
||||
type SessionInfoDto,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
IconButton,
|
||||
Paper,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React, { useCallback, useMemo, useState } from "react";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import { transferSessionToLocal } from "@/utils/methods/transferPlayback";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useAudioPlayback } from "@/utils/store/audioPlayback";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { usePlaybackStore } from "@/utils/store/playback";
|
||||
import useRealtimeStore from "@/utils/store/realtime";
|
||||
|
||||
const DISMISS_STORAGE_KEY = "blink:follow-me-dismissed";
|
||||
const DISMISS_TTL_MS = 30 * 60 * 1000;
|
||||
const MIN_POSITION_TICKS = 45 * 10_000_000;
|
||||
|
||||
type DismissedMap = Record<string, number>;
|
||||
|
||||
const readDismissed = (): DismissedMap => {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(DISMISS_STORAGE_KEY);
|
||||
const parsed = raw ? (JSON.parse(raw) as DismissedMap) : {};
|
||||
const now = Date.now();
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed).filter(([, at]) => now - at < DISMISS_TTL_MS),
|
||||
);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (ticks: number) => {
|
||||
const total = Math.max(0, Math.round(ticks / 10_000_000));
|
||||
const hours = Math.floor(total / 3600);
|
||||
const minutes = Math.floor((total % 3600) / 60);
|
||||
const seconds = total % 60;
|
||||
return hours > 0
|
||||
? `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`
|
||||
: `${minutes}:${String(seconds).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const deviceLabel = (session: SessionInfoDto) =>
|
||||
session.DeviceName || session.Client || "another device";
|
||||
|
||||
const posterId = (item: BaseItemDto) =>
|
||||
item.ImageTags?.Primary ? item.Id : (item.SeriesId ?? item.Id);
|
||||
|
||||
/**
|
||||
* A Spotify-Connect style hand-off prompt. When another session of the same
|
||||
* user is already watching something and this client is idle, offer to
|
||||
* continue the same item here at its current position.
|
||||
*/
|
||||
const FollowMe = () => {
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const navigate = useNavigate();
|
||||
const { enqueueSnackbar } = useSnackbar();
|
||||
|
||||
const localVideoActive = usePlaybackStore((state) =>
|
||||
Boolean(state.playbackStream && state.metadata.item?.Id),
|
||||
);
|
||||
const localAudioActive = useAudioPlayback((state) =>
|
||||
Boolean(state.display && state.item?.Id),
|
||||
);
|
||||
const localActive = localVideoActive || localAudioActive;
|
||||
|
||||
const realtimeSessions = useRealtimeStore((state) => state.sessions);
|
||||
const sessionsQuery = useQuery({
|
||||
queryKey: ["remoteSessions"],
|
||||
queryFn: async () => {
|
||||
if (!api || !user?.Id) return [];
|
||||
return (await getSessionApi(api).getSessions()).data;
|
||||
},
|
||||
enabled: Boolean(api && user?.Id) && !localActive,
|
||||
refetchInterval: localActive ? false : 15_000,
|
||||
networkMode: "always",
|
||||
});
|
||||
|
||||
const [dismissed, setDismissed] = useState<DismissedMap>(readDismissed);
|
||||
const [transferring, setTransferring] = useState(false);
|
||||
|
||||
const candidate = useMemo(() => {
|
||||
if (!api || !user?.Id || localActive) return undefined;
|
||||
const sessions =
|
||||
realtimeSessions.length > 0
|
||||
? realtimeSessions
|
||||
: (sessionsQuery.data ?? []);
|
||||
const options = sessions.filter((session) => {
|
||||
const item = session.NowPlayingItem;
|
||||
const lastCheckIn = session.LastPlaybackCheckIn
|
||||
? Date.parse(session.LastPlaybackCheckIn)
|
||||
: 0;
|
||||
const stale =
|
||||
lastCheckIn > 0 && Date.now() - lastCheckIn > 15 * 60 * 1000;
|
||||
return (
|
||||
Boolean(session.Id && item?.Id) &&
|
||||
!stale &&
|
||||
session.DeviceId !== api.deviceInfo.id &&
|
||||
session.UserId === user.Id &&
|
||||
item?.Type !== BaseItemKind.Photo &&
|
||||
(item?.Type === BaseItemKind.Audio ||
|
||||
item?.Type === BaseItemKind.AudioBook ||
|
||||
item?.Type === BaseItemKind.Episode ||
|
||||
item?.Type === BaseItemKind.Movie ||
|
||||
item?.Type === BaseItemKind.Video ||
|
||||
Boolean(item?.MediaType === "Video")) &&
|
||||
(session.PlayState?.PositionTicks ?? 0) >= MIN_POSITION_TICKS
|
||||
);
|
||||
});
|
||||
if (options.length === 0) return undefined;
|
||||
options.sort((a, b) => {
|
||||
const aAt = a.LastPlaybackCheckIn ? Date.parse(a.LastPlaybackCheckIn) : 0;
|
||||
const bAt = b.LastPlaybackCheckIn ? Date.parse(b.LastPlaybackCheckIn) : 0;
|
||||
if (aAt !== bAt) return bAt - aAt;
|
||||
return (
|
||||
(b.PlayState?.PositionTicks ?? 0) - (a.PlayState?.PositionTicks ?? 0)
|
||||
);
|
||||
});
|
||||
const session = options[0];
|
||||
const item = session.NowPlayingItem;
|
||||
if (!session.Id || !item?.Id) return undefined;
|
||||
const position = session.PlayState?.PositionTicks ?? 0;
|
||||
const key = `${session.Id}:${item.Id}`;
|
||||
if (dismissed[key]) return undefined;
|
||||
return { session, item, position, key };
|
||||
}, [
|
||||
api,
|
||||
user?.Id,
|
||||
localActive,
|
||||
realtimeSessions,
|
||||
sessionsQuery.data,
|
||||
dismissed,
|
||||
]);
|
||||
|
||||
const dismiss = useCallback((key: string) => {
|
||||
setDismissed((current) => {
|
||||
const next = { ...current, [key]: Date.now() };
|
||||
sessionStorage.setItem(DISMISS_STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleContinue = useCallback(async () => {
|
||||
if (!api || !user?.Id || !candidate) return;
|
||||
setTransferring(true);
|
||||
try {
|
||||
const kind = await transferSessionToLocal(
|
||||
api,
|
||||
user.Id,
|
||||
candidate.session,
|
||||
);
|
||||
dismiss(candidate.key);
|
||||
if (kind === "video") navigate({ to: "/player" });
|
||||
if (kind === "audio") navigate({ to: "/player/audio" });
|
||||
if (kind !== "none") {
|
||||
enqueueSnackbar(`Continuing from ${deviceLabel(candidate.session)}`, {
|
||||
variant: "success",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Follow-me transfer failed", error);
|
||||
enqueueSnackbar("Could not continue playback here", {
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
setTransferring(false);
|
||||
}
|
||||
}, [api, user?.Id, candidate, dismiss, enqueueSnackbar, navigate]);
|
||||
|
||||
if (!candidate || !api) return null;
|
||||
const { item, session, position } = candidate;
|
||||
const paused = Boolean(session.PlayState?.IsPaused);
|
||||
const imageUrl = getImageUrlsApi(api).getItemImageUrlById(
|
||||
posterId(item) ?? item.Id ?? "",
|
||||
"Primary",
|
||||
{ fillHeight: 168, fillWidth: 112, quality: 85 },
|
||||
);
|
||||
|
||||
return (
|
||||
<Paper
|
||||
elevation={10}
|
||||
sx={{
|
||||
position: "fixed",
|
||||
left: 24,
|
||||
bottom: 24,
|
||||
zIndex: 1300,
|
||||
display: "flex",
|
||||
gap: 1.5,
|
||||
alignItems: "stretch",
|
||||
width: "min(360px, calc(100vw - 48px))",
|
||||
p: 1.25,
|
||||
borderRadius: "18px",
|
||||
background: "rgba(18, 16, 38, 0.94)",
|
||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
||||
backdropFilter: "blur(24px)",
|
||||
boxShadow: "0 16px 48px rgba(0, 0, 0, 0.45)",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
component="img"
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
sx={{
|
||||
width: 56,
|
||||
height: 84,
|
||||
flex: "0 0 auto",
|
||||
objectFit: "cover",
|
||||
borderRadius: "10px",
|
||||
background: "rgba(255,255,255,0.06)",
|
||||
}}
|
||||
/>
|
||||
<Box
|
||||
sx={{ minWidth: 0, flex: 1, display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<Typography
|
||||
variant="overline"
|
||||
sx={{ lineHeight: 1.2, opacity: 0.65, letterSpacing: 0.8 }}
|
||||
>
|
||||
{paused ? "Paused on" : "Playing on"} {deviceLabel(session)}
|
||||
</Typography>
|
||||
<Typography variant="subtitle2" noWrap sx={{ fontWeight: 700 }}>
|
||||
{item.SeriesName ?? item.Name ?? "Continue watching"}
|
||||
</Typography>
|
||||
<Typography variant="caption" noWrap sx={{ opacity: 0.65 }}>
|
||||
{item.SeriesName && item.Name ? `${item.Name} · ` : ""}
|
||||
{formatTime(position)}
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", gap: 0.5, mt: "auto", pt: 0.5 }}>
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
onClick={handleContinue}
|
||||
disabled={transferring}
|
||||
sx={{ textTransform: "none", borderRadius: "999px" }}
|
||||
>
|
||||
{transferring ? "Starting…" : "Continue here"}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => dismiss(candidate.key)}
|
||||
sx={{ textTransform: "none", borderRadius: "999px", opacity: 0.7 }}
|
||||
>
|
||||
Not now
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
<Tooltip title="Dismiss">
|
||||
<IconButton
|
||||
size="small"
|
||||
aria-label="Dismiss continue prompt"
|
||||
onClick={() => dismiss(candidate.key)}
|
||||
sx={{ alignSelf: "flex-start", opacity: 0.55 }}
|
||||
>
|
||||
<span className="material-symbols-rounded" style={{ fontSize: 18 }}>
|
||||
close
|
||||
</span>
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Paper>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(FollowMe);
|
||||
@@ -3,6 +3,7 @@ import { AnimatePresence, motion } from "motion/react";
|
||||
import React from "react";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import { usePlaybackStore } from "@/utils/store/playback";
|
||||
import useQueue from "@/utils/store/queue";
|
||||
|
||||
const SkipSegmentButton = () => {
|
||||
const {
|
||||
@@ -25,11 +26,16 @@ const SkipSegmentButton = () => {
|
||||
})),
|
||||
);
|
||||
|
||||
const hasNextItem = useQueue((state) =>
|
||||
Boolean(state.tracks?.[state.currentItemIndex + 1]),
|
||||
);
|
||||
const segmentType = mediaSegments?.Items?.[currentSegmentIndex]?.Type;
|
||||
const shouldShow =
|
||||
mediaSegments?.Items?.length &&
|
||||
currentSegmentIndex >= 0 &&
|
||||
activeSegmentId &&
|
||||
mediaSegments?.Items?.[currentSegmentIndex].Type !== "Outro";
|
||||
(segmentType !== "Outro" || !hasNextItem);
|
||||
const label = segmentType === "Outro" ? "Skip credits" : `Skip ${segmentType}`;
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
@@ -81,7 +87,7 @@ const SkipSegmentButton = () => {
|
||||
},
|
||||
}}
|
||||
>
|
||||
Skip {mediaSegments?.Items?.[currentSegmentIndex].Type}
|
||||
{label}
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
@@ -15,8 +15,11 @@ import PlayNextButton from "@/components/buttons/playNextButton";
|
||||
import PlayPreviousButton from "@/components/buttons/playPreviousButtom";
|
||||
import QueueButton from "@/components/buttons/queueButton";
|
||||
import BubbleSlider from "@/components/playback/videoPlayer/bubbleSlider";
|
||||
import { secToTicks } from "@/utils/date/time";
|
||||
import { secToTicks, ticksToSec } from "@/utils/date/time";
|
||||
import { buildPlayDeepLink } from "@/utils/deepLinks";
|
||||
import { openSyncPlayDialog } from "@/utils/methods/syncPlay";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useShareStore } from "@/utils/store/share";
|
||||
import { usePlaybackStore } from "@/utils/store/playback";
|
||||
import useSyncPlayback from "@/utils/store/syncPlayback";
|
||||
import CaptionsButton from "./buttons/CaptionsButton";
|
||||
@@ -87,6 +90,7 @@ const VideoPlayerControls = ({
|
||||
decreaseVolumeByStep,
|
||||
getCurrentTime,
|
||||
isUserHovering,
|
||||
currentTime,
|
||||
} = usePlaybackStore(
|
||||
useShallow((state) => ({
|
||||
mediaSourceId: state.mediaSource.id,
|
||||
@@ -110,6 +114,7 @@ const VideoPlayerControls = ({
|
||||
decreaseVolumeByStep: state.decreaseVolumeByStep,
|
||||
getCurrentTime: state.getCurrentTime,
|
||||
isUserHovering: state.playerState.isUserHovering,
|
||||
currentTime: state.playerState.currentTime,
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -232,6 +237,30 @@ const VideoPlayerControls = ({
|
||||
>
|
||||
<span className="material-symbols-rounded">arrow_back</span>
|
||||
</IconButton>
|
||||
<IconButton
|
||||
onClick={() =>
|
||||
useShareStore
|
||||
.getState()
|
||||
.openShareDialog(
|
||||
buildPlayDeepLink(
|
||||
itemId ?? "",
|
||||
currentTime > 0 ? ticksToSec(currentTime) : getCurrentTime(),
|
||||
),
|
||||
"Share this scene",
|
||||
)
|
||||
}
|
||||
aria-label="Share scene"
|
||||
title="Share scene"
|
||||
>
|
||||
<span className="material-symbols-rounded">share</span>
|
||||
</IconButton>
|
||||
<IconButton
|
||||
onClick={openSyncPlayDialog}
|
||||
aria-label="Watch together"
|
||||
title="Watch together"
|
||||
>
|
||||
<span className="material-symbols-rounded">groups</span>
|
||||
</IconButton>
|
||||
<IconButton
|
||||
onClick={(e) => setSettingsMenuRef(e.currentTarget)}
|
||||
aria-label="Player settings"
|
||||
|
||||
@@ -10,10 +10,16 @@ import { toNumber } from "lodash";
|
||||
import React, {
|
||||
type ChangeEventHandler,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useTransition,
|
||||
} from "react";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
getAutoSkipSegments,
|
||||
setAutoSkipSegments,
|
||||
} from "@/utils/storage/player";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import {
|
||||
changeAudioTrack,
|
||||
@@ -67,6 +73,25 @@ const VideoPlayerSettingsMenu = ({
|
||||
if (itemId) startSync({ itemId, sessionId: null });
|
||||
};
|
||||
|
||||
const [autoSkip, setAutoSkip] = useState(false);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
getAutoSkipSegments().then((enabled) => {
|
||||
if (!cancelled) setAutoSkip(enabled);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const toggleAutoSkip = () => {
|
||||
setAutoSkip((enabled) => {
|
||||
const next = !enabled;
|
||||
setAutoSkipSegments(next);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const [subtitleIsChanging, startSubtitleChange] = useTransition();
|
||||
const handleSubtitleChange: ChangeEventHandler<
|
||||
HTMLInputElement | HTMLTextAreaElement
|
||||
@@ -188,6 +213,20 @@ const VideoPlayerSettingsMenu = ({
|
||||
onChange={toggleSync}
|
||||
/>
|
||||
</MenuItem>
|
||||
<MenuItem onClick={toggleAutoSkip}>
|
||||
<Typography
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
}}
|
||||
>
|
||||
Auto-skip intro & recap
|
||||
</Typography>
|
||||
<Switch
|
||||
checked={autoSkip}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onChange={toggleAutoSkip}
|
||||
/>
|
||||
</MenuItem>
|
||||
</MenuList>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { CircularProgress } from "@mui/material";
|
||||
import QRCode from "qrcode";
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
const QRCodeImage = ({
|
||||
value,
|
||||
size = 220,
|
||||
}: {
|
||||
value: string;
|
||||
size?: number;
|
||||
}) => {
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setSrc(null);
|
||||
QRCode.toDataURL(value, {
|
||||
errorCorrectionLevel: "M",
|
||||
margin: 1,
|
||||
width: size,
|
||||
color: { dark: "#ffffffff", light: "#00000000" },
|
||||
})
|
||||
.then((url) => {
|
||||
if (!cancelled) setSrc(url);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Could not create QR code", error);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [value, size]);
|
||||
|
||||
if (!src) return <CircularProgress size={24} />;
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt="QR code"
|
||||
width={size}
|
||||
height={size}
|
||||
style={{ display: "block", borderRadius: 12 }}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(QRCodeImage);
|
||||
@@ -0,0 +1,133 @@
|
||||
import { getAuthenticationApi } from "@jellyfin/sdk/lib/utils/api/authentication-api";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import useQuickConnectApprovalStore from "@/utils/store/quickConnectApproval";
|
||||
|
||||
const QuickConnectApprovalDialog = () => {
|
||||
const open = useQuickConnectApprovalStore((state) => state.open);
|
||||
const storeCode = useQuickConnectApprovalStore((state) => state.code);
|
||||
const setStoreCode = useQuickConnectApprovalStore((state) => state.setCode);
|
||||
const close = useQuickConnectApprovalStore(
|
||||
(state) => state.closeQuickConnectApproval,
|
||||
);
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const { enqueueSnackbar } = useSnackbar();
|
||||
const [code, setCode] = useState(storeCode);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [approved, setApproved] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setCode(storeCode);
|
||||
setError(null);
|
||||
setApproved(false);
|
||||
}
|
||||
}, [open, storeCode]);
|
||||
|
||||
const approve = async () => {
|
||||
if (!api || !user?.Id) {
|
||||
setError("Sign in before approving another device");
|
||||
return;
|
||||
}
|
||||
const trimmed = code.trim().toUpperCase();
|
||||
if (!trimmed) {
|
||||
setError("Enter the code shown on the other device");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await getAuthenticationApi(api).authorizeQuickConnect({
|
||||
code: trimmed,
|
||||
userId: user.Id,
|
||||
});
|
||||
if (result.data) {
|
||||
setApproved(true);
|
||||
setStoreCode("");
|
||||
enqueueSnackbar("Device approved", { variant: "success" });
|
||||
setTimeout(close, 1200);
|
||||
} else {
|
||||
setError("This code is invalid or has expired");
|
||||
}
|
||||
} catch (reason) {
|
||||
console.error("Quick Connect approval failed", reason);
|
||||
setError("This code is invalid or has expired");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
maxWidth="xs"
|
||||
fullWidth
|
||||
slotProps={{
|
||||
paper: { className: "glass", sx: { borderRadius: "22px" } },
|
||||
}}
|
||||
>
|
||||
<DialogTitle>Approve TV login</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Enter the Quick Connect code shown on the TV or another device. This
|
||||
signs that device in as {user?.Name ?? "your account"} without
|
||||
typing a password on it.
|
||||
</Typography>
|
||||
<TextField
|
||||
autoFocus
|
||||
fullWidth
|
||||
label="Quick Connect code"
|
||||
value={code}
|
||||
onChange={(event) =>
|
||||
setCode(event.target.value.replace(/\s/g, "").toUpperCase())
|
||||
}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") void approve();
|
||||
}}
|
||||
slotProps={{
|
||||
htmlInput: {
|
||||
maxLength: 8,
|
||||
style: {
|
||||
letterSpacing: "0.25em",
|
||||
fontWeight: 700,
|
||||
textTransform: "uppercase",
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
{approved && <Alert severity="success">Device approved</Alert>}
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={close}>Cancel</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={approve}
|
||||
disabled={busy || approved || !code.trim()}
|
||||
>
|
||||
{busy ? "Approving…" : "Approve"}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(QuickConnectApprovalDialog);
|
||||
@@ -0,0 +1,421 @@
|
||||
import {
|
||||
GeneralCommandType,
|
||||
MediaType,
|
||||
PlayCommand,
|
||||
PlaystateCommand,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
|
||||
import { OutboundWebSocketMessageType } from "@jellyfin/sdk/lib/websocket";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import TauriWebSocket from "@tauri-apps/plugin-websocket";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import {
|
||||
getLocalPlayback,
|
||||
pauseLocalPlayback,
|
||||
resumeLocalPlayback,
|
||||
seekLocalPlayback,
|
||||
setLocalMuted,
|
||||
setLocalVolume,
|
||||
stopLocalPlayback,
|
||||
} from "@/utils/methods/localPlayback";
|
||||
import { startPlaybackFromIds } from "@/utils/methods/startPlayback";
|
||||
import {
|
||||
handleSyncPlayCommand,
|
||||
handleSyncPlayGroupUpdate,
|
||||
} from "@/utils/methods/syncPlay";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { playItemFromQueue, usePlaybackStore } from "@/utils/store/playback";
|
||||
import { clearQueue } from "@/utils/store/queue";
|
||||
import useRealtimeStore from "@/utils/store/realtime";
|
||||
|
||||
const SUPPORTED_COMMANDS: GeneralCommandType[] = [
|
||||
GeneralCommandType.VolumeUp,
|
||||
GeneralCommandType.VolumeDown,
|
||||
GeneralCommandType.Mute,
|
||||
GeneralCommandType.Unmute,
|
||||
GeneralCommandType.ToggleMute,
|
||||
GeneralCommandType.SetVolume,
|
||||
GeneralCommandType.ToggleFullscreen,
|
||||
GeneralCommandType.ToggleStats,
|
||||
GeneralCommandType.DisplayMessage,
|
||||
GeneralCommandType.GoHome,
|
||||
GeneralCommandType.GoToSearch,
|
||||
GeneralCommandType.GoToSettings,
|
||||
GeneralCommandType.SendString,
|
||||
GeneralCommandType.SendKey,
|
||||
GeneralCommandType.Back,
|
||||
GeneralCommandType.SetSubtitleStreamIndex,
|
||||
GeneralCommandType.SetAudioStreamIndex,
|
||||
];
|
||||
|
||||
/**
|
||||
* Keeps one WebSocket subscription alive for the session. Apart from live
|
||||
* session lists it makes this client a controllable Jellyfin target and
|
||||
* applies remote playstate/general commands locally.
|
||||
*/
|
||||
const RealtimeBridge = () => {
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const { enqueueSnackbar } = useSnackbar();
|
||||
const invalidationTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api?.accessToken) return;
|
||||
const sessionApi = getSessionApi(api);
|
||||
const userId = user?.Id;
|
||||
|
||||
const invalidate = () => {
|
||||
if (invalidationTimer.current) clearTimeout(invalidationTimer.current);
|
||||
invalidationTimer.current = setTimeout(() => {
|
||||
for (const queryKey of [
|
||||
["item"],
|
||||
["home"],
|
||||
["favorite"],
|
||||
["library"],
|
||||
["search"],
|
||||
["playButton"],
|
||||
]) {
|
||||
queryClient.invalidateQueries({ queryKey });
|
||||
}
|
||||
}, 500);
|
||||
};
|
||||
|
||||
const applyPlaystate = (
|
||||
command?: PlaystateCommand,
|
||||
seekTicks?: number | null,
|
||||
) => {
|
||||
if (!command) return;
|
||||
if (command === PlaystateCommand.Seek) {
|
||||
if (seekTicks != null) seekLocalPlayback(seekTicks);
|
||||
return;
|
||||
}
|
||||
if (command === PlaystateCommand.Pause) {
|
||||
pauseLocalPlayback();
|
||||
return;
|
||||
}
|
||||
if (command === PlaystateCommand.Unpause) {
|
||||
resumeLocalPlayback();
|
||||
return;
|
||||
}
|
||||
if (command === PlaystateCommand.PlayPause) {
|
||||
const local = getLocalPlayback();
|
||||
if (local.paused) resumeLocalPlayback();
|
||||
else pauseLocalPlayback();
|
||||
return;
|
||||
}
|
||||
if (command === PlaystateCommand.Stop) {
|
||||
const local = getLocalPlayback();
|
||||
stopLocalPlayback();
|
||||
if (local.kind === "video") {
|
||||
usePlaybackStore.setState(usePlaybackStore.getInitialState());
|
||||
clearQueue();
|
||||
navigate({ to: "/home" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
command === PlaystateCommand.NextTrack ||
|
||||
command === PlaystateCommand.PreviousTrack
|
||||
) {
|
||||
if (!userId) return;
|
||||
const local = getLocalPlayback();
|
||||
playItemFromQueue(
|
||||
command === PlaystateCommand.NextTrack ? "next" : "previous",
|
||||
userId,
|
||||
api,
|
||||
).then(() => {
|
||||
if (local.kind === "video") navigate({ to: "/player" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
command === PlaystateCommand.Rewind ||
|
||||
command === PlaystateCommand.FastForward
|
||||
) {
|
||||
const local = getLocalPlayback();
|
||||
const delta =
|
||||
(command === PlaystateCommand.Rewind ? -30 : 30) * 10_000_000;
|
||||
seekLocalPlayback(Math.max(0, local.positionTicks + delta));
|
||||
}
|
||||
};
|
||||
|
||||
const applyGeneralCommand = (
|
||||
name?: GeneralCommandType,
|
||||
args?: { [key: string]: string },
|
||||
) => {
|
||||
if (!name) return;
|
||||
const local = getLocalPlayback();
|
||||
const video = usePlaybackStore.getState();
|
||||
const volume = video.playerState.volume;
|
||||
|
||||
switch (name) {
|
||||
case GeneralCommandType.VolumeUp:
|
||||
setLocalVolume(volume + 0.05);
|
||||
break;
|
||||
case GeneralCommandType.VolumeDown:
|
||||
setLocalVolume(volume - 0.05);
|
||||
break;
|
||||
case GeneralCommandType.SetVolume: {
|
||||
const target = Number(args?.Volume);
|
||||
if (Number.isFinite(target)) {
|
||||
setLocalVolume(target > 1 ? target / 100 : target);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GeneralCommandType.Mute:
|
||||
setLocalMuted(true);
|
||||
break;
|
||||
case GeneralCommandType.Unmute:
|
||||
setLocalMuted(false);
|
||||
break;
|
||||
case GeneralCommandType.ToggleMute:
|
||||
setLocalMuted(!video.playerState.isPlayerMuted);
|
||||
break;
|
||||
case GeneralCommandType.ToggleFullscreen:
|
||||
if (local.kind === "video") {
|
||||
try {
|
||||
video.toggleIsPlayerFullscreen();
|
||||
} catch (error) {
|
||||
console.warn("Remote fullscreen failed", error);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case GeneralCommandType.ToggleStats:
|
||||
if (local.kind === "video") {
|
||||
video.toggleShowStatsForNerds();
|
||||
}
|
||||
break;
|
||||
case GeneralCommandType.DisplayMessage:
|
||||
enqueueSnackbar(
|
||||
[args?.Header, args?.Text].filter(Boolean).join(": ") ||
|
||||
"Message from the server",
|
||||
{
|
||||
variant: "info",
|
||||
autoHideDuration: Number(args?.TimeoutMs) || 5000,
|
||||
},
|
||||
);
|
||||
break;
|
||||
case GeneralCommandType.GoHome:
|
||||
navigate({ to: "/home" });
|
||||
break;
|
||||
case GeneralCommandType.GoToSearch:
|
||||
case GeneralCommandType.SendString:
|
||||
navigate({
|
||||
to: "/search",
|
||||
search: { query: args?.String ?? "" },
|
||||
});
|
||||
break;
|
||||
case GeneralCommandType.Back:
|
||||
window.history.back();
|
||||
break;
|
||||
default:
|
||||
console.info("Unhandled remote command", name, args);
|
||||
}
|
||||
};
|
||||
|
||||
const applyPlay = (play?: {
|
||||
ItemIds?: string[] | null;
|
||||
StartIndex?: number | null;
|
||||
StartPositionTicks?: number | null;
|
||||
AudioStreamIndex?: number | null;
|
||||
SubtitleStreamIndex?: number | null;
|
||||
PlayCommand?: PlayCommand;
|
||||
}) => {
|
||||
if (!play?.ItemIds?.length || !userId) return;
|
||||
if (play.PlayCommand && play.PlayCommand !== PlayCommand.PlayNow) {
|
||||
// PlayNext/PlayLast are uncommon from a remote; behave like PlayNow
|
||||
// instead of silently ignoring the user's intent.
|
||||
console.info("Remote play command", play.PlayCommand);
|
||||
}
|
||||
startPlaybackFromIds(api, userId, play.ItemIds, {
|
||||
startIndex: play.StartIndex ?? 0,
|
||||
startPositionTicks: play.StartPositionTicks ?? 0,
|
||||
audioStreamIndex: play.AudioStreamIndex ?? undefined,
|
||||
subtitleStreamIndex: play.SubtitleStreamIndex ?? undefined,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.kind === "video") navigate({ to: "/player" });
|
||||
if (result.kind === "audio") navigate({ to: "/player/audio" });
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Remote play failed", error);
|
||||
enqueueSnackbar("Could not start remote playback", {
|
||||
variant: "error",
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const advertise = () => {
|
||||
sessionApi
|
||||
.postCapabilities({
|
||||
playableMediaTypes: [
|
||||
MediaType.Audio,
|
||||
MediaType.Video,
|
||||
MediaType.Photo,
|
||||
],
|
||||
supportedCommands: SUPPORTED_COMMANDS,
|
||||
supportsMediaControl: true,
|
||||
supportsPersistentIdentifier: true,
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn(
|
||||
"Could not advertise remote-control capabilities",
|
||||
error,
|
||||
);
|
||||
});
|
||||
};
|
||||
advertise();
|
||||
|
||||
// Jellyfin 12 attaches the socket using the Authorization header sent
|
||||
// by the Rust WebSocket client, so keep the token out of the URL.
|
||||
const socketUrl = api.getUri("socket").replace(/^http/, "ws");
|
||||
const handleMessage = (parsed: {
|
||||
MessageType: OutboundWebSocketMessageType;
|
||||
Data?: any;
|
||||
}) => {
|
||||
useRealtimeStore.getState().markMessage();
|
||||
switch (parsed.MessageType) {
|
||||
case OutboundWebSocketMessageType.Sessions:
|
||||
useRealtimeStore.getState().setSessions(parsed.Data ?? []);
|
||||
queryClient.setQueryData(["remoteSessions"], parsed.Data ?? []);
|
||||
break;
|
||||
case OutboundWebSocketMessageType.Playstate:
|
||||
applyPlaystate(parsed.Data?.Command, parsed.Data?.SeekPositionTicks);
|
||||
break;
|
||||
case OutboundWebSocketMessageType.GeneralCommand:
|
||||
applyGeneralCommand(parsed.Data?.Name, parsed.Data?.Arguments);
|
||||
break;
|
||||
case OutboundWebSocketMessageType.Play:
|
||||
applyPlay(parsed.Data);
|
||||
break;
|
||||
case OutboundWebSocketMessageType.UserDataChanged:
|
||||
case OutboundWebSocketMessageType.LibraryChanged:
|
||||
invalidate();
|
||||
break;
|
||||
case OutboundWebSocketMessageType.SyncPlayGroupUpdate:
|
||||
if (parsed.Data) {
|
||||
void handleSyncPlayGroupUpdate(api, userId, parsed.Data);
|
||||
}
|
||||
break;
|
||||
case OutboundWebSocketMessageType.SyncPlayCommand:
|
||||
if (parsed.Data) handleSyncPlayCommand(parsed.Data);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// Jellyfin 12 only attaches a socket to the session when the handshake
|
||||
// carries the Authorization header, which a browser WebSocket cannot set.
|
||||
// The Tauri plugin opens the socket from Rust, so pass the real header.
|
||||
let disposed = false;
|
||||
let socket: TauriWebSocket | null = null;
|
||||
let keepAliveTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let reconnectAttempts = 0;
|
||||
|
||||
const clearKeepAlive = () => {
|
||||
if (keepAliveTimer) {
|
||||
clearInterval(keepAliveTimer);
|
||||
keepAliveTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleReconnect = () => {
|
||||
if (disposed || reconnectTimer) return;
|
||||
useRealtimeStore.getState().setConnected(false);
|
||||
const delay = Math.min(30_000, 1000 * 1.5 ** reconnectAttempts);
|
||||
reconnectAttempts += 1;
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
void connect();
|
||||
}, delay);
|
||||
};
|
||||
|
||||
const connect = async (): Promise<void> => {
|
||||
if (disposed) return;
|
||||
try {
|
||||
const nextSocket = await TauriWebSocket.connect(socketUrl, {
|
||||
headers: { Authorization: api.authorizationHeader },
|
||||
});
|
||||
if (disposed) {
|
||||
await nextSocket.disconnect().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
socket = nextSocket;
|
||||
reconnectAttempts = 0;
|
||||
useRealtimeStore.getState().setConnected(true);
|
||||
advertise();
|
||||
|
||||
nextSocket.addListener((message) => {
|
||||
if (message.type === "Close") {
|
||||
clearKeepAlive();
|
||||
socket = null;
|
||||
scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
if (message.type !== "Text") return;
|
||||
try {
|
||||
const parsed = JSON.parse(message.data) as {
|
||||
MessageType: OutboundWebSocketMessageType;
|
||||
Data?: unknown;
|
||||
};
|
||||
if (
|
||||
parsed.MessageType === OutboundWebSocketMessageType.ForceKeepAlive
|
||||
) {
|
||||
clearKeepAlive();
|
||||
const seconds = Number(parsed.Data) || 60;
|
||||
const sendKeepAlive = () => {
|
||||
socket
|
||||
?.send(JSON.stringify({ MessageType: "KeepAlive" }))
|
||||
.catch(() => undefined);
|
||||
};
|
||||
sendKeepAlive();
|
||||
keepAliveTimer = setInterval(
|
||||
sendKeepAlive,
|
||||
Math.max(1000, (seconds * 1000) / 2),
|
||||
);
|
||||
return;
|
||||
}
|
||||
handleMessage(parsed);
|
||||
} catch (error) {
|
||||
console.warn("Could not parse a WebSocket message", error);
|
||||
}
|
||||
});
|
||||
|
||||
await nextSocket.send(
|
||||
JSON.stringify({
|
||||
MessageType: "SessionsStart",
|
||||
Data: "0,1000",
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn("WebSocket connection failed", error);
|
||||
scheduleReconnect();
|
||||
}
|
||||
};
|
||||
|
||||
void connect();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
clearKeepAlive();
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
socket?.disconnect().catch(() => undefined);
|
||||
socket = null;
|
||||
useRealtimeStore.getState().setConnected(false);
|
||||
if (invalidationTimer.current) {
|
||||
clearTimeout(invalidationTimer.current);
|
||||
invalidationTimer.current = null;
|
||||
}
|
||||
useRealtimeStore.getState().reset();
|
||||
};
|
||||
}, [api, user?.Id, navigate, queryClient, enqueueSnackbar]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default React.memo(RealtimeBridge);
|
||||
@@ -0,0 +1,103 @@
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React from "react";
|
||||
import QRCodeImage from "@/components/qrCode";
|
||||
import { handleDeepLink } from "@/utils/methods/deepLinks";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import useShareStore from "@/utils/store/share";
|
||||
|
||||
const ShareDialog = () => {
|
||||
const open = useShareStore((state) => state.open);
|
||||
const link = useShareStore((state) => state.link);
|
||||
const title = useShareStore((state) => state.title);
|
||||
const close = useShareStore((state) => state.closeShareDialog);
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const navigate = useNavigate();
|
||||
const { enqueueSnackbar } = useSnackbar();
|
||||
|
||||
const copy = async () => {
|
||||
await writeText(link);
|
||||
enqueueSnackbar("Link copied", { variant: "success" });
|
||||
};
|
||||
|
||||
const openHere = async () => {
|
||||
try {
|
||||
await handleDeepLink(link, { api, user, navigate });
|
||||
close();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
enqueueSnackbar("Could not open the link", { variant: "error" });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
maxWidth="xs"
|
||||
fullWidth
|
||||
slotProps={{
|
||||
paper: { className: "glass", sx: { borderRadius: "22px" } },
|
||||
}}
|
||||
>
|
||||
<DialogTitle>{title || "Share"}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ p: 1, background: "#08001f", borderRadius: "14px" }}>
|
||||
<QRCodeImage value={link} />
|
||||
</Box>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{ opacity: 0.7, textAlign: "center" }}
|
||||
>
|
||||
Scan with Blink on a phone or TV, or copy the link to open it on
|
||||
another device.
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
px: 1.5,
|
||||
py: 1,
|
||||
borderRadius: "10px",
|
||||
background: "rgba(255,255,255,0.06)",
|
||||
fontFamily: "var(--font-mono, monospace)",
|
||||
fontSize: "0.78rem",
|
||||
wordBreak: "break-all",
|
||||
userSelect: "all",
|
||||
}}
|
||||
>
|
||||
{link}
|
||||
</Box>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={openHere}>Open here</Button>
|
||||
<Button variant="contained" onClick={copy}>
|
||||
Copy link
|
||||
</Button>
|
||||
<Button onClick={close}>Close</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(ShareDialog);
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import React, { useEffect } from "react";
|
||||
import { getLocalPlayback } from "@/utils/methods/localPlayback";
|
||||
import { reportSyncPlayReady } from "@/utils/methods/syncPlay";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import useSyncPlayStore from "@/utils/store/syncPlay";
|
||||
|
||||
/** Applies navigation requested by a group queue start. */
|
||||
const SyncPlayController = () => {
|
||||
const pendingNavigation = useSyncPlayStore(
|
||||
(state) => state.pendingNavigation,
|
||||
);
|
||||
const setPendingNavigation = useSyncPlayStore(
|
||||
(state) => state.setPendingNavigation,
|
||||
);
|
||||
const group = useSyncPlayStore((state) => state.group);
|
||||
const queue = useSyncPlayStore((state) => state.queue);
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingNavigation) return;
|
||||
setPendingNavigation(null);
|
||||
navigate({
|
||||
to: pendingNavigation === "audio" ? "/player/audio" : "/player",
|
||||
});
|
||||
}, [pendingNavigation, setPendingNavigation, navigate]);
|
||||
|
||||
// While a group is waiting, keep telling the server this player is ready.
|
||||
// Some clients miss the one-shot Ready after a queue update; retrying is
|
||||
// harmless and lets the server release the group as soon as it can.
|
||||
useEffect(() => {
|
||||
if (!api || !user?.Id || !group || group.State !== "Waiting") return;
|
||||
if (!queue?.Playlist?.length) return;
|
||||
const send = () => {
|
||||
const local = getLocalPlayback();
|
||||
reportSyncPlayReady(api, local.positionTicks, !local.paused);
|
||||
};
|
||||
send();
|
||||
const timer = window.setInterval(send, 2000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [api, user?.Id, group?.GroupId, group?.State, queue]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export default React.memo(SyncPlayController);
|
||||
@@ -0,0 +1,354 @@
|
||||
import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api";
|
||||
import { getSyncPlayApi } from "@jellyfin/sdk/lib/utils/api/sync-play-api";
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Chip,
|
||||
CircularProgress,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Divider,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemText,
|
||||
Stack,
|
||||
TextField,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import {
|
||||
closeSyncPlayDialog,
|
||||
createSyncPlayGroup,
|
||||
joinSyncPlayGroup,
|
||||
leaveSyncPlayGroup,
|
||||
pauseSyncPlayGroup,
|
||||
refreshSyncPlayGroups,
|
||||
resumeSyncPlayGroup,
|
||||
startSyncPlayQueue,
|
||||
watchSyncPlayQueueHere,
|
||||
} from "@/utils/methods/syncPlay";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import useQueue from "@/utils/store/queue";
|
||||
import useSyncPlayStore from "@/utils/store/syncPlay";
|
||||
|
||||
const stateLabel = (state?: string) => {
|
||||
switch (state) {
|
||||
case "Waiting":
|
||||
return "Waiting for everyone";
|
||||
case "Paused":
|
||||
return "Paused";
|
||||
case "Playing":
|
||||
return "Playing";
|
||||
default:
|
||||
return "Idle";
|
||||
}
|
||||
};
|
||||
|
||||
const SyncPlayDialog = () => {
|
||||
const api = useApiInContext((state) => state.api);
|
||||
const user = useCentralStore((state) => state.currentUser);
|
||||
const open = useSyncPlayStore((state) => state.open);
|
||||
const group = useSyncPlayStore((state) => state.group);
|
||||
const groups = useSyncPlayStore((state) => state.groups);
|
||||
const queue = useSyncPlayStore((state) => state.queue);
|
||||
const loading = useSyncPlayStore((state) => state.loading);
|
||||
const error = useSyncPlayStore((state) => state.error);
|
||||
const localQueue = useQueue((state) => state.tracks ?? []);
|
||||
const [groupName, setGroupName] = useState("");
|
||||
const setGroups = useSyncPlayStore((state) => state.setGroups);
|
||||
const setGroup = useSyncPlayStore((state) => state.setGroup);
|
||||
|
||||
const groupsQuery = useQuery({
|
||||
queryKey: ["syncPlayGroups", open],
|
||||
queryFn: async () => {
|
||||
if (!api) return [];
|
||||
return (await getSyncPlayApi(api).syncPlayGetGroups()).data ?? [];
|
||||
},
|
||||
enabled: open && Boolean(api),
|
||||
refetchInterval: open && !group ? 3000 : false,
|
||||
networkMode: "always",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (groupsQuery.data) setGroups(groupsQuery.data);
|
||||
}, [groupsQuery.data, setGroups]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && api) void refreshSyncPlayGroups(api);
|
||||
}, [open, api]);
|
||||
|
||||
const groupQuery = useQuery({
|
||||
queryKey: ["syncPlayGroup", group?.GroupId],
|
||||
queryFn: async () => {
|
||||
if (!api || !group?.GroupId) return undefined;
|
||||
return (await getSyncPlayApi(api).syncPlayGetGroup({ id: group.GroupId }))
|
||||
.data;
|
||||
},
|
||||
enabled: open && Boolean(api && group?.GroupId),
|
||||
refetchInterval: open && group ? 3000 : false,
|
||||
networkMode: "always",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (groupQuery.data) setGroup(groupQuery.data);
|
||||
}, [groupQuery.data, setGroup]);
|
||||
|
||||
const queueItemIds = useMemo(
|
||||
() =>
|
||||
(queue?.Playlist ?? [])
|
||||
.map((item) => item.ItemId)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
[queue],
|
||||
);
|
||||
const currentQueueIndex = Math.min(
|
||||
Math.max(0, queue?.PlayingItemIndex ?? 0),
|
||||
Math.max(0, queueItemIds.length - 1),
|
||||
);
|
||||
const currentItemId = queueItemIds[currentQueueIndex];
|
||||
const currentItem = useQuery({
|
||||
queryKey: ["syncPlayItem", currentItemId],
|
||||
queryFn: async () => {
|
||||
if (!api || !currentItemId) return undefined;
|
||||
return (await getLibraryApi(api).getItem({ itemId: currentItemId })).data;
|
||||
},
|
||||
enabled: open && Boolean(api && currentItemId),
|
||||
networkMode: "always",
|
||||
});
|
||||
const imageUrl =
|
||||
api && currentItem.data?.Id && currentItem.data.ImageTags?.Primary
|
||||
? getImageUrlsApi(api).getItemImageUrlById(
|
||||
currentItem.data.Id,
|
||||
"Primary",
|
||||
{ fillWidth: 96, fillHeight: 144, quality: 85 },
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!api) return;
|
||||
const created = await createSyncPlayGroup(api, groupName);
|
||||
if (created) setGroupName("");
|
||||
};
|
||||
|
||||
const handleClose = () => closeSyncPlayDialog();
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
fullWidth
|
||||
maxWidth="sm"
|
||||
slotProps={{
|
||||
paper: { className: "glass", sx: { borderRadius: "22px" } },
|
||||
}}
|
||||
>
|
||||
<DialogTitle sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<span className="material-symbols-rounded">groups</span>
|
||||
Watch together
|
||||
</DialogTitle>
|
||||
<DialogContent>
|
||||
{error && (
|
||||
<Alert severity="warning" sx={{ mb: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
{group ? (
|
||||
<Stack spacing={2}>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<Typography variant="h6" sx={{ flex: 1 }} noWrap>
|
||||
{group.GroupName || "SyncPlay group"}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={stateLabel(group.State)}
|
||||
color={group.State === "Playing" ? "success" : "default"}
|
||||
variant={group.State === "Playing" ? "filled" : "outlined"}
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" sx={{ opacity: 0.65 }}>
|
||||
{group.Participants?.length
|
||||
? `${group.Participants.length} device${
|
||||
group.Participants.length === 1 ? "" : "s"
|
||||
} connected: ${group.Participants.join(", ")}`
|
||||
: "This is the first device in the group."}
|
||||
</Typography>
|
||||
<Divider />
|
||||
<Box sx={{ display: "flex", gap: 2, alignItems: "center" }}>
|
||||
{imageUrl ? (
|
||||
<Box
|
||||
component="img"
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
sx={{
|
||||
width: 64,
|
||||
height: 96,
|
||||
objectFit: "cover",
|
||||
borderRadius: "10px",
|
||||
flex: "0 0 auto",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Box
|
||||
sx={{
|
||||
width: 64,
|
||||
height: 96,
|
||||
borderRadius: "10px",
|
||||
background: "rgba(255,255,255,0.07)",
|
||||
display: "grid",
|
||||
placeItems: "center",
|
||||
flex: "0 0 auto",
|
||||
}}
|
||||
>
|
||||
<span className="material-symbols-rounded">movie</span>
|
||||
</Box>
|
||||
)}
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Typography variant="overline" sx={{ opacity: 0.6 }}>
|
||||
Group queue
|
||||
</Typography>
|
||||
<Typography variant="subtitle1" noWrap>
|
||||
{currentItem.data?.Name ??
|
||||
(queueItemIds.length
|
||||
? "Loading item…"
|
||||
: "Nothing queued yet")}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65 }}>
|
||||
{queueItemIds.length
|
||||
? `${queueItemIds.length} item${
|
||||
queueItemIds.length === 1 ? "" : "s"
|
||||
} · item ${currentQueueIndex + 1}`
|
||||
: "Start a queue on the device that should lead."}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<Divider />
|
||||
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={loading || localQueue.length === 0 || !user?.Id}
|
||||
onClick={() => api && startSyncPlayQueue(api)}
|
||||
>
|
||||
{queueItemIds.length
|
||||
? "Replace with my queue"
|
||||
: "Share my queue"}
|
||||
</Button>
|
||||
{queueItemIds.length > 0 && user?.Id && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
if (api && user?.Id) {
|
||||
void watchSyncPlayQueueHere(api, user.Id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Watch here
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outlined"
|
||||
disabled={loading}
|
||||
onClick={() =>
|
||||
api &&
|
||||
(group.State === "Playing"
|
||||
? pauseSyncPlayGroup(api)
|
||||
: resumeSyncPlayGroup(api))
|
||||
}
|
||||
>
|
||||
{group.State === "Playing" ? "Pause everyone" : "Play everyone"}
|
||||
</Button>
|
||||
<Button
|
||||
color="error"
|
||||
disabled={loading}
|
||||
onClick={() => api && leaveSyncPlayGroup(api)}
|
||||
>
|
||||
Leave group
|
||||
</Button>
|
||||
</Box>
|
||||
{loading && <CircularProgress size={20} />}
|
||||
</Stack>
|
||||
) : (
|
||||
<Stack spacing={2}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.75 }}>
|
||||
Create a group and start the current queue, or join a group
|
||||
created on another device. Every device that joins follows the
|
||||
same timeline.
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={1}>
|
||||
<TextField
|
||||
size="small"
|
||||
fullWidth
|
||||
label="Group name"
|
||||
placeholder="Movie night"
|
||||
value={groupName}
|
||||
onChange={(event) => setGroupName(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") void handleCreate();
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={loading || !api}
|
||||
onClick={handleCreate}
|
||||
sx={{ flex: "0 0 auto" }}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
</Stack>
|
||||
<Divider />
|
||||
<Typography variant="overline" sx={{ opacity: 0.65 }}>
|
||||
Available groups
|
||||
</Typography>
|
||||
{groupsQuery.isPending ? (
|
||||
<CircularProgress size={20} />
|
||||
) : groups.length === 0 ? (
|
||||
<Typography variant="body2" sx={{ opacity: 0.6 }}>
|
||||
No groups yet. Create one above.
|
||||
</Typography>
|
||||
) : (
|
||||
<List dense disablePadding>
|
||||
{groups.map((entry) => (
|
||||
<ListItem
|
||||
key={entry.GroupId}
|
||||
divider
|
||||
secondaryAction={
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
if (api && entry.GroupId) {
|
||||
void joinSyncPlayGroup(api, entry.GroupId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Join
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<ListItemText
|
||||
primary={entry.GroupName || "Watch together"}
|
||||
secondary={`${stateLabel(entry.State)} · ${
|
||||
entry.Participants?.length ?? 0
|
||||
} device${(entry.Participants?.length ?? 0) === 1 ? "" : "s"}`}
|
||||
/>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleClose}>Close</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(SyncPlayDialog);
|
||||
@@ -17,6 +17,7 @@ import React, {
|
||||
import { delUser } from "@/utils/storage/user";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { useQuickConnectApprovalStore } from "@/utils/store/quickConnectApproval";
|
||||
|
||||
export const UserAvatarMenu = () => {
|
||||
const api = useApiInContext((s) => s.api);
|
||||
@@ -106,6 +107,19 @@ export const UserAvatarMenu = () => {
|
||||
Logout
|
||||
</MenuItem>
|
||||
<Divider />
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
useQuickConnectApprovalStore
|
||||
.getState()
|
||||
.openQuickConnectApproval();
|
||||
handleMenuClose();
|
||||
}}
|
||||
>
|
||||
<ListItemIcon>
|
||||
<span className="material-symbols-rounded">qr_code_2</span>
|
||||
</ListItemIcon>
|
||||
Approve device login
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
onClick={() => {
|
||||
navigate({ to: "/settings/preferences" });
|
||||
|
||||
Reference in new issue
Block a user