Remove react-native-track-player implementation

This commit is contained in:
Danish Ahmed Mirza 2022-07-24 18:40:09 +05:30 committed by Danish
parent bb4a59e4d5
commit ddde77fc6b
8 changed files with 280 additions and 416 deletions

View File

@ -5,40 +5,36 @@ import Animated, { useSharedValue, useAnimatedStyle, interpolate, withTiming, Ea
import styles, { SLIDER_THUMB_RADIUS } from '../../styles'; import styles, { SLIDER_THUMB_RADIUS } from '../../styles';
import { useTheme } from '../../../../theme'; import { useTheme } from '../../../../theme';
// import { debounce } from '../../../../lib/methods/helpers';
interface ISliderProps { interface ISliderProps {
value: number; value: number;
maximumValue: number; maximumValue: number;
onValueChange: (value: number) => void; onValueChange: (value: number) => void;
onSlidingStart: () => void;
onSlidingEnd: (value: number) => void; onSlidingEnd: (value: number) => void;
thumbTintColor?: string; thumbTintColor?: string;
minimumTrackTintColor?: string; activeTrackColor: string;
maximumTrackTintColor?: string; trackColor: string;
disabled?: boolean; disabled?: boolean;
thumbImage?: { uri: string; scale: number | undefined }; thumbImage?: { uri: string; scale: number | undefined };
containerStyle?: StyleProp<ViewStyle>; containerStyle?: StyleProp<ViewStyle>;
animationConfig?: { duration: number; easing: Animated.EasingFunction }; animationConfig?: { duration: number; easing: Animated.EasingFunction };
} }
const Slider = React.memo( const Slider = ({
({
value, value,
maximumValue, maximumValue,
onValueChange, onValueChange,
onSlidingStart,
onSlidingEnd, onSlidingEnd,
thumbTintColor, thumbTintColor,
minimumTrackTintColor, activeTrackColor,
maximumTrackTintColor, trackColor,
disabled, disabled,
containerStyle, containerStyle,
animationConfig = { animationConfig = {
duration: 200, duration: 200,
easing: Easing.linear easing: Easing.linear
} }
}: ISliderProps) => { }: ISliderProps): React.ReactElement => {
const { colors } = useTheme(); const { colors } = useTheme();
const [sliderWidth, setSliderWidth] = useState<number>(0); const [sliderWidth, setSliderWidth] = useState<number>(0);
const [isSliding, setSliding] = useState<boolean>(false); const [isSliding, setSliding] = useState<boolean>(false);
@ -59,20 +55,18 @@ const Slider = React.memo(
setSliderWidth(event.nativeEvent.layout.width); setSliderWidth(event.nativeEvent.layout.width);
}; };
// const debouncedOnValueChange = debounce((value: number) => onValueChange(value), 50);
const tapGesture = Gesture.Tap() const tapGesture = Gesture.Tap()
.hitSlop({ vertical: 10 }) .hitSlop({ vertical: 10 })
.onStart(e => { .onStart(e => {
currentValue.value = equivalentValue(clamp(e.x, 0, sliderWidth)); currentValue.value = equivalentValue(clamp(e.x, 0, sliderWidth));
onValueChange(equivalentValue(clamp(e.x, 0, sliderWidth))); onValueChange(equivalentValue(clamp(e.x, 0, sliderWidth)));
onSlidingEnd(equivalentValue(clamp(e.x, 0, sliderWidth)));
}); });
const dragGesture = Gesture.Pan() const dragGesture = Gesture.Pan()
.hitSlop({ horizontal: 5, vertical: 20 }) .hitSlop({ horizontal: 5, vertical: 20 })
.onStart(() => { .onStart(() => {
setSliding(true); setSliding(true);
onSlidingStart();
sliderThumbWidth.value = withTiming(3 * SLIDER_THUMB_RADIUS, { duration: 100 }); sliderThumbWidth.value = withTiming(3 * SLIDER_THUMB_RADIUS, { duration: 100 });
}) })
.onChange(e => { .onChange(e => {
@ -106,18 +100,15 @@ const Slider = React.memo(
return ( return (
<View style={[styles.sliderContainer, containerStyle]}> <View style={[styles.sliderContainer, containerStyle]}>
<GestureDetector gesture={gesture}> <GestureDetector gesture={gesture}>
<View style={[styles.track, { backgroundColor: maximumTrackTintColor || colors.buttonBackground }]} onLayout={onLayout}> <View style={[styles.track, { backgroundColor: trackColor }]} onLayout={onLayout}>
<Animated.View <Animated.View
style={[styles.sliderThumb, { backgroundColor: thumbTintColor || colors.tintColor }, animatedThumbStyles]} style={[styles.sliderThumb, { backgroundColor: thumbTintColor || colors.tintColor }, animatedThumbStyles]}
/> />
<Animated.View <Animated.View style={[styles.activeTrack, { backgroundColor: activeTrackColor }, animatedTrackStyles]} />
style={[styles.activeTrack, { backgroundColor: minimumTrackTintColor || colors.tintColor }, animatedTrackStyles]}
/>
</View> </View>
</GestureDetector> </GestureDetector>
</View> </View>
); );
} };
);
export default Slider; export default Slider;

View File

@ -1,28 +1,24 @@
import React, { useContext, useEffect, useState } from 'react'; import React from 'react';
import { StyleProp, StyleSheet, Text, TextStyle, View } from 'react-native'; import { StyleProp, StyleSheet, Text, TextStyle, View } from 'react-native';
import moment from 'moment';
import { activateKeepAwake, deactivateKeepAwake } from 'expo-keep-awake';
import { Audio, AVPlaybackStatus } from 'expo-av'; import { Audio, AVPlaybackStatus } from 'expo-av';
import TrackPlayer, { Event, useTrackPlayerEvents, State, useProgress } from 'react-native-track-player'; import moment from 'moment';
import { Easing } from 'react-native-reanimated'; import { dequal } from 'dequal';
import { activateKeepAwake, deactivateKeepAwake } from 'expo-keep-awake';
import { Sound } from 'expo-av/build/Audio/Sound';
import Touchable from '../../Touchable'; import Touchable from '../../Touchable';
import Markdown from '../../../markdown'; import Markdown from '../../../markdown';
import { CustomIcon } from '../../../CustomIcon'; import { CustomIcon } from '../../../CustomIcon';
import sharedStyles from '../../../../views/Styles'; import sharedStyles from '../../../../views/Styles';
import { themes } from '../../../../lib/constants'; import { themes } from '../../../../lib/constants';
import { import { isAndroid, isIOS } from '../../../../lib/methods/helpers';
isAndroid
// isIOS
} from '../../../../lib/methods/helpers';
import MessageContext from '../../Context'; import MessageContext from '../../Context';
import ActivityIndicator from '../../../ActivityIndicator'; import ActivityIndicator from '../../../ActivityIndicator';
import { withDimensions } from '../../../../dimensions';
import { TGetCustomEmoji } from '../../../../definitions/IEmoji'; import { TGetCustomEmoji } from '../../../../definitions/IEmoji';
import { IAttachment } from '../../../../definitions'; import { IAttachment } from '../../../../definitions';
import { TSupportedThemes } from '../../../../theme'; import { TSupportedThemes } from '../../../../theme';
import { setupService } from './services';
import Slider from './Slider'; import Slider from './Slider';
import { addTrack, clearTracks, getTrackIndex, useTracks } from './tracksStorage';
interface IButton { interface IButton {
loading: boolean; loading: boolean;
@ -41,6 +37,23 @@ interface IMessageAudioProps {
scale?: number; scale?: number;
} }
interface IMessageAudioState {
loading: boolean;
currentTime: number;
duration: number;
paused: boolean;
}
const mode = {
allowsRecordingIOS: false,
playsInSilentModeIOS: true,
staysActiveInBackground: true,
shouldDuckAndroid: true,
playThroughEarpieceAndroid: false,
interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX
};
const styles = StyleSheet.create({ const styles = StyleSheet.create({
audioContainer: { audioContainer: {
flex: 1, flex: 1,
@ -63,9 +76,6 @@ const styles = StyleSheet.create({
marginHorizontal: 12, marginHorizontal: 12,
fontSize: 14, fontSize: 14,
...sharedStyles.textRegular ...sharedStyles.textRegular
},
slider: {
flex: 1
} }
}); });
@ -94,167 +104,162 @@ const Button = React.memo(({ loading, paused, onPress, disabled, theme }: IButto
Button.displayName = 'MessageAudioButton'; Button.displayName = 'MessageAudioButton';
const MessageAudio = ({ class MessageAudio extends React.Component<IMessageAudioProps, IMessageAudioState> {
file, static contextType = MessageContext;
isReply,
style,
theme,
getCustomEmoji
}: // scale
IMessageAudioProps) => {
const { baseUrl, user } = useContext(MessageContext);
const [loading, setLoading] = useState(false); private sound: Sound;
const [paused, setPaused] = useState(true);
const [currentPosition, setCurrentPosition] = useState(0);
const [duration, setDuration] = useState(0);
const [isSliding, setIsSliding] = useState(false);
const { position } = useProgress();
const [currentTrackId, setCurrentTrackId] = useTracks('currentTrackId'); constructor(props: IMessageAudioProps) {
super(props);
this.state = {
loading: false,
currentTime: 0,
duration: 0,
paused: true
};
this.sound = new Audio.Sound();
this.sound.setOnPlaybackStatusUpdate(this.onPlaybackStatusUpdate);
}
async componentDidMount() {
const { file } = this.props;
const { baseUrl, user } = this.context;
let url = file.audio_url; let url = file.audio_url;
if (url && !url.startsWith('http')) { if (url && !url.startsWith('http')) {
url = `${baseUrl}${file.audio_url}`; url = `${baseUrl}${file.audio_url}`;
} }
const track = { this.setState({ loading: true });
id: `${url}?rc_uid=${user.id}&rc_token=${user.token}`,
url: `${url}?rc_uid=${user.id}&rc_token=${user.token}`,
title: file.title,
artist: file.author_name
};
const updateTrackDuration = (status: AVPlaybackStatus) => {
if (status.isLoaded && status.durationMillis) {
const trackDuration = status.durationMillis / 1000;
setDuration(trackDuration > 0 ? trackDuration : 0);
}
};
useEffect(() => {
const setup = async () => {
setLoading(true);
try { try {
await setupService(); await this.sound.loadAsync({ uri: `${url}?rc_uid=${user.id}&rc_token=${user.token}` });
const sound = new Audio.Sound();
sound.setOnPlaybackStatusUpdate(updateTrackDuration);
await sound.loadAsync({ uri: `${url}?rc_uid=${user.id}&rc_token=${user.token}` });
if (!isReply) {
const index = await TrackPlayer.add(track);
// @ts-ignore
index >= 0 && addTrack({ trackIndex: index, trackId: track.id });
}
} catch { } catch {
// Do nothing // Do nothing
} }
setLoading(false); this.setState({ loading: false });
};
setup();
return () => {
TrackPlayer.destroy();
clearTracks();
setCurrentTrackId(null);
};
}, []);
useEffect(() => {
if (!currentTrackId || currentTrackId !== track.id) {
setCurrentPosition(0);
setPaused(true);
} }
}, [currentTrackId]);
useEffect(() => { shouldComponentUpdate(nextProps: IMessageAudioProps, nextState: IMessageAudioState) {
if (currentTrackId === track.id && !isSliding) { const { currentTime, duration, paused, loading } = this.state;
setCurrentPosition(position); const { file, theme } = this.props;
if (nextProps.theme !== theme) {
return true;
}
if (nextState.currentTime !== currentTime) {
return true;
}
if (nextState.duration !== duration) {
return true;
}
if (nextState.paused !== paused) {
return true;
}
if (!dequal(nextProps.file, file)) {
return true;
}
if (nextState.loading !== loading) {
return true;
}
return false;
} }
}, [position]);
useEffect(() => { componentDidUpdate() {
playPause(); const { paused } = this.state;
}, [paused]);
useEffect(() => {
if (paused) { if (paused) {
deactivateKeepAwake(); deactivateKeepAwake();
} else { } else {
activateKeepAwake(); activateKeepAwake();
} }
}, [paused, currentPosition, duration, file, loading, theme]); }
useTrackPlayerEvents([Event.PlaybackState], ({ state }) => { async componentWillUnmount() {
if (state === State.Stopped) {
try { try {
TrackPlayer.stop(); await this.sound.stopAsync();
setPaused(true); } catch {
// Do nothing
}
}
onPlaybackStatusUpdate = (status: AVPlaybackStatus) => {
if (status) {
this.onLoad(status);
this.onProgress(status);
this.onEnd(status);
}
};
onLoad = (data: AVPlaybackStatus) => {
if (data.isLoaded && data.durationMillis) {
const duration = data.durationMillis / 1000;
this.setState({ duration: duration > 0 ? duration : 0 });
}
};
onProgress = (data: AVPlaybackStatus) => {
if (data.isLoaded) {
const { duration } = this.state;
const currentTime = data.positionMillis / 1000;
if (currentTime <= duration) {
this.setState({ currentTime });
}
}
};
onEnd = async (data: AVPlaybackStatus) => {
if (data.isLoaded) {
if (data.didJustFinish) {
try {
await this.sound.stopAsync();
this.setState({ paused: true, currentTime: 0 });
} catch { } catch {
// do nothing // do nothing
} }
} }
if (state === State.Paused) {
setPaused(true);
} }
if (state === State.Playing && currentTrackId?.trackId === track.id) {
setPaused(false);
}
});
const getDuration = () => formatTime(currentPosition || duration);
const togglePlayPause = () => {
setPaused(!paused);
}; };
const playPause = async () => { get duration() {
const { currentTime, duration } = this.state;
return formatTime(currentTime || duration);
}
togglePlayPause = () => {
const { paused } = this.state;
this.setState({ paused: !paused }, this.playPause);
};
playPause = async () => {
const { paused } = this.state;
try { try {
if (paused) { if (paused) {
if (currentTrackId === track.id) { await this.sound.pauseAsync();
TrackPlayer.pause();
}
} else if (currentTrackId === track.id) {
TrackPlayer.play();
} else { } else {
const index = getTrackIndex(track.id); await Audio.setAudioModeAsync(mode);
index && TrackPlayer.skip(index); await this.sound.playAsync();
if (currentPosition > 0) await TrackPlayer.seekTo(currentPosition);
TrackPlayer.play();
setCurrentTrackId(track.id);
} }
} catch { } catch {
// Do nothing // Do nothing
} }
}; };
const onValueChange = (value: number) => { onValueChange = (value: number) => {
setCurrentPosition(value); this.setState({ currentTime: value });
};
onSlidingEnd = async (value: number) => {
try { try {
if (currentTrackId === track.id && !paused && isSliding) { await this.sound.setPositionAsync(value * 1000);
setPaused(true);
TrackPlayer.pause();
}
} catch { } catch {
// Do nothing // Do nothing
} }
}; };
const onSlidingEnd = async (value: number) => { render() {
setCurrentPosition(value); const { loading, paused, currentTime, duration } = this.state;
try { const { file, getCustomEmoji, theme, scale, isReply, style } = this.props;
if (currentTrackId === track.id) {
await TrackPlayer.seekTo(value);
if (paused) {
TrackPlayer.play();
setPaused(false);
}
}
} catch {
// Do nothing
}
setIsSliding(false);
};
const { description } = file; const { description } = file;
const { baseUrl, user } = this.context;
if (!baseUrl) { if (!baseUrl) {
return null; return null;
@ -267,11 +272,6 @@ IMessageAudioProps) => {
thumbColor = themes[theme].tintColor; thumbColor = themes[theme].tintColor;
} }
const sliderAnimatedConfig = {
duration: 250,
easing: Easing.linear
};
return ( return (
<> <>
<Markdown <Markdown
@ -287,24 +287,23 @@ IMessageAudioProps) => {
styles.audioContainer, styles.audioContainer,
{ backgroundColor: themes[theme].chatComponentBackground, borderColor: themes[theme].borderColor } { backgroundColor: themes[theme].chatComponentBackground, borderColor: themes[theme].borderColor }
]}> ]}>
<Button disabled={isReply} loading={loading} paused={paused} onPress={togglePlayPause} theme={theme} /> <Button disabled={isReply} loading={loading} paused={paused} onPress={this.togglePlayPause} theme={theme} />
<Slider <Slider
value={currentPosition}
maximumValue={duration}
onValueChange={onValueChange}
thumbTintColor={thumbColor}
minimumTrackTintColor={themes[theme].tintColor}
disabled={isReply} disabled={isReply}
maximumTrackTintColor={themes[theme].auxiliaryText} value={currentTime}
animationConfig={sliderAnimatedConfig} maximumValue={duration}
onSlidingStart={() => setIsSliding(true)} thumbTintColor={thumbColor}
onSlidingEnd={onSlidingEnd} trackColor={themes[theme].auxiliaryText}
// thumbImage={isIOS ? { uri: 'audio_thumb', scale } : undefined} activeTrackColor={themes[theme].tintColor}
onValueChange={this.onValueChange}
onSlidingEnd={this.onSlidingEnd}
thumbImage={isIOS ? { uri: 'audio_thumb', scale } : undefined}
/> />
<Text style={[styles.duration, { color: themes[theme].auxiliaryText }]}>{getDuration()}</Text> <Text style={[styles.duration, { color: themes[theme].auxiliaryText }]}>{this.duration}</Text>
</View> </View>
</> </>
); );
}; }
}
export default MessageAudio; export default withDimensions(MessageAudio);

View File

@ -1,44 +0,0 @@
import TrackPlayer, { Event, State, Capability } from 'react-native-track-player';
import { clearTracks } from './tracksStorage';
let wasPausedByDuck = false;
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
// eslint-disable-next-line require-await
export const playbackService = async () => {
TrackPlayer.addEventListener(Event.RemotePause, () => {
TrackPlayer.pause();
});
TrackPlayer.addEventListener(Event.RemotePlay, () => {
TrackPlayer.play();
});
TrackPlayer.addEventListener(Event.RemoteStop, () => {
clearTracks();
TrackPlayer.destroy();
});
TrackPlayer.addEventListener(Event.RemoteDuck, async e => {
if (e.permanent === true) {
TrackPlayer.stop();
} else if (e.paused === true) {
const playerState = await TrackPlayer.getState();
wasPausedByDuck = playerState !== State.Paused;
TrackPlayer.pause();
} else if (wasPausedByDuck === true) {
TrackPlayer.play();
wasPausedByDuck = false;
}
});
};
export const setupService = async () => {
await TrackPlayer.setupPlayer();
await TrackPlayer.updateOptions({
stopWithApp: true,
capabilities: [Capability.Play, Capability.Pause, Capability.Stop],
compactCapabilities: [Capability.Play, Capability.Pause]
});
};

View File

@ -1,35 +0,0 @@
import MMKVStorage, { create } from 'react-native-mmkv-storage';
interface Track {
trackId: string;
trackIndex: number;
}
const TracksStorage = new MMKVStorage.Loader().withInstanceID('tracks').initialize();
export const useTracks = create(TracksStorage);
export const initializeTracks = () => {
const tracks = TracksStorage.getArray('tracks');
if (!tracks) TracksStorage.setArray('tracks', []);
};
export const addTrack = (track: Track) => {
initializeTracks();
const tracks: Track[] = TracksStorage.getArray('tracks') || [];
if (tracks.find((t: Track) => t.trackId === track.trackId)) {
return;
}
TracksStorage.setArray('tracks', [...tracks, track]);
};
export const getTrackIndex = (trackId: string) => {
const tracks: Track[] = TracksStorage.getArray('tracks') || [];
const index = tracks.findIndex((t: Track) => t.trackId === trackId);
if (index !== -1) {
return tracks[index].trackIndex;
}
};
export const clearTracks = () => {
TracksStorage.setArray('tracks', []);
};

View File

@ -180,8 +180,7 @@ export default StyleSheet.create({
justifyContent: 'center' justifyContent: 'center'
}, },
activeTrack: { activeTrack: {
height: 2, height: 2
width: 0
}, },
sliderThumb: { sliderThumb: {
height: SLIDER_THUMB_RADIUS * 2, height: SLIDER_THUMB_RADIUS * 2,

View File

@ -1,10 +1,8 @@
import 'react-native-gesture-handler'; import 'react-native-gesture-handler';
import 'react-native-console-time-polyfill'; import 'react-native-console-time-polyfill';
import { AppRegistry } from 'react-native'; import { AppRegistry } from 'react-native';
import TrackPlayer from 'react-native-track-player';
import { name as appName, share as shareName } from './app.json'; import { name as appName, share as shareName } from './app.json';
import { playbackService } from './app/containers/message/Components/Audio/services';
if (__DEV__) { if (__DEV__) {
require('./app/ReactotronConfig'); require('./app/ReactotronConfig');
@ -23,8 +21,6 @@ if (__DEV__) {
AppRegistry.registerComponent(appName, () => require('./app/index').default); AppRegistry.registerComponent(appName, () => require('./app/index').default);
AppRegistry.registerComponent(shareName, () => require('./app/share').default); AppRegistry.registerComponent(shareName, () => require('./app/share').default);
TrackPlayer.registerPlaybackService(() => playbackService);
// For storybook, comment everything above and uncomment below // For storybook, comment everything above and uncomment below
// import 'react-native-gesture-handler'; // import 'react-native-gesture-handler';
// import 'react-native-console-time-polyfill'; // import 'react-native-console-time-polyfill';

View File

@ -14,9 +14,6 @@ jest.mock('react-native-mmkv-storage', () => ({
withEncryption: jest.fn().mockImplementation(() => ({ withEncryption: jest.fn().mockImplementation(() => ({
initialize: jest.fn() initialize: jest.fn()
})) }))
})),
withInstanceID: jest.fn().mockImplementation(() => ({
initialize: jest.fn()
})) }))
})), })),
create: jest.fn(), create: jest.fn(),
@ -82,45 +79,5 @@ jest.mock('react-native-math-view', () => {
MathText: react.View // {...} Named export MathText: react.View // {...} Named export
}; };
}); });
jest.mock('react-native-track-player', () => ({
__esModule: true,
default: {
addEventListener: () => ({
remove: jest.fn()
}),
registerEventHandler: jest.fn(),
registerPlaybackService: jest.fn(),
setupPlayer: jest.fn(),
destroy: jest.fn(),
updateOptions: jest.fn(),
reset: jest.fn(),
add: jest.fn(),
remove: jest.fn(),
skip: jest.fn(),
skipToNext: jest.fn(),
skipToPrevious: jest.fn(),
removeUpcomingTracks: jest.fn(),
play: jest.fn(),
pause: jest.fn(),
stop: jest.fn(),
seekTo: jest.fn(),
setVolume: jest.fn(),
setRate: jest.fn(),
getQueue: jest.fn(),
getTrack: jest.fn(),
getCurrentTrack: jest.fn(),
getVolume: jest.fn(),
getDuration: jest.fn(),
getPosition: jest.fn(),
getBufferedPosition: jest.fn(),
getState: jest.fn(),
getRate: jest.fn()
},
useProgress: () => ({
position: 100
})
}));
jest.mock('./app/containers/message/Components/Audio/tracksStorage.ts', () => ({ jest.mock('react-native-gesture-handler', () => jest.fn(() => null));
useTracks: () => ['', jest.fn()]
}));

View File

@ -220,7 +220,8 @@
}, },
"setupFilesAfterEnv": [ "setupFilesAfterEnv": [
"@testing-library/jest-native/extend-expect", "@testing-library/jest-native/extend-expect",
"./jest.setup.js" "./jest.setup.js",
"./node_modules/react-native-gesture-handler/jestSetup.js"
] ]
}, },
"snyk": true, "snyk": true,