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() || "Смотреть вместе" }, }) ).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("Не удалось создать группу"); 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("Не удалось войти в группу"); } 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("Сначала включите что-нибудь, затем поделитесь очередью"); 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("Не удалось запустить очередь группы"); } 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("Не удалось запустить воспроизведение"); } 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 pingSyncPlayGroup = async (api: Api) => { try { await syncApi(api).syncPlayPing({ // This is the measured latency in milliseconds, not a timestamp. // The server clamps it to 10s; a huge value would delay every // scheduled pause/unpause, so report a conservative local value. pingRequestDto: { Ping: 50 }, }); } catch (error) { console.warn("Could not ping 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("Нет доступа к библиотеке группы"); 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)); };