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

397 lines
10 KiB
TypeScript
Raw Normal View History

import React from 'react';
import { StyleProp, StyleSheet, Text, TextStyle, View } from 'react-native';
import { Audio, AVPlaybackStatus, InterruptionModeAndroid, InterruptionModeIOS } from 'expo-av';
import Slider from '@react-native-community/slider';
import moment from 'moment';
import { dequal } from 'dequal';
import { activateKeepAwake, 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';
2019-03-29 19:36:07 +00:00
import sharedStyles from '../../views/Styles';
import { themes } from '../../lib/constants';
import { isAndroid, isIOS } from '../../lib/methods/helpers';
import MessageContext from './Context';
import ActivityIndicator from '../ActivityIndicator';
import { withDimensions } from '../../dimensions';
import { TGetCustomEmoji } from '../../definitions/IEmoji';
import { IAttachment, IUserMessage } from '../../definitions';
import { TSupportedThemes, useTheme } from '../../theme';
import { MediaTypes, downloadMediaFile, searchMediaFileAsync } from '../../lib/methods/handleMediaDownload';
import EventEmitter from '../../lib/methods/helpers/events';
import { PAUSE_AUDIO } from './constants';
import { fetchAutoDownloadEnabled } from '../../lib/methods/autoDownloadPreference';
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>[];
theme: TSupportedThemes;
getCustomEmoji: TGetCustomEmoji;
scale?: number;
messageId: string;
author?: IUserMessage;
}
interface IMessageAudioState {
loading: boolean;
currentTime: number;
duration: number;
paused: boolean;
cached: boolean;
}
const mode = {
allowsRecordingIOS: false,
playsInSilentModeIOS: true,
staysActiveInBackground: true,
shouldDuckAndroid: true,
playThroughEarpieceAndroid: false,
interruptionModeIOS: InterruptionModeIOS.DoNotMix,
interruptionModeAndroid: InterruptionModeAndroid.DoNotMix
};
const styles = StyleSheet.create({
audioContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
height: 56,
2019-03-29 19:36:07 +00:00
borderWidth: 1,
borderRadius: 4,
2019-03-29 19:36:07 +00:00
marginBottom: 6
},
playPauseButton: {
marginHorizontal: 10,
alignItems: 'center',
backgroundColor: 'transparent'
},
audioLoading: {
marginHorizontal: 8
},
slider: {
flex: 1
},
duration: {
marginHorizontal: 12,
fontSize: 14,
2019-03-29 19:36:07 +00:00
...sharedStyles.textRegular
}
});
const formatTime = (seconds: number) => moment.utc(seconds * 1000).format('mm:ss');
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';
class MessageAudio extends React.Component<IMessageAudioProps, IMessageAudioState> {
static contextType = MessageContext;
private sound: Sound;
2023-05-19 05:42:21 +00:00
private filePath?: string;
constructor(props: IMessageAudioProps) {
super(props);
this.state = {
2023-05-19 05:42:21 +00:00
loading: true,
currentTime: 0,
duration: 0,
2023-05-11 18:52:48 +00:00
paused: true,
cached: true
};
this.sound = new Audio.Sound();
this.sound.setOnPlaybackStatusUpdate(this.onPlaybackStatusUpdate);
}
pauseSound = () => {
EventEmitter.removeListener(PAUSE_AUDIO, this.pauseSound);
this.togglePlayPause();
};
async componentDidMount() {
2023-05-19 05:42:21 +00:00
const { messageId, file } = this.props;
const fileSearch = await searchMediaFileAsync({
type: MediaTypes.audio,
mimeType: file.audio_type,
messageId
});
this.filePath = fileSearch.filePath;
if (fileSearch?.file?.exists) {
2023-05-19 14:52:22 +00:00
await this.sound.loadAsync({ uri: fileSearch.file.uri });
2023-05-19 05:42:21 +00:00
return this.setState({ loading: false });
}
2023-05-11 18:52:48 +00:00
await this.handleAutoDownload();
}
getUrl = () => {
const { file } = this.props;
2023-05-19 16:01:38 +00:00
// @ts-ignore can't use declare to type this
2023-05-11 18:52:48 +00:00
const { baseUrl } = this.context;
let url = file.audio_url;
2022-03-21 20:44:06 +00:00
if (url && !url.startsWith('http')) {
url = `${baseUrl}${file.audio_url}`;
}
2023-05-11 18:52:48 +00:00
return url;
};
2023-05-11 18:52:48 +00:00
handleAutoDownload = async () => {
2023-05-19 05:42:21 +00:00
const { author } = this.props;
2023-05-19 16:01:38 +00:00
// @ts-ignore can't use declare to type this
const { user } = this.context;
2023-05-11 18:52:48 +00:00
const url = this.getUrl();
try {
if (url) {
const isCurrentUserAuthor = author?._id === user.id;
const autoDownload = fetchAutoDownloadEnabled('audioPreferenceDownload');
if (autoDownload || isCurrentUserAuthor) {
2023-05-30 14:07:34 +00:00
await this.startDownload();
return;
2023-05-11 18:52:48 +00:00
}
// MediaDownloadOption.NEVER or MediaDownloadOption.WIFI and the mobile is using mobile data
return this.setState({ loading: false, cached: false });
}
} catch {
// Do nothing
}
2023-05-11 18:52:48 +00:00
};
shouldComponentUpdate(nextProps: IMessageAudioProps, nextState: IMessageAudioState) {
const { currentTime, duration, paused, loading, cached } = this.state;
[CHORE] Update react-navigation to v5 (#2154) * react-navigation v5 installed * compiling * Outside working * InsideStack compiling * Switch stack * Starting room * RoomView header * SafeAreaView * Slide from right stack animation * stash * Fix params * Create channel * inapp notification * Custom status * Add server working * Refactor appStart * Attachment * in-app notification * AuthLoadingView * Remove compat * Navigation * Outside animations * Fix new server icon * block modal * AttachmentView header * Remove unnecessary code * SelectedUsersView header * StatusView * CreateDiscussionView * RoomInfoView * RoomInfoEditView style * RoomMembersView * RoomsListView header * RoomView header * Share extension * getParam * Focus/blur * Trying to fix inapp * Lint * Simpler app container * Update libs * Revert "Simpler app container" This reverts commit 1e49d80bb49481c34f415831b9da5e9d53e66057. * Load messages faster * Fix safearea on ReactionsModal * Update safe area to v3 * lint * Fix transition * stash - drawer replace working * stash - modal nav * RoomActionsView as tablet modal * RoomStack * Stop showing RoomView header when there's no room * Custom Header and different navigation based on stack * Refactor setHeader * MasterDetailContext * RoomView header * Fix isMasterDetail rule * KeyCommands kind of working * Create channel on tablet * RoomView sCU * Remove withSplit * Settings opening as modal * Settings * StatusView headerLeft * Admin panel * TwoFactor style * DirectoryView * ServerDropdown and SortDropdown animations * ThreadMessagesView * Navigate to empty RoomView on server switch when in master detail * ProfileView header * Fix navigation issues * Nav to any room info on tablet * Room info * Refactoring * Fix rooms search * Roomslist commands * SearchMessagesView close modal * Key commands * Fix undefined subscription * Disallow navigate to focused room * isFocused state on RoomsListView * Blur text inputs when focus is lost * Replace animation * Default nav theme * Refactoring * Always open Attachment with close modal button * ModalContainer backdrop following themes * Screen tracking * Refactor get active route for in-app notification * Only mark room as focused when in master detail layout * Lint * Open modals as fade from bottom on Android * typo * Fixing tests * Fix in-app update * Fixing goRoom issues * Refactor stack names * Fix unreadsCount * Fix stack * Fix header animation * Refactor ShareNavigation * Refactor navigation theme * Make sure title is set * Fix create discussion navigation * Remove unused variable * Create discussions from actions fixed * Layout animation * Screen lock on share extension * Unnecessary change * Admin border * Set header after state callback * Fix key commands on outside stack * Fix back button pressed * Remove layout animations from Android * Tweak animations on Android * Disable swipe gesture to open drawer * Fix current item on RoomsListView * Fix add server * Fix drawer * Fix broadcast * LayoutAnimation instead of Transitions * Fix onboarding back press * Fix assorted tests * Create discussion fix * RoomInfoView header * Drawer active item
2020-06-15 14:00:46 +00:00
const { file, theme } = this.props;
2019-12-04 16:39:53 +00:00
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;
}
if (nextState.cached !== cached) {
2023-05-19 05:42:21 +00:00
return true;
}
return false;
}
componentDidUpdate() {
const { paused } = this.state;
if (paused) {
deactivateKeepAwake();
} else {
activateKeepAwake();
}
}
async componentWillUnmount() {
EventEmitter.removeListener(PAUSE_AUDIO, this.pauseSound);
try {
await this.sound.stopAsync();
} 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 });
EventEmitter.removeListener(PAUSE_AUDIO, this.pauseSound);
} catch {
// do nothing
}
}
}
};
get duration() {
const { currentTime, duration } = this.state;
return formatTime(currentTime || duration);
}
togglePlayPause = () => {
const { paused } = this.state;
this.setState({ paused: !paused }, this.playPause);
};
2023-05-11 18:52:48 +00:00
startDownload = async () => {
2023-05-19 05:42:21 +00:00
const { messageId } = this.props;
2023-05-19 16:01:38 +00:00
// @ts-ignore can't use declare to type this
2023-05-11 18:52:48 +00:00
const { user } = this.context;
this.setState({ loading: true });
2023-05-19 14:35:36 +00:00
try {
const url = this.getUrl();
if (url && this.filePath) {
const audio = await downloadMediaFile({
downloadUrl: `${url}?rc_uid=${user.id}&rc_token=${user.token}`,
mediaType: MediaTypes.audio,
messageId,
path: this.filePath
});
await this.sound.loadAsync({ uri: audio });
return this.setState({ loading: false, cached: true });
2023-05-19 05:42:21 +00:00
}
2023-05-19 14:35:36 +00:00
} catch {
return this.setState({ loading: false, cached: false });
2023-05-11 18:52:48 +00:00
}
};
onPress = () => {
const { cached } = this.state;
return cached ? this.togglePlayPause() : this.startDownload();
2023-05-11 18:52:48 +00:00
};
playPause = async () => {
const { paused } = this.state;
try {
if (paused) {
await this.sound.pauseAsync();
EventEmitter.removeListener(PAUSE_AUDIO, this.pauseSound);
} else {
EventEmitter.emit(PAUSE_AUDIO);
EventEmitter.addEventListener(PAUSE_AUDIO, this.pauseSound);
await Audio.setAudioModeAsync(mode);
await this.sound.playAsync();
}
} catch {
// Do nothing
}
};
onValueChange = async (value: number) => {
try {
this.setState({ currentTime: value });
await this.sound.setPositionAsync(value * 1000);
} catch {
// Do nothing
}
};
render() {
const { loading, paused, currentTime, duration, cached } = this.state;
2022-03-21 20:44:06 +00:00
const { file, getCustomEmoji, theme, scale, isReply, style } = this.props;
const { description } = file;
// @ts-ignore can't use declare to type this
const { baseUrl, user } = this.context;
if (!baseUrl) {
return null;
}
let thumbColor;
if (isAndroid && isReply) {
thumbColor = themes[theme].tintDisabled;
} else if (isAndroid) {
thumbColor = themes[theme].tintColor;
}
return (
<>
2022-03-21 20:44:06 +00:00
<Markdown
msg={description}
style={[isReply && style]}
username={user.username}
getCustomEmoji={getCustomEmoji}
theme={theme}
2022-03-21 20:44:06 +00:00
/>
2019-12-04 16:39:53 +00:00
<View
style={[
styles.audioContainer,
[CHORE] Update react-navigation to v5 (#2154) * react-navigation v5 installed * compiling * Outside working * InsideStack compiling * Switch stack * Starting room * RoomView header * SafeAreaView * Slide from right stack animation * stash * Fix params * Create channel * inapp notification * Custom status * Add server working * Refactor appStart * Attachment * in-app notification * AuthLoadingView * Remove compat * Navigation * Outside animations * Fix new server icon * block modal * AttachmentView header * Remove unnecessary code * SelectedUsersView header * StatusView * CreateDiscussionView * RoomInfoView * RoomInfoEditView style * RoomMembersView * RoomsListView header * RoomView header * Share extension * getParam * Focus/blur * Trying to fix inapp * Lint * Simpler app container * Update libs * Revert "Simpler app container" This reverts commit 1e49d80bb49481c34f415831b9da5e9d53e66057. * Load messages faster * Fix safearea on ReactionsModal * Update safe area to v3 * lint * Fix transition * stash - drawer replace working * stash - modal nav * RoomActionsView as tablet modal * RoomStack * Stop showing RoomView header when there's no room * Custom Header and different navigation based on stack * Refactor setHeader * MasterDetailContext * RoomView header * Fix isMasterDetail rule * KeyCommands kind of working * Create channel on tablet * RoomView sCU * Remove withSplit * Settings opening as modal * Settings * StatusView headerLeft * Admin panel * TwoFactor style * DirectoryView * ServerDropdown and SortDropdown animations * ThreadMessagesView * Navigate to empty RoomView on server switch when in master detail * ProfileView header * Fix navigation issues * Nav to any room info on tablet * Room info * Refactoring * Fix rooms search * Roomslist commands * SearchMessagesView close modal * Key commands * Fix undefined subscription * Disallow navigate to focused room * isFocused state on RoomsListView * Blur text inputs when focus is lost * Replace animation * Default nav theme * Refactoring * Always open Attachment with close modal button * ModalContainer backdrop following themes * Screen tracking * Refactor get active route for in-app notification * Only mark room as focused when in master detail layout * Lint * Open modals as fade from bottom on Android * typo * Fixing tests * Fix in-app update * Fixing goRoom issues * Refactor stack names * Fix unreadsCount * Fix stack * Fix header animation * Refactor ShareNavigation * Refactor navigation theme * Make sure title is set * Fix create discussion navigation * Remove unused variable * Create discussions from actions fixed * Layout animation * Screen lock on share extension * Unnecessary change * Admin border * Set header after state callback * Fix key commands on outside stack * Fix back button pressed * Remove layout animations from Android * Tweak animations on Android * Disable swipe gesture to open drawer * Fix current item on RoomsListView * Fix add server * Fix drawer * Fix broadcast * LayoutAnimation instead of Transitions * Fix onboarding back press * Fix assorted tests * Create discussion fix * RoomInfoView header * Drawer active item
2020-06-15 14:00:46 +00:00
{ backgroundColor: themes[theme].chatComponentBackground, borderColor: themes[theme].borderColor }
]}
>
<Button disabled={isReply} loading={loading} paused={paused} cached={cached} onPress={this.onPress} />
<Slider
2022-03-21 20:44:06 +00:00
disabled={isReply}
style={styles.slider}
value={currentTime}
maximumValue={duration}
minimumValue={0}
thumbTintColor={thumbColor}
2019-12-04 16:39:53 +00:00
minimumTrackTintColor={themes[theme].tintColor}
maximumTrackTintColor={themes[theme].auxiliaryText}
onValueChange={this.onValueChange}
2022-03-21 20:44:06 +00:00
thumbImage={isIOS ? { uri: 'audio_thumb', scale } : undefined}
/>
2019-12-04 16:39:53 +00:00
<Text style={[styles.duration, { color: themes[theme].auxiliaryText }]}>{this.duration}</Text>
</View>
</>
);
}
}
2019-11-25 20:01:17 +00:00
export default withDimensions(MessageAudio);