Merge develop and fix conflicts

This commit is contained in:
Filipe Brito 2019-09-18 11:05:35 -03:00
commit 88e6846f66
223 changed files with 17285 additions and 15916 deletions

View File

@ -1,7 +0,0 @@
// @flow
/* eslint-disable */
import I18nJs from 'i18n-js';
I18nJs.locale = 'en'; // a locale from your available translations
export const getLanguages = (): Promise<string[]> => Promise.resolve(['en']);
export default I18nJs;

View File

@ -1 +0,0 @@
export const CachedImage = 'CachedImage';

View File

@ -1,17 +0,0 @@
class Events {
registerAppLaunchedListener = () => {}
}
const events = new Events();
class NavigationClass {
registerComponent = () => {}
setRoot = () => {}
events = () => events
}
const Navigation = new NavigationClass();
export {
Navigation
};

View File

@ -1,3 +0,0 @@
export default {
realmPath: ''
};

View File

@ -1,5 +0,0 @@
export default function() {
return {
show: () => {}
};
}

View File

@ -1 +0,0 @@
export default () => 'View';

3
__mocks__/react-navigation.js vendored Normal file
View File

@ -0,0 +1,3 @@
export default {
NavigationActions: () => {}
};

View File

@ -1,26 +0,0 @@
export default class Realm {
schema = [];
data = [];
constructor(params) {
require('lodash').each(params.schema, (schema) => {
this.data[schema.name] = [];
this.data[schema.name].filtered = () => this.data[schema.name];
});
this.schema = params.schema;
}
objects(schemaName) {
return this.data[schemaName];
}
write = (fn) => {
fn();
}
create(schemaName, data) {
this.data[schemaName].push(data);
return data;
}
}

File diff suppressed because it is too large Load Diff

17
android/.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>RocketChatRN</name>
<comment>Project android created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
connection.project.dir=
eclipse.preferences.version=1

6
android/app/.classpath Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

23
android/app/.project Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>app</name>
<comment>Project app created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1

View File

