diff --git a/app/containers/LoginServices.tsx b/app/containers/LoginServices.tsx index e10eeed47..5064a4d06 100644 --- a/app/containers/LoginServices.tsx +++ b/app/containers/LoginServices.tsx @@ -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 { 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); diff --git a/app/containers/MessageBox/index.tsx b/app/containers/MessageBox/index.tsx index fdadff83c..647c0e614 100644 --- a/app/containers/MessageBox/index.tsx +++ b/app/containers/MessageBox/index.tsx @@ -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 { 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 { 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 { 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 { }; 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 { }, 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 { 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 { 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 { 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); diff --git a/app/containers/MessageErrorActions.tsx b/app/containers/MessageErrorActions.tsx index b277adac6..6a5d9e024 100644 --- a/app/containers/MessageErrorActions.tsx +++ b/app/containers/MessageErrorActions.tsx @@ -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) => { diff --git a/app/containers/TwoFactor/index.tsx b/app/containers/TwoFactor/index.tsx index 6509f57d3..a83af6c26 100644 --- a/app/containers/TwoFactor/index.tsx +++ b/app/containers/TwoFactor/index.tsx @@ -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)) { diff --git a/app/ee/omnichannel/containers/OmnichannelHeader/index.tsx b/app/ee/omnichannel/containers/OmnichannelHeader/index.tsx index d0496c855..eed3f478a 100644 --- a/app/ee/omnichannel/containers/OmnichannelHeader/index.tsx +++ b/app/ee/omnichannel/containers/OmnichannelHeader/index.tsx @@ -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; } diff --git a/app/ee/omnichannel/lib/subscriptions/inquiry.ts b/app/ee/omnichannel/lib/subscriptions/inquiry.ts index e9358133e..a918e48eb 100644 --- a/app/ee/omnichannel/lib/subscriptions/inquiry.ts +++ b/app/ee/omnichannel/lib/subscriptions/inquiry.ts @@ -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)); } diff --git a/app/ee/omnichannel/sagas/inquiry.js b/app/ee/omnichannel/sagas/inquiry.js index b9bec6b41..ec728e537 100644 --- a/app/ee/omnichannel/sagas/inquiry.js +++ b/app/ee/omnichannel/sagas/inquiry.js @@ -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); diff --git a/app/ee/omnichannel/views/QueueListView.tsx b/app/ee/omnichannel/views/QueueListView.tsx index 6b60b59a1..9d6eab96a 100644 --- a/app/ee/omnichannel/views/QueueListView.tsx +++ b/app/ee/omnichannel/views/QueueListView.tsx @@ -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 { }); }; - getRoomTitle = (item: IOmnichannelRoom) => RocketChat.getRoomTitle(item); - - getRoomAvatar = (item: IOmnichannelRoom) => RocketChat.getRoomAvatar(item); - - getUidDirectMessage = (room: IOmnichannelRoom) => RocketChat.getUidDirectMessage(room); - renderItem: ListRenderItem = ({ item }) => { const { user: { id: userId, username, token }, @@ -115,7 +109,7 @@ class QueueListView extends React.Component { showAvatar, displayMode } = this.props; - const id = this.getUidDirectMessage(item); + const id = getUidDirectMessage(item); return ( { 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} diff --git a/app/index.tsx b/app/index.tsx index 1dd42188c..920db27fe 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -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); }); }; diff --git a/app/lib/constants/keys.ts b/app/lib/constants/keys.ts index ff48f2a05..7c41e0242 100644 --- a/app/lib/constants/keys.ts +++ b/app/lib/constants/keys.ts @@ -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'; diff --git a/app/lib/encryption/encryption.ts b/app/lib/encryption/encryption.ts index 4d0cd68fa..f24e483e7 100644 --- a/app/lib/encryption/encryption.ts +++ b/app/lib/encryption/encryption.ts @@ -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 diff --git a/app/lib/encryption/room.ts b/app/lib/encryption/room.ts index f2ed355d9..db8233445 100644 --- a/app/lib/encryption/room.ts +++ b/app/lib/encryption/room.ts @@ -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); } }; diff --git a/app/lib/methods/actions.ts b/app/lib/methods/actions.ts index 5425f49c8..edf63fc44 100644 --- a/app/lib/methods/actions.ts +++ b/app/lib/methods/actions.ts @@ -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(async (resolve, reject) => { const triggerId = generateTriggerId(appId); diff --git a/app/lib/methods/canOpenRoom.ts b/app/lib/methods/canOpenRoom.ts index 46c041537..6cd389909 100644 --- a/app/lib/methods/canOpenRoom.ts +++ b/app/lib/methods/canOpenRoom.ts @@ -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 { +export async function canOpenRoom({ rid, path, isCall }: { rid: string; isCall: boolean; path: string }): Promise { try { const db = database.active; const subsCollection = db.get('subscriptions'); diff --git a/app/lib/methods/clearCache.ts b/app/lib/methods/clearCache.ts index eeb5a97b2..51fd9e052 100644 --- a/app/lib/methods/clearCache.ts +++ b/app/lib/methods/clearCache.ts @@ -1,6 +1,6 @@ import database from '../database'; -export default async function clearCache({ server }: { server: string }): Promise { +export async function clearCache({ server }: { server: string }): Promise { try { const serversDB = database.servers; await serversDB.write(async () => { diff --git a/app/lib/methods/crashReport.ts b/app/lib/methods/crashReport.ts new file mode 100644 index 000000000..acb229db5 --- /dev/null +++ b/app/lib/methods/crashReport.ts @@ -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); +} diff --git a/app/lib/methods/enterpriseModules.ts b/app/lib/methods/enterpriseModules.ts index e33cd7dcf..b5ce4e74a 100644 --- a/app/lib/methods/enterpriseModules.ts +++ b/app/lib/methods/enterpriseModules.ts @@ -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)); diff --git a/app/lib/methods/getPermalinks.ts b/app/lib/methods/getPermalinks.ts index 29ec4d2bd..f244b9871 100644 --- a/app/lib/methods/getPermalinks.ts +++ b/app/lib/methods/getPermalinks.ts @@ -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'; diff --git a/app/lib/methods/getRoom.ts b/app/lib/methods/getRoom.ts index 35842e4f3..5dd66b81a 100644 --- a/app/lib/methods/getRoom.ts +++ b/app/lib/methods/getRoom.ts @@ -1,7 +1,7 @@ import { TSubscriptionModel } from '../../definitions'; import database from '../database'; -export default async function getRoom(rid: string): Promise { +export async function getRoom(rid: string): Promise { try { const db = database.active; const room = await db.get('subscriptions').find(rid); diff --git a/app/lib/methods/getRoomInfo.ts b/app/lib/methods/getRoomInfo.ts index 142d59177..67125bb3d 100644 --- a/app/lib/methods/getRoomInfo.ts +++ b/app/lib/methods/getRoomInfo.ts @@ -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 => { }; } - result = await RocketChat.getRoomInfo(rid); + result = await Services.getRoomInfo(rid); if (result?.success) { return { rid, diff --git a/app/lib/methods/getRooms.ts b/app/lib/methods/getRooms.ts index cc7a37d77..0c2899531 100644 --- a/app/lib/methods/getRooms.ts +++ b/app/lib/methods/getRooms.ts @@ -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) { diff --git a/app/lib/methods/getSettings.ts b/app/lib/methods/getSettings.ts index 8c53f6faa..76f10aa41 100644 --- a/app/lib/methods/getSettings.ts +++ b/app/lib/methods/getSettings.ts @@ -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', diff --git a/app/lib/methods/getSingleMessage.ts b/app/lib/methods/getSingleMessage.ts index cc153e2f4..9b6ee2d1f 100644 --- a/app/lib/methods/getSingleMessage.ts +++ b/app/lib/methods/getSingleMessage.ts @@ -1,10 +1,10 @@ -import RocketChat from '../rocketchat'; import { IMessage } from '../../definitions'; +import { Services } from '../services'; const getSingleMessage = (messageId: string): Promise => 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); } diff --git a/app/lib/methods/getSlashCommands.ts b/app/lib/methods/getSlashCommands.ts index d2fbe2a7b..2c197227c 100644 --- a/app/lib/methods/getSlashCommands.ts +++ b/app/lib/methods/getSlashCommands.ts @@ -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(async resolve => { try { diff --git a/app/lib/methods/getUsersPresence.ts b/app/lib/methods/getUsersPresence.ts index b8587e43a..a416d11bf 100644 --- a/app/lib/methods/getUsersPresence.ts +++ b/app/lib/methods/getUsersPresence.ts @@ -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 | null = null; + export function getUserPresence(uid: string) { if (!usersTimer) { usersTimer = setTimeout(() => { diff --git a/app/lib/methods/helpers.ts b/app/lib/methods/helpers.ts index c4c360234..c31966e51 100644 --- a/app/lib/methods/helpers.ts +++ b/app/lib/methods/helpers.ts @@ -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) { diff --git a/app/lib/methods/index.ts b/app/lib/methods/index.ts new file mode 100644 index 000000000..f90a2f085 --- /dev/null +++ b/app/lib/methods/index.ts @@ -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'; diff --git a/app/lib/methods/loadMessagesForRoom.ts b/app/lib/methods/loadMessagesForRoom.ts index 87ec9919b..d1e55ed67 100644 --- a/app/lib/methods/loadMessagesForRoom.ts +++ b/app/lib/methods/loadMessagesForRoom.ts @@ -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; diff --git a/app/lib/methods/loadMissedMessages.ts b/app/lib/methods/loadMissedMessages.ts index cb5e0712d..aff5e1530 100644 --- a/app/lib/methods/loadMissedMessages.ts +++ b/app/lib/methods/loadMissedMessages.ts @@ -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 { +export function loadMissedMessages(args: { rid: string; lastOpen?: Date }): Promise { return new Promise(async (resolve, reject) => { try { const data = await load({ rid: args.rid, lastOpen: args.lastOpen }); diff --git a/app/lib/methods/loadNextMessages.ts b/app/lib/methods/loadNextMessages.ts index 533059cdb..055d34f89 100644 --- a/app/lib/methods/loadNextMessages.ts +++ b/app/lib/methods/loadNextMessages.ts @@ -19,7 +19,7 @@ interface ILoadNextMessages { loaderItem: TMessageModel; } -export default function loadNextMessages(args: ILoadNextMessages): Promise { +export function loadNextMessages(args: ILoadNextMessages): Promise { return new Promise(async (resolve, reject) => { try { const data = await sdk.methodCallWrapper('loadNextMessages', args.rid, args.ts, COUNT); diff --git a/app/lib/methods/loadSurroundingMessages.ts b/app/lib/methods/loadSurroundingMessages.ts index 35abf4083..973bd05cd 100644 --- a/app/lib/methods/loadSurroundingMessages.ts +++ b/app/lib/methods/loadSurroundingMessages.ts @@ -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); diff --git a/app/lib/methods/loadThreadMessages.ts b/app/lib/methods/loadThreadMessages.ts index 82beeeeac..2dc49b14e 100644 --- a/app/lib/methods/loadThreadMessages.ts +++ b/app/lib/methods/loadThreadMessages.ts @@ -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(async (resolve, reject) => { try { let data = await load({ tmid }); diff --git a/app/lib/methods/logout.ts b/app/lib/methods/logout.ts index 4cd3469b6..4a84b6421 100644 --- a/app/lib/methods/logout.ts +++ b/app/lib/methods/logout.ts @@ -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 { 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); } diff --git a/app/lib/methods/parseSettings.ts b/app/lib/methods/parseSettings.ts new file mode 100644 index 000000000..a59e725ce --- /dev/null +++ b/app/lib/methods/parseSettings.ts @@ -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; + }); +} diff --git a/app/lib/methods/readMessages.ts b/app/lib/methods/readMessages.ts index 27f4808bb..36f6dfbd0 100644 --- a/app/lib/methods/readMessages.ts +++ b/app/lib/methods/readMessages.ts @@ -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 { +export async function readMessages(rid: string, ls: Date, updateLastOpen = false): Promise { try { const db = database.active; const subscription = await db.get('subscriptions').find(rid); diff --git a/app/lib/methods/roomTypeToApiType.ts b/app/lib/methods/roomTypeToApiType.ts index 4473c5d38..dc081fdd5 100644 --- a/app/lib/methods/roomTypeToApiType.ts +++ b/app/lib/methods/roomTypeToApiType.ts @@ -23,6 +23,4 @@ export const types: { [K in RoomTypes]: ApiTypes } = { l: ETypes.Channels }; -const roomTypeToApiType = (t: T) => types[t]; - -export default roomTypeToApiType; +export const roomTypeToApiType = (t: T) => types[t]; diff --git a/app/lib/methods/sendMessage.ts b/app/lib/methods/sendMessage.ts index 06738a470..0d14c849e 100644 --- a/app/lib/methods/sendMessage.ts +++ b/app/lib/methods/sendMessage.ts @@ -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 diff --git a/app/lib/services/shareExtension.ts b/app/lib/methods/shareExtension.ts similarity index 80% rename from app/lib/services/shareExtension.ts rename to app/lib/methods/shareExtension.ts index 4970ab105..028748bce 100644 --- a/app/lib/services/shareExtension.ts +++ b/app/lib/methods/shareExtension.ts @@ -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) { diff --git a/app/lib/methods/subscribeRooms.ts b/app/lib/methods/subscribeRooms.ts new file mode 100644 index 000000000..8d34195fa --- /dev/null +++ b/app/lib/methods/subscribeRooms.ts @@ -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; + } +} diff --git a/app/lib/methods/subscriptions/room.ts b/app/lib/methods/subscriptions/room.ts index 8685fc3aa..bf60bae1c 100644 --- a/app/lib/methods/subscriptions/room.ts +++ b/app/lib/methods/subscriptions/room.ts @@ -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 => diff --git a/app/lib/methods/subscriptions/rooms.ts b/app/lib/methods/subscriptions/rooms.ts index aa73b09d5..001e07d42 100644 --- a/app/lib/methods/subscriptions/rooms.ts +++ b/app/lib/methods/subscriptions/rooms.ts @@ -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) { diff --git a/app/lib/methods/triggerActions.ts b/app/lib/methods/triggerActions.ts index 8815ac6db..bd43a681c 100644 --- a/app/lib/methods/triggerActions.ts +++ b/app/lib/methods/triggerActions.ts @@ -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 }); } diff --git a/app/lib/rocketchat.ts b/app/lib/rocketchat.ts index 15daa9663..e5fd4900d 100644 --- a/app/lib/rocketchat.ts +++ b/app/lib/rocketchat.ts @@ -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; diff --git a/app/lib/services/connect.ts b/app/lib/services/connect.ts index 6575a5bcd..875e0844b 100644 --- a/app/lib/services/connect.ts +++ b/app/lib/services/connect.ts @@ -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() diff --git a/app/lib/services/index.ts b/app/lib/services/index.ts new file mode 100644 index 000000000..1a80e18f6 --- /dev/null +++ b/app/lib/services/index.ts @@ -0,0 +1,7 @@ +import * as connect from './connect'; +import * as restApi from './restApi'; + +export const Services = { + ...connect, + ...restApi +}; diff --git a/app/lib/services/restApi.ts b/app/lib/services/restApi.ts index 2b18d8706..44e361589 100644 --- a/app/lib/services/restApi.ts +++ b/app/lib/services/restApi.ts @@ -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 { +export function e2eResetOwnKey(): Promise { // {} when TOTP is enabled - // TODO: remove this - this.unsubscribeRooms(); + RocketChat.unsubscribeRooms(); // RC 0.72.0 return sdk.methodCallWrapper('e2e.resetOwnE2EKey'); diff --git a/app/sagas/createChannel.js b/app/sagas/createChannel.js index f540e3226..444f442eb 100644 --- a/app/sagas/createChannel.js +++ b/app/sagas/createChannel.js @@ -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, diff --git a/app/sagas/createDiscussion.js b/app/sagas/createDiscussion.js index 6009fe8b2..9afccc7cf 100644 --- a/app/sagas/createDiscussion.js +++ b/app/sagas/createDiscussion.js @@ -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; diff --git a/app/sagas/deepLinking.js b/app/sagas/deepLinking.js index 71036b4aa..bb545bef7 100644 --- a/app/sagas/deepLinking.js +++ b/app/sagas/deepLinking.js @@ -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(); diff --git a/app/sagas/encryption.js b/app/sagas/encryption.js index d363c5054..f0d7f994e 100644 --- a/app/sagas/encryption.js +++ b/app/sagas/encryption.js @@ -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); diff --git a/app/sagas/init.js b/app/sagas/init.js index 78f2de3d7..9c2f8619f 100644 --- a/app/sagas/init.js +++ b/app/sagas/init.js @@ -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)); } diff --git a/app/sagas/inviteLinks.js b/app/sagas/inviteLinks.js index f37048074..e9bee9d28 100644 --- a/app/sagas/inviteLinks.js +++ b/app/sagas/inviteLinks.js @@ -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 diff --git a/app/sagas/login.js b/app/sagas/login.js index d7cb94c54..4ff0a6ba5 100644 --- a/app/sagas/login.js +++ b/app/sagas/login.js @@ -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 { diff --git a/app/sagas/messages.js b/app/sagas/messages.js index 2f38c2975..bf2ea1275 100644 --- a/app/sagas/messages.js +++ b/app/sagas/messages.js @@ -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 }); } diff --git a/app/sagas/room.js b/app/sagas/room.js index 10d615a0b..7e00e6a71 100644 --- a/app/sagas/room.js +++ b/app/sagas/room.js @@ -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) { diff --git a/app/sagas/rooms.js b/app/sagas/rooms.js index 4787c2714..ee7cacef4 100644 --- a/app/sagas/rooms.js +++ b/app/sagas/rooms.js @@ -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'); diff --git a/app/sagas/selectServer.js b/app/sagas/selectServer.js index b58a61642..ee211c1e9 100644 --- a/app/sagas/selectServer.js +++ b/app/sagas/selectServer.js @@ -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) { diff --git a/app/sagas/state.js b/app/sagas/state.js index 0e00e9bb7..86b1de62c 100644 --- a/app/sagas/state.js +++ b/app/sagas/state.js @@ -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); } diff --git a/app/share.tsx b/app/share.tsx index 53988c7eb..e4836d501 100644 --- a/app/share.tsx +++ b/app/share.tsx @@ -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); diff --git a/app/utils/fetch.ts b/app/utils/fetch.ts index 51a7c7173..17569798e 100644 --- a/app/utils/fetch.ts +++ b/app/utils/fetch.ts @@ -48,6 +48,7 @@ export default (url: string, options: IOptions = {}): Promise => { } // TODO: Refactor when migrate rocketchat.js // @ts-ignore + // WHAT? if (RocketChat.controller) { // @ts-ignore const { signal } = RocketChat.controller; diff --git a/app/utils/goRoom.ts b/app/utils/goRoom.ts index 46de9fb11..0ad369e0c 100644 --- a/app/utils/goRoom.ts +++ b/app/utils/goRoom.ts @@ -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: { diff --git a/app/utils/isReadOnly.ts b/app/utils/isReadOnly.ts index 9e41362b5..2cb6c11e9 100644 --- a/app/utils/isReadOnly.ts +++ b/app/utils/isReadOnly.ts @@ -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]; }; diff --git a/app/views/AddExistingChannelView.tsx b/app/views/AddExistingChannelView.tsx index 361d5c6c8..68e5a0dc1 100644 --- a/app/views/AddExistingChannelView.tsx +++ b/app/views/AddExistingChannelView.tsx @@ -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 this.toggleChannel(item.rid)} testID={`add-existing-channel-view-item-${item.name}`} diff --git a/app/views/AuthenticationWebView.tsx b/app/views/AuthenticationWebView.tsx index 66b251522..71d449117 100644 --- a/app/views/AuthenticationWebView.tsx +++ b/app/views/AuthenticationWebView.tsx @@ -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 { 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 { 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 { saveAutoTranslateLanguage = async (language: string) => { logEvent(events.AT_SET_LANG); try { - await RocketChat.saveAutoTranslate({ + await Services.saveAutoTranslate({ rid: this.rid, field: 'autoTranslateLanguage', value: language diff --git a/app/views/CannedResponseDetail.tsx b/app/views/CannedResponseDetail.tsx index 88136acc8..89af6ec31 100644 --- a/app/views/CannedResponseDetail.tsx +++ b/app/views/CannedResponseDetail.tsx @@ -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 }; diff --git a/app/views/CannedResponsesListView/index.tsx b/app/views/CannedResponsesListView/index.tsx index 9ed27f83c..fc8184551 100644 --- a/app/views/CannedResponsesListView/index.tsx +++ b/app/views/CannedResponsesListView/index.tsx @@ -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, diff --git a/app/views/CreateChannelView.tsx b/app/views/CreateChannelView.tsx index a0b33abbb..1a468166c 100644 --- a/app/views/CreateChannelView.tsx +++ b/app/views/CreateChannelView.tsx @@ -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 { const { createPublicChannelPermission, createPrivateChannelPermission } = this.props; const permissions = [createPublicChannelPermission, createPrivateChannelPermission]; - const permissionsToCreate = await RocketChat.hasPermission(permissions); + const permissionsToCreate = await hasPermission(permissions); this.setState({ permissions: permissionsToCreate }); }; diff --git a/app/views/CreateDiscussionView/SelectChannel.tsx b/app/views/CreateDiscussionView/SelectChannel.tsx index a83d639f6..d5ec42003 100644 --- a/app/views/CreateDiscussionView/SelectChannel.tsx +++ b/app/views/CreateDiscussionView/SelectChannel.tsx @@ -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([])} diff --git a/app/views/CreateDiscussionView/SelectUsers.tsx b/app/views/CreateDiscussionView/SelectUsers.tsx index 26c3291d9..a33fc891e 100644 --- a/app/views/CreateDiscussionView/SelectUsers.tsx +++ b/app/views/CreateDiscussionView/SelectUsers.tsx @@ -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)))} diff --git a/app/views/CreateDiscussionView/index.tsx b/app/views/CreateDiscussionView/index.tsx index 11bb8e6cb..882e989eb 100644 --- a/app/views/CreateDiscussionView/index.tsx +++ b/app/views/CreateDiscussionView/index.tsx @@ -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 { private channel: any; @@ -67,7 +67,7 @@ class CreateChannelView extends React.Component { } const item = { rid, - name: RocketChat.getRoomTitle(result), + name: getRoomTitle(result), t, prid }; @@ -161,7 +161,7 @@ class CreateChannelView extends React.Component { 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} diff --git a/app/views/DirectoryView/index.tsx b/app/views/DirectoryView/index.tsx index 28e3415ca..58ec6ed7b 100644 --- a/app/views/DirectoryView/index.tsx +++ b/app/views/DirectoryView/index.tsx @@ -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; @@ -91,7 +91,7 @@ class DirectoryView extends React.Component { 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 { 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, diff --git a/app/views/DiscussionsView/index.tsx b/app/views/DiscussionsView/index.tsx index bff30f9a6..84313ce08 100644 --- a/app/views/DiscussionsView/index.tsx +++ b/app/views/DiscussionsView/index.tsx @@ -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, diff --git a/app/views/DisplayPrefsView.tsx b/app/views/DisplayPrefsView.tsx index 2c0565f7b..487eae6ed 100644 --- a/app/views/DisplayPrefsView.tsx +++ b/app/views/DisplayPrefsView.tsx @@ -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; @@ -46,7 +46,7 @@ const DisplayPrefsView = (props: IDisplayPrefsView): JSX.Element => { const setSortPreference = (param: Partial) => { dispatch(setPreference(param)); - RocketChat.saveSortPreference(param); + saveSortPreference(param); }; const sortByName = () => { diff --git a/app/views/E2EEncryptionSecurityView.tsx b/app/views/E2EEncryptionSecurityView.tsx index 2ebb15367..c20392172 100644 --- a/app/views/E2EEncryptionSecurityView.tsx +++ b/app/views/E2EEncryptionSecurityView.tsx @@ -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 { 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 diff --git a/app/views/ForgotPasswordView.tsx b/app/views/ForgotPasswordView.tsx index 55305c2dd..fba86105c 100644 --- a/app/views/ForgotPasswordView.tsx +++ b/app/views/ForgotPasswordView.tsx @@ -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 { 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 { try { - const result = await RocketChat.getRoomInfo(rid); + const result = await Services.getRoomInfo(rid); if (result.success) { setRoom(result.room as IServerRoom); } diff --git a/app/views/JitsiMeetView.tsx b/app/views/JitsiMeetView.tsx index c7aba01de..151d6c4e5 100644 --- a/app/views/JitsiMeetView.tsx +++ b/app/views/JitsiMeetView.tsx @@ -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 { 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); } }; diff --git a/app/views/LanguageView/index.tsx b/app/views/LanguageView/index.tsx index 4e1699cbc..d31e87ebb 100644 --- a/app/views/LanguageView/index.tsx +++ b/app/views/LanguageView/index.tsx @@ -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 { user: IUser; @@ -92,7 +92,7 @@ class LanguageView extends React.Component { - 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(); }, []); diff --git a/app/views/MessagesView/index.tsx b/app/views/MessagesView/index.tsx index f91742d77..b63366a4d 100644 --- a/app/views/MessagesView/index.tsx +++ b/app/views/MessagesView/index.tsx @@ -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 { 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 { 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 { 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 { 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 { 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]; diff --git a/app/views/ModalBlockView.tsx b/app/views/ModalBlockView.tsx index 9f817f7d2..1893b41fa 100644 --- a/app/views/ModalBlockView.tsx +++ b/app/views/ModalBlockView.tsx @@ -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 { const { data } = this.state; const { mid, appId, viewId } = data; - await RocketChat.triggerBlockAction({ + await triggerBlockAction({ container: { type: ContainerTypes.VIEW, id: viewId diff --git a/app/views/NewMessageView.tsx b/app/views/NewMessageView.tsx index 2cbd11ddb..3d8219ca8 100644 --- a/app/views/NewMessageView.tsx +++ b/app/views/NewMessageView.tsx @@ -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 { + 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 { - 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 { private name: any; @@ -81,7 +81,7 @@ class ProfileView extends React.Component 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 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 } } - 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 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 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); diff --git a/app/views/ReadReceiptView/index.tsx b/app/views/ReadReceiptView/index.tsx index 4ed6e1405..bb841c408 100644 --- a/app/views/ReadReceiptView/index.tsx +++ b/app/views/ReadReceiptView/index.tsx @@ -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 { const { dispatch, Accounts_EmailVerification, navigation, Accounts_ManuallyApproveNewUsers } = this.props; try { - await RocketChat.register({ + await Services.register({ name, email, pass: password, diff --git a/app/views/RoomActionsView/index.tsx b/app/views/RoomActionsView/index.tsx index cdd644864..4320e079e 100644 --- a/app/views/RoomActionsView/index.tsx +++ b/app/views/RoomActionsView/index.tsx @@ -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 { @@ -163,7 +173,7 @@ class RoomActionsView extends React.Component { 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 { 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 { 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 { 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 dispatch(leaveRoom(ERoomType.c, room)) }); @@ -573,7 +583,7 @@ class RoomActionsView extends React.Component dispatch(leaveRoom(ERoomType.t, room)) }); @@ -661,7 +671,7 @@ class RoomActionsView extends React.Component dispatch(leaveRoom(ERoomType.t, room)) }); @@ -673,7 +683,7 @@ class RoomActionsView extends React.Component { 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 @@ -810,7 +820,7 @@ class RoomActionsView extends React.Component @@ -835,7 +845,7 @@ class RoomActionsView extends React.Component - {RocketChat.getRoomTitle(room)} + {getRoomTitle(room)} )} @@ -850,7 +860,7 @@ class RoomActionsView extends React.Component )} - {isGroupChat ? null : } + {isGroupChatHandler ? null : } @@ -874,7 +884,7 @@ class RoomActionsView extends React.Component RocketChat.callJitsi(room, true)} + onPress={() => callJitsi(room, true)} testID='room-actions-voice' left={() => } showActionIndicator @@ -882,7 +892,7 @@ class RoomActionsView extends React.Component RocketChat.callJitsi(room)} + onPress={() => callJitsi(room)} testID='room-actions-video' left={() => } showActionIndicator @@ -924,7 +934,7 @@ class RoomActionsView extends React.Component @@ -1053,7 +1063,7 @@ class RoomActionsView extends React.Component @@ -1065,7 +1075,7 @@ class RoomActionsView extends React.Component - {(['c', 'p'].includes(t) && canViewMembers) || isGroupChat ? ( + {(['c', 'p'].includes(t) && canViewMembers) || isGroupChatHandler ? ( <> { 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 dispatch(deleteRoom(ERoomType.t, room)) }); @@ -436,7 +437,7 @@ class RoomInfoEditView extends React.Component { 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); diff --git a/app/views/RoomInfoView/Livechat.tsx b/app/views/RoomInfoView/Livechat.tsx index f763c07f3..3dec3be1b 100644 --- a/app/views/RoomInfoView/Livechat.tsx +++ b/app/views/RoomInfoView/Livechat.tsx @@ -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); } diff --git a/app/views/RoomInfoView/index.tsx b/app/views/RoomInfoView/index.tsx index c7d173635..7ba496509 100644 --- a/app/views/RoomInfoView/index.tsx +++ b/app/views/RoomInfoView/index.tsx @@ -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 ? ( <> @@ -71,7 +72,7 @@ const getRoomTitle = ({ room, type, name, username, statusText, theme }: IGetRoo sourceType={room.source} /> - {RocketChat.getRoomTitle(room)} + {getRoomTitle(room)} ); @@ -203,7 +204,7 @@ class RoomInfoView extends React.Component this.setHeader()); } @@ -309,7 +310,7 @@ class RoomInfoView extends React.Component { const { room } = this.state; - RocketChat.callJitsi(room); + callJitsi(room); }; renderAvatar = (room: ISubscription, roomUser: IUserParsed) => { @@ -431,7 +432,7 @@ class RoomInfoView extends React.Component {this.renderAvatar(room, roomUser)} - {getRoomTitle({ + {renderRoomTitle({ room, type: this.t, name: roomUser?.name, diff --git a/app/views/RoomMembersView/index.tsx b/app/views/RoomMembersView/index.tsx index f92c4a8b9..465a089b8 100644 --- a/app/views/RoomMembersView/index.tsx +++ b/app/views/RoomMembersView/index.tsx @@ -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 member._id !== userId); const newMembersFiltered = membersFiltered.filter(member => member._id !== userId); @@ -315,7 +315,7 @@ class RoomMembersView extends React.Component { 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 { 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 { 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 { 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 { 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 { 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 { 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 member._id !== userId), diff --git a/app/views/RoomView/JoinCode.tsx b/app/views/RoomView/JoinCode.tsx index d4d85b864..58ce81d8f 100644 --- a/app/views/RoomView/JoinCode.tsx +++ b/app/views/RoomView/JoinCode.tsx @@ -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} /> diff --git a/app/views/RoomView/List/index.tsx b/app/views/RoomView/List/index.tsx index ad4f2f2c3..376801082 100644 --- a/app/views/RoomView/List/index.tsx +++ b/app/views/RoomView/List/index.tsx @@ -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 { - 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 { + handleCancelUpload = async (item: TUploadModel) => { try { - await RocketChat.cancelUpload(item); + await cancelUpload(item); } catch (e) { log(e); } @@ -158,7 +158,7 @@ class UploadProgress extends Component {I18n.t('Uploading')} {item.name} - this.cancelUpload(item)} /> + this.handleCancelUpload(item)} /> , { }; 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 { } 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 { 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 { 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 { } 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 { 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 { 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 { 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 { } 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 { 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 { 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 { // @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 { 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 { }); }; - 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 { rid: string; mid: string; }) => - RocketChat.triggerBlockAction({ + triggerBlockAction({ blockId, actionId, value, @@ -1214,7 +1226,7 @@ class RoomView extends React.Component { 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 { 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 { return ( => RocketChat.loadThreadMessages({ tmid, rid }); - -export default getThreadMessages; diff --git a/app/views/RoomView/services/index.ts b/app/views/RoomView/services/index.ts index f8799cda8..47565eabe 100644 --- a/app/views/RoomView/services/index.ts +++ b/app/views/RoomView/services/index.ts @@ -1,13 +1,9 @@ import getMessages from './getMessages'; import getMoreMessages from './getMoreMessages'; -import getThreadMessages from './getThreadMessages'; -import readMessages from './readMessages'; import getMessageInfo from './getMessageInfo'; export default { getMessages, getMoreMessages, - getThreadMessages, - readMessages, getMessageInfo }; diff --git a/app/views/RoomView/services/readMessages.ts b/app/views/RoomView/services/readMessages.ts deleted file mode 100644 index 573027d0b..000000000 --- a/app/views/RoomView/services/readMessages.ts +++ /dev/null @@ -1,5 +0,0 @@ -import RocketChat from '../../../lib/rocketchat'; - -const readMessages = (rid: string, newLastOpen: Date): Promise => RocketChat.readMessages(rid, newLastOpen, true); - -export default readMessages; diff --git a/app/views/RoomsListView/ServerDropdown.tsx b/app/views/RoomsListView/ServerDropdown.tsx index 4abef24ae..b74b2016e 100644 --- a/app/views/RoomsListView/ServerDropdown.tsx +++ b/app/views/RoomsListView/ServerDropdown.tsx @@ -9,12 +9,11 @@ import Button from '../../containers/Button'; import { toggleServerDropdown } from '../../actions/rooms'; import { selectServerRequest, serverInitAdd } from '../../actions/server'; import { appStart } from '../../actions/app'; -import RocketChat from '../../lib/rocketchat'; import I18n from '../../i18n'; import EventEmitter from '../../utils/events'; import ServerItem from '../../containers/ServerItem'; import database from '../../lib/database'; -import { themes } from '../../lib/constants'; +import { themes, TOKEN_KEY } from '../../lib/constants'; import { withTheme } from '../../theme'; import { KEY_COMMAND, handleCommandSelectServer, IKeyCommandEvent } from '../../commands'; import { isTablet } from '../../utils/deviceInfo'; @@ -27,6 +26,7 @@ import UserPreferences from '../../lib/methods/userPreferences'; import { IApplicationState, IBaseScreen, RootEnum, TServerModel } from '../../definitions'; import styles from './styles'; import { ChatsStackParamList } from '../../stacks/types'; +import { removeServer } from '../../lib/methods'; const ROW_HEIGHT = 68; const ANIMATION_DURATION = 200; @@ -135,7 +135,7 @@ class ServerDropdown extends Component { this.close(); try { - await RocketChat.removeServer({ server }); + await removeServer({ server }); } catch { // do nothing } diff --git a/app/views/RoomsListView/index.tsx b/app/views/RoomsListView/index.tsx index 9995a47cc..fefd863de 100644 --- a/app/views/RoomsListView/index.tsx +++ b/app/views/RoomsListView/index.tsx @@ -9,7 +9,6 @@ import { Subscription } from 'rxjs'; import { StackNavigationOptions } from '@react-navigation/stack'; import database from '../../lib/database'; -import RocketChat from '../../lib/rocketchat'; import RoomItem, { ROW_HEIGHT, ROW_HEIGHT_CONDENSED } from '../../containers/RoomItem'; import log, { logEvent, events } from '../../utils/log'; import I18n from '../../i18n'; @@ -47,8 +46,19 @@ import ServerDropdown from './ServerDropdown'; import ListHeader, { TEncryptionBanner } from './ListHeader'; import RoomsListHeaderView from './Header'; import { ChatsStackParamList } from '../../stacks/types'; -import { RoomTypes } from '../../lib/methods/roomTypeToApiType'; +import { + getRoomAvatar, + getRoomTitle, + getUidDirectMessage, + getUserPresence, + hasPermission, + isGroupChat, + isRead, + RoomTypes, + search +} from '../../lib/methods'; import { E2E_BANNER_TYPE, DisplayMode, SortBy, MAX_SIDEBAR_WIDTH, themes } from '../../lib/constants'; +import { Services } from '../../lib/services'; interface IRoomsListViewProps extends IBaseScreen { [key: string]: any; @@ -229,7 +239,7 @@ class RoomsListView extends React.Component r === true).length > 0; this.setState({ canCreateRoom }, () => this.setHeader()); }; @@ -591,7 +601,7 @@ class RoomsListView extends React.Component { dispatch(openSearchHeader()); - this.search(''); + this.handleSearch(''); this.setHeader(); }); }; @@ -625,8 +635,8 @@ class RoomsListView extends React.Component { - const result = await RocketChat.search({ text }); + handleSearch = debounce(async (text: string) => { + const result = await search({ text }); // if the search was cancelled before the promise is resolved const { searching } = this.state; @@ -640,19 +650,9 @@ class RoomsListView extends React.Component RocketChat.getRoomTitle(item); - - getRoomAvatar = (item: ISubscription) => RocketChat.getRoomAvatar(item); - - isGroupChat = (item: ISubscription) => RocketChat.isGroupChat(item); - - isRead = (item: ISubscription) => RocketChat.isRead(item); - isSwipeEnabled = (item: IRoomItem) => !(item?.search || item?.joinCodeRequired || item?.outside); - getUserPresence = (uid: string) => RocketChat.getUserPresence(uid); - - getUidDirectMessage = (room: ISubscription) => RocketChat.getUidDirectMessage(room); + handleGetUserPresence = (uid: string) => getUserPresence(uid); get isGrouping() { const { showUnread, showFavorites, groupByType } = this.props; @@ -679,7 +679,7 @@ class RoomsListView extends React.Component { @@ -699,11 +699,11 @@ class RoomsListView extends React.Component { - logEvent(isRead ? events.RL_UNREAD_CHANNEL : events.RL_READ_CHANNEL); + toggleRead = async (rid: string, tIsRead: boolean) => { + logEvent(tIsRead ? events.RL_UNREAD_CHANNEL : events.RL_READ_CHANNEL); try { const db = database.active; - const result = await RocketChat.toggleRead(isRead, rid); + const result = await Services.toggleRead(tIsRead, rid); if (result.success) { const subCollection = db.get('subscriptions'); @@ -711,7 +711,7 @@ class RoomsListView extends React.Component { - sub.alert = isRead; + sub.alert = tIsRead; sub.unread = 0; }); } catch (e) { @@ -729,7 +729,7 @@ class RoomsListView extends React.Component { @@ -946,7 +946,7 @@ class RoomsListView extends React.Component ({ length: ITEM_WIDTH, offset: ITEM_WIDTH * index, index }); @@ -117,13 +117,13 @@ class SelectedUsersView extends React.Component { + handleSearch = async (text: string) => { // TODO: When migrate rocketchat.js pass the param IUser to there and the return should be // IUser | TSubscriptionModel, this because we do a local search too - const result = (await RocketChat.search({ text, filterRooms: false })) as ISelectedUser[]; + const result = (await search({ text, filterRooms: false })) as ISelectedUser[]; this.setState({ search: result }); @@ -260,7 +260,7 @@ class SelectedUsersView extends React.Component 0 ? search : chats) // filter DM between multiple users - .filter(sub => !RocketChat.isGroupChat(sub as ISubscription)); + .filter(sub => !isGroupChat(sub as ISubscription)); return ( ; @@ -39,7 +39,7 @@ const SendEmailConfirmationView = ({ navigation, route }: ISendEmailConfirmation } try { setIsFetching(true); - const result = await RocketChat.sendConfirmationEmail(email); + const result = await Services.sendConfirmationEmail(email); if (result.success) { navigation.pop(); showErrorAlert(I18n.t('Verify_email_desc')); diff --git a/app/views/SetUsernameView.tsx b/app/views/SetUsernameView.tsx index 479e755ed..5bb8858b1 100644 --- a/app/views/SetUsernameView.tsx +++ b/app/views/SetUsernameView.tsx @@ -14,7 +14,6 @@ import StatusBar from '../containers/StatusBar'; import TextInput from '../containers/TextInput'; import { IApplicationState } from '../definitions'; import I18n from '../i18n'; -import RocketChat from '../lib/rocketchat'; import KeyboardView from '../containers/KeyboardView'; import { getUserSelector } from '../selectors/login'; import { TSupportedThemes, withTheme } from '../theme'; @@ -22,6 +21,7 @@ import { isTablet } from '../utils/deviceInfo'; import { showErrorAlert } from '../utils/info'; import scrollPersistTaps from '../utils/scrollPersistTaps'; import sharedStyles from './Styles'; +import { Services } from '../lib/services'; const styles = StyleSheet.create({ loginTitle: { @@ -64,7 +64,7 @@ class SetUsernameView extends React.Component { server: IServer; @@ -96,10 +97,10 @@ class SettingsView extends React.Component { dispatch } = this.props; dispatch(appStart({ root: RootEnum.ROOT_LOADING, text: I18n.t('Clear_cache_loading') })); - await RocketChat.clearCache({ server }); + await clearCache({ server }); await FastImage.clearMemoryCache(); await FastImage.clearDiskCache(); - RocketChat.disconnect(); + Services.disconnect(); dispatch(selectServerRequest(server)); } }); diff --git a/app/views/ShareListView/index.tsx b/app/views/ShareListView/index.tsx index 0a5f34b4e..c6afa7dc5 100644 --- a/app/views/ShareListView/index.tsx +++ b/app/views/ShareListView/index.tsx @@ -20,11 +20,11 @@ import { themes } from '../../lib/constants'; import { animateNextTransition } from '../../utils/layoutAnimation'; import { TSupportedThemes, withTheme } from '../../theme'; import SafeAreaView from '../../containers/SafeAreaView'; -import RocketChat from '../../lib/rocketchat'; import { sanitizeLikeString } from '../../lib/database/utils'; import styles from './styles'; import ShareListHeader from './Header'; import { IServerInfo } from '../../definitions'; +import { getRoomAvatar } from '../../lib/methods'; interface IDataFromShare { value: string; @@ -389,7 +389,7 @@ class ShareListView extends React.Component { return ( this.shareMessage(item)} diff --git a/app/views/ShareView/Header.tsx b/app/views/ShareView/Header.tsx index ecbbbbe97..f6c3d9c4f 100644 --- a/app/views/ShareView/Header.tsx +++ b/app/views/ShareView/Header.tsx @@ -3,13 +3,13 @@ import { StyleSheet, Text, View } from 'react-native'; import I18n from '../../i18n'; import { CustomIcon } from '../../lib/Icons'; -import RocketChat from '../../lib/rocketchat'; import { themes } from '../../lib/constants'; import { useTheme } from '../../theme'; import { isAndroid, isTablet } from '../../utils/deviceInfo'; import sharedStyles from '../Styles'; import { makeThreadName } from '../../utils/room'; import { ISubscription } from '../../definitions'; +import { getRoomTitle, isGroupChat } from '../../lib/methods'; const androidMarginLeft = isTablet ? 0 : 4; @@ -60,7 +60,7 @@ const Header = React.memo(({ room, thread }: IHeader) => { } else if (type === 'l') { icon = 'omnichannel'; } else if (type === 'd') { - if (RocketChat.isGroupChat(room)) { + if (isGroupChat(room)) { icon = 'team'; } else { icon = 'mention'; @@ -75,7 +75,7 @@ const Header = React.memo(({ room, thread }: IHeader) => { if (thread?.id) { title = makeThreadName(thread); } else { - title = RocketChat.getRoomTitle(room); + title = getRoomTitle(room); } return ( diff --git a/app/views/ShareView/index.tsx b/app/views/ShareView/index.tsx index 5d842866d..e98e11628 100644 --- a/app/views/ShareView/index.tsx +++ b/app/views/ShareView/index.tsx @@ -14,7 +14,6 @@ import * as HeaderButton from '../../containers/HeaderButton'; import { isBlocked } from '../../utils/room'; import { isReadOnly } from '../../utils/isReadOnly'; import { TSupportedThemes, withTheme } from '../../theme'; -import RocketChat from '../../lib/rocketchat'; import TextInput from '../../containers/TextInput'; import MessageBox from '../../containers/MessageBox'; import SafeAreaView from '../../containers/SafeAreaView'; @@ -29,6 +28,7 @@ import Header from './Header'; import styles from './styles'; import { IAttachment } from './interfaces'; import { IUser, TSubscriptionModel } from '../../definitions'; +import { hasPermission, sendFileMessage, sendMessage } from '../../lib/methods'; interface IShareViewState { selected: IAttachment; @@ -144,7 +144,7 @@ class ShareView extends Component { const permissionsCollection = db.get('permissions'); const uploadFilePermissionFetch = await permissionsCollection.query(Q.where('id', Q.like('mobile-upload-file'))).fetch(); const uploadFilePermission = uploadFilePermissionFetch[0]?.roles; - const permissionToUpload = await RocketChat.hasPermission([uploadFilePermission], room.rid); + const permissionToUpload = await hasPermission([uploadFilePermission], room.rid); // uploadFilePermission as undefined is considered that there isn't this permission, so all can upload file. return !uploadFilePermission || permissionToUpload[0]; }; @@ -218,7 +218,7 @@ class ShareView extends Component { await Promise.all( attachments.map(({ filename: name, mime: type, description, size, path, canUpload }) => { if (canUpload) { - return RocketChat.sendFileMessage( + return sendFileMessage( room.rid, { name, @@ -240,7 +240,7 @@ class ShareView extends Component { // Send text message } else if (text.length) { - await RocketChat.sendMessage(room.rid, text, thread?.id, { id: user.id, token: user.token } as IUser); + await sendMessage(room.rid, text, thread?.id, { id: user.id, token: user.token } as IUser); } } catch { // Do nothing diff --git a/app/views/StatusView.tsx b/app/views/StatusView.tsx index 8a11e12cc..ca44c2a15 100644 --- a/app/views/StatusView.tsx +++ b/app/views/StatusView.tsx @@ -12,7 +12,7 @@ import TextInput from '../containers/TextInput'; import { LISTENER } from '../containers/Toast'; import { IApplicationState, IBaseScreen, IUser, TUserStatus } from '../definitions'; import I18n from '../i18n'; -import RocketChat from '../lib/rocketchat'; +import { Services } from '../lib/services'; import { getUserSelector } from '../selectors/login'; import { withTheme } from '../theme'; import EventEmitter from '../utils/events'; @@ -111,7 +111,7 @@ class StatusView extends React.Component { this.setState({ loading: true }); try { - const result = await RocketChat.setUserStatus(user.status, statusText); + const result = await Services.setUserStatus(user.status, statusText); if (result.success) { logEvent(events.STATUS_CUSTOM); dispatch(setUser({ statusText })); @@ -161,7 +161,7 @@ class StatusView extends React.Component { logEvent(events[`STATUS_${item.id.toUpperCase()}`]); if (user.status !== item.id) { try { - const result = await RocketChat.setUserStatus(item.id, statusText); + const result = await Services.setUserStatus(item.id, statusText); if (result.success) { dispatch(setUser({ status: item.id })); } diff --git a/app/views/TeamChannelsView.tsx b/app/views/TeamChannelsView.tsx index 2ddd5435d..94bd78072 100644 --- a/app/views/TeamChannelsView.tsx +++ b/app/views/TeamChannelsView.tsx @@ -23,7 +23,6 @@ import { withDimensions } from '../dimensions'; import I18n from '../i18n'; import database from '../lib/database'; import { CustomIcon } from '../lib/Icons'; -import RocketChat from '../lib/rocketchat'; import RoomItem, { ROW_HEIGHT } from '../containers/RoomItem'; import { getUserSelector } from '../selectors/login'; import { ChatsStackParamList } from '../stacks/types'; @@ -33,6 +32,8 @@ import { isIOS } from '../utils/deviceInfo'; import { goRoom } from '../utils/goRoom'; import { showErrorAlert } from '../utils/info'; import log, { events, logEvent } from '../utils/log'; +import { getRoomAvatar, getRoomTitle, hasPermission } from '../lib/methods'; +import { Services } from '../lib/services'; const API_FETCH_COUNT = 25; const PERMISSION_DELETE_C = 'delete-c'; @@ -48,7 +49,7 @@ const getItemLayout = (data: IItem[] | null | undefined, index: number) => ({ }); const keyExtractor = (item: IItem) => item._id; -// This interface comes from request RocketChat.getTeamListRoom +// This interface comes from request getTeamListRoom interface IItem { _id: ERoomType; fname: string; @@ -146,7 +147,7 @@ class TeamChannelsView extends React.Component this.setHeader()); } @@ -171,7 +172,7 @@ class TeamChannelsView extends React.Component navigation.pop()} tintColor={themes[theme].headerTintColor} /> ), headerTitle: () => ( - + ) }; @@ -341,21 +336,17 @@ class TeamChannelsView extends React.Component RocketChat.getRoomTitle(item); - - getRoomAvatar = (item: IItem) => RocketChat.getRoomAvatar(item); - onPressItem = debounce( async (item: IItem) => { logEvent(events.TC_GO_ROOM); const { navigation, isMasterDetail } = this.props; try { let params = {}; - const result = await RocketChat.getRoomInfo(item._id); + const result = await Services.getRoomInfo(item._id); if (result.success) { params = { rid: item._id, - name: RocketChat.getRoomTitle(result.room), + name: getRoomTitle(result.room), joinCodeRequired: result.room.joinCodeRequired, t: result.room.t, teamId: result.room.teamId @@ -381,7 +372,7 @@ class TeamChannelsView extends React.Component { if (i._id === item._id) { @@ -420,7 +411,7 @@ class TeamChannelsView extends React.Component result.room._id !== room._id); this.setState({ data: newData }); @@ -470,7 +461,7 @@ class TeamChannelsView extends React.Component { try { - await RocketChat.toggleFollowMessage(tmid, !isFollowingThread); + await Services.toggleFollowMessage(tmid, !isFollowingThread); EventEmitter.emit(LISTENER, { message: isFollowingThread ? I18n.t('Unfollowed_thread') : I18n.t('Following_thread') }); } catch (e) { log(e); diff --git a/app/views/UserNotificationPreferencesView/index.tsx b/app/views/UserNotificationPreferencesView/index.tsx index f1d460113..b4c1c44d1 100644 --- a/app/views/UserNotificationPreferencesView/index.tsx +++ b/app/views/UserNotificationPreferencesView/index.tsx @@ -7,7 +7,6 @@ import { 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 SafeAreaView from '../../containers/SafeAreaView'; import ActivityIndicator from '../../containers/ActivityIndicator'; @@ -16,6 +15,7 @@ import sharedStyles from '../Styles'; import { OPTIONS } from './options'; import { ProfileStackParamList } from '../../stacks/types'; import { INotificationPreferences, IUser } from '../../definitions'; +import { Services } from '../../lib/services'; const styles = StyleSheet.create({ pickerText: { @@ -56,7 +56,7 @@ class UserNotificationPreferencesView extends React.Component< async componentDidMount() { const { user } = this.props; const { id } = user; - const result = await RocketChat.getUserPreferences(id); + const result = await Services.getUserPreferences(id); if (result.success) { const { preferences } = result; this.setState({ preferences, loading: true }); @@ -108,7 +108,7 @@ class UserNotificationPreferencesView extends React.Component< saveNotificationPreferences = async (params: { [key: string]: string }) => { const { user } = this.props; const { id } = user; - const result = await RocketChat.setUserPreferences(id, params); + const result = await Services.setUserPreferences(id, params); if (result.success) { const { user: { settings } diff --git a/app/views/UserPreferencesView/index.tsx b/app/views/UserPreferencesView/index.tsx index a2319c036..7d894e426 100644 --- a/app/views/UserPreferencesView/index.tsx +++ b/app/views/UserPreferencesView/index.tsx @@ -11,9 +11,9 @@ import StatusBar from '../../containers/StatusBar'; import * as List from '../../containers/List'; import { SWITCH_TRACK_COLOR } from '../../lib/constants'; import { getUserSelector } from '../../selectors/login'; -import RocketChat from '../../lib/rocketchat'; import { ProfileStackParamList } from '../../stacks/types'; import { IApplicationState } from '../../definitions'; +import { Services } from '../../lib/services'; interface IUserPreferencesViewProps { navigation: StackNavigationProp; @@ -37,7 +37,7 @@ const UserPreferencesView = ({ navigation }: IUserPreferencesViewProps): JSX.Ele const toggleMessageParser = async (value: boolean) => { try { dispatch(setUser({ enableMessageParserEarlyAdoption: value })); - await RocketChat.saveUserPreferences({ id, enableMessageParserEarlyAdoption: value }); + await Services.saveUserPreferences({ id, enableMessageParserEarlyAdoption: value }); } catch (e) { log(e); }