[CHORE] Simplify server version comparison (#2922)

* Simplify server version where needed

* Added lte and gte functions and updated imports

* Updated functions names

* Update util functions

* Update util function and added methods

* Remove lt and coerce from getPermissions and mergeSubscriptionsRooms

* Fix comparison

* Update getPermissions.js

* Remove unused import

* Fix lint

* Fix lint

Co-authored-by: Diego Mello <diegolmello@gmail.com>
This commit is contained in:
Gerzon Z 2021-03-18 09:33:35 -04:00 committed by GitHub
parent 45d0d4a5f0
commit 460e82f759
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 37 additions and 37 deletions

View File

@ -1,5 +1,4 @@
import gte from 'semver/functions/gte'; import { compareServerVersion, methods } from '../utils';
import coerce from 'semver/functions/coerce';
import reduxStore from '../createStore'; import reduxStore from '../createStore';
import database from '../database'; import database from '../database';
@ -34,7 +33,7 @@ export function getEnterpriseModules() {
return new Promise(async(resolve) => { return new Promise(async(resolve) => {
try { try {
const { version: serverVersion, server: serverId } = reduxStore.getState().server; const { version: serverVersion, server: serverId } = reduxStore.getState().server;
if (serverVersion && gte(coerce(serverVersion), '3.1.0')) { if (compareServerVersion(serverVersion, '3.1.0', methods.greaterThanOrEqualTo)) {
// RC 3.1.0 // RC 3.1.0
const enterpriseModules = await this.methodCallWrapper('license:getModules'); const enterpriseModules = await this.methodCallWrapper('license:getModules');
if (enterpriseModules) { if (enterpriseModules) {

View File

@ -1,7 +1,7 @@
import lt from 'semver/functions/lt';
import orderBy from 'lodash/orderBy'; import orderBy from 'lodash/orderBy';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord'; import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { compareServerVersion, methods } from '../utils';
import reduxStore from '../createStore'; import reduxStore from '../createStore';
import database from '../database'; import database from '../database';
import log from '../../utils/log'; import log from '../../utils/log';
@ -90,7 +90,7 @@ export function getCustomEmojis() {
const updatedSince = await getUpdatedSince(allRecords); const updatedSince = await getUpdatedSince(allRecords);
// if server version is lower than 0.75.0, fetches from old api // if server version is lower than 0.75.0, fetches from old api
if (serverVersion && lt(serverVersion, '0.75.0')) { if (compareServerVersion(serverVersion, '0.75.0', methods.lowerThan)) {
// RC 0.61.0 // RC 0.61.0
const result = await this.sdk.get('emoji-custom'); const result = await this.sdk.get('emoji-custom');

View File

@ -1,9 +1,8 @@
import lt from 'semver/functions/lt';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord'; import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { Q } from '@nozbe/watermelondb'; import { Q } from '@nozbe/watermelondb';
import coerce from 'semver/functions/coerce';
import orderBy from 'lodash/orderBy'; import orderBy from 'lodash/orderBy';
import { compareServerVersion, methods } from '../utils';
import database from '../database'; import database from '../database';
import log from '../../utils/log'; import log from '../../utils/log';
import reduxStore from '../createStore'; import reduxStore from '../createStore';
@ -123,7 +122,7 @@ export function getPermissions() {
const allRecords = await permissionsCollection.query().fetch(); const allRecords = await permissionsCollection.query().fetch();
// if server version is lower than 0.73.0, fetches from old api // if server version is lower than 0.73.0, fetches from old api
if (serverVersion && lt(coerce(serverVersion), '0.73.0')) { if (compareServerVersion(serverVersion, '0.73.0', methods.lowerThan)) {
// RC 0.66.0 // RC 0.66.0
const result = await this.sdk.get('permissions.list'); const result = await this.sdk.get('permissions.list');
if (!result.success) { if (!result.success) {

View File

@ -1,8 +1,7 @@
import { InteractionManager } from 'react-native'; import { InteractionManager } from 'react-native';
import lt from 'semver/functions/lt';
import gte from 'semver/functions/gte';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord'; import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { compareServerVersion, methods } from '../utils';
import reduxStore from '../createStore'; import reduxStore from '../createStore';
import { setActiveUsers } from '../../actions/activeUsers'; import { setActiveUsers } from '../../actions/activeUsers';
import { setUser } from '../../actions/login'; import { setUser } from '../../actions/login';
@ -12,7 +11,7 @@ export function subscribeUsersPresence() {
const serverVersion = reduxStore.getState().server.version; const serverVersion = reduxStore.getState().server.version;
// if server is lower than 1.1.0 // if server is lower than 1.1.0
if (serverVersion && lt(serverVersion, '1.1.0')) { if (compareServerVersion(serverVersion, '1.1.0', methods.lowerThan)) {
if (this.activeUsersSubTimeout) { if (this.activeUsersSubTimeout) {
clearTimeout(this.activeUsersSubTimeout); clearTimeout(this.activeUsersSubTimeout);
this.activeUsersSubTimeout = false; this.activeUsersSubTimeout = false;
@ -37,11 +36,11 @@ export default async function getUsersPresence() {
const { user: loggedUser } = reduxStore.getState().login; const { user: loggedUser } = reduxStore.getState().login;
// if server is greather than or equal 1.1.0 // if server is greather than or equal 1.1.0
if (serverVersion && gte(serverVersion, '1.1.0')) { if (compareServerVersion(serverVersion, '1.1.0', methods.greaterThanOrEqualTo)) {
let params = {}; let params = {};
// if server is greather than or equal 3.0.0 // if server is greather than or equal 3.0.0
if (serverVersion && gte(serverVersion, '3.0.0')) { if (compareServerVersion(serverVersion, '3.0.0', methods.greaterThanOrEqualTo)) {
// if not have any id // if not have any id
if (!ids.length) { if (!ids.length) {
return; return;

View File

@ -1,10 +1,10 @@
import EJSON from 'ejson'; import EJSON from 'ejson';
import { lt, coerce } from 'semver';
import normalizeMessage from './normalizeMessage'; import normalizeMessage from './normalizeMessage';
import findSubscriptionsRooms from './findSubscriptionsRooms'; import findSubscriptionsRooms from './findSubscriptionsRooms';
import { Encryption } from '../../encryption'; import { Encryption } from '../../encryption';
import reduxStore from '../../createStore'; import reduxStore from '../../createStore';
import { compareServerVersion, methods } from '../../utils';
// TODO: delete and update // TODO: delete and update
export const merge = (subscription, room) => { export const merge = (subscription, room) => {
@ -28,7 +28,7 @@ export const merge = (subscription, room) => {
subscription.usernames = room.usernames; subscription.usernames = room.usernames;
subscription.uids = room.uids; subscription.uids = room.uids;
} }
if (serverVersion && lt(coerce(serverVersion), '3.7.0')) { if (compareServerVersion(serverVersion, '3.7.0', methods.lowerThan)) {
const updatedAt = room?._updatedAt ? new Date(room._updatedAt) : null; const updatedAt = room?._updatedAt ? new Date(room._updatedAt) : null;
const lastMessageTs = subscription?.lastMessage?.ts ? new Date(subscription.lastMessage.ts) : null; const lastMessageTs = subscription?.lastMessage?.ts ? new Date(subscription.lastMessage.ts) : null;
subscription.roomUpdatedAt = Math.max(updatedAt, lastMessageTs); subscription.roomUpdatedAt = Math.max(updatedAt, lastMessageTs);

View File

@ -1,7 +1,4 @@
import { InteractionManager } from 'react-native'; import { InteractionManager } from 'react-native';
import lt from 'semver/functions/lt';
import gte from 'semver/functions/gte';
import coerce from 'semver/functions/coerce';
import { import {
Rocketchat as RocketchatClient, Rocketchat as RocketchatClient,
settings as RocketChatSettings settings as RocketChatSettings
@ -11,6 +8,7 @@ import AsyncStorage from '@react-native-community/async-storage';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord'; import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import RNFetchBlob from 'rn-fetch-blob'; import RNFetchBlob from 'rn-fetch-blob';
import { compareServerVersion, methods } from './utils';
import reduxStore from './createStore'; import reduxStore from './createStore';
import defaultSettings from '../constants/settings'; import defaultSettings from '../constants/settings';
import database from './database'; import database from './database';
@ -133,7 +131,7 @@ const RocketChat = {
message: I18n.t('Not_RC_Server', { contact: I18n.t('Contact_your_server_admin') }) message: I18n.t('Not_RC_Server', { contact: I18n.t('Contact_your_server_admin') })
}; };
} }
if (lt(jsonRes.version, MIN_ROCKETCHAT_VERSION)) { if (compareServerVersion(jsonRes.version, MIN_ROCKETCHAT_VERSION, methods.lowerThan)) {
return { return {
success: false, success: false,
message: I18n.t('Invalid_server_version', { message: I18n.t('Invalid_server_version', {
@ -472,7 +470,7 @@ const RocketChat = {
// Force normalized params for 2FA starting RC 3.9.0. // Force normalized params for 2FA starting RC 3.9.0.
const serverVersion = reduxStore.getState().server.version; const serverVersion = reduxStore.getState().server.version;
if (serverVersion && gte(coerce(serverVersion), '3.9.0')) { if (compareServerVersion(serverVersion, '3.9.0', methods.greaterThanOrEqualTo)) {
const user = params.user ?? params.username; const user = params.user ?? params.username;
const password = params.password ?? params.ldapPass ?? params.crowdPassword; const password = params.password ?? params.ldapPass ?? params.crowdPassword;
params = { user, password }; params = { user, password };
@ -1364,7 +1362,7 @@ const RocketChat = {
}, },
readThreads(tmid) { readThreads(tmid) {
const serverVersion = reduxStore.getState().server.version; const serverVersion = reduxStore.getState().server.version;
if (serverVersion && gte(coerce(serverVersion), '3.4.0')) { if (compareServerVersion(serverVersion, '3.4.0', methods.greaterThanOrEqualTo)) {
// RC 3.4.0 // RC 3.4.0
return this.methodCallWrapper('readThreads', tmid); return this.methodCallWrapper('readThreads', tmid);
} }

View File

@ -1,3 +1,7 @@
import {
lt, lte, gt, gte, coerce
} from 'semver';
export const formatAttachmentUrl = (attachmentUrl, userId, token, server) => { export const formatAttachmentUrl = (attachmentUrl, userId, token, server) => {
if (attachmentUrl.startsWith('http')) { if (attachmentUrl.startsWith('http')) {
if (attachmentUrl.includes('rc_token')) { if (attachmentUrl.includes('rc_token')) {
@ -7,3 +11,12 @@ export const formatAttachmentUrl = (attachmentUrl, userId, token, server) => {
} }
return encodeURI(`${ server }${ attachmentUrl }?rc_uid=${ userId }&rc_token=${ token }`); return encodeURI(`${ server }${ attachmentUrl }?rc_uid=${ userId }&rc_token=${ token }`);
}; };
export const methods = {
lowerThan: lt,
lowerThanOrEqualTo: lte,
greaterThan: gt,
greaterThanOrEqualTo: gte
};
export const compareServerVersion = (currentServerVersion, versionToCompare, func) => currentServerVersion && func(coerce(currentServerVersion), versionToCompare);

View File

@ -1,5 +1,4 @@
import lt from 'semver/functions/lt'; import { compareServerVersion, methods } from '../lib/utils';
import coerce from 'semver/functions/coerce';
const formatUrl = (url, size, query) => `${ url }?format=png&size=${ size }${ query }`; const formatUrl = (url, size, query) => `${ url }?format=png&size=${ size }${ query }`;
@ -9,7 +8,7 @@ export const avatarURL = ({
let room; let room;
if (type === 'd') { if (type === 'd') {
room = text; room = text;
} else if (rid && !(serverVersion && lt(coerce(serverVersion), '3.6.0'))) { } else if (rid && !(compareServerVersion(serverVersion, '3.6.0', methods.lowerThan))) {
room = `room/${ rid }`; room = `room/${ rid }`;
} else { } else {
room = `@${ text }`; room = `@${ text }`;

View File

@ -5,8 +5,7 @@ import {
} from 'react-native'; } from 'react-native';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import isEmpty from 'lodash/isEmpty'; import isEmpty from 'lodash/isEmpty';
import lt from 'semver/functions/lt'; import { compareServerVersion, methods } from '../../lib/utils';
import coerce from 'semver/functions/coerce';
import Touch from '../../utils/touch'; import Touch from '../../utils/touch';
import { setLoading as setLoadingAction } from '../../actions/selectedUsers'; import { setLoading as setLoadingAction } from '../../actions/selectedUsers';
@ -256,7 +255,7 @@ class RoomActionsView extends React.Component {
const { encrypted } = room; const { encrypted } = room;
const { serverVersion } = this.props; const { serverVersion } = this.props;
let hasPermission = false; let hasPermission = false;
if (serverVersion && lt(coerce(serverVersion), '3.11.0')) { if (compareServerVersion(serverVersion, '3.11.0', methods.lowerThan)) {
hasPermission = canEdit; hasPermission = canEdit;
} else { } else {
hasPermission = canToggleEncryption; hasPermission = canToggleEncryption;

View File

@ -8,8 +8,7 @@ import { BLOCK_CONTEXT } from '@rocket.chat/ui-kit';
import ImagePicker from 'react-native-image-crop-picker'; import ImagePicker from 'react-native-image-crop-picker';
import { dequal } from 'dequal'; import { dequal } from 'dequal';
import isEmpty from 'lodash/isEmpty'; import isEmpty from 'lodash/isEmpty';
import lt from 'semver/functions/lt'; import { compareServerVersion, methods } from '../../lib/utils';
import coerce from 'semver/functions/coerce';
import database from '../../lib/database'; import database from '../../lib/database';
import { deleteRoom as deleteRoomAction } from '../../actions/room'; import { deleteRoom as deleteRoomAction } from '../../actions/room';
@ -418,11 +417,6 @@ class RoomInfoEditView extends React.Component {
this.setState({ encrypted: value }); this.setState({ encrypted: value });
} }
isServerVersionLowerThan = (version) => {
const { serverVersion } = this.props;
return serverVersion && lt(coerce(serverVersion), version);
}
render() { render() {
const { const {
name, nameError, description, topic, announcement, t, ro, reactWhenReadOnly, room, joinCode, saving, permissions, archived, enableSysMes, encrypted, avatar name, nameError, description, topic, announcement, t, ro, reactWhenReadOnly, room, joinCode, saving, permissions, archived, enableSysMes, encrypted, avatar
@ -449,7 +443,7 @@ class RoomInfoEditView extends React.Component {
<TouchableOpacity <TouchableOpacity
style={styles.avatarContainer} style={styles.avatarContainer}
onPress={this.changeAvatar} onPress={this.changeAvatar}
disabled={this.isServerVersionLowerThan('3.6.0')} disabled={compareServerVersion(serverVersion, '3.6.0', methods.lowerThan)}
> >
<Avatar <Avatar
type={room.t} type={room.t}
@ -459,7 +453,7 @@ class RoomInfoEditView extends React.Component {
rid={isEmpty(avatar) && room.rid} rid={isEmpty(avatar) && room.rid}
size={100} size={100}
> >
{this.isServerVersionLowerThan('3.6.0') {compareServerVersion(serverVersion, '3.6.0', methods.lowerThan)
? null ? null
: ( : (
<TouchableOpacity style={[styles.resetButton, { backgroundColor: themes[theme].dangerColor }]} onPress={this.resetAvatar}> <TouchableOpacity style={[styles.resetButton, { backgroundColor: themes[theme].dangerColor }]} onPress={this.resetAvatar}>
@ -560,7 +554,7 @@ class RoomInfoEditView extends React.Component {
] ]
: null : null
} }
{serverVersion && !lt(serverVersion, '3.0.0') ? ( {!compareServerVersion(serverVersion, '3.0.0', methods.lowerThan) ? (
<SwitchContainer <SwitchContainer
value={enableSysMes} value={enableSysMes}
leftLabelPrimary={I18n.t('Hide_System_Messages')} leftLabelPrimary={I18n.t('Hide_System_Messages')}