@ -1,4 +1,5 @@
apply plugin: "com.android.application"
apply plugin: 'kotlin-android'
apply plugin: "io.fabric"
apply plugin: "com.google.firebase.firebase-perf"
apply plugin: 'com.bugsnag.android.gradle'
@ -136,7 +137,7 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode VERSIONCODE as Integer
versionName "1.19.0"
versionName "1.20.0"
vectorDrawables.useSupportLibrary = true
manifestPlaceholders = [BugsnagAPIKey: BugsnagAPIKey as String]
}
@ -204,6 +205,7 @@ android {
dependencies {
addUnimodulesDependencies()
implementation project(':watermelondb')
implementation project(':reactnativenotifications')
implementation project(":reactnativekeyboardinput")

View File

@ -31,6 +31,8 @@ import io.invertase.firebase.fabric.crashlytics.RNFirebaseCrashlyticsPackage;
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage;
import io.invertase.firebase.perf.RNFirebasePerformancePackage;
import com.nozbe.watermelondb.WatermelonDBPackage;
import java.util.Arrays;
import java.util.List;
@ -53,6 +55,7 @@ public class MainApplication extends Application implements ReactApplication, IN
packages.add(new RNFirebasePerformancePackage());
packages.add(new KeyboardInputPackage(MainApplication.this));
packages.add(new RNNotificationsPackage(MainApplication.this));
packages.add(new WatermelonDBPackage());
packages.add(new ModuleRegistryAdapter(mModuleRegistryProvider));
return packages;
}

View File

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M10,9V5l-7,7 7,7v-4.1c5,0 8.5,1.6 11,5.1 -1,-5 -4,-10 -11,-11z"/>
</vector>

View File

@ -6,10 +6,8 @@ buildscript {
compileSdkVersion = 28
targetSdkVersion = 28
glideVersion = "4.9.0"
// googlePlayServicesVersion = "17.0.0"
// supportLibVersion = "1.0.2"
// mediaCompatVersion = '1.0.1'
// supportV4Version = '1.0.0'
kotlin_version = "1.3.50"
supportLibVersion = "28.0.0"
}
repositories {
mavenLocal()
@ -24,6 +22,7 @@ buildscript {
classpath 'com.google.gms:google-services:4.2.0'
classpath 'io.fabric.tools:gradle:1.28.1'
classpath 'com.google.firebase:perf-plugin:1.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.bugsnag:bugsnag-android-gradle-plugin:4.+'
// NOTE: Do not place your application dependencies here; they belong

View File

@ -2,6 +2,8 @@ apply from: '../node_modules/react-native-unimodules/gradle.groovy'
includeUnimodulesProjects()
rootProject.name = 'RocketChatRN'
include ':watermelondb'
project(':watermelondb').projectDir = new File(rootProject.projectDir, '../node_modules/@nozbe/watermelondb/native/android')
include ':reactnativenotifications'
project(':reactnativenotifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notifications/android/app')
include ':reactnativekeyboardinput'

View File

@ -32,31 +32,7 @@ export const ROOMS = createRequestTypes('ROOMS', [
]);
export const ROOM = createRequestTypes('ROOM', ['LEAVE', 'ERASE', 'USER_TYPING']);
export const APP = createRequestTypes('APP', ['START', 'READY', 'INIT']);
export const MESSAGES = createRequestTypes('MESSAGES', [
...defaultTypes,
'ACTIONS_SHOW',
'ACTIONS_HIDE',
'ERROR_ACTIONS_SHOW',
'ERROR_ACTIONS_HIDE',
'DELETE_REQUEST',
'DELETE_SUCCESS',
'DELETE_FAILURE',
'EDIT_INIT',
'EDIT_CANCEL',
'EDIT_REQUEST',
'EDIT_SUCCESS',
'EDIT_FAILURE',
'TOGGLE_STAR_REQUEST',
'TOGGLE_STAR_SUCCESS',
'TOGGLE_STAR_FAILURE',
'TOGGLE_PIN_REQUEST',
'TOGGLE_PIN_SUCCESS',
'TOGGLE_PIN_FAILURE',
'REPLY_INIT',
'REPLY_CANCEL',
'TOGGLE_REACTION_PICKER',
'REPLY_BROADCAST'
]);
export const MESSAGES = createRequestTypes('MESSAGES', ['REPLY_BROADCAST']);
export const CREATE_CHANNEL = createRequestTypes('CREATE_CHANNEL', [...defaultTypes]);
export const SELECTED_USERS = createRequestTypes('SELECTED_USERS', ['ADD_USER', 'REMOVE_USER', 'RESET', 'SET_LOADING']);
export const SERVER = createRequestTypes('SERVER', [
@ -75,3 +51,6 @@ export const SORT_PREFERENCES = createRequestTypes('SORT_PREFERENCES', ['SET_ALL
export const NOTIFICATION = createRequestTypes('NOTIFICATION', ['RECEIVED', 'REMOVE']);
export const TOGGLE_MARKDOWN = 'TOGGLE_MARKDOWN';
export const TOGGLE_CRASH_REPORT = 'TOGGLE_CRASH_REPORT';
export const SET_CUSTOM_EMOJIS = 'SET_CUSTOM_EMOJIS';
export const SET_ACTIVE_USERS = 'SET_ACTIVE_USERS';
export const USERS_TYPING = createRequestTypes('USERS_TYPING', ['ADD', 'REMOVE', 'CLEAR']);

View File

@ -0,0 +1,8 @@
import { SET_ACTIVE_USERS } from './actionsTypes';
export function setActiveUsers(activeUsers) {
return {
type: SET_ACTIVE_USERS,
activeUsers
};
}

View File

@ -0,0 +1,8 @@
import * as types from './actionsTypes';
export function setCustomEmojis(emojis) {
return {
type: types.SET_CUSTOM_EMOJIS,
emojis
};
}

View File

@ -1,143 +1,5 @@
import * as types from './actionsTypes';
export function actionsShow(actionMessage) {
return {
type: types.MESSAGES.ACTIONS_SHOW,
actionMessage
};
}
export function actionsHide() {
return {
type: types.MESSAGES.ACTIONS_HIDE
};
}
export function errorActionsShow(actionMessage) {
return {
type: types.MESSAGES.ERROR_ACTIONS_SHOW,
actionMessage
};
}
export function errorActionsHide() {
return {
type: types.MESSAGES.ERROR_ACTIONS_HIDE
};
}
export function deleteRequest(message) {
return {
type: types.MESSAGES.DELETE_REQUEST,
message
};
}
export function deleteSuccess() {
return {
type: types.MESSAGES.DELETE_SUCCESS
};
}
export function deleteFailure() {
return {
type: types.MESSAGES.DELETE_FAILURE
};
}
export function editInit(message) {
return {
type: types.MESSAGES.EDIT_INIT,
message
};
}
export function editCancel() {
return {
type: types.MESSAGES.EDIT_CANCEL
};
}
export function editRequest(message) {
return {
type: types.MESSAGES.EDIT_REQUEST,
message
};
}
export function editSuccess() {
return {
type: types.MESSAGES.EDIT_SUCCESS
};
}
export function editFailure() {
return {
type: types.MESSAGES.EDIT_FAILURE
};
}
export function toggleStarRequest(message) {
return {
type: types.MESSAGES.TOGGLE_STAR_REQUEST,
message
};
}
export function toggleStarSuccess() {
return {
type: types.MESSAGES.TOGGLE_STAR_SUCCESS
};
}
export function toggleStarFailure() {
return {
type: types.MESSAGES.TOGGLE_STAR_FAILURE
};
}
export function togglePinRequest(message) {
return {
type: types.MESSAGES.TOGGLE_PIN_REQUEST,
message
};
}
export function togglePinSuccess() {
return {
type: types.MESSAGES.TOGGLE_PIN_SUCCESS
};
}
export function togglePinFailure(err) {
return {
type: types.MESSAGES.TOGGLE_PIN_FAILURE,
err
};
}
export function replyInit(message, mention) {
return {
type: types.MESSAGES.REPLY_INIT,
message,
mention
};
}
export function replyCancel() {
return {
type: types.MESSAGES.REPLY_CANCEL
};
}
export function toggleReactionPicker(message) {
return {
type: types.MESSAGES.TOGGLE_REACTION_PICKER,
message
};
}
export function replyBroadcast(message) {
return {
type: types.MESSAGES.REPLY_BROADCAST,

View File

@ -23,10 +23,11 @@ export function selectServerFailure() {
};
}
export function serverRequest(server) {
export function serverRequest(server, certificate = null) {
return {
type: SERVER.REQUEST,
server
server,
certificate
};
}

View File

@ -0,0 +1,21 @@
import { USERS_TYPING } from './actionsTypes';
export function addUserTyping(username) {
return {
type: USERS_TYPING.ADD,
username
};
}
export function removeUserTyping(username) {
return {
type: USERS_TYPING.REMOVE,
username
};
}
export function clearUserTyping() {
return {
type: USERS_TYPING.CLEAR
};
}

View File

@ -1,5 +1,5 @@
import React from 'react';
import { Image } from 'react-native';
import FastImage from 'react-native-fast-image';
import PropTypes from 'prop-types';
export default class CustomEmoji extends React.Component {
@ -16,9 +16,13 @@ export default class CustomEmoji extends React.Component {
render() {
const { baseUrl, emoji, style } = this.props;
return (
<Image
<FastImage
style={style}
source={{ uri: `${ baseUrl }/emoji-custom/${ encodeURIComponent(emoji.content || emoji.name) }.${ emoji.extension }` }}
source={{
uri: `${ baseUrl }/emoji-custom/${ encodeURIComponent(emoji.content || emoji.name) }.${ emoji.extension }`,
priority: FastImage.priority.high
}}
resizeMode={FastImage.resizeMode.contain}
/>
);
}

View File

@ -1,7 +1,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Text, TouchableOpacity } from 'react-native';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import { responsive } from 'react-native-responsive-ui';
import { OptimizedFlatList } from 'react-native-optimized-flatlist';
@ -18,7 +18,7 @@ const renderEmoji = (emoji, size, baseUrl) => {
}
return (
<Text style={[styles.categoryEmoji, { height: size, width: size, fontSize: size - 14 }]}>
{emojify(`:${ emoji }:`, { output: 'unicode' })}
{shortnameToUnicode(`:${ emoji }:`)}
</Text>
);
};

View File

@ -2,26 +2,30 @@ import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ScrollView } from 'react-native';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import map from 'lodash/map';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import equal from 'deep-equal';
import { connect } from 'react-redux';
import orderBy from 'lodash/orderBy';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import TabBar from './TabBar';
import EmojiCategory from './EmojiCategory';
import styles from './styles';
import categories from './categories';
import database, { safeAddListener } from '../../lib/realm';
import database from '../../lib/database';
import { emojisByCategory } from '../../emojis';
import protectedFunction from '../../lib/methods/helpers/protectedFunction';
import log from '../../utils/log';
const scrollProps = {
keyboardShouldPersistTaps: 'always',
keyboardDismissMode: 'none'
};
export default class EmojiPicker extends Component {
class EmojiPicker extends Component {
static propTypes = {
baseUrl: PropTypes.string.isRequired,
customEmojis: PropTypes.object,
onEmojiSelected: PropTypes.func,
tabEmojiStyle: PropTypes.object,
emojisPerRow: PropTypes.number,
@ -30,27 +34,27 @@ export default class EmojiPicker extends Component {
constructor(props) {
super(props);
this.frequentlyUsed = database.objects('frequentlyUsedEmoji').sorted('count', true);
this.customEmojis = database.objects('customEmojis');
const customEmojis = Object.keys(props.customEmojis)
.filter(item => item === props.customEmojis[item].name)
.map(item => ({
content: props.customEmojis[item].name,
extension: props.customEmojis[item].extension,
isCustom: true
}));
this.state = {
frequentlyUsed: [],
customEmojis: [],
customEmojis,
show: false
};
this.updateFrequentlyUsed = this.updateFrequentlyUsed.bind(this);
this.updateCustomEmojis = this.updateCustomEmojis.bind(this);
}
componentDidMount() {
this.updateFrequentlyUsed();
this.updateCustomEmojis();
requestAnimationFrame(() => this.setState({ show: true }));
safeAddListener(this.frequentlyUsed, this.updateFrequentlyUsed);
safeAddListener(this.customEmojis, this.updateCustomEmojis);
async componentDidMount() {
await this.updateFrequentlyUsed();
this.setState({ show: true });
}
shouldComponentUpdate(nextProps, nextState) {
const { frequentlyUsed, customEmojis, show } = this.state;
const { frequentlyUsed, show } = this.state;
const { width } = this.props;
if (nextState.show !== show) {
return true;
@ -61,64 +65,70 @@ export default class EmojiPicker extends Component {
if (!equal(nextState.frequentlyUsed, frequentlyUsed)) {
return true;
}
if (!equal(nextState.customEmojis, customEmojis)) {
return true;
}
return false;
}
componentWillUnmount() {
this.frequentlyUsed.removeAllListeners();
this.customEmojis.removeAllListeners();
}
onEmojiSelected(emoji) {
const { onEmojiSelected } = this.props;
if (emoji.isCustom) {
const count = this._getFrequentlyUsedCount(emoji.content);
this._addFrequentlyUsed({
content: emoji.content, extension: emoji.extension, count, isCustom: true
});
onEmojiSelected(`:${ emoji.content }:`);
} else {
const content = emoji;
const count = this._getFrequentlyUsedCount(content);
this._addFrequentlyUsed({ content, count, isCustom: false });
const shortname = `:${ emoji }:`;
onEmojiSelected(emojify(shortname, { output: 'unicode' }), shortname);
onEmojiSelected = (emoji) => {
try {
const { onEmojiSelected } = this.props;
if (emoji.isCustom) {
this._addFrequentlyUsed({
content: emoji.content, extension: emoji.extension, isCustom: true
});
onEmojiSelected(`:${ emoji.content }:`);
} else {
const content = emoji;
this._addFrequentlyUsed({ content, isCustom: false });
const shortname = `:${ emoji }:`;
onEmojiSelected(shortnameToUnicode(shortname), shortname);
}
} catch (e) {
log(e);
}
}
// eslint-disable-next-line react/sort-comp
_addFrequentlyUsed = protectedFunction((emoji) => {
database.write(() => {
database.create('frequentlyUsedEmoji', emoji, true);
_addFrequentlyUsed = protectedFunction(async(emoji) => {
const db = database.active;
const freqEmojiCollection = db.collections.get('frequently_used_emojis');
await db.action(async() => {
try {
const freqEmojiRecord = await freqEmojiCollection.find(emoji.content);
await freqEmojiRecord.update((f) => {
f.count += 1;
});
} catch (error) {
try {
await freqEmojiCollection.create((f) => {
f._raw = sanitizedRaw({ id: emoji.content }, freqEmojiCollection.schema);
Object.assign(f, emoji);
f.count = 1;
});
} catch (e) {
// Do nothing
}
}
});
})
_getFrequentlyUsedCount = (content) => {
const emojiRow = this.frequentlyUsed.filtered('content == $0', content);
return emojiRow.length ? emojiRow[0].count + 1 : 1;
}
updateFrequentlyUsed() {
const frequentlyUsed = map(this.frequentlyUsed.slice(), (item) => {
updateFrequentlyUsed = async() => {
const db = database.active;
const frequentlyUsedRecords = await db.collections.get('frequently_used_emojis').query().fetch();
let frequentlyUsed = orderBy(frequentlyUsedRecords, ['count'], ['desc']);
frequentlyUsed = frequentlyUsed.map((item) => {
if (item.isCustom) {
return item;
return { content: item.content, extension: item.extension, isCustom: item.isCustom };
}
return emojify(`${ item.content }`, { output: 'unicode' });
return shortnameToUnicode(`${ item.content }`);
});
this.setState({ frequentlyUsed });
}
updateCustomEmojis() {
const customEmojis = map(this.customEmojis.slice(), item => ({ content: item.name, extension: item.extension, isCustom: true }));
this.setState({ customEmojis });
}
renderCategory(category, i) {
const { frequentlyUsed, customEmojis } = this.state;
const { emojisPerRow, width, baseUrl } = this.props;
const {
emojisPerRow, width, baseUrl
} = this.props;
let emojis = [];
if (i === 0) {
@ -171,3 +181,9 @@ export default class EmojiPicker extends Component {
);
}
}
const mapStateToProps = state => ({
customEmojis: state.customEmojis
});
export default connect(mapStateToProps)(EmojiPicker);

View File

@ -11,7 +11,6 @@ import { Video } from 'expo-av';
import sharedStyles from '../views/Styles';
import { COLOR_WHITE } from '../constants/colors';
import { formatAttachmentUrl } from '../lib/utils';
import log from '../utils/log';
const styles = StyleSheet.create({
safeArea: {
@ -85,7 +84,7 @@ const ModalContent = React.memo(({
);
}
if (attachment && attachment.video_url) {
const [loading, setLoading] = useState(0);
const [loading, setLoading] = useState(true);
const uri = formatAttachmentUrl(attachment.video_url, user.id, user.token, baseUrl);
return (
<>
@ -94,14 +93,14 @@ const ModalContent = React.memo(({
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode='cover'
resizeMode={Video.RESIZE_MODE_CONTAIN}
shouldPlay
isLooping={false}
style={styles.video}
useNativeControls
onReadyForDisplay={() => setLoading(false)}
onLoadStart={() => setLoading(true)}
onError={log}
onError={console.log}
/>
{ loading ? <ActivityIndicator size='large' style={styles.loading} /> : null }
</>

View File

@ -6,17 +6,8 @@ import ActionSheet from 'react-native-action-sheet';
import moment from 'moment';
import * as Haptics from 'expo-haptics';
import {
actionsHide as actionsHideAction,
deleteRequest as deleteRequestAction,
editInit as editInitAction,
replyInit as replyInitAction,
togglePinRequest as togglePinRequestAction,
toggleReactionPicker as toggleReactionPickerAction,
toggleStarRequest as toggleStarRequestAction
} from '../actions/messages';
import RocketChat from '../lib/rocketchat';
import database from '../lib/realm';
import database from '../lib/database';
import I18n from '../i18n';
import log from '../utils/log';
import Navigation from '../lib/Navigation';
@ -28,14 +19,12 @@ class MessageActions extends React.Component {
static propTypes = {
actionsHide: PropTypes.func.isRequired,
room: PropTypes.object.isRequired,
actionMessage: PropTypes.object,
message: PropTypes.object,
user: PropTypes.object,
deleteRequest: PropTypes.func.isRequired,
editInit: PropTypes.func.isRequired,
toggleStarRequest: PropTypes.func.isRequired,
togglePinRequest: PropTypes.func.isRequired,
toggleReactionPicker: PropTypes.func.isRequired,
reactionInit: PropTypes.func.isRequired,
replyInit: PropTypes.func.isRequired,
isReadOnly: PropTypes.bool,
Message_AllowDeleting: PropTypes.bool,
Message_AllowDeleting_BlockDeleteInMinutes: PropTypes.number,
Message_AllowEditing: PropTypes.bool,
@ -48,22 +37,27 @@ class MessageActions extends React.Component {
constructor(props) {
super(props);
this.handleActionPress = this.handleActionPress.bind(this);
this.setPermissions();
}
const { Message_AllowStarring, Message_AllowPinning, Message_Read_Receipt_Store_Users } = this.props;
async componentDidMount() {
await this.setPermissions();
const {
Message_AllowStarring, Message_AllowPinning, Message_Read_Receipt_Store_Users, user, room, message, isReadOnly
} = this.props;
// Cancel
this.options = [I18n.t('Cancel')];
this.CANCEL_INDEX = 0;
// Reply
if (!this.isRoomReadOnly()) {
if (!isReadOnly) {
this.options.push(I18n.t('Reply'));
this.REPLY_INDEX = this.options.length - 1;
}
// Edit
if (this.allowEdit(props)) {
if (this.allowEdit(this.props)) {
this.options.push(I18n.t('Edit'));
this.EDIT_INDEX = this.options.length - 1;
}
@ -81,25 +75,25 @@ class MessageActions extends React.Component {
this.SHARE_INDEX = this.options.length - 1;
// Quote
if (!this.isRoomReadOnly()) {
if (!isReadOnly) {
this.options.push(I18n.t('Quote'));
this.QUOTE_INDEX = this.options.length - 1;
}
// Star
if (Message_AllowStarring) {
this.options.push(I18n.t(props.actionMessage.starred ? 'Unstar' : 'Star'));
this.options.push(I18n.t(message.starred ? 'Unstar' : 'Star'));
this.STAR_INDEX = this.options.length - 1;
}
// Pin
if (Message_AllowPinning) {
this.options.push(I18n.t(props.actionMessage.pinned ? 'Unpin' : 'Pin'));
this.options.push(I18n.t(message.pinned ? 'Unpin' : 'Pin'));
this.PIN_INDEX = this.options.length - 1;
}
// Reaction
if (!this.isRoomReadOnly() || this.canReactWhenReadOnly()) {
if (!isReadOnly || this.canReactWhenReadOnly()) {
this.options.push(I18n.t('Add_Reaction'));
this.REACTION_INDEX = this.options.length - 1;
}
@ -111,8 +105,8 @@ class MessageActions extends React.Component {
}
// Toggle Auto-translate
if (props.room.autoTranslate && props.actionMessage.u && props.actionMessage.u._id !== props.user.id) {
this.options.push(I18n.t(props.actionMessage.autoTranslate ? 'View_Original' : 'Translate'));
if (room.autoTranslate && message.u && message.u._id !== user.id) {
this.options.push(I18n.t(message.autoTranslate ? 'View_Original' : 'Translate'));
this.TOGGLE_TRANSLATION_INDEX = this.options.length - 1;
}
@ -121,7 +115,7 @@ class MessageActions extends React.Component {
this.REPORT_INDEX = this.options.length - 1;
// Delete
if (this.allowDelete(props)) {
if (this.allowDelete(this.props)) {
this.options.push(I18n.t('Delete'));
this.DELETE_INDEX = this.options.length - 1;
}
@ -131,13 +125,18 @@ class MessageActions extends React.Component {
});
}
setPermissions() {
const { room } = this.props;
const permissions = ['edit-message', 'delete-message', 'force-delete-message'];
const result = RocketChat.hasPermission(permissions, room.rid);
this.hasEditPermission = result[permissions[0]];
this.hasDeletePermission = result[permissions[1]];
this.hasForceDeletePermission = result[permissions[2]];
async setPermissions() {
try {
const { room } = this.props;
const permissions = ['edit-message', 'delete-message', 'force-delete-message'];
const result = await RocketChat.hasPermission(permissions, room.rid);
this.hasEditPermission = result[permissions[0]];
this.hasDeletePermission = result[permissions[1]];
this.hasForceDeletePermission = result[permissions[2]];
} catch (e) {
log(e);
}
Promise.resolve();
}
showActionSheet = () => {
@ -159,12 +158,7 @@ class MessageActions extends React.Component {
}
}
isOwn = props => props.actionMessage.u && props.actionMessage.u._id === props.user.id;
isRoomReadOnly = () => {
const { room } = this.props;
return room.ro;
}
isOwn = props => props.message.u && props.message.u._id === props.user.id;
canReactWhenReadOnly = () => {
const { room } = this.props;
@ -172,7 +166,7 @@ class MessageActions extends React.Component {
}
allowEdit = (props) => {
if (this.isRoomReadOnly()) {
if (props.isReadOnly) {
return false;
}
const editOwn = this.isOwn(props);
@ -184,8 +178,8 @@ class MessageActions extends React.Component {
const blockEditInMinutes = Message_AllowEditing_BlockEditInMinutes;
if (blockEditInMinutes) {
let msgTs;
if (props.actionMessage.ts != null) {
msgTs = moment(props.actionMessage.ts);
if (props.message.ts != null) {
msgTs = moment(props.message.ts);
}
let currentTsDiff;
if (msgTs != null) {
@ -197,12 +191,12 @@ class MessageActions extends React.Component {
}
allowDelete = (props) => {
if (this.isRoomReadOnly()) {
if (props.isReadOnly) {
return false;
}
// Prevent from deleting thread start message when positioned inside the thread
if (props.tmid && props.tmid === props.actionMessage._id) {
if (props.tmid && props.tmid === props.message.id) {
return false;
}
const deleteOwn = this.isOwn(props);
@ -216,8 +210,8 @@ class MessageActions extends React.Component {
const blockDeleteInMinutes = Message_AllowDeleting_BlockDeleteInMinutes;
if (blockDeleteInMinutes != null && blockDeleteInMinutes !== 0) {
let msgTs;
if (props.actionMessage.ts != null) {
msgTs = moment(props.actionMessage.ts);
if (props.message.ts != null) {
msgTs = moment(props.message.ts);
}
let currentTsDiff;
if (msgTs != null) {
@ -229,7 +223,7 @@ class MessageActions extends React.Component {
}
handleDelete = () => {
const { deleteRequest, actionMessage } = this.props;
const { message } = this.props;
Alert.alert(
I18n.t('Are_you_sure_question_mark'),
I18n.t('You_will_not_be_able_to_recover_this_message'),
@ -241,7 +235,13 @@ class MessageActions extends React.Component {
{
text: I18n.t('Yes_action_it', { action: 'delete' }),
style: 'destructive',
onPress: () => deleteRequest(actionMessage)
onPress: async() => {
try {
await RocketChat.deleteMessage(message.id, message.rid);
} catch (e) {
log(e);
}
}
}
],
{ cancelable: false }
@ -249,86 +249,101 @@ class MessageActions extends React.Component {
}
handleEdit = () => {
const { actionMessage, editInit } = this.props;
const { _id, msg, rid } = actionMessage;
editInit({ _id, msg, rid });
const { message, editInit } = this.props;
editInit(message);
}
handleCopy = async() => {
const { actionMessage } = this.props;
await Clipboard.setString(actionMessage.msg);
const { message } = this.props;
await Clipboard.setString(message.msg);
EventEmitter.emit(LISTENER, { message: I18n.t('Copied_to_clipboard') });
}
handleShare = async() => {
const { actionMessage } = this.props;
const permalink = await this.getPermalink(actionMessage);
const { message } = this.props;
const permalink = await this.getPermalink(message);
Share.share({
message: permalink
});
};
handleStar = () => {
const { actionMessage, toggleStarRequest } = this.props;
toggleStarRequest(actionMessage);
handleStar = async() => {
const { message } = this.props;
try {
await RocketChat.toggleStarMessage(message.id, message.starred);
} catch (e) {
log(e);
}
}
handlePermalink = async() => {
const { actionMessage } = this.props;
const permalink = await this.getPermalink(actionMessage);
const { message } = this.props;
const permalink = await this.getPermalink(message);
Clipboard.setString(permalink);
EventEmitter.emit(LISTENER, { message: I18n.t('Permalink_copied_to_clipboard') });
}
handlePin = () => {
const { actionMessage, togglePinRequest } = this.props;
togglePinRequest(actionMessage);
handlePin = async() => {
const { message } = this.props;
try {
await RocketChat.togglePinMessage(message.id, message.pinned);
} catch (e) {
log(e);
}
}
handleReply = () => {
const { actionMessage, replyInit } = this.props;
replyInit(actionMessage, true);
const { message, replyInit } = this.props;
replyInit(message, true);
}
handleQuote = () => {
const { actionMessage, replyInit } = this.props;
replyInit(actionMessage, false);
const { message, replyInit } = this.props;
replyInit(message, false);
}
handleReaction = () => {
const { actionMessage, toggleReactionPicker } = this.props;
toggleReactionPicker(actionMessage);
const { message, reactionInit } = this.props;
reactionInit(message);
}
handleReadReceipt = () => {
const { actionMessage } = this.props;
Navigation.navigate('ReadReceiptsView', { messageId: actionMessage._id });
const { message } = this.props;
Navigation.navigate('ReadReceiptsView', { messageId: message.id });
}
handleReport = async() => {
const { actionMessage } = this.props;
const { message } = this.props;
try {
await RocketChat.reportMessage(actionMessage._id);
await RocketChat.reportMessage(message.id);
Alert.alert(I18n.t('Message_Reported'));
} catch (err) {
log(err);
} catch (e) {
log(e);
}
}
handleToggleTranslation = async() => {
const { actionMessage, room } = this.props;
const { message, room } = this.props;
try {
const message = database.objectForPrimaryKey('messages', actionMessage._id);
database.write(() => {
message.autoTranslate = !message.autoTranslate;
message._updatedAt = new Date();
const db = database.active;
await db.action(async() => {
await message.update((m) => {
m.autoTranslate = !m.autoTranslate;
m._updatedAt = new Date();
});
});
const translatedMessage = getMessageTranslation(message, room.autoTranslateLanguage);
if (!translatedMessage) {
await RocketChat.translateMessage(actionMessage, room.autoTranslateLanguage);
const m = {
_id: message.id,
rid: message.subscription.id,
u: message.u,
msg: message.msg
};
await RocketChat.translateMessage(m, room.autoTranslateLanguage);
}
} catch (err) {
log(err);
} catch (e) {
log(e);
}
}
@ -390,7 +405,6 @@ class MessageActions extends React.Component {
}
const mapStateToProps = state => ({
actionMessage: state.messages.actionMessage,
Message_AllowDeleting: state.settings.Message_AllowDeleting,
Message_AllowDeleting_BlockDeleteInMinutes: state.settings.Message_AllowDeleting_BlockDeleteInMinutes,
Message_AllowEditing: state.settings.Message_AllowEditing,
@ -400,14 +414,4 @@ const mapStateToProps = state => ({
Message_Read_Receipt_Store_Users: state.settings.Message_Read_Receipt_Store_Users
});
const mapDispatchToProps = dispatch => ({
actionsHide: () => dispatch(actionsHideAction()),
deleteRequest: message => dispatch(deleteRequestAction(message)),
editInit: message => dispatch(editInitAction(message)),
toggleStarRequest: message => dispatch(toggleStarRequestAction(message)),
togglePinRequest: message => dispatch(togglePinRequestAction(message)),
toggleReactionPicker: message => dispatch(toggleReactionPickerAction(message)),
replyInit: (message, mention) => dispatch(replyInitAction(message, mention))
});
export default connect(mapStateToProps, mapDispatchToProps)(MessageActions);
export default connect(mapStateToProps)(MessageActions);

View File

@ -5,7 +5,6 @@ import moment from 'moment';
import { connect } from 'react-redux';
import Markdown from '../markdown';
import { getCustomEmoji } from '../message/utils';
import { CustomIcon } from '../../lib/Icons';
import sharedStyles from '../../views/Styles';
import {
@ -55,7 +54,8 @@ class ReplyPreview extends Component {
Message_TimeFormat: PropTypes.string.isRequired,
close: PropTypes.func.isRequired,
baseUrl: PropTypes.string.isRequired,
username: PropTypes.string.isRequired
username: PropTypes.string.isRequired,
getCustomEmoji: PropTypes.func
}
shouldComponentUpdate() {
@ -69,7 +69,7 @@ class ReplyPreview extends Component {
render() {
const {
message, Message_TimeFormat, baseUrl, username, useMarkdown
message, Message_TimeFormat, baseUrl, username, useMarkdown, getCustomEmoji
} = this.props;
const time = moment(message.ts).format(Message_TimeFormat);
return (

View File

@ -4,22 +4,18 @@ import {
View, TextInput, FlatList, Text, TouchableOpacity, Alert, ScrollView
} from 'react-native';
import { connect } from 'react-redux';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import { KeyboardAccessoryView } from 'react-native-keyboard-input';
import ImagePicker from 'react-native-image-crop-picker';
import equal from 'deep-equal';
import DocumentPicker from 'react-native-document-picker';
import ActionSheet from 'react-native-action-sheet';
import { Q } from '@nozbe/watermelondb';
import { userTyping as userTypingAction } from '../../actions/room';
import {
editRequest as editRequestAction,
editCancel as editCancelAction,
replyCancel as replyCancelAction
} from '../../actions/messages';
import RocketChat from '../../lib/rocketchat';
import styles from './styles';
import database from '../../lib/realm';
import database from '../../lib/database';
import Avatar from '../Avatar';
import CustomEmoji from '../EmojiPicker/CustomEmoji';
import { emojis } from '../../emojis';
@ -40,10 +36,6 @@ const MENTIONS_TRACKING_TYPE_EMOJIS = ':';
const MENTIONS_TRACKING_TYPE_COMMANDS = '/';
const MENTIONS_COUNT_TO_DISPLAY = 4;
const onlyUnique = function onlyUnique(value, index, self) {
return self.indexOf(({ _id }) => value._id === _id) === index;
};
const imagePickerConfig = {
cropping: true,
compressImageQuality: 0.8,
@ -69,7 +61,6 @@ class MessageBox extends Component {
rid: PropTypes.string.isRequired,
baseUrl: PropTypes.string.isRequired,
message: PropTypes.object,
replyMessage: PropTypes.object,
replying: PropTypes.bool,
editing: PropTypes.bool,
threadsEnabled: PropTypes.bool,
@ -81,11 +72,13 @@ class MessageBox extends Component {
}),
roomType: PropTypes.string,
tmid: PropTypes.string,
replyWithMention: PropTypes.bool,
getCustomEmoji: PropTypes.func,
editCancel: PropTypes.func.isRequired,
editRequest: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
typing: PropTypes.func,
closeReply: PropTypes.func
replyCancel: PropTypes.func
}
constructor(props) {
@ -102,11 +95,6 @@ class MessageBox extends Component {
commandPreview: []
};
this.showCommandPreview = false;
this.commands = [];
this.users = [];
this.rooms = [];
this.emojis = [];
this.customEmojis = [];
this.onEmojiSelected = this.onEmojiSelected.bind(this);
this.text = '';
this.fileOptions = [
@ -135,20 +123,34 @@ class MessageBox extends Component {
};
}
componentDidMount() {
async componentDidMount() {
const db = database.active;
const { rid, tmid } = this.props;
let msg;
if (tmid) {
const thread = database.objectForPrimaryKey('threads', tmid);
if (thread) {
msg = thread.draftMessage;
}
} else {
const [room] = database.objects('subscriptions').filtered('rid = $0', rid);
if (room) {
msg = room.draftMessage;
try {
const threadsCollection = db.collections.get('threads');
const subsCollection = db.collections.get('subscriptions');
if (tmid) {
try {
const thread = await threadsCollection.find(tmid);
if (thread) {
msg = thread.draftMessage;
}
} catch (error) {
console.log('Messagebox.didMount: Thread not found');
}
} else {
try {
const room = await subsCollection.find(rid);
msg = room.draftMessage;
} catch (error) {
console.log('Messagebox.didMount: Room not found');
}
}
} catch (e) {
log(e);
}
if (msg) {
this.setInput(msg);
this.setShowSend(true);
@ -160,17 +162,16 @@ class MessageBox extends Component {
}
componentWillReceiveProps(nextProps) {
const { message, replyMessage, isFocused } = this.props;
const { isFocused, editing, replying } = this.props;
if (!isFocused) {
return;
}
if (!equal(message, nextProps.message) && nextProps.message.msg) {
if (editing !== nextProps.editing && nextProps.editing) {
this.setInput(nextProps.message.msg);
if (this.text) {
this.setShowSend(true);
}
this.focus();
} else if (!equal(replyMessage, nextProps.replyMessage)) {
} else if (replying !== nextProps.replying && nextProps.replying) {
this.focus();
} else if (!nextProps.message) {
this.clearInput();
@ -181,6 +182,7 @@ class MessageBox extends Component {
const {
showEmojiKeyboard, showSend, recording, mentions, file, commandPreview
} = this.state;
const {
roomType, replying, editing, isFocused
} = this.props;
@ -217,7 +219,12 @@ class MessageBox extends Component {
return false;
}
onChangeText = debounce((text) => {
componentWillUnmount() {
console.countReset(`${ this.constructor.name }.render calls`);
}
onChangeText = debounce(async(text) => {
const db = database.active;
const isTextEmpty = text.length === 0;
this.setShowSend(!isTextEmpty);
this.handleTyping(!isTextEmpty);
@ -226,9 +233,14 @@ class MessageBox extends Component {
const slashCommand = text.match(/^\/([a-z0-9._-]+) (.+)/im);
if (slashCommand) {
const [, name, params] = slashCommand;
const command = database.objects('slashCommand').filtered('command == $0', name);
if (command && command[0] && command[0].providesPreview) {
return this.setCommandPreview(name, params);
const commandsCollection = db.collections.get('slash_commands');
try {
const command = await commandsCollection.find(name);
if (command.providesPreview) {
return this.setCommandPreview(name, params);
}
} catch (e) {
console.log('Slash command not found');
}
}
@ -293,7 +305,7 @@ class MessageBox extends Component {
try {
RocketChat.executeCommandPreview(command, params, rid, item);
} catch (e) {
log('onPressCommandPreview', e);
log(e);
}
}
@ -324,114 +336,49 @@ class MessageBox extends Component {
}
getFixedMentions = (keyword) => {
let result = [];
if ('all'.indexOf(keyword) !== -1) {
this.users = [{ _id: -1, username: 'all' }, ...this.users];
result = [{ _id: -1, username: 'all' }];
}
if ('here'.indexOf(keyword) !== -1) {
this.users = [{ _id: -2, username: 'here' }, ...this.users];
result = [{ _id: -2, username: 'here' }, ...result];
}
return result;
}
getUsers = async(keyword) => {
this.users = database.objects('users');
getUsers = debounce(async(keyword) => {
let res = await RocketChat.search({ text: keyword, filterRooms: false, filterUsers: true });
res = [...this.getFixedMentions(keyword), ...res];
this.setState({ mentions: res });
}, 300)
getRooms = debounce(async(keyword = '') => {
const res = await RocketChat.search({ text: keyword, filterRooms: true, filterUsers: false });
this.setState({ mentions: res });
}, 300)
getEmojis = debounce(async(keyword) => {
const db = database.active;
if (keyword) {
this.users = this.users.filtered('username CONTAINS[c] $0', keyword);
const customEmojisCollection = db.collections.get('custom_emojis');
let customEmojis = await customEmojisCollection.query(
Q.where('name', Q.like(`${ Q.sanitizeLikeString(keyword) }%`))
).fetch();
customEmojis = customEmojis.slice(0, MENTIONS_COUNT_TO_DISPLAY);
const filteredEmojis = emojis.filter(emoji => emoji.indexOf(keyword) !== -1).slice(0, MENTIONS_COUNT_TO_DISPLAY);
const mergedEmojis = [...customEmojis, ...filteredEmojis].slice(0, MENTIONS_COUNT_TO_DISPLAY);
this.setState({ mentions: mergedEmojis || [] });
}
this.getFixedMentions(keyword);
this.setState({ mentions: this.users.slice() });
}, 300)
const usernames = [];
if (keyword && this.users.length > 7) {
return;
}
this.users.forEach(user => usernames.push(user.username));
if (this.oldPromise) {
this.oldPromise();
}
try {
const results = await Promise.race([
RocketChat.spotlight(keyword, usernames, { users: true }),
new Promise((resolve, reject) => (this.oldPromise = reject))
]);
if (results.users && results.users.length) {
database.write(() => {
results.users.forEach((user) => {
try {
database.create('users', user, true);
} catch (e) {
log(e);
}
});
});
}
} catch (e) {
console.warn('spotlight canceled');
} finally {
delete this.oldPromise;
this.users = database.objects('users').filtered('username CONTAINS[c] $0', keyword).slice(0, MENTIONS_COUNT_TO_DISPLAY);
this.getFixedMentions(keyword);
this.setState({ mentions: this.users });
}
}
getRooms = async(keyword = '') => {
this.roomsCache = this.roomsCache || [];
this.rooms = database.objects('subscriptions')
.filtered('t != $0', 'd');
if (keyword) {
this.rooms = this.rooms.filtered('name CONTAINS[c] $0', keyword);
}
const rooms = [];
this.rooms.forEach(room => rooms.push(room));
this.roomsCache.forEach((room) => {
if (room.name && room.name.toUpperCase().indexOf(keyword.toUpperCase()) !== -1) {
rooms.push(room);
}
});
if (rooms.length > 3) {
this.setState({ mentions: rooms });
return;
}
if (this.oldPromise) {
this.oldPromise();
}
try {
const results = await Promise.race([
RocketChat.spotlight(keyword, [...rooms, ...this.roomsCache].map(r => r.name), { rooms: true }),
new Promise((resolve, reject) => (this.oldPromise = reject))
]);
if (results.rooms && results.rooms.length) {
this.roomsCache = [...this.roomsCache, ...results.rooms].filter(onlyUnique);
}
this.setState({ mentions: [...rooms.slice(), ...results.rooms] });
} catch (e) {
console.warn('spotlight canceled');
} finally {
delete this.oldPromise;
}
}
getEmojis = (keyword) => {
if (keyword) {
this.customEmojis = database.objects('customEmojis').filtered('name CONTAINS[c] $0', keyword).slice(0, MENTIONS_COUNT_TO_DISPLAY);
this.emojis = emojis.filter(emoji => emoji.indexOf(keyword) !== -1).slice(0, MENTIONS_COUNT_TO_DISPLAY);
const mergedEmojis = [...this.customEmojis, ...this.emojis].slice(0, MENTIONS_COUNT_TO_DISPLAY);
this.setState({ mentions: mergedEmojis });
}
}
getSlashCommands = (keyword) => {
this.commands = database.objects('slashCommand').filtered('command CONTAINS[c] $0', keyword);
this.setState({ mentions: this.commands });
}
getSlashCommands = debounce(async(keyword) => {
const db = database.active;
const commandsCollection = db.collections.get('slash_commands');
const commands = await commandsCollection.query(
Q.where('id', Q.like(`${ Q.sanitizeLikeString(keyword) }%`))
).fetch();
this.setState({ mentions: commands || [] });
}, 300)
focus = () => {
if (this.component && this.component.focus) {
@ -468,7 +415,7 @@ class MessageBox extends Component {
this.setState({ commandPreview: preview.items });
} catch (e) {
this.showCommandPreview = false;
log('command Preview', e);
log(e);
}
}
@ -546,9 +493,9 @@ class MessageBox extends Component {
mime: res.type,
path: res.uri
});
} catch (error) {
if (!DocumentPicker.isCancel(error)) {
log('chooseFile', error);
} catch (e) {
if (!DocumentPicker.isCancel(e)) {
log(e);
}
}
}
@ -629,7 +576,7 @@ class MessageBox extends Component {
submit = async() => {
const {
message: editingMessage, editRequest, onSubmit, rid: roomId
onSubmit, rid: roomId
} = this.props;
const message = this.text;
@ -646,16 +593,19 @@ class MessageBox extends Component {
} = this.props;
// Slash command
if (message[0] === MENTIONS_TRACKING_TYPE_COMMANDS) {
const db = database.active;
const commandsCollection = db.collections.get('slash_commands');
const command = message.replace(/ .*/, '').slice(1);
const slashCommand = database.objects('slashCommand').filtered('command CONTAINS[c] $0', command);
const slashCommand = await commandsCollection.query(
Q.where('id', Q.like(`${ Q.sanitizeLikeString(command) }%`))
).fetch();
if (slashCommand.length > 0) {
try {
const messageWithoutCommand = message.substr(message.indexOf(' ') + 1);
RocketChat.runSlashCommand(command, roomId, messageWithoutCommand);
} catch (e) {
log('slashCommand', e);
log(e);
}
this.clearInput();
return;
@ -663,32 +613,35 @@ class MessageBox extends Component {
}
// Edit
if (editing) {
const { _id, rid } = editingMessage;
editRequest({ _id, msg: message, rid });
const { message: editingMessage, editRequest } = this.props;
const { id, subscription: { id: rid } } = editingMessage;
editRequest({ id, msg: message, rid });
// Reply
} else if (replying) {
const { replyMessage, closeReply, threadsEnabled } = this.props;
const {
message: replyingMessage, replyCancel, threadsEnabled, replyWithMention
} = this.props;
// Thread
if (threadsEnabled && replyMessage.mention) {
onSubmit(message, replyMessage._id);
if (threadsEnabled && replyWithMention) {
onSubmit(message, replyingMessage.id);
// Legacy reply or quote (quote is a reply without mention)
} else {
const { user, roomType } = this.props;
const permalink = await this.getPermalink(replyMessage);
const permalink = await this.getPermalink(replyingMessage);
let msg = `[ ](${ permalink }) `;
// if original message wasn't sent by current user and neither from a direct room
if (user.username !== replyMessage.u.username && roomType !== 'd' && replyMessage.mention) {
msg += `@${ replyMessage.u.username } `;
if (user.username !== replyingMessage.u.username && roomType !== 'd' && replyWithMention) {
msg += `@${ replyingMessage.u.username } `;
}
msg = `${ msg } ${ message }`;
onSubmit(msg);
}
closeReply();
replyCancel();
// Normal message
} else {
@ -726,11 +679,6 @@ class MessageBox extends Component {
trackingType: '',
commandPreview: []
});
this.users = [];
this.rooms = [];
this.customEmojis = [];
this.emojis = [];
this.commands = [];
}
renderFixedMentionItem = item => (
@ -761,7 +709,7 @@ class MessageBox extends Component {
key='mention-item-avatar'
style={styles.mentionItemEmoji}
>
{emojify(`:${ item }:`, { output: 'unicode' })}
{shortnameToUnicode(`:${ item }:`)}
</Text>
);
}
@ -797,33 +745,33 @@ class MessageBox extends Component {
switch (trackingType) {
case MENTIONS_TRACKING_TYPE_EMOJIS:
return (
<React.Fragment>
<>
{this.renderMentionEmoji(item)}
<Text key='mention-item-name' style={styles.mentionText}>:{ item.name || item }:</Text>
</React.Fragment>
</>
);
case MENTIONS_TRACKING_TYPE_COMMANDS:
return (
<React.Fragment>
<>
<Text key='mention-item-command' style={styles.slash}>/</Text>
<Text key='mention-item-param'>{ item.command}</Text>
</React.Fragment>
</>
);
default:
return (
<React.Fragment>
<>
<Avatar
key='mention-item-avatar'
style={styles.avatar}
text={item.username || item.name}
size={30}
type={item.username ? 'd' : 'c'}
type={item.t}
baseUrl={baseUrl}
userId={user.id}
token={user.token}
/>
<Text key='mention-item-name' style={styles.mentionText}>{ item.username || item.name || item }</Text>
</React.Fragment>
</>
);
}
})()
@ -880,12 +828,12 @@ class MessageBox extends Component {
renderReplyPreview = () => {
const {
replyMessage, replying, closeReply, user
message, replying, replyCancel, user, getCustomEmoji
} = this.props;
if (!replying) {
return null;
}
return <ReplyPreview key='reply-preview' message={replyMessage} close={closeReply} username={user.username} />;
return <ReplyPreview key='reply-preview' message={message} close={replyCancel} username={user.username} getCustomEmoji={getCustomEmoji} />;
};
renderContent = () => {
@ -896,7 +844,7 @@ class MessageBox extends Component {
return (<Recording onFinish={this.finishAudioMessage} />);
}
return (
<React.Fragment>
<>
{this.renderCommandPreview()}
{this.renderMentions()}
<View style={styles.composer} key='messagebox'>
@ -935,14 +883,15 @@ class MessageBox extends Component {
/>
</View>
</View>
</React.Fragment>
</>
);
}
render() {
console.count(`${ this.constructor.name }.render calls`);
const { showEmojiKeyboard, file } = this.state;
return (
<React.Fragment>
<>
<KeyboardAccessoryView
renderContent={this.renderContent}
kbInputRef={this.component}
@ -960,16 +909,12 @@ class MessageBox extends Component {
close={() => this.setState({ file: {} })}
submit={this.sendMediaMessage}
/>
</React.Fragment>
</>
);
}
}
const mapStateToProps = state => ({
message: state.messages.message,
replyMessage: state.messages.replyMessage,
replying: state.messages.replying,
editing: state.messages.editing,
baseUrl: state.settings.Site_Url || state.server ? state.server.server : '',
threadsEnabled: state.settings.Threads_enabled,
user: {
@ -980,10 +925,7 @@ const mapStateToProps = state => ({
});
const dispatchToProps = ({
editCancel: () => editCancelAction(),
editRequest: message => editRequestAction(message),
typing: (rid, status) => userTypingAction(rid, status),
closeReply: () => replyCancelAction()
typing: (rid, status) => userTypingAction(rid, status)
});
export default connect(mapStateToProps, dispatchToProps, null, { forwardRef: true })(MessageBox);

View File

@ -1,33 +1,18 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import ActionSheet from 'react-native-action-sheet';
import { errorActionsHide as errorActionsHideAction } from '../actions/messages';
import RocketChat from '../lib/rocketchat';
import database from '../lib/realm';
import database from '../lib/database';
import protectedFunction from '../lib/methods/helpers/protectedFunction';
import I18n from '../i18n';
class MessageErrorActions extends React.Component {
static propTypes = {
errorActionsHide: PropTypes.func.isRequired,
actionMessage: PropTypes.object
actionsHide: PropTypes.func.isRequired,
message: PropTypes.object
};
handleResend = protectedFunction(() => {
const { actionMessage } = this.props;
RocketChat.resendMessage(actionMessage._id);
});
handleDelete = protectedFunction(() => {
const { actionMessage } = this.props;
database.write(() => {
const msg = database.objects('messages').filtered('_id = $0', actionMessage._id);
database.delete(msg);
});
})
// eslint-disable-next-line react/sort-comp
constructor(props) {
super(props);
@ -41,6 +26,19 @@ class MessageErrorActions extends React.Component {
});
}
handleResend = protectedFunction(async() => {
const { message } = this.props;
await RocketChat.resendMessage(message);
});
handleDelete = protectedFunction(async() => {
const { message } = this.props;
const db = database.active;
await db.action(async() => {
await message.destroyPermanently();
});
})
showActionSheet = () => {
ActionSheet.showActionSheetWithOptions({
options: this.options,
@ -53,7 +51,7 @@ class MessageErrorActions extends React.Component {
}
handleActionPress = (actionIndex) => {
const { errorActionsHide } = this.props;
const { actionsHide } = this.props;
switch (actionIndex) {
case this.RESEND_INDEX:
this.handleResend();
@ -64,7 +62,7 @@ class MessageErrorActions extends React.Component {
default:
break;
}
errorActionsHide();
actionsHide();
}
render() {
@ -74,12 +72,4 @@ class MessageErrorActions extends React.Component {
}
}
const mapStateToProps = state => ({
actionMessage: state.messages.actionMessage
});
const mapDispatchToProps = dispatch => ({
errorActionsHide: () => dispatch(errorActionsHideAction())
});
export default connect(mapStateToProps, mapDispatchToProps)(MessageErrorActions);
export default MessageErrorActions;

View File

@ -7,7 +7,6 @@ import Modal from 'react-native-modal';
import Touchable from 'react-native-platform-touchable';
import Emoji from './message/Emoji';
import { getCustomEmoji } from './message/utils';
import I18n from '../i18n';
import { CustomIcon } from '../lib/Icons';
import sharedStyles from '../views/Styles';
@ -62,7 +61,9 @@ const styles = StyleSheet.create({
const standardEmojiStyle = { fontSize: 20 };
const customEmojiStyle = { width: 20, height: 20 };
const Item = React.memo(({ item, user, baseUrl }) => {
const Item = React.memo(({
item, user, baseUrl, getCustomEmoji
}) => {
const count = item.usernames.length;
let usernames = item.usernames.slice(0, 3)
.map(username => (username === user.username ? I18n.t('you') : username)).join(', ');
@ -146,7 +147,8 @@ ModalContent.displayName = 'ReactionsModalContent';
Item.propTypes = {
item: PropTypes.object,
user: PropTypes.object,
baseUrl: PropTypes.string
baseUrl: PropTypes.string,
getCustomEmoji: PropTypes.func
};
Item.displayName = 'ReactionsModalItem';

View File

@ -3,56 +3,26 @@ import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Status from './Status';
import database, { safeAddListener } from '../../lib/realm';
class StatusContainer extends React.PureComponent {
static propTypes = {
id: PropTypes.string,
style: PropTypes.any,
size: PropTypes.number,
offline: PropTypes.bool
status: PropTypes.string
};
static defaultProps = {
size: 16
}
constructor(props) {
super(props);
this.user = database.memoryDatabase.objects('activeUsers').filtered('id == $0', props.id);
this.state = {
user: this.user[0] || {}
};
safeAddListener(this.user, this.updateState);
}
componentWillUnmount() {
this.user.removeAllListeners();
}
get status() {
const { user } = this.state;
const { offline } = this.props;
if (offline || !user) {
return 'offline';
}
return user.status || 'offline';
}
updateState = () => {
if (this.user.length) {
this.setState({ user: this.user[0] });
}
}
render() {
const { style, size } = this.props;
return <Status size={size} style={style} status={this.status} />;
const { style, size, status } = this.props;
return <Status size={size} style={style} status={status} />;
}
}
const mapStateToProps = state => ({
offline: !state.meteor.connected
const mapStateToProps = (state, ownProps) => ({
status: state.meteor.connected ? state.activeUsers[ownProps.id] : 'offline'
});
export default connect(mapStateToProps)(StatusContainer);

View File

@ -1,7 +1,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Text } from 'react-native';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import CustomEmoji from '../EmojiPicker/CustomEmoji';
@ -10,7 +10,7 @@ import styles from './styles';
const Emoji = React.memo(({
emojiName, literal, isMessageContainsOnlyEmoji, getCustomEmoji, baseUrl
}) => {
const emojiUnicode = emojify(literal, { output: 'unicode' });
const emojiUnicode = shortnameToUnicode(literal);
const emoji = getCustomEmoji && getCustomEmoji(emojiName);
if (emoji) {
return (

View File

@ -3,6 +3,7 @@ import { View, Text, Image } from 'react-native';
import { Parser, Node } from 'commonmark';
import Renderer from 'commonmark-react-renderer';
import PropTypes from 'prop-types';
import { toShort, shortnameToUnicode } from 'emoji-toolkit';
import I18n from '../../i18n';
@ -52,6 +53,8 @@ const emojiCount = (str) => {
return counter;
};
const encodeEmojis = str => toShort(shortnameToUnicode(str));
export default class Markdown extends PureComponent {
static propTypes = {
msg: PropTypes.string,
@ -154,14 +157,12 @@ export default class Markdown extends PureComponent {
}
renderParagraph = ({ children }) => {
const { numberOfLines } = this.props;
if (!children || children.length === 0) {
return null;
}
return (
<View style={styles.block}>
<Text numberOfLines={numberOfLines}>
<Text>
{children}
</Text>
</View>
@ -286,7 +287,8 @@ export default class Markdown extends PureComponent {
}
const ast = this.parser.parse(m);
this.isMessageContainsOnlyEmoji = isOnlyEmoji(m) && emojiCount(m) <= 3;
const encodedEmojis = encodeEmojis(m);
this.isMessageContainsOnlyEmoji = isOnlyEmoji(encodedEmojis) && emojiCount(encodedEmojis) <= 3;
this.editedMessage(ast);

View File

@ -24,10 +24,10 @@ const Content = React.memo((props) => {
getCustomEmoji={props.getCustomEmoji}
username={props.user.username}
isEdited={props.isEdited}
numberOfLines={props.tmid ? 1 : 0}
numberOfLines={(props.tmid && !props.isThreadRoom) ? 1 : 0}
channels={props.channels}
mentions={props.mentions}
useMarkdown={props.useMarkdown}
useMarkdown={props.useMarkdown && (!props.tmid || props.isThreadRoom)}
navToRoomInfo={props.navToRoomInfo}
tmid={props.tmid}
/>
@ -45,6 +45,7 @@ Content.propTypes = {
isTemp: PropTypes.bool,
isInfo: PropTypes.bool,
tmid: PropTypes.string,
isThreadRoom: PropTypes.bool,
msg: PropTypes.string,
isEdited: PropTypes.bool,
useMarkdown: PropTypes.bool,

View File

@ -1,7 +1,7 @@
import React from 'react';
import { Text } from 'react-native';
import PropTypes from 'prop-types';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import CustomEmoji from '../EmojiPicker/CustomEmoji';
@ -13,7 +13,7 @@ const Emoji = React.memo(({
if (emoji) {
return <CustomEmoji key={content} baseUrl={baseUrl} style={customEmojiStyle} emoji={emoji} />;
}
return <Text style={standardEmojiStyle}>{ emojify(content, { output: 'unicode' }) }</Text>;
return <Text style={standardEmojiStyle}>{ shortnameToUnicode(content) }</Text>;
}, () => true);
Emoji.propTypes = {

View File

@ -32,7 +32,7 @@ const MessageAvatar = React.memo(({
);
}
return null;
}, (prevProps, nextProps) => prevProps.isHeader === nextProps.isHeader);
});
MessageAvatar.propTypes = {
isHeader: PropTypes.bool,

View File

@ -8,9 +8,9 @@ import styles from './styles';
import Emoji from './Emoji';
import { BUTTON_HIT_SLOP } from './utils';
const AddReaction = React.memo(({ toggleReactionPicker }) => (
const AddReaction = React.memo(({ reactionInit }) => (
<Touchable
onPress={toggleReactionPicker}
onPress={reactionInit}
key='message-add-reaction'
testID='message-add-reaction'
style={styles.reactionButton}
@ -52,7 +52,7 @@ const Reaction = React.memo(({
});
const Reactions = React.memo(({
reactions, user, baseUrl, onReactionPress, toggleReactionPicker, onReactionLongPress, getCustomEmoji
reactions, user, baseUrl, onReactionPress, reactionInit, onReactionLongPress, getCustomEmoji
}) => {
if (!reactions || reactions.length === 0) {
return null;
@ -70,11 +70,10 @@ const Reactions = React.memo(({
getCustomEmoji={getCustomEmoji}
/>
))}
<AddReaction toggleReactionPicker={toggleReactionPicker} />
<AddReaction reactionInit={reactionInit} />
</View>
);
});
// FIXME: can't compare because it's a Realm object (it may be fixed by JSON.parse(JSON.stringify(reactions)))
Reaction.propTypes = {
reaction: PropTypes.object,
@ -91,14 +90,14 @@ Reactions.propTypes = {
user: PropTypes.object,
baseUrl: PropTypes.string,
onReactionPress: PropTypes.func,
toggleReactionPicker: PropTypes.func,
reactionInit: PropTypes.func,
onReactionLongPress: PropTypes.func,
getCustomEmoji: PropTypes.func
};
Reactions.displayName = 'MessageReactions';
AddReaction.propTypes = {
toggleReactionPicker: PropTypes.func
reactionInit: PropTypes.func
};
AddReaction.displayName = 'MessageAddReaction';

View File

@ -1,7 +1,7 @@
import React from 'react';
import { View, Text } from 'react-native';
import removeMarkdown from 'remove-markdown';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import PropTypes from 'prop-types';
import { CustomIcon } from '../../lib/Icons';
@ -9,18 +9,18 @@ import DisclosureIndicator from '../DisclosureIndicator';
import styles from './styles';
const RepliedThread = React.memo(({
tmid, tmsg, isHeader, isTemp, fetchThreadName
tmid, tmsg, isHeader, isTemp, fetchThreadName, id
}) => {
if (!tmid || !isHeader || isTemp) {
return null;
}
if (!tmsg) {
fetchThreadName(tmid);
fetchThreadName(tmid, id);
return null;
}
let msg = emojify(tmsg, { output: 'unicode' });
let msg = shortnameToUnicode(tmsg);
msg = removeMarkdown(msg);
return (
@ -49,6 +49,7 @@ const RepliedThread = React.memo(({
RepliedThread.propTypes = {
tmid: PropTypes.string,
tmsg: PropTypes.string,
id: PropTypes.string,
isHeader: PropTypes.bool,
isTemp: PropTypes.bool,
fetchThreadName: PropTypes.func

View File

@ -8,9 +8,9 @@ import { CustomIcon } from '../../lib/Icons';
import { THREAD } from './constants';
const Thread = React.memo(({
msg, tcount, tlm, customThreadTimeFormat
msg, tcount, tlm, customThreadTimeFormat, isThreadRoom
}) => {
if (!tlm) {
if (!tlm || isThreadRoom) {
return null;
}
@ -39,7 +39,8 @@ Thread.propTypes = {
msg: PropTypes.string,
tcount: PropTypes.string,
tlm: PropTypes.string,
customThreadTimeFormat: PropTypes.string
customThreadTimeFormat: PropTypes.string,
isThreadRoom: PropTypes.bool
};
Thread.displayName = 'MessageThread';

View File

@ -10,7 +10,7 @@ import { isIOS } from '../../utils/deviceInfo';
import { CustomIcon } from '../../lib/Icons';
import { formatAttachmentUrl } from '../../lib/utils';
const SUPPORTED_TYPES = ['video/quicktime', 'video/mp4', ...(isIOS ? [] : ['video/webm', 'video/3gp', 'video/mkv'])];
const SUPPORTED_TYPES = ['video/quicktime', 'video/mp4', ...(isIOS ? [] : ['video/3gp', 'video/mkv'])];
const isTypeSupported = type => SUPPORTED_TYPES.indexOf(type) !== -1;
const styles = StyleSheet.create({

View File

@ -4,7 +4,7 @@ import { KeyboardUtils } from 'react-native-keyboard-input';
import Message from './Message';
import debounce from '../../utils/debounce';
import { SYSTEM_MESSAGES, getCustomEmoji, getMessageTranslation } from './utils';
import { SYSTEM_MESSAGES, getMessageTranslation } from './utils';
import messagesStatus from '../../constants/messagesStatus';
export default class MessageContainer extends React.Component {
@ -21,22 +21,23 @@ export default class MessageContainer extends React.Component {
archived: PropTypes.bool,
broadcast: PropTypes.bool,
previousItem: PropTypes.object,
_updatedAt: PropTypes.instanceOf(Date),
baseUrl: PropTypes.string,
Message_GroupingPeriod: PropTypes.number,
isReadReceiptEnabled: PropTypes.bool,
isThreadRoom: PropTypes.bool,
useRealName: PropTypes.bool,
useMarkdown: PropTypes.bool,
autoTranslateRoom: PropTypes.bool,
autoTranslateLanguage: PropTypes.string,
status: PropTypes.number,
getCustomEmoji: PropTypes.func,
onLongPress: PropTypes.func,
onReactionPress: PropTypes.func,
onDiscussionPress: PropTypes.func,
onThreadPress: PropTypes.func,
errorActionsShow: PropTypes.func,
replyBroadcast: PropTypes.func,
toggleReactionPicker: PropTypes.func,
reactionInit: PropTypes.func,
fetchThreadName: PropTypes.func,
onOpenFileModal: PropTypes.func,
onReactionLongPress: PropTypes.func,
@ -45,55 +46,53 @@ export default class MessageContainer extends React.Component {
static defaultProps = {
onLongPress: () => {},
_updatedAt: new Date(),
archived: false,
broadcast: false
}
shouldComponentUpdate(nextProps) {
const {
status, item, _updatedAt, autoTranslateRoom
} = this.props;
componentDidMount() {
const { item } = this.props;
if (item && item.observe) {
const observable = item.observe();
this.subscription = observable.subscribe(() => {
this.forceUpdate();
});
}
}
if (status !== nextProps.status) {
return true;
}
if (autoTranslateRoom !== nextProps.autoTranslateRoom) {
return true;
}
if (item.tmsg !== nextProps.item.tmsg) {
return true;
}
if (item.unread !== nextProps.item.unread) {
return true;
}
shouldComponentUpdate() {
return false;
}
return _updatedAt.toISOString() !== nextProps._updatedAt.toISOString();
componentWillUnmount() {
if (this.subscription && this.subscription.unsubscribe) {
this.subscription.unsubscribe();
}
}
onPress = debounce(() => {
const { item } = this.props;
const { item, isThreadRoom } = this.props;
KeyboardUtils.dismiss();
if ((item.tlm || item.tmid)) {
if (((item.tlm || item.tmid) && !isThreadRoom)) {
this.onThreadPress();
}
}, 300, true);
onLongPress = () => {
const { archived, onLongPress } = this.props;
const { archived, onLongPress, item } = this.props;
if (this.isInfo || this.hasError || archived) {
return;
}
if (onLongPress) {
onLongPress(this.parseMessage());
onLongPress(item);
}
}
onErrorPress = () => {
const { errorActionsShow } = this.props;
const { errorActionsShow, item } = this.props;
if (errorActionsShow) {
errorActionsShow(this.parseMessage());
errorActionsShow(item);
}
}
@ -132,23 +131,30 @@ export default class MessageContainer extends React.Component {
if (this.hasError || (previousItem && previousItem.status === messagesStatus.ERROR)) {
return true;
}
if (previousItem && (
(previousItem.ts.toDateString() === item.ts.toDateString())
&& (previousItem.u.username === item.u.username)
&& !(previousItem.groupable === false || item.groupable === false || broadcast === true)
&& (item.ts - previousItem.ts < Message_GroupingPeriod * 1000)
&& (previousItem.tmid === item.tmid)
)) {
return false;
try {
if (previousItem && (
(previousItem.ts.toDateString() === item.ts.toDateString())
&& (previousItem.u.username === item.u.username)
&& !(previousItem.groupable === false || item.groupable === false || broadcast === true)
&& (item.ts - previousItem.ts < Message_GroupingPeriod * 1000)
&& (previousItem.tmid === item.tmid)
)) {
return false;
}
return true;
} catch (error) {
return true;
}
return true;
}
get isThreadReply() {
const {
item, previousItem
item, previousItem, isThreadRoom
} = this.props;
if (previousItem && item.tmid && (previousItem.tmid !== item.tmid) && (previousItem._id !== item.tmid)) {
if (isThreadRoom) {
return false;
}
if (previousItem && item.tmid && (previousItem.tmid !== item.tmid) && (previousItem.id !== item.tmid)) {
return true;
}
return false;
@ -156,9 +162,12 @@ export default class MessageContainer extends React.Component {
get isThreadSequential() {
const {
item, previousItem
item, previousItem, isThreadRoom
} = this.props;
if (previousItem && item.tmid && ((previousItem.tmid === item.tmid) || (previousItem._id === item.tmid))) {
if (isThreadRoom) {
return false;
}
if (previousItem && item.tmid && ((previousItem.tmid === item.tmid) || (previousItem.id === item.tmid))) {
return true;
}
return false;
@ -179,31 +188,26 @@ export default class MessageContainer extends React.Component {
return item.status === messagesStatus.ERROR;
}
parseMessage = () => {
const { item } = this.props;
return JSON.parse(JSON.stringify(item));
}
toggleReactionPicker = () => {
const { toggleReactionPicker } = this.props;
if (toggleReactionPicker) {
toggleReactionPicker(this.parseMessage());
reactionInit = () => {
const { reactionInit, item } = this.props;
if (reactionInit) {
reactionInit(item);
}
}
replyBroadcast = () => {
const { replyBroadcast } = this.props;
const { replyBroadcast, item } = this.props;
if (replyBroadcast) {
replyBroadcast(this.parseMessage());
replyBroadcast(item);
}
}
render() {
const {
item, user, style, archived, baseUrl, useRealName, broadcast, fetchThreadName, customThreadTimeFormat, onOpenFileModal, timeFormat, useMarkdown, isReadReceiptEnabled, autoTranslateRoom, autoTranslateLanguage, navToRoomInfo
item, user, style, archived, baseUrl, useRealName, broadcast, fetchThreadName, customThreadTimeFormat, onOpenFileModal, timeFormat, useMarkdown, isReadReceiptEnabled, autoTranslateRoom, autoTranslateLanguage, navToRoomInfo, getCustomEmoji, isThreadRoom
} = this.props;
const {
_id, msg, ts, attachments, urls, reactions, t, avatar, u, alias, editedBy, role, drid, dcount, dlm, tmid, tcount, tlm, tmsg, mentions, channels, unread, autoTranslate: autoTranslateMessage
id, msg, ts, attachments, urls, reactions, t, avatar, u, alias, editedBy, role, drid, dcount, dlm, tmid, tcount, tlm, tmsg, mentions, channels, unread, autoTranslate: autoTranslateMessage
} = item;
let message = msg;
@ -215,7 +219,7 @@ export default class MessageContainer extends React.Component {
return (
<Message
id={_id}
id={id}
msg={message}
author={u}
ts={ts}
@ -251,6 +255,7 @@ export default class MessageContainer extends React.Component {
isHeader={this.isHeader}
isThreadReply={this.isThreadReply}
isThreadSequential={this.isThreadSequential}
isThreadRoom={isThreadRoom}
isInfo={this.isInfo}
isTemp={this.isTemp}
hasError={this.hasError}
@ -260,7 +265,7 @@ export default class MessageContainer extends React.Component {
onReactionLongPress={this.onReactionLongPress}
onReactionPress={this.onReactionPress}
replyBroadcast={this.replyBroadcast}
toggleReactionPicker={this.toggleReactionPicker}
reactionInit={this.reactionInit}
onDiscussionPress={this.onDiscussionPress}
onOpenFileModal={onOpenFileModal}
getCustomEmoji={getCustomEmoji}

View File

@ -1,7 +1,6 @@
import moment from 'moment';
import I18n from '../../i18n';
import database from '../../lib/realm';
import { DISCUSSION } from './constants';
export const formatLastMessage = (lm, customFormat) => {
@ -96,25 +95,6 @@ export const getInfoMessage = ({
return '';
};
export const getCustomEmoji = (content) => {
// search by name
const data = database.objects('customEmojis').filtered('name == $0', content);
if (data.length) {
return data[0];
}
// searches by alias
// RealmJS doesn't support IN operator: https://github.com/realm/realm-js/issues/450
const emojis = database.objects('customEmojis');
const findByAlias = emojis.find((emoji) => {
if (emoji.aliases.length && emoji.aliases.findIndex(alias => alias === content) !== -1) {
return true;
}
return false;
});
return findByAlias;
};
export const getMessageTranslation = (message, autoTranslateLanguage) => {
if (!autoTranslateLanguage) {
return null;

View File

@ -94,6 +94,7 @@ export default {
and: 'and',
announcement: 'announcement',
Announcement: 'Announcement',
Apply_Your_Certificate: 'Apply Your Certificate',
ARCHIVE: 'ARCHIVE',
archive: 'archive',
are_typing: 'are typing',
@ -137,6 +138,8 @@ export default {
Copied_to_clipboard: 'Copied to clipboard!',
Copy: 'Copy',
Permalink: 'Permalink',
Certificate_password: 'Certificate Password',
Whats_the_password_for_your_certificate: 'What\'s the password for your certificate?',
Create_account: 'Create an account',
Create_Channel: 'Create Channel',
Created_snippet: 'Created a snippet',
@ -155,6 +158,7 @@ export default {
Disable_notifications: 'Disable notifications',
Discussions: 'Discussions',
Dont_Have_An_Account: 'Don\'t have an account?',
Do_you_have_a_certificate: 'Do you have a certificate?',
Do_you_really_want_to_key_this_room_question_mark: 'Do you really want to {{key}} this room?',
edit: 'edit',
edited: 'edited',
@ -427,6 +431,7 @@ export default {
you: 'you',
You: 'You',
You_need_to_access_at_least_one_RocketChat_server_to_share_something: 'You need to access at least one Rocket.Chat server to share something.',
Your_certificate: 'Your Certificate',
Version_no: 'Version: {{version}}',
You_will_not_be_able_to_recover_this_message: 'You will not be able to recover this message!',
Change_Language: 'Change Language',

View File

@ -1,7 +1,7 @@
import React from 'react';
import {
createStackNavigator, createAppContainer, createSwitchNavigator, createDrawerNavigator
} from 'react-navigation';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { Provider } from 'react-redux';
import { useScreens } from 'react-native-screens'; // eslint-disable-line import/no-unresolved
import { Linking } from 'react-native';

82
app/lib/database/index.js Normal file
View File

@ -0,0 +1,82 @@
import { Database } from '@nozbe/watermelondb';
import SQLiteAdapter from '@nozbe/watermelondb/adapters/sqlite';
import RNFetchBlob from 'rn-fetch-blob';
import Subscription from './model/Subscription';
import Room from './model/Room';
import Message from './model/Message';
import Thread from './model/Thread';
import ThreadMessage from './model/ThreadMessage';
import CustomEmoji from './model/CustomEmoji';
import FrequentlyUsedEmoji from './model/FrequentlyUsedEmoji';
import Upload from './model/Upload';
import Setting from './model/Setting';
import Role from './model/Role';
import Permission from './model/Permission';
import SlashCommand from './model/SlashCommand';
import User from './model/User';
import Server from './model/Server';
import serversSchema from './schema/servers';
import appSchema from './schema/app';
import { isIOS } from '../../utils/deviceInfo';
const appGroupPath = isIOS ? `${ RNFetchBlob.fs.syncPathAppGroup('group.ios.chat.rocket') }/` : '';
if (__DEV__ && isIOS) {
console.log(appGroupPath);
}
class DB {
databases = {
serversDB: new Database({
adapter: new SQLiteAdapter({
dbName: `${ appGroupPath }default.db`,
schema: serversSchema
}),
modelClasses: [Server, User],
actionsEnabled: true
})
}
get active() {
return this.databases.activeDB;
}
get servers() {
return this.databases.serversDB;
}
setActiveDB(database = '') {
const path = database.replace(/(^\w+:|^)\/\//, '');
const dbName = `${ appGroupPath }${ path }.db`;
const adapter = new SQLiteAdapter({
dbName,
schema: appSchema
});
this.databases.activeDB = new Database({
adapter,
modelClasses: [
Subscription,
Room,
Message,
Thread,
ThreadMessage,
CustomEmoji,
FrequentlyUsedEmoji,
Upload,
Setting,
Role,
Permission,
SlashCommand
],
actionsEnabled: true
});
}
}
const db = new DB();
export default db;

View File

@ -0,0 +1,16 @@
import { Model } from '@nozbe/watermelondb';
import { field, date, json } from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class CustomEmoji extends Model {
static table = 'custom_emojis';
@field('name') name;
@json('aliases', sanitizer) aliases;
@field('extension') extension;
@date('_updated_at') _updatedAt;
}

View File

@ -0,0 +1,14 @@
import { Model } from '@nozbe/watermelondb';
import { field } from '@nozbe/watermelondb/decorators';
export default class FrequentlyUsedEmoji extends Model {
static table = 'frequently_used_emojis';
@field('content') content;
@field('extension') extension;
@field('is_custom') isCustom;
@field('count') count;
}

View File

@ -0,0 +1,76 @@
import { Model } from '@nozbe/watermelondb';
import {
field, relation, date, json
} from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class Message extends Model {
static table = 'messages';
static associations = {
subscriptions: { type: 'belongs_to', key: 'rid' }
}
@field('msg') msg;
@field('t') t;
@date('ts') ts;
@json('u', sanitizer) u;
@relation('subscriptions', 'rid') subscription;
@field('alias') alias;
@json('parse_urls', sanitizer) parseUrls;
@field('groupable') groupable;
@field('avatar') avatar;
@json('attachments', sanitizer) attachments;
@json('urls', sanitizer) urls;
@date('_updated_at') _updatedAt;
@field('status') status;
@field('pinned') pinned;
@field('starred') starred;
@json('edited_by', sanitizer) editedBy;
@json('reactions', sanitizer) reactions;
@field('role') role;
@field('drid') drid;
@field('dcount') dcount;
@date('dlm') dlm;
@field('tmid') tmid;
@field('tcount') tcount;
@date('tlm') tlm;
@json('replies', sanitizer) replies;
@json('mentions', sanitizer) mentions;
@json('channels', sanitizer) channels;
@field('unread') unread;
@field('auto_translate') autoTranslate;
@json('translations', sanitizer) translations;
@field('tmsg') tmsg;
}

View File

@ -0,0 +1,12 @@
import { Model } from '@nozbe/watermelondb';
import { json, date } from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class Permission extends Model {
static table = 'permissions';
@json('roles', sanitizer) roles;
@date('_updated_at') _updatedAt;
}

View File

@ -0,0 +1,8 @@
import { Model } from '@nozbe/watermelondb';
import { field } from '@nozbe/watermelondb/decorators';
export default class Role extends Model {
static table = 'roles';
@field('description') description;
}

View File

@ -0,0 +1,16 @@
import { Model } from '@nozbe/watermelondb';
import { field, json } from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class Room extends Model {
static table = 'rooms';
@json('custom_fields', sanitizer) customFields;
@field('broadcast') broadcast;
@field('encrypted') encrypted;
@field('ro') ro;
}

View File

@ -0,0 +1,20 @@
import { Model } from '@nozbe/watermelondb';
import { field, date } from '@nozbe/watermelondb/decorators';
export default class Server extends Model {
static table = 'servers';
@field('name') name;
@field('icon_url') iconURL;
@field('use_real_name') useRealName;
@field('file_upload_media_type_white_list') FileUpload_MediaTypeWhiteList;
@field('file_upload_max_file_size') FileUpload_MaxFileSize;
@date('rooms_updated_at') roomsUpdatedAt;
@field('version') version;
}

View File

@ -0,0 +1,14 @@
import { Model } from '@nozbe/watermelondb';
import { field, date } from '@nozbe/watermelondb/decorators';
export default class Setting extends Model {
static table = 'settings';
@field('value_as_string') valueAsString;
@field('value_as_boolean') valueAsBoolean;
@field('value_as_number') valueAsNumber;
@date('_updated_at') _updatedAt;
}

View File

@ -0,0 +1,14 @@
import { Model } from '@nozbe/watermelondb';
import { field } from '@nozbe/watermelondb/decorators';
export default class SlashCommand extends Model {
static table = 'slash_commands';
@field('params') params;
@field('description') description;
@field('client_only') clientOnly;
@field('provides_preview') providesPreview;
}

View File

@ -0,0 +1,88 @@
import { Model } from '@nozbe/watermelondb';
import {
field, date, json, children
} from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class Subscription extends Model {
static table = 'subscriptions';
static associations = {
messages: { type: 'has_many', foreignKey: 'rid' },
threads: { type: 'has_many', foreignKey: 'rid' },
thread_messages: { type: 'has_many', foreignKey: 'subscription_id' },
uploads: { type: 'has_many', foreignKey: 'rid' }
}
@field('_id') _id;
@field('f') f;
@field('t') t;
@date('ts') ts;
@date('ls') ls;
@field('name') name;
@field('fname') fname;
@field('rid') rid;
@field('open') open;
@field('alert') alert;
@json('roles', sanitizer) roles;
@field('unread') unread;
@field('user_mentions') userMentions;
@date('room_updated_at') roomUpdatedAt;
@field('ro') ro;
@date('last_open') lastOpen;
@field('description') description;
@field('announcement') announcement;
@field('topic') topic;
@field('blocked') blocked;
@field('blocker') blocker;
@field('react_when_read_only') reactWhenReadOnly;
@field('archived') archived;
@field('join_code_required') joinCodeRequired;
@field('notifications') notifications;
@json('muted', sanitizer) muted;
@field('broadcast') broadcast;
@field('prid') prid;
@field('draft_message') draftMessage;
@date('last_thread_sync') lastThreadSync;
@field('auto_translate') autoTranslate;
@field('auto_translate_language') autoTranslateLanguage;
@json('last_message', sanitizer) lastMessage;
@children('messages') messages;
@children('threads') threads;
@children('thread_messages') threadMessages;
}

View File

@ -0,0 +1,74 @@
import { Model } from '@nozbe/watermelondb';
import {
field, relation, date, json
} from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class Thread extends Model {
static table = 'threads';
static associations = {
subscriptions: { type: 'belongs_to', key: 'rid' }
}
@field('msg') msg;
@field('t') t;
@date('ts') ts;
@json('u', sanitizer) u;
@relation('subscriptions', 'rid') subscription;
@field('alias') alias;
@json('parse_urls', sanitizer) parseUrls;
@field('groupable') groupable;
@field('avatar') avatar;
@json('attachments', sanitizer) attachments;
@json('urls', sanitizer) urls;
@date('_updated_at') _updatedAt;
@field('status') status;
@field('pinned') pinned;
@field('starred') starred;
@json('edited_by', sanitizer) editedBy;
@json('reactions', sanitizer) reactions;
@field('role') role;
@field('drid') drid;
@field('dcount') dcount;
@date('dlm') dlm;
@field('tmid') tmid;
@field('tcount') tcount;
@date('tlm') tlm;
@json('replies', sanitizer) replies;
@json('mentions', sanitizer) mentions;
@json('channels', sanitizer) channels;
@field('unread') unread;
@field('auto_translate') autoTranslate;
@json('translations', sanitizer) translations;
}

View File

@ -0,0 +1,76 @@
import { Model } from '@nozbe/watermelondb';
import {
field, relation, date, json
} from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class ThreadMessage extends Model {
static table = 'thread_messages';
static associations = {
subscriptions: { type: 'belongs_to', key: 'subscription_id' }
}
@field('msg') msg;
@field('t') t;
@date('ts') ts;
@json('u', sanitizer) u;
@relation('subscriptions', 'subscription_id') subscription;
@field('rid') rid;
@field('alias') alias;
@json('parse_urls', sanitizer) parseUrls;
@field('groupable') groupable;
@field('avatar') avatar;
@json('attachments', sanitizer) attachments;
@json('urls', sanitizer) urls;
@date('_updated_at') _updatedAt;
@field('status') status;
@field('pinned') pinned;
@field('starred') starred;
@json('edited_by', sanitizer) editedBy;
@json('reactions', sanitizer) reactions;
@field('role') role;
@field('drid') drid;
@field('dcount') dcount;
@date('dlm') dlm;
@field('tcount') tcount;
@date('tlm') tlm;
@json('replies', sanitizer) replies;
@json('mentions', sanitizer) mentions;
@json('channels', sanitizer) channels;
@field('unread') unread;
@field('auto_translate') autoTranslate;
@json('translations', sanitizer) translations;
@field('draft_message') draftMessage;
}

View File

@ -0,0 +1,28 @@
import { Model } from '@nozbe/watermelondb';
import { field, relation } from '@nozbe/watermelondb/decorators';
export default class Upload extends Model {
static table = 'uploads';
static associations = {
subscriptions: { type: 'belongs_to', key: 'rid' }
}
@field('path') path;
@relation('subscriptions', 'rid') subscription;
@field('name') name;
@field('description') description;
@field('size') size;
@field('type') type;
@field('store') store;
@field('progress') progress;
@field('error') error;
}

View File

@ -0,0 +1,20 @@
import { Model } from '@nozbe/watermelondb';
import { field, json } from '@nozbe/watermelondb/decorators';
import { sanitizer } from '../utils';
export default class User extends Model {
static table = 'users';
@field('token') token;
@field('username') username;
@field('name') name;
@field('language') language;
@field('status') status;
@json('roles', sanitizer) roles;
}

View File

@ -0,0 +1,222 @@
import { appSchema, tableSchema } from '@nozbe/watermelondb';
export default appSchema({
version: 1,
tables: [
tableSchema({
name: 'subscriptions',
columns: [
{ name: '_id', type: 'string' },
{ name: 'f', type: 'boolean' },
{ name: 't', type: 'string', isIndexed: true },
{ name: 'ts', type: 'number' },
{ name: 'ls', type: 'number' },
{ name: 'name', type: 'string', isIndexed: true },
{ name: 'fname', type: 'string' },
{ name: 'rid', type: 'string', isIndexed: true },
{ name: 'open', type: 'boolean' },
{ name: 'alert', type: 'boolean' },
{ name: 'roles', type: 'string', isOptional: true },
{ name: 'unread', type: 'number' },
{ name: 'user_mentions', type: 'number' },
{ name: 'room_updated_at', type: 'number' },
{ name: 'ro', type: 'boolean' },
{ name: 'last_open', type: 'number', isOptional: true },
{ name: 'last_message', type: 'string', isOptional: true },
{ name: 'description', type: 'string', isOptional: true },
{ name: 'announcement', type: 'string', isOptional: true },
{ name: 'topic', type: 'string', isOptional: true },
{ name: 'blocked', type: 'boolean', isOptional: true },
{ name: 'blocker', type: 'boolean', isOptional: true },
{ name: 'react_when_read_only', type: 'boolean', isOptional: true },
{ name: 'archived', type: 'boolean' },
{ name: 'join_code_required', type: 'boolean', isOptional: true },
{ name: 'muted', type: 'string', isOptional: true },
{ name: 'broadcast', type: 'boolean', isOptional: true },
{ name: 'prid', type: 'string', isOptional: true },
{ name: 'draft_message', type: 'string', isOptional: true },
{ name: 'last_thread_sync', type: 'number', isOptional: true },
{ name: 'auto_translate', type: 'boolean', isOptional: true },
{ name: 'auto_translate_language', type: 'string' }
]
}),
tableSchema({
name: 'rooms',
columns: [
{ name: 'custom_fields', type: 'string' },
{ name: 'broadcast', type: 'boolean' },
{ name: 'encrypted', type: 'boolean' },
{ name: 'ro', type: 'boolean' }
]
}),
tableSchema({
name: 'messages',
columns: [
{ name: 'msg', type: 'string', isOptional: true },
{ name: 't', type: 'string', isOptional: true },
{ name: 'rid', type: 'string', isIndexed: true },
{ name: 'ts', type: 'number' },
{ name: 'u', type: 'string' },
{ name: 'alias', type: 'string' },
{ name: 'parse_urls', type: 'string' },
{ name: 'groupable', type: 'boolean', isOptional: true },
{ name: 'avatar', type: 'string', isOptional: true },
{ name: 'attachments', type: 'string', isOptional: true },
{ name: 'urls', type: 'string', isOptional: true },
{ name: '_updated_at', type: 'number' },
{ name: 'status', type: 'number', isOptional: true },
{ name: 'pinned', type: 'boolean', isOptional: true },
{ name: 'starred', type: 'boolean', isOptional: true },
{ name: 'edited_by', type: 'string', isOptional: true },
{ name: 'reactions', type: 'string', isOptional: true },
{ name: 'role', type: 'string', isOptional: true },
{ name: 'drid', type: 'string', isOptional: true },
{ name: 'dcount', type: 'number', isOptional: true },
{ name: 'dlm', type: 'number', isOptional: true },
{ name: 'tmid', type: 'string', isOptional: true },
{ name: 'tcount', type: 'number', isOptional: true },
{ name: 'tlm', type: 'number', isOptional: true },
{ name: 'replies', type: 'string', isOptional: true },
{ name: 'mentions', type: 'string', isOptional: true },
{ name: 'channels', type: 'string', isOptional: true },
{ name: 'unread', type: 'boolean', isOptional: true },
{ name: 'auto_translate', type: 'boolean', isOptional: true },
{ name: 'translations', type: 'string', isOptional: true },
{ name: 'tmsg', type: 'string', isOptional: true }
]
}),
tableSchema({
name: 'threads',
columns: [
{ name: 'msg', type: 'string', isOptional: true },
{ name: 't', type: 'string', isOptional: true },
{ name: 'rid', type: 'string', isIndexed: true },
{ name: '_updated_at', type: 'number' },
{ name: 'ts', type: 'number' },
{ name: 'u', type: 'string' },
{ name: 'alias', type: 'string', isOptional: true },
{ name: 'parse_urls', type: 'string', isOptional: true },
{ name: 'groupable', type: 'boolean', isOptional: true },
{ name: 'avatar', type: 'string', isOptional: true },
{ name: 'attachments', type: 'string', isOptional: true },
{ name: 'urls', type: 'string', isOptional: true },
{ name: 'status', type: 'number', isOptional: true },
{ name: 'pinned', type: 'boolean', isOptional: true },
{ name: 'starred', type: 'boolean', isOptional: true },
{ name: 'edited_by', type: 'string', isOptional: true },
{ name: 'reactions', type: 'string', isOptional: true },
{ name: 'role', type: 'string', isOptional: true },
{ name: 'drid', type: 'string', isOptional: true },
{ name: 'dcount', type: 'number', isOptional: true },
{ name: 'dlm', type: 'number', isOptional: true },
{ name: 'tmid', type: 'string', isOptional: true },
{ name: 'tcount', type: 'number', isOptional: true },
{ name: 'tlm', type: 'number', isOptional: true },
{ name: 'replies', type: 'string', isOptional: true },
{ name: 'mentions', type: 'string', isOptional: true },
{ name: 'channels', type: 'string', isOptional: true },
{ name: 'unread', type: 'boolean', isOptional: true },
{ name: 'auto_translate', type: 'boolean', isOptional: true },
{ name: 'translations', type: 'string', isOptional: true }
]
}),
tableSchema({
name: 'thread_messages',
columns: [
{ name: 'msg', type: 'string', isOptional: true },
{ name: 't', type: 'string', isOptional: true },
{ name: 'rid', type: 'string', isIndexed: true },
{ name: 'subscription_id', type: 'string', isIndexed: true },
{ name: '_updated_at', type: 'number' },
{ name: 'ts', type: 'number' },
{ name: 'u', type: 'string' },
{ name: 'alias', type: 'string', isOptional: true },
{ name: 'parse_urls', type: 'string', isOptional: true },
{ name: 'groupable', type: 'boolean', isOptional: true },
{ name: 'avatar', type: 'string', isOptional: true },
{ name: 'attachments', type: 'string', isOptional: true },
{ name: 'urls', type: 'string', isOptional: true },
{ name: 'status', type: 'number', isOptional: true },
{ name: 'pinned', type: 'boolean', isOptional: true },
{ name: 'starred', type: 'boolean', isOptional: true },
{ name: 'edited_by', type: 'string', isOptional: true },
{ name: 'reactions', type: 'string', isOptional: true },
{ name: 'role', type: 'string', isOptional: true },
{ name: 'drid', type: 'string', isOptional: true },
{ name: 'dcount', type: 'number', isOptional: true },
{ name: 'dlm', type: 'number', isOptional: true },
{ name: 'tcount', type: 'number', isOptional: true },
{ name: 'tlm', type: 'number', isOptional: true },
{ name: 'replies', type: 'string', isOptional: true },
{ name: 'mentions', type: 'string', isOptional: true },
{ name: 'channels', type: 'string', isOptional: true },
{ name: 'unread', type: 'boolean', isOptional: true },
{ name: 'auto_translate', type: 'boolean', isOptional: true },
{ name: 'translations', type: 'string', isOptional: true }
]
}),
tableSchema({
name: 'custom_emojis',
columns: [
{ name: 'name', type: 'string', isOptional: true },
{ name: 'aliases', type: 'string', isOptional: true },
{ name: 'extension', type: 'string' },
{ name: '_updated_at', type: 'number' }
]
}),
tableSchema({
name: 'frequently_used_emojis',
columns: [
{ name: 'content', type: 'string', isOptional: true },
{ name: 'extension', type: 'string', isOptional: true },
{ name: 'is_custom', type: 'boolean' },
{ name: 'count', type: 'number' }
]
}),
tableSchema({
name: 'uploads',
columns: [
{ name: 'path', type: 'string', isOptional: true },
{ name: 'rid', type: 'string', isIndexed: true },
{ name: 'name', type: 'string', isOptional: true },
{ name: 'description', type: 'string', isOptional: true },
{ name: 'size', type: 'number' },
{ name: 'type', type: 'string', isOptional: true },
{ name: 'store', type: 'string', isOptional: true },
{ name: 'progress', type: 'number' },
{ name: 'error', type: 'boolean' }
]
}),
tableSchema({
name: 'settings',
columns: [
{ name: 'value_as_string', type: 'string', isOptional: true },
{ name: 'value_as_boolean', type: 'boolean', isOptional: true },
{ name: 'value_as_number', type: 'number', isOptional: true },
{ name: '_updated_at', type: 'number', isOptional: true }
]
}),
tableSchema({
name: 'roles',
columns: [
{ name: 'description', type: 'string', isOptional: true }
]
}),
tableSchema({
name: 'permissions',
columns: [
{ name: 'roles', type: 'string' },
{ name: '_updated_at', type: 'number', isOptional: true }
]
}),
tableSchema({
name: 'slash_commands',
columns: [
{ name: 'params', type: 'string', isOptional: true },
{ name: 'description', type: 'string', isOptional: true },
{ name: 'client_only', type: 'boolean', isOptional: true },
{ name: 'provides_preview', type: 'boolean', isOptional: true }
]
})
]
});

View File

@ -0,0 +1,30 @@
import { appSchema, tableSchema } from '@nozbe/watermelondb';
export default appSchema({
version: 2,
tables: [
tableSchema({
name: 'users',
columns: [
{ name: 'token', type: 'string', isOptional: true },
{ name: 'username', type: 'string', isOptional: true },
{ name: 'name', type: 'string', isOptional: true },
{ name: 'language', type: 'string', isOptional: true },
{ name: 'status', type: 'string', isOptional: true },
{ name: 'roles', type: 'string', isOptional: true }
]
}),
tableSchema({
name: 'servers',
columns: [
{ name: 'name', type: 'string', isOptional: true },
{ name: 'icon_url', type: 'string', isOptional: true },
{ name: 'use_real_name', type: 'boolean', isOptional: true },
{ name: 'file_upload_media_type_white_list', type: 'string', isOptional: true },
{ name: 'file_upload_max_file_size', type: 'number', isOptional: true },
{ name: 'rooms_updated_at', type: 'number', isOptional: true },
{ name: 'version', type: 'string', isOptional: true }
]
})
]
});

View File

@ -0,0 +1 @@
export const sanitizer = r => r;

View File

@ -1,4 +1,4 @@
import database from '../realm';
import database from '../database';
const restTypes = {
channel: 'channels', direct: 'im', group: 'groups'
@ -18,18 +18,26 @@ async function open({ type, rid }) {
}
export default async function canOpenRoom({ rid, path }) {
const [type] = path.split('/');
if (type === 'channel') {
return true;
}
const room = database.objects('subscriptions').filtered('rid == $0', rid);
if (room.length) {
return true;
}
try {
return await open.call(this, { type, rid });
const db = database.active;
const subsCollection = db.collections.get('subscriptions');
const [type] = path.split('/');
if (type === 'channel') {
return true;
}
try {
await subsCollection.find(rid);
return true;
} catch (error) {
// Do nothing
}
try {
return await open.call(this, { type, rid });
} catch (e) {
return false;
}
} catch (e) {
return false;
}

View File

@ -1,45 +1,110 @@
import { InteractionManager } from 'react-native';
import semver from 'semver';
import orderBy from 'lodash/orderBy';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import reduxStore from '../createStore';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import { setCustomEmojis as setCustomEmojisAction } from '../../actions/customEmojis';
const getUpdatedSince = () => {
const emoji = database.objects('customEmojis').sorted('_updatedAt', true)[0];
return emoji && emoji._updatedAt.toISOString();
const getUpdatedSince = (allEmojis) => {
if (!allEmojis.length) {
return null;
}
const ordered = orderBy(allEmojis.filter(item => item._updatedAt !== null), ['_updatedAt'], ['desc']);
return ordered && ordered[0]._updatedAt.toISOString();
};
const create = (customEmojis) => {
if (customEmojis && customEmojis.length) {
customEmojis.forEach((emoji) => {
try {
database.create('customEmojis', emoji, true);
} catch (e) {
// log('getEmojis create', e);
}
const updateEmojis = async({ update = [], remove = [], allRecords }) => {
if (!((update && update.length) || (remove && remove.length))) {
return;
}
const db = database.active;
const emojisCollection = db.collections.get('custom_emojis');
let emojisToCreate = [];
let emojisToUpdate = [];
let emojisToDelete = [];
// Create or update
if (update && update.length) {
emojisToCreate = update.filter(i1 => !allRecords.find(i2 => i1._id === i2.id));
emojisToUpdate = allRecords.filter(i1 => update.find(i2 => i1.id === i2._id));
emojisToCreate = emojisToCreate.map(emoji => emojisCollection.prepareCreate((e) => {
e._raw = sanitizedRaw({ id: emoji._id }, emojisCollection.schema);
Object.assign(e, emoji);
}));
emojisToUpdate = emojisToUpdate.map((emoji) => {
const newEmoji = update.find(e => e._id === emoji.id);
return emoji.prepareUpdate((e) => {
Object.assign(e, newEmoji);
});
});
}
if (remove && remove.length) {
emojisToDelete = allRecords.filter(i1 => remove.find(i2 => i1.id === i2._id));
emojisToDelete = emojisToDelete.map(emoji => emoji.prepareDestroyPermanently());
}
try {
await db.action(async() => {
await db.batch(
...emojisToCreate,
...emojisToUpdate,
...emojisToDelete
);
});
return true;
} catch (e) {
log(e);
}
};
export async function setCustomEmojis() {
const db = database.active;
const emojisCollection = db.collections.get('custom_emojis');
const allEmojis = await emojisCollection.query().fetch();
const parsed = allEmojis.reduce((ret, item) => {
ret[item.name] = {
name: item.name,
extension: item.extension
};
item.aliases.forEach((alias) => {
ret[alias] = {
name: item.name,
extension: item.extension
};
});
return ret;
}, {});
reduxStore.dispatch(setCustomEmojisAction(parsed));
}
export default function() {
export function getCustomEmojis() {
return new Promise(async(resolve) => {
try {
const serverVersion = reduxStore.getState().server.version;
const updatedSince = getUpdatedSince();
const db = database.active;
const emojisCollection = db.collections.get('custom_emojis');
const allRecords = await emojisCollection.query().fetch();
const updatedSince = await getUpdatedSince(allRecords);
// if server version is lower than 0.75.0, fetches from old api
if (semver.lt(serverVersion, '0.75.0')) {
// RC 0.61.0
const result = await this.sdk.get('emoji-custom');
InteractionManager.runAfterInteractions(() => {
InteractionManager.runAfterInteractions(async() => {
let { emojis } = result;
emojis = emojis.filter(emoji => !updatedSince || emoji._updatedAt > updatedSince);
database.write(() => {
create(emojis);
});
const changedEmojis = await updateEmojis({ update: emojis, allRecords });
// `setCustomEmojis` is fired on selectServer
// We run it again only if emojis were changed
if (changedEmojis) {
setCustomEmojis();
}
return resolve();
});
} else {
@ -55,26 +120,17 @@ export default function() {
return resolve();
}
InteractionManager.runAfterInteractions(
() => database.write(() => {
const { emojis } = result;
create(emojis.update);
InteractionManager.runAfterInteractions(async() => {
const { emojis } = result;
const { update, remove } = emojis;
const changedEmojis = await updateEmojis({ update, remove, allRecords });
if (emojis.delete && emojis.delete.length) {
emojis.delete.forEach((emoji) => {
try {
const emojiRecord = database.objectForPrimaryKey('customEmojis', emoji._id);
if (emojiRecord) {
database.delete(emojiRecord);
}
} catch (e) {
log(e);
}
});
}
return resolve();
})
);
// `setCustomEmojis` is fired on selectServer
// We run it again only if emojis were changed
if (changedEmojis) {
setCustomEmojis();
}
});
}
} catch (e) {
log(e);

View File

@ -1,31 +1,82 @@
import { InteractionManager } from 'react-native';
import semver from 'semver';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { orderBy } from 'lodash';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import reduxStore from '../createStore';
import protectedFunction from './helpers/protectedFunction';
const getUpdatedSince = () => {
const permissions = database.objects('permissions').sorted('_updatedAt', true)[0];
return permissions && permissions._updatedAt.toISOString();
const getUpdatedSince = (allRecords) => {
try {
if (!allRecords.length) {
return null;
}
const ordered = orderBy(allRecords.filter(item => item._updatedAt !== null), ['_updatedAt'], ['desc']);
return ordered && ordered[0]._updatedAt.toISOString();
} catch (e) {
log(e);
}
return null;
};
const create = (permissions) => {
if (permissions && permissions.length) {
permissions.forEach((permission) => {
try {
database.create('permissions', permission, true);
} catch (e) {
log(e);
}
const updatePermissions = async({ update = [], remove = [], allRecords }) => {
if (!((update && update.length) || (remove && remove.length))) {
return;
}
const db = database.active;
const permissionsCollection = db.collections.get('permissions');
// filter permissions
let permissionsToCreate = [];
let permissionsToUpdate = [];
let permissionsToDelete = [];
// Create or update
if (update && update.length) {
permissionsToCreate = update.filter(i1 => !allRecords.find(i2 => i1._id === i2.id));
permissionsToUpdate = allRecords.filter(i1 => update.find(i2 => i1.id === i2._id));
permissionsToCreate = permissionsToCreate.map(permission => permissionsCollection.prepareCreate(protectedFunction((p) => {
p._raw = sanitizedRaw({ id: permission._id }, permissionsCollection.schema);
Object.assign(p, permission);
})));
permissionsToUpdate = permissionsToUpdate.map((permission) => {
const newPermission = update.find(p => p._id === permission.id);
return permission.prepareUpdate(protectedFunction((p) => {
Object.assign(p, newPermission);
}));
});
}
// Delete
if (remove && remove.length) {
permissionsToDelete = allRecords.filter(i1 => remove.find(i2 => i1.id === i2._id));
permissionsToDelete = permissionsToDelete.map(permission => permission.prepareDestroyPermanently());
}
const batch = [
...permissionsToCreate,
...permissionsToUpdate,
...permissionsToDelete
];
try {
await db.action(async() => {
await db.batch(...batch);
});
} catch (e) {
log(e);
}
};
export default function() {
return new Promise(async(resolve) => {
try {
const serverVersion = reduxStore.getState().server.version;
const db = database.active;
const permissionsCollection = db.collections.get('permissions');
const allRecords = await permissionsCollection.query().fetch();
// if server version is lower than 0.73.0, fetches from old api
if (semver.lt(serverVersion, '0.73.0')) {
@ -34,15 +85,13 @@ export default function() {
if (!result.success) {
return resolve();
}
InteractionManager.runAfterInteractions(() => {
database.write(() => {
create(result.permissions);
});
InteractionManager.runAfterInteractions(async() => {
await updatePermissions({ update: result.permissions, allRecords });
return resolve();
});
} else {
const params = {};
const updatedSince = getUpdatedSince();
const updatedSince = await getUpdatedSince(allRecords);
if (updatedSince) {
params.updatedSince = updatedSince;
}
@ -53,25 +102,10 @@ export default function() {
return resolve();
}
InteractionManager.runAfterInteractions(
() => database.write(() => {
create(result.update);
if (result.delete && result.delete.length) {
result.delete.forEach((p) => {
try {
const permission = database.objectForPrimaryKey('permissions', p._id);
if (permission) {
database.delete(permission);
}
} catch (e) {
log(e);
}
});
}
return resolve();
})
);
InteractionManager.runAfterInteractions(async() => {
await updatePermissions({ update: result.update, remove: result.delete, allRecords });
return resolve();
});
}
} catch (e) {
log(e);

View File

@ -1,9 +1,12 @@
import { InteractionManager } from 'react-native';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import protectedFunction from './helpers/protectedFunction';
export default function() {
const db = database.active;
return new Promise(async(resolve) => {
try {
// RC 0.70.0
@ -16,14 +19,41 @@ export default function() {
const { roles } = result;
if (roles && roles.length) {
InteractionManager.runAfterInteractions(() => {
database.write(() => roles.forEach((role) => {
InteractionManager.runAfterInteractions(async() => {
await db.action(async() => {
const rolesCollections = db.collections.get('roles');
const allRolesRecords = await rolesCollections.query().fetch();
// filter roles
let rolesToCreate = roles.filter(i1 => !allRolesRecords.find(i2 => i1._id === i2.id));
let rolesToUpdate = allRolesRecords.filter(i1 => roles.find(i2 => i1.id === i2._id));
// Create
rolesToCreate = rolesToCreate.map(role => rolesCollections.prepareCreate(protectedFunction((r) => {
r._raw = sanitizedRaw({ id: role._id }, rolesCollections.schema);
Object.assign(r, role);
})));
// Update
rolesToUpdate = rolesToUpdate.map((role) => {
const newRole = roles.find(r => r._id === role.id);
return role.prepareUpdate(protectedFunction((r) => {
Object.assign(r, newRole);
}));
});
const allRecords = [
...rolesToCreate,
...rolesToUpdate
];
try {
database.create('roles', role, true);
await db.batch(...allRecords);
} catch (e) {
log(e);
}
}));
return allRecords.length;
});
return resolve();
});
}

View File

@ -1,23 +1,58 @@
import { InteractionManager } from 'react-native';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { Q } from '@nozbe/watermelondb';
import reduxStore from '../createStore';
import database from '../realm';
import * as actions from '../../actions';
import log from '../../utils/log';
import settings from '../../constants/settings';
import log from '../../utils/log';
import database from '../database';
import protectedFunction from './helpers/protectedFunction';
function updateServer(param) {
database.databases.serversDB.write(() => {
const serverInfoKeys = ['Site_Name', 'UI_Use_Real_Name', 'FileUpload_MediaTypeWhiteList', 'FileUpload_MaxFileSize'];
const serverInfoUpdate = async(serverInfo, iconSetting) => {
const serversDB = database.servers;
const serverId = reduxStore.getState().server.server;
let info = serverInfo.reduce((allSettings, setting) => {
if (setting._id === 'Site_Name') {
return { ...allSettings, name: setting.valueAsString };
}
if (setting._id === 'UI_Use_Real_Name') {
return { ...allSettings, useRealName: setting.valueAsBoolean };
}
if (setting._id === 'FileUpload_MediaTypeWhiteList') {
return { ...allSettings, FileUpload_MediaTypeWhiteList: setting.valueAsString };
}
if (setting._id === 'FileUpload_MaxFileSize') {
return { ...allSettings, FileUpload_MaxFileSize: setting.valueAsNumber };
}
return allSettings;
}, {});
if (iconSetting) {
const iconURL = `${ serverId }/${ iconSetting.value.url || iconSetting.value.defaultUrl }`;
info = { ...info, iconURL };
}
await serversDB.action(async() => {
try {
database.databases.serversDB.create('servers', { id: reduxStore.getState().server.server, ...param }, true);
const serversCollection = serversDB.collections.get('servers');
const server = await serversCollection.find(serverId);
await server.update((record) => {
Object.assign(record, info);
});
} catch (e) {
log(e);
}
});
}
};
export default async function() {
try {
const db = database.active;
const settingsParams = JSON.stringify(Object.keys(settings));
// RC 0.60.0
const result = await fetch(`${ this.sdk.client.host }/api/v1/settings.public?query={"_id":{"$in":${ settingsParams }}}`).then(response => response.json());
@ -27,39 +62,52 @@ export default async function() {
}
const data = result.settings || [];
const filteredSettings = this._prepareSettings(data.filter(item => item._id !== 'Assets_favicon_512'));
const filteredSettingsIds = filteredSettings.map(s => s._id);
InteractionManager.runAfterInteractions(
() => database.write(
() => filteredSettings.forEach((setting) => {
try {
database.create('settings', { ...setting, _updatedAt: new Date() }, true);
} catch (e) {
log(e);
}
if (setting._id === 'Site_Name') {
updateServer.call(this, { name: setting.valueAsString });
}
if (setting._id === 'UI_Use_Real_Name') {
updateServer.call(this, { useRealName: setting.valueAsBoolean });
}
if (setting._id === 'FileUpload_MediaTypeWhiteList') {
updateServer.call(this, { FileUpload_MediaTypeWhiteList: setting.valueAsString });
}
if (setting._id === 'FileUpload_MaxFileSize') {
updateServer.call(this, { FileUpload_MaxFileSize: setting.valueAsNumber });
}
})
)
);
reduxStore.dispatch(actions.addSettings(this.parseSettings(filteredSettings)));
InteractionManager.runAfterInteractions(async() => {
// filter server info
const serverInfo = filteredSettings.filter(i1 => serverInfoKeys.includes(i1._id));
const iconSetting = data.find(item => item._id === 'Assets_favicon_512');
await serverInfoUpdate(serverInfo, iconSetting);
const iconSetting = data.find(item => item._id === 'Assets_favicon_512');
if (iconSetting) {
const baseUrl = reduxStore.getState().server.server;
const iconURL = `${ baseUrl }/${ iconSetting.value.url || iconSetting.value.defaultUrl }`;
updateServer.call(this, { iconURL });
}
await db.action(async() => {
const settingsCollection = db.collections.get('settings');
const allSettingsRecords = await settingsCollection
.query(Q.where('id', Q.oneOf(filteredSettingsIds)))
.fetch();
// filter settings
let settingsToCreate = filteredSettings.filter(i1 => !allSettingsRecords.find(i2 => i1._id === i2.id));
let settingsToUpdate = allSettingsRecords.filter(i1 => filteredSettings.find(i2 => i1.id === i2._id));
// Create
settingsToCreate = settingsToCreate.map(setting => settingsCollection.prepareCreate(protectedFunction((s) => {
s._raw = sanitizedRaw({ id: setting._id }, settingsCollection.schema);
Object.assign(s, setting);
})));
// Update
settingsToUpdate = settingsToUpdate.map((setting) => {
const newSetting = filteredSettings.find(s => s._id === setting.id);
return setting.prepareUpdate(protectedFunction((s) => {
Object.assign(s, newSetting);
}));
});
const allRecords = [
...settingsToCreate,
...settingsToUpdate
];
try {
await db.batch(...allRecords);
} catch (e) {
log(e);
}
return allRecords.length;
});
});
} catch (e) {
log(e);
}

View File

@ -1,31 +1,60 @@
import { InteractionManager } from 'react-native';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import protectedFunction from './helpers/protectedFunction';
export default function() {
const db = database.active;
return new Promise(async(resolve) => {
try {
// RC 0.60.2
const result = await this.sdk.get('commands.list');
if (!result.success) {
log('getSlashCommand fetch', result);
console.log(result);
return resolve();
}
const { commands } = result;
if (commands && commands.length) {
InteractionManager.runAfterInteractions(() => {
database.write(() => commands.forEach((command) => {
InteractionManager.runAfterInteractions(async() => {
await db.action(async() => {
const slashCommandsCollection = db.collections.get('slash_commands');
const allSlashCommandsRecords = await slashCommandsCollection.query().fetch();
// filter slash commands
let slashCommandsToCreate = commands.filter(i1 => !allSlashCommandsRecords.find(i2 => i1.command === i2.id));
let slashCommandsToUpdate = allSlashCommandsRecords.filter(i1 => commands.find(i2 => i1.id === i2.command));
// Create
slashCommandsToCreate = slashCommandsToCreate.map(command => slashCommandsCollection.prepareCreate(protectedFunction((s) => {
s._raw = sanitizedRaw({ id: command.command }, slashCommandsCollection.schema);
Object.assign(s, command);
})));
// Update
slashCommandsToUpdate = slashCommandsToUpdate.map((command) => {
const newCommand = commands.find(s => s.command === command.id);
return command.prepareUpdate(protectedFunction((s) => {
Object.assign(s, newCommand);
}));
});
const allRecords = [
...slashCommandsToCreate,
...slashCommandsToUpdate
];
try {
database.create('slashCommand', command, true);
await db.batch(...allRecords);
} catch (e) {
log('get_slash_command', e);
log(e);
}
}));
return resolve();
return allRecords.length;
});
});
}
} catch (e) {

View File

@ -11,18 +11,17 @@ export const merge = (subscription, room) => {
return;
}
if (room) {
if (room.rid) {
subscription.rid = room.rid;
if (room._updatedAt) {
subscription.roomUpdatedAt = room._updatedAt;
subscription.lastMessage = normalizeMessage(room.lastMessage);
subscription.description = room.description;
subscription.topic = room.topic;
subscription.announcement = room.announcement;
subscription.reactWhenReadOnly = room.reactWhenReadOnly;
subscription.archived = room.archived || false;
subscription.joinCodeRequired = room.joinCodeRequired;
}
subscription.roomUpdatedAt = room._updatedAt;
subscription.lastMessage = normalizeMessage(room.lastMessage);
subscription.ro = room.ro;
subscription.description = room.description;
subscription.topic = room.topic;
subscription.announcement = room.announcement;
subscription.reactWhenReadOnly = room.reactWhenReadOnly;
subscription.archived = room.archived;
subscription.joinCodeRequired = room.joinCodeRequired;
subscription.broadcast = room.broadcast;
if (!subscription.roles || !subscription.roles.length) {
subscription.roles = [];

View File

@ -2,12 +2,6 @@ export default fn => (...params) => {
try {
fn(...params);
} catch (e) {
let error = e;
if (typeof error !== 'object') {
error = { error };
}
if (__DEV__) {
alert(error);
}
console.log(e);
}
};

View File

@ -1,24 +1,9 @@
import { InteractionManager } from 'react-native';
import buildMessage from './helpers/buildMessage';
import database from '../realm';
import log from '../../utils/log';
import updateMessages from './updateMessages';
async function load({ rid: roomId, latest, t }) {
if (t === 'l') {
try {
// RC 0.51.0
const data = await this.sdk.methodCall('loadHistory', roomId, null, 50, latest);
if (!data || data.status === 'error') {
return [];
}
return data.messages;
} catch (e) {
log(e);
return [];
}
}
let params = { roomId, count: 50 };
if (latest) {
params = { ...params, latest: new Date(latest).toISOString() };
@ -31,30 +16,14 @@ async function load({ rid: roomId, latest, t }) {
return data.messages;
}
export default function loadMessagesForRoom(...args) {
export default function loadMessagesForRoom(args) {
return new Promise(async(resolve, reject) => {
try {
const data = await load.call(this, ...args);
const data = await load.call(this, args);
if (data && data.length) {
InteractionManager.runAfterInteractions(() => {
database.write(() => data.forEach((message) => {
message = buildMessage(message);
try {
database.create('messages', message, true);
// if it's a thread "header"
if (message.tlm) {
database.create('threads', message, true);
}
// if it belongs to a thread
if (message.tmid) {
message.rid = message.tmid;
database.create('threadMessages', message, true);
}
} catch (e) {
log(e);
}
}));
InteractionManager.runAfterInteractions(async() => {
await updateMessages({ rid: args.rid, update: data });
return resolve(data);
});
} else {

View File

@ -1,14 +1,19 @@
import { InteractionManager } from 'react-native';
import buildMessage from './helpers/buildMessage';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import updateMessages from './updateMessages';
const getLastUpdate = (rid) => {
const sub = database
.objects('subscriptions')
.filtered('rid == $0', rid)[0];
return sub && new Date(sub.lastOpen).toISOString();
const getLastUpdate = async(rid) => {
try {
const db = database.active;
const subsCollection = db.collections.get('subscriptions');
const sub = await subsCollection.find(rid);
return sub.lastOpen.toISOString();
} catch (e) {
// Do nothing
}
return null;
};
async function load({ rid: roomId, lastOpen }) {
@ -16,59 +21,23 @@ async function load({ rid: roomId, lastOpen }) {
if (lastOpen) {
lastUpdate = new Date(lastOpen).toISOString();
} else {
lastUpdate = getLastUpdate(roomId);
lastUpdate = await getLastUpdate(roomId);
}
// RC 0.60.0
const { result } = await this.sdk.get('chat.syncMessages', { roomId, lastUpdate });
return result;
}
export default function loadMissedMessages(...args) {
export default function loadMissedMessages(args) {
return new Promise(async(resolve, reject) => {
try {
const data = (await load.call(this, ...args));
const data = (await load.call(this, { rid: args.rid, lastOpen: args.lastOpen }));
if (data) {
if (data.updated && data.updated.length) {
const { updated } = data;
InteractionManager.runAfterInteractions(() => {
database.write(() => updated.forEach((message) => {
try {
message = buildMessage(message);
database.create('messages', message, true);
// if it's a thread "header"
if (message.tlm) {
database.create('threads', message, true);
}
if (message.tmid) {
message.rid = message.tmid;
database.create('threadMessages', message, true);
}
} catch (e) {
log(e);
}
}));
});
}
if (data.deleted && data.deleted.length) {
const { deleted } = data;
InteractionManager.runAfterInteractions(() => {
try {
database.write(() => {
deleted.forEach((m) => {
const message = database.objects('messages').filtered('_id = $0', m._id);
database.delete(message);
const thread = database.objects('threads').filtered('_id = $0', m._id);
database.delete(thread);
const threadMessage = database.objects('threadMessages').filtered('_id = $0', m._id);
database.delete(threadMessage);
});
});
} catch (e) {
log(e);
}
});
}
const { updated, deleted } = data;
InteractionManager.runAfterInteractions(async() => {
await updateMessages({ rid: args.rid, update: updated, remove: deleted });
});
}
resolve();
} catch (e) {

View File

@ -1,9 +1,11 @@
import { InteractionManager } from 'react-native';
import EJSON from 'ejson';
import { Q } from '@nozbe/watermelondb';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import buildMessage from './helpers/buildMessage';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import protectedFunction from './helpers/protectedFunction';
async function load({ tmid, offset }) {
try {
@ -21,29 +23,53 @@ async function load({ tmid, offset }) {
}
}
export default function loadThreadMessages({ tmid, offset = 0 }) {
export default function loadThreadMessages({ tmid, rid, offset = 0 }) {
return new Promise(async(resolve, reject) => {
try {
const data = await load.call(this, { tmid, offset });
let data = await load.call(this, { tmid, offset });
if (data && data.length) {
InteractionManager.runAfterInteractions(() => {
database.write(() => data.forEach((m) => {
try {
const message = buildMessage(EJSON.fromJSONValue(m));
message.rid = tmid;
database.create('threadMessages', message, true);
} catch (e) {
log(e);
}
}));
InteractionManager.runAfterInteractions(async() => {
try {
data = data.map(m => buildMessage(m));
const db = database.active;
const threadMessagesCollection = db.collections.get('thread_messages');
const allThreadMessagesRecords = await threadMessagesCollection.query(Q.where('rid', tmid)).fetch();
let threadMessagesToCreate = data.filter(i1 => !allThreadMessagesRecords.find(i2 => i1._id === i2.id));
let threadMessagesToUpdate = allThreadMessagesRecords.filter(i1 => data.find(i2 => i1.id === i2._id));
threadMessagesToCreate = threadMessagesToCreate.map(threadMessage => threadMessagesCollection.prepareCreate(protectedFunction((tm) => {
tm._raw = sanitizedRaw({ id: threadMessage._id }, threadMessagesCollection.schema);
Object.assign(tm, threadMessage);
tm.subscription.id = rid;
tm.rid = threadMessage.tmid;
delete threadMessage.tmid;
})));
threadMessagesToUpdate = threadMessagesToUpdate.map((threadMessage) => {
const newThreadMessage = data.find(t => t._id === threadMessage.id);
return threadMessage.prepareUpdate(protectedFunction((tm) => {
Object.assign(tm, newThreadMessage);
tm.rid = threadMessage.tmid;
delete threadMessage.tmid;
}));
});
await db.action(async() => {
await db.batch(
...threadMessagesToCreate,
...threadMessagesToUpdate
);
});
} catch (e) {
log(e);
}
return resolve(data);
});
} else {
return resolve([]);
}
} catch (e) {
log(e);
reject(e);
}
});

View File

@ -1,20 +1,26 @@
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
export default async function readMessages(rid) {
const ls = new Date();
export default async function readMessages(rid, lastOpen) {
try {
// RC 0.61.0
const data = await this.sdk.post('subscriptions.read', { rid });
const [subscription] = database.objects('subscriptions').filtered('rid = $0', rid);
database.write(() => {
subscription.open = true;
subscription.alert = false;
subscription.unread = 0;
subscription.userMentions = 0;
subscription.groupMentions = 0;
subscription.ls = ls;
subscription.lastOpen = ls;
const db = database.active;
await db.action(async() => {
try {
const subscription = await db.collections.get('subscriptions').find(rid);
await subscription.update((s) => {
s.open = true;
s.alert = false;
s.unread = 0;
s.userMentions = 0;
s.groupMentions = 0;
s.ls = lastOpen;
s.lastOpen = lastOpen;
});
} catch (e) {
// Do nothing
}
});
return data;
} catch (e) {

View File

@ -1,4 +1,6 @@
import database from '../realm';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import database from '../database';
import log from '../../utils/log';
const uploadQueue = {};
@ -7,26 +9,28 @@ export function isUploadActive(path) {
return !!uploadQueue[path];
}
export function cancelUpload(path) {
if (uploadQueue[path]) {
uploadQueue[path].abort();
database.write(() => {
const upload = database.objects('uploads').filtered('path = $0', path);
try {
database.delete(upload);
} catch (e) {
log(e);
}
});
delete uploadQueue[path];
export async function cancelUpload(item) {
if (uploadQueue[item.path]) {
uploadQueue[item.path].abort();
try {
const db = database.active;
await db.database.action(async() => {
await item.destroyPermanently();
});
} catch (e) {
log(e);
}
delete uploadQueue[item.path];
}
}
export function sendFileMessage(rid, fileInfo, tmid, server, user) {
return new Promise((resolve, reject) => {
return new Promise(async(resolve, reject) => {
try {
const { serversDB } = database.databases;
const { FileUpload_MaxFileSize, id: Site_Url } = serversDB.objectForPrimaryKey('servers', server);
const serversDB = database.servers;
const serversCollection = serversDB.collections.get('servers');
const serverInfo = await serversCollection.find(server);
const { FileUpload_MaxFileSize, id: Site_Url } = serverInfo;
const { id, token } = user;
// -1 maxFileSize means there is no limit
@ -41,13 +45,24 @@ export function sendFileMessage(rid, fileInfo, tmid, server, user) {
fileInfo.rid = rid;
database.write(() => {
const db = database.active;
const uploadsCollection = db.collections.get('uploads');
let uploadRecord;
try {
uploadRecord = await uploadsCollection.find(fileInfo.path);
} catch (error) {
try {
database.create('uploads', fileInfo, true);
await db.action(async() => {
uploadRecord = await uploadsCollection.create((u) => {
u._raw = sanitizedRaw({ id: fileInfo.path }, uploadsCollection.schema);
Object.assign(u, fileInfo);
u.subscription.id = rid;
});
});
} catch (e) {
return log(e);
}
});
}
uploadQueue[fileInfo.path] = xhr;
xhr.open('POST', uploadUrl);
@ -69,61 +84,60 @@ export function sendFileMessage(rid, fileInfo, tmid, server, user) {
xhr.setRequestHeader('X-Auth-Token', token);
xhr.setRequestHeader('X-User-Id', id);
xhr.upload.onprogress = ({ total, loaded }) => {
database.write(() => {
fileInfo.progress = Math.floor((loaded / total) * 100);
try {
database.create('uploads', fileInfo, true);
} catch (e) {
return log(e);
}
});
};
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 400) { // If response is all good...
database.write(() => {
const upload = database.objects('uploads').filtered('path = $0', fileInfo.path);
try {
database.delete(upload);
const response = JSON.parse(xhr.response);
resolve(response);
} catch (e) {
reject(e);
log(e);
}
});
} else {
database.write(() => {
fileInfo.error = true;
try {
database.create('uploads', fileInfo, true);
const response = JSON.parse(xhr.response);
reject(response);
} catch (err) {
reject(err);
log(err);
}
xhr.upload.onprogress = async({ total, loaded }) => {
try {
await db.action(async() => {
await uploadRecord.update((u) => {
u.progress = Math.floor((loaded / total) * 100);
});
});
} catch (e) {
log(e);
}
};
xhr.onerror = (e) => {
database.write(() => {
fileInfo.error = true;
xhr.onload = async() => {
if (xhr.status >= 200 && xhr.status < 400) { // If response is all good...
try {
database.create('uploads', fileInfo, true);
reject(e);
} catch (err) {
reject(err);
log(err);
await db.action(async() => {
await uploadRecord.destroyPermanently();
});
const response = JSON.parse(xhr.response);
resolve(response);
} catch (e) {
log(e);
}
});
} else {
try {
await db.action(async() => {
await uploadRecord.update((u) => {
u.error = true;
});
});
} catch (e) {
log(e);
}
const response = JSON.parse(xhr.response);
reject(response);
}
};
xhr.onerror = async(error) => {
try {
await db.action(async() => {
await uploadRecord.update((u) => {
u.error = true;
});
});
} catch (e) {
log(e);
}
reject(error);
};
xhr.send(formData);
} catch (err) {
log(err);
} catch (e) {
log(e);
}
});
}

View File

@ -1,38 +1,41 @@
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import messagesStatus from '../../constants/messagesStatus';
import buildMessage from './helpers/buildMessage';
import database from '../realm';
import database from '../database';
import log from '../../utils/log';
import random from '../../utils/random';
export const getMessage = (rid, msg = '', tmid, user) => {
export const getMessage = async(rid, msg = '', tmid, user) => {
const _id = random(17);
const { id, username } = user;
const message = {
_id,
rid,
msg,
tmid,
ts: new Date(),
_updatedAt: new Date(),
status: messagesStatus.TEMP,
u: {
_id: id || '1',
username
}
};
try {
database.write(() => {
database.create('messages', message, true);
const db = database.active;
const msgCollection = db.collections.get('messages');
let message;
await db.action(async() => {
message = await msgCollection.create((m) => {
m._raw = sanitizedRaw({ id: _id }, msgCollection.schema);
m.subscription.id = rid;
m.msg = msg;
m.tmid = tmid;
m.ts = new Date();
m._updatedAt = new Date();
m.status = messagesStatus.TEMP;
m.u = {
_id: id || '1',
username
};
});
});
return message;
} catch (error) {
console.warn('getMessage', error);
}
return message;
};
export async function sendMessageCall(message) {
const {
_id, rid, msg, tmid
id: _id, subscription: { id: rid }, msg, tmid
} = message;
// RC 0.60.0
const data = await this.sdk.post('chat.sendMessage', {
@ -45,24 +48,36 @@ export async function sendMessageCall(message) {
export default async function(rid, msg, tmid, user) {
try {
const message = getMessage(rid, msg, tmid, user);
const [room] = database.objects('subscriptions').filtered('rid == $0', rid);
if (room) {
database.write(() => {
room.draftMessage = null;
});
const db = database.active;
const subsCollections = db.collections.get('subscriptions');
const message = await getMessage(rid, msg, tmid, user);
if (!message) {
return;
}
try {
const ret = await sendMessageCall.call(this, message);
database.write(() => {
database.create('messages', buildMessage({ ...message, ...ret }), true);
const room = await subsCollections.find(rid);
await db.action(async() => {
await room.update((r) => {
r.draftMessage = null;
});
});
} catch (e) {
database.write(() => {
message.status = messagesStatus.ERROR;
database.create('messages', message, true);
// Do nothing
}
try {
await sendMessageCall.call(this, message);
await db.action(async() => {
await message.update((m) => {
m.status = messagesStatus.SENT;
});
});
} catch (e) {
await db.action(async() => {
await message.update((m) => {
m.status = messagesStatus.ERROR;
});
});
}
} catch (e) {

View File

@ -1,15 +1,19 @@
import EJSON from 'ejson';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { InteractionManager } from 'react-native';
import log from '../../../utils/log';
import protectedFunction from '../helpers/protectedFunction';
import buildMessage from '../helpers/buildMessage';
import database from '../../realm';
import debounce from '../../../utils/debounce';
import database from '../../database';
import reduxStore from '../../createStore';
import { addUserTyping, removeUserTyping, clearUserTyping } from '../../../actions/usersTyping';
const unsubscribe = subscriptions => subscriptions.forEach(sub => sub.unsubscribe().catch(() => console.log('unsubscribeRoom')));
const removeListener = listener => listener.stop();
export default function subscribeRoom({ rid }) {
console.log(`[RCRN] Subscribed to room ${ rid }`);
let promises;
let connectedListener;
let disconnectedListener;
@ -18,52 +22,7 @@ export default function subscribeRoom({ rid }) {
const typingTimeouts = {};
const handleConnection = () => {
this.loadMissedMessages({ rid });
};
const getUserTyping = username => (
database
.memoryDatabase.objects('usersTyping')
.filtered('rid = $0 AND username = $1', rid, username)
);
const removeUserTyping = (username) => {
const userTyping = getUserTyping(username);
try {
database.memoryDatabase.write(() => {
database.memoryDatabase.delete(userTyping);
});
if (typingTimeouts[username]) {
clearTimeout(typingTimeouts[username]);
typingTimeouts[username] = null;
}
} catch (e) {
log(e);
}
};
const addUserTyping = (username) => {
const userTyping = getUserTyping(username);
// prevent duplicated
if (userTyping.length === 0) {
try {
database.memoryDatabase.write(() => {
database.memoryDatabase.create('usersTyping', { rid, username });
});
if (typingTimeouts[username]) {
clearTimeout(typingTimeouts[username]);
typingTimeouts[username] = null;
}
typingTimeouts[username] = setTimeout(() => {
removeUserTyping(username);
}, 10000);
} catch (e) {
log(e);
}
}
this.loadMissedMessages({ rid }).catch(e => console.log(e));
};
const handleNotifyRoomReceived = protectedFunction((ddpMessage) => {
@ -74,59 +33,147 @@ export default function subscribeRoom({ rid }) {
if (ev === 'typing') {
const [username, typing] = ddpMessage.fields.args;
if (typing) {
addUserTyping(username);
reduxStore.dispatch(addUserTyping(username));
} else {
removeUserTyping(username);
reduxStore.dispatch(removeUserTyping(username));
}
} else if (ev === 'deleteMessage') {
database.write(() => {
InteractionManager.runAfterInteractions(async() => {
if (ddpMessage && ddpMessage.fields && ddpMessage.fields.args.length > 0) {
const { _id } = ddpMessage.fields.args[0];
const message = database.objects('messages').filtered('_id = $0', _id);
database.delete(message);
const thread = database.objects('threads').filtered('_id = $0', _id);
database.delete(thread);
const threadMessage = database.objects('threadMessages').filtered('_id = $0', _id);
database.delete(threadMessage);
const cleanTmids = database.objects('messages').filtered('tmid = $0', _id).snapshot();
if (cleanTmids && cleanTmids.length) {
cleanTmids.forEach((m) => {
m.tmid = null;
try {
const { _id } = ddpMessage.fields.args[0];
const db = database.active;
const msgCollection = db.collections.get('messages');
const threadsCollection = db.collections.get('threads');
const threadMessagesCollection = db.collections.get('thread_messages');
let deleteMessage;
let deleteThread;
let deleteThreadMessage;
// Delete message
try {
const m = await msgCollection.find(_id);
deleteMessage = m.prepareDestroyPermanently();
} catch (e) {
// Do nothing
}
// Delete thread
try {
const m = await threadsCollection.find(_id);
deleteThread = m.prepareDestroyPermanently();
} catch (e) {
// Do nothing
}
// Delete thread message
try {
const m = await threadMessagesCollection.find(_id);
deleteThreadMessage = m.prepareDestroyPermanently();
} catch (e) {
// Do nothing
}
await db.action(async() => {
await db.batch(
deleteMessage, deleteThread, deleteThreadMessage
);
});
} catch (e) {
log(e);
}
}
});
}
});
const read = debounce(() => {
const [room] = database.objects('subscriptions').filtered('rid = $0', rid);
if (room && room._id) {
this.readMessages(rid);
}
}, 300);
const handleMessageReceived = protectedFunction((ddpMessage) => {
const message = buildMessage(EJSON.fromJSONValue(ddpMessage.fields.args[0]));
if (rid !== message.rid) {
return;
}
requestAnimationFrame(() => {
try {
database.write(() => {
database.create('messages', message, true);
// if it's a thread "header"
if (message.tlm) {
database.create('threads', message, true);
} else if (message.tmid) {
message.rid = message.tmid;
database.create('threadMessages', message, true);
}
});
InteractionManager.runAfterInteractions(async() => {
const db = database.active;
const batch = [];
const subCollection = db.collections.get('subscriptions');
const msgCollection = db.collections.get('messages');
const threadsCollection = db.collections.get('threads');
const threadMessagesCollection = db.collections.get('thread_messages');
read();
// Create or update message
try {
const messageRecord = await msgCollection.find(message._id);
batch.push(
messageRecord.prepareUpdate((m) => {
Object.assign(m, message);
})
);
} catch (error) {
batch.push(
msgCollection.prepareCreate(protectedFunction((m) => {
m._raw = sanitizedRaw({ id: message._id }, msgCollection.schema);
m.subscription.id = rid;
Object.assign(m, message);
}))
);
}
// Create or update thread
if (message.tlm) {
try {
const threadRecord = await threadsCollection.find(message._id);
batch.push(
threadRecord.prepareUpdate((t) => {
Object.assign(t, message);
})
);
} catch (error) {
batch.push(
threadsCollection.prepareCreate(protectedFunction((t) => {
t._raw = sanitizedRaw({ id: message._id }, threadsCollection.schema);
t.subscription.id = rid;
Object.assign(t, message);
}))
);
}
}
// Create or update thread message
if (message.tmid) {
try {
const threadMessageRecord = await threadMessagesCollection.find(message._id);
batch.push(
threadMessageRecord.prepareUpdate((tm) => {
Object.assign(tm, message);
tm.rid = message.tmid;
delete tm.tmid;
})
);
} catch (error) {
batch.push(
threadMessagesCollection.prepareCreate(protectedFunction((tm) => {
tm._raw = sanitizedRaw({ id: message._id }, threadMessagesCollection.schema);
Object.assign(tm, message);
tm.subscription.id = rid;
tm.rid = message.tmid;
delete tm.tmid;
}))
);
}
}
try {
await subCollection.find(rid);
this.readMessages(rid);
} catch (e) {
console.warn('handleMessageReceived', e);
console.log('Subscription not found. We probably subscribed to a not joined channel. No need to mark as read.');
}
try {
await db.action(async() => {
await db.batch(...batch);
});
} catch (e) {
log(e);
}
});
});
@ -158,10 +205,7 @@ export default function subscribeRoom({ rid }) {
typingTimeouts[key] = null;
}
});
database.memoryDatabase.write(() => {
const usersTyping = database.memoryDatabase.objects('usersTyping').filtered('rid == $0', rid);
database.memoryDatabase.delete(usersTyping);
});
reduxStore.dispatch(clearUserTyping());
};
connectedListener = this.sdk.onStreamData('connected', handleConnection);

View File

@ -1,4 +1,6 @@
import database from '../../realm';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import database from '../../database';
import { merge } from '../helpers/mergeSubscriptionsRooms';
import protectedFunction from '../helpers/protectedFunction';
import messagesStatus from '../../../constants/messagesStatus';
@ -15,12 +17,112 @@ let disconnectedListener;
let streamListener;
let subServer;
// TODO: batch execution
const createOrUpdateSubscription = async(subscription, room) => {
try {
const db = database.active;
const subCollection = db.collections.get('subscriptions');
const roomsCollection = db.collections.get('rooms');
if (!subscription) {
try {
const s = await subCollection.find(room._id);
// We have to create a plain obj so we can manipulate it on `merge`
// Can we do it in a better way?
subscription = {
_id: s._id,
f: s.f,
t: s.t,
ts: s.ts,
ls: s.ls,
name: s.name,
fname: s.fname,
rid: s.rid,
open: s.open,
alert: s.alert,
unread: s.unread,
userMentions: s.userMentions,
roomUpdatedAt: s.roomUpdatedAt,
ro: s.ro,
lastOpen: s.lastOpen,
description: s.description,
announcement: s.announcement,
topic: s.topic,
blocked: s.blocked,
blocker: s.blocker,
reactWhenReadOnly: s.reactWhenReadOnly,
archived: s.archived,
joinCodeRequired: s.joinCodeRequired,
muted: s.muted,
broadcast: s.broadcast,
prid: s.prid,
draftMessage: s.draftMessage,
lastThreadSync: s.lastThreadSync,
autoTranslate: s.autoTranslate,
autoTranslateLanguage: s.autoTranslateLanguage,
lastMessage: s.lastMessage
};
} catch (error) {
try {
await db.action(async() => {
await roomsCollection.create((r) => {
r._raw = sanitizedRaw({ id: room._id }, roomsCollection.schema);
Object.assign(r, room);
});
});
} catch (e) {
// Do nothing
}
return;
}
}
if (!room && subscription) {
try {
const r = await roomsCollection.find(subscription.rid);
// We have to create a plain obj so we can manipulate it on `merge`
// Can we do it in a better way?
room = {
customFields: r.customFields,
broadcast: r.broadcast,
encrypted: r.encrypted,
ro: r.ro
};
} catch (error) {
// Do nothing
}
}
const tmp = merge(subscription, room);
await db.action(async() => {
try {
const sub = await subCollection.find(tmp.rid);
await sub.update((s) => {
Object.assign(s, tmp);
});
} catch (error) {
await subCollection.create((s) => {
s._raw = sanitizedRaw({ id: tmp.rid }, subCollection.schema);
Object.assign(s, tmp);
if (s.roomUpdatedAt) {
s.roomUpdatedAt = new Date();
}
});
}
});
} catch (e) {
log(e);
}
};
export default function subscribeRooms() {
const handleConnection = () => {
store.dispatch(roomsRequest());
};
const handleStreamMessageReceived = protectedFunction((ddpMessage) => {
const handleStreamMessageReceived = protectedFunction(async(ddpMessage) => {
const db = database.active;
// check if the server from variable is the same as the js sdk client
if (this.sdk && this.sdk.client && this.sdk.client.host !== subServer) {
return;
@ -32,52 +134,33 @@ export default function subscribeRooms() {
const [, ev] = ddpMessage.fields.eventName.split('/');
if (/subscriptions/.test(ev)) {
if (type === 'removed') {
let messages = [];
const [subscription] = database.objects('subscriptions').filtered('_id == $0', data._id);
if (subscription) {
messages = database.objects('messages').filtered('rid == $0', subscription.rid);
}
try {
database.write(() => {
database.delete(messages);
database.delete(subscription);
const subCollection = db.collections.get('subscriptions');
const sub = await subCollection.find(data.rid);
const messages = await sub.messages.fetch();
const threads = await sub.threads.fetch();
const threadMessages = await sub.threadMessages.fetch();
const messagesToDelete = messages.map(m => m.prepareDestroyPermanently());
const threadsToDelete = threads.map(m => m.prepareDestroyPermanently());
const threadMessagesToDelete = threadMessages.map(m => m.prepareDestroyPermanently());
await db.action(async() => {
await db.batch(
sub.prepareDestroyPermanently(),
...messagesToDelete,
...threadsToDelete,
...threadMessagesToDelete,
);
});
} catch (e) {
log(e);
}
} else {
const rooms = database.objects('rooms').filtered('_id == $0', data.rid);
const tpm = merge(data, rooms[0]);
try {
database.write(() => {
database.create('subscriptions', tpm, true);
database.delete(rooms);
});
} catch (e) {
log(e);
}
await createOrUpdateSubscription(data);
}
}
if (/rooms/.test(ev)) {
if (type === 'updated') {
const [sub] = database.objects('subscriptions').filtered('rid == $0', data._id);
try {
database.write(() => {
const tmp = merge(sub, data);
database.create('subscriptions', tmp, true);
});
} catch (e) {
log(e);
}
} else if (type === 'inserted') {
try {
database.write(() => {
database.create('rooms', data, true);
});
} catch (e) {
log(e);
}
if (type === 'updated' || type === 'inserted') {
await createOrUpdateSubscription(null, data);
}
}
if (/message/.test(ev)) {
@ -95,15 +178,18 @@ export default function subscribeRooms() {
username: 'rocket.cat'
}
};
requestAnimationFrame(() => {
try {
database.write(() => {
database.create('messages', message, true);
});
} catch (e) {
log(e);
}
});
try {
const msgCollection = db.collections.get('messages');
await db.action(async() => {
await msgCollection.create(protectedFunction((m) => {
m._raw = sanitizedRaw({ id: message._id }, msgCollection.schema);
m.subscription.id = args.rid;
Object.assign(m, message);
}));
});
} catch (e) {
log(e);
}
}
if (/notification/.test(ev)) {
const [notification] = ddpMessage.fields.args;

View File

@ -0,0 +1,131 @@
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { Q } from '@nozbe/watermelondb';
import buildMessage from './helpers/buildMessage';
import log from '../../utils/log';
import database from '../database';
import protectedFunction from './helpers/protectedFunction';
export default function updateMessages({ rid, update, remove }) {
try {
if (!((update && update.length) || (remove && remove.length))) {
return;
}
const db = database.active;
return db.action(async() => {
const subCollection = db.collections.get('subscriptions');
let sub;
try {
sub = await subCollection.find(rid);
} catch (error) {
sub = { id: rid };
console.log('updateMessages: subscription not found');
}
const messagesIds = update.map(m => m._id);
const msgCollection = db.collections.get('messages');
const threadCollection = db.collections.get('threads');
const threadMessagesCollection = db.collections.get('thread_messages');
const allMessagesRecords = await msgCollection
.query(Q.where('rid', rid), Q.where('id', Q.oneOf(messagesIds)))
.fetch();
const allThreadsRecords = await threadCollection
.query(Q.where('rid', rid), Q.where('id', Q.oneOf(messagesIds)))
.fetch();
const allThreadMessagesRecords = await threadMessagesCollection
.query(Q.where('subscription_id', rid), Q.where('id', Q.oneOf(messagesIds)))
.fetch();
update = update.map(m => buildMessage(m));
// filter messages
let msgsToCreate = update.filter(i1 => !allMessagesRecords.find(i2 => i1._id === i2.id));
let msgsToUpdate = allMessagesRecords.filter(i1 => update.find(i2 => i1.id === i2._id));
// filter threads
const allThreads = update.filter(m => m.tlm);
let threadsToCreate = allThreads.filter(i1 => !allThreadsRecords.find(i2 => i1._id === i2.id));
let threadsToUpdate = allThreadsRecords.filter(i1 => allThreads.find(i2 => i1.id === i2._id));
// filter thread messages
const allThreadMessages = update.filter(m => m.tmid);
let threadMessagesToCreate = allThreadMessages.filter(i1 => !allThreadMessagesRecords.find(i2 => i1._id === i2.id));
let threadMessagesToUpdate = allThreadMessagesRecords.filter(i1 => allThreadMessages.find(i2 => i1.id === i2._id));
// Create
msgsToCreate = msgsToCreate.map(message => msgCollection.prepareCreate(protectedFunction((m) => {
m._raw = sanitizedRaw({ id: message._id }, msgCollection.schema);
m.subscription.id = sub.id;
Object.assign(m, message);
})));
threadsToCreate = threadsToCreate.map(thread => threadCollection.prepareCreate(protectedFunction((t) => {
t._raw = sanitizedRaw({ id: thread._id }, threadCollection.schema);
t.subscription.id = sub.id;
Object.assign(t, thread);
})));
threadMessagesToCreate = threadMessagesToCreate.map(threadMessage => threadMessagesCollection.prepareCreate(protectedFunction((tm) => {
tm._raw = sanitizedRaw({ id: threadMessage._id }, threadMessagesCollection.schema);
Object.assign(tm, threadMessage);
tm.subscription.id = sub.id;
tm.rid = threadMessage.tmid;
delete threadMessage.tmid;
})));
// Update
msgsToUpdate = msgsToUpdate.map((message) => {
const newMessage = update.find(m => m._id === message.id);
return message.prepareUpdate(protectedFunction((m) => {
Object.assign(m, newMessage);
}));
});
threadsToUpdate = threadsToUpdate.map((thread) => {
const newThread = allThreads.find(t => t._id === thread.id);
return thread.prepareUpdate(protectedFunction((t) => {
Object.assign(t, newThread);
}));
});
threadMessagesToUpdate = threadMessagesToUpdate.map((threadMessage) => {
const newThreadMessage = allThreadMessages.find(t => t._id === threadMessage.id);
return threadMessage.prepareUpdate(protectedFunction((tm) => {
Object.assign(tm, newThreadMessage);
tm.rid = threadMessage.tmid;
delete threadMessage.tmid;
}));
});
// Delete
let msgsToDelete = [];
let threadsToDelete = [];
let threadMessagesToDelete = [];
if (remove && remove.length) {
msgsToDelete = allMessagesRecords.filter(i1 => remove.find(i2 => i1.id === i2._id));
msgsToDelete = msgsToDelete.map(m => m.prepareDestroyPermanently());
threadsToDelete = allThreadsRecords.filter(i1 => remove.find(i2 => i1.id === i2._id));
threadsToDelete = threadsToDelete.map(t => t.prepareDestroyPermanently());
threadMessagesToDelete = allThreadMessagesRecords.filter(i1 => remove.find(i2 => i1.id === i2._id));
threadMessagesToDelete = threadMessagesToDelete.map(tm => tm.prepareDestroyPermanently());
}
const allRecords = [
...msgsToCreate,
...msgsToUpdate,
...msgsToDelete,
...threadsToCreate,
...threadsToUpdate,
...threadsToDelete,
...threadMessagesToCreate,
...threadMessagesToUpdate,
...threadMessagesToDelete
];
try {
await db.batch(...allRecords);
} catch (e) {
log(e);
}
return allRecords.length;
});
} catch (e) {
log(e);
}
}

View File

@ -1,526 +0,0 @@
import Realm from 'realm';
import RNRealmPath from 'react-native-realm-path';
// import { AsyncStorage } from 'react-native';
// Realm.clearTestState();
// AsyncStorage.clear();
const userSchema = {
name: 'user',
primaryKey: 'id',
properties: {
id: 'string',
token: { type: 'string', optional: true },
username: { type: 'string', optional: true },
name: { type: 'string', optional: true },
language: { type: 'string', optional: true },
status: { type: 'string', optional: true },
roles: { type: 'string[]', optional: true }
}
};
const serversSchema = {
name: 'servers',
primaryKey: 'id',
properties: {
id: 'string',
name: { type: 'string', optional: true },
iconURL: { type: 'string', optional: true },
useRealName: { type: 'bool', optional: true },
FileUpload_MediaTypeWhiteList: { type: 'string', optional: true },
FileUpload_MaxFileSize: { type: 'int', optional: true },
roomsUpdatedAt: { type: 'date', optional: true },
version: 'string?'
}
};
const settingsSchema = {
name: 'settings',
primaryKey: '_id',
properties: {
_id: 'string',
valueAsString: { type: 'string', optional: true },
valueAsBoolean: { type: 'bool', optional: true },
valueAsNumber: { type: 'int', optional: true },
_updatedAt: { type: 'date', optional: true }
}
};
const permissionsSchema = {
name: 'permissions',
primaryKey: '_id',
properties: {
_id: 'string',
roles: 'string[]',
_updatedAt: { type: 'date', optional: true }
}
};
const roomsSchema = {
name: 'rooms',
primaryKey: '_id',
properties: {
_id: 'string',
name: 'string?',
broadcast: { type: 'bool', optional: true }
}
};
const subscriptionSchema = {
name: 'subscriptions',
primaryKey: '_id',
properties: {
_id: 'string',
f: { type: 'bool', optional: true },
t: 'string',
ts: { type: 'date', optional: true },
ls: { type: 'date', optional: true },
name: { type: 'string', indexed: true },
fname: { type: 'string', optional: true },
rid: { type: 'string', indexed: true },
open: { type: 'bool', optional: true },
alert: { type: 'bool', optional: true },
roles: 'string[]',
unread: { type: 'int', optional: true },
userMentions: { type: 'int', optional: true },
roomUpdatedAt: { type: 'date', optional: true },
ro: { type: 'bool', optional: true },
lastOpen: { type: 'date', optional: true },
lastMessage: { type: 'messages', optional: true },
description: { type: 'string', optional: true },
announcement: { type: 'string', optional: true },
topic: { type: 'string', optional: true },
blocked: { type: 'bool', optional: true },
blocker: { type: 'bool', optional: true },
reactWhenReadOnly: { type: 'bool', optional: true },
archived: { type: 'bool', optional: true },
joinCodeRequired: { type: 'bool', optional: true },
muted: 'string[]',
broadcast: { type: 'bool', optional: true },
prid: { type: 'string', optional: true },
draftMessage: { type: 'string', optional: true },
lastThreadSync: 'date?',
autoTranslate: 'bool?',
autoTranslateLanguage: 'string?',
// Notifications
emailNotifications: { type: 'string', default: 'default' },
disableNotifications: { type: 'bool', default: false },
muteGroupMentions: { type: 'bool', default: false },
hideUnreadStatus: { type: 'bool', default: false },
audioNotifications: { type: 'string', default: 'default' },
desktopNotifications: { type: 'string', default: 'default' },
audioNotificationValue: { type: 'string', default: '0 Default' },
desktopNotificationDuration: { type: 'int', default: 0 },
mobilePushNotifications: { type: 'string', default: 'default' }
}
};
const usersSchema = {
name: 'users',
primaryKey: '_id',
properties: {
_id: 'string',
username: 'string',
name: { type: 'string', optional: true }
}
};
const attachmentFields = {
name: 'attachmentFields',
properties: {
title: { type: 'string', optional: true },
value: { type: 'string', optional: true },
short: { type: 'bool', optional: true }
}
};
const attachment = {
name: 'attachment',
properties: {
description: { type: 'string', optional: true },
image_size: { type: 'int', optional: true },
image_type: { type: 'string', optional: true },
image_url: { type: 'string', optional: true },
audio_size: { type: 'int', optional: true },
audio_type: { type: 'string', optional: true },
audio_url: { type: 'string', optional: true },
video_size: { type: 'int', optional: true },
video_type: { type: 'string', optional: true },
video_url: { type: 'string', optional: true },
title: { type: 'string', optional: true },
title_link: { type: 'string', optional: true },
// title_link_download: { type: 'bool', optional: true },
type: { type: 'string', optional: true },
author_icon: { type: 'string', optional: true },
author_name: { type: 'string', optional: true },
author_link: { type: 'string', optional: true },
text: { type: 'string', optional: true },
color: { type: 'string', optional: true },
ts: { type: 'date', optional: true },
attachments: { type: 'list', objectType: 'attachment' },
fields: {
type: 'list', objectType: 'attachmentFields', default: []
}
}
};
const url = {
name: 'url',
primaryKey: 'url',
properties: {
// _id: { type: 'int', optional: true },
url: { type: 'string', optional: true },
title: { type: 'string', optional: true },
description: { type: 'string', optional: true },
image: { type: 'string', optional: true }
}
};
const messagesReactionsSchema = {
name: 'messagesReactions',
primaryKey: '_id',
properties: {
_id: 'string',
emoji: 'string',
usernames: 'string[]'
}
};
const messagesTranslationsSchema = {
name: 'messagesTranslations',
primaryKey: '_id',
properties: {
_id: 'string',
language: 'string',
value: 'string'
}
};
const messagesEditedBySchema = {
name: 'messagesEditedBy',
primaryKey: '_id',
properties: {
_id: { type: 'string', optional: true },
username: { type: 'string', optional: true }
}
};
const messagesSchema = {
name: 'messages',
primaryKey: '_id',
properties: {
_id: 'string',
msg: { type: 'string', optional: true },
t: { type: 'string', optional: true },
rid: { type: 'string', indexed: true },
ts: 'date',
u: 'users',
alias: { type: 'string', optional: true },
parseUrls: { type: 'bool', optional: true },
groupable: { type: 'bool', optional: true },
avatar: { type: 'string', optional: true },
attachments: { type: 'list', objectType: 'attachment' },
urls: { type: 'list', objectType: 'url', default: [] },
_updatedAt: { type: 'date', optional: true },
status: { type: 'int', optional: true },
pinned: { type: 'bool', optional: true },
starred: { type: 'bool', optional: true },
editedBy: 'messagesEditedBy',
reactions: { type: 'list', objectType: 'messagesReactions' },
role: { type: 'string', optional: true },
drid: { type: 'string', optional: true },
dcount: { type: 'int', optional: true },
dlm: { type: 'date', optional: true },
tmid: { type: 'string', optional: true },
tcount: { type: 'int', optional: true },
tlm: { type: 'date', optional: true },
replies: 'string[]',
mentions: { type: 'list', objectType: 'users' },
channels: { type: 'list', objectType: 'rooms' },
unread: { type: 'bool', optional: true },
autoTranslate: { type: 'bool', default: false },
translations: { type: 'list', objectType: 'messagesTranslations' }
}
};
const threadsSchema = {
name: 'threads',
primaryKey: '_id',
properties: {
_id: 'string',
msg: { type: 'string', optional: true },
t: { type: 'string', optional: true },
rid: { type: 'string', indexed: true },
ts: 'date',
u: 'users',
alias: { type: 'string', optional: true },
parseUrls: { type: 'bool', optional: true },
groupable: { type: 'bool', optional: true },
avatar: { type: 'string', optional: true },
attachments: { type: 'list', objectType: 'attachment' },
urls: { type: 'list', objectType: 'url', default: [] },
_updatedAt: { type: 'date', optional: true },
status: { type: 'int', optional: true },
pinned: { type: 'bool', optional: true },
starred: { type: 'bool', optional: true },
editedBy: 'messagesEditedBy',
reactions: { type: 'list', objectType: 'messagesReactions' },
role: { type: 'string', optional: true },
drid: { type: 'string', optional: true },
dcount: { type: 'int', optional: true },
dlm: { type: 'date', optional: true },
tmid: { type: 'string', optional: true },
tcount: { type: 'int', optional: true },
tlm: { type: 'date', optional: true },
replies: 'string[]',
mentions: { type: 'list', objectType: 'users' },
channels: { type: 'list', objectType: 'rooms' },
unread: { type: 'bool', optional: true },
autoTranslate: { type: 'bool', default: false },
translations: { type: 'list', objectType: 'messagesTranslations' },
draftMessage: 'string?'
}
};
const threadMessagesSchema = {
name: 'threadMessages',
primaryKey: '_id',
properties: {
_id: 'string',
msg: { type: 'string', optional: true },
t: { type: 'string', optional: true },
rid: { type: 'string', indexed: true },
ts: 'date',
u: 'users',
alias: { type: 'string', optional: true },
parseUrls: { type: 'bool', optional: true },
groupable: { type: 'bool', optional: true },
avatar: { type: 'string', optional: true },
attachments: { type: 'list', objectType: 'attachment' },
urls: { type: 'list', objectType: 'url', default: [] },
_updatedAt: { type: 'date', optional: true },
status: { type: 'int', optional: true },
pinned: { type: 'bool', optional: true },
starred: { type: 'bool', optional: true },
editedBy: 'messagesEditedBy',
reactions: { type: 'list', objectType: 'messagesReactions' },
role: { type: 'string', optional: true },
replies: 'string[]',
mentions: { type: 'list', objectType: 'users' },
channels: { type: 'list', objectType: 'rooms' },
unread: { type: 'bool', optional: true },
autoTranslate: { type: 'bool', default: false },
translations: { type: 'list', objectType: 'messagesTranslations' }
}
};
const frequentlyUsedEmojiSchema = {
name: 'frequentlyUsedEmoji',
primaryKey: 'content',
properties: {
content: { type: 'string', optional: true },
extension: { type: 'string', optional: true },
isCustom: 'bool',
count: 'int'
}
};
const slashCommandSchema = {
name: 'slashCommand',
primaryKey: 'command',
properties: {
command: 'string',
params: { type: 'string', optional: true },
description: { type: 'string', optional: true },
clientOnly: { type: 'bool', optional: true },
providesPreview: { type: 'bool', optional: true }
}
};
const customEmojisSchema = {
name: 'customEmojis',
primaryKey: '_id',
properties: {
_id: 'string',
name: 'string',
aliases: 'string[]',
extension: 'string',
_updatedAt: { type: 'date', optional: true }
}
};
const rolesSchema = {
name: 'roles',
primaryKey: '_id',
properties: {
_id: 'string',
description: { type: 'string', optional: true }
}
};
const uploadsSchema = {
name: 'uploads',
primaryKey: 'path',
properties: {
path: 'string',
rid: 'string',
name: { type: 'string', optional: true },
description: { type: 'string', optional: true },
size: { type: 'int', optional: true },
type: { type: 'string', optional: true },
store: { type: 'string', optional: true },
progress: { type: 'int', default: 1 },
error: { type: 'bool', default: false }
}
};
const usersTypingSchema = {
name: 'usersTyping',
properties: {
rid: { type: 'string', indexed: true },
username: { type: 'string', optional: true }
}
};
const activeUsersSchema = {
name: 'activeUsers',
primaryKey: 'id',
properties: {
id: 'string',
name: 'string?',
username: 'string?',
status: 'string?',
utcOffset: 'double?'
}
};
const schema = [
settingsSchema,
subscriptionSchema,
messagesSchema,
threadsSchema,
threadMessagesSchema,
usersSchema,
roomsSchema,
attachment,
attachmentFields,
messagesEditedBySchema,
permissionsSchema,
url,
frequentlyUsedEmojiSchema,
customEmojisSchema,
messagesReactionsSchema,
rolesSchema,
uploadsSchema,
slashCommandSchema,
messagesTranslationsSchema
];
const inMemorySchema = [usersTypingSchema, activeUsersSchema];
class DB {
databases = {
serversDB: new Realm({
path: `${ RNRealmPath.realmPath }default.realm`,
schema: [
userSchema,
serversSchema
],
schemaVersion: 10,
migration: (oldRealm, newRealm) => {
if (oldRealm.schemaVersion >= 1 && newRealm.schemaVersion <= 9) {
const newServers = newRealm.objects('servers');
// eslint-disable-next-line no-plusplus
for (let i = 0; i < newServers.length; i++) {
newServers[i].roomsUpdatedAt = null;
}
}
}
}),
inMemoryDB: new Realm({
path: `${ RNRealmPath.realmPath }memory.realm`,
schema: inMemorySchema,
schemaVersion: 2,
inMemory: true
})
}
deleteAll(...args) {
return this.database.write(() => this.database.deleteAll(...args));
}
delete(...args) {
return this.database.delete(...args);
}
write(...args) {
return this.database.write(...args);
}
create(...args) {
return this.database.create(...args);
}
objects(...args) {
return this.database.objects(...args);
}
objectForPrimaryKey(...args) {
return this.database.objectForPrimaryKey(...args);
}
get database() {
return this.databases.activeDB;
}
get memoryDatabase() {
return this.databases.inMemoryDB;
}
setActiveDB(database = '') {
const path = database.replace(/(^\w+:|^)\/\//, '');
return this.databases.activeDB = new Realm({
path: `${ RNRealmPath.realmPath }${ path }.realm`,
schema,
schemaVersion: 14,
migration: (oldRealm, newRealm) => {
if (oldRealm.schemaVersion >= 3 && newRealm.schemaVersion <= 13) {
const newSubs = newRealm.objects('subscriptions');
newRealm.delete(newSubs);
const newMessages = newRealm.objects('messages');
newRealm.delete(newMessages);
const newThreads = newRealm.objects('threads');
newRealm.delete(newThreads);
const newThreadMessages = newRealm.objects('threadMessages');
newRealm.delete(newThreadMessages);
}
if (newRealm.schemaVersion === 9) {
const newEmojis = newRealm.objects('customEmojis');
newRealm.delete(newEmojis);
const newSettings = newRealm.objects('settings');
newRealm.delete(newSettings);
}
}
});
}
}
const db = new DB();
export default db;
// Realm workaround for "Cannot create asynchronous query while in a write transaction"
// inpired from https://github.com/realm/realm-js/issues/1188#issuecomment-359223918
export function safeAddListener(results, callback, database = db) {
if (!results || !results.addListener) {
console.log('⚠️ safeAddListener called for non addListener-compliant object');
return;
}
if (database.isInTransaction) {
setTimeout(() => {
safeAddListener(results, callback);
}, 50);
} else {
results.addListener(callback);
}
}

View File

@ -2,13 +2,16 @@ import { AsyncStorage, InteractionManager } from 'react-native';
import semver from 'semver';
import { Rocketchat as RocketchatClient } from '@rocket.chat/sdk';
import RNUserDefaults from 'rn-user-defaults';
import { Q } from '@nozbe/watermelondb';
import * as FileSystem from 'expo-file-system';
import reduxStore from './createStore';
import defaultSettings from '../constants/settings';
import messagesStatus from '../constants/messagesStatus';
import database from './realm';
import database from './database';
import log from '../utils/log';
import { isIOS, getBundleId } from '../utils/deviceInfo';
import { extractHostname } from '../utils/server';
import {
setUser, setLoginServices, loginRequest, loginFailure, logout
@ -27,7 +30,7 @@ import getSettings from './methods/getSettings';
import getRooms from './methods/getRooms';
import getPermissions from './methods/getPermissions';
import getCustomEmojis from './methods/getCustomEmojis';
import { getCustomEmojis, setCustomEmojis } from './methods/getCustomEmojis';
import getSlashCommands from './methods/getSlashCommands';
import getRoles from './methods/getRoles';
import canOpenRoom from './methods/canOpenRoom';
@ -41,6 +44,7 @@ import { sendFileMessage, cancelUpload, isUploadActive } from './methods/sendFil
import { getDeviceToken } from '../notifications/push';
import { SERVERS, SERVER_URL } from '../constants/credentials';
import { setActiveUsers } from '../actions/activeUsers';
const TOKEN_KEY = 'reactnativemeteor_usertoken';
const SORT_PREFS_KEY = 'RC_SORT_PREFS_KEY';
@ -57,7 +61,11 @@ const RocketChat = {
if (this.roomsSub) {
this.roomsSub.stop();
}
this.roomsSub = await subscribeRooms.call(this);
try {
this.roomsSub = await subscribeRooms.call(this);
} catch (e) {
log(e);
}
},
subscribeRoom,
canOpenRoom,
@ -98,67 +106,36 @@ const RocketChat = {
message: 'The_URL_is_invalid'
};
},
_setUser(ddpMessage) {
this.activeUsers = this.activeUsers || {};
const { user } = reduxStore.getState().login;
if (ddpMessage.fields && user && user.id === ddpMessage.id) {
reduxStore.dispatch(setUser(ddpMessage.fields));
}
if (ddpMessage.cleared && user && user.id === ddpMessage.id) {
reduxStore.dispatch(setUser({ status: 'offline' }));
}
if (!this._setUserTimer) {
this._setUserTimer = setTimeout(() => {
const batchUsers = this.activeUsers;
InteractionManager.runAfterInteractions(() => {
database.memoryDatabase.write(() => {
Object.keys(batchUsers).forEach((key) => {
if (batchUsers[key] && batchUsers[key].id) {
try {
const data = batchUsers[key];
if (data.removed) {
const userRecord = database.memoryDatabase.objectForPrimaryKey('activeUsers', data.id);
if (userRecord) {
userRecord.status = 'offline';
}
} else {
database.memoryDatabase.create('activeUsers', data, true);
}
} catch (error) {
console.log(error);
}
}
});
});
});
this._setUserTimer = null;
return this.activeUsers = {};
}, 10000);
}
if (!ddpMessage.fields) {
this.activeUsers[ddpMessage.id] = {
id: ddpMessage.id,
removed: true
};
} else {
this.activeUsers[ddpMessage.id] = {
id: ddpMessage.id, ...this.activeUsers[ddpMessage.id], ...ddpMessage.fields
};
}
stopListener(listener) {
return listener && listener.stop();
},
connect({ server, user }) {
return new Promise((resolve) => {
database.setActiveDB(server);
if (!this.sdk || this.sdk.client.host !== server) {
database.setActiveDB(server);
}
reduxStore.dispatch(connectRequest());
if (this.connectTimeout) {
clearTimeout(this.connectTimeout);
}
if (this.connectedListener) {
this.connectedListener.then(this.stopListener);
}
if (this.closeListener) {
this.closeListener.then(this.stopListener);
}
if (this.usersListener) {
this.usersListener.then(this.stopListener);
}
if (this.notifyLoggedListener) {
this.notifyLoggedListener.then(this.stopListener);
}
if (this.roomsSub) {
this.roomsSub.stop();
}
@ -189,35 +166,37 @@ const RocketChat = {
}, 10000);
});
this.sdk.onStreamData('connected', () => {
this.connectedListener = this.sdk.onStreamData('connected', () => {
reduxStore.dispatch(connectSuccess());
// const { isAuthenticated } = reduxStore.getState().login;
// if (isAuthenticated) {
// this.getUserPresence();
// }
});
this.sdk.onStreamData('close', () => {
this.closeListener = this.sdk.onStreamData('close', () => {
reduxStore.dispatch(disconnect());
});
this.sdk.onStreamData('users', protectedFunction(ddpMessage => RocketChat._setUser(ddpMessage)));
this.usersListener = this.sdk.onStreamData('users', protectedFunction(ddpMessage => RocketChat._setUser(ddpMessage)));
this.sdk.onStreamData('stream-notify-logged', protectedFunction((ddpMessage) => {
this.notifyLoggedListener = this.sdk.onStreamData('stream-notify-logged', protectedFunction((ddpMessage) => {
const { eventName } = ddpMessage.fields;
if (eventName === 'user-status') {
this.activeUsers = this.activeUsers || {};
if (!this._setUserTimer) {
this._setUserTimer = setTimeout(() => {
const activeUsersBatch = this.activeUsers;
InteractionManager.runAfterInteractions(() => {
reduxStore.dispatch(setActiveUsers(activeUsersBatch));
});
this._setUserTimer = null;
return this.activeUsers = {};
}, 10000);
}
const userStatus = ddpMessage.fields.args[0];
const [id, username, status] = userStatus;
if (username) {
database.memoryDatabase.write(() => {
try {
database.memoryDatabase.create('activeUsers', {
id, username, status: STATUSES[status]
}, true);
} catch (error) {
console.log(error);
}
});
const [id,, status] = userStatus;
this.activeUsers[id] = STATUSES[status];
const { user: loggedUser } = reduxStore.getState().login;
if (loggedUser && loggedUser.id === id) {
reduxStore.dispatch(setUser({ status: STATUSES[status] }));
}
}
}));
@ -240,19 +219,31 @@ const RocketChat = {
this.sdk = new RocketchatClient({ host: server, protocol: 'ddp', useSsl });
// set Server
const { serversDB } = database.databases;
const serversDB = database.servers;
reduxStore.dispatch(shareSelectServer(server));
// set User info
const userId = await RNUserDefaults.get(`${ RocketChat.TOKEN_KEY }-${ server }`);
const user = userId && serversDB.objectForPrimaryKey('user', userId);
reduxStore.dispatch(shareSetUser({
id: user.id,
token: user.token,
username: user.username
}));
await RocketChat.login({ resume: user.token });
try {
const userId = await RNUserDefaults.get(`${ RocketChat.TOKEN_KEY }-${ server }`);
const userCollections = serversDB.collections.get('users');
let user = null;
if (userId) {
user = await userCollections.find(userId);
user = {
id: user.id,
token: user.token,
username: user.username
};
}
reduxStore.dispatch(shareSetUser({
id: user.id,
token: user.token,
username: user.username
}));
await RocketChat.login({ resume: user.token });
} catch (e) {
log(e);
}
},
register(credentials) {
@ -364,27 +355,36 @@ const RocketChat = {
try {
const servers = await RNUserDefaults.objectForKey(SERVERS);
await RNUserDefaults.setObjectForKey(SERVERS, servers && servers.filter(srv => srv[SERVER_URL] !== server));
// clear certificate for server - SSL Pinning
const certificate = await RNUserDefaults.objectForKey(extractHostname(server));
if (certificate && certificate.path) {
await RNUserDefaults.clear(extractHostname(server));
await FileSystem.deleteAsync(certificate.path);
}
} catch (error) {
console.log('logout_rn_user_defaults', error);
}
const { serversDB } = database.databases;
const userId = await RNUserDefaults.get(`${ TOKEN_KEY }-${ server }`);
serversDB.write(() => {
const user = serversDB.objectForPrimaryKey('user', userId);
serversDB.delete(user);
});
try {
const serversDB = database.servers;
await serversDB.action(async() => {
const usersCollection = serversDB.collections.get('users');
const user = await usersCollection.find(userId);
await user.destroyPermanently();
});
} catch (error) {
// Do nothing
}
Promise.all([
RNUserDefaults.clear('currentServer'),
RNUserDefaults.clear(TOKEN_KEY),
RNUserDefaults.clear(`${ TOKEN_KEY }-${ server }`)
]).catch(error => console.log(error));
await RNUserDefaults.clear('currentServer');
await RNUserDefaults.clear(TOKEN_KEY);
await RNUserDefaults.clear(`${ TOKEN_KEY }-${ server }`);
try {
database.deleteAll();
const db = database.active;
await db.action(() => db.unsafeResetDatabase());
} catch (error) {
console.log(error);
}
@ -424,19 +424,21 @@ const RocketChat = {
sendMessage,
getRooms,
readMessages,
async resendMessage(messageId) {
const message = await database.objects('messages').filtered('_id = $0', messageId)[0];
async resendMessage(message) {
const db = database.active;
try {
database.write(() => {
message.status = messagesStatus.TEMP;
database.create('messages', message, true);
await db.action(async() => {
await message.update((m) => {
m.status = messagesStatus.TEMP;
});
});
await sendMessageCall.call(this, JSON.parse(JSON.stringify(message)));
await sendMessageCall.call(this, message);
} catch (error) {
try {
database.write(() => {
message.status = messagesStatus.ERROR;
database.create('messages', message, true);
await db.action(async() => {
await message.update((m) => {
m.status = messagesStatus.ERROR;
});
});
} catch (e) {
log(e);
@ -456,12 +458,15 @@ const RocketChat = {
return [];
}
let data = database.objects('subscriptions').filtered('name CONTAINS[c] $0', searchText);
const db = database.active;
let data = await db.collections.get('subscriptions').query(
Q.where('name', Q.like(`%${ Q.sanitizeLikeString(searchText) }%`))
).fetch();
if (filterUsers && !filterRooms) {
data = data.filtered('t = $0', 'd');
data = data.filter(item => item.t === 'd');
} else if (!filterUsers && filterRooms) {
data = data.filtered('t != $0', 'd');
data = data.filter(item => item.t !== 'd');
}
data = data.slice(0, 7);
@ -517,6 +522,7 @@ const RocketChat = {
getSettings,
getPermissions,
getCustomEmojis,
setCustomEmojis,
getSlashCommands,
getRoles,
parseSettings: settings => settings.reduce((ret, item) => {
@ -529,46 +535,47 @@ const RocketChat = {
return setting;
});
},
deleteMessage(message) {
const { _id, rid } = message;
deleteMessage(messageId, rid) {
// RC 0.48.0
return this.sdk.post('chat.delete', { roomId: rid, msgId: _id });
return this.sdk.post('chat.delete', { msgId: messageId, roomId: rid });
},
editMessage(message) {
const { _id, msg, rid } = message;
const { id, msg, rid } = message;
// RC 0.49.0
return this.sdk.post('chat.update', { roomId: rid, msgId: _id, text: msg });
return this.sdk.post('chat.update', { roomId: rid, msgId: id, text: msg });
},
toggleStarMessage(message) {
if (message.starred) {
toggleStarMessage(messageId, starred) {
if (starred) {
// RC 0.59.0
return this.sdk.post('chat.unStarMessage', { messageId: message._id });
return this.sdk.post('chat.unStarMessage', { messageId });
}
// RC 0.59.0
return this.sdk.post('chat.starMessage', { messageId: message._id });
return this.sdk.post('chat.starMessage', { messageId });
},
togglePinMessage(message) {
if (message.pinned) {
togglePinMessage(messageId, pinned) {
if (pinned) {
// RC 0.59.0
return this.sdk.post('chat.unPinMessage', { messageId: message._id });
return this.sdk.post('chat.unPinMessage', { messageId });
}
// RC 0.59.0
return this.sdk.post('chat.pinMessage', { messageId: message._id });
return this.sdk.post('chat.pinMessage', { messageId });
},
reportMessage(messageId) {
return this.sdk.post('chat.reportMessage', { messageId, description: 'Message reported by user' });
},
getRoom(rid) {
const [result] = database.objects('subscriptions').filtered('rid = $0', rid);
if (!result) {
async getRoom(rid) {
try {
const db = database.active;
const room = await db.collections.get('subscriptions').find(rid);
return Promise.resolve(room);
} catch (error) {
return Promise.reject(new Error('Room not found'));
}
return Promise.resolve(result);
},
async getPermalinkMessage(message) {
let room;
try {
room = await RocketChat.getRoom(message.rid);
room = await RocketChat.getRoom(message.subscription.id);
} catch (e) {
log(e);
return null;
@ -579,7 +586,7 @@ const RocketChat = {
c: 'channel',
d: 'direct'
}[room.t];
return `${ server }/${ roomType }/${ room.name }?msg=${ message._id }`;
return `${ server }/${ roomType }/${ room.name }?msg=${ message.id }`;
},
getPermalinkChannel(channel) {
const { server } = reduxStore.getState().server;
@ -717,40 +724,44 @@ const RocketChat = {
// RC 0.57.0
return this.sdk.methodCall('getSingleMessage', msgId);
},
hasPermission(permissions, rid) {
async hasPermission(permissions, rid) {
const db = database.active;
const subsCollection = db.collections.get('subscriptions');
const permissionsCollection = db.collections.get('permissions');
let roomRoles = [];
try {
// get the room from realm
const [room] = database.objects('subscriptions').filtered('rid = $0', rid);
if (!room) {
return permissions.reduce((result, permission) => {
result[permission] = false;
return result;
}, {});
}
// get the room from database
const room = await subsCollection.find(rid);
// get room roles
roomRoles = room.roles;
} catch (error) {
console.log('hasPermission -> error', error);
console.log('hasPermission -> Room not found');
return permissions.reduce((result, permission) => {
result[permission] = false;
return result;
}, {});
}
// get permissions from realm
const permissionsFiltered = database.objects('permissions')
.filter(permission => permissions.includes(permission._id));
// get user roles on the server from redux
const userRoles = (reduxStore.getState().login.user && reduxStore.getState().login.user.roles) || [];
// merge both roles
const mergedRoles = [...new Set([...roomRoles, ...userRoles])];
// get permissions from database
try {
const permissionsFiltered = await permissionsCollection.query(Q.where('id', Q.oneOf(permissions))).fetch();
// get user roles on the server from redux
const userRoles = (reduxStore.getState().login.user && reduxStore.getState().login.user.roles) || [];
// merge both roles
const mergedRoles = [...new Set([...roomRoles, ...userRoles])];
// return permissions in object format
// e.g. { 'edit-room': true, 'set-readonly': false }
return permissions.reduce((result, permission) => {
result[permission] = false;
const permissionFound = permissionsFiltered.find(p => p._id === permission);
if (permissionFound) {
result[permission] = returnAnArray(permissionFound.roles).some(r => mergedRoles.includes(r));
}
return result;
}, {});
// return permissions in object format
// e.g. { 'edit-room': true, 'set-readonly': false }
return permissions.reduce((result, permission) => {
result[permission] = false;
const permissionFound = permissionsFiltered.find(p => p.id === permission);
if (permissionFound) {
result[permission] = returnAnArray(permissionFound.roles).some(r => mergedRoles.includes(r));
}
return result;
}, {});
} catch (e) {
log(e);
}
},
getAvatarSuggestion() {
// RC 0.51.0
@ -919,6 +930,35 @@ const RocketChat = {
command, params, roomId, previewItem
});
},
_setUser(ddpMessage) {
this.activeUsers = this.activeUsers || {};
const { user } = reduxStore.getState().login;
if (ddpMessage.fields && user && user.id === ddpMessage.id) {
reduxStore.dispatch(setUser(ddpMessage.fields));
}
if (ddpMessage.cleared && user && user.id === ddpMessage.id) {
reduxStore.dispatch(setUser({ status: 'offline' }));
}
if (!this._setUserTimer) {
this._setUserTimer = setTimeout(() => {
const activeUsersBatch = this.activeUsers;
InteractionManager.runAfterInteractions(() => {
reduxStore.dispatch(setActiveUsers(activeUsersBatch));
});
this._setUserTimer = null;
return this.activeUsers = {};
}, 10000);
}
if (!ddpMessage.fields) {
this.activeUsers[ddpMessage.id] = 'offline';
} else if (ddpMessage.fields.status) {
this.activeUsers[ddpMessage.id] = ddpMessage.fields.status;
}
},
getUserPresence() {
return new Promise(async(resolve) => {
const serverVersion = reduxStore.getState().server.version;
@ -942,16 +982,12 @@ const RocketChat = {
// RC 1.1.0
const result = await this.sdk.get('users.presence', params);
if (result.success) {
// this.lastUserPresenceFetch = new Date();
database.memoryDatabase.write(() => {
result.users.forEach((item) => {
try {
item.id = item._id;
database.memoryDatabase.create('activeUsers', item, true);
} catch (error) {
console.log(error);
}
});
const activeUsers = result.users.reduce((ret, item) => {
ret[item._id] = item.status;
return ret;
}, {});
InteractionManager.runAfterInteractions(() => {
reduxStore.dispatch(setActiveUsers(activeUsers));
});
this.sdk.subscribe('stream-notify-logged', 'user-status');
return resolve();
@ -967,13 +1003,15 @@ const RocketChat = {
query, count, offset, sort
});
},
canAutoTranslate() {
async canAutoTranslate() {
const db = database.active;
try {
const AutoTranslate_Enabled = reduxStore.getState().settings && reduxStore.getState().settings.AutoTranslate_Enabled;
if (!AutoTranslate_Enabled) {
return false;
}
const autoTranslatePermission = database.objectForPrimaryKey('permissions', 'auto-translate');
const permissionsCollection = db.collections.get('permissions');
const autoTranslatePermission = await permissionsCollection.find('auto-translate');
const userRoles = (reduxStore.getState().login.user && reduxStore.getState().login.user.roles) || [];
return autoTranslatePermission.roles.some(role => userRoles.includes(role));
} catch (e) {

View File

@ -1,6 +1,6 @@
import React from 'react';
import { Text } from 'react-native';
import { emojify } from 'react-emojione';
import { shortnameToUnicode } from 'emoji-toolkit';
import PropTypes from 'prop-types';
import _ from 'lodash';
@ -20,7 +20,7 @@ const formatMsg = ({
let prefix = '';
const isLastMessageSentByMe = lastMessage.u.username === username;
if (!lastMessage.msg && Object.keys(lastMessage.attachments).length) {
if (!lastMessage.msg && lastMessage.attachments && Object.keys(lastMessage.attachments).length) {
const user = isLastMessageSentByMe ? I18n.t('You') : lastMessage.u.username;
return I18n.t('User_sent_an_attachment', { user });
}
@ -33,7 +33,7 @@ const formatMsg = ({
let msg = `${ prefix }${ lastMessage.msg.replace(/[\n\t\r]/igm, '') }`;
if (msg) {
msg = emojify(msg, { output: 'unicode' });
msg = shortnameToUnicode(msg);
}
return msg;
};

View File

@ -1,20 +1,20 @@
import React from 'react';
import PropTypes from 'prop-types';
import Status from '../../containers/Status';
import Status from '../../containers/Status/Status';
import RoomTypeIcon from '../../containers/RoomTypeIcon';
import styles from './styles';
const TypeIcon = React.memo(({ type, id, prid }) => {
const TypeIcon = React.memo(({ type, prid, status }) => {
if (type === 'd') {
return <Status style={styles.status} size={10} id={id} />;
return <Status style={styles.status} size={10} status={status} />;
}
return <RoomTypeIcon type={prid ? 'discussion' : type} />;
});
TypeIcon.propTypes = {
type: PropTypes.string,
id: PropTypes.string,
status: PropTypes.string,
prid: PropTypes.string
};

View File

@ -1,12 +1,20 @@
import React from 'react';
import PropTypes from 'prop-types';
import { View, Text, Animated } from 'react-native';
import { RectButton, PanGestureHandler, State } from 'react-native-gesture-handler';
import {
RectButton,
PanGestureHandler,
State
} from 'react-native-gesture-handler';
import { connect } from 'react-redux';
import Avatar from '../../containers/Avatar';
import I18n from '../../i18n';
import styles, {
ROW_HEIGHT, ACTION_WIDTH, SMALL_SWIPE, LONG_SWIPE
ROW_HEIGHT,
ACTION_WIDTH,
SMALL_SWIPE,
LONG_SWIPE
} from './styles';
import UnreadBadge from './UnreadBadge';
import TypeIcon from './TypeIcon';
@ -16,9 +24,20 @@ import { LeftActions, RightActions } from './Actions';
export { ROW_HEIGHT };
const attrs = ['name', 'unread', 'userMentions', 'showLastMessage', 'alert', 'type', 'width', 'isRead', 'favorite'];
const attrs = [
'name',
'unread',
'userMentions',
'showLastMessage',
'alert',
'type',
'width',
'isRead',
'favorite',
'status'
];
export default class RoomItem extends React.Component {
class RoomItem extends React.Component {
static propTypes = {
type: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
@ -41,17 +60,16 @@ export default class RoomItem extends React.Component {
favorite: PropTypes.bool,
isRead: PropTypes.bool,
rid: PropTypes.string,
status: PropTypes.string,
toggleFav: PropTypes.func,
toggleRead: PropTypes.func,
hideChannel: PropTypes.func
}
};
static defaultProps = {
avatarSize: 48
}
};
// Making jest happy: https://github.com/facebook/react-native/issues/22175
// eslint-disable-next-line no-useless-constructor
constructor(props) {
super(props);
this.dragX = new Animated.Value(0);
@ -70,13 +88,7 @@ export default class RoomItem extends React.Component {
}
shouldComponentUpdate(nextProps) {
const { lastMessage, _updatedAt } = this.props;
const oldlastMessage = lastMessage;
const newLastmessage = nextProps.lastMessage;
if (oldlastMessage && newLastmessage && oldlastMessage.ts !== newLastmessage.ts) {
return true;
}
const { _updatedAt } = this.props;
if (_updatedAt && nextProps._updatedAt && nextProps._updatedAt.toISOString() !== _updatedAt.toISOString()) {
return true;
}
@ -165,31 +177,31 @@ export default class RoomItem extends React.Component {
toggleFav(rid, favorite);
}
this.close();
}
};
toggleRead = () => {
const { toggleRead, rid, isRead } = this.props;
if (toggleRead) {
toggleRead(rid, isRead);
}
}
};
hideChannel = () => {
const { hideChannel, rid, type } = this.props;
if (hideChannel) {
hideChannel(rid, type);
}
}
};
onToggleReadPress = () => {
this.toggleRead();
this.close();
}
};
onHidePress = () => {
this.hideChannel();
this.close();
}
};
onPress = () => {
const { rowState } = this.state;
@ -201,11 +213,11 @@ export default class RoomItem extends React.Component {
if (onPress) {
onPress();
}
}
};
render() {
const {
unread, userMentions, name, _updatedAt, alert, testID, type, avatarSize, baseUrl, userId, username, token, id, prid, showLastMessage, lastMessage, isRead, width, favorite
unread, userMentions, name, _updatedAt, alert, testID, type, avatarSize, baseUrl, userId, username, token, id, prid, showLastMessage, lastMessage, isRead, width, favorite, status
} = this.props;
const date = formatDate(_updatedAt);
@ -246,11 +258,9 @@ export default class RoomItem extends React.Component {
onHidePress={this.onHidePress}
/>
<Animated.View
style={
{
transform: [{ translateX: this.transX }]
}
}
style={{
transform: [{ translateX: this.transX }]
}}
>
<RectButton
onPress={this.onPress}
@ -263,16 +273,59 @@ export default class RoomItem extends React.Component {
style={styles.container}
accessibilityLabel={accessibilityLabel}
>
<Avatar text={name} size={avatarSize} type={type} baseUrl={baseUrl} style={styles.avatar} userId={userId} token={token} />
<Avatar
text={name}
size={avatarSize}
type={type}
baseUrl={baseUrl}
style={styles.avatar}
userId={userId}
token={token}
/>
<View style={styles.centerContainer}>
<View style={styles.titleContainer}>
<TypeIcon type={type} id={id} prid={prid} />
<Text style={[styles.title, alert && styles.alert]} ellipsizeMode='tail' numberOfLines={1}>{ name }</Text>
{_updatedAt ? <Text style={[styles.date, alert && styles.updateAlert]} ellipsizeMode='tail' numberOfLines={1}>{ capitalize(date) }</Text> : null}
<TypeIcon
type={type}
id={id}
prid={prid}
status={status}
/>
<Text
style={[
styles.title,
alert && styles.alert
]}
ellipsizeMode='tail'
numberOfLines={1}
>
{name}
</Text>
{_updatedAt ? (
<Text
style={[
styles.date,
alert && styles.updateAlert
]}
ellipsizeMode='tail'
numberOfLines={1}
>
{capitalize(date)}
</Text>
) : null}
</View>
<View style={styles.row}>
<LastMessage lastMessage={lastMessage} type={type} showLastMessage={showLastMessage} username={username} alert={alert} />
<UnreadBadge unread={unread} userMentions={userMentions} type={type} />
<LastMessage
lastMessage={lastMessage}
type={type}
showLastMessage={showLastMessage}
username={username}
alert={alert}
/>
<UnreadBadge
unread={unread}
userMentions={userMentions}
type={type}
/>
</View>
</View>
</View>
@ -283,3 +336,9 @@ export default class RoomItem extends React.Component {
);
}
}
const mapStateToProps = (state, ownProps) => ({
status: state.meteor.connected && ownProps.type === 'd' ? state.activeUsers[ownProps.id] : 'offline'
});
export default connect(mapStateToProps)(RoomItem);

View File

@ -4,7 +4,6 @@ import { View, Text } from 'react-native';
import FastImage from 'react-native-fast-image';
import { RectButton } from 'react-native-gesture-handler';
import log from '../../utils/log';
import Check from '../../containers/Check';
import styles, { ROW_HEIGHT } from './styles';
@ -24,7 +23,7 @@ const ServerItem = React.memo(({
}}
defaultSource={{ uri: 'logo' }}
style={styles.serverIcon}
onError={() => log('err_loading_server_icon')}
onError={() => console.log('err_loading_server_icon')}
/>
)
: (

View File

@ -0,0 +1,15 @@
import { SET_ACTIVE_USERS } from '../actions/actionsTypes';
const initialState = {};
export default function activeUsers(state = initialState, action) {
switch (action.type) {
case SET_ACTIVE_USERS:
return {
...state,
...action.activeUsers
};
default:
return state;
}
}

View File

@ -7,7 +7,7 @@ const initialState = {
error: {}
};
export default function messages(state = initialState, action) {
export default function(state = initialState, action) {
switch (action.type) {
case CREATE_CHANNEL.REQUEST:
return {

View File

@ -0,0 +1,14 @@
import { SET_CUSTOM_EMOJIS } from '../actions/actionsTypes';
const initialState = {
customEmojis: {}
};
export default function customEmojis(state = initialState, action) {
switch (action.type) {
case SET_CUSTOM_EMOJIS:
return action.emojis;
default:
return state;
}
}

View File

@ -2,7 +2,6 @@ import { combineReducers } from 'redux';
import settings from './reducers';
import login from './login';
import meteor from './connect';
import messages from './messages';
import rooms from './rooms';
import server from './server';
import selectedUsers from './selectedUsers';
@ -13,12 +12,14 @@ import notification from './notification';
import markdown from './markdown';
import share from './share';
import crashReport from './crashReport';
import customEmojis from './customEmojis';
import activeUsers from './activeUsers';
import usersTyping from './usersTyping';
export default combineReducers({
settings,
login,
meteor,
messages,
server,
selectedUsers,
createChannel,
@ -28,5 +29,8 @@ export default combineReducers({
notification,
markdown,
share,
crashReport
crashReport,
customEmojis,
activeUsers,
usersTyping
});

View File

@ -1,96 +0,0 @@
import * as types from '../actions/actionsTypes';
const initialState = {
message: {},
actionMessage: {},
replyMessage: {},
replying: false,
editing: false,
showActions: false,
showErrorActions: false,
showReactionPicker: false
};
export default function messages(state = initialState, action) {
switch (action.type) {
case types.MESSAGES.ACTIONS_SHOW:
return {
...state,
showActions: true,
actionMessage: action.actionMessage
};
case types.MESSAGES.ACTIONS_HIDE:
return {
...state,
showActions: false
};
case types.MESSAGES.ERROR_ACTIONS_SHOW:
return {
...state,
showErrorActions: true,
actionMessage: action.actionMessage
};
case types.MESSAGES.ERROR_ACTIONS_HIDE:
return {
...state,
showErrorActions: false
};
case types.MESSAGES.EDIT_INIT:
return {
...state,
message: action.message,
editing: true
};
case types.MESSAGES.EDIT_CANCEL:
return {
...state,
message: {},
editing: false
};
case types.MESSAGES.EDIT_SUCCESS:
return {
...state,
message: {},
editing: false
};
case types.MESSAGES.EDIT_FAILURE:
return {
...state,
message: {},
editing: false
};
case types.MESSAGES.REPLY_INIT:
return {
...state,
replyMessage: {
...action.message,
mention: action.mention
},
replying: true
};
case types.MESSAGES.REPLY_CANCEL:
return {
...state,
replyMessage: {},
replying: false
};
case types.MESSAGES.SET_INPUT:
return {
...state,
message: action.message
};
case types.MESSAGES.CLEAR_INPUT:
return {
...state,
message: {}
};
case types.MESSAGES.TOGGLE_REACTION_PICKER:
return {
...state,
showReactionPicker: !state.showReactionPicker,
actionMessage: action.message
};
default:
return state;
}
}

View File

@ -5,7 +5,7 @@ const initialState = {
loading: false
};
export default function messages(state = initialState, action) {
export default function(state = initialState, action) {
switch (action.type) {
case SELECTED_USERS.ADD_USER:
return {

View File

@ -0,0 +1,19 @@
import { USERS_TYPING } from '../actions/actionsTypes';
const initialState = [];
export default function usersTyping(state = initialState, action) {
switch (action.type) {
case USERS_TYPING.ADD:
if (state.findIndex(item => item === action.username) === -1) {
return [...state, action.username];
}
return state;
case USERS_TYPING.REMOVE:
return state.filter(item => item !== action.username);
case USERS_TYPING.CLEAR:
return initialState;
default:
return state;
}
}

View File

@ -6,7 +6,7 @@ import RNUserDefaults from 'rn-user-defaults';
import Navigation from '../lib/Navigation';
import * as types from '../actions/actionsTypes';
import { selectServerRequest } from '../actions/server';
import database from '../lib/realm';
import database from '../lib/database';
import RocketChat from '../lib/rocketchat';
import EventEmitter from '../utils/events';
import { appStart } from '../actions';
@ -66,21 +66,27 @@ const handleOpen = function* handleOpen({ params }) {
}
} else {
// search if deep link's server already exists
const servers = yield database.databases.serversDB.objects('servers').filtered('id = $0', host); // TODO: need better test
if (servers.length && user) {
yield put(selectServerRequest(host));
yield take(types.SERVER.SELECT_SUCCESS);
yield navigate({ params });
} else {
// if deep link is from a different server
const result = yield RocketChat.getServerInfo(server);
if (!result.success) {
const serversDB = database.servers;
const serversCollection = serversDB.collections.get('servers');
try {
const servers = yield serversCollection.find(host);
if (servers && user) {
yield put(selectServerRequest(host));
yield take(types.SERVER.SELECT_SUCCESS);
yield navigate({ params });
return;
}
Navigation.navigate('OnboardingView', { previousServer: server });
yield delay(1000);
EventEmitter.emit('NewServer', { server: host });
} catch (e) {
// do nothing?
}
// if deep link is from a different server
const result = yield RocketChat.getServerInfo(server);
if (!result.success) {
return;
}
Navigation.navigate('OnboardingView', { previousServer: server });
yield delay(1000);
EventEmitter.emit('NewServer', { server: host });
}
};

View File

@ -2,6 +2,7 @@ import { AsyncStorage } from 'react-native';
import { put, takeLatest, all } from 'redux-saga/effects';
import SplashScreen from 'react-native-splash-screen';
import RNUserDefaults from 'rn-user-defaults';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import * as actions from '../actions';
import { selectServerRequest } from '../actions/server';
@ -12,10 +13,11 @@ import { APP } from '../actions/actionsTypes';
import RocketChat from '../lib/rocketchat';
import log from '../utils/log';
import Navigation from '../lib/Navigation';
import database from '../lib/realm';
import {
IDENTIFIER, SERVERS, SERVER_ICON, SERVER_NAME, SERVER_URL, TOKEN, USER_ID
} from '../constants/credentials';
import database from '../lib/database';
import protectedFunction from '../lib/methods/helpers/protectedFunction';
const restore = function* restore() {
try {
@ -27,33 +29,47 @@ const restore = function* restore() {
server: RNUserDefaults.get('currentServer')
});
let servers = yield RNUserDefaults.objectForKey(SERVERS);
// if not have current
if (servers && servers.length !== 0 && (!token || !server)) {
server = servers[0][SERVER_URL];
token = servers[0][TOKEN];
}
// get native credentials
if (!hasMigration) {
const { serversDB } = database.databases;
const servers = yield RNUserDefaults.objectForKey(SERVERS);
if (servers) {
serversDB.write(() => {
servers.forEach(async(serverItem) => {
const serverInfo = {
id: serverItem[SERVER_URL],
name: serverItem[SERVER_NAME],
iconURL: serverItem[SERVER_ICON]
};
try {
serversDB.create('servers', serverInfo, true);
await RNUserDefaults.set(`${ RocketChat.TOKEN_KEY }-${ serverInfo.id }`, serverItem[USER_ID]);
} catch (e) {
log(e);
}
});
if (servers && !hasMigration) {
// parse servers
servers = yield Promise.all(servers.map(async(s) => {
await RNUserDefaults.set(`${ RocketChat.TOKEN_KEY }-${ s[SERVER_URL] }`, s[USER_ID]);
return ({ id: s[SERVER_URL], name: s[SERVER_NAME], iconURL: s[SERVER_ICON] });
}));
try {
const serversDB = database.servers;
yield serversDB.action(async() => {
const serversCollection = serversDB.collections.get('servers');
const allServerRecords = await serversCollection.query().fetch();
// filter servers
let serversToCreate = servers.filter(i1 => !allServerRecords.find(i2 => i1.id === i2.id));
// Create
serversToCreate = serversToCreate.map(record => serversCollection.prepareCreate(protectedFunction((s) => {
s._raw = sanitizedRaw({ id: record.id }, serversCollection.schema);
Object.assign(s, record);
})));
const allRecords = serversToCreate;
try {
await serversDB.batch(...allRecords);
} catch (e) {
log(e);
}
return allRecords.length;
});
yield AsyncStorage.setItem('hasMigration', '1');
}
// if not have current
if (servers && servers.length !== 0 && (!token || !server)) {
server = servers[0][SERVER_URL];
token = servers[0][TOKEN];
} catch (e) {
log(e);
}
}
@ -73,13 +89,16 @@ const restore = function* restore() {
]);
yield put(actions.appStart('outside'));
} else if (server) {
const serverObj = database.databases.serversDB.objectForPrimaryKey('servers', server);
const serversDB = database.servers;
const serverCollections = serversDB.collections.get('servers');
const serverObj = yield serverCollections.find(server);
yield put(selectServerRequest(server, serverObj && serverObj.version));
}
yield put(actions.appReady({}));
} catch (e) {
log(e);
yield put(actions.appStart('outside'));
}
};

View File

@ -2,6 +2,7 @@ import {
put, call, takeLatest, select, take, fork, cancel
} from 'redux-saga/effects';
import RNUserDefaults from 'rn-user-defaults';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import moment from 'moment';
import 'moment/min/locales';
@ -14,8 +15,9 @@ import { toMomentLocale } from '../utils/moment';
import RocketChat from '../lib/rocketchat';
import log from '../utils/log';
import I18n from '../i18n';
import database from '../lib/realm';
import database from '../lib/database';
import EventEmitter from '../utils/events';
import Navigation from '../lib/Navigation';
const getServer = state => state.server.server;
const loginWithPasswordCall = args => RocketChat.loginWithPassword(args);
@ -77,12 +79,28 @@ const handleLoginSuccess = function* handleLoginSuccess({ user }) {
I18n.locale = user.language;
moment.locale(toMomentLocale(user.language));
const { serversDB } = database.databases;
serversDB.write(() => {
const serversDB = database.servers;
const usersCollection = serversDB.collections.get('users');
const u = {
token: user.token,
username: user.username,
name: user.name,
language: user.language,
status: user.status,
roles: user.roles
};
yield serversDB.action(async() => {
try {
serversDB.create('user', user, true);
const userRecord = await usersCollection.find(user.id);
await userRecord.update((record) => {
record._raw = sanitizedRaw({ id: user.id, ...record._raw }, usersCollection.schema);
Object.assign(record, u);
});
} catch (e) {
log(e);
await usersCollection.create((record) => {
record._raw = sanitizedRaw({ id: user.id }, usersCollection.schema);
Object.assign(record, u);
});
}
});
@ -104,18 +122,23 @@ const handleLoginSuccess = function* handleLoginSuccess({ user }) {
};
const handleLogout = function* handleLogout() {
Navigation.navigate('AuthLoading');
const server = yield select(getServer);
if (server) {
try {
yield call(logoutCall, { server });
const { serversDB } = database.databases;
const serversDB = database.servers;
// all servers
const servers = yield serversDB.objects('servers');
const serversCollection = serversDB.collections.get('servers');
// filter logging out server and delete it
const serverRecord = servers.filtered('id = $0', server);
serversDB.write(() => {
serversDB.delete(serverRecord);
yield serversDB.action(async() => {
const serverRecord = await serversCollection.find(server);
await serverRecord.destroyPermanently();
});
const servers = yield serversCollection.query().fetch();
// see if there's other logged in servers and selects first one
if (servers.length > 0) {
const newServer = servers[0].id;

View File

@ -1,92 +1,37 @@
import {
takeLatest, put, call, delay
} from 'redux-saga/effects';
import { takeLatest } from 'redux-saga/effects';
import { Q } from '@nozbe/watermelondb';
import Navigation from '../lib/Navigation';
import { MESSAGES } from '../actions/actionsTypes';
import {
deleteSuccess,
deleteFailure,
editSuccess,
editFailure,
toggleStarSuccess,
toggleStarFailure,
togglePinSuccess,
togglePinFailure,
replyInit
} from '../actions/messages';
import RocketChat from '../lib/rocketchat';
import database from '../lib/realm';
import database from '../lib/database';
import log from '../utils/log';
const deleteMessage = message => RocketChat.deleteMessage(message);
const editMessage = message => RocketChat.editMessage(message);
const toggleStarMessage = message => RocketChat.toggleStarMessage(message);
const togglePinMessage = message => RocketChat.togglePinMessage(message);
const handleDeleteRequest = function* handleDeleteRequest({ message }) {
try {
yield call(deleteMessage, message);
yield put(deleteSuccess());
} catch (error) {
yield put(deleteFailure());
}
};
const handleEditRequest = function* handleEditRequest({ message }) {
try {
yield call(editMessage, message);
yield put(editSuccess());
} catch (error) {
yield put(editFailure());
}
};
const handleToggleStarRequest = function* handleToggleStarRequest({ message }) {
try {
yield call(toggleStarMessage, message);
yield put(toggleStarSuccess());
} catch (error) {
yield put(toggleStarFailure());
}
};
const handleTogglePinRequest = function* handleTogglePinRequest({ message }) {
try {
yield call(togglePinMessage, message);
yield put(togglePinSuccess());
} catch (error) {
yield put(togglePinFailure(error));
}
};
const goRoom = function goRoom({ rid, name }) {
const goRoom = function goRoom({ rid, name, message }) {
Navigation.navigate('RoomsListView');
Navigation.navigate('RoomView', { rid, name, t: 'd' });
Navigation.navigate('RoomView', {
rid, name, t: 'd', message
});
};
const handleReplyBroadcast = function* handleReplyBroadcast({ message }) {
try {
const db = database.active;
const { username } = message.u;
const subscriptions = database.objects('subscriptions').filtered('name = $0', username);
const subsCollection = db.collections.get('subscriptions');
const subscriptions = yield subsCollection.query(Q.where('name', username)).fetch();
if (subscriptions.length) {
yield goRoom({ rid: subscriptions[0].rid, name: username });
yield goRoom({ rid: subscriptions[0].rid, name: username, message });
} else {
const room = yield RocketChat.createDirectMessage(username);
yield goRoom({ rid: room.rid, name: username });
yield goRoom({ rid: room.rid, name: username, message });
}
yield delay(500);
yield put(replyInit(message, false));
} catch (e) {
log(e);
}
};
const root = function* root() {
yield takeLatest(MESSAGES.DELETE_REQUEST, handleDeleteRequest);
yield takeLatest(MESSAGES.EDIT_REQUEST, handleEditRequest);
yield takeLatest(MESSAGES.TOGGLE_STAR_REQUEST, handleToggleStarRequest);
yield takeLatest(MESSAGES.TOGGLE_PIN_REQUEST, handleTogglePinRequest);
yield takeLatest(MESSAGES.REPLY_BROADCAST, handleReplyBroadcast);
};
export default root;

Some files were not shown because too many files have changed in this diff Show More