Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/car play stand alone #50

Merged
merged 4 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"Epika",
"GEMIUS",
"KLASIKA",
"LITHUANICA",
"notifee",
"RADIJAS",
"Theo",
Expand Down
17 changes: 12 additions & 5 deletions App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import {initialWindowMetrics, SafeAreaProvider} from 'react-native-safe-area-con
import {persistor, store} from './app/redux/store';
import useAppTrackingPermission from './app/util/useAppTrackingPermission';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {StyleSheet} from 'react-native';
import {Platform, StyleSheet} from 'react-native';
import PlayerProvider from './app/components/videoComponent/context/PlayerProvider';
import useNotificationsPermission from './app/util/useNotificationsPermission';
import useGoogleAnalyticsSetup from './app/util/useGoogleAnalyticsSetup';
import CarPlayProvider from './app/car/CarPlayProvider';
import ThemeProvider from './app/theme/ThemeProvider';
import useCarPlayController from './app/car/useCarPlayController';
import useTrackPlayerSetup from './app/car/useTrackPlayerSetup';

const ReduxProvider: React.FC<React.PropsWithChildren<{}>> = ({children}) => {
return (
Expand All @@ -32,16 +33,22 @@ const App: React.FC = () => {
useAppTrackingPermission();
useGoogleAnalyticsSetup();
useGemiusSetup();
useTrackPlayerSetup();

const {isConnected: _} =
Platform.OS === 'ios'
? useCarPlayController()
: {
isConnected: false,
};

return (
<SafeAreaProvider initialMetrics={initialWindowMetrics}>
<SettingsProvider>
<ThemeProvider>
<AppBackground>
<PlayerProvider>
<CarPlayProvider>
<Navigation />
</CarPlayProvider>
<Navigation />
</PlayerProvider>
</AppBackground>
</ThemeProvider>
Expand Down
93 changes: 93 additions & 0 deletions PlaybackService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import TrackPlayer, {Event, State} from 'react-native-track-player';
import {tracker} from './app/components/videoComponent/useMediaTracking';
import Gemius from 'react-native-gemius-plugin';

const PlaybackService = async () => {
TrackPlayer.addEventListener(Event.RemotePause, () => {
console.log('Event.RemotePause');
TrackPlayer.pause();
});
TrackPlayer.addEventListener(Event.RemotePlay, () => {
console.log('Event.RemotePlay');
TrackPlayer.play();
});
TrackPlayer.addEventListener(Event.RemoteStop, () => {
console.log('Event.RemoteStop');
TrackPlayer.stop();
});
TrackPlayer.addEventListener(Event.RemoteNext, () => {
console.log('Event.RemoteNext');
TrackPlayer.skipToNext();
});
TrackPlayer.addEventListener(Event.RemotePrevious, () => {
console.log('Event.RemotePrevious');
TrackPlayer.skipToPrevious();
});
TrackPlayer.addEventListener(Event.RemoteJumpForward, async (event) => {
console.log('Event.RemoteJumpForward', event);
await TrackPlayer.seekBy(event.interval);

const activeTrack = await TrackPlayer.getActiveTrack();
if (!activeTrack) {
console.warn('No active track');
return;
}
const progress = await TrackPlayer.getProgress();
tracker.trackSeek(activeTrack.url, progress.position);
});
TrackPlayer.addEventListener(Event.RemoteJumpBackward, async (event) => {
console.log('Event.RemoteJumpBackward', event);
await TrackPlayer.seekBy(-event.interval);

const activeTrack = await TrackPlayer.getActiveTrack();
if (!activeTrack) {
console.warn('No active track');
return;
}
const progress = await TrackPlayer.getProgress();
tracker.trackSeek(activeTrack.url, progress.position);
});
TrackPlayer.addEventListener(Event.RemoteSeek, async (event) => {
console.log('Event.RemoteSeek', event);
TrackPlayer.seekTo(event.position);

const activeTrack = await TrackPlayer.getActiveTrack();
if (!activeTrack) {
console.log('PlaybackService: no active track. Skipping analytics tracking.');
return;
}
tracker.trackSeek(activeTrack.url, event.position);
});
TrackPlayer.addEventListener(Event.PlaybackState, async (event) => {
console.log('Event.PlaybackState', event);
const activeTrack = await TrackPlayer.getActiveTrack();
if (!activeTrack) {
console.log('PlaybackService: no active track. Skipping analytics tracking.');
return;
}

const progress = await TrackPlayer.getProgress();
switch (event.state) {
case State.Ready:
Gemius.setProgramData(activeTrack.url, activeTrack.title ?? '', progress.duration, false);
break;
case State.Playing:
tracker.trackPlay(activeTrack.url, progress.position);
break;
case State.Paused:
tracker.trackPause(activeTrack.url, progress.position);
break;
case State.Stopped:
tracker.trackClose(activeTrack.url, progress.position);
break;
case State.Buffering:
tracker.trackBuffer(activeTrack.url, progress.position);
break;
case State.Ended:
tracker.trackComplete(activeTrack.url, progress.position);
break;
}
});
};

export default PlaybackService;
2 changes: 2 additions & 0 deletions app/api/Endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,5 @@ export const carPlaylistPodcastsGet = (count: number) =>

export const carPlaylistCategoryGet = (id: number | string) =>
`https://www.lrt.lt/api/json/category?id=${id}`;

export const carPlaylistLiveGet = () => 'https://www.lrt.lt/static/tvprog/tvprog.json';
16 changes: 15 additions & 1 deletion app/api/Types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,20 @@ export type MenuResponse = {
main_menu: (MenuItem | MenuItemCategory | MenuItemPage | MenuItemChannels | MenuItemProjects)[];
};

export type TVProgramResponse = {
tvprog: {
has_tvprog?: 0 | 1;
items: TVProgramChannel[];
live_items?: TVProgramChannel[];
};
};

export type TVProgramChannel = Omit<TVChannel, 'certification' | 'get_streams_url'> & {
description?: string;
stream_url: string;
app_logo: string;
};

/**
* Channel type in home page
*/
Expand All @@ -79,7 +93,7 @@ export type TVChannel = {
certification: string;
time_start: string;
time_end: string;
stream_embed: string;
stream_embed?: string;
get_streams_url: string;
is_radio?: 0 | 1;
block_all?: 0 | 1;
Expand Down
4 changes: 4 additions & 0 deletions app/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
articlesGetByTag,
audiotekaGet,
carPlaylistCategoryGet,
carPlaylistLiveGet,
carPlaylistNewestGet,
carPlaylistPodcastsGet,
carPlaylistPopularGet,
Expand Down Expand Up @@ -46,6 +47,7 @@ import {
SearchFilter,
SearchResponse,
SlugArticlesResponse,
TVProgramResponse,
VideoDataDefault,
VideoDataLiveStream,
} from './Types';
Expand Down Expand Up @@ -113,3 +115,5 @@ export const fetchCarPodcasts = (count: number) =>

export const fetchCarCategoryPlaylist = (id: string | number) =>
get<CarPlayCategoryResponse>(carPlaylistCategoryGet(id));

export const fetchCarLivePlaylist = () => get<TVProgramResponse>(carPlaylistLiveGet());
28 changes: 15 additions & 13 deletions app/car/live/useCarLiveChannels.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import {useSelector} from 'react-redux';
import {selectHomeChannels} from '../../redux/selectors';
import {checkEqual} from '../../util/LodashEqualityCheck';
import {useEffect, useState} from 'react';
import {PlayListItem} from '../CarPlayContext';
import {fetchStreamData} from '../../components/videoComponent/fetchStreamData';
import useCancellablePromise from '../../hooks/useCancellablePromise';
import {VIDEO_DEFAULT_BACKGROUND_IMAGE} from '../../constants';
import {fetchCarLivePlaylist} from '../../api';
import {BASE_IMG_URL} from '../../util/ImageUtil';

const useCarLiveChannels = (isConnected: boolean) => {
const [channels, setChannels] = useState<PlayListItem[]>([]);
const [lastLoadTime, setLastLoadTime] = useState<number>(0);
const channelsData = useSelector(selectHomeChannels, checkEqual);

const cancellablePromise = useCancellablePromise();

Expand All @@ -20,14 +18,18 @@ const useCarLiveChannels = (isConnected: boolean) => {
}

cancellablePromise(
Promise.all(
channelsData?.channels?.map((channel) =>
fetchStreamData({
url: channel.get_streams_url,
title: channel.channel_title,
poster: channel.cover_url,
}),
) || [],
fetchCarLivePlaylist().then((response) =>
Promise.all(
response.tvprog?.items?.map((channel) =>
fetchStreamData({
url: channel.stream_url,
title: channel.channel_title,
poster: channel.cover_url.startsWith('http')
? channel.cover_url
: BASE_IMG_URL + channel.cover_url,
}),
) || [],
),
),
).then((data) => {
if (data?.length) {
Expand All @@ -41,7 +43,7 @@ const useCarLiveChannels = (isConnected: boolean) => {
setChannels(channels);
}
});
}, [channelsData, isConnected, lastLoadTime]);
}, [isConnected, lastLoadTime]);

return {
channels,
Expand Down
2 changes: 1 addition & 1 deletion app/car/newest/useCarNewestTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const useCarNewestTemplate = (isConnected: boolean) => {
channels.map((item) => ({
uri: item.streamUrl,
mediaType: MediaType.AUDIO,
isLiveStream: true,
isLiveStream: false,
poster: item.imgUrl,
title: item.text,
})),
Expand Down
12 changes: 12 additions & 0 deletions app/car/nowPlaying/createNowPlayingTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,16 @@ export const createNowPlayingTemplate = ({onNextPress, onPreviousPress}: Props)
export const carPlayNowPlayingTemplate = new NowPlayingTemplate({
id: 'lrt-now-playing-template',
albumArtistButtonEnabled: true,
onBarButtonPressed: (button) => {
console.log('onBarButtonPressed', button);
},
onButtonPressed: (button) => {
console.log('onButtonPressed', button);
},
onAlbumArtistButtonPressed: () => {
console.log('onAlbumArtistButtonPressed');
},
onUpNextButtonPressed: () => {
console.log('onUpNextButtonPressed');
},
});
2 changes: 1 addition & 1 deletion app/car/popular/useCarPopularTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const useCarPopularTemplate = (isConnected: boolean) => {
channels.map((item) => ({
uri: item.streamUrl,
mediaType: MediaType.AUDIO,
isLiveStream: true,
isLiveStream: false,
poster: item.imgUrl,
title: item.text,
})),
Expand Down
2 changes: 1 addition & 1 deletion app/car/recommended/useCarRecommendedTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const useCarRecommendedTemplate = (isConnected: boolean) => {
channels.map((item) => ({
uri: item.streamUrl,
mediaType: MediaType.AUDIO,
isLiveStream: true,
isLiveStream: false,
poster: item.imgUrl,
title: item.text,
})),
Expand Down
6 changes: 0 additions & 6 deletions app/car/useCarPlay.ts

This file was deleted.

5 changes: 4 additions & 1 deletion app/car/useCarPlayController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ import {CarPlayContextType} from './CarPlayContext';
import useCarPlayRootTemplate from './root/useCarPlayRootTemplate';
import Gemius from 'react-native-gemius-plugin';
import analytics from '@react-native-firebase/analytics';
import TrackPlayer from 'react-native-track-player';

type ReturnType = CarPlayContextType;

const useCarPlayController = (): ReturnType => {
const [isConnected, setIsConnected] = useState(false);
const [isConnected, setIsConnected] = useState(CarPlay.connected);

const rootTemplate = useCarPlayRootTemplate(isConnected);

useEffect(() => {
if (isConnected) {
CarPlay.setRootTemplate(rootTemplate);
CarPlay.enableNowPlaying(true);
} else {
TrackPlayer.reset();
}
}, [isConnected]);

Expand Down
52 changes: 52 additions & 0 deletions app/car/useTrackPlayerSetup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {useCallback, useEffect} from 'react';
import TrackPlayer, {Capability, IOSCategory, IOSCategoryMode, RepeatMode} from 'react-native-track-player';

const useTrackPlayerSetup = () => {
const setup = useCallback(async () => {
await TrackPlayer.setupPlayer({
iosCategory: IOSCategory.Playback,
iosCategoryMode: IOSCategoryMode.SpokenAudio,
autoHandleInterruptions: true,
autoUpdateMetadata: true,
//androidAudioContentType: 'music',
});
await TrackPlayer.updateOptions({
capabilities: [
Capability.Play,
Capability.Pause,
Capability.SkipToNext,
Capability.SkipToPrevious,
Capability.JumpBackward,
Capability.JumpForward,
Capability.SeekTo,
Capability.Stop,
],
notificationCapabilities: [
Capability.Play,
Capability.Pause,
Capability.SkipToNext,
Capability.SkipToPrevious,
Capability.JumpBackward,
Capability.JumpForward,
Capability.SeekTo,
],
compactCapabilities: [
Capability.Play,
Capability.Pause,
Capability.SkipToNext,
Capability.SkipToPrevious,
Capability.JumpBackward,
Capability.JumpForward,
Capability.SeekTo,
],
});
await TrackPlayer.setRepeatMode(RepeatMode.Queue);
console.log('TrackPlayer ready!');
}, []);

useEffect(() => {
setup();
}, []);
};

export default useTrackPlayerSetup;
Loading
Loading