Files
upstream-rocketchat/apps/meteor/server/lib/omnichannel/startup.ts
upstream-mirror 30810eecd7
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:21:02 +05:00

149 lines
4.7 KiB
TypeScript

import type { IUser } from '@rocket.chat/core-typings';
import { ILivechatAgentStatus, isOmnichannelRoom } from '@rocket.chat/core-typings';
import { Logger } from '@rocket.chat/logger';
import { LivechatContacts, LivechatRooms } from '@rocket.chat/models';
import { registerGuest } from '@rocket.chat/omni-core';
import { validateEmail, wrapExceptions } from '@rocket.chat/tools';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import { businessHourManager } from './business-hour';
import { createDefaultBusinessHourIfNotExists } from './business-hour/Helper';
import { LivechatAgentActivityMonitor } from './statistics/LivechatAgentActivityMonitor';
import { setUserStatusLivechatIf } from './utils';
import { maybeMigrateLivechatRoom } from '../../api/lib/maybeMigrateLivechatRoom';
import { settings } from '../../settings';
import { hasPermissionAsync } from '../authorization/hasPermission';
import { callbacks } from '../callbacks';
import { beforeLeaveRoomCallback } from '../callbacks/beforeLeaveRoomCallback';
import { i18n } from '../i18n';
import { notifyOnUserChange } from '../notifyListener';
import { roomCoordinator } from '../rooms/roomCoordinator';
import './roomAccessValidator.internalService';
import { ContactMerger, type FieldAndValue } from './contacts/ContactMerger';
const logger = new Logger('LivechatStartup');
// TODO this patch is temporary because `ContactMerger` still a lot of dependencies, so it is not suitable to be moved to omni-core package
// TODO add tests covering the ContactMerger usage
registerGuest.patch(async (originalFn, newData, options) => {
const visitor = await originalFn(newData, options);
if (!visitor) {
return null;
}
const { name, phone, email, username } = newData;
const validatedEmail =
email &&
wrapExceptions(() => {
const trimmedEmail = email.trim().toLowerCase();
validateEmail(trimmedEmail);
return trimmedEmail;
}).suppress();
const fields = [
{ type: 'name', value: name },
{ type: 'phone', value: phone?.number },
{ type: 'email', value: validatedEmail },
{ type: 'username', value: username || visitor.username },
].filter((field) => Boolean(field.value)) as FieldAndValue[];
if (!fields.length) {
return null;
}
// If a visitor was updated who already had contacts, load up the contacts and update that information as well
const contacts = await LivechatContacts.findAllByVisitorId(visitor._id).toArray();
for await (const contact of contacts) {
await ContactMerger.mergeFieldsIntoContact({
fields,
contact,
conflictHandlingMode: contact.unknown ? 'overwrite' : 'conflict',
});
}
return visitor;
});
Meteor.startup(async () => {
roomCoordinator.setRoomFind('l', async (id) => maybeMigrateLivechatRoom(await LivechatRooms.findOneById(id)));
beforeLeaveRoomCallback.add(
(user, room) => {
if (!isOmnichannelRoom(room)) {
return;
}
throw new Meteor.Error(
i18n.t('You_cant_leave_a_livechat_room_Please_use_the_close_button', {
lng: user.language || settings.get('Language') || 'en',
}),
);
},
callbacks.priority.LOW,
'cant-leave-omnichannel-room',
);
callbacks.add(
'beforeJoinRoom',
async (user, room) => {
if (isOmnichannelRoom(room) && !(await hasPermissionAsync(user, 'view-l-room'))) {
throw new Meteor.Error('error-user-is-not-agent', 'User is not an Omnichannel Agent', {
method: 'beforeJoinRoom',
});
}
return user;
},
callbacks.priority.LOW,
'cant-join-omnichannel-room',
);
const monitor = new LivechatAgentActivityMonitor();
settings.watch<boolean>('Troubleshoot_Disable_Livechat_Activity_Monitor', async (value) => {
if (value) {
return monitor.stop();
}
await monitor.start();
});
await createDefaultBusinessHourIfNotExists();
settings.watch<boolean>(
'Livechat_enable_business_hours',
async (value) => {
logger.debug({ msg: 'Starting business hour manager', enabled: value });
if (value) {
await businessHourManager.startManager();
return;
}
await businessHourManager.stopManager();
},
process.env.TEST_MODE === 'true' || process.env.TEST_MODE === 'api'
? {
debounce: 10,
}
: undefined,
);
// Remove when accounts.onLogout is async
Accounts.onLogout(({ user }: { user?: IUser }) => {
if (!user?.roles?.includes('livechat-agent') || user?.roles?.includes('bot')) {
return;
}
void setUserStatusLivechatIf(user._id, ILivechatAgentStatus.NOT_AVAILABLE, {}, { livechatStatusSystemModified: true }).catch();
// TODO: Shouldn't this notifier be the same as the one inside setUserStatusLivechatIf?
void notifyOnUserChange({
id: user._id,
clientAction: 'updated',
diff: {
statusLivechat: ILivechatAgentStatus.NOT_AVAILABLE,
livechatStatusSystemModified: true,
},
});
});
});