Chore: remove lib/rocketchat step 2 (#4035)

* create index file

* remove roomTypeToApiType from rocketchat and fix imports

* move TOKEN_KEY to const file

* move CURRENT_SERVER to const file

* move CERTIFICATE_KEY to const file

* getRoom

* rename getSlashCommands

* getSlashCommands

* readMessages

* getRooms

* loadThreadMessages

* loadNextMessages

* loadSurroundingMessages

* loadMessagesForRoom

* loadMissedMessages

* clearCache

* canOpenRoom

* setUser

* userPreferencesMethods

* getCustomEmojis

* callJtisi

* triggerActions

* getPermissions

* getRoles

* getSettings

* getUsersPresence

* logout

* sendFileMessage

* shareExtension

* sendMessage

* enterpriseModules

* getPermalinks

* search

* change RocketChat.metodo to direct call

* fix types

* Fix login

* Fix createChannel

* migrate service methods to Service.method call

* change call directly to RocketChat because the use of this

* rollback

* rollback

* fix create discussion

* fix import

Co-authored-by: Diego Mello <diegolmello@gmail.com>
This commit is contained in:
Gleidson Daniel Silva 2022-04-28 17:37:25 -03:00 committed by GitHub
parent 08271f6114
commit 89e0a40d95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
119 changed files with 744 additions and 756 deletions

View File

@ -14,11 +14,11 @@ import Touch from '../utils/touch';
import I18n from '../i18n'; import I18n from '../i18n';
import random from '../utils/random'; import random from '../utils/random';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
import RocketChat from '../lib/rocketchat';
import { CustomIcon } from '../lib/Icons'; import { CustomIcon } from '../lib/Icons';
import { IServices } from '../selectors/login'; import { IServices } from '../selectors/login';
import { OutsideParamList } from '../stacks/types'; import { OutsideParamList } from '../stacks/types';
import { IApplicationState } from '../definitions'; import { IApplicationState } from '../definitions';
import { Services } from '../lib/services';
const BUTTON_HEIGHT = 48; const BUTTON_HEIGHT = 48;
const SERVICE_HEIGHT = 58; const SERVICE_HEIGHT = 58;
@ -248,7 +248,7 @@ class LoginServices extends React.PureComponent<ILoginServicesProps, ILoginServi
AppleAuthentication.AppleAuthenticationScope.EMAIL AppleAuthentication.AppleAuthenticationScope.EMAIL
] ]
}); });
await RocketChat.loginOAuthOrSso({ fullName, email, identityToken }); await Services.loginOAuthOrSso({ fullName, email, identityToken });
} catch { } catch {
logEvent(events.ENTER_WITH_APPLE_F); logEvent(events.ENTER_WITH_APPLE_F);
} }

View File

