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

feat: VoIP Backend for FreeSwitch #33093

Merged
merged 14 commits into from
Sep 16, 2024
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
1 change: 1 addition & 0 deletions apps/meteor/app/api/server/lib/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ export async function findPaginatedUsersByStatus({
type: 1,
reason: 1,
federated: 1,
freeSwitchExtension: 1,
};

const actualSort: Record<string, 1 | -1> = sort || { username: 1 };
Expand Down
4 changes: 4 additions & 0 deletions apps/meteor/ee/app/api-enterprise/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ import { License } from '@rocket.chat/license';
await License.onLicense('canned-responses', async () => {
await import('./canned-responses');
});

await License.onLicense('voip-enterprise', async () => {
await import('./voip-freeswitch');
});
150 changes: 150 additions & 0 deletions apps/meteor/ee/app/api-enterprise/server/voip-freeswitch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { VoipFreeSwitch } from '@rocket.chat/core-services';
import { Users } from '@rocket.chat/models';
import {
isVoipFreeSwitchExtensionAssignProps,
isVoipFreeSwitchExtensionGetDetailsProps,
isVoipFreeSwitchExtensionGetInfoProps,
isVoipFreeSwitchExtensionListProps,
} from '@rocket.chat/rest-typings';
import { wrapExceptions } from '@rocket.chat/tools';

import { API } from '../../../../app/api/server';
import { settings } from '../../../../app/settings/server/cached';

API.v1.addRoute(
'voip-freeswitch.extension.list',
{ authRequired: true, permissionsRequired: ['manage-voip-call-settings'], validateParams: isVoipFreeSwitchExtensionListProps },
{
async get() {
const { username, type = 'all' } = this.queryParams;

const extensions = await wrapExceptions(() => VoipFreeSwitch.getExtensionList()).catch(() => {
throw new Error('Failed to load extension list.');
});

if (type === 'all') {
return API.v1.success({ extensions });
}

const assignedExtensions = await Users.findAssignedFreeSwitchExtensions().toArray();

switch (type) {
case 'free':
const freeExtensions = extensions.filter(({ extension }) => !assignedExtensions.includes(extension));
return API.v1.success({ extensions: freeExtensions });
case 'allocated':
// Extensions that are already assigned to some user
const allocatedExtensions = extensions.filter(({ extension }) => assignedExtensions.includes(extension));
return API.v1.success({ extensions: allocatedExtensions });
case 'available':
// Extensions that are free or assigned to the specified user
const user = (username && (await Users.findOneByUsername(username, { projection: { freeSwitchExtension: 1 } }))) || undefined;
const currentExtension = user?.freeSwitchExtension;

const availableExtensions = extensions.filter(
({ extension }) => extension === currentExtension || !assignedExtensions.includes(extension),
);

return API.v1.success({ extensions: availableExtensions });
}

return API.v1.success({ extensions });
},
},
);

API.v1.addRoute(
'voip-freeswitch.extension.assign',
{ authRequired: true, permissionsRequired: ['manage-voip-call-settings'], validateParams: isVoipFreeSwitchExtensionAssignProps },
{
async post() {
const { extension, username } = this.bodyParams;

if (!username) {
return API.v1.notFound();
}

const user = await Users.findOneByUsername(username, { projection: { freeSwitchExtension: 1 } });
if (!user) {
return API.v1.notFound();
}

const existingUser = extension && (await Users.findOneByFreeSwitchExtension(extension, { projection: { _id: 1 } }));
if (existingUser && existingUser._id !== user._id) {
throw new Error('Extension not available.');
}

if (extension && user.freeSwitchExtension === extension) {
return API.v1.success();
}

await Users.setFreeSwitchExtension(user._id, extension);
return API.v1.success();
},
},
);

API.v1.addRoute(
'voip-freeswitch.extension.getDetails',
{ authRequired: true, permissionsRequired: ['manage-voip-call-settings'], validateParams: isVoipFreeSwitchExtensionGetDetailsProps },
{
async get() {
const { extension, group } = this.queryParams;

if (!extension) {
throw new Error('Invalid params');
}

const extensionData = await wrapExceptions(() => VoipFreeSwitch.getExtensionDetails({ extension, group })).suppress(() => undefined);
if (!extensionData) {
return API.v1.notFound();
}

const existingUser = await Users.findOneByFreeSwitchExtension(extensionData.extension, { projection: { username: 1 } });

return API.v1.success({
...extensionData,
...(existingUser && { userId: existingUser._id, username: existingUser.username }),
});
},
},
);

API.v1.addRoute(
'voip-freeswitch.extension.getRegistrationInfoByUserId',
{ authRequired: true, permissionsRequired: ['manage-voip-call-settings'], validateParams: isVoipFreeSwitchExtensionGetInfoProps },
{
async get() {
const { userId } = this.queryParams;

if (!userId) {
throw new Error('Invalid params.');
}

const user = await Users.findOneById(userId, { projection: { freeSwitchExtension: 1 } });
if (!user) {
throw new Error('User not found.');
}

const { freeSwitchExtension: extension } = user;

if (!extension) {
throw new Error('Extension not assigned.');
}

const extensionData = await wrapExceptions(() => VoipFreeSwitch.getExtensionDetails({ extension })).suppress(() => undefined);
if (!extensionData) {
return API.v1.notFound();
}
const password = await wrapExceptions(() => VoipFreeSwitch.getUserPassword(extension)).suppress(() => undefined);

return API.v1.success({
extension: extensionData,
credentials: {
websocketPath: settings.get<string>('VoIP_TeamCollab_FreeSwitch_WebSocket_Path'),
password,
},
});
},
},
);
1 change: 1 addition & 0 deletions apps/meteor/ee/server/configuration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ import './oauth';
import './outlookCalendar';
import './saml';
import './videoConference';
import './voip';
10 changes: 10 additions & 0 deletions apps/meteor/ee/server/configuration/voip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { License } from '@rocket.chat/license';
import { Meteor } from 'meteor/meteor';

import { addSettings } from '../settings/voip';

Meteor.startup(async () => {
await License.onLicense('voip-enterprise', async () => {
await addSettings();
});
});
53 changes: 53 additions & 0 deletions apps/meteor/ee/server/local-services/voip-freeswitch/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { type IVoipFreeSwitchService, ServiceClassInternal } from '@rocket.chat/core-services';
import type { FreeSwitchExtension, ISetting, SettingValue } from '@rocket.chat/core-typings';
import { getDomain, getUserPassword, getExtensionList, getExtensionDetails } from '@rocket.chat/freeswitch';

export class VoipFreeSwitchService extends ServiceClassInternal implements IVoipFreeSwitchService {
protected name = 'voip-freeswitch';

constructor(private getSetting: <T extends SettingValue = SettingValue>(id: ISetting['_id']) => T) {
super();
}

private getConnectionSettings(): { host: string; port: number; password: string; timeout: number } {
if (!this.getSetting('VoIP_TeamCollab_Enabled') && !process.env.FREESWITCHIP) {
throw new Error('VoIP is disabled.');
}

const host = process.env.FREESWITCHIP || this.getSetting<string>('VoIP_TeamCollab_FreeSwitch_Host');
if (!host) {
throw new Error('VoIP is not properly configured.');
}

const port = this.getSetting<number>('VoIP_TeamCollab_FreeSwitch_Port') || 8021;
const timeout = this.getSetting<number>('VoIP_TeamCollab_FreeSwitch_Timeout') || 3000;
const password = this.getSetting<string>('VoIP_TeamCollab_FreeSwitch_Password');

return {
host,
port,
password,
timeout,
};
}

async getDomain(): Promise<string> {
const options = this.getConnectionSettings();
return getDomain(options);
}

async getUserPassword(user: string): Promise<string> {
const options = this.getConnectionSettings();
return getUserPassword(options, user);
}

async getExtensionList(): Promise<FreeSwitchExtension[]> {
const options = this.getConnectionSettings();
return getExtensionList(options);
}

async getExtensionDetails(requestParams: { extension: string; group?: string }): Promise<FreeSwitchExtension> {
const options = this.getConnectionSettings();
return getExtensionDetails(options, requestParams);
}
}
49 changes: 49 additions & 0 deletions apps/meteor/ee/server/settings/voip.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { settingsRegistry } from '../../../app/settings/server';

export function addSettings(): Promise<void> {
return settingsRegistry.addGroup('VoIP_TeamCollab', async function () {
await this.with(
{
enterprise: true,
modules: ['voip-enterprise'],
},
async function () {
await this.add('VoIP_TeamCollab_Enabled', false, {
type: 'boolean',
public: true,
invalidValue: false,
});

await this.add('VoIP_TeamCollab_FreeSwitch_Host', '', {
type: 'string',
public: true,
invalidValue: '',
});

await this.add('VoIP_TeamCollab_FreeSwitch_Port', 8021, {
type: 'int',
public: true,
invalidValue: 8021,
});

await this.add('VoIP_TeamCollab_FreeSwitch_Password', '', {
type: 'password',
public: true,
invalidValue: '',
});

await this.add('VoIP_TeamCollab_FreeSwitch_Timeout', 3000, {
type: 'int',
public: true,
invalidValue: 3000,
});

await this.add('VoIP_TeamCollab_FreeSwitch_WebSocket_Path', '', {
type: 'string',
public: true,
invalidValue: '',
});
},
);
});
}
3 changes: 3 additions & 0 deletions apps/meteor/ee/server/startup/services.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { api } from '@rocket.chat/core-services';
import { License } from '@rocket.chat/license';

import { settings } from '../../../app/settings/server/cached';
import { isRunningMs } from '../../../server/lib/isRunningMs';
import { FederationService } from '../../../server/services/federation/service';
import { LicenseService } from '../../app/license/server/license.internalService';
Expand All @@ -10,13 +11,15 @@ import { FederationServiceEE } from '../local-services/federation/service';
import { InstanceService } from '../local-services/instance/service';
import { LDAPEEService } from '../local-services/ldap/service';
import { MessageReadsService } from '../local-services/message-reads/service';
import { VoipFreeSwitchService } from '../local-services/voip-freeswitch/service';

// TODO consider registering these services only after a valid license is added
api.registerService(new EnterpriseSettings());
api.registerService(new LDAPEEService());
api.registerService(new LicenseService());
api.registerService(new MessageReadsService());
api.registerService(new OmnichannelEE());
api.registerService(new VoipFreeSwitchService((id) => settings.get(id)));

// when not running micro services we want to start up the instance intercom
if (!isRunningMs()) {
Expand Down
2 changes: 2 additions & 0 deletions apps/meteor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@
"@rocket.chat/favicon": "workspace:^",
"@rocket.chat/forked-matrix-appservice-bridge": "^4.0.2",
"@rocket.chat/forked-matrix-bot-sdk": "^0.6.0-beta.3",
"@rocket.chat/freeswitch": "workspace:^",
"@rocket.chat/fuselage": "^0.59.0",
"@rocket.chat/fuselage-hooks": "^0.33.1",
"@rocket.chat/fuselage-polyfills": "~0.31.25",
Expand Down Expand Up @@ -331,6 +332,7 @@
"emailreplyparser": "^0.0.5",
"emoji-toolkit": "^7.0.1",
"emojione": "^4.5.0",
"esl": "github:pierre-lehnen-rc/esl",
MarcosSpessatto marked this conversation as resolved.
Show resolved Hide resolved
"eventemitter3": "^4.0.7",
"exif-be-gone": "^1.3.2",
"express": "^4.17.3",
Expand Down
43 changes: 42 additions & 1 deletion apps/meteor/server/models/raw/Users.js
Original file line number Diff line number Diff line change
Expand Up @@ -713,8 +713,10 @@ export class UsersRaw extends BaseRaw {
$nin: exceptions,
},
},
{
...conditions,
},
MarcosSpessatto marked this conversation as resolved.
Show resolved Hide resolved
],
...conditions,
};

