Rocket.Chat.ReactNative/app/containers/message/Components/Audio/index.tsx

286 lines
7.3 KiB
TypeScript
Raw Normal View History

2023-08-02 19:50:20 +00:00
import React, { useContext, useEffect, useRef, useState } from 'react';
2023-08-07 23:57:15 +00:00
import { StyleProp, TextStyle, View } from 'react-native';
import { Audio, AVPlaybackStatus, InterruptionModeAndroid, InterruptionModeIOS } from 'expo-av';
2023-08-04 21:39:23 +00:00
import { activateKeepAwakeAsync, deactivateKeepAwake } from 'expo-keep-awake';
import { Sound } from 'expo-av/build/Audio/Sound';
import Touchable from '../../Touchable';
import Markdown from '../../../markdown';
import { CustomIcon } from '../../../CustomIcon';
import { themes } from '../../../../lib/constants';
import MessageContext from '../../Context';
import ActivityIndicator from '../../../ActivityIndicator';
import { TGetCustomEmoji } from '../../../../definitions/IEmoji';
import { IAttachment, IUserMessage } from '../../../../definitions';
import { useTheme } from '../../../../theme';
import { downloadMediaFile, getMediaCache } from '../../../../lib/methods/handleMediaDownload';
import EventEmitter from '../../../../lib/methods/helpers/events';
import { PAUSE_AUDIO } from '../../constants';
import { fetchAutoDownloadEnabled } from '../../../../lib/methods/autoDownloadPreference';
2023-08-07 23:57:15 +00:00
import styles from './styles';
import Slider from './Slider';
interface IButton {
loading: boolean;
paused: boolean;
2022-03-21 20:44:06 +00:00
disabled?: boolean;
onPress: () => void;
cached: boolean;
}
interface IMessageAudioProps {
2022-03-21 20:44:06 +00:00
file: IAttachment;
isReply?: boolean;
style?: StyleProp<TextStyle>[];
getCustomEmoji: TGetCustomEmoji;
author?: IUserMessage;
}
const mode = {
allowsRecordingIOS: false,
playsInSilentModeIOS: true,
staysActiveInBackground: true,
shouldDuckAndroid: true,
playThroughEarpieceAndroid: false,
interruptionModeIOS: InterruptionModeIOS.DoNotMix,
interruptionModeAndroid: InterruptionModeAndroid.DoNotMix
};
const BUTTON_HIT_SLOP = { top: 12, right: 12, bottom: 12, left: 12 };
const Button = React.memo(({ loading, paused, onPress, disabled, cached }: IButton) => {
const { colors } = useTheme();
let customIconName: 'arrow-down-circle' | 'play-filled' | 'pause-filled' = 'arrow-down-circle';
if (cached) {
customIconName = paused ? 'play-filled' : 'pause-filled';
}
2023-05-11 18:52:48 +00:00
return (
<Touchable
style={styles.playPauseButton}
disabled={disabled}
onPress={onPress}
hitSlop={BUTTON_HIT_SLOP}
background={Touchable.SelectableBackgroundBorderless()}
>
2023-05-11 18:52:48 +00:00
{loading ? (
<ActivityIndicator style={[styles.playPauseButton, styles.audioLoading]} />
) : (
<CustomIcon name={customIconName} size={36} color={disabled ? colors.tintDisabled : colors.tintColor} />
2023-05-11 18:52:48 +00:00
)}
</Touchable>
);
});
Button.displayName = 'MessageAudioButton';
2023-08-02 19:50:20 +00:00
const MessageAudio = ({ file, getCustomEmoji, author, isReply, style }: IMessageAudioProps) => {
const [loading, setLoading] = useState(true);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const [paused, setPaused] = useState(true);
const [cached, setCached] = useState(false);
2023-08-02 19:50:20 +00:00
const { baseUrl, user } = useContext(MessageContext);
const { theme } = useTheme();
2023-05-11 18:52:48 +00:00
2023-08-02 19:50:20 +00:00
const sound = useRef<Sound | null>(null);
2023-08-02 19:50:20 +00:00
const pauseSound = () => {
EventEmitter.removeListener(PAUSE_AUDIO, pauseSound);
togglePlayPause();
};
2023-08-02 19:50:20 +00:00
const onPlaybackStatusUpdate = (status: AVPlaybackStatus) => {
if (status) {
onLoad(status);
onProgress(status);
onEnd(status);
}
2023-08-02 19:50:20 +00:00
};
2023-08-02 19:50:20 +00:00
const getUrl = () => {
let url = file.audio_url;
if (url && !url.startsWith('http')) {
url = `${baseUrl}${file.audio_url}`;
}
return url;
};
2023-08-02 19:50:20 +00:00
const onLoad = (data: AVPlaybackStatus) => {
if (data.isLoaded && data.durationMillis) {
const duration = data.durationMillis / 1000;
2023-08-02 19:50:20 +00:00
setDuration(duration > 0 ? duration : 0);
}
};
2023-08-02 19:50:20 +00:00
const onProgress = (data: AVPlaybackStatus) => {
if (data.isLoaded) {
const currentTime = data.positionMillis / 1000;
2023-08-07 23:57:15 +00:00
console.log('🚀 ~ file: index.tsx:120 ~ onProgress ~ currentTime:', currentTime);
if (currentTime <= duration) {
2023-08-02 19:50:20 +00:00
setCurrentTime(currentTime);
}
}
};
2023-08-02 19:50:20 +00:00
const onEnd = async (data: AVPlaybackStatus) => {
if (data.isLoaded) {
if (data.didJustFinish) {
try {
2023-08-02 19:50:20 +00:00
await sound.current?.stopAsync();
setPaused(true);
setCurrentTime(0);
EventEmitter.removeListener(PAUSE_AUDIO, pauseSound);
} catch {
// do nothing
}
}
}
};
2023-08-02 19:50:20 +00:00
const togglePlayPause = () => {
setPaused(!paused);
2023-08-04 21:39:23 +00:00
playPause(!paused);
};
const playPause = async (isPaused: boolean) => {
try {
if (isPaused) {
await sound.current?.pauseAsync();
EventEmitter.removeListener(PAUSE_AUDIO, pauseSound);
} else {
EventEmitter.emit(PAUSE_AUDIO);
EventEmitter.addEventListener(PAUSE_AUDIO, pauseSound);
await Audio.setAudioModeAsync(mode);
await sound.current?.playAsync();
}
} catch {
// Do nothing
}
};
2023-08-02 19:50:20 +00:00
const handleDownload = async () => {
setLoading(true);
2023-05-19 14:35:36 +00:00
try {
2023-08-02 19:50:20 +00:00
const url = getUrl();
if (url) {
2023-05-19 14:35:36 +00:00
const audio = await downloadMediaFile({
downloadUrl: `${url}?rc_uid=${user.id}&rc_token=${user.token}`,
type: 'audio',
mimeType: file.audio_type
2023-05-19 14:35:36 +00:00
});
2023-08-02 19:50:20 +00:00
await sound.current?.loadAsync({ uri: audio });
setLoading(false);
setCached(true);
2023-05-19 05:42:21 +00:00
}
2023-05-19 14:35:36 +00:00
} catch {
2023-08-02 19:50:20 +00:00
setLoading(false);
setCached(false);
}
2023-05-11 18:52:48 +00:00
};
2023-08-02 19:50:20 +00:00
const handleAutoDownload = async () => {
const url = getUrl();
try {
2023-08-02 19:50:20 +00:00
if (url) {
const isCurrentUserAuthor = author?._id === user.id;
const isAutoDownloadEnabled = fetchAutoDownloadEnabled('audioPreferenceDownload');
if (isAutoDownloadEnabled || isCurrentUserAuthor) {
await handleDownload();
return;
}
setLoading(false);
setCached(false);
}
} catch {
// Do nothing
}
};
2023-08-02 19:50:20 +00:00
const onPress = () => {
if (cached) {
togglePlayPause();
return;
}
handleDownload();
};
useEffect(() => {
sound.current = new Audio.Sound();
sound.current?.setOnPlaybackStatusUpdate(onPlaybackStatusUpdate);
const handleCache = async () => {
const cachedAudioResult = await getMediaCache({
type: 'audio',
mimeType: file.audio_type,
urlToCache: getUrl()
});
if (cachedAudioResult?.exists) {
await sound.current?.loadAsync({ uri: cachedAudioResult.uri });
setLoading(false);
setCached(true);
return;
}
if (isReply) {
setLoading(false);
return;
}
await handleAutoDownload();
};
handleCache();
2023-08-04 21:39:23 +00:00
return () => {
EventEmitter.removeListener(PAUSE_AUDIO, pauseSound);
2023-08-02 19:50:20 +00:00
try {
2023-08-04 21:39:23 +00:00
sound.current?.stopAsync();
2023-08-02 19:50:20 +00:00
} catch {
// Do nothing
}
};
2023-08-04 21:39:23 +00:00
}, []);
useEffect(() => {
2023-08-02 19:50:20 +00:00
if (paused) {
deactivateKeepAwake();
} else {
2023-08-04 21:39:23 +00:00
activateKeepAwakeAsync();
}
2023-08-02 19:50:20 +00:00
}, [paused]);
2023-08-02 19:50:20 +00:00
if (!baseUrl) {
return null;
}
2023-08-02 19:50:20 +00:00
let thumbColor;
2023-08-07 23:57:15 +00:00
if (isReply) {
2023-08-02 19:50:20 +00:00
thumbColor = themes[theme].tintDisabled;
2023-08-07 23:57:15 +00:00
} else {
2023-08-02 19:50:20 +00:00
thumbColor = themes[theme].tintColor;
}
2019-11-25 20:01:17 +00:00
2023-08-02 19:50:20 +00:00
return (
<>
<Markdown
msg={file.description}
style={[isReply && style]}
username={user.username}
getCustomEmoji={getCustomEmoji}
theme={theme}
/>
<View
style={[
styles.audioContainer,
{ backgroundColor: themes[theme].chatComponentBackground, borderColor: themes[theme].borderColor }
]}
>
<Button disabled={isReply} loading={loading} paused={paused} cached={cached} onPress={onPress} />
2023-08-07 23:57:15 +00:00
<Slider currentTime={currentTime} duration={duration} thumbColor={thumbColor} />
<View style={{ width: 36, height: 24, backgroundColor: '#999', borderRadius: 4, marginRight: 16 }} />
2023-08-02 19:50:20 +00:00
</View>
</>
);
};
export default MessageAudio;