Chore: Migrate lib/utils to TypeScript (#3637)

* Migrate utils to TypeScript

* Add @types/semver

* Refactor compareServerVersion(currentVersion, oldVersion, func) to compareServerVersion(current, func, oldVersion)

Co-authored-by: Diego Mello <diegolmello@gmail.com>
This commit is contained in:
Gerzon Z 2022-02-07 14:44:04 -04:00 committed by GitHub
parent d894c6aab8
commit 2d1b093666
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 72 additions and 58 deletions

View File

@ -19,5 +19,5 @@ export interface IAvatar {
isStatic?: boolean | string;
rid?: string;
blockUnauthenticatedAccess?: boolean;
serverVersion?: string;
serverVersion: string;
}

View File

@ -214,7 +214,7 @@ const Reply = React.memo(
if (!url) {
return;
}
if (attachment.type === 'file') {
if (attachment.type === 'file' && attachment.title_link) {
setLoading(true);
url = formatAttachmentUrl(attachment.title_link, user.id, user.token, baseUrl);
await fileDownloadAndPreview(url, attachment);

View File

@ -50,7 +50,7 @@ const Video = React.memo(
return showAttachment(file);
}
if (!isIOS) {
if (!isIOS && file.video_url) {
const uri = formatAttachmentUrl(file.video_url, user.id, user.token, baseUrl);
await downloadVideo(uri);
return;

View File

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

View File

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

View File

@ -2,7 +2,7 @@ import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { Q } from '@nozbe/watermelondb';
import orderBy from 'lodash/orderBy';
import { compareServerVersion, methods } from '../utils';
import { compareServerVersion } from '../utils';
import database from '../database';
import log from '../../utils/log';
import reduxStore from '../createStore';
@ -146,7 +146,7 @@ export function getPermissions() {
const allRecords = await permissionsCollection.query().fetch();
RocketChat.subscribe('stream-notify-logged', 'permissions-changed');
// if server version is lower than 0.73.0, fetches from old api
if (compareServerVersion(serverVersion, '0.73.0', methods.lowerThan)) {
if (compareServerVersion(serverVersion, 'lowerThan', '0.73.0')) {
// RC 0.66.0
const result = await this.sdk.get('permissions.list');
if (!result.success) {

View File

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

View File

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

View File

@ -26,7 +26,7 @@ import EventEmitter from '../utils/events';
import { updatePermission } from '../actions/permissions';
import { TEAM_TYPE } from '../definitions/ITeam';
import { updateSettings } from '../actions/settings';
import { compareServerVersion, methods } from './utils';
import { compareServerVersion } from './utils';
import reduxStore from './createStore';
import database from './database';
import subscribeRooms from './methods/subscriptions/rooms';
@ -138,7 +138,7 @@ const RocketChat = {
message: I18n.t('Not_RC_Server', { contact: I18n.t('Contact_your_server_admin') })
};
}
if (compareServerVersion(jsonRes.version, MIN_ROCKETCHAT_VERSION, methods.lowerThan)) {
if (compareServerVersion(jsonRes.version, 'lowerThan', MIN_ROCKETCHAT_VERSION)) {
return {
success: false,
message: I18n.t('Invalid_server_version', {
@ -549,7 +549,7 @@ const RocketChat = {
// Force normalized params for 2FA starting RC 3.9.0.
const serverVersion = reduxStore.getState().server.version;
if (compareServerVersion(serverVersion, '3.9.0', methods.greaterThanOrEqualTo)) {
if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '3.9.0')) {
const user = params.user ?? params.username;
const password = params.password ?? params.ldapPass ?? params.crowdPassword;
params = { user, password };
@ -1059,7 +1059,7 @@ const RocketChat = {
},
async getRoomMembers({ rid, allUsers, roomType, type, filter, skip = 0, limit = 10 }) {
const serverVersion = reduxStore.getState().server.version;
if (compareServerVersion(serverVersion, '3.16.0', methods.greaterThanOrEqualTo)) {
if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '3.16.0')) {
const params = {
roomId: rid,
offset: skip,
@ -1587,7 +1587,7 @@ const RocketChat = {
},
readThreads(tmid) {
const serverVersion = reduxStore.getState().server.version;
if (compareServerVersion(serverVersion, '3.4.0', methods.greaterThanOrEqualTo)) {
if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '3.4.0')) {
// RC 3.4.0
return this.methodCallWrapper('readThreads', tmid);
}

View File

@ -1,23 +0,0 @@
import { coerce, gt, gte, lt, lte } from 'semver';
export const formatAttachmentUrl = (attachmentUrl, userId, token, server) => {
if (attachmentUrl.startsWith('http')) {
if (attachmentUrl.includes('rc_token')) {
return encodeURI(attachmentUrl);
}
return encodeURI(`${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);
export const generateLoadMoreId = id => `load-more-${id}`;

27
app/lib/utils.ts Normal file
View File

@ -0,0 +1,27 @@
import { coerce, gt, gte, lt, lte, SemVer } from 'semver';
export const formatAttachmentUrl = (attachmentUrl: string, userId: string, token: string, server: string): string => {
if (attachmentUrl.startsWith('http')) {
if (attachmentUrl.includes('rc_token')) {
return encodeURI(attachmentUrl);
}
return encodeURI(`${attachmentUrl}?rc_uid=${userId}&rc_token=${token}`);
}
return encodeURI(`${server}${attachmentUrl}?rc_uid=${userId}&rc_token=${token}`);
};
const methods = {
lowerThan: lt,
lowerThanOrEqualTo: lte,
greaterThan: gt,
greaterThanOrEqualTo: gte
};
export const compareServerVersion = (
currentServerVersion: string,
method: keyof typeof methods,
versionToCompare: string
): boolean =>
(currentServerVersion && methods[method](coerce(currentServerVersion) as string | SemVer, versionToCompare)) as boolean;
export const generateLoadMoreId = (id: string): string => `load-more-${id}`;

View File

@ -1,4 +1,4 @@
import { compareServerVersion, methods } from '../lib/utils';
import { compareServerVersion } from '../lib/utils';
import { SubscriptionType } from '../definitions/ISubscription';
import { IAvatar } from '../containers/Avatar/interfaces';
@ -19,7 +19,7 @@ export const avatarURL = ({
let room;
if (type === SubscriptionType.DIRECT) {
room = text;
} else if (rid && !compareServerVersion(serverVersion, '3.6.0', methods.lowerThan)) {
} else if (rid && !compareServerVersion(serverVersion, 'lowerThan', '3.6.0')) {
room = `room/${rid}`;
} else {
room = `@${text}`;

View File

@ -107,8 +107,12 @@ class AttachmentView extends React.Component<IAttachmentViewProps, IAttachmentVi
const { user, baseUrl } = this.props;
const { title_link, image_url, image_type, video_url, video_type } = attachment;
const url = title_link || image_url || video_url;
const mediaAttachment = formatAttachmentUrl(url, user.id, user.token, baseUrl);
if (!url) {
return;
}
const mediaAttachment = formatAttachmentUrl(url, user.id, user.token, baseUrl);
if (isAndroid) {
const rationale = {
title: I18n.t('Write_External_Permission'),

View File

@ -18,7 +18,7 @@ import database from '../lib/database';
import { CustomIcon } from '../lib/Icons';
import Navigation from '../lib/Navigation';
import RocketChat from '../lib/rocketchat';
import { compareServerVersion, methods } from '../lib/utils';
import { compareServerVersion } from '../lib/utils';
import UserItem from '../presentation/UserItem';
import { withTheme } from '../theme';
import { goRoom } from '../utils/goRoom';
@ -247,7 +247,7 @@ class NewMessageView extends React.Component<INewMessageViewProps, INewMessageVi
first: true
})
: null}
{compareServerVersion(serverVersion, '3.13.0', methods.greaterThanOrEqualTo) && permissions[2]
{compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '3.13.0') && permissions[2]
? this.renderButton({
onPress: this.createTeam,
title: I18n.t('Create_Team'),

View File

@ -5,7 +5,7 @@ import { connect } from 'react-redux';
import isEmpty from 'lodash/isEmpty';
import { Q } from '@nozbe/watermelondb';
import { compareServerVersion, methods } from '../../lib/utils';
import { compareServerVersion } from '../../lib/utils';
import Touch from '../../utils/touch';
import { setLoading as setLoadingAction } from '../../actions/selectedUsers';
import { closeRoom as closeRoomAction, leaveRoom as leaveRoomAction } from '../../actions/room';
@ -320,7 +320,7 @@ class RoomActionsView extends React.Component {
const { encrypted } = room;
const { serverVersion } = this.props;
let hasPermission = false;
if (compareServerVersion(serverVersion, '3.11.0', methods.lowerThan)) {
if (compareServerVersion(serverVersion, 'lowerThan', '3.11.0')) {
hasPermission = canEdit;
} else {
hasPermission = canToggleEncryption;

View File

@ -8,7 +8,7 @@ import { dequal } from 'dequal';
import isEmpty from 'lodash/isEmpty';
import { Q } from '@nozbe/watermelondb';
import { compareServerVersion, methods } from '../../lib/utils';
import { compareServerVersion } from '../../lib/utils';
import database from '../../lib/database';
import { deleteRoom as deleteRoomAction } from '../../actions/room';
import KeyboardView from '../../presentation/KeyboardView';
@ -538,7 +538,7 @@ class RoomInfoEditView extends React.Component {
<TouchableOpacity
style={styles.avatarContainer}
onPress={this.changeAvatar}
disabled={compareServerVersion(serverVersion, '3.6.0', methods.lowerThan)}>
disabled={compareServerVersion(serverVersion, 'lowerThan', '3.6.0')}>
<Avatar
type={room.t}
text={room.name}
@ -546,7 +546,7 @@ class RoomInfoEditView extends React.Component {
isStatic={avatar?.url}
rid={isEmpty(avatar) && room.rid}
size={100}>
{compareServerVersion(serverVersion, '3.6.0', methods.lowerThan) ? null : (
{compareServerVersion(serverVersion, 'lowerThan', '3.6.0') ? null : (
<TouchableOpacity
style={[styles.resetButton, { backgroundColor: themes[theme].dangerColor }]}
onPress={this.resetAvatar}>
@ -670,7 +670,7 @@ class RoomInfoEditView extends React.Component {
<View style={[styles.divider, { borderColor: themes[theme].separatorColor }]} />
]
: null}
{!compareServerVersion(serverVersion, '3.0.0', methods.lowerThan) ? (
{!compareServerVersion(serverVersion, 'lowerThan', '3.0.0') ? (
<SwitchContainer
value={enableSysMes}
leftLabelPrimary={I18n.t('Hide_System_Messages')}

View File

@ -14,7 +14,7 @@ import { animateNextTransition } from '../../../utils/layoutAnimation';
import ActivityIndicator from '../../../containers/ActivityIndicator';
import { themes } from '../../../constants/colors';
import debounce from '../../../utils/debounce';
import { compareServerVersion, methods } from '../../../lib/utils';
import { compareServerVersion } from '../../../lib/utils';
import List from './List';
import NavBottomFAB from './NavBottomFAB';
@ -179,7 +179,7 @@ class ListContainer extends React.Component {
* Since 3.16.0 server version, the backend don't response with messages if
* hide system message is enabled
*/
if (compareServerVersion(serverVersion, '3.16.0', methods.lowerThan) || hideSystemMessages.length) {
if (compareServerVersion(serverVersion, 'lowerThan', '3.16.0') || hideSystemMessages.length) {
messages = messages.filter(m => !m.t || !hideSystemMessages?.includes(m.t));
}

View File

@ -29,7 +29,7 @@ import { sanitizeLikeString } from '../../lib/database/utils';
import getThreadName from '../../lib/methods/getThreadName';
import getRoomInfo from '../../lib/methods/getRoomInfo';
import { isIOS } from '../../utils/deviceInfo';
import { compareServerVersion, methods } from '../../lib/utils';
import { compareServerVersion } from '../../lib/utils';
import styles from './styles';
import { InsideStackParamList, ChatsStackParamList } from '../../stacks/types';
@ -235,7 +235,7 @@ class SearchMessagesView extends React.Component<ISearchMessagesViewProps, ISear
messages.length < this.offset ||
this.encrypted ||
loading ||
compareServerVersion(serverVersion, '3.17.0', methods.lowerThan)
compareServerVersion(serverVersion, 'lowerThan', '3.17.0')
) {
return;
}

View File

@ -155,6 +155,7 @@
"@types/react-native-scrollable-tab-view": "^0.10.2",
"@types/react-redux": "^7.1.18",
"@types/react-test-renderer": "^17.0.1",
"@types/semver": "^7.3.9",
"@types/url-parse": "^1.4.6",
"@typescript-eslint/eslint-plugin": "^4.28.3",
"@typescript-eslint/parser": "^4.28.5",

View File

@ -4496,6 +4496,11 @@
resolved "https://registry.yarnpkg.com/@types/scheduler/-/scheduler-0.16.1.tgz#18845205e86ff0038517aab7a18a62a6b9f71275"
integrity sha512-EaCxbanVeyxDRTQBkdLb3Bvl/HK7PBK6UJjsSixB0iHKoWxE5uu2Q/DgtpOhPIojN0Zl1whvOd7PoHs2P0s5eA==
"@types/semver@^7.3.9":
version "7.3.9"
resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.9.tgz#152c6c20a7688c30b967ec1841d31ace569863fc"
integrity sha512-L/TMpyURfBkf+o/526Zb6kd/tchUP3iBDEPjqjb+U2MAJhVRxxrmr2fwpe08E7QsV7YLcpq0tUaQ9O9x97ZIxQ==
"@types/source-list-map@*":
version "0.1.2"
resolved "https://registry.yarnpkg.com/@types/source-list-map/-/source-list-map-0.1.2.tgz#0078836063ffaf17412349bba364087e0ac02ec9"