Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:RocketChat/Rocket.Chat into regr…
Browse files Browse the repository at this point in the history
…ession/livechat-takeInquiry-client-error
  • Loading branch information
aleksandernsilva committed Oct 3, 2022
2 parents bde974b + 0e6bc45 commit 79448e4
Show file tree
Hide file tree
Showing 69 changed files with 635 additions and 951 deletions.
30 changes: 20 additions & 10 deletions apps/meteor/app/api/server/lib/users.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,24 @@
import { escapeRegExp } from '@rocket.chat/string-helpers';
import type { IUser } from '@rocket.chat/core-typings';
import type { Filter } from 'mongodb';
import { Users } from '@rocket.chat/models';
import { Users, Subscriptions } from '@rocket.chat/models';
import type { Mongo } from 'meteor/mongo';

import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { settings } from '../../../settings/server';

type UserAutoComplete = Required<Pick<IUser, '_id' | 'name' | 'username' | 'nickname' | 'status' | 'avatarETag'>>;

export async function findUsersToAutocomplete({
uid,
selector,
}: {
uid: string;
selector: {
exceptions: string[];
conditions: Filter<IUser>;
term: string;
};
selector: { exceptions: Required<IUser>['username'][]; conditions: Filter<IUser>; term: string };
}): Promise<{
items: UserAutoComplete[];
}> {
if (!(await hasPermissionAsync(uid, 'view-outside-room'))) {
return { items: [] };
}
const searchFields = settings.get<string>('Accounts_SearchFields').trim().split(',');
const exceptions = selector.exceptions || [];
const conditions = selector.conditions || {};
const options = {
Expand All @@ -39,6 +35,20 @@ export async function findUsersToAutocomplete({
limit: 10,
};

// Search on DMs first, to list known users before others.
const contacts = await Subscriptions.findConnectedUsersExcept(uid, selector.term, exceptions, searchFields, conditions, 10, 'd');
if (contacts.length >= options.limit) {
return { items: contacts as UserAutoComplete[] };
}

options.limit -= contacts.length;
contacts.forEach(({ username }) => exceptions.push(username));

if (!(await hasPermissionAsync(uid, 'view-outside-room'))) {
const users = await Subscriptions.findConnectedUsersExcept(uid, selector.term, exceptions, searchFields, conditions, 10);
return { items: contacts.concat(users) as UserAutoComplete[] };
}

const users = await Users.findActiveByUsernameOrNameRegexWithExceptionsAndConditions<UserAutoComplete>(
new RegExp(escapeRegExp(selector.term), 'i'),
exceptions,
Expand All @@ -47,7 +57,7 @@ export async function findUsersToAutocomplete({
).toArray();

return {
items: users,
items: (contacts as UserAutoComplete[]).concat(users),
};
}

Expand Down
16 changes: 14 additions & 2 deletions apps/meteor/app/api/server/v1/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { Match, check } from 'meteor/check';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import type { IExportOperation, IPersonalAccessToken, IUser } from '@rocket.chat/core-typings';
import { Users as UsersRaw } from '@rocket.chat/models';
import type { Filter } from 'mongodb';

import { Users, Subscriptions } from '../../../models/server';
import { hasPermission } from '../../../authorization/server';
Expand Down Expand Up @@ -815,11 +816,22 @@ API.v1.addRoute(
{ authRequired: true, validateParams: isUsersAutocompleteProps },
{
async get() {
const { selector } = this.queryParams;
const { selector: selectorRaw } = this.queryParams;

const selector: { exceptions: Required<IUser>['username'][]; conditions: Filter<IUser>; term: string } = JSON.parse(selectorRaw);

try {
if (selector?.conditions && !isValidQuery(selector.conditions, ['*'], ['$or', '$and'])) {
throw new Error('error-invalid-query');
}
} catch (e) {
return API.v1.failure(e);
}

return API.v1.success(
await findUsersToAutocomplete({
uid: this.userId,
selector: JSON.parse(selector),
selector,
}),
);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ function handleMentionLinkClick(event: JQuery.ClickEvent, template: CommonRoomTe
}
}

export const getCommonRoomEvents = () => ({
export const getCommonRoomEvents = (useLegacyMessageTemplate = true) => ({
...createMessageTouchEvents(),
'click [data-message-action]': handleMessageActionButtonClick,
'click .js-follow-thread': handleFollowThreadButtonClick,
Expand All @@ -345,5 +345,5 @@ export const getCommonRoomEvents = () => ({
'click .js-actionButton-respondWithQuotedMessage': handleRespondWithQuotedMessageActionButtonClick,
'click .js-actionButton-sendMessage': handleSendMessageActionButtonClick,
'click .message-actions__menu': handleMessageActionMenuClick,
'click .mention-link': handleMentionLinkClick,
...(useLegacyMessageTemplate && { 'click .mention-link': handleMentionLinkClick }),
});
4 changes: 2 additions & 2 deletions apps/meteor/client/components/message/Metrics/Discussion.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Message } from '@rocket.chat/fuselage';
import { useTranslation } from '@rocket.chat/ui-contexts';
import React, { FC } from 'react';
import React, { FC, UIEvent } from 'react';

import { useTimeAgo } from '../../../hooks/useTimeAgo';
import { useBlockRendered } from '../hooks/useBlockRendered';

type DicussionOptions = {
drid: string;
rid: string;
openDiscussion: () => void;
openDiscussion: (event: UIEvent) => void;
count: number;
lm?: Date;
};
Expand Down
39 changes: 4 additions & 35 deletions apps/meteor/client/views/blocks/MessageBlock.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import { UIKitIncomingInteractionContainerType } from '@rocket.chat/apps-engine/definition/uikit/UIKitIncomingInteractionContainer';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { UiKitMessage, UiKitComponent, kitContext, messageParser } from '@rocket.chat/fuselage-ui-kit';
import React from 'react';

import * as ActionManager from '../../../app/ui-message/client/ActionManager';
import { useBlockRendered } from '../../components/message/hooks/useBlockRendered';
import {
useVideoConfJoinCall,
useVideoConfSetPreferences,
useVideoConfIsCalling,
useVideoConfIsRinging,
useVideoConfDispatchOutgoing,
} from '../../contexts/VideoConfContext';
import { VideoConfManager } from '../../lib/VideoConfManager';
import { useVideoConfJoinCall, useVideoConfSetPreferences } from '../../contexts/VideoConfContext';
import { renderMessageBody } from '../../lib/utils/renderMessageBody';
import './textParsers';
import { useVideoConfWarning } from '../room/contextualBar/VideoConference/useVideoConfWarning';

// TODO: move this to fuselage-ui-kit itself
const mrkdwn = ({ text } = {}) => text && <span dangerouslySetInnerHTML={{ __html: renderMessageBody({ msg: text }) }} />;
Expand All @@ -25,36 +16,14 @@ function MessageBlock({ mid: _mid, rid, blocks, appId }) {
const { ref, className } = useBlockRendered();
const joinCall = useVideoConfJoinCall();
const setPreferences = useVideoConfSetPreferences();
const isCalling = useVideoConfIsCalling();
const isRinging = useVideoConfIsRinging();
const dispatchWarning = useVideoConfWarning();
const dispatchPopup = useVideoConfDispatchOutgoing();

const handleOpenVideoConf = useMutableCallback(async (rid) => {
if (isCalling || isRinging) {
return;
}

try {
await VideoConfManager.loadCapabilities();
dispatchPopup({ rid });
} catch (error) {
dispatchWarning(error.error);
}
});

const context = {
action: ({ actionId, value, blockId, mid = _mid, appId }, event) => {
if (appId === 'videoconf-core') {
if (appId === 'videoconf-core' && actionId === 'join') {
event.preventDefault();
setPreferences({ mic: true, cam: false });
if (actionId === 'join') {
return joinCall(blockId);
}

if (actionId === 'callBack') {
return handleOpenVideoConf(blockId);
}
joinCall(blockId);
return;
}

ActionManager.triggerBlockAction({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const useQuery: useQueryType = ({ servedBy, status, departmentId, itemsPe
useMemo(() => {
const query: {
agentId?: string;
includeOflineAgents?: 'true' | 'false';
includeOfflineAgents?: 'true' | 'false';
departmentId?: string;
sort: string;
count: number;
Expand All @@ -39,7 +39,7 @@ export const useQuery: useQueryType = ({ servedBy, status, departmentId, itemsPe
};

if (status !== 'online') {
query.includeOflineAgents = 'true';
query.includeOfflineAgents = 'true';
}
if (servedBy) {
query.agentId = servedBy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ import { Box, MessageBody } from '@rocket.chat/fuselage';
import colors from '@rocket.chat/fuselage-tokens/colors';
import { MarkupInteractionContext, Markup, UserMention, ChannelMention } from '@rocket.chat/gazzodown';
import { escapeRegExp } from '@rocket.chat/string-helpers';
import React, { ReactElement, useCallback, useMemo } from 'react';
import { useLayout } from '@rocket.chat/ui-contexts';
import { FlowRouter } from 'meteor/kadira:flow-router';
import React, { ReactElement, UIEvent, useCallback, useMemo } from 'react';

import { emoji } from '../../../../../app/emoji/client';
import { fireGlobalEvent } from '../../../../lib/utils/fireGlobalEvent';
import { useMessageActions } from '../../contexts/MessageContext';
import { useMessageListHighlights } from '../contexts/MessageListContext';
import { MessageWithMdEnforced } from '../lib/parseMessageTextToAstMarkdown';
Expand Down Expand Up @@ -61,14 +64,33 @@ const MessageContentBody = ({ mentions, channels, md }: MessageContentBodyProps)
return;
}

return openUserCard(username);
return (event: UIEvent): void => {
event.stopPropagation();
openUserCard(username)(event);
};
},
[openUserCard],
);

const resolveChannelMention = useCallback((mention: string) => channels?.find(({ name }) => name === mention), [channels]);

const onChannelMentionClick = useCallback(({ _id: rid }: ChannelMention) => openRoom(rid), [openRoom]);
const { isEmbedded } = useLayout();

const onChannelMentionClick = useCallback(
({ _id: rid }: ChannelMention) =>
(event: UIEvent): void => {
if (isEmbedded) {
fireGlobalEvent('click-mention-link', {
path: FlowRouter.path('channel', { name: rid }),
channel: rid,
});
}

event.stopPropagation();
openRoom(rid)(event);
},
[isEmbedded, openRoom],
);

// TODO: this style should go to Fuselage <MessageBody> repository
const messageBodyAdditionalStyles = css`
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/client/views/room/components/body/RoomBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const RoomBody = (): ReactElement => {
const hideFlexTab = useUserPreference<boolean>('hideFlexTab');
const hideUsernames = useUserPreference<boolean>('hideUsernames');
const displayAvatars = useUserPreference<boolean>('displayAvatars');
const useLegacyMessageTemplate = useUserPreference<boolean>('useLegacyMessageTemplate');
const useLegacyMessageTemplate = useUserPreference<boolean>('useLegacyMessageTemplate') ?? false;
const viewMode = useUserPreference<number>('messageViewMode');

const wrapperRef = useRef<HTMLDivElement | null>(null);
Expand Down Expand Up @@ -329,7 +329,7 @@ const RoomBody = (): ReactElement => {
}

const messageEvents: Record<string, (event: any, template: CommonRoomTemplateInstance) => void> = {
...getCommonRoomEvents(),
...getCommonRoomEvents(useLegacyMessageTemplate),
'click .toggle-hidden'(event: JQuery.ClickEvent) {
const mid = event.target.dataset.message;
if (mid) document.getElementById(mid)?.classList.toggle('message--ignored');
Expand Down Expand Up @@ -361,7 +361,7 @@ const RoomBody = (): ReactElement => {
$(messageList).off(event, selector, listener);
}
};
}, [room._id, sendToBottomIfNecessary, toolbox]);
}, [room._id, sendToBottomIfNecessary, toolbox, useLegacyMessageTemplate]);

useEffect(() => {
const wrapper = wrapperRef.current;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ export const ComposerOmnichannelOnHold = (): ReactElement => {
<footer className='rc-message-box footer'>
<MessageFooterCallout>
<MessageFooterCalloutContent>{t('chat_on_hold_due_to_inactivity')}</MessageFooterCalloutContent>
<MessageFooterCalloutAction onClick={(): Promise<unknown> => resume(room._id)}>{t('Resume')}</MessageFooterCalloutAction>
<MessageFooterCalloutAction onClick={(): Promise<unknown> => resume(room._id, { clientAction: true })}>
{t('Resume')}
</MessageFooterCalloutAction>
</MessageFooterCallout>
</footer>
);
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/client/views/room/contexts/MessageContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export type MessageContextValue = {
oembedEnabled: boolean;
actions: {
openUserCard: (username: string) => (e: UIEvent) => void;
openRoom: (id: string) => () => void;
openRoom: (id: string) => (event: UIEvent) => void;
openThread: (tmid: string, jump?: string) => (e: MouseEvent) => void;
runActionLink: (message: IMessage) => (action: string) => () => void;
replyBroadcast: (message: IMessage) => void;
Expand Down
10 changes: 5 additions & 5 deletions apps/meteor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@
"email": "support@rocket.chat"
},
"devDependencies": {
"@babel/core": "^7.18.13",
"@babel/core": "^7.18.9",
"@babel/eslint-parser": "^7.18.9",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
"@babel/plugin-proposal-optional-chaining": "^7.18.9",
"@babel/preset-env": "^7.18.10",
"@babel/preset-env": "^7.18.9",
"@babel/preset-react": "^7.18.6",
"@babel/register": "^7.18.9",
"@faker-js/faker": "^6.3.1",
Expand Down Expand Up @@ -126,7 +126,7 @@
"@types/prometheus-gc-stats": "^0.6.2",
"@types/proxyquire": "^1.3.28",
"@types/psl": "^1.1.0",
"@types/react": "~17.0.48",
"@types/react": "~17.0.47",
"@types/react-dom": "~17.0.17",
"@types/rewire": "^2.5.28",
"@types/semver": "^7.3.10",
Expand Down Expand Up @@ -154,7 +154,7 @@
"chai-spies": "^1.0.0",
"cross-env": "^7.0.3",
"emojione-assets": "^4.5.0",
"eslint": "^8.22.0",
"eslint": "^8.20.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^4.2.1",
Expand Down Expand Up @@ -212,7 +212,7 @@
"@rocket.chat/fuselage-polyfills": "next",
"@rocket.chat/fuselage-toastbar": "next",
"@rocket.chat/fuselage-tokens": "next",
"@rocket.chat/fuselage-ui-kit": "workspace:^",
"@rocket.chat/fuselage-ui-kit": "next",
"@rocket.chat/gazzodown": "workspace:^",
"@rocket.chat/icons": "next",
"@rocket.chat/layout": "next",
Expand Down
4 changes: 0 additions & 4 deletions apps/meteor/packages/rocketchat-i18n/i18n/en.i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,6 @@
"By_author": "By __author__",
"cache_cleared": "Cache cleared",
"Call": "Call",
"Call_back": "Call back",
"Calling": "Calling",
"Call_Center": "Voice Channel",
"Call_Center_Description": "Configure Rocket.Chat's voice channels",
Expand All @@ -783,9 +782,7 @@
"Call_number_enterprise_only": "Call number (Enterprise Edition only)",
"call-management": "Call Management",
"call-management_description": "Permission to start a meeting",
"Call_ongoing": "Call ongoing",
"Call_unavailable_for_federation": "Call is unavailable for Federated rooms",
"Call_was_not_answered": "Call was not answered",
"Caller": "Caller",
"Caller_Id": "Caller ID",
"Cam_on": "Cam On",
Expand Down Expand Up @@ -5239,7 +5236,6 @@
"VoIP_Toggle": "Enable/Disable VoIP",
"Chat_opened_by_visitor": "Chat opened by the visitor",
"Wait_activation_warning": "Before you can login, your account must be manually activated by an administrator.",
"Waiting_for_answer": "Waiting for answer",
"Waiting_queue": "Waiting queue",
"Waiting_queue_message": "Waiting queue message",
"Waiting_queue_message_description": "Message that will be displayed to the visitors when they get in the queue",
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/lib/spotlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export class Spotlight {

users.push(
...Promise.await(
SubscriptionsRaw.findConnectedUsersExcept(userId, text, usernames, searchFields, options.limit || 5, roomType, match),
SubscriptionsRaw.findConnectedUsersExcept(userId, text, usernames, searchFields, {}, options.limit || 5, roomType, match),
{
readPreference: options.readPreference,
},
Expand Down
2 changes: 2 additions & 0 deletions apps/meteor/server/models/raw/Subscriptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ export class SubscriptionsRaw extends BaseRaw<ISubscription> implements ISubscri
searchTerm: string,
exceptions: string[],
searchFields: string[],
extraConditions: Filter<IUser>,
limit: number,
roomType?: ISubscription['t'],
{ startsWith = false, endsWith = false }: { startsWith?: string | false; endsWith?: string | false } = {},
Expand Down Expand Up @@ -319,6 +320,7 @@ export class SubscriptionsRaw extends BaseRaw<ISubscription> implements ISubscri
{
$match: {
$expr: { $eq: ['$_id', '$$id'] },
...extraConditions,
active: true,
username: {
$exists: true,
Expand Down

0 comments on commit 79448e4

Please sign in to comment.