From 8ff785da40a96d882cdae8c8dd7d2bd1424759ba Mon Sep 17 00:00:00 2001 From: Lei Nelissen Date: Sun, 18 Jun 2023 22:04:20 +0200 Subject: [PATCH] fix: properly end previous playing track --- src/utility/JellyfinApi.ts | 7 +++++-- src/utility/PlaybackService.ts | 9 +++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/utility/JellyfinApi.ts b/src/utility/JellyfinApi.ts index 1f804cf..4f639ce 100644 --- a/src/utility/JellyfinApi.ts +++ b/src/utility/JellyfinApi.ts @@ -261,10 +261,10 @@ const RepeatModeMap: Record = { * This will generate the payload that is required for playback events and send * it to the supplied path. */ -export async function sendPlaybackEvent(path: string, credentials: Credentials) { +export async function sendPlaybackEvent(path: string, credentials: Credentials, trackIndex?: number) { // Extract all data from react-native-track-player const [ - track, position, repeatMode, volume, queue, state, + currentTrack, position, repeatMode, volume, queue, state, ] = await Promise.all([ TrackPlayer.getCurrentTrack(), TrackPlayer.getPosition(), @@ -274,6 +274,9 @@ export async function sendPlaybackEvent(path: string, credentials: Credentials) TrackPlayer.getState(), ]); + // Switch between overriden track index and current track + const track = trackIndex !== undefined ? trackIndex : currentTrack; + // Generate a payload from the gathered data const payload = { VolumeLevel: volume * 100, diff --git a/src/utility/PlaybackService.ts b/src/utility/PlaybackService.ts index 7b77076..2a80d14 100644 --- a/src/utility/PlaybackService.ts +++ b/src/utility/PlaybackService.ts @@ -36,12 +36,17 @@ export default async function() { TrackPlayer.seekTo(event.position); }); - TrackPlayer.addEventListener(Event.PlaybackTrackChanged, () => { + TrackPlayer.addEventListener(Event.PlaybackTrackChanged, async (e) => { // Retrieve the current settings from the Redux store const settings = store.getState().settings; // GUARD: Only report playback when the settings is enabled - if (settings.enablePlaybackReporting) { + if (settings.enablePlaybackReporting && 'track' in e) { + // GUARD: End the previous track if it's about to end + if ('nextTrack' in e && typeof e.track === 'number') { + sendPlaybackEvent('/Sessions/Stopped', settings.jellyfin, e.track); + } + sendPlaybackEvent('/Sessions/Playing', settings.jellyfin); } });