@ -4,7 +4,6 @@ import Clipboard from '@react-native-clipboard/clipboard';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import moment from 'moment'; import moment from 'moment';
import RocketChat from '../../lib/rocketchat';
import database from '../../lib/database'; import database from '../../lib/database';
import I18n from '../../i18n'; import I18n from '../../i18n';
import log, { logEvent } from '../../utils/log'; import log, { logEvent } from '../../utils/log';
@ -17,6 +16,8 @@ import { TActionSheetOptionsItem, useActionSheet } from '../ActionSheet';
import Header, { HEADER_HEIGHT, IHeader } from './Header'; import Header, { HEADER_HEIGHT, IHeader } from './Header';
import events from '../../utils/log/events'; import events from '../../utils/log/events';
import { IApplicationState, ILoggedUser, TAnyMessageModel, TSubscriptionModel } from '../../definitions'; import { IApplicationState, ILoggedUser, TAnyMessageModel, TSubscriptionModel } from '../../definitions';
import { getPermalinkMessage, hasPermission } from '../../lib/methods';
import { Services } from '../../lib/services';
export interface IMessageActions { export interface IMessageActions {
room: TSubscriptionModel; room: TSubscriptionModel;
@ -81,7 +82,7 @@ const MessageActions = React.memo(
const getPermissions = async () => { const getPermissions = async () => {
try { try {
const permission = [editMessagePermission, deleteMessagePermission, forceDeleteMessagePermission, pinMessagePermission]; const permission = [editMessagePermission, deleteMessagePermission, forceDeleteMessagePermission, pinMessagePermission];
const result = await RocketChat.hasPermission(permission, room.rid); const result = await hasPermission(permission, room.rid);
permissions = { permissions = {
hasEditPermission: result[0], hasEditPermission: result[0],
hasDeletePermission: result[1], hasDeletePermission: result[1],
@ -150,7 +151,7 @@ const MessageActions = React.memo(
return true; return true;
}; };
const getPermalink = (message: TAnyMessageModel) => RocketChat.getPermalinkMessage(message); const getPermalink = (message: TAnyMessageModel) => getPermalinkMessage(message);
const handleReply = (message: TAnyMessageModel) => { const handleReply = (message: TAnyMessageModel) => {
logEvent(events.ROOM_MSG_ACTION_REPLY); logEvent(events.ROOM_MSG_ACTION_REPLY);
@ -178,7 +179,7 @@ const MessageActions = React.memo(
const { rid } = room; const { rid } = room;
try { try {
const db = database.active; const db = database.active;
const result = await RocketChat.markAsUnread({ messageId }); const result = await Services.markAsUnread({ messageId });
if (result.success) { if (result.success) {
const subCollection = db.get('subscriptions'); const subCollection = db.get('subscriptions');
const subRecord = await subCollection.find(rid); const subRecord = await subCollection.find(rid);
@ -234,7 +235,7 @@ const MessageActions = React.memo(
const handleStar = async (message: TAnyMessageModel) => { const handleStar = async (message: TAnyMessageModel) => {
logEvent(message.starred ? events.ROOM_MSG_ACTION_UNSTAR : events.ROOM_MSG_ACTION_STAR); logEvent(message.starred ? events.ROOM_MSG_ACTION_UNSTAR : events.ROOM_MSG_ACTION_STAR);
try { try {
await RocketChat.toggleStarMessage(message.id, message.starred as boolean); // TODO: reevaluate `message.starred` type on IMessage await Services.toggleStarMessage(message.id, message.starred as boolean); // TODO: reevaluate `message.starred` type on IMessage
EventEmitter.emit(LISTENER, { message: message.starred ? I18n.t('Message_unstarred') : I18n.t('Message_starred') }); EventEmitter.emit(LISTENER, { message: message.starred ? I18n.t('Message_unstarred') : I18n.t('Message_starred') });
} catch (e) { } catch (e) {
logEvent(events.ROOM_MSG_ACTION_STAR_F); logEvent(events.ROOM_MSG_ACTION_STAR_F);
@ -245,7 +246,7 @@ const MessageActions = React.memo(
const handlePin = async (message: TAnyMessageModel) => { const handlePin = async (message: TAnyMessageModel) => {
logEvent(events.ROOM_MSG_ACTION_PIN); logEvent(events.ROOM_MSG_ACTION_PIN);
try { try {
await RocketChat.togglePinMessage(message.id, message.pinned as boolean); // TODO: reevaluate `message.pinned` type on IMessage await Services.togglePinMessage(message.id, message.pinned as boolean); // TODO: reevaluate `message.pinned` type on IMessage
} catch (e) { } catch (e) {
logEvent(events.ROOM_MSG_ACTION_PIN_F); logEvent(events.ROOM_MSG_ACTION_PIN_F);
log(e); log(e);
@ -292,7 +293,7 @@ const MessageActions = React.memo(
u: message.u, u: message.u,
msg: message.msg msg: message.msg
}; };
await RocketChat.translateMessage(m, room.autoTranslateLanguage); await Services.translateMessage(m, room.autoTranslateLanguage);
} }
} catch (e) { } catch (e) {
log(e); log(e);
@ -302,7 +303,7 @@ const MessageActions = React.memo(
const handleReport = async (message: TAnyMessageModel) => { const handleReport = async (message: TAnyMessageModel) => {
logEvent(events.ROOM_MSG_ACTION_REPORT); logEvent(events.ROOM_MSG_ACTION_REPORT);
try { try {
await RocketChat.reportMessage(message.id); await Services.reportMessage(message.id);
Alert.alert(I18n.t('Message_Reported')); Alert.alert(I18n.t('Message_Reported'));
} catch (e) { } catch (e) {
logEvent(events.ROOM_MSG_ACTION_REPORT_F); logEvent(events.ROOM_MSG_ACTION_REPORT_F);
@ -317,7 +318,7 @@ const MessageActions = React.memo(
onPress: async () => { onPress: async () => {
try { try {
logEvent(events.ROOM_MSG_ACTION_DELETE); logEvent(events.ROOM_MSG_ACTION_DELETE);
await RocketChat.deleteMessage(message.id, message.subscription ? message.subscription.id : ''); await Services.deleteMessage(message.id, message.subscription ? message.subscription.id : '');
} catch (e) { } catch (e) {
logEvent(events.ROOM_MSG_ACTION_DELETE_F); logEvent(events.ROOM_MSG_ACTION_DELETE_F);
log(e); log(e);

View File

@ -11,7 +11,6 @@ import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { generateTriggerId } from '../../lib/methods/actions'; import { generateTriggerId } from '../../lib/methods/actions';
import TextInput, { IThemedTextInput } from '../../presentation/TextInput'; import TextInput, { IThemedTextInput } from '../../presentation/TextInput';
import { userTyping as userTypingAction } from '../../actions/room'; import { userTyping as userTypingAction } from '../../actions/room';
import RocketChat from '../../lib/rocketchat';
import styles from './styles'; import styles from './styles';
import database from '../../lib/database'; import database from '../../lib/database';
import { emojis } from '../../emojis'; import { emojis } from '../../emojis';
@ -52,6 +51,8 @@ import { IMessage } from '../../definitions/IMessage';
import { forceJpgExtension } from './forceJpgExtension'; import { forceJpgExtension } from './forceJpgExtension';
import { IBaseScreen, IPreviewItem, IUser, TSubscriptionModel, TThreadModel } from '../../definitions'; import { IBaseScreen, IPreviewItem, IUser, TSubscriptionModel, TThreadModel } from '../../definitions';
import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types'; import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types';
import { getPermalinkMessage, hasPermission, search, sendFileMessage } from '../../lib/methods';
import { Services } from '../../lib/services';
import { TSupportedThemes } from '../../theme'; import { TSupportedThemes } from '../../theme';
if (isAndroid) { if (isAndroid) {
@ -408,7 +409,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
return; return;
} }
const permissionToUpload = await RocketChat.hasPermission([uploadFilePermission], rid); const permissionToUpload = await hasPermission([uploadFilePermission], rid);
this.setState({ permissionToUpload: permissionToUpload[0] }); this.setState({ permissionToUpload: permissionToUpload[0] });
}; };
@ -529,7 +530,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
try { try {
const { appId } = command; const { appId } = command;
const triggerId = generateTriggerId(appId); const triggerId = generateTriggerId(appId);
RocketChat.executeCommandPreview(name, params, rid, item, triggerId, tmid || messageTmid); Services.executeCommandPreview(name, params, rid, item, triggerId, tmid || messageTmid);
replyCancel(); replyCancel();
} catch (e) { } catch (e) {
log(e); log(e);
@ -552,7 +553,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
getPermalink = async (message: any) => { getPermalink = async (message: any) => {
try { try {
return await RocketChat.getPermalinkMessage(message); return await getPermalinkMessage(message);
} catch (error) { } catch (error) {
return null; return null;
} }
@ -570,13 +571,13 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
}; };
getUsers = debounce(async (keyword: any) => { getUsers = debounce(async (keyword: any) => {
let res = await RocketChat.search({ text: keyword, filterRooms: false, filterUsers: true }); let res = await search({ text: keyword, filterRooms: false, filterUsers: true });
res = [...this.getFixedMentions(keyword), ...res]; res = [...this.getFixedMentions(keyword), ...res];
this.setState({ mentions: res, mentionLoading: false }); this.setState({ mentions: res, mentionLoading: false });
}, 300); }, 300);
getRooms = debounce(async (keyword = '') => { getRooms = debounce(async (keyword = '') => {
const res = await RocketChat.search({ text: keyword, filterRooms: true, filterUsers: false }); const res = await search({ text: keyword, filterRooms: true, filterUsers: false });
this.setState({ mentions: res, mentionLoading: false }); this.setState({ mentions: res, mentionLoading: false });
}, 300); }, 300);
@ -604,7 +605,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
}, 300); }, 300);
getCannedResponses = debounce(async (text?: string) => { getCannedResponses = debounce(async (text?: string) => {
const res = await RocketChat.getListCannedResponse({ text }); const res = await Services.getListCannedResponse({ text });
this.setState({ mentions: res.success ? res.cannedResponses : [], mentionLoading: false }); this.setState({ mentions: res.success ? res.cannedResponses : [], mentionLoading: false });
}, 500); }, 500);
@ -641,7 +642,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
setCommandPreview = async (command: any, name: string, params: string) => { setCommandPreview = async (command: any, name: string, params: string) => {
const { rid } = this.props; const { rid } = this.props;
try { try {
const response = await RocketChat.getCommandPreview(name, rid, params); const response = await Services.getCommandPreview(name, rid, params);
if (response.success) { if (response.success) {
return this.setState({ commandPreview: response.preview?.items || [], showCommandPreview: true, command }); return this.setState({ commandPreview: response.preview?.items || [], showCommandPreview: true, command });
} }
@ -836,7 +837,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
if (fileInfo) { if (fileInfo) {
try { try {
if (this.canUploadFile(fileInfo)) { if (this.canUploadFile(fileInfo)) {
await RocketChat.sendFileMessage(rid, fileInfo, tmid, server, user); await sendFileMessage(rid, fileInfo, tmid, server, user);
} }
} catch (e) { } catch (e) {
log(e); log(e);
@ -888,7 +889,7 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
const messageWithoutCommand = message.replace(/([^\s]+)/, '').trim(); const messageWithoutCommand = message.replace(/([^\s]+)/, '').trim();
const [{ appId }] = slashCommand; const [{ appId }] = slashCommand;
const triggerId = generateTriggerId(appId); const triggerId = generateTriggerId(appId);
await RocketChat.runSlashCommand(command, roomId, messageWithoutCommand, triggerId, tmid || messageTmid); await Services.runSlashCommand(command, roomId, messageWithoutCommand, triggerId, tmid || messageTmid);
replyCancel(); replyCancel();
} catch (e) { } catch (e) {
logEvent(events.COMMAND_RUN_F); logEvent(events.COMMAND_RUN_F);

View File

@ -1,20 +1,20 @@
import { forwardRef, useImperativeHandle } from 'react'; import { forwardRef, useImperativeHandle } from 'react';
import Model from '@nozbe/watermelondb/Model'; import Model from '@nozbe/watermelondb/Model';
import RocketChat from '../lib/rocketchat';
import database from '../lib/database'; import database from '../lib/database';
import protectedFunction from '../lib/methods/helpers/protectedFunction'; import protectedFunction from '../lib/methods/helpers/protectedFunction';
import { useActionSheet } from './ActionSheet'; import { useActionSheet } from './ActionSheet';
import I18n from '../i18n'; import I18n from '../i18n';
import log from '../utils/log'; import log from '../utils/log';
import { TMessageModel } from '../definitions'; import { TMessageModel } from '../definitions';
import { resendMessage } from '../lib/methods';
const MessageErrorActions = forwardRef(({ tmid }: { tmid: string }, ref) => { const MessageErrorActions = forwardRef(({ tmid }: { tmid: string }, ref) => {
// TODO - remove this any after merge ActionSheet evaluate // TODO - remove this any after merge ActionSheet evaluate
const { showActionSheet }: any = useActionSheet(); const { showActionSheet }: any = useActionSheet();
const handleResend = protectedFunction(async (message: TMessageModel) => { const handleResend = protectedFunction(async (message: TMessageModel) => {
await RocketChat.resendMessage(message, tmid); await resendMessage(message, tmid);
}); });
const handleDelete = async (message: TMessageModel) => { const handleDelete = async (message: TMessageModel) => {

View File

@ -13,9 +13,9 @@ import { useTheme } from '../../theme';
import { themes } from '../../lib/constants'; import { themes } from '../../lib/constants';
import Button from '../Button'; import Button from '../Button';
import sharedStyles from '../../views/Styles'; import sharedStyles from '../../views/Styles';
import RocketChat from '../../lib/rocketchat';
import styles from './styles'; import styles from './styles';
import { IApplicationState } from '../../definitions'; import { IApplicationState } from '../../definitions';
import { Services } from '../../lib/services';
export const TWO_FACTOR = 'TWO_FACTOR'; export const TWO_FACTOR = 'TWO_FACTOR';
@ -63,7 +63,7 @@ const TwoFactor = React.memo(({ isMasterDetail }: { isMasterDetail: boolean }) =
const method = data.method ? methods[data.method] : null; const method = data.method ? methods[data.method] : null;
const isEmail = data.method === 'email'; const isEmail = data.method === 'email';
const sendEmail = () => RocketChat.sendEmailCode(); const sendEmail = () => Services.sendEmailCode();
useDeepCompareEffect(() => { useDeepCompareEffect(() => {
if (!isEmpty(data)) { if (!isEmpty(data)) {

View File

@ -5,12 +5,12 @@ import * as List from '../../../../containers/List';
import styles from './styles'; import styles from './styles';
import { SWITCH_TRACK_COLOR, themes } from '../../../../lib/constants'; import { SWITCH_TRACK_COLOR, themes } from '../../../../lib/constants';
import { useTheme } from '../../../../theme'; import { useTheme } from '../../../../theme';
import RocketChat from '../../../../lib/rocketchat';
import { IUser } from '../../../../definitions/IUser'; import { IUser } from '../../../../definitions/IUser';
import { showConfirmationAlert } from '../../../../utils/info'; import { showConfirmationAlert } from '../../../../utils/info';
import I18n from '../../../../i18n'; import I18n from '../../../../i18n';
import { changeLivechatStatus, isOmnichannelStatusAvailable } from '../../lib'; import { changeLivechatStatus, isOmnichannelStatusAvailable } from '../../lib';
import OmnichannelQueue from './OmnichannelQueue'; import OmnichannelQueue from './OmnichannelQueue';
import { isOmnichannelModuleAvailable } from '../../../../lib/methods';
interface IOmnichannelStatus { interface IOmnichannelStatus {
searching: boolean; searching: boolean;
@ -28,7 +28,7 @@ const OmnichannelStatus = memo(({ searching, goQueue, queueSize, user }: IOmnich
setStatus(isOmnichannelStatusAvailable(user)); setStatus(isOmnichannelStatusAvailable(user));
}, [user.statusLivechat]); }, [user.statusLivechat]);
if (searching || !(RocketChat.isOmnichannelModuleAvailable() && user?.roles?.includes('livechat-agent'))) { if (searching || !(isOmnichannelModuleAvailable() && user?.roles?.includes('livechat-agent'))) {
return null; return null;
} }

View File

@ -1,9 +1,10 @@
import log from '../../../../utils/log'; import log from '../../../../utils/log';
import { store } from '../../../../lib/store/auxStore'; import { store } from '../../../../lib/store/auxStore';
import RocketChat from '../../../../lib/rocketchat';
import { inquiryQueueAdd, inquiryQueueRemove, inquiryQueueUpdate, inquiryRequest } from '../../actions/inquiry'; import { inquiryQueueAdd, inquiryQueueRemove, inquiryQueueUpdate, inquiryRequest } from '../../actions/inquiry';
import sdk from '../../../../lib/services/sdk'; import sdk from '../../../../lib/services/sdk';
import { IOmnichannelRoom } from '../../../../definitions'; import { IOmnichannelRoom } from '../../../../definitions';
import { hasRole } from '../../../../lib/methods';
import { Services } from '../../../../lib/services';
interface IArgsQueueOmnichannel extends IOmnichannelRoom { interface IArgsQueueOmnichannel extends IOmnichannelRoom {
type: string; type: string;
@ -81,11 +82,11 @@ export default function subscribeInquiry() {
throw new Error('inquiry: @subscribeInquiry user.id not found'); throw new Error('inquiry: @subscribeInquiry user.id not found');
} }
RocketChat.getAgentDepartments(user.id).then(result => { Services.getAgentDepartments(user.id).then(result => {
if (result.success) { if (result.success) {
const { departments } = result; const { departments } = result;
if (!departments.length || RocketChat.hasRole('livechat-manager')) { if (!departments.length || hasRole('livechat-manager')) {
sdk.subscribe(streamTopic, 'public').catch((e: unknown) => console.log(e)); sdk.subscribe(streamTopic, 'public').catch((e: unknown) => console.log(e));
} }

View File

@ -1,14 +1,14 @@
import { put, select, takeLatest } from 'redux-saga/effects'; import { put, select, takeLatest } from 'redux-saga/effects';
import * as types from '../../../actions/actionsTypes'; import * as types from '../../../actions/actionsTypes';
import RocketChat from '../../../lib/rocketchat'; import { Services } from '../../../lib/services';
import EventEmitter from '../../../utils/events'; import EventEmitter from '../../../utils/events';
import { inquiryFailure, inquirySetEnabled, inquirySuccess } from '../actions/inquiry'; import { inquiryFailure, inquirySetEnabled, inquirySuccess } from '../actions/inquiry';
import { getInquiriesQueued, isOmnichannelStatusAvailable } from '../lib'; import { getInquiriesQueued, isOmnichannelStatusAvailable } from '../lib';
const handleRequest = function* handleRequest() { const handleRequest = function* handleRequest() {
try { try {
const routingConfig = yield RocketChat.getRoutingConfig(); const routingConfig = yield Services.getRoutingConfig();
const user = yield select(state => state.login.user); const user = yield select(state => state.login.user);
// if routingConfig showQueue is enabled and omnichannel is enabled // if routingConfig showQueue is enabled and omnichannel is enabled
const showQueue = routingConfig.showQueue && isOmnichannelStatusAvailable(user); const showQueue = routingConfig.showQueue && isOmnichannelStatusAvailable(user);

View File

@ -15,7 +15,6 @@ import SafeAreaView from '../../../containers/SafeAreaView';
import StatusBar from '../../../containers/StatusBar'; import StatusBar from '../../../containers/StatusBar';
import { goRoom } from '../../../utils/goRoom'; import { goRoom } from '../../../utils/goRoom';
import * as HeaderButton from '../../../containers/HeaderButton'; import * as HeaderButton from '../../../containers/HeaderButton';
import RocketChat from '../../../lib/rocketchat';
import { events, logEvent } from '../../../utils/log'; import { events, logEvent } from '../../../utils/log';
import { getInquiryQueueSelector } from '../selectors/inquiry'; import { getInquiryQueueSelector } from '../selectors/inquiry';
import { IOmnichannelRoom, IApplicationState } from '../../../definitions'; import { IOmnichannelRoom, IApplicationState } from '../../../definitions';
@ -23,6 +22,7 @@ import { DisplayMode, MAX_SIDEBAR_WIDTH, themes } from '../../../lib/constants';
import { ChatsStackParamList } from '../../../stacks/types'; import { ChatsStackParamList } from '../../../stacks/types';
import { MasterDetailInsideStackParamList } from '../../../stacks/MasterDetailStack/types'; import { MasterDetailInsideStackParamList } from '../../../stacks/MasterDetailStack/types';
import { TSettingsValues } from '../../../reducers/settings'; import { TSettingsValues } from '../../../reducers/settings';
import { getRoomAvatar, getRoomTitle, getUidDirectMessage } from '../../../lib/methods';
interface INavigationOptions { interface INavigationOptions {
isMasterDetail: boolean; isMasterDetail: boolean;
@ -98,12 +98,6 @@ class QueueListView extends React.Component<IQueueListView, any> {
}); });
}; };
getRoomTitle = (item: IOmnichannelRoom) => RocketChat.getRoomTitle(item);
getRoomAvatar = (item: IOmnichannelRoom) => RocketChat.getRoomAvatar(item);
getUidDirectMessage = (room: IOmnichannelRoom) => RocketChat.getUidDirectMessage(room);
renderItem: ListRenderItem<IOmnichannelRoom> = ({ item }) => { renderItem: ListRenderItem<IOmnichannelRoom> = ({ item }) => {
const { const {
user: { id: userId, username, token }, user: { id: userId, username, token },
@ -115,7 +109,7 @@ class QueueListView extends React.Component<IQueueListView, any> {
showAvatar, showAvatar,
displayMode displayMode
} = this.props; } = this.props;
const id = this.getUidDirectMessage(item); const id = getUidDirectMessage(item);
return ( return (
<RoomItem <RoomItem
@ -131,8 +125,8 @@ class QueueListView extends React.Component<IQueueListView, any> {
testID={`queue-list-view-item-${item.name}`} testID={`queue-list-view-item-${item.name}`}
width={isMasterDetail ? MAX_SIDEBAR_WIDTH : width} width={isMasterDetail ? MAX_SIDEBAR_WIDTH : width}
useRealName={useRealName} useRealName={useRealName}
getRoomTitle={this.getRoomTitle} getRoomTitle={getRoomTitle}
getRoomAvatar={this.getRoomAvatar} getRoomAvatar={getRoomAvatar}
visitor={item.v} visitor={item.v}
swipeEnabled={false} swipeEnabled={false}
showAvatar={showAvatar} showAvatar={showAvatar}

View File

@ -1,36 +1,36 @@
import React from 'react'; import React from 'react';
import { Dimensions, Linking } from 'react-native'; import { Dimensions, Linking } from 'react-native';
import { AppearanceProvider } from 'react-native-appearance'; import { AppearanceProvider } from 'react-native-appearance';
import { Provider } from 'react-redux';
import { KeyCommandsEmitter } from 'react-native-keycommands'; import { KeyCommandsEmitter } from 'react-native-keycommands';
import { initialWindowMetrics, SafeAreaProvider } from 'react-native-safe-area-context';
import RNScreens from 'react-native-screens'; import RNScreens from 'react-native-screens';
import { SafeAreaProvider, initialWindowMetrics } from 'react-native-safe-area-context'; import { Provider } from 'react-redux';
import { getTheme, initialTheme, newThemeState, subscribeTheme, unsubscribeTheme } from './utils/theme';
import EventEmitter from './utils/events';
import { appInit, appInitLocalSettings, setMasterDetail as setMasterDetailAction } from './actions/app'; import { appInit, appInitLocalSettings, setMasterDetail as setMasterDetailAction } from './actions/app';
import { deepLinkingOpen } from './actions/deepLinking'; import { deepLinkingOpen } from './actions/deepLinking';
import AppContainer from './AppContainer';
import { KEY_COMMAND } from './commands';
import { ActionSheetProvider } from './containers/ActionSheet';
import InAppNotification from './containers/InAppNotification';
import Toast from './containers/Toast';
import TwoFactor from './containers/TwoFactor';
import { ICommand } from './definitions/ICommand';
import { IThemePreference } from './definitions/ITheme';
import { DimensionsContext } from './dimensions';
import { colors, isFDroidBuild, MIN_WIDTH_MASTER_DETAIL_LAYOUT, themes } from './lib/constants';
import { getAllowAnalyticsEvents, getAllowCrashReport } from './lib/methods';
import parseQuery from './lib/methods/helpers/parseQuery'; import parseQuery from './lib/methods/helpers/parseQuery';
import { initializePushNotifications, onNotification } from './lib/notifications'; import { initializePushNotifications, onNotification } from './lib/notifications';
import { toggleAnalyticsEventsReport, toggleCrashErrorsReport } from './utils/log';
import { ThemeContext, TSupportedThemes } from './theme';
import { DimensionsContext } from './dimensions';
import RocketChat from './lib/rocketchat';
import { isTablet } from './utils/deviceInfo';
import { KEY_COMMAND } from './commands';
import AppContainer from './AppContainer';
import TwoFactor from './containers/TwoFactor';
import ScreenLockedView from './views/ScreenLockedView';
import ChangePasscodeView from './views/ChangePasscodeView';
import Toast from './containers/Toast';
import InAppNotification from './containers/InAppNotification';
import { ActionSheetProvider } from './containers/ActionSheet';
import debounce from './utils/debounce';
import { isFDroidBuild, MIN_WIDTH_MASTER_DETAIL_LAYOUT, colors, themes } from './lib/constants';
import { IThemePreference } from './definitions/ITheme';
import { ICommand } from './definitions/ICommand';
import store from './lib/store'; import store from './lib/store';
import { initStore } from './lib/store/auxStore'; import { initStore } from './lib/store/auxStore';
import { ThemeContext, TSupportedThemes } from './theme';
import debounce from './utils/debounce';
import { isTablet } from './utils/deviceInfo';
import EventEmitter from './utils/events';
import { toggleAnalyticsEventsReport, toggleCrashErrorsReport } from './utils/log';
import { getTheme, initialTheme, newThemeState, subscribeTheme, unsubscribeTheme } from './utils/theme';
import ChangePasscodeView from './views/ChangePasscodeView';
import ScreenLockedView from './views/ScreenLockedView';
RNScreens.enableScreens(); RNScreens.enableScreens();
initStore(store); initStore(store);
@ -193,10 +193,10 @@ export default class Root extends React.Component<{}, IState> {
}; };
initCrashReport = () => { initCrashReport = () => {
RocketChat.getAllowCrashReport().then(allowCrashReport => { getAllowCrashReport().then(allowCrashReport => {
toggleCrashErrorsReport(allowCrashReport); toggleCrashErrorsReport(allowCrashReport);
}); });
RocketChat.getAllowAnalyticsEvents().then(allowAnalyticsEvents => { getAllowAnalyticsEvents().then(allowAnalyticsEvents => {
toggleAnalyticsEventsReport(allowAnalyticsEvents); toggleAnalyticsEventsReport(allowAnalyticsEvents);
}); });
}; };

View File

@ -19,3 +19,6 @@ export const THEME_PREFERENCES_KEY = 'RC_THEME_PREFERENCES_KEY';
export const CRASH_REPORT_KEY = 'RC_CRASH_REPORT_KEY'; export const CRASH_REPORT_KEY = 'RC_CRASH_REPORT_KEY';
export const ANALYTICS_EVENTS_KEY = 'RC_ANALYTICS_EVENTS_KEY'; export const ANALYTICS_EVENTS_KEY = 'RC_ANALYTICS_EVENTS_KEY';
export const MIN_ROCKETCHAT_VERSION = '0.70.0'; export const MIN_ROCKETCHAT_VERSION = '0.70.0';
export const TOKEN_KEY = 'reactnativemeteor_usertoken';
export const CURRENT_SERVER = 'currentServer';
export const CERTIFICATE_KEY = 'RC_CERTIFICATE_KEY';

View File

@ -3,7 +3,6 @@ import SimpleCrypto from 'react-native-simple-crypto';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord'; import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { Q, Model } from '@nozbe/watermelondb'; import { Q, Model } from '@nozbe/watermelondb';
import RocketChat from '../rocketchat';
import UserPreferences from '../methods/userPreferences'; import UserPreferences from '../methods/userPreferences';
import database from '../database'; import database from '../database';
import protectedFunction from '../methods/helpers/protectedFunction'; import protectedFunction from '../methods/helpers/protectedFunction';
@ -21,6 +20,7 @@ import {
E2E_RANDOM_PASSWORD_KEY, E2E_RANDOM_PASSWORD_KEY,
E2E_STATUS E2E_STATUS
} from '../constants'; } from '../constants';
import { Services } from '../services';
class Encryption { class Encryption {
ready: boolean; ready: boolean;
@ -141,10 +141,10 @@ class Encryption {
const encodedPrivateKey = await this.encodePrivateKey(EJSON.stringify(privateKey), password, userId); const encodedPrivateKey = await this.encodePrivateKey(EJSON.stringify(privateKey), password, userId);
// Send the new keys to the server // Send the new keys to the server
await RocketChat.e2eSetUserPublicAndPrivateKeys(EJSON.stringify(publicKey), encodedPrivateKey); await Services.e2eSetUserPublicAndPrivateKeys(EJSON.stringify(publicKey), encodedPrivateKey);
// Request e2e keys of all encrypted rooms // Request e2e keys of all encrypted rooms
await RocketChat.e2eRequestSubscriptionKeys(); await Services.e2eRequestSubscriptionKeys();
}; };
// Encode a private key before send it to the server // Encode a private key before send it to the server
@ -197,7 +197,7 @@ class Encryption {
const publicKey = UserPreferences.getString(`${server}-${E2E_PUBLIC_KEY}`); const publicKey = UserPreferences.getString(`${server}-${E2E_PUBLIC_KEY}`);
// Send the new keys to the server // Send the new keys to the server
await RocketChat.e2eSetUserPublicAndPrivateKeys(EJSON.stringify(publicKey), encodedPrivateKey); await Services.e2eSetUserPublicAndPrivateKeys(EJSON.stringify(publicKey), encodedPrivateKey);
}; };
// get a encryption room instance // get a encryption room instance

View File

@ -4,7 +4,6 @@ import SimpleCrypto from 'react-native-simple-crypto';
import ByteBuffer from 'bytebuffer'; import ByteBuffer from 'bytebuffer';
import { IMessage } from '../../definitions'; import { IMessage } from '../../definitions';
import RocketChat from '../rocketchat';
import Deferred from '../../utils/deferred'; import Deferred from '../../utils/deferred';
import debounce from '../../utils/debounce'; import debounce from '../../utils/debounce';
import database from '../database'; import database from '../database';
@ -22,6 +21,7 @@ import {
import { Encryption } from './index'; import { Encryption } from './index';
import { IUser } from '../../definitions/IUser'; import { IUser } from '../../definitions/IUser';
import { E2E_MESSAGE_TYPE, E2E_STATUS } from '../constants'; import { E2E_MESSAGE_TYPE, E2E_STATUS } from '../constants';
import { Services } from '../services';
export default class EncryptionRoom { export default class EncryptionRoom {
ready: boolean; ready: boolean;
@ -134,7 +134,7 @@ export default class EncryptionRoom {
this.sessionKeyExportedString = EJSON.stringify(sessionKeyExported); this.sessionKeyExportedString = EJSON.stringify(sessionKeyExported);
this.keyID = Base64.encode(this.sessionKeyExportedString).slice(0, 12); this.keyID = Base64.encode(this.sessionKeyExportedString).slice(0, 12);
await RocketChat.e2eSetRoomKeyID(this.roomId, this.keyID); await Services.e2eSetRoomKeyID(this.roomId, this.keyID);
await this.encryptRoomKey(); await this.encryptRoomKey();
}; };
@ -147,7 +147,7 @@ export default class EncryptionRoom {
// this will be called again and run once in 5 seconds // this will be called again and run once in 5 seconds
requestRoomKey = debounce( requestRoomKey = debounce(
async (e2eKeyId: string) => { async (e2eKeyId: string) => {
await RocketChat.e2eRequestRoomKey(this.roomId, e2eKeyId); await Services.e2eRequestRoomKey(this.roomId, e2eKeyId);
}, },
5000, 5000,
true true
@ -155,7 +155,7 @@ export default class EncryptionRoom {
// Create an encrypted key for this room based on users // Create an encrypted key for this room based on users
encryptRoomKey = async () => { encryptRoomKey = async () => {
const result = await RocketChat.e2eGetUsersOfRoomWithoutKey(this.roomId); const result = await Services.e2eGetUsersOfRoomWithoutKey(this.roomId);
if (result.success) { if (result.success) {
const { users } = result; const { users } = result;
await Promise.all(users.map(user => this.encryptRoomKeyForUser(user))); await Promise.all(users.map(user => this.encryptRoomKeyForUser(user)));
@ -168,7 +168,7 @@ export default class EncryptionRoom {
const { public_key: publicKey } = user.e2e; const { public_key: publicKey } = user.e2e;
const userKey = await SimpleCrypto.RSA.importKey(EJSON.parse(publicKey)); const userKey = await SimpleCrypto.RSA.importKey(EJSON.parse(publicKey));
const encryptedUserKey = await SimpleCrypto.RSA.encrypt(this.sessionKeyExportedString as string, userKey); const encryptedUserKey = await SimpleCrypto.RSA.encrypt(this.sessionKeyExportedString as string, userKey);
await RocketChat.e2eUpdateGroupKey(user?._id, this.roomId, this.keyID + encryptedUserKey); await Services.e2eUpdateGroupKey(user?._id, this.roomId, this.keyID + encryptedUserKey);
} }
}; };

View File

@ -1,5 +1,4 @@
import { ITriggerAction, IUserInteraction, ModalActions } from '../../containers/UIKit/interfaces'; import { ITriggerAction, IUserInteraction, ModalActions } from '../../containers/UIKit/interfaces';
import { TRocketChat } from '../../definitions/IRocketChat';
import EventEmitter from '../../utils/events'; import EventEmitter from '../../utils/events';
import fetch from '../../utils/fetch'; import fetch from '../../utils/fetch';
import random from '../../utils/random'; import random from '../../utils/random';
@ -82,10 +81,7 @@ export const handlePayloadUserInteraction = (
return ModalActions.CLOSE; return ModalActions.CLOSE;
}; };
export function triggerAction( export function triggerAction({ type, actionId, appId, rid, mid, viewId, container, ...rest }: ITriggerAction) {
this: TRocketChat,
{ type, actionId, appId, rid, mid, viewId, container, ...rest }: ITriggerAction
) {
return new Promise<ModalActions | undefined | void>(async (resolve, reject) => { return new Promise<ModalActions | undefined | void>(async (resolve, reject) => {
const triggerId = generateTriggerId(appId); const triggerId = generateTriggerId(appId);

View File

@ -1,8 +1,8 @@
import { ERoomTypes } from '../../definitions'; import { ERoomTypes } from '../../definitions';
import { store } from '../store/auxStore'; import { store } from '../store/auxStore';
import database from '../database'; import database from '../database';
import RocketChat from '../rocketchat';
import sdk from '../services/sdk'; import sdk from '../services/sdk';
import { Services } from '../services';
const restTypes = { const restTypes = {
channel: 'channels', channel: 'channels',
@ -17,7 +17,7 @@ async function open({ type, rid, name }: { type: ERoomTypes; rid: string; name:
// if it's a direct link without rid we'll create a new dm // if it's a direct link without rid we'll create a new dm
// if the dm already exists it'll return the existent // if the dm already exists it'll return the existent
if (type === ERoomTypes.DIRECT && !rid) { if (type === ERoomTypes.DIRECT && !rid) {
const result = await RocketChat.createDirectMessage(name); const result = await Services.createDirectMessage(name);
if (result.success) { if (result.success) {
const { room } = result; const { room } = result;
return { return {
@ -63,7 +63,7 @@ async function open({ type, rid, name }: { type: ERoomTypes; rid: string; name:
} }
} }
export default async function canOpenRoom({ rid, path, isCall }: { rid: string; isCall: boolean; path: string }): Promise<any> { export async function canOpenRoom({ rid, path, isCall }: { rid: string; isCall: boolean; path: string }): Promise<any> {
try { try {
const db = database.active; const db = database.active;
const subsCollection = db.get('subscriptions'); const subsCollection = db.get('subscriptions');

View File

@ -1,6 +1,6 @@
import database from '../database'; import database from '../database';
export default async function clearCache({ server }: { server: string }): Promise<void> { export async function clearCache({ server }: { server: string }): Promise<void> {
try { try {
const serversDB = database.servers; const serversDB = database.servers;
await serversDB.write(async () => { await serversDB.write(async () => {

View File

@ -0,0 +1,19 @@
import AsyncStorage from '@react-native-community/async-storage';
import { ANALYTICS_EVENTS_KEY, CRASH_REPORT_KEY } from '../constants';
export async function getAllowCrashReport() {
const allowCrashReport = await AsyncStorage.getItem(CRASH_REPORT_KEY);
if (allowCrashReport === null) {
return true;
}
return JSON.parse(allowCrashReport);
}
export async function getAllowAnalyticsEvents() {
const allowAnalyticsEvents = await AsyncStorage.getItem(ANALYTICS_EVENTS_KEY);
if (allowAnalyticsEvents === null) {
return true;
}
return JSON.parse(allowAnalyticsEvents);
}

View File

@ -57,11 +57,6 @@ export function getEnterpriseModules() {
}); });
} }
export function hasLicense(module: string) {
const { enterpriseModules } = reduxStore.getState();
return enterpriseModules.includes(module);
}
export function isOmnichannelModuleAvailable() { export function isOmnichannelModuleAvailable() {
const { enterpriseModules } = reduxStore.getState(); const { enterpriseModules } = reduxStore.getState();
return [LICENSE_OMNICHANNEL_MOBILE_ENTERPRISE, LICENSE_LIVECHAT_ENTERPRISE].some(module => enterpriseModules.includes(module)); return [LICENSE_OMNICHANNEL_MOBILE_ENTERPRISE, LICENSE_LIVECHAT_ENTERPRISE].some(module => enterpriseModules.includes(module));

View File

@ -2,7 +2,7 @@ import log from '../../utils/log';
import { TMessageModel, TSubscriptionModel } from '../../definitions'; import { TMessageModel, TSubscriptionModel } from '../../definitions';
import { store } from '../store/auxStore'; import { store } from '../store/auxStore';
import { isGroupChat } from './helpers'; import { isGroupChat } from './helpers';
import getRoom from './getRoom'; import { getRoom } from './getRoom';
type TRoomType = 'p' | 'c' | 'd'; type TRoomType = 'p' | 'c' | 'd';

View File

@ -1,7 +1,7 @@
import { TSubscriptionModel } from '../../definitions'; import { TSubscriptionModel } from '../../definitions';
import database from '../database'; import database from '../database';
export default async function getRoom(rid: string): Promise<TSubscriptionModel> { export async function getRoom(rid: string): Promise<TSubscriptionModel> {
try { try {
const db = database.active; const db = database.active;
const room = await db.get('subscriptions').find(rid); const room = await db.get('subscriptions').find(rid);

View File

@ -1,6 +1,6 @@
import { IServerSubscription, RoomType } from '../../definitions'; import { IServerSubscription, RoomType } from '../../definitions';
import { getSubscriptionByRoomId } from '../database/services/Subscription'; import { getSubscriptionByRoomId } from '../database/services/Subscription';
import RocketChat from '../rocketchat'; import { Services } from '../services';
export interface IRoomInfoResult { export interface IRoomInfoResult {
rid: IServerSubscription['rid']; rid: IServerSubscription['rid'];
@ -21,7 +21,7 @@ const getRoomInfo = async (rid: string): Promise<IRoomInfoResult | null> => {
}; };
} }
result = await RocketChat.getRoomInfo(rid); result = await Services.getRoomInfo(rid);
if (result?.success) { if (result?.success) {
return { return {
rid, rid,

View File

@ -1,6 +1,6 @@
import sdk from '../services/sdk'; import sdk from '../services/sdk';
export default function (updatedSince: Date) { export function getRooms(updatedSince: Date) {
// subscriptions.get: Since RC 0.60.0 // subscriptions.get: Since RC 0.60.0
// rooms.get: Since RC 0.62.0 // rooms.get: Since RC 0.62.0
if (updatedSince) { if (updatedSince) {

View File

@ -9,8 +9,8 @@ import log from '../../utils/log';
import { store as reduxStore } from '../store/auxStore'; import { store as reduxStore } from '../store/auxStore';
import database from '../database'; import database from '../database';
import sdk from '../services/sdk'; import sdk from '../services/sdk';
import { parseSettings, _prepareSettings } from './helpers';
import protectedFunction from './helpers/protectedFunction'; import protectedFunction from './helpers/protectedFunction';
import { parseSettings, _prepareSettings } from './parseSettings';
const serverInfoKeys = [ const serverInfoKeys = [
'Site_Name', 'Site_Name',

View File

@ -1,10 +1,10 @@
import RocketChat from '../rocketchat';
import { IMessage } from '../../definitions'; import { IMessage } from '../../definitions';
import { Services } from '../services';
const getSingleMessage = (messageId: string): Promise<IMessage> => const getSingleMessage = (messageId: string): Promise<IMessage> =>
new Promise(async (resolve, reject) => { new Promise(async (resolve, reject) => {
try { try {
const result = await RocketChat.getSingleMessage(messageId); const result = await Services.getSingleMessage(messageId);
if (result.success) { if (result.success) {
return resolve(result.message); return resolve(result.message);
} }

View File

@ -6,7 +6,7 @@ import protectedFunction from './helpers/protectedFunction';
import { ISlashCommandResult, TSlashCommandModel } from '../../definitions'; import { ISlashCommandResult, TSlashCommandModel } from '../../definitions';
import sdk from '../services/sdk'; import sdk from '../services/sdk';
export default function getSlashCommands() { export function getSlashCommands() {
const db = database.active; const db = database.active;
return new Promise<void>(async resolve => { return new Promise<void>(async resolve => {
try { try {

View File

@ -34,7 +34,7 @@ export function subscribeUsersPresence(this: IRocketChat) {
let usersBatch: string[] = []; let usersBatch: string[] = [];
export default async function getUsersPresence(usersParams: string[]) { export async function getUsersPresence(usersParams: string[]) {
const serverVersion = reduxStore.getState().server.version as string; const serverVersion = reduxStore.getState().server.version as string;
const { user: loggedUser } = reduxStore.getState().login; const { user: loggedUser } = reduxStore.getState().login;
@ -106,6 +106,7 @@ export default async function getUsersPresence(usersParams: string[]) {
} }
let usersTimer: ReturnType<typeof setTimeout> | null = null; let usersTimer: ReturnType<typeof setTimeout> | null = null;
export function getUserPresence(uid: string) { export function getUserPresence(uid: string) {
if (!usersTimer) { if (!usersTimer) {
usersTimer = setTimeout(() => { usersTimer = setTimeout(() => {

View File

@ -1,11 +1,7 @@
// @ts-nocheck - TEMP // @ts-nocheck - TEMP
import AsyncStorage from '@react-native-community/async-storage';
import log from '../../utils/log'; import log from '../../utils/log';
import { store as reduxStore } from '../store/auxStore'; import { store as reduxStore } from '../store/auxStore';
import database from '../database'; import database from '../database';
import subscribeRoomsTmp from './subscriptions/rooms';
import { ANALYTICS_EVENTS_KEY, CRASH_REPORT_KEY, defaultSettings } from '../constants';
export function isGroupChat(room): boolean { export function isGroupChat(room): boolean {
return ((room.uids && room.uids.length > 2) || (room.usernames && room.usernames.length > 2)) ?? false; return ((room.uids && room.uids.length > 2) || (room.usernames && room.usernames.length > 2)) ?? false;
@ -89,63 +85,6 @@ export function hasRole(role): boolean {
return userRoles.indexOf(role) > -1; return userRoles.indexOf(role) > -1;
} }
// AsyncStorage
export async function getAllowCrashReport() {
const allowCrashReport = await AsyncStorage.getItem(CRASH_REPORT_KEY);
if (allowCrashReport === null) {
return true;
}
return JSON.parse(allowCrashReport);
}
export async function getAllowAnalyticsEvents() {
const allowAnalyticsEvents = await AsyncStorage.getItem(ANALYTICS_EVENTS_KEY);
if (allowAnalyticsEvents === null) {
return true;
}
return JSON.parse(allowAnalyticsEvents);
}
// TODO: remove this
export async function subscribeRooms(this: any) {
if (!this.roomsSub) {
try {
// TODO: We need to change this naming. Maybe move this logic to the SDK?
this.roomsSub = await subscribeRoomsTmp.call(this);
} catch (e) {
log(e);
}
}
}
// TODO: remove this
export function unsubscribeRooms(this: any) {
if (this.roomsSub) {
this.roomsSub.stop();
this.roomsSub = null;
}
}
export function parseSettings(settings) {
return settings.reduce((ret, item) => {
ret[item._id] = defaultSettings[item._id] && item[defaultSettings[item._id].type];
if (item._id === 'Hide_System_Messages') {
ret[item._id] = ret[item._id].reduce(
(array, value) => [...array, ...(value === 'mute_unmute' ? ['user-muted', 'user-unmuted'] : [value])],
[]
);
}
return ret;
});
}
export function _prepareSettings(settings) {
return settings.map(setting => {
setting[defaultSettings[setting._id].type] = setting.value;
return setting;
});
}
export async function hasPermission(permissions, rid?: any) { export async function hasPermission(permissions, rid?: any) {
let roomRoles = []; let roomRoles = [];
if (rid) { if (rid) {

36
app/lib/methods/index.ts Normal file
View File

@ -0,0 +1,36 @@
export * from './actions';
export * from './callJitsi';
export * from './canOpenRoom';
export * from './clearCache';
export * from './enterpriseModules';
export * from './getCustomEmojis';
export * from './getPermalinks';
export * from './getPermissions';
export * from './getRoles';
// export * from './getRoom'; only used inside methods folder
export * from './getRoomInfo';
export * from './getRooms';
export * from './getSettings';
export * from './getSingleMessage';
export * from './getSlashCommands';
export * from './getThreadName';
export * from './getUsersPresence';
export * from './helpers';
export * from './loadMessagesForRoom';
export * from './loadMissedMessages';
export * from './loadNextMessages';
export * from './loadSurroundingMessages';
export * from './loadThreadMessages';
export * from './logout';
export * from './readMessages';
export * from './roomTypeToApiType';
export * from './search';
export * from './sendFileMessage';
export * from './sendMessage';
export * from './setUser';
export * from './triggerActions';
export * from './updateMessages';
export * from './userPreferences';
export * from './userPreferencesMethods';
export * from './crashReport';
export * from './parseSettings';

View File

@ -4,7 +4,7 @@ import { MessageTypeLoad } from '../constants';
import { IMessage, TMessageModel } from '../../definitions'; import { IMessage, TMessageModel } from '../../definitions';
import log from '../../utils/log'; import log from '../../utils/log';
import { getMessageById } from '../database/services/Message'; import { getMessageById } from '../database/services/Message';
import roomTypeToApiType, { RoomTypes } from './roomTypeToApiType'; import { RoomTypes, roomTypeToApiType } from './roomTypeToApiType';
import sdk from '../services/sdk'; import sdk from '../services/sdk';
import updateMessages from './updateMessages'; import updateMessages from './updateMessages';
import { generateLoadMoreId } from './helpers/generateLoadMoreId'; import { generateLoadMoreId } from './helpers/generateLoadMoreId';
@ -30,7 +30,7 @@ async function load({ rid: roomId, latest, t }: { rid: string; latest?: Date; t:
return data.messages; return data.messages;
} }
export default function loadMessagesForRoom(args: { export function loadMessagesForRoom(args: {
rid: string; rid: string;
t: RoomTypes; t: RoomTypes;
latest?: Date; latest?: Date;

View File

@ -29,7 +29,7 @@ async function load({ rid: roomId, lastOpen }: { rid: string; lastOpen?: Date })
return result; return result;
} }
export default function loadMissedMessages(args: { rid: string; lastOpen?: Date }): Promise<void> { export function loadMissedMessages(args: { rid: string; lastOpen?: Date }): Promise<void> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const data = await load({ rid: args.rid, lastOpen: args.lastOpen }); const data = await load({ rid: args.rid, lastOpen: args.lastOpen });

View File

@ -19,7 +19,7 @@ interface ILoadNextMessages {
loaderItem: TMessageModel; loaderItem: TMessageModel;
} }
export default function loadNextMessages(args: ILoadNextMessages): Promise<void> { export function loadNextMessages(args: ILoadNextMessages): Promise<void> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const data = await sdk.methodCallWrapper('loadNextMessages', args.rid, args.ts, COUNT); const data = await sdk.methodCallWrapper('loadNextMessages', args.rid, args.ts, COUNT);

View File

@ -12,7 +12,7 @@ import { generateLoadMoreId } from './helpers/generateLoadMoreId';
const COUNT = 50; const COUNT = 50;
export default function loadSurroundingMessages({ messageId, rid }: { messageId: string; rid: string }) { export function loadSurroundingMessages({ messageId, rid }: { messageId: string; rid: string }) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const data = await sdk.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, COUNT); const data = await sdk.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, COUNT);

View File

@ -24,7 +24,7 @@ async function load({ tmid }: { tmid: string }) {
} }
} }
export default function loadThreadMessages({ tmid, rid }: { tmid: string; rid: string }) { export function loadThreadMessages({ tmid, rid }: { tmid: string; rid: string }) {
return new Promise<void>(async (resolve, reject) => { return new Promise<void>(async (resolve, reject) => {
try { try {
let data = await load({ tmid }); let data = await load({ tmid });

View File

@ -10,14 +10,14 @@ import { isSsl } from '../../utils/url';
import log from '../../utils/log'; import log from '../../utils/log';
import { ICertificate, IRocketChat } from '../../definitions'; import { ICertificate, IRocketChat } from '../../definitions';
import sdk from '../services/sdk'; import sdk from '../services/sdk';
import { E2E_PRIVATE_KEY, E2E_PUBLIC_KEY, E2E_RANDOM_PASSWORD_KEY } from '../constants'; import { CURRENT_SERVER, E2E_PRIVATE_KEY, E2E_PUBLIC_KEY, E2E_RANDOM_PASSWORD_KEY, TOKEN_KEY } from '../constants';
import UserPreferences from './userPreferences'; import UserPreferences from './userPreferences';
import RocketChat from '../rocketchat'; import { Services } from '../services';
function removeServerKeys({ server, userId }: { server: string; userId?: string | null }) { function removeServerKeys({ server, userId }: { server: string; userId?: string | null }) {
UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${server}`); UserPreferences.removeItem(`${TOKEN_KEY}-${server}`);
if (userId) { if (userId) {
UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${userId}`); UserPreferences.removeItem(`${TOKEN_KEY}-${userId}`);
} }
UserPreferences.removeItem(`${BASIC_AUTH_KEY}-${server}`); UserPreferences.removeItem(`${BASIC_AUTH_KEY}-${server}`);
UserPreferences.removeItem(`${server}-${E2E_PUBLIC_KEY}`); UserPreferences.removeItem(`${server}-${E2E_PUBLIC_KEY}`);
@ -42,7 +42,7 @@ async function removeServerData({ server }: { server: string }) {
try { try {
const batch: Model[] = []; const batch: Model[] = [];
const serversDB = database.servers; const serversDB = database.servers;
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`); const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
const usersCollection = serversDB.get('users'); const usersCollection = serversDB.get('users');
if (userId) { if (userId) {
@ -62,7 +62,7 @@ async function removeServerData({ server }: { server: string }) {
} }
function removeCurrentServer() { function removeCurrentServer() {
UserPreferences.removeItem(RocketChat.CURRENT_SERVER); UserPreferences.removeItem(CURRENT_SERVER);
} }
async function removeServerDatabase({ server }: { server: string }) { async function removeServerDatabase({ server }: { server: string }) {
@ -76,9 +76,9 @@ async function removeServerDatabase({ server }: { server: string }) {
export async function removeServer({ server }: { server: string }): Promise<void> { export async function removeServer({ server }: { server: string }): Promise<void> {
try { try {
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`); const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
if (userId) { if (userId) {
const resume = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${userId}`); const resume = UserPreferences.getString(`${TOKEN_KEY}-${userId}`);
const sdk = new RocketchatClient({ host: server, protocol: 'ddp', useSsl: isSsl(server) }); const sdk = new RocketchatClient({ host: server, protocol: 'ddp', useSsl: isSsl(server) });
await sdk.login({ resume }); await sdk.login({ resume });
@ -110,7 +110,7 @@ export async function logout(this: IRocketChat, { server }: { server: string }):
} }
try { try {
await this.removePushToken(); await Services.removePushToken();
} catch (e) { } catch (e) {
log(e); log(e);
} }

View File

@ -0,0 +1,23 @@
import { defaultSettings } from '../constants';
export function parseSettings(settings: any) {
return settings.reduce((ret: any, item: any) => {
// @ts-ignore
ret[item._id] = defaultSettings[item._id] && item[defaultSettings[item._id].type];
if (item._id === 'Hide_System_Messages') {
ret[item._id] = ret[item._id].reduce(
(array: any, value: any) => [...array, ...(value === 'mute_unmute' ? ['user-muted', 'user-unmuted'] : [value])],
[]
);
}
return ret;
});
}
export function _prepareSettings(settings: any) {
return settings.map((setting: any) => {
// @ts-ignore
setting[defaultSettings[setting._id].type] = setting.value;
return setting;
});
}

View File

@ -3,7 +3,7 @@ import log from '../../utils/log';
import { TSubscriptionModel } from '../../definitions'; import { TSubscriptionModel } from '../../definitions';
import sdk from '../services/sdk'; import sdk from '../services/sdk';
export default async function readMessages(rid: string, ls: Date, updateLastOpen = false): Promise<void> { export async function readMessages(rid: string, ls: Date, updateLastOpen = false): Promise<void> {
try { try {
const db = database.active; const db = database.active;
const subscription = await db.get('subscriptions').find(rid); const subscription = await db.get('subscriptions').find(rid);

View File

@ -23,6 +23,4 @@ export const types: { [K in RoomTypes]: ApiTypes<K> } = {
l: ETypes.Channels l: ETypes.Channels
}; };
const roomTypeToApiType = <T extends RoomTypes>(t: T) => types[t]; export const roomTypeToApiType = <T extends RoomTypes>(t: T) => types[t];
export default roomTypeToApiType;

View File

@ -47,7 +47,7 @@ const changeMessageStatus = async (id: string, status: number, tmid?: string, me
} }
}; };
export async function sendMessageCall(message: any) { async function sendMessageCall(message: any) {
const { _id, tmid } = message; const { _id, tmid } = message;
try { try {
// RC 0.60.0 // RC 0.60.0

View File

@ -4,18 +4,21 @@ import { shareSetSettings, shareSelectServer, shareSetUser } from '../../actions
import SSLPinning from '../../utils/sslPinning'; import SSLPinning from '../../utils/sslPinning';
import log from '../../utils/log'; import log from '../../utils/log';
import { IShareServer, IShareUser } from '../../reducers/share'; import { IShareServer, IShareUser } from '../../reducers/share';
import UserPreferences from '../methods/userPreferences'; import UserPreferences from './userPreferences';
import database from '../database'; import database from '../database';
import RocketChat from '../rocketchat';
import { encryptionInit } from '../../actions/encryption'; import { encryptionInit } from '../../actions/encryption';
import { store } from '../store/auxStore'; import { store } from '../store/auxStore';
import sdk from './sdk'; import sdk from '../services/sdk';
import { CERTIFICATE_KEY, TOKEN_KEY } from '../constants';
import { setCustomEmojis } from './getCustomEmojis';
import { Services } from '../services';
import { parseSettings } from './parseSettings';
export async function shareExtensionInit(server: string) { export async function shareExtensionInit(server: string) {
database.setShareDB(server); database.setShareDB(server);
try { try {
const certificate = UserPreferences.getString(`${RocketChat.CERTIFICATE_KEY}-${server}`); const certificate = UserPreferences.getString(`${CERTIFICATE_KEY}-${server}`);
if (SSLPinning && certificate) { if (SSLPinning && certificate) {
await SSLPinning.setCertificate(certificate, server); await SSLPinning.setCertificate(certificate, server);
} }
@ -41,7 +44,7 @@ export async function shareExtensionInit(server: string) {
} }
store.dispatch(shareSelectServer(currentServer)); store.dispatch(shareSelectServer(currentServer));
RocketChat.setCustomEmojis(); setCustomEmojis();
try { try {
// set Settings // set Settings
@ -57,10 +60,10 @@ export async function shareExtensionInit(server: string) {
valueAsArray: item.valueAsArray, valueAsArray: item.valueAsArray,
_updatedAt: item._updatedAt _updatedAt: item._updatedAt
})); }));
store.dispatch(shareSetSettings(RocketChat.parseSettings(parsed))); store.dispatch(shareSetSettings(parseSettings(parsed)));
// set User info // set User info
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`); const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
const userCollections = serversDB.get('users'); const userCollections = serversDB.get('users');
let user = null; let user = null;
if (userId) { if (userId) {
@ -74,7 +77,7 @@ export async function shareExtensionInit(server: string) {
} }
store.dispatch(shareSetUser(user as IShareUser)); store.dispatch(shareSetUser(user as IShareUser));
if (user) { if (user) {
await RocketChat.login({ resume: user.token }); await Services.login({ resume: user.token });
} }
store.dispatch(encryptionInit()); store.dispatch(encryptionInit());
} catch (e) { } catch (e) {

View File

@ -0,0 +1,22 @@
import log from '../../utils/log';
import subscribeRoomsTmp from './subscriptions/rooms';
// TODO: remove this
export async function subscribeRooms(this: any) {
if (!this.roomsSub) {
try {
// TODO: We need to change this naming. Maybe move this logic to the SDK?
this.roomsSub = await subscribeRoomsTmp.call(this);
} catch (e) {
log(e);
}
}
}
// TODO: remove this
export function unsubscribeRooms(this: any) {
if (this.roomsSub) {
this.roomsSub.stop();
this.roomsSub = null;
}
}

View File

@ -12,12 +12,13 @@ import { getThreadMessageById } from '../../database/services/ThreadMessage';
import { store as reduxStore } from '../../store/auxStore'; import { store as reduxStore } from '../../store/auxStore';
import { addUserTyping, clearUserTyping, removeUserTyping } from '../../../actions/usersTyping'; import { addUserTyping, clearUserTyping, removeUserTyping } from '../../../actions/usersTyping';
import debounce from '../../../utils/debounce'; import debounce from '../../../utils/debounce';
import RocketChat from '../../rocketchat';
import { subscribeRoom, unsubscribeRoom } from '../../../actions/room'; import { subscribeRoom, unsubscribeRoom } from '../../../actions/room';
import { Encryption } from '../../encryption'; import { Encryption } from '../../encryption';
import { IMessage, TMessageModel, TSubscriptionModel, TThreadMessageModel, TThreadModel } from '../../../definitions'; import { IMessage, TMessageModel, TSubscriptionModel, TThreadMessageModel, TThreadModel } from '../../../definitions';
import { IDDPMessage } from '../../../definitions/IDDPMessage'; import { IDDPMessage } from '../../../definitions/IDDPMessage';
import sdk from '../../services/sdk'; import sdk from '../../services/sdk';
import { readMessages } from '../readMessages';
import { loadMissedMessages } from '../loadMissedMessages';
const WINDOW_TIME = 1000; const WINDOW_TIME = 1000;
@ -107,7 +108,7 @@ export default class RoomSubscription {
handleConnection = async () => { handleConnection = async () => {
try { try {
reduxStore.dispatch(clearUserTyping()); reduxStore.dispatch(clearUserTyping());
await RocketChat.loadMissedMessages({ rid: this.rid }); await loadMissedMessages({ rid: this.rid });
const _lastOpen = new Date(); const _lastOpen = new Date();
this.read(_lastOpen); this.read(_lastOpen);
this.lastOpen = _lastOpen; this.lastOpen = _lastOpen;
@ -185,7 +186,7 @@ export default class RoomSubscription {
}); });
read = debounce((lastOpen: Date) => { read = debounce((lastOpen: Date) => {
RocketChat.readMessages(this.rid, lastOpen); readMessages(this.rid, lastOpen);
}, 300); }, 300);
updateMessage = (message: IMessage): Promise<void> => updateMessage = (message: IMessage): Promise<void> =>

View File

@ -11,7 +11,6 @@ import random from '../../../utils/random';
import { store } from '../../store/auxStore'; import { store } from '../../store/auxStore';
import { handlePayloadUserInteraction } from '../actions'; import { handlePayloadUserInteraction } from '../actions';
import buildMessage from '../helpers/buildMessage'; import buildMessage from '../helpers/buildMessage';
import RocketChat from '../../rocketchat';
import EventEmitter from '../../../utils/events'; import EventEmitter from '../../../utils/events';
import { removedRoom } from '../../../actions/room'; import { removedRoom } from '../../../actions/room';
import { setUser } from '../../../actions/login'; import { setUser } from '../../../actions/login';
@ -34,6 +33,8 @@ import { IDDPMessage } from '../../../definitions/IDDPMessage';
import { getSubscriptionByRoomId } from '../../database/services/Subscription'; import { getSubscriptionByRoomId } from '../../database/services/Subscription';
import { getMessageById } from '../../database/services/Message'; import { getMessageById } from '../../database/services/Message';
import { E2E_MESSAGE_TYPE } from '../../constants'; import { E2E_MESSAGE_TYPE } from '../../constants';
import { getRoom } from '../getRoom';
import { getRoomAvatar, getRoomTitle, getSenderName } from '../helpers';
const removeListener = (listener: { stop: () => void }) => listener.stop(); const removeListener = (listener: { stop: () => void }) => listener.stop();
@ -358,9 +359,9 @@ export default function subscribeRooms() {
const { const {
payload: { rid, message, sender } payload: { rid, message, sender }
} = notification; } = notification;
const room = await RocketChat.getRoom(rid); const room = await getRoom(rid);
notification.title = RocketChat.getRoomTitle(room); notification.title = getRoomTitle(room);
notification.avatar = RocketChat.getRoomAvatar(room); notification.avatar = getRoomAvatar(room);
// If it's from a encrypted room // If it's from a encrypted room
if (message?.t === E2E_MESSAGE_TYPE) { if (message?.t === E2E_MESSAGE_TYPE) {
@ -371,7 +372,7 @@ export default function subscribeRooms() {
notification.text = msg; notification.text = msg;
// If it's a private group we should add the sender name // If it's a private group we should add the sender name
} else { } else {
notification.text = `${RocketChat.getSenderName(sender)}: ${msg}`; notification.text = `${getSenderName(sender)}: ${msg}`;
} }
} }
} catch (e) { } catch (e) {

View File

@ -5,21 +5,20 @@ import {
ITriggerSubmitView, ITriggerSubmitView,
ModalActions ModalActions
} from '../../containers/UIKit/interfaces'; } from '../../containers/UIKit/interfaces';
import { TRocketChat } from '../../definitions';
import Navigation from '../navigation/appNavigation'; import Navigation from '../navigation/appNavigation';
import { triggerAction } from './actions'; import { triggerAction } from './actions';
export function triggerBlockAction(this: TRocketChat, options: ITriggerBlockAction) { export async function triggerSubmitView({ viewId, ...options }: ITriggerSubmitView) {
return triggerAction.call(this, { type: ActionTypes.ACTION, ...options }); const result = await triggerAction({ type: ActionTypes.SUBMIT, viewId, ...options });
}
export async function triggerSubmitView(this: TRocketChat, { viewId, ...options }: ITriggerSubmitView) {
const result = await triggerAction.call(this, { type: ActionTypes.SUBMIT, viewId, ...options });
if (!result || ModalActions.CLOSE === result) { if (!result || ModalActions.CLOSE === result) {
Navigation.back(); Navigation.back();
} }
} }
export function triggerCancel(this: TRocketChat, { view, ...options }: ITriggerCancel) { export function triggerCancel({ view, ...options }: ITriggerCancel) {
return triggerAction.call(this, { type: ActionTypes.CLOSED, view, ...options }); return triggerAction({ type: ActionTypes.CLOSED, view, ...options });
}
export function triggerBlockAction(options: ITriggerBlockAction) {
return triggerAction({ type: ActionTypes.ACTION, ...options });
} }

View File

@ -1,77 +1,16 @@
// Methods import { _setUser } from './methods/setUser';
import canOpenRoom from './methods/canOpenRoom'; import { logout } from './methods/logout';
import clearCache from './methods/clearCache'; import { subscribeRooms, unsubscribeRooms } from './methods/subscribeRooms';
import getRoom from './methods/getRoom'; import { subscribeUsersPresence } from './methods/getUsersPresence';
import getRooms from './methods/getRooms'; import { connect } from './services/connect';
import getSlashCommands from './methods/getSlashCommands';
import loadMessagesForRoom from './methods/loadMessagesForRoom';
import loadMissedMessages from './methods/loadMissedMessages';
import loadNextMessages from './methods/loadNextMessages';
import loadSurroundingMessages from './methods/loadSurroundingMessages';
import loadThreadMessages from './methods/loadThreadMessages';
import readMessages from './methods/readMessages';
import roomTypeToApiType from './methods/roomTypeToApiType';
// Spread Methods
import * as sendMessage from './methods/sendMessage';
import * as callJitsi from './methods/callJitsi';
import * as enterpriseModules from './methods/enterpriseModules';
import * as getCustomEmojis from './methods/getCustomEmojis';
import * as getPermalinks from './methods/getPermalinks';
import * as getPermissions from './methods/getPermissions';
import * as getRoles from './methods/getRoles';
import * as getSettings from './methods/getSettings';
import * as getUsersPresence from './methods/getUsersPresence';
import * as helpers from './methods/helpers';
import * as logout from './methods/logout';
import * as search from './methods/search';
import * as sendFileMessage from './methods/sendFileMessage';
import * as setUser from './methods/setUser';
import * as triggerActions from './methods/triggerActions';
import * as userPreferencesMethods from './methods/userPreferencesMethods';
import * as connect from './services/connect';
import * as restApis from './services/restApi';
import * as shareExtension from './services/shareExtension';
const TOKEN_KEY = 'reactnativemeteor_usertoken';
const CURRENT_SERVER = 'currentServer';
const CERTIFICATE_KEY = 'RC_CERTIFICATE_KEY';
const RocketChat = { const RocketChat = {
TOKEN_KEY, logout,
CURRENT_SERVER, subscribeRooms,
CERTIFICATE_KEY, unsubscribeRooms,
...restApis, _setUser,
...search, subscribeUsersPresence,
...getPermalinks, connect
...connect,
...enterpriseModules,
...sendMessage,
...shareExtension,
...sendFileMessage,
...logout,
...getUsersPresence,
...getSettings,
...getRoles,
...getPermissions,
...triggerActions,
...callJitsi,
...getCustomEmojis,
...helpers,
...userPreferencesMethods,
...setUser,
canOpenRoom,
clearCache,
loadMissedMessages,
loadMessagesForRoom,
loadSurroundingMessages,
loadNextMessages,
loadThreadMessages,
getRooms,
readMessages,
getSlashCommands,
getRoom,
roomTypeToApiType
}; };
export default RocketChat; export default RocketChat;

View File

@ -24,6 +24,7 @@ import { updateSettings } from '../../actions/settings';
import { defaultSettings, MIN_ROCKETCHAT_VERSION } from '../constants'; import { defaultSettings, MIN_ROCKETCHAT_VERSION } from '../constants';
import { compareServerVersion } from '../methods/helpers/compareServerVersion'; import { compareServerVersion } from '../methods/helpers/compareServerVersion';
import { onRolesChanged } from '../methods/getRoles'; import { onRolesChanged } from '../methods/getRoles';
import { getSettings } from '../methods';
interface IServices { interface IServices {
[index: string]: string | boolean; [index: string]: string | boolean;
@ -85,7 +86,7 @@ function connect(
EventEmitter.emit('INQUIRY_UNSUBSCRIBE'); EventEmitter.emit('INQUIRY_UNSUBSCRIBE');
sdk.initialize(server); sdk.initialize(server);
this.getSettings(); getSettings();
sdk.current sdk.current
.connect() .connect()

View File

@ -0,0 +1,7 @@
import * as connect from './connect';
import * as restApi from './restApi';
export const Services = {
...connect,
...restApi
};

View File

@ -5,8 +5,7 @@ import {
IRoom, IRoom,
IRoomNotifications, IRoomNotifications,
SubscriptionType, SubscriptionType,
IUser, IUser
TRocketChat
} from '../../definitions'; } from '../../definitions';
import { IAvatarSuggestion, IParams } from '../../definitions/IProfileViewInterfaces'; import { IAvatarSuggestion, IParams } from '../../definitions/IProfileViewInterfaces';
import { ISpotlight } from '../../definitions/ISpotlight'; import { ISpotlight } from '../../definitions/ISpotlight';
@ -16,9 +15,10 @@ import { TParams } from '../../definitions/ILivechatEditView';
import { store as reduxStore } from '../store/auxStore'; import { store as reduxStore } from '../store/auxStore';
import { getDeviceToken } from '../notifications'; import { getDeviceToken } from '../notifications';
import { getBundleId, isIOS } from '../../utils/deviceInfo'; import { getBundleId, isIOS } from '../../utils/deviceInfo';
import roomTypeToApiType, { RoomTypes } from '../methods/roomTypeToApiType'; import { RoomTypes, roomTypeToApiType } from '../methods';
import sdk from './sdk'; import sdk from './sdk';
import { compareServerVersion } from '../methods/helpers/compareServerVersion'; import { compareServerVersion } from '../methods/helpers/compareServerVersion';
import RocketChat from '../rocketchat';
export const createChannel = ({ export const createChannel = ({
name, name,
@ -801,10 +801,9 @@ export const emitTyping = (room: IRoom, typing = true) => {
return sdk.methodCall('stream-notify-room', `${room}/typing`, name, typing); return sdk.methodCall('stream-notify-room', `${room}/typing`, name, typing);
}; };
export function e2eResetOwnKey(this: TRocketChat): Promise<boolean | {}> { export function e2eResetOwnKey(): Promise<boolean | {}> {
// {} when TOTP is enabled // {} when TOTP is enabled
// TODO: remove this RocketChat.unsubscribeRooms();
this.unsubscribeRooms();
// RC 0.72.0 // RC 0.72.0
return sdk.methodCallWrapper('e2e.resetOwnE2EKey'); return sdk.methodCallWrapper('e2e.resetOwnE2EKey');

View File

@ -4,24 +4,12 @@ import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { CREATE_CHANNEL, LOGIN } from '../actions/actionsTypes'; import { CREATE_CHANNEL, LOGIN } from '../actions/actionsTypes';
import { createChannelFailure, createChannelSuccess } from '../actions/createChannel'; import { createChannelFailure, createChannelSuccess } from '../actions/createChannel';
import { showErrorAlert } from '../utils/info'; import { showErrorAlert } from '../utils/info';
import RocketChat from '../lib/rocketchat';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import database from '../lib/database'; import database from '../lib/database';
import I18n from '../i18n'; import I18n from '../i18n';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
import { goRoom } from '../utils/goRoom'; import { goRoom } from '../utils/goRoom';
import { Services } from '../lib/services';
const createChannel = function createChannel(data) {
return RocketChat.createChannel(data);
};
const createGroupChat = function createGroupChat() {
return RocketChat.createGroupChat();
};
const createTeam = function createTeam(data) {
return RocketChat.createTeam(data);
};
const handleRequest = function* handleRequest({ data }) { const handleRequest = function* handleRequest({ data }) {
try { try {
@ -39,7 +27,7 @@ const handleRequest = function* handleRequest({ data }) {
broadcast: `${broadcast}`, broadcast: `${broadcast}`,
encrypted: `${encrypted}` encrypted: `${encrypted}`
}); });
const result = yield call(createTeam, data); const result = yield Services.createTeam(data);
sub = { sub = {
rid: result?.team?.roomId, rid: result?.team?.roomId,
...result.team, ...result.team,
@ -47,7 +35,7 @@ const handleRequest = function* handleRequest({ data }) {
}; };
} else if (data.group) { } else if (data.group) {
logEvent(events.SELECTED_USERS_CREATE_GROUP); logEvent(events.SELECTED_USERS_CREATE_GROUP);
const result = yield call(createGroupChat); const result = yield Services.createGroupChat();
if (result.success) { if (result.success) {
sub = { sub = {
rid: result.room?._id, rid: result.room?._id,
@ -62,7 +50,7 @@ const handleRequest = function* handleRequest({ data }) {
broadcast, broadcast,
encrypted encrypted
}); });
const result = yield call(createChannel, data); const result = yield Services.createChannel(data);
sub = { sub = {
rid: result?.channel?._id || result?.group?._id, rid: result?.channel?._id || result?.group?._id,
...result?.channel, ...result?.channel,

View File

@ -3,13 +3,9 @@ import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { CREATE_DISCUSSION, LOGIN } from '../actions/actionsTypes'; import { CREATE_DISCUSSION, LOGIN } from '../actions/actionsTypes';
import { createDiscussionFailure, createDiscussionSuccess } from '../actions/createDiscussion'; import { createDiscussionFailure, createDiscussionSuccess } from '../actions/createDiscussion';
import RocketChat from '../lib/rocketchat';
import database from '../lib/database'; import database from '../lib/database';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
import { Services } from '../lib/services';
const create = function* create(data) {
return yield RocketChat.createDiscussion(data);
};
const handleRequest = function* handleRequest({ data }) { const handleRequest = function* handleRequest({ data }) {
logEvent(events.CD_CREATE); logEvent(events.CD_CREATE);
@ -18,7 +14,7 @@ const handleRequest = function* handleRequest({ data }) {
if (!auth) { if (!auth) {
yield take(LOGIN.SUCCESS); yield take(LOGIN.SUCCESS);
} }
const result = yield call(create, data); const result = yield Services.createDiscussion(data);
if (result.success) { if (result.success) {
const { discussion: sub } = result; const { discussion: sub } = result;

View File

@ -6,7 +6,6 @@ import * as types from '../actions/actionsTypes';
import { selectServerRequest, serverInitAdd } from '../actions/server'; import { selectServerRequest, serverInitAdd } from '../actions/server';
import { inviteLinksRequest, inviteLinksSetToken } from '../actions/inviteLinks'; import { inviteLinksRequest, inviteLinksSetToken } from '../actions/inviteLinks';
import database from '../lib/database'; import database from '../lib/database';
import RocketChat from '../lib/rocketchat';
import EventEmitter from '../utils/events'; import EventEmitter from '../utils/events';
import { appInit, appStart } from '../actions/app'; import { appInit, appStart } from '../actions/app';
import { localAuthenticate } from '../utils/localAuthentication'; import { localAuthenticate } from '../utils/localAuthentication';
@ -14,6 +13,9 @@ import { goRoom } from '../utils/goRoom';
import { loginRequest } from '../actions/login'; import { loginRequest } from '../actions/login';
import log from '../utils/log'; import log from '../utils/log';
import { RootEnum } from '../definitions'; import { RootEnum } from '../definitions';
import { CURRENT_SERVER, TOKEN_KEY } from '../lib/constants';
import { callJitsi, callJitsiWithoutServer, canOpenRoom, getUidDirectMessage } from '../lib/methods';
import { Services } from '../lib/services';
const roomTypes = { const roomTypes = {
channel: 'c', channel: 'c',
@ -52,12 +54,12 @@ const navigate = function* navigate({ params }) {
[type, name, , jumpToThreadId] = params.path.split('/'); [type, name, , jumpToThreadId] = params.path.split('/');
} }
if (type !== 'invite' || params.rid) { if (type !== 'invite' || params.rid) {
const room = yield RocketChat.canOpenRoom(params); const room = yield canOpenRoom(params);
if (room) { if (room) {
const item = { const item = {
name, name,
t: roomTypes[type], t: roomTypes[type],
roomUserId: RocketChat.getUidDirectMessage(room), roomUserId: getUidDirectMessage(room),
...room ...room
}; };
@ -84,7 +86,7 @@ const navigate = function* navigate({ params }) {
} }
if (params.isCall) { if (params.isCall) {
RocketChat.callJitsi(item); callJitsi(item);
} }
} }
} else { } else {
@ -104,7 +106,7 @@ const fallbackNavigation = function* fallbackNavigation() {
const handleOAuth = function* handleOAuth({ params }) { const handleOAuth = function* handleOAuth({ params }) {
const { credentialToken, credentialSecret } = params; const { credentialToken, credentialSecret } = params;
try { try {
yield RocketChat.loginOAuthOrSso({ oauth: { credentialToken, credentialSecret } }, false); yield Services.loginOAuthOrSso({ oauth: { credentialToken, credentialSecret } }, false);
} catch (e) { } catch (e) {
log(e); log(e);
} }
@ -125,7 +127,7 @@ const handleOpen = function* handleOpen({ params }) {
}); });
if (!host && params.fullURL) { if (!host && params.fullURL) {
RocketChat.callJitsiWithoutServer(params.fullURL); callJitsiWithoutServer(params.fullURL);
return; return;
} }
} }
@ -158,8 +160,8 @@ const handleOpen = function* handleOpen({ params }) {
} }
const [server, user] = yield all([ const [server, user] = yield all([
UserPreferences.getString(RocketChat.CURRENT_SERVER), UserPreferences.getString(CURRENT_SERVER),
UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${host}`) UserPreferences.getString(`${TOKEN_KEY}-${host}`)
]); ]);
// TODO: needs better test // TODO: needs better test
@ -187,7 +189,7 @@ const handleOpen = function* handleOpen({ params }) {
// do nothing? // do nothing?
} }
// if deep link is from a different server // if deep link is from a different server
const result = yield RocketChat.getServerInfo(host); const result = yield Services.getServerInfo(host);
if (!result.success) { if (!result.success) {
// Fallback to prevent the app from being stuck on splash screen // Fallback to prevent the app from being stuck on splash screen
yield fallbackNavigation(); yield fallbackNavigation();

View File

@ -6,13 +6,13 @@ import { encryptionSet } from '../actions/encryption';
import { Encryption } from '../lib/encryption'; import { Encryption } from '../lib/encryption';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import database from '../lib/database'; import database from '../lib/database';
import RocketChat from '../lib/rocketchat';
import UserPreferences from '../lib/methods/userPreferences'; import UserPreferences from '../lib/methods/userPreferences';
import { getUserSelector } from '../selectors/login'; import { getUserSelector } from '../selectors/login';
import { showErrorAlert } from '../utils/info'; import { showErrorAlert } from '../utils/info';
import I18n from '../i18n'; import I18n from '../i18n';
import log from '../utils/log'; import log from '../utils/log';
import { E2E_BANNER_TYPE, E2E_PRIVATE_KEY, E2E_PUBLIC_KEY, E2E_RANDOM_PASSWORD_KEY } from '../lib/constants'; import { E2E_BANNER_TYPE, E2E_PRIVATE_KEY, E2E_PUBLIC_KEY, E2E_RANDOM_PASSWORD_KEY } from '../lib/constants';
import { Services } from '../lib/services';
const getServer = state => state.share.server.server || state.server.server; const getServer = state => state.share.server.server || state.server.server;
const getE2eEnable = state => state.settings.E2E_Enable; const getE2eEnable = state => state.settings.E2E_Enable;
@ -42,7 +42,7 @@ const handleEncryptionInit = function* handleEncryptionInit() {
const storedPrivateKey = UserPreferences.getString(`${server}-${E2E_PRIVATE_KEY}`); const storedPrivateKey = UserPreferences.getString(`${server}-${E2E_PRIVATE_KEY}`);
// Fetch server stored e2e keys // Fetch server stored e2e keys
const keys = yield RocketChat.e2eFetchMyKeys(); const keys = yield Services.e2eFetchMyKeys();
// A private key was received from the server, but it's not saved locally yet // A private key was received from the server, but it's not saved locally yet
// Show the banner asking for the password // Show the banner asking for the password
@ -96,7 +96,7 @@ const handleEncryptionDecodeKey = function* handleEncryptionDecodeKey({ password
const user = yield select(getUserSelector); const user = yield select(getUserSelector);
// Fetch server stored e2e keys // Fetch server stored e2e keys
const keys = yield RocketChat.e2eFetchMyKeys(); const keys = yield Services.e2eFetchMyKeys();
const publicKey = EJSON.parse(keys?.publicKey); const publicKey = EJSON.parse(keys?.publicKey);

View File

@ -1,20 +1,20 @@
import { put, takeLatest } from 'redux-saga/effects'; import { put, takeLatest } from 'redux-saga/effects';
import RNBootSplash from 'react-native-bootsplash'; import RNBootSplash from 'react-native-bootsplash';
import { BIOMETRY_ENABLED_KEY } from '../lib/constants'; import { BIOMETRY_ENABLED_KEY, CURRENT_SERVER, TOKEN_KEY } from '../lib/constants';
import UserPreferences from '../lib/methods/userPreferences'; import UserPreferences from '../lib/methods/userPreferences';
import { selectServerRequest } from '../actions/server'; import { selectServerRequest } from '../actions/server';
import { setAllPreferences } from '../actions/sortPreferences'; import { setAllPreferences } from '../actions/sortPreferences';
import { APP } from '../actions/actionsTypes'; import { APP } from '../actions/actionsTypes';
import RocketChat from '../lib/rocketchat';
import log from '../utils/log'; import log from '../utils/log';
import database from '../lib/database'; import database from '../lib/database';
import { localAuthenticate } from '../utils/localAuthentication'; import { localAuthenticate } from '../utils/localAuthentication';
import { appReady, appStart } from '../actions/app'; import { appReady, appStart } from '../actions/app';
import { RootEnum } from '../definitions'; import { RootEnum } from '../definitions';
import { getSortPreferences } from '../lib/methods';
export const initLocalSettings = function* initLocalSettings() { export const initLocalSettings = function* initLocalSettings() {
const sortPreferences = RocketChat.getSortPreferences(); const sortPreferences = getSortPreferences();
yield put(setAllPreferences(sortPreferences)); yield put(setAllPreferences(sortPreferences));
}; };
@ -22,8 +22,8 @@ const BIOMETRY_MIGRATION_KEY = 'kBiometryMigration';
const restore = function* restore() { const restore = function* restore() {
try { try {
const server = UserPreferences.getString(RocketChat.CURRENT_SERVER); const server = UserPreferences.getString(CURRENT_SERVER);
let userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`); let userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
// Migration biometry setting from WatermelonDB to MMKV // Migration biometry setting from WatermelonDB to MMKV
// TODO: remove it after a few versions // TODO: remove it after a few versions
@ -48,7 +48,7 @@ const restore = function* restore() {
if (servers.length > 0) { if (servers.length > 0) {
for (let i = 0; i < servers.length; i += 1) { for (let i = 0; i < servers.length; i += 1) {
const newServer = servers[i].id; const newServer = servers[i].id;
userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${newServer}`); userId = UserPreferences.getString(`${TOKEN_KEY}-${newServer}`);
if (userId) { if (userId) {
return yield put(selectServerRequest(newServer)); return yield put(selectServerRequest(newServer));
} }

View File

@ -3,20 +3,21 @@ import { Alert } from 'react-native';
import { INVITE_LINKS } from '../actions/actionsTypes'; import { INVITE_LINKS } from '../actions/actionsTypes';
import { inviteLinksFailure, inviteLinksSetInvite, inviteLinksSuccess } from '../actions/inviteLinks'; import { inviteLinksFailure, inviteLinksSetInvite, inviteLinksSuccess } from '../actions/inviteLinks';
import RocketChat from '../lib/rocketchat';
import log from '../utils/log'; import log from '../utils/log';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import I18n from '../i18n'; import I18n from '../i18n';
import { getRoomTitle } from '../lib/methods';
import { Services } from '../lib/services';
const handleRequest = function* handleRequest({ token }) { const handleRequest = function* handleRequest({ token }) {
try { try {
const validateResult = yield RocketChat.validateInviteToken(token); const validateResult = yield Services.validateInviteToken(token);
if (!validateResult.valid) { if (!validateResult.valid) {
yield put(inviteLinksFailure()); yield put(inviteLinksFailure());
return; return;
} }
const result = yield RocketChat.inviteToken(token); const result = yield Services.inviteToken(token);
if (!result.success) { if (!result.success) {
yield put(inviteLinksFailure()); yield put(inviteLinksFailure());
return; return;
@ -28,7 +29,7 @@ const handleRequest = function* handleRequest({ token }) {
const { room } = result; const { room } = result;
Navigation.navigate('RoomView', { Navigation.navigate('RoomView', {
rid: room.rid, rid: room.rid,
name: RocketChat.getRoomTitle(room), name: getRoomTitle(room),
t: room.t t: room.t
}); });
} }
@ -47,7 +48,7 @@ const handleFailure = function handleFailure() {
const handleCreateInviteLink = function* handleCreateInviteLink({ rid }) { const handleCreateInviteLink = function* handleCreateInviteLink({ rid }) {
try { try {
const inviteLinks = yield select(state => state.inviteLinks); const inviteLinks = yield select(state => state.inviteLinks);
const result = yield RocketChat.findOrCreateInvite({ const result = yield Services.findOrCreateInvite({
rid, rid,
days: inviteLinks.days, days: inviteLinks.days,
maxUses: inviteLinks.maxUses maxUses: inviteLinks.maxUses

View File

@ -5,7 +5,7 @@ import { Q } from '@nozbe/watermelondb';
import * as types from '../actions/actionsTypes'; import * as types from '../actions/actionsTypes';
import { appStart } from '../actions/app'; import { appStart } from '../actions/app';
import { selectServerRequest, serverFinishAdd } from '../actions/server'; import { selectServerRequest, serverFinishAdd } from '../actions/server';
import { loginFailure, loginSuccess, logout, setUser } from '../actions/login'; import { loginFailure, loginSuccess, logout as logoutAction, setUser } from '../actions/login';
import { roomsRequest } from '../actions/rooms'; import { roomsRequest } from '../actions/rooms';
import RocketChat from '../lib/rocketchat'; import RocketChat from '../lib/rocketchat';
import log, { events, logEvent } from '../utils/log'; import log, { events, logEvent } from '../utils/log';
@ -21,10 +21,22 @@ import { inquiryRequest, inquiryReset } from '../ee/omnichannel/actions/inquiry'
import { isOmnichannelStatusAvailable } from '../ee/omnichannel/lib'; import { isOmnichannelStatusAvailable } from '../ee/omnichannel/lib';
import { RootEnum } from '../definitions'; import { RootEnum } from '../definitions';
import sdk from '../lib/services/sdk'; import sdk from '../lib/services/sdk';
import { TOKEN_KEY } from '../lib/constants';
import {
getCustomEmojis,
getEnterpriseModules,
getPermissions,
getRoles,
getSlashCommands,
getUserPresence,
isOmnichannelModuleAvailable,
subscribeSettings
} from '../lib/methods';
import { Services } from '../lib/services';
const getServer = state => state.server.server; const getServer = state => state.server.server;
const loginWithPasswordCall = args => RocketChat.loginWithPassword(args); const loginWithPasswordCall = args => Services.loginWithPassword(args);
const loginCall = (credentials, isFromWebView) => RocketChat.login(credentials, isFromWebView); const loginCall = (credentials, isFromWebView) => Services.login(credentials, isFromWebView);
const logoutCall = args => RocketChat.logout(args); const logoutCall = args => RocketChat.logout(args);
const handleLoginRequest = function* handleLoginRequest({ credentials, logoutOnError = false, isFromWebView = false }) { const handleLoginRequest = function* handleLoginRequest({ credentials, logoutOnError = false, isFromWebView = false }) {
@ -66,9 +78,9 @@ const handleLoginRequest = function* handleLoginRequest({ credentials, logoutOnE
} }
} catch (e) { } catch (e) {
if (e?.data?.message && /you've been logged out by the server/i.test(e.data.message)) { if (e?.data?.message && /you've been logged out by the server/i.test(e.data.message)) {
yield put(logout(true, 'Logged_out_by_server')); yield put(logoutAction(true, 'Logged_out_by_server'));
} else if (e?.data?.message && /your session has expired/i.test(e.data.message)) { } else if (e?.data?.message && /your session has expired/i.test(e.data.message)) {
yield put(logout(true, 'Token_expired')); yield put(logoutAction(true, 'Token_expired'));
} else { } else {
logEvent(events.LOGIN_DEFAULT_LOGIN_F); logEvent(events.LOGIN_DEFAULT_LOGIN_F);
yield put(loginFailure(e)); yield put(loginFailure(e));
@ -76,61 +88,61 @@ const handleLoginRequest = function* handleLoginRequest({ credentials, logoutOnE
} }
}; };
const subscribeSettings = function* subscribeSettings() { const subscribeSettingsFork = function* subscribeSettingsFork() {
yield RocketChat.subscribeSettings(); yield subscribeSettings();
}; };
const fetchPermissions = function* fetchPermissions() { const fetchPermissionsFork = function* fetchPermissionsFork() {
yield RocketChat.getPermissions(); yield getPermissions();
}; };
const fetchCustomEmojis = function* fetchCustomEmojis() { const fetchCustomEmojisFork = function* fetchCustomEmojisFork() {
yield RocketChat.getCustomEmojis(); yield getCustomEmojis();
}; };
const fetchRoles = function* fetchRoles() { const fetchRolesFork = function* fetchRolesFork() {
sdk.subscribe('stream-roles', 'roles'); sdk.subscribe('stream-roles', 'roles');
yield RocketChat.getRoles(); yield getRoles();
}; };
const fetchSlashCommands = function* fetchSlashCommands() { const fetchSlashCommandsFork = function* fetchSlashCommandsFork() {
yield RocketChat.getSlashCommands(); yield getSlashCommands();
}; };
const registerPushToken = function* registerPushToken() { const registerPushTokenFork = function* registerPushTokenFork() {
yield RocketChat.registerPushToken(); yield Services.registerPushToken();
}; };
const fetchUsersPresence = function* fetchUserPresence() { const fetchUsersPresenceFork = function* fetchUsersPresenceFork() {
RocketChat.subscribeUsersPresence(); RocketChat.subscribeUsersPresence();
}; };
const fetchEnterpriseModules = function* fetchEnterpriseModules({ user }) { const fetchEnterpriseModulesFork = function* fetchEnterpriseModulesFork({ user }) {
yield RocketChat.getEnterpriseModules(); yield getEnterpriseModules();
if (isOmnichannelStatusAvailable(user) && RocketChat.isOmnichannelModuleAvailable()) { if (isOmnichannelStatusAvailable(user) && isOmnichannelModuleAvailable()) {
yield put(inquiryRequest()); yield put(inquiryRequest());
} }
}; };
const fetchRooms = function* fetchRooms() { const fetchRoomsFork = function* fetchRoomsFork() {
yield put(roomsRequest()); yield put(roomsRequest());
}; };
const handleLoginSuccess = function* handleLoginSuccess({ user }) { const handleLoginSuccess = function* handleLoginSuccess({ user }) {
try { try {
RocketChat.getUserPresence(user.id); getUserPresence(user.id);
const server = yield select(getServer); const server = yield select(getServer);
yield fork(fetchRooms); yield fork(fetchRoomsFork);
yield fork(fetchPermissions); yield fork(fetchPermissionsFork);
yield fork(fetchCustomEmojis); yield fork(fetchCustomEmojisFork);
yield fork(fetchRoles); yield fork(fetchRolesFork);
yield fork(fetchSlashCommands); yield fork(fetchSlashCommandsFork);
yield fork(registerPushToken); yield fork(registerPushTokenFork);
yield fork(fetchUsersPresence); yield fork(fetchUsersPresenceFork);
yield fork(fetchEnterpriseModules, { user }); yield fork(fetchEnterpriseModulesFork, { user });
yield fork(subscribeSettings); yield fork(subscribeSettingsFork);
yield put(encryptionInit()); yield put(encryptionInit());
setLanguage(user?.language); setLanguage(user?.language);
@ -164,8 +176,8 @@ const handleLoginSuccess = function* handleLoginSuccess({ user }) {
} }
}); });
UserPreferences.setString(`${RocketChat.TOKEN_KEY}-${server}`, user.id); UserPreferences.setString(`${TOKEN_KEY}-${server}`, user.id);
UserPreferences.setString(`${RocketChat.TOKEN_KEY}-${user.id}`, user.token); UserPreferences.setString(`${TOKEN_KEY}-${user.id}`, user.token);
yield put(setUser(user)); yield put(setUser(user));
EventEmitter.emit('connected'); EventEmitter.emit('connected');
@ -205,7 +217,7 @@ const handleLogout = function* handleLogout({ forcedByServer, message }) {
if (servers.length > 0) { if (servers.length > 0) {
for (let i = 0; i < servers.length; i += 1) { for (let i = 0; i < servers.length; i += 1) {
const newServer = servers[i].id; const newServer = servers[i].id;
const token = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${newServer}`); const token = UserPreferences.getString(`${TOKEN_KEY}-${newServer}`);
if (token) { if (token) {
yield put(selectServerRequest(newServer)); yield put(selectServerRequest(newServer));
return; return;
@ -225,7 +237,7 @@ const handleLogout = function* handleLogout({ forcedByServer, message }) {
const handleSetUser = function* handleSetUser({ user }) { const handleSetUser = function* handleSetUser({ user }) {
setLanguage(user?.language); setLanguage(user?.language);
if (user?.statusLivechat && RocketChat.isOmnichannelModuleAvailable()) { if (user?.statusLivechat && isOmnichannelModuleAvailable()) {
if (isOmnichannelStatusAvailable(user)) { if (isOmnichannelStatusAvailable(user)) {
yield put(inquiryRequest()); yield put(inquiryRequest());
} else { } else {

View File

@ -3,10 +3,10 @@ import { Q } from '@nozbe/watermelondb';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import { MESSAGES } from '../actions/actionsTypes'; import { MESSAGES } from '../actions/actionsTypes';
import RocketChat from '../lib/rocketchat';
import database from '../lib/database'; import database from '../lib/database';
import log from '../utils/log'; import log from '../utils/log';
import { goRoom } from '../utils/goRoom'; import { goRoom } from '../utils/goRoom';
import { Services } from '../lib/services';
const handleReplyBroadcast = function* handleReplyBroadcast({ message }) { const handleReplyBroadcast = function* handleReplyBroadcast({ message }) {
try { try {
@ -25,7 +25,7 @@ const handleReplyBroadcast = function* handleReplyBroadcast({ message }) {
if (subscriptions.length) { if (subscriptions.length) {
goRoom({ item: subscriptions[0], isMasterDetail, message }); goRoom({ item: subscriptions[0], isMasterDetail, message });
} else { } else {
const result = yield RocketChat.createDirectMessage(username); const result = yield Services.createDirectMessage(username);
if (result?.success) { if (result?.success) {
goRoom({ item: result?.room, isMasterDetail, message }); goRoom({ item: result?.room, isMasterDetail, message });
} }

View File

@ -6,11 +6,11 @@ import EventEmitter from '../utils/events';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import * as types from '../actions/actionsTypes'; import * as types from '../actions/actionsTypes';
import { removedRoom } from '../actions/room'; import { removedRoom } from '../actions/room';
import RocketChat from '../lib/rocketchat';
import log, { events, logEvent } from '../utils/log'; import log, { events, logEvent } from '../utils/log';
import I18n from '../i18n'; import I18n from '../i18n';
import { showErrorAlert } from '../utils/info'; import { showErrorAlert } from '../utils/info';
import { LISTENER } from '../containers/Toast'; import { LISTENER } from '../containers/Toast';
import { Services } from '../lib/services';
const watchUserTyping = function* watchUserTyping({ rid, status }) { const watchUserTyping = function* watchUserTyping({ rid, status }) {
const auth = yield select(state => state.login.isAuthenticated); const auth = yield select(state => state.login.isAuthenticated);
@ -19,11 +19,11 @@ const watchUserTyping = function* watchUserTyping({ rid, status }) {
} }
try { try {
yield RocketChat.emitTyping(rid, status); yield Services.emitTyping(rid, status);
if (status) { if (status) {
yield delay(5000); yield delay(5000);
yield RocketChat.emitTyping(rid, false); yield Services.emitTyping(rid, false);
} }
} catch (e) { } catch (e) {
log(e); log(e);
@ -65,9 +65,9 @@ const handleLeaveRoom = function* handleLeaveRoom({ room, roomType, selected })
let result = {}; let result = {};
if (roomType === 'channel') { if (roomType === 'channel') {
result = yield RocketChat.leaveRoom(room.rid, room.t); result = yield Services.leaveRoom(room.rid, room.t);
} else if (roomType === 'team') { } else if (roomType === 'team') {
result = yield RocketChat.leaveTeam({ teamId: room.teamId, ...(selected && { rooms: selected }) }); result = yield Services.leaveTeam({ teamId: room.teamId, ...(selected && { rooms: selected }) });
} }
if (result?.success) { if (result?.success) {
@ -91,9 +91,9 @@ const handleDeleteRoom = function* handleDeleteRoom({ room, roomType, selected }
let result = {}; let result = {};
if (roomType === 'channel') { if (roomType === 'channel') {
result = yield RocketChat.deleteRoom(room.rid, room.t); result = yield Services.deleteRoom(room.rid, room.t);
} else if (roomType === 'team') { } else if (roomType === 'team') {
result = yield RocketChat.deleteTeam({ teamId: room.teamId, ...(selected && { roomsToRemove: selected }) }); result = yield Services.deleteTeam({ teamId: room.teamId, ...(selected && { roomsToRemove: selected }) });
} }
if (result?.success) { if (result?.success) {
@ -116,7 +116,7 @@ const handleCloseRoom = function* handleCloseRoom({ rid }) {
const closeRoom = async (comment = '') => { const closeRoom = async (comment = '') => {
try { try {
await RocketChat.closeLivechat(rid, comment); await Services.closeLivechat(rid, comment);
if (isMasterDetail) { if (isMasterDetail) {
Navigation.navigate('DrawerNavigator'); Navigation.navigate('DrawerNavigator');
} else { } else {
@ -150,7 +150,7 @@ const handleCloseRoom = function* handleCloseRoom({ rid }) {
const handleForwardRoom = function* handleForwardRoom({ transferData }) { const handleForwardRoom = function* handleForwardRoom({ transferData }) {
try { try {
const result = yield RocketChat.forwardLivechat(transferData); const result = yield Services.forwardLivechat(transferData);
if (result === true) { if (result === true) {
const isMasterDetail = yield select(state => state.app.isMasterDetail); const isMasterDetail = yield select(state => state.app.isMasterDetail);
if (isMasterDetail) { if (isMasterDetail) {

View File

@ -9,6 +9,7 @@ import log from '../utils/log';
import mergeSubscriptionsRooms from '../lib/methods/helpers/mergeSubscriptionsRooms'; import mergeSubscriptionsRooms from '../lib/methods/helpers/mergeSubscriptionsRooms';
import RocketChat from '../lib/rocketchat'; import RocketChat from '../lib/rocketchat';
import buildMessage from '../lib/methods/helpers/buildMessage'; import buildMessage from '../lib/methods/helpers/buildMessage';
import { getRooms } from '../lib/methods';
const updateRooms = function* updateRooms({ server, newRoomsUpdatedAt }) { const updateRooms = function* updateRooms({ server, newRoomsUpdatedAt }) {
const serversDB = database.servers; const serversDB = database.servers;
@ -45,7 +46,7 @@ const handleRoomsRequest = function* handleRoomsRequest({ params }) {
} }
} }
const [subscriptionsResult, roomsResult] = yield RocketChat.getRooms(roomsUpdatedAt); const [subscriptionsResult, roomsResult] = yield getRooms(roomsUpdatedAt);
const subscriptions = yield mergeSubscriptionsRooms(subscriptionsResult, roomsResult); const subscriptions = yield mergeSubscriptionsRooms(subscriptionsResult, roomsResult);
const db = database.active; const db = database.active;
const subCollection = db.get('subscriptions'); const subCollection = db.get('subscriptions');

View File

@ -22,13 +22,16 @@ import { encryptionStop } from '../actions/encryption';
import SSLPinning from '../utils/sslPinning'; import SSLPinning from '../utils/sslPinning';
import { inquiryReset } from '../ee/omnichannel/actions/inquiry'; import { inquiryReset } from '../ee/omnichannel/actions/inquiry';
import { RootEnum } from '../definitions'; import { RootEnum } from '../definitions';
import { CERTIFICATE_KEY, CURRENT_SERVER, TOKEN_KEY } from '../lib/constants';
import { getLoginSettings, setCustomEmojis, setEnterpriseModules, setPermissions, setRoles, setSettings } from '../lib/methods';
import { Services } from '../lib/services';
const getServerInfo = function* getServerInfo({ server, raiseError = true }) { const getServerInfo = function* getServerInfo({ server, raiseError = true }) {
try { try {
const serverInfo = yield RocketChat.getServerInfo(server); const serverInfo = yield Services.getServerInfo(server);
let websocketInfo = { success: true }; let websocketInfo = { success: true };
if (raiseError) { if (raiseError) {
websocketInfo = yield RocketChat.getWebsocketInfo({ server }); websocketInfo = yield Services.getWebsocketInfo({ server });
} }
if (!serverInfo.success || !websocketInfo.success) { if (!serverInfo.success || !websocketInfo.success) {
if (raiseError) { if (raiseError) {
@ -69,14 +72,14 @@ const getServerInfo = function* getServerInfo({ server, raiseError = true }) {
const handleSelectServer = function* handleSelectServer({ server, version, fetchVersion }) { const handleSelectServer = function* handleSelectServer({ server, version, fetchVersion }) {
try { try {
// SSL Pinning - Read certificate alias and set it to be used by network requests // SSL Pinning - Read certificate alias and set it to be used by network requests
const certificate = UserPreferences.getString(`${RocketChat.CERTIFICATE_KEY}-${server}`); const certificate = UserPreferences.getString(`${CERTIFICATE_KEY}-${server}`);
SSLPinning.setCertificate(certificate, server); SSLPinning.setCertificate(certificate, server);
yield put(inquiryReset()); yield put(inquiryReset());
yield put(encryptionStop()); yield put(encryptionStop());
yield put(clearActiveUsers()); yield put(clearActiveUsers());
const serversDB = database.servers; const serversDB = database.servers;
UserPreferences.setString(RocketChat.CURRENT_SERVER, server); UserPreferences.setString(CURRENT_SERVER, server);
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`); const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
const userCollections = serversDB.get('users'); const userCollections = serversDB.get('users');
let user = null; let user = null;
if (userId) { if (userId) {
@ -96,7 +99,7 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
}; };
} catch { } catch {
// search credentials on shared credentials (Experimental/Official) // search credentials on shared credentials (Experimental/Official)
const token = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${userId}`); const token = UserPreferences.getString(`${TOKEN_KEY}-${userId}`);
if (token) { if (token) {
user = { token }; user = { token };
} }
@ -107,7 +110,7 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
setBasicAuth(basicAuth); setBasicAuth(basicAuth);
// Check for running requests and abort them before connecting to the server // Check for running requests and abort them before connecting to the server
RocketChat.abort(); Services.abort();
if (user) { if (user) {
yield put(clearSettings()); yield put(clearSettings());
@ -122,11 +125,11 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
// We can't use yield here because fetch of Settings & Custom Emojis is slower // We can't use yield here because fetch of Settings & Custom Emojis is slower
// and block the selectServerSuccess raising multiples errors // and block the selectServerSuccess raising multiples errors
RocketChat.setSettings(); setSettings();
RocketChat.setCustomEmojis(); setCustomEmojis();
RocketChat.setPermissions(); setPermissions();
RocketChat.setRoles(); setRoles();
RocketChat.setEnterpriseModules(); setEnterpriseModules();
let serverInfo; let serverInfo;
if (fetchVersion) { if (fetchVersion) {
@ -148,7 +151,7 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
const handleServerRequest = function* handleServerRequest({ server, username, fromServerHistory }) { const handleServerRequest = function* handleServerRequest({ server, username, fromServerHistory }) {
try { try {
// SSL Pinning - Read certificate alias and set it to be used by network requests // SSL Pinning - Read certificate alias and set it to be used by network requests
const certificate = UserPreferences.getString(`${RocketChat.CERTIFICATE_KEY}-${server}`); const certificate = UserPreferences.getString(`${CERTIFICATE_KEY}-${server}`);
SSLPinning.setCertificate(certificate, server); SSLPinning.setCertificate(certificate, server);
const serverInfo = yield getServerInfo({ server }); const serverInfo = yield getServerInfo({ server });
@ -156,8 +159,8 @@ const handleServerRequest = function* handleServerRequest({ server, username, fr
const serversHistoryCollection = serversDB.get('servers_history'); const serversHistoryCollection = serversDB.get('servers_history');
if (serverInfo) { if (serverInfo) {
yield RocketChat.getLoginServices(server); yield Services.getLoginServices(server);
yield RocketChat.getLoginSettings({ server }); yield getLoginSettings({ server });
Navigation.navigate('WorkspaceView'); Navigation.navigate('WorkspaceView');
if (fromServerHistory) { if (fromServerHistory) {

View File

@ -1,11 +1,11 @@
import { select, takeLatest } from 'redux-saga/effects'; import { select, takeLatest } from 'redux-saga/effects';
import RocketChat from '../lib/rocketchat';
import Push from '../lib/notifications/push'; import Push from '../lib/notifications/push';
import log from '../utils/log'; import log from '../utils/log';
import { localAuthenticate, saveLastLocalAuthenticationSession } from '../utils/localAuthentication'; import { localAuthenticate, saveLastLocalAuthenticationSession } from '../utils/localAuthentication';
import { APP_STATE } from '../actions/actionsTypes'; import { APP_STATE } from '../actions/actionsTypes';
import { RootEnum } from '../definitions'; import { RootEnum } from '../definitions';
import { Services } from '../lib/services';
const appHasComeBackToForeground = function* appHasComeBackToForeground() { const appHasComeBackToForeground = function* appHasComeBackToForeground() {
const appRoot = yield select(state => state.app.root); const appRoot = yield select(state => state.app.root);
@ -19,9 +19,9 @@ const appHasComeBackToForeground = function* appHasComeBackToForeground() {
} }
try { try {
yield localAuthenticate(server.server); yield localAuthenticate(server.server);
RocketChat.checkAndReopen(); Services.checkAndReopen();
Push.setBadgeCount(); Push.setBadgeCount();
return yield RocketChat.setUserPresenceOnline(); return yield Services.setUserPresenceOnline();
} catch (e) { } catch (e) {
log(e); log(e);
} }
@ -36,7 +36,7 @@ const appHasComeBackToBackground = function* appHasComeBackToBackground() {
const server = yield select(state => state.server.server); const server = yield select(state => state.server.server);
yield saveLastLocalAuthenticationSession(server); yield saveLastLocalAuthenticationSession(server);
yield RocketChat.setUserPresenceAway(); yield Services.setUserPresenceAway();
} catch (e) { } catch (e) {
log(e); log(e);
} }

View File

@ -10,9 +10,8 @@ import UserPreferences from './lib/methods/userPreferences';
import Navigation from './lib/navigation/shareNavigation'; import Navigation from './lib/navigation/shareNavigation';
import store from './lib/store'; import store from './lib/store';
import { initStore } from './lib/store/auxStore'; import { initStore } from './lib/store/auxStore';
import { closeShareExtension, shareExtensionInit } from './lib/services/shareExtension'; import { closeShareExtension, shareExtensionInit } from './lib/methods/shareExtension';
import { defaultHeader, getActiveRouteName, navigationTheme, themedHeader } from './utils/navigation'; import { defaultHeader, getActiveRouteName, navigationTheme, themedHeader } from './utils/navigation';
import RocketChat from './lib/rocketchat';
import { ThemeContext, TSupportedThemes } from './theme'; import { ThemeContext, TSupportedThemes } from './theme';
import { localAuthenticate } from './utils/localAuthentication'; import { localAuthenticate } from './utils/localAuthentication';
import { IThemePreference } from './definitions/ITheme'; import { IThemePreference } from './definitions/ITheme';
@ -28,7 +27,7 @@ import AuthLoadingView from './views/AuthLoadingView';
import { DimensionsContext } from './dimensions'; import { DimensionsContext } from './dimensions';
import debounce from './utils/debounce'; import debounce from './utils/debounce';
import { ShareInsideStackParamList, ShareOutsideStackParamList, ShareAppStackParamList } from './definitions/navigationTypes'; import { ShareInsideStackParamList, ShareOutsideStackParamList, ShareAppStackParamList } from './definitions/navigationTypes';
import { colors } from './lib/constants'; import { colors, CURRENT_SERVER } from './lib/constants';
initStore(store); initStore(store);
@ -114,7 +113,7 @@ class Root extends React.Component<{}, IState> {
} }
init = async () => { init = async () => {
const currentServer = UserPreferences.getString(RocketChat.CURRENT_SERVER); const currentServer = UserPreferences.getString(CURRENT_SERVER);
if (currentServer) { if (currentServer) {
await localAuthenticate(currentServer); await localAuthenticate(currentServer);

View File

@ -48,6 +48,7 @@ export default (url: string, options: IOptions = {}): Promise<Response> => {
} }
// TODO: Refactor when migrate rocketchat.js // TODO: Refactor when migrate rocketchat.js
// @ts-ignore // @ts-ignore
// WHAT?
if (RocketChat.controller) { if (RocketChat.controller) {
// @ts-ignore // @ts-ignore
const { signal } = RocketChat.controller; const { signal } = RocketChat.controller;

View File

@ -1,7 +1,8 @@
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import RocketChat from '../lib/rocketchat';
import { IOmnichannelRoom, SubscriptionType, IVisitor, TSubscriptionModel, ISubscription } from '../definitions'; import { IOmnichannelRoom, SubscriptionType, IVisitor, TSubscriptionModel, ISubscription } from '../definitions';
import { getRoomTitle, getUidDirectMessage } from '../lib/methods';
import { Services } from '../lib/services';
interface IGoRoomItem { interface IGoRoomItem {
search?: boolean; // comes from spotlight search?: boolean; // comes from spotlight
@ -32,12 +33,12 @@ const navigate = ({
navigationMethod('RoomView', { navigationMethod('RoomView', {
rid: item.rid, rid: item.rid,
name: RocketChat.getRoomTitle(item), name: getRoomTitle(item),
t: item.t, t: item.t,
prid: item.prid, prid: item.prid,
room: item, room: item,
visitor: item.visitor, visitor: item.visitor,
roomUserId: RocketChat.getUidDirectMessage(item), roomUserId: getUidDirectMessage(item),
...props ...props
}); });
}; };
@ -62,7 +63,7 @@ export const goRoom = async ({
// if user is using the search we need first to join/create room // if user is using the search we need first to join/create room
try { try {
const { username } = item; const { username } = item;
const result = await RocketChat.createDirectMessage(username as string); const result = await Services.createDirectMessage(username as string);
if (result.success && result?.room?._id) { if (result.success && result?.room?._id) {
return navigate({ return navigate({
item: { item: {

View File

@ -1,11 +1,11 @@
import RocketChat from '../lib/rocketchat';
import { store as reduxStore } from '../lib/store/auxStore'; import { store as reduxStore } from '../lib/store/auxStore';
import { ISubscription } from '../definitions/ISubscription'; import { ISubscription } from '../definitions/ISubscription';
import { hasPermission } from '../lib/methods';
const canPostReadOnly = async ({ rid }: { rid: string }) => { const canPostReadOnly = async ({ rid }: { rid: string }) => {
// TODO: this is not reactive. If this permission changes, the component won't be updated // TODO: this is not reactive. If this permission changes, the component won't be updated
const postReadOnlyPermission = reduxStore.getState().permissions['post-readonly']; const postReadOnlyPermission = reduxStore.getState().permissions['post-readonly'];
const permission = await RocketChat.hasPermission([postReadOnlyPermission], rid); const permission = await hasPermission([postReadOnlyPermission], rid);
return permission[0]; return permission[0];
}; };

View File

@ -7,7 +7,6 @@ import { Q } from '@nozbe/watermelondb';
import * as List from '../containers/List'; import * as List from '../containers/List';
import database from '../lib/database'; import database from '../lib/database';
import RocketChat from '../lib/rocketchat';
import I18n from '../i18n'; import I18n from '../i18n';
import log, { events, logEvent } from '../utils/log'; import log, { events, logEvent } from '../utils/log';
import SearchBox from '../containers/SearchBox'; import SearchBox from '../containers/SearchBox';
@ -23,6 +22,8 @@ import { showErrorAlert } from '../utils/info';
import debounce from '../utils/debounce'; import debounce from '../utils/debounce';
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
import { TSubscriptionModel, SubscriptionType } from '../definitions'; import { TSubscriptionModel, SubscriptionType } from '../definitions';
import { getRoomTitle, hasPermission } from '../lib/methods';
import { Services } from '../lib/services';
interface IAddExistingChannelViewState { interface IAddExistingChannelViewState {
search: TSubscriptionModel[]; search: TSubscriptionModel[];
@ -100,7 +101,7 @@ class AddExistingChannelView extends React.Component<IAddExistingChannelViewProp
if (channel.prid) { if (channel.prid) {
return false; return false;
} }
const permissions = await RocketChat.hasPermission([addTeamChannelPermission], channel.rid); const permissions = await hasPermission([addTeamChannelPermission], channel.rid);
if (!permissions[0]) { if (!permissions[0]) {
return false; return false;
} }
@ -133,7 +134,7 @@ class AddExistingChannelView extends React.Component<IAddExistingChannelViewProp
this.setState({ loading: true }); this.setState({ loading: true });
try { try {
logEvent(events.CT_ADD_ROOM_TO_TEAM); logEvent(events.CT_ADD_ROOM_TO_TEAM);
const result = await RocketChat.addRoomsToTeam({ rooms: selected, teamId: this.teamId }); const result = await Services.addRoomsToTeam({ rooms: selected, teamId: this.teamId });
if (result.success) { if (result.success) {
this.setState({ loading: false }); this.setState({ loading: false });
// @ts-ignore // @ts-ignore
@ -181,7 +182,7 @@ class AddExistingChannelView extends React.Component<IAddExistingChannelViewProp
const icon = item.t === SubscriptionType.DIRECT && !item?.teamId ? 'channel-private' : 'channel-public'; const icon = item.t === SubscriptionType.DIRECT && !item?.teamId ? 'channel-private' : 'channel-public';
return ( return (
<List.Item <List.Item
title={RocketChat.getRoomTitle(item)} title={getRoomTitle(item)}
translateTitle={false} translateTitle={false}
onPress={() => this.toggleChannel(item.rid)} onPress={() => this.toggleChannel(item.rid)}
testID={`add-existing-channel-view-item-${item.name}`} testID={`add-existing-channel-view-item-${item.name}`}

View File

@ -7,13 +7,13 @@ import { WebViewMessage } from 'react-native-webview/lib/WebViewTypes';
import { RouteProp } from '@react-navigation/core'; import { RouteProp } from '@react-navigation/core';
import { OutsideModalParamList } from '../stacks/types'; import { OutsideModalParamList } from '../stacks/types';
import RocketChat from '../lib/rocketchat';
import { isIOS } from '../utils/deviceInfo'; import { isIOS } from '../utils/deviceInfo';
import StatusBar from '../containers/StatusBar'; import StatusBar from '../containers/StatusBar';
import ActivityIndicator from '../containers/ActivityIndicator'; import ActivityIndicator from '../containers/ActivityIndicator';
import { TSupportedThemes, withTheme } from '../theme'; import { TSupportedThemes, withTheme } from '../theme';
import debounce from '../utils/debounce'; import debounce from '../utils/debounce';
import * as HeaderButton from '../containers/HeaderButton'; import * as HeaderButton from '../containers/HeaderButton';
import { Services } from '../lib/services';
const userAgent = isIOS const userAgent = isIOS
? 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1' ? 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'
@ -102,7 +102,7 @@ class AuthenticationWebView extends React.PureComponent<IAuthenticationWebView,
this.setState({ logging: true }); this.setState({ logging: true });
try { try {
RocketChat.loginOAuthOrSso(params); Services.loginOAuthOrSso(params);
} catch (e) { } catch (e) {
console.warn(e); console.warn(e);
} }

View File

@ -3,7 +3,6 @@ import { FlatList, StyleSheet, Switch } from 'react-native';
import { RouteProp } from '@react-navigation/core'; import { RouteProp } from '@react-navigation/core';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import RocketChat from '../../lib/rocketchat';
import I18n from '../../i18n'; import I18n from '../../i18n';
import StatusBar from '../../containers/StatusBar'; import StatusBar from '../../containers/StatusBar';
import * as List from '../../containers/List'; import * as List from '../../containers/List';
@ -12,6 +11,7 @@ import { TSupportedThemes, withTheme } from '../../theme';
import SafeAreaView from '../../containers/SafeAreaView'; import SafeAreaView from '../../containers/SafeAreaView';
import { events, logEvent } from '../../utils/log'; import { events, logEvent } from '../../utils/log';
import { ISubscription } from '../../definitions/ISubscription'; import { ISubscription } from '../../definitions/ISubscription';
import { Services } from '../../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
list: { list: {
@ -64,7 +64,7 @@ class AutoTranslateView extends React.Component<IAutoTranslateViewProps, any> {
async componentDidMount() { async componentDidMount() {
this.mounted = true; this.mounted = true;
try { try {
const languages = await RocketChat.getSupportedLanguagesAutoTranslate(); const languages = await Services.getSupportedLanguagesAutoTranslate();
this.setState({ languages }); this.setState({ languages });
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@ -81,7 +81,7 @@ class AutoTranslateView extends React.Component<IAutoTranslateViewProps, any> {
logEvent(events.AT_TOGGLE_TRANSLATE); logEvent(events.AT_TOGGLE_TRANSLATE);
const { enableAutoTranslate } = this.state; const { enableAutoTranslate } = this.state;
try { try {
await RocketChat.saveAutoTranslate({ await Services.saveAutoTranslate({
rid: this.rid, rid: this.rid,
field: 'autoTranslate', field: 'autoTranslate',
value: enableAutoTranslate ? '0' : '1', value: enableAutoTranslate ? '0' : '1',
@ -97,7 +97,7 @@ class AutoTranslateView extends React.Component<IAutoTranslateViewProps, any> {
saveAutoTranslateLanguage = async (language: string) => { saveAutoTranslateLanguage = async (language: string) => {
logEvent(events.AT_SET_LANG); logEvent(events.AT_SET_LANG);
try { try {
await RocketChat.saveAutoTranslate({ await Services.saveAutoTranslate({
rid: this.rid, rid: this.rid,
field: 'autoTranslateLanguage', field: 'autoTranslateLanguage',
value: language value: language

View File

@ -9,7 +9,6 @@ import SafeAreaView from '../containers/SafeAreaView';
import StatusBar from '../containers/StatusBar'; import StatusBar from '../containers/StatusBar';
import Button from '../containers/Button'; import Button from '../containers/Button';
import { TSupportedThemes, useTheme } from '../theme'; import { TSupportedThemes, useTheme } from '../theme';
import RocketChat from '../lib/rocketchat';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import { goRoom } from '../utils/goRoom'; import { goRoom } from '../utils/goRoom';
import { themes } from '../lib/constants'; import { themes } from '../lib/constants';
@ -17,6 +16,7 @@ import Markdown from '../containers/markdown';
import { ICannedResponse } from '../definitions/ICannedResponse'; import { ICannedResponse } from '../definitions/ICannedResponse';
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { getRoomTitle, getUidDirectMessage } from '../lib/methods';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
scroll: { scroll: {
@ -111,12 +111,12 @@ const CannedResponseDetail = ({ navigation, route }: ICannedResponseDetailProps)
const { name } = room; const { name } = room;
const params = { const params = {
rid: room.rid, rid: room.rid,
name: RocketChat.getRoomTitle({ name: getRoomTitle({
t: room.t, t: room.t,
fname: name fname: name
}), }),
t: room.t as any, t: room.t as any,
roomUserId: RocketChat.getUidDirectMessage(room), roomUserId: getUidDirectMessage(room),
usedCannedResponse: item.text usedCannedResponse: item.text
}; };

View File

@ -14,7 +14,6 @@ import SearchHeader from '../../containers/SearchHeader';
import BackgroundContainer from '../../containers/BackgroundContainer'; import BackgroundContainer from '../../containers/BackgroundContainer';
import { getHeaderTitlePosition } from '../../containers/Header'; import { getHeaderTitlePosition } from '../../containers/Header';
import { useTheme } from '../../theme'; import { useTheme } from '../../theme';
import RocketChat from '../../lib/rocketchat';
import debounce from '../../utils/debounce'; import debounce from '../../utils/debounce';
import Navigation from '../../lib/navigation/appNavigation'; import Navigation from '../../lib/navigation/appNavigation';
import { goRoom } from '../../utils/goRoom'; import { goRoom } from '../../utils/goRoom';
@ -29,6 +28,8 @@ import styles from './styles';
import { ICannedResponse, IDepartment } from '../../definitions/ICannedResponse'; import { ICannedResponse, IDepartment } from '../../definitions/ICannedResponse';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import { ISubscription } from '../../definitions/ISubscription'; import { ISubscription } from '../../definitions/ISubscription';
import { getRoomTitle, getUidDirectMessage } from '../../lib/methods';
import { Services } from '../../lib/services';
const COUNT = 25; const COUNT = 25;
@ -91,7 +92,7 @@ const CannedResponsesListView = ({ navigation, route }: ICannedResponsesListView
const getDepartments = debounce(async () => { const getDepartments = debounce(async () => {
try { try {
const res: any = await RocketChat.getDepartments(); const res: any = await Services.getDepartments();
if (res.success) { if (res.success) {
setDepartments([...fixedScopes, ...res.departments]); setDepartments([...fixedScopes, ...res.departments]);
} }
@ -114,12 +115,12 @@ const CannedResponsesListView = ({ navigation, route }: ICannedResponsesListView
const { name } = room; const { name } = room;
const params = { const params = {
rid: room.rid, rid: room.rid,
name: RocketChat.getRoomTitle({ name: getRoomTitle({
t: room.t, t: room.t,
fname: name fname: name
}), }),
t: room.t as any, t: room.t as any,
roomUserId: RocketChat.getUidDirectMessage(room), roomUserId: getUidDirectMessage(room),
usedCannedResponse: item.text usedCannedResponse: item.text
}; };
@ -151,7 +152,7 @@ const CannedResponsesListView = ({ navigation, route }: ICannedResponsesListView
debounced: boolean; debounced: boolean;
}) => { }) => {
try { try {
const res = await RocketChat.getListCannedResponse({ const res = await Services.getListCannedResponse({
text, text,
offset, offset,
count: COUNT, count: COUNT,

View File

@ -20,10 +20,10 @@ import { Review } from '../utils/review';
import { getUserSelector } from '../selectors/login'; import { getUserSelector } from '../selectors/login';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
import SafeAreaView from '../containers/SafeAreaView'; import SafeAreaView from '../containers/SafeAreaView';
import RocketChat from '../lib/rocketchat';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
import { IApplicationState, IBaseScreen, IUser } from '../definitions'; import { IApplicationState, IBaseScreen, IUser } from '../definitions';
import { hasPermission } from '../lib/methods';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -255,7 +255,7 @@ class CreateChannelView extends React.Component<ICreateChannelViewProps, ICreate
handleHasPermission = async () => { handleHasPermission = async () => {
const { createPublicChannelPermission, createPrivateChannelPermission } = this.props; const { createPublicChannelPermission, createPrivateChannelPermission } = this.props;
const permissions = [createPublicChannelPermission, createPrivateChannelPermission]; const permissions = [createPublicChannelPermission, createPrivateChannelPermission];
const permissionsToCreate = await RocketChat.hasPermission(permissions); const permissionsToCreate = await hasPermission(permissions);
this.setState({ permissions: permissionsToCreate }); this.setState({ permissions: permissionsToCreate });
}; };

View File

@ -5,11 +5,11 @@ import { themes } from '../../lib/constants';
import { MultiSelect } from '../../containers/UIKit/MultiSelect'; import { MultiSelect } from '../../containers/UIKit/MultiSelect';
import { ISearchLocal } from '../../definitions'; import { ISearchLocal } from '../../definitions';
import I18n from '../../i18n'; import I18n from '../../i18n';
import RocketChat from '../../lib/rocketchat';
import { avatarURL } from '../../utils/avatar'; import { avatarURL } from '../../utils/avatar';
import debounce from '../../utils/debounce'; import debounce from '../../utils/debounce';
import { ICreateDiscussionViewSelectChannel } from './interfaces'; import { ICreateDiscussionViewSelectChannel } from './interfaces';
import styles from './styles'; import styles from './styles';
import { getRoomAvatar, getRoomTitle, localSearch } from '../../lib/methods';
const SelectChannel = ({ const SelectChannel = ({
server, server,
@ -25,7 +25,7 @@ const SelectChannel = ({
const getChannels = debounce(async (keyword = '') => { const getChannels = debounce(async (keyword = '') => {
try { try {
const res = await RocketChat.localSearch({ text: keyword }); const res = await localSearch({ text: keyword });
setChannels(res); setChannels(res);
} catch { } catch {
// do nothing // do nothing
@ -34,7 +34,7 @@ const SelectChannel = ({
const getAvatar = (item: any) => const getAvatar = (item: any) =>
avatarURL({ avatarURL({
text: RocketChat.getRoomAvatar(item), text: getRoomAvatar(item),
type: item.t, type: item.t,
user: { id: userId, token }, user: { id: userId, token },
server, server,
@ -55,7 +55,7 @@ const SelectChannel = ({
disabled={!!initial} disabled={!!initial}
options={channels.map(channel => ({ options={channels.map(channel => ({
value: channel, value: channel,
text: { text: RocketChat.getRoomTitle(channel) }, text: { text: getRoomTitle(channel) },
imageUrl: getAvatar(channel) imageUrl: getAvatar(channel)
}))} }))}
onClose={() => setChannels([])} onClose={() => setChannels([])}

View File

@ -4,13 +4,13 @@ import { BLOCK_CONTEXT } from '@rocket.chat/ui-kit';
import debounce from '../../utils/debounce'; import debounce from '../../utils/debounce';
import { avatarURL } from '../../utils/avatar'; import { avatarURL } from '../../utils/avatar';
import RocketChat from '../../lib/rocketchat';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { MultiSelect } from '../../containers/UIKit/MultiSelect'; import { MultiSelect } from '../../containers/UIKit/MultiSelect';
import { themes } from '../../lib/constants'; import { themes } from '../../lib/constants';
import styles from './styles'; import styles from './styles';
import { ICreateDiscussionViewSelectUsers } from './interfaces'; import { ICreateDiscussionViewSelectUsers } from './interfaces';
import { SubscriptionType } from '../../definitions/ISubscription'; import { SubscriptionType } from '../../definitions/ISubscription';
import { getRoomAvatar, getRoomTitle, search } from '../../lib/methods';
interface IUser { interface IUser {
name: string; name: string;
@ -31,7 +31,7 @@ const SelectUsers = ({
const getUsers = debounce(async (keyword = '') => { const getUsers = debounce(async (keyword = '') => {
try { try {
const res = await RocketChat.search({ text: keyword, filterRooms: false }); const res = await search({ text: keyword, filterRooms: false });
const selectedUsers = users.filter((u: IUser) => selected.includes(u.name)); const selectedUsers = users.filter((u: IUser) => selected.includes(u.name));
const filteredUsers = res.filter(r => !users.find((u: IUser) => u.name === r.name)); const filteredUsers = res.filter(r => !users.find((u: IUser) => u.name === r.name));
const items = [...selectedUsers, ...filteredUsers]; const items = [...selectedUsers, ...filteredUsers];
@ -43,7 +43,7 @@ const SelectUsers = ({
const getAvatar = (item: any) => const getAvatar = (item: any) =>
avatarURL({ avatarURL({
text: RocketChat.getRoomAvatar(item), text: getRoomAvatar(item),
type: SubscriptionType.DIRECT, type: SubscriptionType.DIRECT,
user: { id: userId, token }, user: { id: userId, token },
server, server,
@ -61,7 +61,7 @@ const SelectUsers = ({
onChange={onUserSelect} onChange={onUserSelect}
options={users.map((user: IUser) => ({ options={users.map((user: IUser) => ({
value: user.name, value: user.name,
text: { text: RocketChat.getRoomTitle(user) }, text: { text: getRoomTitle(user) },
imageUrl: getAvatar(user) imageUrl: getAvatar(user)
}))} }))}
onClose={() => setUsers(users.filter((u: IUser) => selected.includes(u.name)))} onClose={() => setUsers(users.filter((u: IUser) => selected.includes(u.name)))}

View File

@ -12,7 +12,6 @@ import StatusBar from '../../containers/StatusBar';
import { withTheme } from '../../theme'; import { withTheme } from '../../theme';
import { getUserSelector } from '../../selectors/login'; import { getUserSelector } from '../../selectors/login';
import TextInput from '../../containers/TextInput'; import TextInput from '../../containers/TextInput';
import RocketChat from '../../lib/rocketchat';
import Navigation from '../../lib/navigation/appNavigation'; import Navigation from '../../lib/navigation/appNavigation';
import { createDiscussionRequest } from '../../actions/createDiscussion'; import { createDiscussionRequest } from '../../actions/createDiscussion';
import { showErrorAlert } from '../../utils/info'; import { showErrorAlert } from '../../utils/info';
@ -25,6 +24,7 @@ import SelectChannel from './SelectChannel';
import { ICreateChannelViewProps, IResult, IError } from './interfaces'; import { ICreateChannelViewProps, IResult, IError } from './interfaces';
import { IApplicationState } from '../../definitions'; import { IApplicationState } from '../../definitions';
import { E2E_ROOM_TYPES, SWITCH_TRACK_COLOR, themes } from '../../lib/constants'; import { E2E_ROOM_TYPES, SWITCH_TRACK_COLOR, themes } from '../../lib/constants';
import { getRoomTitle } from '../../lib/methods';
class CreateChannelView extends React.Component<ICreateChannelViewProps, any> { class CreateChannelView extends React.Component<ICreateChannelViewProps, any> {
private channel: any; private channel: any;
@ -67,7 +67,7 @@ class CreateChannelView extends React.Component<ICreateChannelViewProps, any> {
} }
const item = { const item = {
rid, rid,
name: RocketChat.getRoomTitle(result), name: getRoomTitle(result),
t, t,
prid prid
}; };
@ -161,7 +161,7 @@ class CreateChannelView extends React.Component<ICreateChannelViewProps, any> {
server={server} server={server}
userId={user.id} userId={user.id}
token={user.token} token={user.token}
initial={this.channel && { text: RocketChat.getRoomTitle(this.channel) }} initial={this.channel && { text: getRoomTitle(this.channel) }}
onChannelSelect={this.selectChannel} onChannelSelect={this.selectChannel}
blockUnauthenticatedAccess={blockUnauthenticatedAccess} blockUnauthenticatedAccess={blockUnauthenticatedAccess}
serverVersion={serverVersion} serverVersion={serverVersion}

View File

@ -6,7 +6,6 @@ import { StackNavigationOptions, StackNavigationProp } from '@react-navigation/s
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import * as List from '../../containers/List'; import * as List from '../../containers/List';
import Touch from '../../utils/touch'; import Touch from '../../utils/touch';
import RocketChat from '../../lib/rocketchat';
import DirectoryItem from '../../containers/DirectoryItem'; import DirectoryItem from '../../containers/DirectoryItem';
import sharedStyles from '../Styles'; import sharedStyles from '../Styles';
import I18n from '../../i18n'; import I18n from '../../i18n';
@ -24,6 +23,7 @@ import SafeAreaView from '../../containers/SafeAreaView';
import { goRoom } from '../../utils/goRoom'; import { goRoom } from '../../utils/goRoom';
import styles from './styles'; import styles from './styles';
import Options from './Options'; import Options from './Options';
import { Services } from '../../lib/services';
interface IDirectoryViewProps { interface IDirectoryViewProps {
navigation: StackNavigationProp<ChatsStackParamList, 'DirectoryView'>; navigation: StackNavigationProp<ChatsStackParamList, 'DirectoryView'>;
@ -91,7 +91,7 @@ class DirectoryView extends React.Component<IDirectoryViewProps, any> {
try { try {
const { data, type, globalUsers } = this.state; const { data, type, globalUsers } = this.state;
const query = { text, type, workspace: globalUsers ? 'all' : 'local' }; const query = { text, type, workspace: globalUsers ? 'all' : 'local' };
const directories = await RocketChat.getDirectory({ const directories = await Services.getDirectory({
query, query,
offset: data.length, offset: data.length,
count: 50, count: 50,
@ -152,12 +152,12 @@ class DirectoryView extends React.Component<IDirectoryViewProps, any> {
onPressItem = async (item: any) => { onPressItem = async (item: any) => {
const { type } = this.state; const { type } = this.state;
if (type === 'users') { if (type === 'users') {
const result = await RocketChat.createDirectMessage(item.username); const result = await Services.createDirectMessage(item.username);
if (result.success) { if (result.success) {
this.goRoom({ rid: result.room._id, name: item.username, t: 'd' }); this.goRoom({ rid: result.room._id, name: item.username, t: 'd' });
} }
} else if (['p', 'c'].includes(item.t) && !item.teamMain) { } else if (['p', 'c'].includes(item.t) && !item.teamMain) {
const result = await RocketChat.getRoomInfo(item._id); const result = await Services.getRoomInfo(item._id);
if (result.success) { if (result.success) {
this.goRoom({ this.goRoom({
rid: item._id, rid: item._id,

View File

@ -20,10 +20,10 @@ import BackgroundContainer from '../../containers/BackgroundContainer';
import { isIOS } from '../../utils/deviceInfo'; import { isIOS } from '../../utils/deviceInfo';
import { getHeaderTitlePosition } from '../../containers/Header'; import { getHeaderTitlePosition } from '../../containers/Header';
import { useTheme } from '../../theme'; import { useTheme } from '../../theme';
import RocketChat from '../../lib/rocketchat';
import SearchHeader from '../../containers/SearchHeader'; import SearchHeader from '../../containers/SearchHeader';
import { TThreadModel } from '../../definitions/IThread'; import { TThreadModel } from '../../definitions/IThread';
import Item from './Item'; import Item from './Item';
import { Services } from '../../lib/services';
const API_FETCH_COUNT = 50; const API_FETCH_COUNT = 50;
@ -63,7 +63,7 @@ const DiscussionsView = ({ navigation, route }: IDiscussionsViewProps): JSX.Elem
setLoading(true); setLoading(true);
try { try {
const result = await RocketChat.getDiscussions({ const result = await Services.getDiscussions({
roomId: rid, roomId: rid,
offset: isSearching ? search.length : discussions.length, offset: isSearching ? search.length : discussions.length,
count: API_FETCH_COUNT, count: API_FETCH_COUNT,

View File

@ -13,10 +13,10 @@ import SafeAreaView from '../containers/SafeAreaView';
import StatusBar from '../containers/StatusBar'; import StatusBar from '../containers/StatusBar';
import { IApplicationState, IPreferences } from '../definitions'; import { IApplicationState, IPreferences } from '../definitions';
import I18n from '../i18n'; import I18n from '../i18n';
import RocketChat from '../lib/rocketchat';
import { SettingsStackParamList } from '../stacks/types'; import { SettingsStackParamList } from '../stacks/types';
import { useTheme } from '../theme'; import { useTheme } from '../theme';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
import { saveSortPreference } from '../lib/methods';
interface IDisplayPrefsView { interface IDisplayPrefsView {
navigation: StackNavigationProp<SettingsStackParamList, 'DisplayPrefsView'>; navigation: StackNavigationProp<SettingsStackParamList, 'DisplayPrefsView'>;
@ -46,7 +46,7 @@ const DisplayPrefsView = (props: IDisplayPrefsView): JSX.Element => {
const setSortPreference = (param: Partial<IPreferences>) => { const setSortPreference = (param: Partial<IPreferences>) => {
dispatch(setPreference(param)); dispatch(setPreference(param));
RocketChat.saveSortPreference(param); saveSortPreference(param);
}; };
const sortByName = () => { const sortByName = () => {

View File

@ -16,7 +16,6 @@ import { getUserSelector } from '../selectors/login';
import { PADDING_HORIZONTAL } from '../containers/List/constants'; import { PADDING_HORIZONTAL } from '../containers/List/constants';
import { themes } from '../lib/constants'; import { themes } from '../lib/constants';
import { Encryption } from '../lib/encryption'; import { Encryption } from '../lib/encryption';
import RocketChat from '../lib/rocketchat';
import { logout as logoutAction } from '../actions/login'; import { logout as logoutAction } from '../actions/login';
import { showConfirmationAlert, showErrorAlert } from '../utils/info'; import { showConfirmationAlert, showErrorAlert } from '../utils/info';
import EventEmitter from '../utils/events'; import EventEmitter from '../utils/events';
@ -24,6 +23,7 @@ import { LISTENER } from '../containers/Toast';
import debounce from '../utils/debounce'; import debounce from '../utils/debounce';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { IUser } from '../definitions'; import { IUser } from '../definitions';
import { Services } from '../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -101,7 +101,7 @@ class E2EEncryptionSecurityView extends React.Component<IE2EEncryptionSecurityVi
onPress: async () => { onPress: async () => {
logEvent(events.E2E_SEC_RESET_OWN_KEY); logEvent(events.E2E_SEC_RESET_OWN_KEY);
try { try {
const res = await RocketChat.e2eResetOwnKey(); const res = await Services.e2eResetOwnKey();
/** /**
* It might return an empty object when TOTP is enabled, * It might return an empty object when TOTP is enabled,
* that's why we're using strict equality to boolean * that's why we're using strict equality to boolean

View File

@ -1,20 +1,20 @@
import { RouteProp } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import React from 'react'; import React from 'react';
import { Text } from 'react-native'; import { Text } from 'react-native';
import { StackNavigationProp } from '@react-navigation/stack';
import { RouteProp } from '@react-navigation/native';
import TextInput from '../containers/TextInput';
import Button from '../containers/Button'; import Button from '../containers/Button';
import FormContainer, { FormContainerInner } from '../containers/FormContainer';
import TextInput from '../containers/TextInput';
import I18n from '../i18n';
import { themes } from '../lib/constants';
import { Services } from '../lib/services';
import { OutsideParamList } from '../stacks/types';
import { TSupportedThemes, withTheme } from '../theme';
import { showErrorAlert } from '../utils/info'; import { showErrorAlert } from '../utils/info';
import isValidEmail from '../utils/isValidEmail'; import isValidEmail from '../utils/isValidEmail';
import I18n from '../i18n';
import RocketChat from '../lib/rocketchat';
import { TSupportedThemes, withTheme } from '../theme';
import { themes } from '../lib/constants';
import FormContainer, { FormContainerInner } from '../containers/FormContainer';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { OutsideParamList } from '../stacks/types';
interface IForgotPasswordViewState { interface IForgotPasswordViewState {
email: string; email: string;
@ -73,7 +73,7 @@ class ForgotPasswordView extends React.Component<IForgotPasswordViewProps, IForg
} }
try { try {
this.setState({ isFetching: true }); this.setState({ isFetching: true });
const result = await RocketChat.forgotPassword(email); const result = await Services.forgotPassword(email);
if (result.success) { if (result.success) {
const { navigation } = this.props; const { navigation } = this.props;
navigation.pop(); navigation.pop();

View File

@ -9,10 +9,10 @@ import OrSeparator from '../containers/OrSeparator';
import Input from '../containers/UIKit/MultiSelect/Input'; import Input from '../containers/UIKit/MultiSelect/Input';
import { IBaseScreen, IServerRoom } from '../definitions'; import { IBaseScreen, IServerRoom } from '../definitions';
import I18n from '../i18n'; import I18n from '../i18n';
import RocketChat from '../lib/rocketchat';
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
import { withTheme } from '../theme'; import { withTheme } from '../theme';
import { IOptionsField } from './NotificationPreferencesView/options'; import { IOptionsField } from './NotificationPreferencesView/options';
import { Services } from '../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -41,7 +41,7 @@ const ForwardLivechatView = ({ navigation, route, theme }: IBaseScreen<ChatsStac
const getDepartments = async (text = '', offset = 0) => { const getDepartments = async (text = '', offset = 0) => {
try { try {
const result = await RocketChat.getDepartments({ count: COUNT_DEPARTMENT, text, offset }); const result = await Services.getDepartments({ count: COUNT_DEPARTMENT, text, offset });
if (result.success) { if (result.success) {
const parsedDepartments = result.departments.map(department => ({ const parsedDepartments = result.departments.map(department => ({
label: department.name, label: department.name,
@ -62,7 +62,7 @@ const ForwardLivechatView = ({ navigation, route, theme }: IBaseScreen<ChatsStac
try { try {
const { servedBy: { _id: agentId } = {} } = room; const { servedBy: { _id: agentId } = {} } = room;
const _id = agentId && { $ne: agentId }; const _id = agentId && { $ne: agentId };
const result = await RocketChat.usersAutoComplete({ const result = await Services.usersAutoComplete({
conditions: { _id, status: { $ne: 'offline' }, statusLivechat: 'available' }, conditions: { _id, status: { $ne: 'offline' }, statusLivechat: 'available' },
term term
}); });
@ -80,7 +80,7 @@ const ForwardLivechatView = ({ navigation, route, theme }: IBaseScreen<ChatsStac
const getRoom = async () => { const getRoom = async () => {
try { try {
const result = await RocketChat.getRoomInfo(rid); const result = await Services.getRoomInfo(rid);
if (result.success) { if (result.success) {
setRoom(result.room as IServerRoom); setRoom(result.room as IServerRoom);
} }

View File

@ -6,7 +6,6 @@ import JitsiMeet, { JitsiMeetView as RNJitsiMeetView } from 'react-native-jitsi-
import BackgroundTimer from 'react-native-background-timer'; import BackgroundTimer from 'react-native-background-timer';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import RocketChat from '../lib/rocketchat';
import { getUserSelector } from '../selectors/login'; import { getUserSelector } from '../selectors/login';
import ActivityIndicator from '../containers/ActivityIndicator'; import ActivityIndicator from '../containers/ActivityIndicator';
import { events, logEvent } from '../utils/log'; import { events, logEvent } from '../utils/log';
@ -14,6 +13,7 @@ import { isAndroid, isIOS } from '../utils/deviceInfo';
import { TSupportedThemes, withTheme } from '../theme'; import { TSupportedThemes, withTheme } from '../theme';
import { InsideStackParamList } from '../stacks/types'; import { InsideStackParamList } from '../stacks/types';
import { IApplicationState, IUser } from '../definitions'; import { IApplicationState, IUser } from '../definitions';
import { Services } from '../lib/services';
const formatUrl = (url: string, baseUrl: string, uriSize: number, avatarAuthURLFragment: string) => const formatUrl = (url: string, baseUrl: string, uriSize: number, avatarAuthURLFragment: string) =>
`${baseUrl}/avatar/${url}?format=png&width=${uriSize}&height=${uriSize}${avatarAuthURLFragment}`; `${baseUrl}/avatar/${url}?format=png&width=${uriSize}&height=${uriSize}${avatarAuthURLFragment}`;
@ -93,14 +93,14 @@ class JitsiMeetView extends React.Component<IJitsiMeetViewProps, IJitsiMeetViewS
onConferenceJoined = () => { onConferenceJoined = () => {
logEvent(events.JM_CONFERENCE_JOIN); logEvent(events.JM_CONFERENCE_JOIN);
if (this.rid) { if (this.rid) {
RocketChat.updateJitsiTimeout(this.rid).catch((e: unknown) => console.log(e)); Services.updateJitsiTimeout(this.rid).catch((e: unknown) => console.log(e));
if (this.jitsiTimeout) { if (this.jitsiTimeout) {
BackgroundTimer.clearInterval(this.jitsiTimeout); BackgroundTimer.clearInterval(this.jitsiTimeout);
BackgroundTimer.stopBackgroundTimer(); BackgroundTimer.stopBackgroundTimer();
this.jitsiTimeout = null; this.jitsiTimeout = null;
} }
this.jitsiTimeout = BackgroundTimer.setInterval(() => { this.jitsiTimeout = BackgroundTimer.setInterval(() => {
RocketChat.updateJitsiTimeout(this.rid).catch((e: unknown) => console.log(e)); Services.updateJitsiTimeout(this.rid).catch((e: unknown) => console.log(e));
}, 10000); }, 10000);
} }
}; };

View File

@ -12,12 +12,12 @@ import StatusBar from '../../containers/StatusBar';
import { IApplicationState, IBaseScreen, IUser, RootEnum } from '../../definitions'; import { IApplicationState, IBaseScreen, IUser, RootEnum } from '../../definitions';
import I18n, { isRTL, LANGUAGES } from '../../i18n'; import I18n, { isRTL, LANGUAGES } from '../../i18n';
import database from '../../lib/database'; import database from '../../lib/database';
import RocketChat from '../../lib/rocketchat';
import { getUserSelector } from '../../selectors/login'; import { getUserSelector } from '../../selectors/login';
import { SettingsStackParamList } from '../../stacks/types'; import { SettingsStackParamList } from '../../stacks/types';
import { withTheme } from '../../theme'; import { withTheme } from '../../theme';
import { showErrorAlert } from '../../utils/info'; import { showErrorAlert } from '../../utils/info';
import log, { events, logEvent } from '../../utils/log'; import log, { events, logEvent } from '../../utils/log';
import { Services } from '../../lib/services';
interface ILanguageViewProps extends IBaseScreen<SettingsStackParamList, 'LanguageView'> { interface ILanguageViewProps extends IBaseScreen<SettingsStackParamList, 'LanguageView'> {
user: IUser; user: IUser;
@ -92,7 +92,7 @@ class LanguageView extends React.Component<ILanguageViewProps, ILanguageViewStat
} }
try { try {
await RocketChat.saveUserPreferences(params); await Services.saveUserPreferences(params);
dispatch(setUser({ language: params.language })); dispatch(setUser({ language: params.language }));
const serversDB = database.servers; const serversDB = database.servers;

View File

@ -9,7 +9,6 @@ import { TSupportedThemes, withTheme } from '../theme';
import { themes } from '../lib/constants'; import { themes } from '../lib/constants';
import TextInput from '../containers/TextInput'; import TextInput from '../containers/TextInput';
import KeyboardView from '../containers/KeyboardView'; import KeyboardView from '../containers/KeyboardView';
import RocketChat from '../lib/rocketchat';
import I18n from '../i18n'; import I18n from '../i18n';
import { LISTENER } from '../containers/Toast'; import { LISTENER } from '../containers/Toast';
import EventEmitter from '../utils/events'; import EventEmitter from '../utils/events';
@ -22,6 +21,8 @@ import { ICustomFields, IInputsRefs, TParams, ITitle, ILivechat } from '../defin
import { IApplicationState } from '../definitions'; import { IApplicationState } from '../definitions';
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { hasPermission } from '../lib/methods';
import { Services } from '../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -74,7 +75,7 @@ const LivechatEditView = ({
const visitor = route.params?.roomUser ?? {}; const visitor = route.params?.roomUser ?? {};
const getCustomFields = async () => { const getCustomFields = async () => {
const result = await RocketChat.getCustomFields(); const result = await Services.getCustomFields();
if (result.success && result.customFields?.length) { if (result.success && result.customFields?.length) {
const visitorCustomFields = result.customFields const visitorCustomFields = result.customFields
.filter(field => field.visibility !== 'hidden' && field.scope === 'visitor') .filter(field => field.visibility !== 'hidden' && field.scope === 'visitor')
@ -99,8 +100,8 @@ const LivechatEditView = ({
setTags(uniqueArray); setTags(uniqueArray);
}, [availableUserTags]); }, [availableUserTags]);
const getTagsList = async (agentDepartments: string[]) => { const handleGetTagsList = async (agentDepartments: string[]) => {
const tags = await RocketChat.getTagsList(); const tags = await Services.getTagsList();
const isAdmin = ['admin', 'livechat-manager'].find(role => user.roles.includes(role)); const isAdmin = ['admin', 'livechat-manager'].find(role => user.roles.includes(role));
const availableTags = tags const availableTags = tags
.filter(({ departments }) => isAdmin || departments.length === 0 || departments.some(i => agentDepartments.indexOf(i) > -1)) .filter(({ departments }) => isAdmin || departments.length === 0 || departments.some(i => agentDepartments.indexOf(i) > -1))
@ -108,11 +109,11 @@ const LivechatEditView = ({
setAvailableUserTags(availableTags); setAvailableUserTags(availableTags);
}; };
const getAgentDepartments = async () => { const handleGetAgentDepartments = async () => {
const result = await RocketChat.getAgentDepartments(visitor?._id); const result = await Services.getAgentDepartments(visitor?._id);
if (result.success) { if (result.success) {
const agentDepartments = result.departments.map(dept => dept.departmentId); const agentDepartments = result.departments.map(dept => dept.departmentId);
getTagsList(agentDepartments); handleGetTagsList(agentDepartments);
} }
}; };
@ -158,7 +159,7 @@ const LivechatEditView = ({
delete userData.phone; delete userData.phone;
} }
const { error } = await RocketChat.editLivechat(userData, roomData); const { error } = await Services.editLivechat(userData, roomData);
if (error) { if (error) {
EventEmitter.emit(LISTENER, { message: error }); EventEmitter.emit(LISTENER, { message: error });
} else { } else {
@ -172,7 +173,7 @@ const LivechatEditView = ({
}; };
const getPermissions = async () => { const getPermissions = async () => {
const permissionsArray = await RocketChat.hasPermission([editOmnichannelContact, editLivechatRoomCustomfields], livechat.rid); const permissionsArray = await hasPermission([editOmnichannelContact, editLivechatRoomCustomfields], livechat.rid);
setPermissions(permissionsArray); setPermissions(permissionsArray);
}; };
@ -180,7 +181,7 @@ const LivechatEditView = ({
navigation.setOptions({ navigation.setOptions({
title: I18n.t('Edit') title: I18n.t('Edit')
}); });
getAgentDepartments(); handleGetAgentDepartments();
getCustomFields(); getCustomFields();
getPermissions(); getPermissions();
}, []); }, []);

View File

@ -9,7 +9,6 @@ import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack
import Message from '../../containers/message'; import Message from '../../containers/message';
import ActivityIndicator from '../../containers/ActivityIndicator'; import ActivityIndicator from '../../containers/ActivityIndicator';
import I18n from '../../i18n'; import I18n from '../../i18n';
import RocketChat from '../../lib/rocketchat';
import StatusBar from '../../containers/StatusBar'; import StatusBar from '../../containers/StatusBar';
import getFileUrlFromMessage from '../../lib/methods/helpers/getFileUrlFromMessage'; import getFileUrlFromMessage from '../../lib/methods/helpers/getFileUrlFromMessage';
import { themes } from '../../lib/constants'; import { themes } from '../../lib/constants';
@ -24,6 +23,7 @@ import { ISubscription, SubscriptionType } from '../../definitions/ISubscription
import { IEmoji } from '../../definitions/IEmoji'; import { IEmoji } from '../../definitions/IEmoji';
import { IRoomInfoParam } from '../SearchMessagesView'; import { IRoomInfoParam } from '../SearchMessagesView';
import { TMessageModel } from '../../definitions'; import { TMessageModel } from '../../definitions';
import { Services } from '../../lib/services';
interface IMessagesViewProps { interface IMessagesViewProps {
user: { user: {
@ -191,7 +191,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
name: I18n.t('Files'), name: I18n.t('Files'),
fetchFunc: async () => { fetchFunc: async () => {
const { messages } = this.state; const { messages } = this.state;
const result = await RocketChat.getFiles(this.rid, this.t, messages.length); const result = await Services.getFiles(this.rid, this.t, messages.length);
if (result.success) { if (result.success) {
return { ...result, messages: result.files }; return { ...result, messages: result.files };
} }
@ -222,7 +222,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
name: I18n.t('Mentions'), name: I18n.t('Mentions'),
fetchFunc: () => { fetchFunc: () => {
const { messages } = this.state; const { messages } = this.state;
return RocketChat.getMessages(this.rid, this.t, { 'mentions._id': { $in: [user.id] } }, messages.length); return Services.getMessages(this.rid, this.t, { 'mentions._id': { $in: [user.id] } }, messages.length);
}, },
noDataMsg: I18n.t('No_mentioned_messages'), noDataMsg: I18n.t('No_mentioned_messages'),
testID: 'mentioned-messages-view', testID: 'mentioned-messages-view',
@ -234,7 +234,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
name: I18n.t('Starred'), name: I18n.t('Starred'),
fetchFunc: () => { fetchFunc: () => {
const { messages } = this.state; const { messages } = this.state;
return RocketChat.getMessages(this.rid, this.t, { 'starred._id': { $in: [user.id] } }, messages.length); return Services.getMessages(this.rid, this.t, { 'starred._id': { $in: [user.id] } }, messages.length);
}, },
noDataMsg: I18n.t('No_starred_messages'), noDataMsg: I18n.t('No_starred_messages'),
testID: 'starred-messages-view', testID: 'starred-messages-view',
@ -247,14 +247,14 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
icon: message.starred ? 'star-filled' : 'star', icon: message.starred ? 'star-filled' : 'star',
onPress: this.handleActionPress onPress: this.handleActionPress
}), }),
handleActionPress: (message: IMessageItem) => RocketChat.toggleStarMessage(message._id, message.starred) handleActionPress: (message: IMessageItem) => Services.toggleStarMessage(message._id, message.starred)
}, },
// Pinned Messages Screen // Pinned Messages Screen
Pinned: { Pinned: {
name: I18n.t('Pinned'), name: I18n.t('Pinned'),
fetchFunc: () => { fetchFunc: () => {
const { messages } = this.state; const { messages } = this.state;
return RocketChat.getMessages(this.rid, this.t, { pinned: true }, messages.length); return Services.getMessages(this.rid, this.t, { pinned: true }, messages.length);
}, },
noDataMsg: I18n.t('No_pinned_messages'), noDataMsg: I18n.t('No_pinned_messages'),
testID: 'pinned-messages-view', testID: 'pinned-messages-view',
@ -263,7 +263,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
<Message {...renderItemCommonProps(item)} msg={item.msg} onLongPress={() => this.onLongPress(item)} theme={theme} /> <Message {...renderItemCommonProps(item)} msg={item.msg} onLongPress={() => this.onLongPress(item)} theme={theme} />
), ),
action: () => ({ title: I18n.t('Unpin'), icon: 'pin', onPress: this.handleActionPress }), action: () => ({ title: I18n.t('Unpin'), icon: 'pin', onPress: this.handleActionPress }),
handleActionPress: (message: IMessageItem) => RocketChat.togglePinMessage(message._id, message.pinned) handleActionPress: (message: IMessageItem) => Services.togglePinMessage(message._id, message.pinned)
} }
// @ts-ignore // @ts-ignore
}[name]; }[name];

View File

@ -10,12 +10,12 @@ import EventEmitter from '../utils/events';
import { themes } from '../lib/constants'; import { themes } from '../lib/constants';
import * as HeaderButton from '../containers/HeaderButton'; import * as HeaderButton from '../containers/HeaderButton';
import { modalBlockWithContext } from '../containers/UIKit/MessageBlock'; import { modalBlockWithContext } from '../containers/UIKit/MessageBlock';
import RocketChat from '../lib/rocketchat';
import ActivityIndicator from '../containers/ActivityIndicator'; import ActivityIndicator from '../containers/ActivityIndicator';
import { textParser } from '../containers/UIKit/utils'; import { textParser } from '../containers/UIKit/utils';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import { MasterDetailInsideStackParamList } from '../stacks/MasterDetailStack/types'; import { MasterDetailInsideStackParamList } from '../stacks/MasterDetailStack/types';
import { ContainerTypes, ModalActions } from '../containers/UIKit/interfaces'; import { ContainerTypes, ModalActions } from '../containers/UIKit/interfaces';
import { triggerBlockAction, triggerCancel, triggerSubmitView } from '../lib/methods';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -183,7 +183,7 @@ class ModalBlockView extends React.Component<IModalBlockViewProps, IModalBlockVi
} }
try { try {
await RocketChat.triggerCancel({ await triggerCancel({
appId, appId,
viewId, viewId,
view: { view: {
@ -209,7 +209,7 @@ class ModalBlockView extends React.Component<IModalBlockViewProps, IModalBlockVi
const { appId, viewId } = data; const { appId, viewId } = data;
this.setState({ loading: true }); this.setState({ loading: true });
try { try {
await RocketChat.triggerSubmitView({ await triggerSubmitView({
viewId, viewId,
appId, appId,
payload: { payload: {
@ -230,7 +230,7 @@ class ModalBlockView extends React.Component<IModalBlockViewProps, IModalBlockVi
action = async ({ actionId, value, blockId }: IActions) => { action = async ({ actionId, value, blockId }: IActions) => {
const { data } = this.state; const { data } = this.state;
const { mid, appId, viewId } = data; const { mid, appId, viewId } = data;
await RocketChat.triggerBlockAction({ await triggerBlockAction({
container: { container: {
type: ContainerTypes.VIEW, type: ContainerTypes.VIEW,
id: viewId id: viewId

View File

@ -18,13 +18,13 @@ import database from '../lib/database';
import { CustomIcon } from '../lib/Icons'; import { CustomIcon } from '../lib/Icons';
import Navigation from '../lib/navigation/appNavigation'; import Navigation from '../lib/navigation/appNavigation';
import { compareServerVersion } from '../lib/methods/helpers/compareServerVersion'; import { compareServerVersion } from '../lib/methods/helpers/compareServerVersion';
import RocketChat from '../lib/rocketchat';
import UserItem from '../containers/UserItem'; import UserItem from '../containers/UserItem';
import { withTheme } from '../theme'; import { withTheme } from '../theme';
import { goRoom } from '../utils/goRoom'; import { goRoom } from '../utils/goRoom';
import log, { events, logEvent } from '../utils/log'; import log, { events, logEvent } from '../utils/log';
import Touch from '../utils/touch'; import Touch from '../utils/touch';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { hasPermission, search } from '../lib/methods';
const QUERY_SIZE = 50; const QUERY_SIZE = 50;
@ -127,8 +127,15 @@ class NewMessageView extends React.Component<INewMessageViewProps, INewMessageVi
} }
} }
handleSearch = async (text: string) => {
const result = (await search({ text, filterRooms: false })) as ISearch[];
this.setState({
search: result
});
};
onSearchChangeText(text: string) { onSearchChangeText(text: string) {
this.search(text); this.handleSearch(text);
} }
dismiss = () => { dismiss = () => {
@ -136,13 +143,6 @@ class NewMessageView extends React.Component<INewMessageViewProps, INewMessageVi
return navigation.pop(); return navigation.pop();
}; };
search = async (text: string) => {
const result = (await RocketChat.search({ text, filterRooms: false })) as ISearch[];
this.setState({
search: result
});
};
createChannel = () => { createChannel = () => {
logEvent(events.NEW_MSG_CREATE_CHANNEL); logEvent(events.NEW_MSG_CREATE_CHANNEL);
const { navigation } = this.props; const { navigation } = this.props;
@ -214,7 +214,7 @@ class NewMessageView extends React.Component<INewMessageViewProps, INewMessageVi
createDirectMessagePermission, createDirectMessagePermission,
createDiscussionPermission createDiscussionPermission
]; ];
const permissionsToCreate = await RocketChat.hasPermission(permissions); const permissionsToCreate = await hasPermission(permissions);
this.setState({ permissions: permissionsToCreate }); this.setState({ permissions: permissionsToCreate });
}; };

View File

@ -9,7 +9,7 @@ import parse from 'url-parse';
import { inviteLinksClear } from '../../actions/inviteLinks'; import { inviteLinksClear } from '../../actions/inviteLinks';
import { selectServerRequest, serverFinishAdd, serverRequest } from '../../actions/server'; import { selectServerRequest, serverFinishAdd, serverRequest } from '../../actions/server';
import { themes } from '../../lib/constants'; import { CERTIFICATE_KEY, themes } from '../../lib/constants';
import Button from '../../containers/Button'; import Button from '../../containers/Button';
import FormContainer, { FormContainerInner } from '../../containers/FormContainer'; import FormContainer, { FormContainerInner } from '../../containers/FormContainer';
import * as HeaderButton from '../../containers/HeaderButton'; import * as HeaderButton from '../../containers/HeaderButton';
@ -19,7 +19,6 @@ import { withDimensions } from '../../dimensions';
import I18n from '../../i18n'; import I18n from '../../i18n';
import database from '../../lib/database'; import database from '../../lib/database';
import { sanitizeLikeString } from '../../lib/database/utils'; import { sanitizeLikeString } from '../../lib/database/utils';
import RocketChat from '../../lib/rocketchat';
import UserPreferences from '../../lib/methods/userPreferences'; import UserPreferences from '../../lib/methods/userPreferences';
import { OutsideParamList } from '../../stacks/types'; import { OutsideParamList } from '../../stacks/types';
import { withTheme } from '../../theme'; import { withTheme } from '../../theme';
@ -194,7 +193,7 @@ class NewServerView extends React.Component<INewServerViewProps, INewServerViewS
// Save info - SSL Pinning // Save info - SSL Pinning
if (certificate) { if (certificate) {
UserPreferences.setString(`${RocketChat.CERTIFICATE_KEY}-${server}`, certificate); UserPreferences.setString(`${CERTIFICATE_KEY}-${server}`, certificate);
} }
// Save info - HTTP Basic Authentication // Save info - HTTP Basic Authentication

View File

@ -10,7 +10,6 @@ import { SWITCH_TRACK_COLOR, themes } from '../../lib/constants';
import StatusBar from '../../containers/StatusBar'; import StatusBar from '../../containers/StatusBar';
import * as List from '../../containers/List'; import * as List from '../../containers/List';
import I18n from '../../i18n'; import I18n from '../../i18n';
import RocketChat from '../../lib/rocketchat';
import { TSupportedThemes, withTheme } from '../../theme'; import { TSupportedThemes, withTheme } from '../../theme';
import protectedFunction from '../../lib/methods/helpers/protectedFunction'; import protectedFunction from '../../lib/methods/helpers/protectedFunction';
import SafeAreaView from '../../containers/SafeAreaView'; import SafeAreaView from '../../containers/SafeAreaView';
@ -19,6 +18,7 @@ import sharedStyles from '../Styles';
import { IOptionsField, OPTIONS } from './options'; import { IOptionsField, OPTIONS } from './options';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import { IRoomNotifications } from '../../definitions'; import { IRoomNotifications } from '../../definitions';
import { Services } from '../../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
pickerText: { pickerText: {
@ -90,7 +90,7 @@ class NotificationPreferencesView extends React.Component<INotificationPreferenc
}); });
try { try {
const result = await RocketChat.saveNotificationSettings(this.rid, params); const result = await Services.saveNotificationSettings(this.rid, params);
if (result.success) { if (result.success) {
return; return;
} }

View File

@ -16,7 +16,6 @@ import scrollPersistTaps from '../../utils/scrollPersistTaps';
import { showConfirmationAlert, showErrorAlert } from '../../utils/info'; import { showConfirmationAlert, showErrorAlert } from '../../utils/info';
import { LISTENER } from '../../containers/Toast'; import { LISTENER } from '../../containers/Toast';
import EventEmitter from '../../utils/events'; import EventEmitter from '../../utils/events';
import RocketChat from '../../lib/rocketchat';
import RCTextInput from '../../containers/TextInput'; import RCTextInput from '../../containers/TextInput';
import log, { events, logEvent } from '../../utils/log'; import log, { events, logEvent } from '../../utils/log';
import I18n from '../../i18n'; import I18n from '../../i18n';
@ -40,6 +39,7 @@ import {
IProfileViewState IProfileViewState
} from '../../definitions/IProfileViewInterfaces'; } from '../../definitions/IProfileViewInterfaces';
import { IUser } from '../../definitions'; import { IUser } from '../../definitions';
import { Services } from '../../lib/services';
class ProfileView extends React.Component<IProfileViewProps, IProfileViewState> { class ProfileView extends React.Component<IProfileViewProps, IProfileViewState> {
private name: any; private name: any;
@ -81,7 +81,7 @@ class ProfileView extends React.Component<IProfileViewProps, IProfileViewState>
this.init(); this.init();
try { try {
const result = await RocketChat.getAvatarSuggestion(); const result = await Services.getAvatarSuggestion();
this.setState({ avatarSuggestions: result }); this.setState({ avatarSuggestions: result });
} catch (e) { } catch (e) {
log(e); log(e);
@ -228,7 +228,7 @@ class ProfileView extends React.Component<IProfileViewProps, IProfileViewState>
if (avatar!.url) { if (avatar!.url) {
try { try {
logEvent(events.PROFILE_SAVE_AVATAR); logEvent(events.PROFILE_SAVE_AVATAR);
await RocketChat.setAvatarFromService(avatar); await Services.setAvatarFromService(avatar);
} catch (e) { } catch (e) {
logEvent(events.PROFILE_SAVE_AVATAR_F); logEvent(events.PROFILE_SAVE_AVATAR_F);
this.setState({ saving: false, currentPassword: null }); this.setState({ saving: false, currentPassword: null });
@ -236,7 +236,7 @@ class ProfileView extends React.Component<IProfileViewProps, IProfileViewState>
} }
} }
const result = await RocketChat.saveUserProfile(params, customFields); const result = await Services.saveUserProfile(params, customFields);
if (result.success) { if (result.success) {
logEvent(events.PROFILE_SAVE_CHANGES); logEvent(events.PROFILE_SAVE_CHANGES);
@ -265,7 +265,7 @@ class ProfileView extends React.Component<IProfileViewProps, IProfileViewState>
try { try {
const { user } = this.props; const { user } = this.props;
await RocketChat.resetAvatar(user.id); await Services.resetAvatar(user.id);
EventEmitter.emit(LISTENER, { message: I18n.t('Avatar_changed_successfully') }); EventEmitter.emit(LISTENER, { message: I18n.t('Avatar_changed_successfully') });
this.init(); this.init();
} catch (e) { } catch (e) {
@ -437,7 +437,7 @@ class ProfileView extends React.Component<IProfileViewProps, IProfileViewState>
confirmationText: I18n.t('Logout'), confirmationText: I18n.t('Logout'),
onPress: async () => { onPress: async () => {
try { try {
await RocketChat.logoutOtherLocations(); await Services.logoutOtherLocations();
EventEmitter.emit(LISTENER, { message: I18n.t('Logged_out_of_other_clients_successfully') }); EventEmitter.emit(LISTENER, { message: I18n.t('Logged_out_of_other_clients_successfully') });
} catch { } catch {
logEvent(events.PL_OTHER_LOCATIONS_F); logEvent(events.PL_OTHER_LOCATIONS_F);

View File

@ -10,7 +10,6 @@ import * as List from '../../containers/List';
import Avatar from '../../containers/Avatar'; import Avatar from '../../containers/Avatar';
import * as HeaderButton from '../../containers/HeaderButton'; import * as HeaderButton from '../../containers/HeaderButton';
import I18n from '../../i18n'; import I18n from '../../i18n';
import RocketChat from '../../lib/rocketchat';
import StatusBar from '../../containers/StatusBar'; import StatusBar from '../../containers/StatusBar';
import { TSupportedThemes, withTheme } from '../../theme'; import { TSupportedThemes, withTheme } from '../../theme';
import { themes } from '../../lib/constants'; import { themes } from '../../lib/constants';
@ -18,6 +17,7 @@ import SafeAreaView from '../../containers/SafeAreaView';
import styles from './styles'; import styles from './styles';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import { IReadReceipts } from '../../definitions'; import { IReadReceipts } from '../../definitions';
import { Services } from '../../lib/services';
interface IReadReceiptViewState { interface IReadReceiptViewState {
loading: boolean; loading: boolean;
@ -85,7 +85,7 @@ class ReadReceiptView extends React.Component<IReadReceiptViewProps, IReadReceip
this.setState({ loading: true }); this.setState({ loading: true });
try { try {
const result = await RocketChat.getReadReceipts(this.messageId); const result = await Services.getReadReceipts(this.messageId);
if (result.success) { if (result.success) {
this.setState({ this.setState({
receipts: result.receipts, receipts: result.receipts,

View File

@ -12,7 +12,6 @@ import LoginServices from '../containers/LoginServices';
import TextInput from '../containers/TextInput'; import TextInput from '../containers/TextInput';
import { IApplicationState, IBaseScreen } from '../definitions'; import { IApplicationState, IBaseScreen } from '../definitions';
import I18n from '../i18n'; import I18n from '../i18n';
import RocketChat from '../lib/rocketchat';
import { getShowLoginButton } from '../selectors/login'; import { getShowLoginButton } from '../selectors/login';
import { OutsideParamList } from '../stacks/types'; import { OutsideParamList } from '../stacks/types';
import { withTheme } from '../theme'; import { withTheme } from '../theme';
@ -21,6 +20,7 @@ import isValidEmail from '../utils/isValidEmail';
import log, { events, logEvent } from '../utils/log'; import log, { events, logEvent } from '../utils/log';
import openLink from '../utils/openLink'; import openLink from '../utils/openLink';
import sharedStyles from './Styles'; import sharedStyles from './Styles';
import { Services } from '../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
title: { title: {
@ -128,7 +128,7 @@ class RegisterView extends React.Component<IProps, any> {
const { dispatch, Accounts_EmailVerification, navigation, Accounts_ManuallyApproveNewUsers } = this.props; const { dispatch, Accounts_EmailVerification, navigation, Accounts_ManuallyApproveNewUsers } = this.props;
try { try {
await RocketChat.register({ await Services.register({
name, name,
email, email,
pass: password, pass: password,

View File

@ -29,7 +29,6 @@ import { withDimensions } from '../../dimensions';
import I18n from '../../i18n'; import I18n from '../../i18n';
import database from '../../lib/database'; import database from '../../lib/database';
import protectedFunction from '../../lib/methods/helpers/protectedFunction'; import protectedFunction from '../../lib/methods/helpers/protectedFunction';
import RocketChat from '../../lib/rocketchat';
import { getUserSelector } from '../../selectors/login'; import { getUserSelector } from '../../selectors/login';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import { withTheme } from '../../theme'; import { withTheme } from '../../theme';
@ -41,6 +40,17 @@ import styles from './styles';
import { ERoomType } from '../../definitions/ERoomType'; import { ERoomType } from '../../definitions/ERoomType';
import { E2E_ROOM_TYPES, SWITCH_TRACK_COLOR, themes } from '../../lib/constants'; import { E2E_ROOM_TYPES, SWITCH_TRACK_COLOR, themes } from '../../lib/constants';
import { compareServerVersion } from '../../lib/methods/helpers/compareServerVersion'; import { compareServerVersion } from '../../lib/methods/helpers/compareServerVersion';
import {
callJitsi,
canAutoTranslate as canAutoTranslateMethod,
getPermalinkChannel,
getRoomAvatar,
getRoomTitle,
getUidDirectMessage,
hasPermission,
isGroupChat
} from '../../lib/methods';
import { Services } from '../../lib/services';
import { getSubscriptionByRoomId } from '../../lib/database/services/Subscription'; import { getSubscriptionByRoomId } from '../../lib/database/services/Subscription';
interface IRoomActionsViewProps extends IBaseScreen<ChatsStackParamList, 'RoomActionsView'> { interface IRoomActionsViewProps extends IBaseScreen<ChatsStackParamList, 'RoomActionsView'> {
@ -163,7 +173,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
} }
} else { } else {
try { try {
const result = await RocketChat.getChannelInfo(room.rid); const result = await Services.getChannelInfo(room.rid);
if (result.success) { if (result.success) {
// @ts-ignore // @ts-ignore
this.setState({ room: { ...result.channel, rid: result.channel._id } }); this.setState({ room: { ...result.channel, rid: result.channel._id } });
@ -176,7 +186,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
if (room && room.t !== 'd' && this.canViewMembers()) { if (room && room.t !== 'd' && this.canViewMembers()) {
try { try {
const counters = await RocketChat.getRoomCounters(room.rid, room.t as any); const counters = await Services.getRoomCounters(room.rid, room.t as any);
if (counters.success) { if (counters.success) {
this.setState({ membersCount: counters.members, joined: counters.joined }); this.setState({ membersCount: counters.members, joined: counters.joined });
} }
@ -187,7 +197,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
this.updateRoomMember(); this.updateRoomMember();
} }
const canAutoTranslate = await RocketChat.canAutoTranslate(); const canAutoTranslate = canAutoTranslateMethod();
const canAddUser = await this.canAddUser(); const canAddUser = await this.canAddUser();
const canInviteUser = await this.canInviteUser(); const canInviteUser = await this.canInviteUser();
const canEdit = await this.canEdit(); const canEdit = await this.canEdit();
@ -269,7 +279,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
let canAddUser = false; let canAddUser = false;
const userInRoom = joined; const userInRoom = joined;
const permissions = await RocketChat.hasPermission( const permissions = await hasPermission(
[addUserToJoinedRoomPermission, addUserToAnyCRoomPermission, addUserToAnyPRoomPermission], [addUserToJoinedRoomPermission, addUserToAnyCRoomPermission, addUserToAnyPRoomPermission],
rid rid
); );
@ -290,7 +300,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { createInviteLinksPermission } = this.props; const { createInviteLinksPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([createInviteLinksPermission], rid); const permissions = await hasPermission([createInviteLinksPermission], rid);
const canInviteUser = permissions[0]; const canInviteUser = permissions[0];
return canInviteUser; return canInviteUser;
@ -300,7 +310,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { editRoomPermission } = this.props; const { editRoomPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([editRoomPermission], rid); const permissions = await hasPermission([editRoomPermission], rid);
const canEdit = permissions[0]; const canEdit = permissions[0];
return canEdit; return canEdit;
@ -310,7 +320,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { createTeamPermission } = this.props; const { createTeamPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([createTeamPermission], rid); const permissions = await hasPermission([createTeamPermission], rid);
const canCreateTeam = permissions[0]; const canCreateTeam = permissions[0];
return canCreateTeam; return canCreateTeam;
@ -320,7 +330,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { addTeamChannelPermission } = this.props; const { addTeamChannelPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([addTeamChannelPermission], rid); const permissions = await hasPermission([addTeamChannelPermission], rid);
const canAddChannelToTeam = permissions[0]; const canAddChannelToTeam = permissions[0];
return canAddChannelToTeam; return canAddChannelToTeam;
@ -330,7 +340,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { convertTeamPermission } = this.props; const { convertTeamPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([convertTeamPermission], rid); const permissions = await hasPermission([convertTeamPermission], rid);
const canConvertTeam = permissions[0]; const canConvertTeam = permissions[0];
return canConvertTeam; return canConvertTeam;
@ -340,7 +350,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { toggleRoomE2EEncryptionPermission } = this.props; const { toggleRoomE2EEncryptionPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([toggleRoomE2EEncryptionPermission], rid); const permissions = await hasPermission([toggleRoomE2EEncryptionPermission], rid);
const canToggleEncryption = permissions[0]; const canToggleEncryption = permissions[0];
return canToggleEncryption; return canToggleEncryption;
@ -351,7 +361,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { viewBroadcastMemberListPermission } = this.props; const { viewBroadcastMemberListPermission } = this.props;
const { rid, t, broadcast } = room; const { rid, t, broadcast } = room;
if (broadcast) { if (broadcast) {
const permissions = await RocketChat.hasPermission([viewBroadcastMemberListPermission], rid); const permissions = await hasPermission([viewBroadcastMemberListPermission], rid);
if (!permissions[0]) { if (!permissions[0]) {
return false; return false;
} }
@ -367,7 +377,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { transferLivechatGuestPermission } = this.props; const { transferLivechatGuestPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([transferLivechatGuestPermission], rid); const permissions = await hasPermission([transferLivechatGuestPermission], rid);
return permissions[0]; return permissions[0];
}; };
@ -375,7 +385,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
const { viewCannedResponsesPermission } = this.props; const { viewCannedResponsesPermission } = this.props;
const { rid } = room; const { rid } = room;
const permissions = await RocketChat.hasPermission([viewCannedResponsesPermission], rid); const permissions = await hasPermission([viewCannedResponsesPermission], rid);
return permissions[0]; return permissions[0];
}; };
@ -388,7 +398,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
canReturnQueue = async () => { canReturnQueue = async () => {
try { try {
const { returnQueue } = await RocketChat.getRoutingConfig(); const { returnQueue } = await Services.getRoutingConfig();
return returnQueue; return returnQueue;
} catch { } catch {
return false; return false;
@ -428,7 +438,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
confirmationText: I18n.t('Yes'), confirmationText: I18n.t('Yes'),
onPress: async () => { onPress: async () => {
try { try {
await RocketChat.onHoldLivechat(room.rid); await Services.onHoldLivechat(room.rid);
navigation.navigate('RoomsListView'); navigation.navigate('RoomsListView');
} catch (e: any) { } catch (e: any) {
showErrorAlert(e.data?.error, I18n.t('Oops')); showErrorAlert(e.data?.error, I18n.t('Oops'));
@ -446,7 +456,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
confirmationText: I18n.t('Yes'), confirmationText: I18n.t('Yes'),
onPress: async () => { onPress: async () => {
try { try {
await RocketChat.returnLivechat(rid); await Services.returnLivechat(rid);
} catch (e: any) { } catch (e: any) {
showErrorAlert(e.reason, I18n.t('Oops')); showErrorAlert(e.reason, I18n.t('Oops'));
} }
@ -458,9 +468,9 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { room } = this.state; const { room } = this.state;
try { try {
if (!RocketChat.isGroupChat(room)) { if (!isGroupChat(room)) {
const roomUserId = RocketChat.getUidDirectMessage(room); const roomUserId = getUidDirectMessage(room);
const result = await RocketChat.getUserInfo(roomUserId); const result = await Services.getUserInfo(roomUserId);
if (result.success) { if (result.success) {
this.setState({ member: result.user as any }); this.setState({ member: result.user as any });
} }
@ -477,7 +487,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { rid } = room; const { rid } = room;
try { try {
dispatch(setLoading(true)); dispatch(setLoading(true));
await RocketChat.addUsersToRoom(rid); await Services.addUsersToRoom(rid);
navigation.pop(); navigation.pop();
} catch (e) { } catch (e) {
log(e); log(e);
@ -492,7 +502,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { rid, blocker } = room; const { rid, blocker } = room;
const { member } = this.state; const { member } = this.state;
try { try {
await RocketChat.toggleBlockUser(rid, member._id as string, !blocker); await Services.toggleBlockUser(rid, member._id as string, !blocker);
} catch (e) { } catch (e) {
logEvent(events.RA_TOGGLE_BLOCK_USER_F); logEvent(events.RA_TOGGLE_BLOCK_USER_F);
log(e); log(e);
@ -519,7 +529,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
try { try {
// Send new room setting value to server // Send new room setting value to server
const { result } = await RocketChat.saveRoomSettings(rid, { encrypted }); const { result } = await Services.saveRoomSettings(rid, { encrypted });
// If it was saved successfully // If it was saved successfully
if (result) { if (result) {
return; return;
@ -545,7 +555,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
handleShare = () => { handleShare = () => {
logEvent(events.RA_SHARE); logEvent(events.RA_SHARE);
const { room } = this.state; const { room } = this.state;
const permalink = RocketChat.getPermalinkChannel(room); const permalink = getPermalinkChannel(room);
if (!permalink) { if (!permalink) {
return; return;
} }
@ -559,7 +569,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { dispatch } = this.props; const { dispatch } = this.props;
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('Are_you_sure_you_want_to_leave_the_room', { room: RocketChat.getRoomTitle(room) }), message: I18n.t('Are_you_sure_you_want_to_leave_the_room', { room: getRoomTitle(room) }),
confirmationText: I18n.t('Yes_action_it', { action: I18n.t('leave') }), confirmationText: I18n.t('Yes_action_it', { action: I18n.t('leave') }),
onPress: () => dispatch(leaveRoom(ERoomType.c, room)) onPress: () => dispatch(leaveRoom(ERoomType.c, room))
}); });
@ -573,7 +583,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
if (!room.teamId) { if (!room.teamId) {
return; return;
} }
const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId, userId }); const result = await Services.teamListRoomsOfUser({ teamId: room.teamId, userId });
if (result.success) { if (result.success) {
if (result.rooms?.length) { if (result.rooms?.length) {
@ -606,7 +616,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
if (!room.teamId) { if (!room.teamId) {
return; return;
} }
const result = await RocketChat.convertTeamToChannel({ teamId: room.teamId, selected }); const result = await Services.convertTeamToChannel({ teamId: room.teamId, selected });
if (result.success) { if (result.success) {
navigation.navigate('RoomView'); navigation.navigate('RoomView');
@ -634,7 +644,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
if (!room.teamId) { if (!room.teamId) {
return; return;
} }
const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId, userId }); const result = await Services.teamListRoomsOfUser({ teamId: room.teamId, userId });
if (result.success) { if (result.success) {
if (result.rooms?.length) { if (result.rooms?.length) {
@ -653,7 +663,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
}); });
} else { } else {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('You_are_leaving_the_team', { team: RocketChat.getRoomTitle(room) }), message: I18n.t('You_are_leaving_the_team', { team: getRoomTitle(room) }),
confirmationText: I18n.t('Yes_action_it', { action: I18n.t('leave') }), confirmationText: I18n.t('Yes_action_it', { action: I18n.t('leave') }),
onPress: () => dispatch(leaveRoom(ERoomType.t, room)) onPress: () => dispatch(leaveRoom(ERoomType.t, room))
}); });
@ -661,7 +671,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
} }
} catch (e) { } catch (e) {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('You_are_leaving_the_team', { team: RocketChat.getRoomTitle(room) }), message: I18n.t('You_are_leaving_the_team', { team: getRoomTitle(room) }),
confirmationText: I18n.t('Yes_action_it', { action: I18n.t('leave') }), confirmationText: I18n.t('Yes_action_it', { action: I18n.t('leave') }),
onPress: () => dispatch(leaveRoom(ERoomType.t, room)) onPress: () => dispatch(leaveRoom(ERoomType.t, room))
}); });
@ -673,7 +683,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
try { try {
const { room } = this.state; const { room } = this.state;
const { navigation } = this.props; const { navigation } = this.props;
const result = await RocketChat.convertChannelToTeam({ rid: room.rid, name: room.name, type: room.t as any }); const result = await Services.convertChannelToTeam({ rid: room.rid, name: room.name, type: room.t as any });
if (result.success) { if (result.success) {
navigation.navigate('RoomView'); navigation.navigate('RoomView');
@ -698,7 +708,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
try { try {
const { room } = this.state; const { room } = this.state;
const { navigation } = this.props; const { navigation } = this.props;
const result = await RocketChat.addRoomsToTeam({ teamId: selected?.[0], rooms: [room.rid] }); const result = await Services.addRoomsToTeam({ teamId: selected?.[0], rooms: [room.rid] });
if (result.success) { if (result.success) {
navigation.navigate('RoomView'); navigation.navigate('RoomView');
} }
@ -767,7 +777,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const asyncFilter = async (teamArray: TSubscriptionModel[]) => { const asyncFilter = async (teamArray: TSubscriptionModel[]) => {
const results = await Promise.all( const results = await Promise.all(
teamArray.map(async team => { teamArray.map(async team => {
const permissions = await RocketChat.hasPermission([addTeamChannelPermission, createTeamPermission], team.rid); const permissions = await hasPermission([addTeamChannelPermission, createTeamPermission], team.rid);
if (!permissions[0]) { if (!permissions[0]) {
return false; return false;
} }
@ -789,8 +799,8 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
const { rid, name, t, topic, source } = room; const { rid, name, t, topic, source } = room;
const { theme, fontScale } = this.props; const { theme, fontScale } = this.props;
const avatar = RocketChat.getRoomAvatar(room); const avatar = getRoomAvatar(room);
const isGroupChat = RocketChat.isGroupChat(room); const isGroupChatHandler = isGroupChat(room);
return ( return (
<List.Section> <List.Section>
@ -810,7 +820,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
} }
style={{ backgroundColor: themes[theme].backgroundColor }} style={{ backgroundColor: themes[theme].backgroundColor }}
accessibilityLabel={I18n.t('Room_Info')} accessibilityLabel={I18n.t('Room_Info')}
enabled={!isGroupChat} enabled={!isGroupChatHandler}
testID='room-actions-info' testID='room-actions-info'
theme={theme}> theme={theme}>
<View style={[styles.roomInfoContainer, { height: 72 * fontScale }]}> <View style={[styles.roomInfoContainer, { height: 72 * fontScale }]}>
@ -835,7 +845,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
sourceType={source} sourceType={source}
/> />
<Text style={[styles.roomTitle, { color: themes[theme].titleText }]} numberOfLines={1}> <Text style={[styles.roomTitle, { color: themes[theme].titleText }]} numberOfLines={1}>
{RocketChat.getRoomTitle(room)} {getRoomTitle(room)}
</Text> </Text>
</View> </View>
)} )}
@ -850,7 +860,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
/> />
)} )}
</View> </View>
{isGroupChat ? null : <List.Icon name='chevron-right' style={styles.actionIndicator} />} {isGroupChatHandler ? null : <List.Icon name='chevron-right' style={styles.actionIndicator} />}
</View> </View>
</Touch> </Touch>
<List.Separator /> <List.Separator />
@ -874,7 +884,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
<List.Separator /> <List.Separator />
<List.Item <List.Item
title='Voice_call' title='Voice_call'
onPress={() => RocketChat.callJitsi(room, true)} onPress={() => callJitsi(room, true)}
testID='room-actions-voice' testID='room-actions-voice'
left={() => <List.Icon name='phone' />} left={() => <List.Icon name='phone' />}
showActionIndicator showActionIndicator
@ -882,7 +892,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
<List.Separator /> <List.Separator />
<List.Item <List.Item
title='Video_call' title='Video_call'
onPress={() => RocketChat.callJitsi(room)} onPress={() => callJitsi(room)}
testID='room-actions-video' testID='room-actions-video'
left={() => <List.Icon name='camera' />} left={() => <List.Icon name='camera' />}
showActionIndicator showActionIndicator
@ -924,7 +934,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
return null; return null;
} }
if (t === 'd' && !RocketChat.isGroupChat(room)) { if (t === 'd' && !isGroupChat(room)) {
return ( return (
<List.Section> <List.Section>
<List.Separator /> <List.Separator />
@ -1053,7 +1063,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
canPlaceLivechatOnHold canPlaceLivechatOnHold
} = this.state; } = this.state;
const { rid, t, prid } = room; const { rid, t, prid } = room;
const isGroupChat = RocketChat.isGroupChat(room); const isGroupChatHandler = isGroupChat(room);
return ( return (
<SafeAreaView testID='room-actions-view'> <SafeAreaView testID='room-actions-view'>
@ -1065,7 +1075,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
<List.Section> <List.Section>
<List.Separator /> <List.Separator />
{(['c', 'p'].includes(t) && canViewMembers) || isGroupChat ? ( {(['c', 'p'].includes(t) && canViewMembers) || isGroupChatHandler ? (
<> <>
<List.Item <List.Item
title='Members' title='Members'

View File

@ -21,7 +21,6 @@ import { ERoomType } from '../../definitions/ERoomType';
import I18n from '../../i18n'; import I18n from '../../i18n';
import database from '../../lib/database'; import database from '../../lib/database';
import { CustomIcon } from '../../lib/Icons'; import { CustomIcon } from '../../lib/Icons';
import RocketChat from '../../lib/rocketchat';
import KeyboardView from '../../containers/KeyboardView'; import KeyboardView from '../../containers/KeyboardView';
import { TSupportedPermissions } from '../../reducers/permissions'; import { TSupportedPermissions } from '../../reducers/permissions';
import { ModalStackParamList } from '../../stacks/MasterDetailStack/types'; import { ModalStackParamList } from '../../stacks/MasterDetailStack/types';
@ -38,6 +37,8 @@ import sharedStyles from '../Styles';
import styles from './styles'; import styles from './styles';
import SwitchContainer from './SwitchContainer'; import SwitchContainer from './SwitchContainer';
import { compareServerVersion } from '../../lib/methods/helpers/compareServerVersion'; import { compareServerVersion } from '../../lib/methods/helpers/compareServerVersion';
import { getRoomTitle, hasPermission } from '../../lib/methods';
import { Services } from '../../lib/services';
interface IRoomInfoEditViewState { interface IRoomInfoEditViewState {
room: ISubscription; room: ISubscription;
@ -143,7 +144,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
this.init(this.room); this.init(this.room);
}); });
const result = await RocketChat.hasPermission( const result = await hasPermission(
[ [
setReadOnlyPermission, setReadOnlyPermission,
setReactWhenReadOnlyPermission, setReactWhenReadOnlyPermission,
@ -179,7 +180,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
// fake password just to user knows about it // fake password just to user knows about it
this.setState({ this.setState({
room, room,
name: RocketChat.getRoomTitle(room), name: getRoomTitle(room),
description, description,
topic, topic,
announcement, announcement,
@ -320,7 +321,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
} }
try { try {
await RocketChat.saveRoomSettings(room.rid, params); await Services.saveRoomSettings(room.rid, params);
} catch (e: any) { } catch (e: any) {
if (e.error === 'error-invalid-room-name') { if (e.error === 'error-invalid-room-name') {
this.setState({ nameError: e }); this.setState({ nameError: e });
@ -359,7 +360,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
const permissionType = teamChannels[i].t === 'c' ? deleteCPermission : deletePPermission; const permissionType = teamChannels[i].t === 'c' ? deleteCPermission : deletePPermission;
// @ts-ignore - wm schema type error dont including array // @ts-ignore - wm schema type error dont including array
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
const permissions = await RocketChat.hasPermission([permissionType], teamChannels[i].rid); const permissions = await hasPermission([permissionType], teamChannels[i].rid);
if (permissions[0]) { if (permissions[0]) {
// @ts-ignore - wm schema type error dont including array // @ts-ignore - wm schema type error dont including array
teamChannelOwner.push(teamChannels[i]); teamChannelOwner.push(teamChannels[i]);
@ -373,7 +374,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
infoText: 'Select_channels_to_delete', infoText: 'Select_channels_to_delete',
nextAction: (selected: string[]) => { nextAction: (selected: string[]) => {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('You_are_deleting_the_team', { team: RocketChat.getRoomTitle(room) }), message: I18n.t('You_are_deleting_the_team', { team: getRoomTitle(room) }),
confirmationText: I18n.t('Yes_action_it', { action: I18n.t('delete') }), confirmationText: I18n.t('Yes_action_it', { action: I18n.t('delete') }),
onPress: () => deleteRoom(ERoomType.t, room, selected) onPress: () => deleteRoom(ERoomType.t, room, selected)
}); });
@ -381,7 +382,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
}); });
} else { } else {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('You_are_deleting_the_team', { team: RocketChat.getRoomTitle(room) }), message: I18n.t('You_are_deleting_the_team', { team: getRoomTitle(room) }),
confirmationText: I18n.t('Yes_action_it', { action: I18n.t('delete') }), confirmationText: I18n.t('Yes_action_it', { action: I18n.t('delete') }),
onPress: () => dispatch(deleteRoom(ERoomType.t, room)) onPress: () => dispatch(deleteRoom(ERoomType.t, room))
}); });
@ -436,7 +437,7 @@ class RoomInfoEditView extends React.Component<IRoomInfoEditViewProps, IRoomInfo
onPress: async () => { onPress: async () => {
try { try {
logEvent(events.RI_EDIT_TOGGLE_ARCHIVE); logEvent(events.RI_EDIT_TOGGLE_ARCHIVE);
await RocketChat.toggleArchiveRoom(rid, t as SubscriptionType, !archived); await Services.toggleArchiveRoom(rid, t as SubscriptionType, !archived);
} catch (e) { } catch (e) {
logEvent(events.RI_EDIT_TOGGLE_ARCHIVE_F); logEvent(events.RI_EDIT_TOGGLE_ARCHIVE_F);
log(e); log(e);

View File

@ -1,7 +1,6 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { StyleSheet, Text } from 'react-native'; import { StyleSheet, Text } from 'react-native';
import RocketChat from '../../lib/rocketchat';
import { TSupportedThemes, useTheme } from '../../theme'; import { TSupportedThemes, useTheme } from '../../theme';
import sharedStyles from '../Styles'; import sharedStyles from '../Styles';
import { themes } from '../../lib/constants'; import { themes } from '../../lib/constants';
@ -12,6 +11,7 @@ import CustomFields from './CustomFields';
import Item from './Item'; import Item from './Item';
import Timezone from './Timezone'; import Timezone from './Timezone';
import { ILivechatDepartment } from '../../definitions/ILivechatDepartment'; import { ILivechatDepartment } from '../../definitions/ILivechatDepartment';
import { Services } from '../../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
title: { title: {
@ -31,7 +31,7 @@ const Livechat = ({ room, roomUser }: { room: ISubscription; roomUser: ILivechat
const getDepartment = async (id: string) => { const getDepartment = async (id: string) => {
if (id) { if (id) {
const result = await RocketChat.getDepartmentInfo(id); const result = await Services.getDepartmentInfo(id);
if (result.success) { if (result.success) {
setDepartment(result.department as ILivechatDepartment); setDepartment(result.department as ILivechatDepartment);
} }

View File

@ -12,7 +12,6 @@ import { CustomIcon } from '../../lib/Icons';
import Status from '../../containers/Status'; import Status from '../../containers/Status';
import Avatar from '../../containers/Avatar'; import Avatar from '../../containers/Avatar';
import sharedStyles from '../Styles'; import sharedStyles from '../Styles';
import RocketChat from '../../lib/rocketchat';
import RoomTypeIcon from '../../containers/RoomTypeIcon'; import RoomTypeIcon from '../../containers/RoomTypeIcon';
import I18n from '../../i18n'; import I18n from '../../i18n';
import * as HeaderButton from '../../containers/HeaderButton'; import * as HeaderButton from '../../containers/HeaderButton';
@ -34,6 +33,8 @@ import { ChatsStackParamList } from '../../stacks/types';
import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types'; import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types';
import { SubscriptionType, TSubscriptionModel, ISubscription, IUser, IApplicationState } from '../../definitions'; import { SubscriptionType, TSubscriptionModel, ISubscription, IUser, IApplicationState } from '../../definitions';
import { ILivechatVisitor } from '../../definitions/ILivechatVisitor'; import { ILivechatVisitor } from '../../definitions/ILivechatVisitor';
import { callJitsi, getRoomTitle, getUidDirectMessage, hasPermission } from '../../lib/methods';
import { Services } from '../../lib/services';
interface IGetRoomTitle { interface IGetRoomTitle {
room: ISubscription; room: ISubscription;
@ -44,7 +45,7 @@ interface IGetRoomTitle {
theme: TSupportedThemes; theme: TSupportedThemes;
} }
const getRoomTitle = ({ room, type, name, username, statusText, theme }: IGetRoomTitle) => const renderRoomTitle = ({ room, type, name, username, statusText, theme }: IGetRoomTitle) =>
type === SubscriptionType.DIRECT ? ( type === SubscriptionType.DIRECT ? (
<> <>
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]}> <Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]}>
@ -71,7 +72,7 @@ const getRoomTitle = ({ room, type, name, username, statusText, theme }: IGetRoo
sourceType={room.source} sourceType={room.source}
/> />
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]} key='room-info-name'> <Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]} key='room-info-name'>
{RocketChat.getRoomTitle(room)} {getRoomTitle(room)}
</Text> </Text>
</View> </View>
); );
@ -203,7 +204,7 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
const { room } = this.state; const { room } = this.state;
try { try {
if (room.visitor?._id) { if (room.visitor?._id) {
const result = await RocketChat.getVisitorInfo(room.visitor._id); const result = await Services.getVisitorInfo(room.visitor._id);
if (result.success) { if (result.success) {
const { visitor } = result; const { visitor } = result;
const params: { os?: string; browser?: string } = {}; const params: { os?: string; browser?: string } = {};
@ -234,8 +235,8 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
if (isEmpty(roomUser)) { if (isEmpty(roomUser)) {
try { try {
const roomUserId = RocketChat.getUidDirectMessage(room); const roomUserId = getUidDirectMessage(room);
const result = await RocketChat.getUserInfo(roomUserId); const result = await Services.getUserInfo(roomUserId);
if (result.success) { if (result.success) {
const { user } = result; const { user } = result;
const { roles } = user; const { roles } = user;
@ -276,7 +277,7 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
}); });
} else { } else {
try { try {
const result = await RocketChat.getRoomInfo(this.rid); const result = await Services.getRoomInfo(this.rid);
if (result.success) { if (result.success) {
({ room } = result); ({ room } = result);
this.setState({ room: { ...roomState, ...room } }); this.setState({ room: { ...roomState, ...room } });
@ -288,7 +289,7 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
const permissionToEdit = this.isLivechat ? [editOmnichannelContact, editLivechatRoomCustomfields] : [editRoomPermission]; const permissionToEdit = this.isLivechat ? [editOmnichannelContact, editLivechatRoomCustomfields] : [editRoomPermission];
const permissions = await RocketChat.hasPermission(permissionToEdit, room.rid); const permissions = await hasPermission(permissionToEdit, room.rid);
if (permissions.some(Boolean)) { if (permissions.some(Boolean)) {
this.setState({ showEdit: true }, () => this.setHeader()); this.setState({ showEdit: true }, () => this.setHeader());
} }
@ -309,7 +310,7 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
const { const {
roomUser: { username } roomUser: { username }
} = this.state; } = this.state;
const result = await RocketChat.createDirectMessage(username); const result = await Services.createDirectMessage(username);
if (result.success) { if (result.success) {
const { const {
room: { rid } room: { rid }
@ -329,13 +330,13 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
const { rooms, navigation, isMasterDetail } = this.props; const { rooms, navigation, isMasterDetail } = this.props;
const params = { const params = {
rid: room.rid, rid: room.rid,
name: RocketChat.getRoomTitle({ name: getRoomTitle({
t: room.t, t: room.t,
fname: name, fname: name,
name: username name: username
}), }),
t: room.t, t: room.t,
roomUserId: RocketChat.getUidDirectMessage(room) roomUserId: getUidDirectMessage(room)
}; };
if (room.rid) { if (room.rid) {
@ -356,7 +357,7 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
videoCall = () => { videoCall = () => {
const { room } = this.state; const { room } = this.state;
RocketChat.callJitsi(room); callJitsi(room);
}; };
renderAvatar = (room: ISubscription, roomUser: IUserParsed) => { renderAvatar = (room: ISubscription, roomUser: IUserParsed) => {
@ -431,7 +432,7 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
<View style={[styles.avatarContainer, { backgroundColor: themes[theme].auxiliaryBackground }]}> <View style={[styles.avatarContainer, { backgroundColor: themes[theme].auxiliaryBackground }]}>
{this.renderAvatar(room, roomUser)} {this.renderAvatar(room, roomUser)}
<View style={styles.roomTitleContainer}> <View style={styles.roomTitleContainer}>
{getRoomTitle({ {renderRoomTitle({
room, room,
type: this.t, type: this.t,
name: roomUser?.name, name: roomUser?.name,

View File

@ -18,7 +18,6 @@ import I18n from '../../i18n';
import database from '../../lib/database'; import database from '../../lib/database';
import { CustomIcon } from '../../lib/Icons'; import { CustomIcon } from '../../lib/Icons';
import protectedFunction from '../../lib/methods/helpers/protectedFunction'; import protectedFunction from '../../lib/methods/helpers/protectedFunction';
import RocketChat from '../../lib/rocketchat';
import UserItem from '../../containers/UserItem'; import UserItem from '../../containers/UserItem';
import { getUserSelector } from '../../selectors/login'; import { getUserSelector } from '../../selectors/login';
import { ModalStackParamList } from '../../stacks/MasterDetailStack/types'; import { ModalStackParamList } from '../../stacks/MasterDetailStack/types';
@ -28,8 +27,9 @@ import { goRoom, TGoRoomItem } from '../../utils/goRoom';
import { showConfirmationAlert, showErrorAlert } from '../../utils/info'; import { showConfirmationAlert, showErrorAlert } from '../../utils/info';
import log from '../../utils/log'; import log from '../../utils/log';
import scrollPersistTaps from '../../utils/scrollPersistTaps'; import scrollPersistTaps from '../../utils/scrollPersistTaps';
import { RoomTypes } from '../../lib/methods/roomTypeToApiType'; import { getRoomTitle, hasPermission, isGroupChat, RoomTypes } from '../../lib/methods';
import styles from './styles'; import styles from './styles';
import { Services } from '../../lib/services';
const PAGE_SIZE = 25; const PAGE_SIZE = 25;
@ -110,7 +110,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
this.fetchMembers(); this.fetchMembers();
// @ts-ignore - TODO: room param is wrong // @ts-ignore - TODO: room param is wrong
if (RocketChat.isGroupChat(room)) { if (isGroupChat(room)) {
return; return;
} }
@ -125,7 +125,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
viewAllTeamsPermission viewAllTeamsPermission
} = this.props; } = this.props;
const result = await RocketChat.hasPermission( const result = await hasPermission(
[ [
muteUserPermission, muteUserPermission,
setLeaderPermission, setLeaderPermission,
@ -200,7 +200,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
const [room] = query; const [room] = query;
this.goRoom(room); this.goRoom(room);
} else { } else {
const result = await RocketChat.createDirectMessage(item.username); const result = await Services.createDirectMessage(item.username);
if (result.success) { if (result.success) {
this.goRoom({ rid: result.room?._id as string, name: item.username, t: SubscriptionType.DIRECT }); this.goRoom({ rid: result.room?._id as string, name: item.username, t: SubscriptionType.DIRECT });
} }
@ -215,7 +215,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
const { navigation } = this.props; const { navigation } = this.props;
const { room } = this.state; const { room } = this.state;
const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId as string, userId: selectedUser._id }); const result = await Services.teamListRoomsOfUser({ teamId: room.teamId as string, userId: selectedUser._id });
if (result.success) { if (result.success) {
if (result.rooms?.length) { if (result.rooms?.length) {
@ -255,13 +255,13 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
const { navigation } = this.props; const { navigation } = this.props;
const userId = selectedUser._id; const userId = selectedUser._id;
const result = await RocketChat.removeTeamMember({ const result = await Services.removeTeamMember({
teamId: room.teamId, teamId: room.teamId,
userId, userId,
...(selected && { rooms: selected }) ...(selected && { rooms: selected })
}); });
if (result.success) { if (result.success) {
const message = I18n.t('User_has_been_removed_from_s', { s: RocketChat.getRoomTitle(room) }); const message = I18n.t('User_has_been_removed_from_s', { s: getRoomTitle(room) });
EventEmitter.emit(LISTENER, { message }); EventEmitter.emit(LISTENER, { message });
const newMembers = members.filter(member => member._id !== userId); const newMembers = members.filter(member => member._id !== userId);
const newMembersFiltered = membersFiltered.filter(member => member._id !== userId); const newMembersFiltered = membersFiltered.filter(member => member._id !== userId);
@ -315,7 +315,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
onPress: () => { onPress: () => {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t(`The_user_${userIsMuted ? 'will' : 'wont'}_be_able_to_type_in_roomName`, { message: I18n.t(`The_user_${userIsMuted ? 'will' : 'wont'}_be_able_to_type_in_roomName`, {
roomName: RocketChat.getRoomTitle(room) roomName: getRoomTitle(room)
}), }),
confirmationText: I18n.t(userIsMuted ? 'Unmute' : 'Mute'), confirmationText: I18n.t(userIsMuted ? 'Unmute' : 'Mute'),
onPress: () => this.handleMute(selectedUser) onPress: () => this.handleMute(selectedUser)
@ -404,7 +404,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
danger: true, danger: true,
onPress: () => { onPress: () => {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('The_user_will_be_removed_from_s', { s: RocketChat.getRoomTitle(room) }), message: I18n.t('The_user_will_be_removed_from_s', { s: getRoomTitle(room) }),
confirmationText: I18n.t('Yes_remove_user'), confirmationText: I18n.t('Yes_remove_user'),
onPress: () => this.handleRemoveUserFromRoom(selectedUser) onPress: () => this.handleRemoveUserFromRoom(selectedUser)
}); });
@ -434,7 +434,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
try { try {
const { room } = this.state; const { room } = this.state;
const type = room.t as SubscriptionType.CHANNEL | SubscriptionType.GROUP | SubscriptionType.OMNICHANNEL; const type = room.t as SubscriptionType.CHANNEL | SubscriptionType.GROUP | SubscriptionType.OMNICHANNEL;
const result = await RocketChat.getRoomRoles(room.rid, type); const result = await Services.getRoomRoles(room.rid, type);
if (result?.success) { if (result?.success) {
this.roomRoles = result.roles; this.roomRoles = result.roles;
} }
@ -452,7 +452,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
this.setState({ isLoading: true }); this.setState({ isLoading: true });
try { try {
const membersResult = await RocketChat.getRoomMembers({ const membersResult = await Services.getRoomMembers({
rid, rid,
roomType: t, roomType: t,
type: allUsers ? 'all' : 'online', type: allUsers ? 'all' : 'online',
@ -492,7 +492,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
handleMute = async (user: TUserModel) => { handleMute = async (user: TUserModel) => {
const { rid } = this.state; const { rid } = this.state;
try { try {
await RocketChat.toggleMuteUserInRoom(rid, user?.username, !user?.muted); await Services.toggleMuteUserInRoom(rid, user?.username, !user?.muted);
EventEmitter.emit(LISTENER, { EventEmitter.emit(LISTENER, {
message: I18n.t('User_has_been_key', { key: user?.muted ? I18n.t('unmuted') : I18n.t('muted') }) message: I18n.t('User_has_been_key', { key: user?.muted ? I18n.t('unmuted') : I18n.t('muted') })
}); });
@ -504,7 +504,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
handleOwner = async (selectedUser: TUserModel, isOwner: boolean) => { handleOwner = async (selectedUser: TUserModel, isOwner: boolean) => {
try { try {
const { room } = this.state; const { room } = this.state;
await RocketChat.toggleRoomOwner({ await Services.toggleRoomOwner({
roomId: room.rid, roomId: room.rid,
t: room.t, t: room.t,
userId: selectedUser._id, userId: selectedUser._id,
@ -516,7 +516,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
EventEmitter.emit(LISTENER, { EventEmitter.emit(LISTENER, {
message: I18n.t(message, { message: I18n.t(message, {
username: this.getUserDisplayName(selectedUser), username: this.getUserDisplayName(selectedUser),
room_name: RocketChat.getRoomTitle(room) room_name: getRoomTitle(room)
}) })
}); });
} catch (e) { } catch (e) {
@ -528,7 +528,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
handleLeader = async (selectedUser: TUserModel, isLeader: boolean) => { handleLeader = async (selectedUser: TUserModel, isLeader: boolean) => {
try { try {
const { room } = this.state; const { room } = this.state;
await RocketChat.toggleRoomLeader({ await Services.toggleRoomLeader({
roomId: room.rid, roomId: room.rid,
t: room.t, t: room.t,
userId: selectedUser._id, userId: selectedUser._id,
@ -540,7 +540,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
EventEmitter.emit(LISTENER, { EventEmitter.emit(LISTENER, {
message: I18n.t(message, { message: I18n.t(message, {
username: this.getUserDisplayName(selectedUser), username: this.getUserDisplayName(selectedUser),
room_name: RocketChat.getRoomTitle(room) room_name: getRoomTitle(room)
}) })
}); });
} catch (e) { } catch (e) {
@ -552,7 +552,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
handleModerator = async (selectedUser: TUserModel, isModerator: boolean) => { handleModerator = async (selectedUser: TUserModel, isModerator: boolean) => {
try { try {
const { room } = this.state; const { room } = this.state;
await RocketChat.toggleRoomModerator({ await Services.toggleRoomModerator({
roomId: room.rid, roomId: room.rid,
t: room.t, t: room.t,
userId: selectedUser._id, userId: selectedUser._id,
@ -564,7 +564,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
EventEmitter.emit(LISTENER, { EventEmitter.emit(LISTENER, {
message: I18n.t(message, { message: I18n.t(message, {
username: this.getUserDisplayName(selectedUser), username: this.getUserDisplayName(selectedUser),
room_name: RocketChat.getRoomTitle(room) room_name: getRoomTitle(room)
}) })
}); });
} catch (e) { } catch (e) {
@ -576,7 +576,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
handleIgnore = async (selectedUser: TUserModel, ignore: boolean) => { handleIgnore = async (selectedUser: TUserModel, ignore: boolean) => {
try { try {
const { room } = this.state; const { room } = this.state;
await RocketChat.ignoreUser({ await Services.ignoreUser({
rid: room.rid, rid: room.rid,
userId: selectedUser._id, userId: selectedUser._id,
ignore ignore
@ -593,8 +593,8 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
const { room, members, membersFiltered } = this.state; const { room, members, membersFiltered } = this.state;
const userId = selectedUser._id; const userId = selectedUser._id;
// TODO: interface SubscriptionType on IRoom is wrong // TODO: interface SubscriptionType on IRoom is wrong
await RocketChat.removeUserFromRoom({ roomId: room.rid, t: room.t as RoomTypes, userId }); await Services.removeUserFromRoom({ roomId: room.rid, t: room.t as RoomTypes, userId });
const message = I18n.t('User_has_been_removed_from_s', { s: RocketChat.getRoomTitle(room) }); const message = I18n.t('User_has_been_removed_from_s', { s: getRoomTitle(room) });
EventEmitter.emit(LISTENER, { message }); EventEmitter.emit(LISTENER, { message });
this.setState({ this.setState({
members: members.filter(member => member._id !== userId), members: members.filter(member => member._id !== userId),

View File

@ -6,10 +6,10 @@ import { connect } from 'react-redux';
import I18n from '../../i18n'; import I18n from '../../i18n';
import Button from '../../containers/Button'; import Button from '../../containers/Button';
import TextInput from '../../containers/TextInput'; import TextInput from '../../containers/TextInput';
import RocketChat from '../../lib/rocketchat';
import sharedStyles from '../Styles'; import sharedStyles from '../Styles';
import { themes } from '../../lib/constants'; import { themes } from '../../lib/constants';
import { IApplicationState } from '../../definitions'; import { IApplicationState } from '../../definitions';
import { Services } from '../../lib/services';
import { TSupportedThemes } from '../../theme'; import { TSupportedThemes } from '../../theme';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
@ -60,9 +60,9 @@ const JoinCode = React.memo(
const hide = () => setVisible(false); const hide = () => setVisible(false);
const joinRoom = async () => { const handleJoinRoom = async () => {
try { try {
await RocketChat.joinRoom(rid, code, t as any); await Services.joinRoom(rid, code, t as any);
onJoin(); onJoin();
hide(); hide();
} catch (e) { } catch (e) {
@ -90,7 +90,7 @@ const JoinCode = React.memo(
returnKeyType='send' returnKeyType='send'
autoCapitalize='none' autoCapitalize='none'
onChangeText={setCode} onChangeText={setCode}
onSubmitEditing={joinRoom} onSubmitEditing={handleJoinRoom}
placeholder={I18n.t('Join_Code')} placeholder={I18n.t('Join_Code')}
secureTextEntry secureTextEntry
error={error ? { error: 'error-code-invalid', reason: I18n.t('Code_or_password_invalid') } : undefined} error={error ? { error: 'error-code-invalid', reason: I18n.t('Code_or_password_invalid') } : undefined}
@ -112,7 +112,7 @@ const JoinCode = React.memo(
style={styles.button} style={styles.button}
theme={theme} theme={theme}
testID='join-code-submit' testID='join-code-submit'
onPress={joinRoom} onPress={handleJoinRoom}
/> />
</View> </View>
</View> </View>

View File

@ -12,13 +12,14 @@ import ActivityIndicator from '../../../containers/ActivityIndicator';
import { TAnyMessageModel, TMessageModel, TThreadMessageModel, TThreadModel } from '../../../definitions'; import { TAnyMessageModel, TMessageModel, TThreadMessageModel, TThreadModel } from '../../../definitions';
import database from '../../../lib/database'; import database from '../../../lib/database';
import { compareServerVersion } from '../../../lib/methods/helpers/compareServerVersion'; import { compareServerVersion } from '../../../lib/methods/helpers/compareServerVersion';
import RocketChat from '../../../lib/rocketchat';
import debounce from '../../../utils/debounce'; import debounce from '../../../utils/debounce';
import { animateNextTransition } from '../../../utils/layoutAnimation'; import { animateNextTransition } from '../../../utils/layoutAnimation';
import log from '../../../utils/log'; import log from '../../../utils/log';
import EmptyRoom from '../EmptyRoom'; import EmptyRoom from '../EmptyRoom';
import List, { IListProps } from './List'; import List, { IListProps } from './List';
import NavBottomFAB from './NavBottomFAB'; import NavBottomFAB from './NavBottomFAB';
import { loadMissedMessages, loadThreadMessages } from '../../../lib/methods';
import { Services } from '../../../lib/services';
const QUERY_SIZE = 50; const QUERY_SIZE = 50;
@ -219,7 +220,7 @@ class ListContainer extends React.Component<IListContainerProps, IListContainerS
if (tmid) { if (tmid) {
try { try {
await RocketChat.readThreads(tmid); await Services.readThreads(tmid);
} catch { } catch {
// Do nothing // Do nothing
} }
@ -236,9 +237,9 @@ class ListContainer extends React.Component<IListContainerProps, IListContainerS
if (messages.length) { if (messages.length) {
try { try {
if (tmid) { if (tmid) {
await RocketChat.loadThreadMessages({ tmid, rid }); await loadThreadMessages({ tmid, rid });
} else { } else {
await RocketChat.loadMissedMessages({ rid, lastOpen: moment().subtract(7, 'days').toDate() }); await loadMissedMessages({ rid, lastOpen: moment().subtract(7, 'days').toDate() });
} }
} catch (e) { } catch (e) {
log(e); log(e);

View File

@ -4,7 +4,6 @@ import { Q } from '@nozbe/watermelondb';
import { Observable, Subscription } from 'rxjs'; import { Observable, Subscription } from 'rxjs';
import database from '../../lib/database'; import database from '../../lib/database';
import RocketChat from '../../lib/rocketchat';
import log from '../../utils/log'; import log from '../../utils/log';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { CustomIcon } from '../../lib/Icons'; import { CustomIcon } from '../../lib/Icons';
@ -12,6 +11,7 @@ import { themes } from '../../lib/constants';
import sharedStyles from '../Styles'; import sharedStyles from '../Styles';
import { TSupportedThemes, withTheme } from '../../theme'; import { TSupportedThemes, withTheme } from '../../theme';
import { IUser, TUploadModel } from '../../definitions'; import { IUser, TUploadModel } from '../../definitions';
import { cancelUpload, isUploadActive, sendFileMessage } from '../../lib/methods';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -114,7 +114,7 @@ class UploadProgress extends Component<IUploadProgressProps, IUploadProgressStat
this.ranInitialUploadCheck = true; this.ranInitialUploadCheck = true;
const { uploads } = this.state; const { uploads } = this.state;
uploads.forEach(async u => { uploads.forEach(async u => {
if (!RocketChat.isUploadActive(u.path)) { if (!isUploadActive(u.path)) {
try { try {
const db = database.active; const db = database.active;
await db.write(async () => { await db.write(async () => {
@ -140,9 +140,9 @@ class UploadProgress extends Component<IUploadProgressProps, IUploadProgressStat
} }
}; };
cancelUpload = async (item: TUploadModel) => { handleCancelUpload = async (item: TUploadModel) => {
try { try {
await RocketChat.cancelUpload(item); await cancelUpload(item);
} catch (e) { } catch (e) {
log(e); log(e);
} }
@ -158,7 +158,7 @@ class UploadProgress extends Component<IUploadProgressProps, IUploadProgressStat
item.error = false; item.error = false;
}); });
}); });
await RocketChat.sendFileMessage(rid, item, undefined, server, user); await sendFileMessage(rid, item, undefined, server, user);
} catch (e) { } catch (e) {
log(e); log(e);
} }
@ -176,7 +176,7 @@ class UploadProgress extends Component<IUploadProgressProps, IUploadProgressStat
numberOfLines={1}> numberOfLines={1}>
{I18n.t('Uploading')} {item.name} {I18n.t('Uploading')} {item.name}
</Text> </Text>
<CustomIcon name='close' size={20} color={themes[theme!].auxiliaryText} onPress={() => this.cancelUpload(item)} /> <CustomIcon name='close' size={20} color={themes[theme!].auxiliaryText} onPress={() => this.handleCancelUpload(item)} />
</View>, </View>,
<View <View
key='progress' key='progress'

View File

@ -13,7 +13,6 @@ import { IReduxEmoji } from '../../definitions/IEmoji';
import Touch from '../../utils/touch'; import Touch from '../../utils/touch';
import { replyBroadcast } from '../../actions/messages'; import { replyBroadcast } from '../../actions/messages';
import database from '../../lib/database'; import database from '../../lib/database';
import RocketChat from '../../lib/rocketchat';
import Message from '../../containers/message'; import Message from '../../containers/message';
import MessageActions, { IMessageActions } from '../../containers/MessageActions'; import MessageActions, { IMessageActions } from '../../containers/MessageActions';
import MessageErrorActions from '../../containers/MessageErrorActions'; import MessageErrorActions from '../../containers/MessageErrorActions';
@ -81,6 +80,19 @@ import {
} from '../../definitions'; } from '../../definitions';
import { ICustomEmojis } from '../../reducers/customEmojis'; import { ICustomEmojis } from '../../reducers/customEmojis';
import { E2E_MESSAGE_TYPE, E2E_STATUS, MESSAGE_TYPE_ANY_LOAD, MessageTypeLoad, themes } from '../../lib/constants'; import { E2E_MESSAGE_TYPE, E2E_STATUS, MESSAGE_TYPE_ANY_LOAD, MessageTypeLoad, themes } from '../../lib/constants';
import {
callJitsi,
canAutoTranslate as canAutoTranslateMethod,
getRoomTitle,
getUidDirectMessage,
isGroupChat,
loadSurroundingMessages,
loadThreadMessages,
readMessages,
sendMessage,
triggerBlockAction
} from '../../lib/methods';
import { Services } from '../../lib/services';
const stateAttrsUpdate = [ const stateAttrsUpdate = [
'joined', 'joined',
@ -213,7 +225,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
}; };
this.jumpToMessageId = props.route.params?.jumpToMessageId; this.jumpToMessageId = props.route.params?.jumpToMessageId;
this.jumpToThreadId = props.route.params?.jumpToThreadId; this.jumpToThreadId = props.route.params?.jumpToThreadId;
const roomUserId = props.route.params?.roomUserId ?? RocketChat.getUidDirectMessage(room); const roomUserId = props.route.params?.roomUserId ?? getUidDirectMessage(room);
this.state = { this.state = {
joined: true, joined: true,
room, room,
@ -431,15 +443,15 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
} }
const prid = room?.prid; const prid = room?.prid;
const isGroupChat = RocketChat.isGroupChat(room as ISubscription); const isGroupChatConst = isGroupChat(room as ISubscription);
let title = route.params?.name; let title = route.params?.name;
let parentTitle = ''; let parentTitle = '';
// TODO: I think it's safe to remove this, but we need to test tablet without rooms // TODO: I think it's safe to remove this, but we need to test tablet without rooms
if (!tmid) { if (!tmid) {
title = RocketChat.getRoomTitle(room); title = getRoomTitle(room);
} }
if (tmid) { if (tmid) {
parentTitle = RocketChat.getRoomTitle(room); parentTitle = getRoomTitle(room);
} }
let subtitle: string | undefined; let subtitle: string | undefined;
let t: string; let t: string;
@ -510,7 +522,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
type={t} type={t}
roomUserId={roomUserId} roomUserId={roomUserId}
visitor={visitor} visitor={visitor}
isGroupChat={isGroupChat} isGroupChat={isGroupChatConst}
onPress={this.goRoomActionsView} onPress={this.goRoomActionsView}
testID={`room-view-title-${title}`} testID={`room-view-title-${title}`}
sourceType={sourceType} sourceType={sourceType}
@ -576,7 +588,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
return; return;
} }
if (this.tmid) { if (this.tmid) {
await RoomServices.getThreadMessages(this.tmid, this.rid); await loadThreadMessages({ tmid: this.tmid, rid: this.rid });
} else { } else {
const newLastOpen = new Date(); const newLastOpen = new Date();
await RoomServices.getMessages(room); await RoomServices.getMessages(room);
@ -588,11 +600,11 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
} else { } else {
this.setLastOpen(null); this.setLastOpen(null);
} }
RoomServices.readMessages(room.rid, newLastOpen).catch(e => console.log(e)); readMessages(room.rid, newLastOpen, true).catch(e => console.log(e));
} }
} }
const canAutoTranslate = RocketChat.canAutoTranslate(); const canAutoTranslate = canAutoTranslateMethod();
const member = await this.getRoomMember(); const member = await this.getRoomMember();
this.setState({ canAutoTranslate, member, loading: false }); this.setState({ canAutoTranslate, member, loading: false });
@ -611,12 +623,12 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
const { room } = this.state; const { room } = this.state;
const { t } = room; const { t } = room;
if ('id' in room && t === 'd' && !RocketChat.isGroupChat(room)) { if ('id' in room && t === 'd' && !isGroupChat(room)) {
try { try {
const roomUserId = RocketChat.getUidDirectMessage(room); const roomUserId = getUidDirectMessage(room);
this.setState({ roomUserId }, () => this.setHeader()); this.setState({ roomUserId }, () => this.setHeader());
const result = await RocketChat.getUserInfo(roomUserId); const result = await Services.getUserInfo(roomUserId);
if (result.success) { if (result.success) {
return result.user; return result.user;
} }
@ -706,7 +718,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
onEditRequest = async (message: TAnyMessageModel) => { onEditRequest = async (message: TAnyMessageModel) => {
this.setState({ selectedMessage: undefined, editing: false }); this.setState({ selectedMessage: undefined, editing: false });
try { try {
await RocketChat.editMessage(message); await Services.editMessage(message);
} catch (e) { } catch (e) {
log(e); log(e);
} }
@ -745,7 +757,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
onReactionPress = async (shortname: string, messageId: string) => { onReactionPress = async (shortname: string, messageId: string) => {
try { try {
await RocketChat.setReaction(shortname, messageId); await Services.setReaction(shortname, messageId);
this.onReactionClose(); this.onReactionClose();
Review.pushPositiveEvent(); Review.pushPositiveEvent();
} catch (e) { } catch (e) {
@ -858,10 +870,10 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
} else { } else {
/** /**
* if it's from server, we don't have it saved locally and so we fetch surroundings * if it's from server, we don't have it saved locally and so we fetch surroundings
* we test if it's not from threads because we're fetching from threads currently with `getThreadMessages` * we test if it's not from threads because we're fetching from threads currently with `loadThreadMessages`
*/ */
if (message.fromServer && !message.tmid && this.rid) { if (message.fromServer && !message.tmid && this.rid) {
await RocketChat.loadSurroundingMessages({ messageId, rid: this.rid }); await loadSurroundingMessages({ messageId, rid: this.rid });
} }
// @ts-ignore // @ts-ignore
await Promise.race([this.list.current.jumpToMessage(message.id), new Promise(res => setTimeout(res, 5000))]); await Promise.race([this.list.current.jumpToMessage(message.id), new Promise(res => setTimeout(res, 5000))]);
@ -890,7 +902,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
if (rid === this.rid) { if (rid === this.rid) {
Navigation.navigate('RoomsListView'); Navigation.navigate('RoomsListView');
!this.isOmnichannel && !this.isOmnichannel &&
showErrorAlert(I18n.t('You_were_removed_from_channel', { channel: RocketChat.getRoomTitle(room) }), I18n.t('Oops')); showErrorAlert(I18n.t('You_were_removed_from_channel', { channel: getRoomTitle(room) }), I18n.t('Oops'));
} }
}; };
@ -902,11 +914,11 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
this.setState(...args); this.setState(...args);
}; };
sendMessage = (message: string, tmid?: string, tshow?: boolean) => { handleSendMessage = (message: string, tmid?: string, tshow?: boolean) => {
logEvent(events.ROOM_SEND_MESSAGE); logEvent(events.ROOM_SEND_MESSAGE);
const { rid } = this.state.room; const { rid } = this.state.room;
const { user } = this.props; const { user } = this.props;
RocketChat.sendMessage(rid, message, this.tmid || tmid, user, tshow).then(() => { sendMessage(rid, message, this.tmid || tmid, user, tshow).then(() => {
if (this.list && this.list.current) { if (this.list && this.list.current) {
// @ts-ignore // @ts-ignore
this.list.current.update(); this.list.current.update();
@ -950,7 +962,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
// @ts-ignore // @ts-ignore
this.joinCode.current?.show(); this.joinCode.current?.show();
} else { } else {
await RocketChat.joinRoom(rid, null, this.t as any); await Services.joinRoom(rid, null, this.t as any);
this.onJoin(); this.onJoin();
} }
} }
@ -986,7 +998,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
if (!threadMessageId) { if (!threadMessageId) {
return; return;
} }
await RocketChat.toggleFollowMessage(threadMessageId, !isFollowingThread); await Services.toggleFollowMessage(threadMessageId, !isFollowingThread);
EventEmitter.emit(LISTENER, { message: isFollowingThread ? I18n.t('Unfollowed_thread') : I18n.t('Following_thread') }); EventEmitter.emit(LISTENER, { message: isFollowingThread ? I18n.t('Unfollowed_thread') : I18n.t('Following_thread') });
} catch (e) { } catch (e) {
log(e); log(e);
@ -1072,14 +1084,14 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
}); });
}; };
callJitsi = () => { handleCallJitsi = () => {
const { room } = this.state; const { room } = this.state;
if ('id' in room) { if ('id' in room) {
const { jitsiTimeout } = room; const { jitsiTimeout } = room;
if (jitsiTimeout && jitsiTimeout < new Date()) { if (jitsiTimeout && jitsiTimeout < new Date()) {
showErrorAlert(I18n.t('Call_already_ended')); showErrorAlert(I18n.t('Call_already_ended'));
} else { } else {
RocketChat.callJitsi(room); callJitsi(room);
} }
} }
}; };
@ -1121,7 +1133,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
rid: string; rid: string;
mid: string; mid: string;
}) => }) =>
RocketChat.triggerBlockAction({ triggerBlockAction({
blockId, blockId,
actionId, actionId,
value, value,
@ -1214,7 +1226,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
onEncryptedPress={this.onEncryptedPress} onEncryptedPress={this.onEncryptedPress}
onDiscussionPress={this.onDiscussionPress} onDiscussionPress={this.onDiscussionPress}
onThreadPress={this.onThreadPress} onThreadPress={this.onThreadPress}
onAnswerButtonPress={this.sendMessage} onAnswerButtonPress={this.handleSendMessage}
showAttachment={this.showAttachment} showAttachment={this.showAttachment}
reactionInit={this.onReactionInit} reactionInit={this.onReactionInit}
replyBroadcast={this.replyBroadcast} replyBroadcast={this.replyBroadcast}
@ -1228,7 +1240,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
autoTranslateLanguage={'id' in room ? room.autoTranslateLanguage : undefined} autoTranslateLanguage={'id' in room ? room.autoTranslateLanguage : undefined}
navToRoomInfo={this.navToRoomInfo} navToRoomInfo={this.navToRoomInfo}
getCustomEmoji={this.getCustomEmoji} getCustomEmoji={this.getCustomEmoji}
callJitsi={this.callJitsi} callJitsi={this.handleCallJitsi}
blockAction={this.blockAction} blockAction={this.blockAction}
threadBadgeColor={this.getBadgeColor(item?.id)} threadBadgeColor={this.getBadgeColor(item?.id)}
toggleFollowThread={this.toggleFollowThread} toggleFollowThread={this.toggleFollowThread}
@ -1319,7 +1331,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
return ( return (
<MessageBox <MessageBox
ref={this.messagebox} ref={this.messagebox}
onSubmit={this.sendMessage} onSubmit={this.handleSendMessage}
rid={this.rid} rid={this.rid}
tmid={this.tmid} tmid={this.tmid}
roomType={room.t} roomType={room.t}

View File

@ -1,5 +1,4 @@
import loadMessagesForRoom from '../../../lib/methods/loadMessagesForRoom'; import { loadMessagesForRoom, loadMissedMessages } from '../../../lib/methods';
import loadMissedMessages from '../../../lib/methods/loadMissedMessages';
// TODO: clarify latest vs lastOpen // TODO: clarify latest vs lastOpen
const getMessages = ({ const getMessages = ({
@ -20,4 +19,5 @@ const getMessages = ({
} }
return loadMessagesForRoom({ rid, t: t as any, latest, loaderItem }); return loadMessagesForRoom({ rid, t: t as any, latest, loaderItem });
}; };
export default getMessages; export default getMessages;

View File

@ -1,6 +1,5 @@
import { SubscriptionType, TAnyMessageModel } from '../../../definitions'; import { SubscriptionType, TAnyMessageModel } from '../../../definitions';
import loadMessagesForRoom from '../../../lib/methods/loadMessagesForRoom'; import { loadNextMessages, loadMessagesForRoom } from '../../../lib/methods';
import loadNextMessages from '../../../lib/methods/loadNextMessages';
import { MessageTypeLoad } from '../../../lib/constants'; import { MessageTypeLoad } from '../../../lib/constants';
const getMoreMessages = ({ const getMoreMessages = ({
@ -33,4 +32,5 @@ const getMoreMessages = ({
} }
return Promise.resolve(); return Promise.resolve();
}; };
export default getMoreMessages; export default getMoreMessages;

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