Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: remove Users from fibers 13 #28772

Merged
merged 2 commits into from
Apr 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions apps/meteor/app/livechat/server/lib/LivechatTyped.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ type GenericCloseRoomParams = {
};

export type CloseRoomParamsByUser = {
user: IUser;
user: IUser | null;
} & GenericCloseRoomParams;

export type CloseRoomParamsByVisitor = {
Expand Down Expand Up @@ -90,11 +90,11 @@ class LivechatClass {
let chatCloser: any;
if (isRoomClosedByUserParams(params)) {
const { user } = params;
this.logger.debug(`Closing by user ${user._id}`);
this.logger.debug(`Closing by user ${user?._id}`);
closeData.closer = 'user';
closeData.closedBy = {
_id: user._id,
username: user.username,
_id: user?._id || '',
username: user?.username,
};
chatCloser = user;
} else if (isRoomClosedByVisitorParams(params)) {
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/meteor-accounts-saml/server/lib/SAML.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Random } from '@rocket.chat/random';
import { Accounts } from 'meteor/accounts-base';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import { escapeRegExp, escapeHTML } from '@rocket.chat/string-helpers';
import type { IUser, IIncomingMessage, ILoginToken } from '@rocket.chat/core-typings';
import type { IUser, IIncomingMessage, IPersonalAccessToken } from '@rocket.chat/core-typings';
import { CredentialTokens, Rooms, Users } from '@rocket.chat/models';

import { settings } from '../../../settings/server';
Expand Down Expand Up @@ -175,7 +175,7 @@ export class SAML {
const stampedToken = Accounts._generateStampedLoginToken();
await Users.addPersonalAccessTokenToUser({
userId: user._id,
loginTokenObject: stampedToken as unknown as ILoginToken,
loginTokenObject: stampedToken as unknown as IPersonalAccessToken,
});

const updateData: Record<string, any> = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const hoverStyle = css`
`;

const ReadReceiptRow = ({ user, ts }: ReadReceipt): ReactElement => {
const displayName = useUserDisplayName(user);
const displayName = useUserDisplayName(user || {});
const formatDateAndTime = useFormatDateAndTime({ withSeconds: true });

return (
Expand All @@ -30,7 +30,7 @@ const ReadReceiptRow = ({ user, ts }: ReadReceipt): ReactElement => {
className={hoverStyle}
>
<Box>
<UserAvatar username={user.username || ''} size='x24' />
<UserAvatar username={user?.username || ''} size='x24' />
<Box is='span' mis='x8'>
{displayName}
</Box>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import get from 'lodash.get';
import type { IMessage, IOmnichannelRoom } from '@rocket.chat/core-typings';
import { isOmnichannelRoom } from '@rocket.chat/core-typings';
import { LivechatVisitors, Rooms } from '@rocket.chat/models';
import { LivechatVisitors, Rooms, Users } from '@rocket.chat/models';

import { settings } from '../../../../../app/settings/server';
import { callbacks } from '../../../../../lib/callbacks';
import { Users } from '../../../../../app/models/server';

const placeholderFields = {
'contact.name': {
Expand Down Expand Up @@ -44,8 +43,11 @@ const handleBeforeSaveMessage = async (message: IMessage, room?: IOmnichannelRoo

let messageText = message.msg;
const agentId = room?.servedBy?._id;
if (!agentId) {
return message;
}
const visitorId = room?.v?._id;
const agent = Users.findOneById(agentId, { fields: { name: 1, _id: 1, emails: 1 } }) || {};
const agent = (await Users.findOneById(agentId, { projection: { name: 1, _id: 1, emails: 1 } })) || {};
const visitor = visitorId && ((await LivechatVisitors.findOneById(visitorId, {})) || {});

Object.keys(placeholderFields).map((field) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
import type { ServerMethods } from '@rocket.chat/ui-contexts';
import { LivechatDepartment, CannedResponse } from '@rocket.chat/models';
import { LivechatDepartment, CannedResponse, Users } from '@rocket.chat/models';
import type { IOmnichannelCannedResponse } from '@rocket.chat/core-typings';

import { hasPermissionAsync } from '../../../../../app/authorization/server/functions/hasPermission';
import { Users } from '../../../../../app/models/server';
import notifications from '../../../../../app/notifications/server/lib/Notifications';

declare module '@rocket.chat/ui-contexts' {
Expand Down Expand Up @@ -95,12 +94,12 @@ Meteor.methods<ServerMethods>({

result = await CannedResponse.updateCannedResponse(_id, { ...responseData, createdBy: cannedResponse.createdBy });
} else {
const user = Users.findOneById(Meteor.userId());
const user = await Users.findOneById(userId);

const data = {
...responseData,
...(responseData.scope === 'user' && { userId: user._id }),
createdBy: { _id: user._id, username: user.username },
...(responseData.scope === 'user' && { userId: user?._id }),
createdBy: { _id: user?._id || '', username: user?.username || '' },
_createdAt: new Date(),
};

Expand Down
6 changes: 2 additions & 4 deletions apps/meteor/ee/app/license/server/getSeatsRequestLink.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import type { ISetting } from '@rocket.chat/core-typings';
import { Settings } from '@rocket.chat/models';

import { Users } from '../../../../app/models/server';
import { Settings, Users } from '@rocket.chat/models';

type WizardSettings = Array<ISetting>;

const url = 'https://go.rocket.chat/i/seats-cap-upgrade';

export const getSeatsRequestLink = async (): Promise<string> => {
const workspaceId = await Settings.findOneById('Cloud_Workspace_Id');
const activeUsers = Users.getActiveLocalUserCount();
const activeUsers = await Users.getActiveLocalUserCount();
const wizardSettings: WizardSettings = await Settings.findSetupWizardSettings().toArray();

const newUrl = new URL(url);
Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/ee/app/license/server/license.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { EventEmitter } from 'events';

import { Apps } from '@rocket.chat/core-services';
import type { IAppStorageItem } from '@rocket.chat/apps-engine/server/storage';
import { Users } from '@rocket.chat/models';

import { Users } from '../../../../app/models/server';
import type { BundleFeature } from './bundles';
import { getBundleModules, isBundle, getBundleFromModule } from './bundles';
import decrypt from './decrypt';
Expand Down Expand Up @@ -211,12 +211,12 @@ class LicenseClass {
this.showLicenses();
}

canAddNewUser(): boolean {
async canAddNewUser(): Promise<boolean> {
if (!maxActiveUsers) {
return true;
}

return maxActiveUsers > Users.getActiveLocalUserCount();
return maxActiveUsers > (await Users.getActiveLocalUserCount());
}

async canEnableApp(source: LicenseAppSources): Promise<boolean> {
Expand Down Expand Up @@ -330,7 +330,7 @@ export function getAppsConfig(): NonNullable<ILicense['apps']> {
return License.getAppsConfig();
}

export function canAddNewUser(): boolean {
export async function canAddNewUser(): Promise<boolean> {
return License.canAddNewUser();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,21 @@ const getAgentIdsToHandle = async (businessHour: Record<string, any>): Promise<s
export const openBusinessHour = async (businessHour: Record<string, any>): Promise<void> => {
const agentIds: string[] = await getAgentIdsToHandle(businessHour);
await Users.addBusinessHourByAgentIds(agentIds, businessHour._id);
Users.updateLivechatStatusBasedOnBusinessHours();
await Users.updateLivechatStatusBasedOnBusinessHours();
};

export const closeBusinessHour = async (businessHour: Record<string, any>): Promise<void> => {
const agentIds: string[] = await getAgentIdsToHandle(businessHour);
await Users.removeBusinessHourByAgentIds(agentIds, businessHour._id);
Users.updateLivechatStatusBasedOnBusinessHours();
await Users.updateLivechatStatusBasedOnBusinessHours();
};

export const removeBusinessHourByAgentIds = async (agentIds: string[], businessHourId: string): Promise<void> => {
if (!agentIds.length) {
return;
}
await Users.removeBusinessHourByAgentIds(agentIds, businessHourId);
Users.updateLivechatStatusBasedOnBusinessHours();
await Users.updateLivechatStatusBasedOnBusinessHours();
};

export const resetDefaultBusinessHourIfNeeded = async (): Promise<void> => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { LivechatVisitors, LivechatInquiry, LivechatRooms } from '@rocket.chat/models';
import { LivechatVisitors, LivechatInquiry, LivechatRooms, Users } from '@rocket.chat/models';
import type { IUser } from '@rocket.chat/core-typings';

import { callbacks } from '../../../../../lib/callbacks';
import { RoutingManager } from '../../../../../app/livechat/server/lib/RoutingManager';
import { settings } from '../../../../../app/settings/server';
import { Users } from '../../../../../app/models/server';

let contactManagerPreferred = false;
let lastChattedAgentPreferred = false;

const normalizeDefaultAgent = (agent: { _id: string; username: string }) => {
const normalizeDefaultAgent = (agent?: Pick<IUser, '_id' | 'username'> | null) => {
if (!agent) {
return;
}
Expand All @@ -17,8 +17,9 @@ const normalizeDefaultAgent = (agent: { _id: string; username: string }) => {
return { agentId, username };
};

const getDefaultAgent = async (username: string) =>
username && normalizeDefaultAgent(await Users.findOneOnlineAgentByUserList(username, { fields: { _id: 1, username: 1 } }));
const getDefaultAgent = async (username?: string) =>
username !== undefined &&
normalizeDefaultAgent(await Users.findOneOnlineAgentByUserList(username, { projection: { _id: 1, username: 1 } }));

settings.watch<boolean>('Livechat_last_chatted_agent_routing', function (value) {
lastChattedAgentPreferred = value;
Expand Down Expand Up @@ -117,7 +118,12 @@ callbacks.add(
const {
servedBy: { username: usernameByRoom },
} = room;
const lastRoomAgent = normalizeDefaultAgent(Users.findOneOnlineAgentByUserList(usernameByRoom, { fields: { _id: 1, username: 1 } }));
if (!usernameByRoom) {
return defaultAgent;
}
const lastRoomAgent = normalizeDefaultAgent(
await Users.findOneOnlineAgentByUserList(usernameByRoom, { projection: { _id: 1, username: 1 } }),
);
return lastRoomAgent ?? defaultAgent;
},
callbacks.priority.MEDIUM,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { Agenda } from '@rocket.chat/agenda';
import { MongoInternals } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';
import { LivechatRooms } from '@rocket.chat/models';
import { LivechatRooms, Users } from '@rocket.chat/models';
import type { IUser } from '@rocket.chat/core-typings';

import { Users } from '../../../../../app/models/server';
import { Livechat } from '../../../../../app/livechat/server';
import { RoutingManager } from '../../../../../app/livechat/server/lib/RoutingManager';
import { forwardRoomToAgent } from '../../../../../app/livechat/server/lib/Helper';
import { settings } from '../../../../../app/settings/server';

const schedulerUser = Users.findOneById('rocket.cat');
const SCHEDULER_NAME = 'omnichannel_scheduler';

class AutoTransferChatSchedulerClass {
Expand All @@ -35,6 +33,10 @@ class AutoTransferChatSchedulerClass {
this.running = true;
}

private async getSchedulerUser(): Promise<IUser | null> {
return Users.findOneById('rocket.cat');
}

public async scheduleRoom(roomId: string, timeout: number): Promise<void> {
await this.unscheduleRoom(roomId);

Expand Down Expand Up @@ -77,15 +79,15 @@ class AutoTransferChatSchedulerClass {
return Livechat.returnRoomAsInquiry(room._id, departmentId, {
scope: 'autoTransferUnansweredChatsToQueue',
comment: timeoutDuration,
transferredBy: schedulerUser,
transferredBy: await this.getSchedulerUser(),
});
}

const agent = await RoutingManager.getNextAgent(departmentId, ignoreAgentId);
if (agent) {
return forwardRoomToAgent(room, {
userId: agent.agentId,
transferredBy: schedulerUser,
transferredBy: await this.getSchedulerUser(),
transferredTo: agent,
scope: 'autoTransferUnansweredChatsToAgent',
comment: timeoutDuration,
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/ee/app/livechat-enterprise/server/lib/Helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import {
LivechatDepartment as LivechatDepartmentRaw,
LivechatCustomField,
LivechatInquiry,
Users,
} from '@rocket.chat/models';
import { api } from '@rocket.chat/core-services';

import { memoizeDebounce } from './debounceByParams';
import { Users } from '../../../../../app/models/server';
import { settings } from '../../../../../app/settings/server';
import { RoutingManager } from '../../../../../app/livechat/server/lib/RoutingManager';
import { dispatchAgentDelegated } from '../../../../../app/livechat/server/lib/Helper';
Expand All @@ -29,7 +29,7 @@ export const getMaxNumberSimultaneousChat = async ({ agentId, departmentId }) =>
}

if (agentId) {
const user = Users.getAgentInfo(agentId);
const user = await Users.getAgentInfo(agentId);
const { livechat: { maxNumberSimultaneousChat } = {} } = user || {};
if (maxNumberSimultaneousChat > 0) {
return maxNumberSimultaneousChat;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const LivechatEnterprise = {
async addMonitor(username) {
check(username, String);

const user = await Users.findOneByUsername(username, { fields: { _id: 1, username: 1 } });
const user = await Users.findOneByUsername(username, { projection: { _id: 1, username: 1 } });

if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
Expand All @@ -47,7 +47,7 @@ export const LivechatEnterprise = {
async removeMonitor(username) {
check(username, String);

const user = await Users.findOneByUsername(username, { fields: { _id: 1 } });
const user = await Users.findOneByUsername(username, { projection: { _id: 1 } });

if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { MongoInternals } from 'meteor/mongo';
import { Meteor } from 'meteor/meteor';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import type { IUser, IOmnichannelRoom } from '@rocket.chat/core-typings';
import { LivechatRooms, LivechatInquiry as LivechatInquiryRaw } from '@rocket.chat/models';
import { LivechatRooms, LivechatInquiry as LivechatInquiryRaw, Users } from '@rocket.chat/models';

import { settings } from '../../../../../app/settings/server';
import { Logger } from '../../../../../app/logger/server';
import { Users } from '../../../../../app/models/server';
import { Livechat } from '../../../../../app/livechat/server/lib/LivechatTyped';

const SCHEDULER_NAME = 'omnichannel_queue_inactivity_monitor';
Expand Down Expand Up @@ -41,12 +40,15 @@ class OmnichannelQueueInactivityMonitorClass {
defaultConcurrency: 1,
});
this.createIndex();
this.user = Users.findOneById('rocket.cat');
const language = settings.get<string>('Language') || 'en';
this.message = TAPi18n.__('Closed_automatically_chat_queued_too_long', { lng: language });
this.bindedCloseRoom = Meteor.bindEnvironment(this.closeRoom.bind(this));
}

private async getRocketCatUser(): Promise<IUser | null> {
return Users.findOneById('rocket.cat');
}

getName(inquiryId: string): string {
return `${this._name}-${inquiryId}`;
}
Expand Down Expand Up @@ -93,12 +95,12 @@ class OmnichannelQueueInactivityMonitorClass {
await this.scheduler.cancel({ name });
}

closeRoomAction(room: IOmnichannelRoom): Promise<void> {
async closeRoomAction(room: IOmnichannelRoom): Promise<void> {
const comment = this.message;
return Livechat.closeRoom({
comment,
room,
user: this.user,
user: await this.getRocketCatUser(),
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Meteor } from 'meteor/meteor';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import type { ILivechatVisitor } from '@rocket.chat/core-typings';
import { LivechatVisitors, LivechatInquiry, LivechatRooms } from '@rocket.chat/models';
import { LivechatVisitors, LivechatInquiry, LivechatRooms, Users } from '@rocket.chat/models';
import { Message } from '@rocket.chat/core-services';
import type { ServerMethods } from '@rocket.chat/ui-contexts';

import { Users } from '../../../../../app/models/server';
import { RoutingManager } from '../../../../../app/livechat/server/lib/RoutingManager';
import { callbacks } from '../../../../../lib/callbacks';

Expand Down Expand Up @@ -62,7 +61,10 @@ Meteor.methods<ServerMethods>({
const { servedBy: { _id: agentId, username } = {} } = room;
await RoutingManager.takeInquiry(inquiry, { agentId, username }, options);

const onHoldChatResumedBy = options.clientAction ? await Meteor.userAsync() : Users.findOneById('rocket.cat');
const onHoldChatResumedBy = options.clientAction ? await Meteor.userAsync() : await Users.findOneById('rocket.cat');
if (!onHoldChatResumedBy) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'livechat:resumeOnHold' });
}

const comment = await resolveOnHoldCommentInfo(options, room, onHoldChatResumedBy);

Expand Down
Loading