return this.find(query, options);
Expand Down Expand Up @@ -2432,6 +2434,34 @@ export class UsersRaw extends BaseRaw {
});
}

findOneByFreeSwitchExtension(freeSwitchExtension, options = {}) {
return this.findOne(
{
freeSwitchExtension,
},
options,
);
}

findAssignedFreeSwitchExtensions() {
pierre-lehnen-rc marked this conversation as resolved.
Show resolved Hide resolved
return this.findUsersWithAssignedFreeSwitchExtensions({
projection: {
freeSwitchExtension: 1,
},
}).map(({ freeSwitchExtension }) => freeSwitchExtension);
}

findUsersWithAssignedFreeSwitchExtensions(options = {}) {
return this.find(
{
freeSwitchExtension: {
$exists: 1,
},
},
options,
);
}

// UPDATE
addImportIds(_id, importIds) {
importIds = [].concat(importIds);
Expand Down Expand Up @@ -2905,6 +2935,17 @@ export class UsersRaw extends BaseRaw {
);
}

async setFreeSwitchExtension(_id, extension) {
return this.updateOne(
{
_id,
},
{
...(extension ? { $set: { freeSwitchExtension: extension } } : { $unset: { freeSwitchExtension: 1 } }),
},
);
}

// INSERT
create(data) {
const user = {
Expand Down
Loading
Loading