Rocket.Chat.ReactNative/app/views/ShareListView/index.js

417 lines
11 KiB
JavaScript
Raw Normal View History

[RELEASE] Merge beta into master (#1082) * Bump version to 1.16.0 (#1014) * [IMPROVEMENT] Share credentials with Rocket.Chat.iOS (#982) * :sparkles: Create user table * :sparkles: Introduce user table * :fire: Remove unused table * :heavy_plus_sign: Add userdefaults to storage data * :green_heart: Fix android build * :sparkles: Get credentials from iOS native client * :fire: Remove unused code * :rewind: Revert sign xcode * :bug: Fix first login-logout * :art: Use constants to UserDefaults Keys * :bug: Fix clear server-user-info on logout * :bug: Fix filter null value * :ambulance: Remove user object in logout * :sparkles: Fix get servers from native-client * :ambulance: Fix error on change server * [FIX] Don't run UserDefaults credentials on Android (#1015) * :bug: Fix native credentials (android) * Fix migration loop * [IMPROVEMENT] Hide frequently used emoji tab when empty (#792) * [IMPROVEMENT] Bigger emoji in emoji only messages (#793) * issue #725: bigger emoji in emoji only message * issue-725/add storybook for Message/Emoji * issue-725: update storybook/Message jest snapshot * comment storybook import * allow spaces and line breaks in emoji only message * merge develop * revert unnecessary spacing * [FIX] Empty message if contains only a link (#787) * Fix empty message if contains only a link * :bug: Fix empty space * [IMPROVEMENT] Refactor empty space regex on quote (#1017) * :art: Improve regex to empty space on quote * :art: Improve on regex to empty space on quote * [NEW] Custom fields on signup (#1013) * added custom feilds on registration * added flag as leftIcon and removed lable * added try and catch * typo * [CHORE] Renew provisioning profiles (#1020) * [NEW] Auto-translate (#1012) * Update realm * View original and translate working * Read AutoTranslate_Enabled setting * RocketChat.canAutoTranslate() * AutoTranslateView * Save language * Auto-translate switch * Translate message * [IMPROVEMENT] Use haptics rather than vibration (#1016) * Install expo-haptics * Use expo-haptics rather than RN's Vibration module * [IMPROVEMENT] Use Rest API for file upload (#1005) * removed rn-fetch-blob and use native XMLHttpRequest instead * removed unnessary changes * fix android bug * fix android bug * added tmid support * fix bug * fixed isssue with cacel model * fix problems with audio * done requested changes * fix bug with android * [CHORE] [CI] [TESTS] update detox to make ci pass (#1026) * feat: update detox to 12.11.3 to make CI pass * ci: comment all jobs but leave e2e-test job * commit to rerun IC e2e-test job * ci: uncomment all CI jobs * [NEW] Room swipe actions: mark as read/unread, hide, fav (#976) * added unread and fav feature * changed the layout * fix jest * done requested changes * added requested changes * [FIX] Android build (#1027) * [FIX] Android build * CircleCI error * [FIX] iOS share credentials build (#1028) * [FIX] iOS share credentials build * Use `hasMigration` as a string * [CI] Restore cache on CI (#1029) * feat: add fastlane save\restore cache config; comment not needed jobs; * install fastlane using 'bundle install' * install fastlane using 'sudo bundle install' * uncomment ios build commands * run set up google services in ios folder * add working_directory: ios to ios-build steps * remove 'cd ios' from Fastlane build step * add save\restore cache for npm modules * group save_cache steps * cache fastlane in ios-testflight job * uncomment previously commented jobs\steps * fix: add missing colon * use key for caching: node-modules-{{ checksum ".circleci/config.yml" }}-{{ checksum "yarn.lock" }} * add names for save\restore steps * ci: add `default` step with `working_directory: ~/repo` to ios-build job * return back caching npm: `node-v1-{{ checksum "package.json" }}-{{ arch }}` * fix: add missing curly braces * save\restore cache in e2e-test job; remove {{arch}} from cache names * add names to restore_cache steps in android-build job * add names to save_cache steps in android-build job * add names to all save\restore steps; change checksum package.json to yarn.lock * change `npm` to `NPM` in steps naming * remove {{ checksum circle ci }} from android-build job and fix naming of steps * [FIX] Rooms swipes (#1034) * Regression: on press style feedback * Action button styles * Fix animations * Styles changed * Update subscription without having to wait for socket * Calculate width on RoomsListView instead * [FIX] Decrease bigger emoji size to 30 (#1031) * [FIX] Append server URL on avatar if necessary (#1038) * Comment removeClippedSubviews * Comment width animation * Remove redux from RoomItem * Fix wrong re-render comparison * Remove listener * Raise minDeltaX * memo actions * Spring with native driver * Refactor functions * Fix props issues * Remove RoomItem.height * Long swipe * Refactor animations * this.rowTranslation -> this.transX * Moved state to this * Bump version to 1.16.1 (#1045) * [FIX] Set UserDefaults AppGroup on notification tap (#1047) * [FIX] Auto-translate messages as they arrive * Fix favorite button * [FIX] Swipe animations (#1044) * Comment removeClippedSubviews * Comment width animation * Remove redux from RoomItem * Fix wrong re-render comparison * Remove listener * Raise minDeltaX * memo actions * Spring with native driver * Refactor functions * Fix props issues * Remove RoomItem.height * Long swipe * Refactor animations * this.rowTranslation -> this.transX * Moved state to this * Fix favorite button * [FIX] Auto-translate messages as they arrive (#1049) * Comment removeClippedSubviews * Comment width animation * Remove redux from RoomItem * Fix wrong re-render comparison * Remove listener * Raise minDeltaX * memo actions * Spring with native driver * Refactor functions * Fix props issues * Remove RoomItem.height * Long swipe * Refactor animations * this.rowTranslation -> this.transX * Moved state to this * [FIX] Auto-translate messages as they arrive * [i18n] Add missing de translations (#1040) * [CHORE] Switch to react-native-localize (#1043) * Bump version to 1.17.0 (#1057) * Load views as needed (#1056) * [IMPROVEMENT] Change "resend" icon position (#1048) * [NEW] Video support (#801) * [NEW] File upload (#882) * [NEW] Share extension (#942) * [FIX] Share extension CI build (#1060) * Change bundleID * Provisioning * get provisioning profile * [IMPROVEMENT] Reusable toast (#1065) * [FIX] Moment locales (#1066) * [FIX] Share Extension issues (#1064) * [FIX] Empty white list enables all media types upload (#1077) * Merge branch 'master' into develop (#1079) * [FIX] Empty white list enables all media types upload (#1080) * Create utils to media (canUpload) * Fix variable name * [CHORE] Update README (#1081)
2019-07-29 20:44:39 +00:00
import React from 'react';
import PropTypes from 'prop-types';
import {
View, Text, LayoutAnimation, FlatList, ActivityIndicator, Keyboard, BackHandler
} from 'react-native';
import { SafeAreaView } from 'react-navigation';
import ShareExtension from 'rn-extensions-share';
import { connect } from 'react-redux';
import RNFetchBlob from 'rn-fetch-blob';
import * as mime from 'react-native-mime-types';
import { isEqual } from 'lodash';
import Navigation from '../../lib/ShareNavigation';
import database from '../../lib/realm';
import { isIOS, isAndroid } from '../../utils/deviceInfo';
import I18n from '../../i18n';
import { CustomIcon } from '../../lib/Icons';
import log from '../../utils/log';
import { canUploadFile } from '../../utils/media';
import DirectoryItem, { ROW_HEIGHT } from '../../presentation/DirectoryItem';
import ServerItem from '../../presentation/ServerItem';
import { CloseShareExtensionButton, CustomHeaderButtons, Item } from '../../containers/HeaderButton';
import ShareListHeader from './Header';
import styles from './styles';
import StatusBar from '../../containers/StatusBar';
const LIMIT = 50;
const getItemLayout = (data, index) => ({ length: ROW_HEIGHT, offset: ROW_HEIGHT * index, index });
const keyExtractor = item => item.rid;
@connect(({ share }) => ({
userId: share.user && share.user.id,
token: share.user && share.user.token,
server: share.server,
baseUrl: share ? share.server : ''
}))
/** @extends React.Component */
export default class ShareListView extends React.Component {
static navigationOptions = ({ navigation }) => {
const searching = navigation.getParam('searching');
const initSearch = navigation.getParam('initSearch', () => {});
const cancelSearch = navigation.getParam('cancelSearch', () => {});
const search = navigation.getParam('search', () => {});
if (isIOS) {
return {
headerTitle: (
<ShareListHeader
searching={searching}
initSearch={initSearch}
cancelSearch={cancelSearch}
search={search}
/>
)
};
}
return {
headerBackTitle: null,
headerLeft: searching
? (
<CustomHeaderButtons left>
<Item title='cancel' iconName='cross' onPress={cancelSearch} />
</CustomHeaderButtons>
)
: (
<CloseShareExtensionButton
onPress={ShareExtension.close}
testID='share-extension-close'
/>
),
headerTitle: <ShareListHeader searching={searching} search={search} />,
headerRight: (
searching
? null
: (
<CustomHeaderButtons>
{isAndroid ? <Item title='search' iconName='magnifier' onPress={initSearch} /> : null}
</CustomHeaderButtons>
)
)
};
}
static propTypes = {
navigation: PropTypes.object,
server: PropTypes.string,
baseUrl: PropTypes.string,
token: PropTypes.string,
userId: PropTypes.string
}
constructor(props) {
super(props);
this.data = [];
this.state = {
showError: false,
searching: false,
searchText: '',
value: '',
isMedia: false,
mediaLoading: false,
fileInfo: null,
searchResults: [],
chats: [],
servers: [],
loading: true,
serverInfo: null
};
this.didFocusListener = props.navigation.addListener('didFocus', () => BackHandler.addEventListener('hardwareBackPress', this.handleBackPress));
this.willBlurListener = props.navigation.addListener('willBlur', () => BackHandler.addEventListener('hardwareBackPress', this.handleBackPress));
}
async componentDidMount() {
const { navigation, server } = this.props;
navigation.setParams({
initSearch: this.initSearch,
cancelSearch: this.cancelSearch,
search: this.search
});
try {
const { value, type } = await ShareExtension.data();
let fileInfo = null;
const isMedia = (type === 'media');
if (isMedia) {
this.setState({ mediaLoading: true });
const data = await RNFetchBlob.fs.stat(this.uriToPath(value));
fileInfo = {
name: data.filename,
description: '',
size: data.size,
mime: mime.lookup(data.path),
path: isIOS ? data.path : `file://${ data.path }`
};
}
this.setState({
value, fileInfo, isMedia, mediaLoading: false
});
} catch (e) {
log('err_process_media_share_extension', e);
this.setState({ mediaLoading: false });
}
this.getSubscriptions(server);
}
componentWillReceiveProps(nextProps) {
const { server } = this.props;
if (nextProps.server !== server) {
this.getSubscriptions(nextProps.server);
}
}
shouldComponentUpdate(nextProps, nextState) {
const { searching } = this.state;
if (nextState.searching !== searching) {
return true;
}
const { isMedia } = this.state;
if (nextState.isMedia !== isMedia) {
this.getSubscriptions(nextProps.server, nextState.fileInfo);
return true;
}
const { server } = this.props;
if (server !== nextProps.server) {
return true;
}
const { searchResults } = this.state;
if (!isEqual(nextState.searchResults, searchResults)) {
return true;
}
return false;
}
// eslint-disable-next-line react/sort-comp
internalSetState = (...args) => {
const { navigation } = this.props;
if (isIOS && navigation.isFocused()) {
LayoutAnimation.easeInEaseOut();
}
this.setState(...args);
}
getSubscriptions = (server, fileInfo) => {
const { fileInfo: fileData } = this.state;
const { serversDB } = database.databases;
if (server) {
this.data = database.objects('subscriptions').filtered('archived != true && open == true').sorted('roomUpdatedAt', true);
this.servers = serversDB.objects('servers');
this.chats = this.data.slice(0, LIMIT);
const serverInfo = serversDB.objectForPrimaryKey('servers', server);
this.internalSetState({
chats: this.chats ? this.chats.slice() : [],
servers: this.servers ? this.servers.slice() : [],
loading: false,
showError: !canUploadFile(fileInfo || fileData, serverInfo),
serverInfo
});
this.forceUpdate();
}
};
uriToPath = uri => decodeURIComponent(isIOS ? uri.replace(/^file:\/\//, '') : uri);
getRoomTitle = (item) => {
const { serverInfo } = this.state;
const { useRealName } = serverInfo;
return ((item.prid || useRealName) && item.fname) || item.name;
}
shareMessage = (item) => {
const { value, isMedia, fileInfo } = this.state;
const { navigation } = this.props;
navigation.navigate('ShareView', {
rid: item.rid,
value,
isMedia,
fileInfo,
name: this.getRoomTitle(item)
});
}
search = (text) => {
const result = database.objects('subscriptions').filtered('name CONTAINS[c] $0', text);
this.internalSetState({
searchResults: result.slice(0, LIMIT),
searchText: text
});
}
initSearch = () => {
const { chats } = this.state;
const { navigation } = this.props;
this.setState({ searching: true, searchResults: chats });
navigation.setParams({ searching: true });
}
cancelSearch = () => {
const { navigation } = this.props;
this.internalSetState({ searching: false, searchResults: [], searchText: '' });
navigation.setParams({ searching: false });
Keyboard.dismiss();
}
handleBackPress = () => {
const { searching } = this.state;
if (searching) {
this.cancelSearch();
return true;
}
return false;
}
renderSectionHeader = (header) => {
const { searching } = this.state;
if (searching) {
return null;
}
return (
<View style={styles.headerContainer}>
<Text style={styles.headerText}>
{I18n.t(header)}
</Text>
</View>
);
}
renderItem = ({ item }) => {
const { userId, token, baseUrl } = this.props;
return (
<DirectoryItem
user={{
userId,
token
}}
title={this.getRoomTitle(item)}
baseUrl={baseUrl}
avatar={this.getRoomTitle(item)}
description={
item.t === 'c'
? (item.topic || item.description)
: item.fname
}
type={item.t}
onPress={() => this.shareMessage(item)}
testID={`share-extension-item-${ item.name }`}
/>
);
}
renderSeparator = () => <View style={styles.separator} />;
renderBorderBottom = () => <View style={styles.borderBottom} />;
renderSelectServer = () => {
const { servers } = this.state;
const { server } = this.props;
const currentServer = servers.find(serverFiltered => serverFiltered.id === server);
return currentServer ? (
<React.Fragment>
{this.renderSectionHeader('Select_Server')}
<View style={styles.bordered}>
<ServerItem
server={server}
onPress={() => Navigation.navigate('SelectServerView')}
item={currentServer}
/>
</View>
</React.Fragment>
) : null;
}
renderEmptyComponent = () => (
<View style={[styles.container, styles.emptyContainer]}>
<Text style={styles.title}>{I18n.t('No_results_found')}</Text>
</View>
);
renderHeader = () => {
const { searching } = this.state;
return (
<React.Fragment>
{ !searching
? (
<React.Fragment>
{this.renderSelectServer()}
{this.renderSectionHeader('Chats')}
</React.Fragment>
)
: null
}
</React.Fragment>
);
}
renderContent = () => {
const {
chats, mediaLoading, loading, searchResults, searching, searchText
} = this.state;
if (mediaLoading || loading) {
return <ActivityIndicator style={styles.loading} />;
}
return (
<FlatList
data={searching ? searchResults : chats}
keyExtractor={keyExtractor}
style={styles.flatlist}
renderItem={this.renderItem}
getItemLayout={getItemLayout}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={!searching && this.renderBorderBottom}
ListHeaderComponentStyle={!searching ? styles.borderBottom : {}}
ListEmptyComponent={searching && searchText ? this.renderEmptyComponent : null}
enableEmptySections
removeClippedSubviews
keyboardShouldPersistTaps='always'
initialNumToRender={12}
windowSize={20}
/>
);
}
renderError = () => {
const {
fileInfo: file, loading, searching, serverInfo
} = this.state;
const { FileUpload_MaxFileSize } = serverInfo;
const errorMessage = (FileUpload_MaxFileSize < file.size)
? 'error-file-too-large'
: 'error-invalid-file-type';
if (loading) {
return <ActivityIndicator style={styles.loading} />;
}
return (
<View style={styles.container}>
{ !searching
? (
<React.Fragment>
{this.renderSelectServer()}
</React.Fragment>
)
: null
}
<View style={[styles.container, styles.centered]}>
<Text style={styles.title}>{I18n.t(errorMessage)}</Text>
<CustomIcon name='circle-cross' size={120} style={styles.errorIcon} />
<Text style={styles.fileMime}>{ file.mime }</Text>
</View>
</View>
);
}
render() {
const { showError } = this.state;
return (
<SafeAreaView style={styles.container} forceInset={{ bottom: 'never' }}>
<StatusBar />
{ showError ? this.renderError() : this.renderContent() }
</SafeAreaView>
);
}
}