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
@@ -0,0 +1,68 @@
|
||||
import type { Api } from "@jellyfin/sdk";
|
||||
import type { UserDto } from "@jellyfin/sdk/lib/generated-client";
|
||||
import type { useNavigate } from "@tanstack/react-router";
|
||||
import { parseDeepLink } from "@/utils/deepLinks";
|
||||
import { startPlaybackFromIds } from "@/utils/methods/startPlayback";
|
||||
import { useQuickConnectApprovalStore } from "@/utils/store/quickConnectApproval";
|
||||
|
||||
const PENDING_LINK_KEY = "blink:pending-deep-link";
|
||||
|
||||
type Navigate = ReturnType<typeof useNavigate>;
|
||||
|
||||
export const handleDeepLink = async (
|
||||
url: string,
|
||||
options: {
|
||||
api: Api | undefined;
|
||||
user: UserDto | null | undefined;
|
||||
navigate: Navigate;
|
||||
},
|
||||
): Promise<"video" | "audio" | "quickconnect" | "item" | "search" | "none"> => {
|
||||
const parsed = parseDeepLink(url);
|
||||
if (parsed.kind === "quickconnect") {
|
||||
useQuickConnectApprovalStore
|
||||
.getState()
|
||||
.openQuickConnectApproval(parsed.code);
|
||||
return "quickconnect";
|
||||
}
|
||||
|
||||
if (!options.api || !options.user?.Id) {
|
||||
sessionStorage.setItem(PENDING_LINK_KEY, url);
|
||||
return "none";
|
||||
}
|
||||
|
||||
if (parsed.kind === "play") {
|
||||
const result = await startPlaybackFromIds(
|
||||
options.api,
|
||||
options.user.Id,
|
||||
[parsed.itemId],
|
||||
{ startPositionTicks: Math.round(parsed.seconds * 10_000_000) },
|
||||
);
|
||||
if (result.kind === "video") options.navigate({ to: "/player" });
|
||||
if (result.kind === "audio") options.navigate({ to: "/player/audio" });
|
||||
return result.kind === "none" ? "none" : result.kind;
|
||||
}
|
||||
|
||||
if (parsed.kind === "item") {
|
||||
options.navigate({
|
||||
to: "/item/$id",
|
||||
params: { id: parsed.itemId },
|
||||
});
|
||||
return "item";
|
||||
}
|
||||
|
||||
if (parsed.kind === "search") {
|
||||
options.navigate({
|
||||
to: "/search",
|
||||
search: { query: parsed.query },
|
||||
});
|
||||
return "search";
|
||||
}
|
||||
|
||||
return "none";
|
||||
};
|
||||
|
||||
export const consumePendingDeepLink = () => {
|
||||
const url = sessionStorage.getItem(PENDING_LINK_KEY);
|
||||
if (url) sessionStorage.removeItem(PENDING_LINK_KEY);
|
||||
return url;
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
import { secToTicks, ticksToSec } from "@/utils/date/time";
|
||||
import {
|
||||
setVolume as setAudioVolume,
|
||||
setIsMuted,
|
||||
stopPlayback,
|
||||
useAudioPlayback,
|
||||
} from "@/utils/store/audioPlayback";
|
||||
import { usePlaybackStore } from "@/utils/store/playback";
|
||||
|
||||
export type LocalPlaybackSnapshot = {
|
||||
kind: "video" | "audio" | "none";
|
||||
itemId: string | null;
|
||||
positionTicks: number;
|
||||
paused: boolean;
|
||||
};
|
||||
|
||||
const getVideoElement = () =>
|
||||
document
|
||||
.querySelector("hls-video")
|
||||
?.shadowRoot?.querySelector("video") as HTMLVideoElement | null;
|
||||
|
||||
/** What this client is currently playing, if anything. */
|
||||
export const getLocalPlayback = (): LocalPlaybackSnapshot => {
|
||||
const video = usePlaybackStore.getState();
|
||||
if (video.playbackStream && video.metadata.item?.Id) {
|
||||
return {
|
||||
kind: "video",
|
||||
itemId: video.metadata.item.Id,
|
||||
positionTicks: video.playerState.currentTime ?? 0,
|
||||
paused: !video.playerState.isPlayerPlaying,
|
||||
};
|
||||
}
|
||||
|
||||
const audio = useAudioPlayback.getState();
|
||||
if (audio.display && audio.item?.Id) {
|
||||
const element = audio.player.ref?.current;
|
||||
return {
|
||||
kind: "audio",
|
||||
itemId: audio.item.Id,
|
||||
positionTicks: element
|
||||
? secToTicks(element.currentTime)
|
||||
: audio.player.currentTick,
|
||||
paused: element ? element.paused : !audio.player.playing,
|
||||
};
|
||||
}
|
||||
|
||||
return { kind: "none", itemId: null, positionTicks: 0, paused: false };
|
||||
};
|
||||
|
||||
export const pauseLocalPlayback = () => {
|
||||
const video = usePlaybackStore.getState();
|
||||
if (video.playbackStream && video.metadata.item?.Id) {
|
||||
getVideoElement()?.pause();
|
||||
video.setIsPlaying(false);
|
||||
}
|
||||
useAudioPlayback.getState().player.ref?.current?.pause();
|
||||
};
|
||||
|
||||
export const resumeLocalPlayback = () => {
|
||||
const video = usePlaybackStore.getState();
|
||||
if (video.playbackStream && video.metadata.item?.Id) {
|
||||
video.setIsPlaying(true);
|
||||
getVideoElement()
|
||||
?.play()
|
||||
.catch(() => {
|
||||
// The ReactPlayer `playing` prop retries once the media is ready.
|
||||
});
|
||||
}
|
||||
const audio = useAudioPlayback.getState();
|
||||
if (audio.display && audio.item?.Id) {
|
||||
audio.player.ref?.current?.play().catch(() => undefined);
|
||||
}
|
||||
};
|
||||
|
||||
export const seekLocalPlayback = (positionTicks: number) => {
|
||||
const ticks = Math.max(0, Math.round(positionTicks));
|
||||
const video = usePlaybackStore.getState();
|
||||
if (video.playbackStream && video.metadata.item?.Id) {
|
||||
if (!video.playerState.isPlayerReady) {
|
||||
usePlaybackStore.setState((state) => {
|
||||
state.playerState.seekValue = ticks;
|
||||
state.playerState.currentTime = ticks;
|
||||
});
|
||||
return;
|
||||
}
|
||||
video.seekTo(ticksToSec(ticks));
|
||||
return;
|
||||
}
|
||||
|
||||
const audio = useAudioPlayback.getState();
|
||||
const element = audio.player.ref?.current;
|
||||
if (element) {
|
||||
element.currentTime = ticksToSec(ticks);
|
||||
}
|
||||
};
|
||||
|
||||
export const setLocalVolume = (volume: number) => {
|
||||
const value = Math.min(1, Math.max(0, volume));
|
||||
const video = usePlaybackStore.getState();
|
||||
if (video.playbackStream && video.metadata.item?.Id) {
|
||||
video.setVolume(value);
|
||||
}
|
||||
if (useAudioPlayback.getState().display) {
|
||||
setAudioVolume(value);
|
||||
}
|
||||
};
|
||||
|
||||
export const setLocalMuted = (muted: boolean) => {
|
||||
const video = usePlaybackStore.getState();
|
||||
if (video.playbackStream && video.metadata.item?.Id) {
|
||||
if (video.playerState.isPlayerMuted !== muted) {
|
||||
video.toggleIsPlayerMuted();
|
||||
}
|
||||
}
|
||||
if (useAudioPlayback.getState().display) {
|
||||
setIsMuted(muted);
|
||||
}
|
||||
};
|
||||
|
||||
export const stopLocalPlayback = () => {
|
||||
pauseLocalPlayback();
|
||||
if (useAudioPlayback.getState().display) {
|
||||
stopPlayback();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { Api } from "@jellyfin/sdk";
|
||||
import {
|
||||
type BaseItemDto,
|
||||
BaseItemKind,
|
||||
ItemFields,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api";
|
||||
import { getPlaybackInfo } from "@/utils/methods/playback";
|
||||
import { generateAudioStreamUrl, playAudio } from "@/utils/store/audioPlayback";
|
||||
import { initializePlayback } from "@/utils/store/playback";
|
||||
import { setQueue } from "@/utils/store/queue";
|
||||
|
||||
const PLAYBACK_FIELDS = [
|
||||
ItemFields.MediaSources,
|
||||
ItemFields.MediaStreams,
|
||||
ItemFields.Chapters,
|
||||
ItemFields.Trickplay,
|
||||
ItemFields.Overview,
|
||||
];
|
||||
|
||||
export type StartedPlayback = {
|
||||
kind: "audio" | "video" | "none";
|
||||
itemId?: string;
|
||||
queueLength: number;
|
||||
};
|
||||
|
||||
type StartPlaybackOptions = {
|
||||
startIndex?: number;
|
||||
startPositionTicks?: number;
|
||||
audioStreamIndex?: number;
|
||||
subtitleStreamIndex?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Start playback for a list of item ids (a SyncPlay queue, a remote Play
|
||||
* command or a deep link). Returns the kind of playback that started; the
|
||||
* caller owns navigation so this can be used outside React.
|
||||
*/
|
||||
export const startPlaybackFromIds = async (
|
||||
api: Api,
|
||||
userId: string,
|
||||
itemIds: string[],
|
||||
options: StartPlaybackOptions = {},
|
||||
): Promise<StartedPlayback> => {
|
||||
const ids = itemIds.filter((id): id is string => Boolean(id));
|
||||
if (!api || !userId || ids.length === 0) {
|
||||
return { kind: "none", queueLength: 0 };
|
||||
}
|
||||
|
||||
const response = await getLibraryApi(api).getItems({
|
||||
userId,
|
||||
ids,
|
||||
fields: PLAYBACK_FIELDS,
|
||||
enableUserData: true,
|
||||
});
|
||||
const byId = new Map(
|
||||
(response.data.Items ?? [])
|
||||
.filter((item): item is BaseItemDto & { Id: string } => Boolean(item.Id))
|
||||
.map((item) => [item.Id, item]),
|
||||
);
|
||||
const items = ids
|
||||
.map((id) => byId.get(id))
|
||||
.filter((item): item is BaseItemDto & { Id: string } => Boolean(item));
|
||||
if (items.length === 0) {
|
||||
return { kind: "none", queueLength: 0 };
|
||||
}
|
||||
|
||||
const startIndex = Math.min(
|
||||
Math.max(0, options.startIndex ?? 0),
|
||||
items.length - 1,
|
||||
);
|
||||
const item = items[startIndex];
|
||||
const startPositionTicks = Math.max(0, options.startPositionTicks ?? 0);
|
||||
|
||||
if (
|
||||
item.Type === BaseItemKind.Audio ||
|
||||
item.Type === BaseItemKind.AudioBook
|
||||
) {
|
||||
const url = generateAudioStreamUrl(
|
||||
item.Id,
|
||||
userId,
|
||||
api.deviceInfo.id,
|
||||
api.basePath,
|
||||
api.accessToken,
|
||||
);
|
||||
playAudio(url, item, undefined, startPositionTicks);
|
||||
setQueue(items, startIndex);
|
||||
return { kind: "audio", itemId: item.Id, queueLength: items.length };
|
||||
}
|
||||
|
||||
if (item.Type === BaseItemKind.Photo) {
|
||||
return { kind: "none", queueLength: 0 };
|
||||
}
|
||||
|
||||
const playback = await getPlaybackInfo(api, userId, item, {
|
||||
startPositionTicks,
|
||||
currentAudioTrack: options.audioStreamIndex ?? "auto",
|
||||
currentSubTrack: options.subtitleStreamIndex,
|
||||
});
|
||||
|
||||
if (!playback.mediaSource?.MediaSources?.[0]?.Id) {
|
||||
throw new Error("No playable media source found");
|
||||
}
|
||||
|
||||
const playbackItems: BaseItemDto[] = playback.item?.Items ?? [];
|
||||
let queueItems: BaseItemDto[] =
|
||||
items.length > 1 ? items : playbackItems.length > 0 ? playbackItems : items;
|
||||
let queueIndex = queueItems.findIndex((entry) => entry.Id === item.Id);
|
||||
if (queueIndex < 0) {
|
||||
queueItems = items;
|
||||
queueIndex = startIndex;
|
||||
}
|
||||
|
||||
let playbackItem = queueItems[queueIndex];
|
||||
if (item.Type === BaseItemKind.Series) {
|
||||
playbackItem =
|
||||
playbackItems[playback.episodeIndex ?? 0] ?? playbackItems[0] ?? item;
|
||||
queueItems = playbackItems;
|
||||
queueIndex = Math.max(
|
||||
0,
|
||||
queueItems.findIndex((entry) => entry.Id === playbackItem.Id),
|
||||
);
|
||||
}
|
||||
if (!playbackItem) {
|
||||
playbackItem = item;
|
||||
}
|
||||
|
||||
await initializePlayback({
|
||||
api,
|
||||
userId,
|
||||
item: playbackItem,
|
||||
mediaSource: playback.mediaSource,
|
||||
mediaSegments: playback.mediaSegments,
|
||||
queueItems,
|
||||
queueIndex,
|
||||
startPositionTicks,
|
||||
audioStreamIndex: options.audioStreamIndex,
|
||||
subtitleStreamIndex: options.subtitleStreamIndex,
|
||||
});
|
||||
|
||||
return {
|
||||
kind: "video",
|
||||
itemId: playbackItem.Id,
|
||||
queueLength: queueItems.length,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,482 @@
|
||||
import type { Api } from "@jellyfin/sdk";
|
||||
import {
|
||||
type GroupUpdate,
|
||||
type PlayQueueUpdate,
|
||||
type SendCommand,
|
||||
SendCommandType,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getSyncPlayApi } from "@jellyfin/sdk/lib/utils/api/sync-play-api";
|
||||
import {
|
||||
getLocalPlayback,
|
||||
pauseLocalPlayback,
|
||||
resumeLocalPlayback,
|
||||
seekLocalPlayback,
|
||||
} from "@/utils/methods/localPlayback";
|
||||
import { startPlaybackFromIds } from "@/utils/methods/startPlayback";
|
||||
import useQueue from "@/utils/store/queue";
|
||||
import useSyncPlayStore from "@/utils/store/syncPlay";
|
||||
|
||||
const SEEK_REPORT_INTERVAL_MS = 300;
|
||||
const PAUSE_REPORT_INTERVAL_MS = 400;
|
||||
const AUTO_START_GUARD_MS = 5000;
|
||||
const DRIFT_TOLERANCE_TICKS = 2 * 10_000_000;
|
||||
|
||||
let applyingRemoteUntil = 0;
|
||||
let lastSeekReport = { at: 0, ticks: 0 };
|
||||
let lastPauseReport = { at: 0, paused: false };
|
||||
let lastAutoStart = { itemId: "", at: 0 };
|
||||
|
||||
const syncApi = (api: Api) => getSyncPlayApi(api);
|
||||
|
||||
const guardRemote = (ms = 1200) => {
|
||||
applyingRemoteUntil = Date.now() + ms;
|
||||
};
|
||||
|
||||
export const isApplyingSyncPlayRemote = () => Date.now() < applyingRemoteUntil;
|
||||
|
||||
export const inSyncPlayGroup = () => Boolean(useSyncPlayStore.getState().group);
|
||||
|
||||
const currentQueueItem = (queue: PlayQueueUpdate | null) => {
|
||||
if (!queue?.Playlist?.length) return undefined;
|
||||
return queue.Playlist[
|
||||
Math.min(
|
||||
Math.max(0, queue.PlayingItemIndex ?? 0),
|
||||
queue.Playlist.length - 1,
|
||||
)
|
||||
];
|
||||
};
|
||||
|
||||
export const refreshSyncPlayGroups = async (api: Api) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
try {
|
||||
const groups = (await syncApi(api).syncPlayGetGroups()).data ?? [];
|
||||
store.setGroups(groups);
|
||||
} catch (error) {
|
||||
console.warn("Could not load SyncPlay groups", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const refreshSyncPlayGroup = async (api: Api) => {
|
||||
const group = useSyncPlayStore.getState().group;
|
||||
if (!group?.GroupId) return;
|
||||
try {
|
||||
const fresh = (await syncApi(api).syncPlayGetGroup({ id: group.GroupId }))
|
||||
.data;
|
||||
if (fresh) useSyncPlayStore.getState().setGroup(fresh);
|
||||
} catch (error) {
|
||||
console.warn("Could not refresh SyncPlay group", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const openSyncPlayDialog = () => {
|
||||
useSyncPlayStore.getState().setOpen(true);
|
||||
useSyncPlayStore.getState().setError(null);
|
||||
};
|
||||
|
||||
export const closeSyncPlayDialog = () =>
|
||||
useSyncPlayStore.getState().setOpen(false);
|
||||
|
||||
export const createSyncPlayGroup = async (api: Api, name: string) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
store.setLoading(true);
|
||||
store.setError(null);
|
||||
try {
|
||||
const group = (
|
||||
await syncApi(api).syncPlayCreateGroup({
|
||||
newGroupRequestDto: { GroupName: name.trim() || "Watch together" },
|
||||
})
|
||||
).data;
|
||||
if (group) {
|
||||
store.setGroup(group);
|
||||
store.setGroups([
|
||||
...store.groups.filter((g) => g.GroupId !== group.GroupId),
|
||||
group,
|
||||
]);
|
||||
await refreshSyncPlayGroups(api);
|
||||
}
|
||||
return group;
|
||||
} catch (error) {
|
||||
console.error("Could not create SyncPlay group", error);
|
||||
store.setError("Could not create a group");
|
||||
return undefined;
|
||||
} finally {
|
||||
store.setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
export const joinSyncPlayGroup = async (api: Api, groupId: string) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
store.setLoading(true);
|
||||
store.setError(null);
|
||||
try {
|
||||
await syncApi(api).syncPlayJoinGroup({
|
||||
joinGroupRequestDto: { GroupId: groupId },
|
||||
});
|
||||
try {
|
||||
const group = (await syncApi(api).syncPlayGetGroup({ id: groupId })).data;
|
||||
if (group) store.setGroup(group);
|
||||
} catch {
|
||||
const known = store.groups.find((g) => g.GroupId === groupId);
|
||||
if (known) store.setGroup(known);
|
||||
}
|
||||
await refreshSyncPlayGroups(api);
|
||||
} catch (error) {
|
||||
console.error("Could not join SyncPlay group", error);
|
||||
store.setError("Could not join this group");
|
||||
} finally {
|
||||
store.setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
export const leaveSyncPlayGroup = async (api: Api) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
store.setLoading(true);
|
||||
try {
|
||||
await syncApi(api).syncPlayLeaveGroup();
|
||||
} catch (error) {
|
||||
console.warn("Could not leave SyncPlay group", error);
|
||||
} finally {
|
||||
store.setLoading(false);
|
||||
store.reset();
|
||||
store.setOpen(false);
|
||||
lastAutoStart = { itemId: "", at: 0 };
|
||||
applyingRemoteUntil = 0;
|
||||
}
|
||||
};
|
||||
|
||||
export const startSyncPlayQueue = async (api: Api) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
const queue = useQueue.getState();
|
||||
const ids = (queue.tracks ?? [])
|
||||
.map((item) => item.Id)
|
||||
.filter((id): id is string => Boolean(id));
|
||||
if (ids.length === 0) {
|
||||
store.setError("Start something first, then share the queue");
|
||||
return;
|
||||
}
|
||||
const position = getLocalPlayback();
|
||||
store.setLoading(true);
|
||||
store.setError(null);
|
||||
try {
|
||||
await syncApi(api).syncPlaySetNewQueue({
|
||||
playRequestDto: {
|
||||
PlayingQueue: ids,
|
||||
PlayingItemPosition: queue.currentItemIndex,
|
||||
StartPositionTicks: position.positionTicks,
|
||||
},
|
||||
});
|
||||
// A lone host should not be stuck on "waiting for everyone".
|
||||
if ((store.group?.Participants?.length ?? 0) <= 1) {
|
||||
window.setTimeout(() => {
|
||||
void resumeSyncPlayGroup(api);
|
||||
}, 900);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Could not start SyncPlay queue", error);
|
||||
store.setError("Could not start the group queue");
|
||||
} finally {
|
||||
store.setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
export const watchSyncPlayQueueHere = async (api: Api, userId: string) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
const queue = store.queue;
|
||||
const index = queue?.PlayingItemIndex ?? 0;
|
||||
const ids = (queue?.Playlist ?? [])
|
||||
.map((item) => item.ItemId)
|
||||
.filter((id): id is string => Boolean(id));
|
||||
if (ids.length === 0 || !userId) return;
|
||||
guardRemote(4000);
|
||||
store.setLoading(true);
|
||||
try {
|
||||
const result = await startPlaybackFromIds(api, userId, ids, {
|
||||
startIndex: index,
|
||||
startPositionTicks: queue?.StartPositionTicks ?? 0,
|
||||
});
|
||||
if (result.kind !== "none") {
|
||||
store.setPendingNavigation(result.kind);
|
||||
if (queue && !queue.IsPlaying) pauseLocalPlayback();
|
||||
if ((store.group?.Participants?.length ?? 0) <= 1) {
|
||||
window.setTimeout(() => {
|
||||
void resumeSyncPlayGroup(api);
|
||||
}, 900);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Could not start the group queue here", error);
|
||||
store.setError("Could not start playback");
|
||||
} finally {
|
||||
store.setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
export const pauseSyncPlayGroup = async (api: Api) => {
|
||||
try {
|
||||
await syncApi(api).syncPlayPause();
|
||||
} catch (error) {
|
||||
console.warn("Could not pause SyncPlay group", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const resumeSyncPlayGroup = async (api: Api) => {
|
||||
try {
|
||||
await syncApi(api).syncPlayUnpause();
|
||||
} catch (error) {
|
||||
console.warn("Could not resume SyncPlay group", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const seekSyncPlayGroup = async (api: Api, positionTicks: number) => {
|
||||
try {
|
||||
await syncApi(api).syncPlaySeek({
|
||||
seekRequestDto: { PositionTicks: Math.max(0, Math.round(positionTicks)) },
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("Could not seek SyncPlay group", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const nextSyncPlayItem = async (api: Api) => {
|
||||
const item = currentQueueItem(useSyncPlayStore.getState().queue);
|
||||
try {
|
||||
await syncApi(api).syncPlayNextItem({
|
||||
nextItemRequestDto: { PlaylistItemId: item?.PlaylistItemId },
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("Could not advance SyncPlay group", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const previousSyncPlayItem = async (api: Api) => {
|
||||
const item = currentQueueItem(useSyncPlayStore.getState().queue);
|
||||
try {
|
||||
await syncApi(api).syncPlayPreviousItem({
|
||||
previousItemRequestDto: { PlaylistItemId: item?.PlaylistItemId },
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("Could not rewind SyncPlay group", error);
|
||||
}
|
||||
};
|
||||
|
||||
const applyQueueUpdate = async (
|
||||
api: Api,
|
||||
userId: string | undefined,
|
||||
queue: PlayQueueUpdate,
|
||||
) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
const item = currentQueueItem(queue);
|
||||
if (!item?.ItemId) return;
|
||||
const local = getLocalPlayback();
|
||||
const position = queue.StartPositionTicks ?? 0;
|
||||
|
||||
if (local.kind !== "none" && local.itemId === item.ItemId) {
|
||||
guardRemote();
|
||||
if (queue.IsPlaying) resumeLocalPlayback();
|
||||
else pauseLocalPlayback();
|
||||
if (Math.abs(local.positionTicks - position) > DRIFT_TOLERANCE_TICKS) {
|
||||
seekLocalPlayback(position);
|
||||
}
|
||||
// A new group queue starts in Waiting until every device reports that
|
||||
// it is ready. The host already has the item loaded.
|
||||
reportSyncPlayReady(api, local.positionTicks, queue.IsPlaying ?? false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!userId) return;
|
||||
if (
|
||||
lastAutoStart.itemId === item.ItemId &&
|
||||
Date.now() - lastAutoStart.at < AUTO_START_GUARD_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastAutoStart = { itemId: item.ItemId, at: Date.now() };
|
||||
const ids = (queue.Playlist ?? [])
|
||||
.map((entry) => entry.ItemId)
|
||||
.filter((id): id is string => Boolean(id));
|
||||
guardRemote(5000);
|
||||
try {
|
||||
const result = await startPlaybackFromIds(api, userId, ids, {
|
||||
startIndex: Math.max(0, queue.PlayingItemIndex ?? 0),
|
||||
startPositionTicks: position,
|
||||
});
|
||||
if (result.kind !== "none") {
|
||||
store.setPendingNavigation(result.kind);
|
||||
if (!queue.IsPlaying) pauseLocalPlayback();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Could not follow the SyncPlay queue", error);
|
||||
}
|
||||
};
|
||||
|
||||
export const handleSyncPlayGroupUpdate = async (
|
||||
api: Api,
|
||||
userId: string | undefined,
|
||||
update: GroupUpdate,
|
||||
) => {
|
||||
const store = useSyncPlayStore.getState();
|
||||
switch (update.Type) {
|
||||
case "GroupJoined":
|
||||
if (update.Data) store.setGroup(update.Data);
|
||||
await refreshSyncPlayGroups(api);
|
||||
break;
|
||||
case "PlayQueue":
|
||||
if (update.Data) {
|
||||
store.setQueue(update.Data);
|
||||
await applyQueueUpdate(api, userId, update.Data);
|
||||
}
|
||||
break;
|
||||
case "StateUpdate": {
|
||||
const group = store.group;
|
||||
if (group && update.Data?.State) {
|
||||
store.setGroup({ ...group, State: update.Data.State });
|
||||
}
|
||||
if (update.Data?.State === "Paused") {
|
||||
guardRemote();
|
||||
pauseLocalPlayback();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "UserJoined":
|
||||
case "UserLeft":
|
||||
await refreshSyncPlayGroup(api);
|
||||
await refreshSyncPlayGroups(api);
|
||||
break;
|
||||
case "GroupLeft":
|
||||
case "NotInGroup":
|
||||
case "GroupDoesNotExist":
|
||||
store.reset();
|
||||
store.setOpen(false);
|
||||
lastAutoStart = { itemId: "", at: 0 };
|
||||
applyingRemoteUntil = 0;
|
||||
break;
|
||||
case "LibraryAccessDenied":
|
||||
useSyncPlayStore.getState().setError("No access to this group's library");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
export const handleSyncPlayCommand = (command: SendCommand) => {
|
||||
const group = useSyncPlayStore.getState().group;
|
||||
if (!group) return;
|
||||
const apply = () => {
|
||||
guardRemote(1500);
|
||||
switch (command.Command) {
|
||||
case SendCommandType.Pause:
|
||||
case SendCommandType.Stop:
|
||||
pauseLocalPlayback();
|
||||
break;
|
||||
case SendCommandType.Unpause:
|
||||
resumeLocalPlayback();
|
||||
break;
|
||||
case SendCommandType.Seek:
|
||||
if (command.PositionTicks != null) {
|
||||
seekLocalPlayback(command.PositionTicks);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
const when = command.When ? Date.parse(command.When) : Number.NaN;
|
||||
const delay = Number.isFinite(when)
|
||||
? Math.min(10_000, Math.max(0, when - Date.now()))
|
||||
: 0;
|
||||
if (delay > 0) setTimeout(apply, delay);
|
||||
else apply();
|
||||
};
|
||||
|
||||
export const reportSyncPlayPause = (api: Api | undefined) => {
|
||||
if (!api || !inSyncPlayGroup() || isApplyingSyncPlayRemote()) return;
|
||||
const now = Date.now();
|
||||
if (
|
||||
lastPauseReport.paused &&
|
||||
now - lastPauseReport.at < PAUSE_REPORT_INTERVAL_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastPauseReport = { at: now, paused: true };
|
||||
pauseSyncPlayGroup(api);
|
||||
};
|
||||
|
||||
export const reportSyncPlayResume = (api: Api | undefined) => {
|
||||
if (!api || !inSyncPlayGroup() || isApplyingSyncPlayRemote()) return;
|
||||
const now = Date.now();
|
||||
if (
|
||||
!lastPauseReport.paused &&
|
||||
now - lastPauseReport.at < PAUSE_REPORT_INTERVAL_MS
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastPauseReport = { at: now, paused: false };
|
||||
resumeSyncPlayGroup(api);
|
||||
};
|
||||
|
||||
export const reportSyncPlaySeek = (
|
||||
api: Api | undefined,
|
||||
positionTicks: number,
|
||||
) => {
|
||||
if (!api || !inSyncPlayGroup() || isApplyingSyncPlayRemote()) return;
|
||||
const now = Date.now();
|
||||
if (
|
||||
now - lastSeekReport.at < SEEK_REPORT_INTERVAL_MS ||
|
||||
Math.abs(positionTicks - lastSeekReport.ticks) < 10_000_000
|
||||
) {
|
||||
return;
|
||||
}
|
||||
lastSeekReport = { at: now, ticks: positionTicks };
|
||||
seekSyncPlayGroup(api, positionTicks);
|
||||
};
|
||||
|
||||
export const reportSyncPlayReady = (
|
||||
api: Api | undefined,
|
||||
positionTicks: number,
|
||||
isPlaying: boolean,
|
||||
) => {
|
||||
if (!api || !inSyncPlayGroup()) return;
|
||||
const queue = useSyncPlayStore.getState().queue;
|
||||
const item = currentQueueItem(queue);
|
||||
if (!item?.PlaylistItemId) return;
|
||||
syncApi(api)
|
||||
.syncPlayReady({
|
||||
readyRequestDto: {
|
||||
When: new Date().toISOString(),
|
||||
PositionTicks: Math.max(0, Math.round(positionTicks)),
|
||||
IsPlaying: isPlaying,
|
||||
PlaylistItemId: item.PlaylistItemId,
|
||||
},
|
||||
})
|
||||
.then(() => {
|
||||
window.setTimeout(() => {
|
||||
void refreshSyncPlayGroup(api);
|
||||
}, 800);
|
||||
// A solo host can begin immediately; with more devices the server
|
||||
// waits for everyone, then sends the unpause command.
|
||||
const participants =
|
||||
useSyncPlayStore.getState().group?.Participants?.length ?? 0;
|
||||
if (participants <= 1) {
|
||||
void resumeSyncPlayGroup(api);
|
||||
}
|
||||
})
|
||||
.catch((error) => console.warn("SyncPlay ready failed", error));
|
||||
};
|
||||
|
||||
export const reportSyncPlayBuffering = (
|
||||
api: Api | undefined,
|
||||
isBuffering: boolean,
|
||||
positionTicks: number,
|
||||
isPlaying: boolean,
|
||||
) => {
|
||||
if (!api || !inSyncPlayGroup()) return;
|
||||
const queue = useSyncPlayStore.getState().queue;
|
||||
const item = currentQueueItem(queue);
|
||||
if (!item?.PlaylistItemId) return;
|
||||
syncApi(api)
|
||||
.syncPlayBuffering({
|
||||
bufferRequestDto: {
|
||||
When: new Date().toISOString(),
|
||||
PositionTicks: Math.max(0, Math.round(positionTicks)),
|
||||
IsPlaying: isBuffering ? false : isPlaying,
|
||||
PlaylistItemId: item.PlaylistItemId,
|
||||
},
|
||||
})
|
||||
.catch((error) => console.warn("SyncPlay buffering failed", error));
|
||||
};
|
||||
Reference in new issue
Block a user