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 random from '../utils/random';
import { events, logEvent } from '../utils/log';
import RocketChat from '../lib/rocketchat';
import { CustomIcon } from '../lib/Icons';
import { IServices } from '../selectors/login';
import { OutsideParamList } from '../stacks/types';
import { IApplicationState } from '../definitions';
import { Services } from '../lib/services';
const BUTTON_HEIGHT = 48;
const SERVICE_HEIGHT = 58;
@ -248,7 +248,7 @@ class LoginServices extends React.PureComponent<ILoginServicesProps, ILoginServi
AppleAuthentication.AppleAuthenticationScope.EMAIL
]
});
await RocketChat.loginOAuthOrSso({ fullName, email, identityToken });
await Services.loginOAuthOrSso({ fullName, email, identityToken });
} catch {
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 moment from 'moment';
import RocketChat from '../../lib/rocketchat';
import database from '../../lib/database';
import I18n from '../../i18n';
import log, { logEvent } from '../../utils/log';
@ -17,6 +16,8 @@ import { TActionSheetOptionsItem, useActionSheet } from '../ActionSheet';
import Header, { HEADER_HEIGHT, IHeader } from './Header';
import events from '../../utils/log/events';
import { IApplicationState, ILoggedUser, TAnyMessageModel, TSubscriptionModel } from '../../definitions';
import { getPermalinkMessage, hasPermission } from '../../lib/methods';
import { Services } from '../../lib/services';
export interface IMessageActions {
room: TSubscriptionModel;
@ -81,7 +82,7 @@ const MessageActions = React.memo(
const getPermissions = async () => {
try {
const permission = [editMessagePermission, deleteMessagePermission, forceDeleteMessagePermission, pinMessagePermission];
const result = await RocketChat.hasPermission(permission, room.rid);
const result = await hasPermission(permission, room.rid);
permissions = {
hasEditPermission: result[0],
hasDeletePermission: result[1],
@ -150,7 +151,7 @@ const MessageActions = React.memo(
return true;
};
const getPermalink = (message: TAnyMessageModel) => RocketChat.getPermalinkMessage(message);
const getPermalink = (message: TAnyMessageModel) => getPermalinkMessage(message);
const handleReply = (message: TAnyMessageModel) => {
logEvent(events.ROOM_MSG_ACTION_REPLY);
@ -178,7 +179,7 @@ const MessageActions = React.memo(
const { rid } = room;
try {
const db = database.active;
const result = await RocketChat.markAsUnread({ messageId });
const result = await Services.markAsUnread({ messageId });
if (result.success) {
const subCollection = db.get('subscriptions');
const subRecord = await subCollection.find(rid);
@ -234,7 +235,7 @@ const MessageActions = React.memo(
const handleStar = async (message: TAnyMessageModel) => {
logEvent(message.starred ? events.ROOM_MSG_ACTION_UNSTAR : events.ROOM_MSG_ACTION_STAR);
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') });
} catch (e) {
logEvent(events.ROOM_MSG_ACTION_STAR_F);
@ -245,7 +246,7 @@ const MessageActions = React.memo(
const handlePin = async (message: TAnyMessageModel) => {
logEvent(events.ROOM_MSG_ACTION_PIN);
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) {
logEvent(events.ROOM_MSG_ACTION_PIN_F);
log(e);
@ -292,7 +293,7 @@ const MessageActions = React.memo(
u: message.u,
msg: message.msg
};
await RocketChat.translateMessage(m, room.autoTranslateLanguage);
await Services.translateMessage(m, room.autoTranslateLanguage);
}
} catch (e) {
log(e);
@ -302,7 +303,7 @@ const MessageActions = React.memo(
const handleReport = async (message: TAnyMessageModel) => {
logEvent(events.ROOM_MSG_ACTION_REPORT);
try {
await RocketChat.reportMessage(message.id);
await Services.reportMessage(message.id);
Alert.alert(I18n.t('Message_Reported'));
} catch (e) {
logEvent(events.ROOM_MSG_ACTION_REPORT_F);
@ -317,7 +318,7 @@ const MessageActions = React.memo(
onPress: async () => {
try {
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) {
logEvent(events.ROOM_MSG_ACTION_DELETE_F);
log(e);

View File

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

View File

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

View File

@ -13,9 +13,9 @@ import { useTheme } from '../../theme';
import { themes } from '../../lib/constants';
import Button from '../Button';
import sharedStyles from '../../views/Styles';
import RocketChat from '../../lib/rocketchat';
import styles from './styles';
import { IApplicationState } from '../../definitions';
import { Services } from '../../lib/services';
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 isEmail = data.method === 'email';
const sendEmail = () => RocketChat.sendEmailCode();
const sendEmail = () => Services.sendEmailCode();
useDeepCompareEffect(() => {
if (!isEmpty(data)) {

View File

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

View File

@ -1,9 +1,10 @@
import log from '../../../../utils/log';
import { store } from '../../../../lib/store/auxStore';
import RocketChat from '../../../../lib/rocketchat';
import { inquiryQueueAdd, inquiryQueueRemove, inquiryQueueUpdate, inquiryRequest } from '../../actions/inquiry';
import sdk from '../../../../lib/services/sdk';
import { IOmnichannelRoom } from '../../../../definitions';
import { hasRole } from '../../../../lib/methods';
import { Services } from '../../../../lib/services';
interface IArgsQueueOmnichannel extends IOmnichannelRoom {
type: string;
@ -81,11 +82,11 @@ export default function subscribeInquiry() {
throw new Error('inquiry: @subscribeInquiry user.id not found');
}
RocketChat.getAgentDepartments(user.id).then(result => {
Services.getAgentDepartments(user.id).then(result => {
if (result.success) {
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));
}

View File

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

View File

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

View File

@ -1,36 +1,36 @@
import React from 'react';
import { Dimensions, Linking } from 'react-native';
import { AppearanceProvider } from 'react-native-appearance';
import { Provider } from 'react-redux';
import { KeyCommandsEmitter } from 'react-native-keycommands';
import { initialWindowMetrics, SafeAreaProvider } from 'react-native-safe-area-context';
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 { 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 { 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 { 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();
initStore(store);
@ -193,10 +193,10 @@ export default class Root extends React.Component<{}, IState> {
};
initCrashReport = () => {
RocketChat.getAllowCrashReport().then(allowCrashReport => {
getAllowCrashReport().then(allowCrashReport => {
toggleCrashErrorsReport(allowCrashReport);
});
RocketChat.getAllowAnalyticsEvents().then(allowAnalyticsEvents => {
getAllowAnalyticsEvents().then(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 ANALYTICS_EVENTS_KEY = 'RC_ANALYTICS_EVENTS_KEY';
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 { Q, Model } from '@nozbe/watermelondb';
import RocketChat from '../rocketchat';
import UserPreferences from '../methods/userPreferences';
import database from '../database';
import protectedFunction from '../methods/helpers/protectedFunction';
@ -21,6 +20,7 @@ import {
E2E_RANDOM_PASSWORD_KEY,
E2E_STATUS
} from '../constants';
import { Services } from '../services';
class Encryption {
ready: boolean;
@ -141,10 +141,10 @@ class Encryption {
const encodedPrivateKey = await this.encodePrivateKey(EJSON.stringify(privateKey), password, userId);
// 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
await RocketChat.e2eRequestSubscriptionKeys();
await Services.e2eRequestSubscriptionKeys();
};
// Encode a private key before send it to the server
@ -197,7 +197,7 @@ class Encryption {
const publicKey = UserPreferences.getString(`${server}-${E2E_PUBLIC_KEY}`);
// 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

View File

@ -4,7 +4,6 @@ import SimpleCrypto from 'react-native-simple-crypto';
import ByteBuffer from 'bytebuffer';
import { IMessage } from '../../definitions';
import RocketChat from '../rocketchat';
import Deferred from '../../utils/deferred';
import debounce from '../../utils/debounce';
import database from '../database';
@ -22,6 +21,7 @@ import {
import { Encryption } from './index';
import { IUser } from '../../definitions/IUser';
import { E2E_MESSAGE_TYPE, E2E_STATUS } from '../constants';
import { Services } from '../services';
export default class EncryptionRoom {
ready: boolean;
@ -134,7 +134,7 @@ export default class EncryptionRoom {
this.sessionKeyExportedString = EJSON.stringify(sessionKeyExported);
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();
};
@ -147,7 +147,7 @@ export default class EncryptionRoom {
// this will be called again and run once in 5 seconds
requestRoomKey = debounce(
async (e2eKeyId: string) => {
await RocketChat.e2eRequestRoomKey(this.roomId, e2eKeyId);
await Services.e2eRequestRoomKey(this.roomId, e2eKeyId);
},
5000,
true
@ -155,7 +155,7 @@ export default class EncryptionRoom {
// Create an encrypted key for this room based on users
encryptRoomKey = async () => {
const result = await RocketChat.e2eGetUsersOfRoomWithoutKey(this.roomId);
const result = await Services.e2eGetUsersOfRoomWithoutKey(this.roomId);
if (result.success) {
const { users } = result;
await Promise.all(users.map(user => this.encryptRoomKeyForUser(user)));
@ -168,7 +168,7 @@ export default class EncryptionRoom {
const { public_key: publicKey } = user.e2e;
const userKey = await SimpleCrypto.RSA.importKey(EJSON.parse(publicKey));
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 { TRocketChat } from '../../definitions/IRocketChat';
import EventEmitter from '../../utils/events';
import fetch from '../../utils/fetch';
import random from '../../utils/random';
@ -82,10 +81,7 @@ export const handlePayloadUserInteraction = (
return ModalActions.CLOSE;
};
export function triggerAction(
this: TRocketChat,
{ type, actionId, appId, rid, mid, viewId, container, ...rest }: ITriggerAction
) {
export function triggerAction({ type, actionId, appId, rid, mid, viewId, container, ...rest }: ITriggerAction) {
return new Promise<ModalActions | undefined | void>(async (resolve, reject) => {
const triggerId = generateTriggerId(appId);

View File

@ -1,8 +1,8 @@
import { ERoomTypes } from '../../definitions';
import { store } from '../store/auxStore';
import database from '../database';
import RocketChat from '../rocketchat';
import sdk from '../services/sdk';
import { Services } from '../services';
const restTypes = {
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 the dm already exists it'll return the existent
if (type === ERoomTypes.DIRECT && !rid) {
const result = await RocketChat.createDirectMessage(name);
const result = await Services.createDirectMessage(name);
if (result.success) {
const { room } = result;
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 {
const db = database.active;
const subsCollection = db.get('subscriptions');

View File

@ -1,6 +1,6 @@
import database from '../database';
export default async function clearCache({ server }: { server: string }): Promise<void> {
export async function clearCache({ server }: { server: string }): Promise<void> {
try {
const serversDB = database.servers;
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() {
const { enterpriseModules } = reduxStore.getState();
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 { store } from '../store/auxStore';
import { isGroupChat } from './helpers';
import getRoom from './getRoom';
import { getRoom } from './getRoom';
type TRoomType = 'p' | 'c' | 'd';

View File

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

View File

@ -1,6 +1,6 @@
import { IServerSubscription, RoomType } from '../../definitions';
import { getSubscriptionByRoomId } from '../database/services/Subscription';
import RocketChat from '../rocketchat';
import { Services } from '../services';
export interface IRoomInfoResult {
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) {
return {
rid,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,7 @@
// @ts-nocheck - TEMP
import AsyncStorage from '@react-native-community/async-storage';
import log from '../../utils/log';
import { store as reduxStore } from '../store/auxStore';
import database from '../database';
import subscribeRoomsTmp from './subscriptions/rooms';
import { ANALYTICS_EVENTS_KEY, CRASH_REPORT_KEY, defaultSettings } from '../constants';
export function isGroupChat(room): boolean {
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;
}
// 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) {
let roomRoles = [];
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 log from '../../utils/log';
import { getMessageById } from '../database/services/Message';
import roomTypeToApiType, { RoomTypes } from './roomTypeToApiType';
import { RoomTypes, roomTypeToApiType } from './roomTypeToApiType';
import sdk from '../services/sdk';
import updateMessages from './updateMessages';
import { generateLoadMoreId } from './helpers/generateLoadMoreId';
@ -30,7 +30,7 @@ async function load({ rid: roomId, latest, t }: { rid: string; latest?: Date; t:
return data.messages;
}
export default function loadMessagesForRoom(args: {
export function loadMessagesForRoom(args: {
rid: string;
t: RoomTypes;
latest?: Date;

View File

@ -29,7 +29,7 @@ async function load({ rid: roomId, lastOpen }: { rid: string; lastOpen?: Date })
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) => {
try {
const data = await load({ rid: args.rid, lastOpen: args.lastOpen });

View File

@ -19,7 +19,7 @@ interface ILoadNextMessages {
loaderItem: TMessageModel;
}
export default function loadNextMessages(args: ILoadNextMessages): Promise<void> {
export function loadNextMessages(args: ILoadNextMessages): Promise<void> {
return new Promise(async (resolve, reject) => {
try {
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;
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) => {
try {
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) => {
try {
let data = await load({ tmid });

View File

@ -10,14 +10,14 @@ import { isSsl } from '../../utils/url';
import log from '../../utils/log';
import { ICertificate, IRocketChat } from '../../definitions';
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 RocketChat from '../rocketchat';
import { Services } from '../services';
function removeServerKeys({ server, userId }: { server: string; userId?: string | null }) {
UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${server}`);
UserPreferences.removeItem(`${TOKEN_KEY}-${server}`);
if (userId) {
UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${userId}`);
UserPreferences.removeItem(`${TOKEN_KEY}-${userId}`);
}
UserPreferences.removeItem(`${BASIC_AUTH_KEY}-${server}`);
UserPreferences.removeItem(`${server}-${E2E_PUBLIC_KEY}`);
@ -42,7 +42,7 @@ async function removeServerData({ server }: { server: string }) {
try {
const batch: Model[] = [];
const serversDB = database.servers;
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`);
const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
const usersCollection = serversDB.get('users');
if (userId) {
@ -62,7 +62,7 @@ async function removeServerData({ server }: { server: string }) {
}
function removeCurrentServer() {
UserPreferences.removeItem(RocketChat.CURRENT_SERVER);
UserPreferences.removeItem(CURRENT_SERVER);
}
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> {
try {
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`);
const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
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) });
await sdk.login({ resume });
@ -110,7 +110,7 @@ export async function logout(this: IRocketChat, { server }: { server: string }):
}
try {
await this.removePushToken();
await Services.removePushToken();
} catch (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 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 {
const db = database.active;
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
};
const roomTypeToApiType = <T extends RoomTypes>(t: T) => types[t];
export default roomTypeToApiType;
export const roomTypeToApiType = <T extends RoomTypes>(t: T) => types[t];

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;
try {
// RC 0.60.0

View File

@ -4,18 +4,21 @@ import { shareSetSettings, shareSelectServer, shareSetUser } from '../../actions
import SSLPinning from '../../utils/sslPinning';
import log from '../../utils/log';
import { IShareServer, IShareUser } from '../../reducers/share';
import UserPreferences from '../methods/userPreferences';
import UserPreferences from './userPreferences';
import database from '../database';
import RocketChat from '../rocketchat';
import { encryptionInit } from '../../actions/encryption';
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) {
database.setShareDB(server);
try {
const certificate = UserPreferences.getString(`${RocketChat.CERTIFICATE_KEY}-${server}`);
const certificate = UserPreferences.getString(`${CERTIFICATE_KEY}-${server}`);
if (SSLPinning && certificate) {
await SSLPinning.setCertificate(certificate, server);
}
@ -41,7 +44,7 @@ export async function shareExtensionInit(server: string) {
}
store.dispatch(shareSelectServer(currentServer));
RocketChat.setCustomEmojis();
setCustomEmojis();
try {
// set Settings
@ -57,10 +60,10 @@ export async function shareExtensionInit(server: string) {
valueAsArray: item.valueAsArray,
_updatedAt: item._updatedAt
}));
store.dispatch(shareSetSettings(RocketChat.parseSettings(parsed)));
store.dispatch(shareSetSettings(parseSettings(parsed)));
// set User info
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`);
const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
const userCollections = serversDB.get('users');
let user = null;
if (userId) {
@ -74,7 +77,7 @@ export async function shareExtensionInit(server: string) {
}
store.dispatch(shareSetUser(user as IShareUser));
if (user) {
await RocketChat.login({ resume: user.token });
await Services.login({ resume: user.token });
}
store.dispatch(encryptionInit());
} 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 { addUserTyping, clearUserTyping, removeUserTyping } from '../../../actions/usersTyping';
import debounce from '../../../utils/debounce';
import RocketChat from '../../rocketchat';
import { subscribeRoom, unsubscribeRoom } from '../../../actions/room';
import { Encryption } from '../../encryption';
import { IMessage, TMessageModel, TSubscriptionModel, TThreadMessageModel, TThreadModel } from '../../../definitions';
import { IDDPMessage } from '../../../definitions/IDDPMessage';
import sdk from '../../services/sdk';
import { readMessages } from '../readMessages';
import { loadMissedMessages } from '../loadMissedMessages';
const WINDOW_TIME = 1000;
@ -107,7 +108,7 @@ export default class RoomSubscription {
handleConnection = async () => {
try {
reduxStore.dispatch(clearUserTyping());
await RocketChat.loadMissedMessages({ rid: this.rid });
await loadMissedMessages({ rid: this.rid });
const _lastOpen = new Date();
this.read(_lastOpen);
this.lastOpen = _lastOpen;
@ -185,7 +186,7 @@ export default class RoomSubscription {
});
read = debounce((lastOpen: Date) => {
RocketChat.readMessages(this.rid, lastOpen);
readMessages(this.rid, lastOpen);
}, 300);
updateMessage = (message: IMessage): Promise<void> =>

View File

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

View File

@ -5,21 +5,20 @@ import {
ITriggerSubmitView,
ModalActions
} from '../../containers/UIKit/interfaces';
import { TRocketChat } from '../../definitions';
import Navigation from '../navigation/appNavigation';
import { triggerAction } from './actions';
export function triggerBlockAction(this: TRocketChat, options: ITriggerBlockAction) {
return triggerAction.call(this, { type: ActionTypes.ACTION, ...options });
}
export async function triggerSubmitView(this: TRocketChat, { viewId, ...options }: ITriggerSubmitView) {
const result = await triggerAction.call(this, { type: ActionTypes.SUBMIT, viewId, ...options });
export async function triggerSubmitView({ viewId, ...options }: ITriggerSubmitView) {
const result = await triggerAction({ type: ActionTypes.SUBMIT, viewId, ...options });
if (!result || ModalActions.CLOSE === result) {
Navigation.back();
}
}
export function triggerCancel(this: TRocketChat, { view, ...options }: ITriggerCancel) {
return triggerAction.call(this, { type: ActionTypes.CLOSED, view, ...options });
export function triggerCancel({ view, ...options }: ITriggerCancel) {
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 canOpenRoom from './methods/canOpenRoom';
import clearCache from './methods/clearCache';
import getRoom from './methods/getRoom';
import getRooms from './methods/getRooms';
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';
import { _setUser } from './methods/setUser';
import { logout } from './methods/logout';
import { subscribeRooms, unsubscribeRooms } from './methods/subscribeRooms';
import { subscribeUsersPresence } from './methods/getUsersPresence';
import { connect } from './services/connect';
const RocketChat = {
TOKEN_KEY,
CURRENT_SERVER,
CERTIFICATE_KEY,
...restApis,
...search,
...getPermalinks,
...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
logout,
subscribeRooms,
unsubscribeRooms,
_setUser,
subscribeUsersPresence,
connect
};
export default RocketChat;

View File

@ -24,6 +24,7 @@ import { updateSettings } from '../../actions/settings';
import { defaultSettings, MIN_ROCKETCHAT_VERSION } from '../constants';
import { compareServerVersion } from '../methods/helpers/compareServerVersion';
import { onRolesChanged } from '../methods/getRoles';
import { getSettings } from '../methods';
interface IServices {
[index: string]: string | boolean;
@ -85,7 +86,7 @@ function connect(
EventEmitter.emit('INQUIRY_UNSUBSCRIBE');
sdk.initialize(server);
this.getSettings();
getSettings();
sdk.current
.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,
IRoomNotifications,
SubscriptionType,
IUser,
TRocketChat
IUser
} from '../../definitions';
import { IAvatarSuggestion, IParams } from '../../definitions/IProfileViewInterfaces';
import { ISpotlight } from '../../definitions/ISpotlight';
@ -16,9 +15,10 @@ import { TParams } from '../../definitions/ILivechatEditView';
import { store as reduxStore } from '../store/auxStore';
import { getDeviceToken } from '../notifications';
import { getBundleId, isIOS } from '../../utils/deviceInfo';
import roomTypeToApiType, { RoomTypes } from '../methods/roomTypeToApiType';
import { RoomTypes, roomTypeToApiType } from '../methods';
import sdk from './sdk';
import { compareServerVersion } from '../methods/helpers/compareServerVersion';
import RocketChat from '../rocketchat';
export const createChannel = ({
name,
@ -801,10 +801,9 @@ export const emitTyping = (room: IRoom, typing = true) => {
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
// TODO: remove this
this.unsubscribeRooms();
RocketChat.unsubscribeRooms();
// RC 0.72.0
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 { createChannelFailure, createChannelSuccess } from '../actions/createChannel';
import { showErrorAlert } from '../utils/info';
import RocketChat from '../lib/rocketchat';
import Navigation from '../lib/navigation/appNavigation';
import database from '../lib/database';
import I18n from '../i18n';
import { events, logEvent } from '../utils/log';
import { goRoom } from '../utils/goRoom';
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);
};
import { Services } from '../lib/services';
const handleRequest = function* handleRequest({ data }) {
try {
@ -39,7 +27,7 @@ const handleRequest = function* handleRequest({ data }) {
broadcast: `${broadcast}`,
encrypted: `${encrypted}`
});
const result = yield call(createTeam, data);
const result = yield Services.createTeam(data);
sub = {
rid: result?.team?.roomId,
...result.team,
@ -47,7 +35,7 @@ const handleRequest = function* handleRequest({ data }) {
};
} else if (data.group) {
logEvent(events.SELECTED_USERS_CREATE_GROUP);
const result = yield call(createGroupChat);
const result = yield Services.createGroupChat();
if (result.success) {
sub = {
rid: result.room?._id,
@ -62,7 +50,7 @@ const handleRequest = function* handleRequest({ data }) {
broadcast,
encrypted
});
const result = yield call(createChannel, data);
const result = yield Services.createChannel(data);
sub = {
rid: result?.channel?._id || result?.group?._id,
...result?.channel,

View File

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

View File

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

View File

@ -6,13 +6,13 @@ import { encryptionSet } from '../actions/encryption';
import { Encryption } from '../lib/encryption';
import Navigation from '../lib/navigation/appNavigation';
import database from '../lib/database';
import RocketChat from '../lib/rocketchat';
import UserPreferences from '../lib/methods/userPreferences';
import { getUserSelector } from '../selectors/login';
import { showErrorAlert } from '../utils/info';
import I18n from '../i18n';
import log from '../utils/log';
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 getE2eEnable = state => state.settings.E2E_Enable;
@ -42,7 +42,7 @@ const handleEncryptionInit = function* handleEncryptionInit() {
const storedPrivateKey = UserPreferences.getString(`${server}-${E2E_PRIVATE_KEY}`);
// 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
// Show the banner asking for the password
@ -96,7 +96,7 @@ const handleEncryptionDecodeKey = function* handleEncryptionDecodeKey({ password
const user = yield select(getUserSelector);
// Fetch server stored e2e keys
const keys = yield RocketChat.e2eFetchMyKeys();
const keys = yield Services.e2eFetchMyKeys();
const publicKey = EJSON.parse(keys?.publicKey);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,6 +9,7 @@ import log from '../utils/log';
import mergeSubscriptionsRooms from '../lib/methods/helpers/mergeSubscriptionsRooms';
import RocketChat from '../lib/rocketchat';
import buildMessage from '../lib/methods/helpers/buildMessage';
import { getRooms } from '../lib/methods';
const updateRooms = function* updateRooms({ server, newRoomsUpdatedAt }) {
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 db = database.active;
const subCollection = db.get('subscriptions');

View File

@ -22,13 +22,16 @@ import { encryptionStop } from '../actions/encryption';
import SSLPinning from '../utils/sslPinning';
import { inquiryReset } from '../ee/omnichannel/actions/inquiry';
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 }) {
try {
const serverInfo = yield RocketChat.getServerInfo(server);
const serverInfo = yield Services.getServerInfo(server);
let websocketInfo = { success: true };
if (raiseError) {
websocketInfo = yield RocketChat.getWebsocketInfo({ server });
websocketInfo = yield Services.getWebsocketInfo({ server });
}
if (!serverInfo.success || !websocketInfo.success) {
if (raiseError) {
@ -69,14 +72,14 @@ const getServerInfo = function* getServerInfo({ server, raiseError = true }) {
const handleSelectServer = function* handleSelectServer({ server, version, fetchVersion }) {
try {
// 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);
yield put(inquiryReset());
yield put(encryptionStop());
yield put(clearActiveUsers());
const serversDB = database.servers;
UserPreferences.setString(RocketChat.CURRENT_SERVER, server);
const userId = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${server}`);
UserPreferences.setString(CURRENT_SERVER, server);
const userId = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
const userCollections = serversDB.get('users');
let user = null;
if (userId) {
@ -96,7 +99,7 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
};
} catch {
// search credentials on shared credentials (Experimental/Official)
const token = UserPreferences.getString(`${RocketChat.TOKEN_KEY}-${userId}`);
const token = UserPreferences.getString(`${TOKEN_KEY}-${userId}`);
if (token) {
user = { token };
}
@ -107,7 +110,7 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
setBasicAuth(basicAuth);
// Check for running requests and abort them before connecting to the server
RocketChat.abort();
Services.abort();
if (user) {
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
// and block the selectServerSuccess raising multiples errors
RocketChat.setSettings();
RocketChat.setCustomEmojis();
RocketChat.setPermissions();
RocketChat.setRoles();
RocketChat.setEnterpriseModules();
setSettings();
setCustomEmojis();
setPermissions();
setRoles();
setEnterpriseModules();
let serverInfo;
if (fetchVersion) {
@ -148,7 +151,7 @@ const handleSelectServer = function* handleSelectServer({ server, version, fetch
const handleServerRequest = function* handleServerRequest({ server, username, fromServerHistory }) {
try {
// 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);
const serverInfo = yield getServerInfo({ server });
@ -156,8 +159,8 @@ const handleServerRequest = function* handleServerRequest({ server, username, fr
const serversHistoryCollection = serversDB.get('servers_history');
if (serverInfo) {
yield RocketChat.getLoginServices(server);
yield RocketChat.getLoginSettings({ server });
yield Services.getLoginServices(server);
yield getLoginSettings({ server });
Navigation.navigate('WorkspaceView');
if (fromServerHistory) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,7 +7,6 @@ import { Q } from '@nozbe/watermelondb';
import * as List from '../containers/List';
import database from '../lib/database';
import RocketChat from '../lib/rocketchat';
import I18n from '../i18n';
import log, { events, logEvent } from '../utils/log';
import SearchBox from '../containers/SearchBox';
@ -23,6 +22,8 @@ import { showErrorAlert } from '../utils/info';
import debounce from '../utils/debounce';
import { ChatsStackParamList } from '../stacks/types';
import { TSubscriptionModel, SubscriptionType } from '../definitions';
import { getRoomTitle, hasPermission } from '../lib/methods';
import { Services } from '../lib/services';
interface IAddExistingChannelViewState {
search: TSubscriptionModel[];
@ -100,7 +101,7 @@ class AddExistingChannelView extends React.Component<IAddExistingChannelViewProp
if (channel.prid) {
return false;
}
const permissions = await RocketChat.hasPermission([addTeamChannelPermission], channel.rid);
const permissions = await hasPermission([addTeamChannelPermission], channel.rid);
if (!permissions[0]) {
return false;
}
@ -133,7 +134,7 @@ class AddExistingChannelView extends React.Component<IAddExistingChannelViewProp
this.setState({ loading: true });
try {
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) {
this.setState({ loading: false });
// @ts-ignore
@ -181,7 +182,7 @@ class AddExistingChannelView extends React.Component<IAddExistingChannelViewProp
const icon = item.t === SubscriptionType.DIRECT && !item?.teamId ? 'channel-private' : 'channel-public';
return (
<List.Item
title={RocketChat.getRoomTitle(item)}
title={getRoomTitle(item)}
translateTitle={false}
onPress={() => this.toggleChannel(item.rid)}
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 { OutsideModalParamList } from '../stacks/types';
import RocketChat from '../lib/rocketchat';
import { isIOS } from '../utils/deviceInfo';
import StatusBar from '../containers/StatusBar';
import ActivityIndicator from '../containers/ActivityIndicator';
import { TSupportedThemes, withTheme } from '../theme';
import debounce from '../utils/debounce';
import * as HeaderButton from '../containers/HeaderButton';
import { Services } from '../lib/services';
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'
@ -102,7 +102,7 @@ class AuthenticationWebView extends React.PureComponent<IAuthenticationWebView,
this.setState({ logging: true });
try {
RocketChat.loginOAuthOrSso(params);
Services.loginOAuthOrSso(params);
} catch (e) {
console.warn(e);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,13 +4,13 @@ import { BLOCK_CONTEXT } from '@rocket.chat/ui-kit';
import debounce from '../../utils/debounce';
import { avatarURL } from '../../utils/avatar';
import RocketChat from '../../lib/rocketchat';
import I18n from '../../i18n';
import { MultiSelect } from '../../containers/UIKit/MultiSelect';
import { themes } from '../../lib/constants';
import styles from './styles';
import { ICreateDiscussionViewSelectUsers } from './interfaces';
import { SubscriptionType } from '../../definitions/ISubscription';
import { getRoomAvatar, getRoomTitle, search } from '../../lib/methods';
interface IUser {
name: string;
@ -31,7 +31,7 @@ const SelectUsers = ({
const getUsers = debounce(async (keyword = '') => {
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 filteredUsers = res.filter(r => !users.find((u: IUser) => u.name === r.name));
const items = [...selectedUsers, ...filteredUsers];
@ -43,7 +43,7 @@ const SelectUsers = ({
const getAvatar = (item: any) =>
avatarURL({
text: RocketChat.getRoomAvatar(item),
text: getRoomAvatar(item),
type: SubscriptionType.DIRECT,
user: { id: userId, token },
server,
@ -61,7 +61,7 @@ const SelectUsers = ({
onChange={onUserSelect}
options={users.map((user: IUser) => ({
value: user.name,
text: { text: RocketChat.getRoomTitle(user) },
text: { text: getRoomTitle(user) },
imageUrl: getAvatar(user)
}))}
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 { getUserSelector } from '../../selectors/login';
import TextInput from '../../containers/TextInput';
import RocketChat from '../../lib/rocketchat';
import Navigation from '../../lib/navigation/appNavigation';
import { createDiscussionRequest } from '../../actions/createDiscussion';
import { showErrorAlert } from '../../utils/info';
@ -25,6 +24,7 @@ import SelectChannel from './SelectChannel';
import { ICreateChannelViewProps, IResult, IError } from './interfaces';
import { IApplicationState } from '../../definitions';
import { E2E_ROOM_TYPES, SWITCH_TRACK_COLOR, themes } from '../../lib/constants';
import { getRoomTitle } from '../../lib/methods';
class CreateChannelView extends React.Component<ICreateChannelViewProps, any> {
private channel: any;
@ -67,7 +67,7 @@ class CreateChannelView extends React.Component<ICreateChannelViewProps, any> {
}
const item = {
rid,
name: RocketChat.getRoomTitle(result),
name: getRoomTitle(result),
t,
prid
};
@ -161,7 +161,7 @@ class CreateChannelView extends React.Component<ICreateChannelViewProps, any> {
server={server}
userId={user.id}
token={user.token}
initial={this.channel && { text: RocketChat.getRoomTitle(this.channel) }}
initial={this.channel && { text: getRoomTitle(this.channel) }}
onChannelSelect={this.selectChannel}
blockUnauthenticatedAccess={blockUnauthenticatedAccess}
serverVersion={serverVersion}

View File

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

View File

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

View File

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

View File

@ -16,7 +16,6 @@ import { getUserSelector } from '../selectors/login';
import { PADDING_HORIZONTAL } from '../containers/List/constants';
import { themes } from '../lib/constants';
import { Encryption } from '../lib/encryption';
import RocketChat from '../lib/rocketchat';
import { logout as logoutAction } from '../actions/login';
import { showConfirmationAlert, showErrorAlert } from '../utils/info';
import EventEmitter from '../utils/events';
@ -24,6 +23,7 @@ import { LISTENER } from '../containers/Toast';
import debounce from '../utils/debounce';
import sharedStyles from './Styles';
import { IUser } from '../definitions';
import { Services } from '../lib/services';
const styles = StyleSheet.create({
container: {
@ -101,7 +101,7 @@ class E2EEncryptionSecurityView extends React.Component<IE2EEncryptionSecurityVi
onPress: async () => {
logEvent(events.E2E_SEC_RESET_OWN_KEY);
try {
const res = await RocketChat.e2eResetOwnKey();
const res = await Services.e2eResetOwnKey();
/**
* It might return an empty object when TOTP is enabled,
* 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 { 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 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 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 sharedStyles from './Styles';
import { OutsideParamList } from '../stacks/types';
interface IForgotPasswordViewState {
email: string;
@ -73,7 +73,7 @@ class ForgotPasswordView extends React.Component<IForgotPasswordViewProps, IForg
}
try {
this.setState({ isFetching: true });
const result = await RocketChat.forgotPassword(email);
const result = await Services.forgotPassword(email);
if (result.success) {
const { navigation } = this.props;
navigation.pop();

View File

@ -9,10 +9,10 @@ import OrSeparator from '../containers/OrSeparator';
import Input from '../containers/UIKit/MultiSelect/Input';
import { IBaseScreen, IServerRoom } from '../definitions';
import I18n from '../i18n';
import RocketChat from '../lib/rocketchat';
import { ChatsStackParamList } from '../stacks/types';
import { withTheme } from '../theme';
import { IOptionsField } from './NotificationPreferencesView/options';
import { Services } from '../lib/services';
const styles = StyleSheet.create({
container: {
@ -41,7 +41,7 @@ const ForwardLivechatView = ({ navigation, route, theme }: IBaseScreen<ChatsStac
const getDepartments = async (text = '', offset = 0) => {
try {
const result = await RocketChat.getDepartments({ count: COUNT_DEPARTMENT, text, offset });
const result = await Services.getDepartments({ count: COUNT_DEPARTMENT, text, offset });
if (result.success) {
const parsedDepartments = result.departments.map(department => ({
label: department.name,
@ -62,7 +62,7 @@ const ForwardLivechatView = ({ navigation, route, theme }: IBaseScreen<ChatsStac
try {
const { servedBy: { _id: agentId } = {} } = room;
const _id = agentId && { $ne: agentId };
const result = await RocketChat.usersAutoComplete({
const result = await Services.usersAutoComplete({
conditions: { _id, status: { $ne: 'offline' }, statusLivechat: 'available' },
term
});
@ -80,7 +80,7 @@ const ForwardLivechatView = ({ navigation, route, theme }: IBaseScreen<ChatsStac
const getRoom = async () => {
try {
const result = await RocketChat.getRoomInfo(rid);
const result = await Services.getRoomInfo(rid);
if (result.success) {
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 { connect } from 'react-redux';
import RocketChat from '../lib/rocketchat';
import { getUserSelector } from '../selectors/login';
import ActivityIndicator from '../containers/ActivityIndicator';
import { events, logEvent } from '../utils/log';
@ -14,6 +13,7 @@ import { isAndroid, isIOS } from '../utils/deviceInfo';
import { TSupportedThemes, withTheme } from '../theme';
import { InsideStackParamList } from '../stacks/types';
import { IApplicationState, IUser } from '../definitions';
import { Services } from '../lib/services';
const formatUrl = (url: string, baseUrl: string, uriSize: number, avatarAuthURLFragment: string) =>
`${baseUrl}/avatar/${url}?format=png&width=${uriSize}&height=${uriSize}${avatarAuthURLFragment}`;
@ -93,14 +93,14 @@ class JitsiMeetView extends React.Component<IJitsiMeetViewProps, IJitsiMeetViewS
onConferenceJoined = () => {
logEvent(events.JM_CONFERENCE_JOIN);
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) {
BackgroundTimer.clearInterval(this.jitsiTimeout);
BackgroundTimer.stopBackgroundTimer();
this.jitsiTimeout = null;
}
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);
}
};

View File

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

View File

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

View File

@ -9,7 +9,6 @@ import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack
import Message from '../../containers/message';
import ActivityIndicator from '../../containers/ActivityIndicator';
import I18n from '../../i18n';
import RocketChat from '../../lib/rocketchat';
import StatusBar from '../../containers/StatusBar';
import getFileUrlFromMessage from '../../lib/methods/helpers/getFileUrlFromMessage';
import { themes } from '../../lib/constants';
@ -24,6 +23,7 @@ import { ISubscription, SubscriptionType } from '../../definitions/ISubscription
import { IEmoji } from '../../definitions/IEmoji';
import { IRoomInfoParam } from '../SearchMessagesView';
import { TMessageModel } from '../../definitions';
import { Services } from '../../lib/services';
interface IMessagesViewProps {
user: {
@ -191,7 +191,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
name: I18n.t('Files'),
fetchFunc: async () => {
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) {
return { ...result, messages: result.files };
}
@ -222,7 +222,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
name: I18n.t('Mentions'),
fetchFunc: () => {
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'),
testID: 'mentioned-messages-view',
@ -234,7 +234,7 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
name: I18n.t('Starred'),
fetchFunc: () => {
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'),
testID: 'starred-messages-view',
@ -247,14 +247,14 @@ class MessagesView extends React.Component<IMessagesViewProps, any> {
icon: message.starred ? 'star-filled' : 'star',
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: {
name: I18n.t('Pinned'),
fetchFunc: () => {
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'),
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} />
),
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
}[name];

View File

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

View File

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

View File

@ -9,7 +9,7 @@ import parse from 'url-parse';
import { inviteLinksClear } from '../../actions/inviteLinks';
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 FormContainer, { FormContainerInner } from '../../containers/FormContainer';
import * as HeaderButton from '../../containers/HeaderButton';
@ -19,7 +19,6 @@ import { withDimensions } from '../../dimensions';
import I18n from '../../i18n';
import database from '../../lib/database';
import { sanitizeLikeString } from '../../lib/database/utils';
import RocketChat from '../../lib/rocketchat';
import UserPreferences from '../../lib/methods/userPreferences';
import { OutsideParamList } from '../../stacks/types';
import { withTheme } from '../../theme';
@ -194,7 +193,7 @@ class NewServerView extends React.Component<INewServerViewProps, INewServerViewS
// Save info - SSL Pinning
if (certificate) {
UserPreferences.setString(`${RocketChat.CERTIFICATE_KEY}-${server}`, certificate);
UserPreferences.setString(`${CERTIFICATE_KEY}-${server}`, certificate);
}
// 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 * as List from '../../containers/List';
import I18n from '../../i18n';
import RocketChat from '../../lib/rocketchat';
import { TSupportedThemes, withTheme } from '../../theme';
import protectedFunction from '../../lib/methods/helpers/protectedFunction';
import SafeAreaView from '../../containers/SafeAreaView';
@ -19,6 +18,7 @@ import sharedStyles from '../Styles';
import { IOptionsField, OPTIONS } from './options';
import { ChatsStackParamList } from '../../stacks/types';
import { IRoomNotifications } from '../../definitions';
import { Services } from '../../lib/services';
const styles = StyleSheet.create({
pickerText: {
@ -90,7 +90,7 @@ class NotificationPreferencesView extends React.Component<INotificationPreferenc
});
try {
const result = await RocketChat.saveNotificationSettings(this.rid, params);
const result = await Services.saveNotificationSettings(this.rid, params);
if (result.success) {
return;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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