diff --git a/packages/rocketchat-api/client/lib/RestApiClient.js b/packages/rocketchat-api/client/lib/RestApiClient.js index 107462f2057d..403ff02f2827 100644 --- a/packages/rocketchat-api/client/lib/RestApiClient.js +++ b/packages/rocketchat-api/client/lib/RestApiClient.js @@ -109,4 +109,3 @@ export const API = { }, }, }; -RocketChat.API = API; diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index a6664d10b8f1..33c14dae9024 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -17,7 +17,6 @@ Package.onUse(function(api) { 'rocketchat:utils', 'rocketchat:metrics', 'rocketchat:authorization', - 'rocketchat:integrations', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-api/server/api.js b/packages/rocketchat-api/server/api.js index a4ee71d3b9a6..d8e1d331ea47 100644 --- a/packages/rocketchat-api/server/api.js +++ b/packages/rocketchat-api/server/api.js @@ -2,7 +2,6 @@ import { Meteor } from 'meteor/meteor'; import { DDPCommon } from 'meteor/ddp-common'; import { DDP } from 'meteor/ddp'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; import { Logger } from 'meteor/rocketchat:logger'; import { settings } from 'meteor/rocketchat:settings'; @@ -448,8 +447,6 @@ API = { ApiClass: APIClass, }; -RocketChat.API = API; - const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { if (this.request.method === 'OPTIONS' && this.request.headers['access-control-request-method']) { if (settings.get('API_Enable_CORS') === true) { diff --git a/packages/rocketchat-api/server/v1/chat.js b/packages/rocketchat-api/server/v1/chat.js index f83b8dc2c804..c3bf42672d00 100644 --- a/packages/rocketchat-api/server/v1/chat.js +++ b/packages/rocketchat-api/server/v1/chat.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { processWebhookMessage } from 'meteor/rocketchat:integrations'; import { Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { processWebhookMessage } from 'meteor/rocketchat:lib'; import { API } from '../api'; API.v1.addRoute('chat.delete', { authRequired: true }, { diff --git a/packages/rocketchat-api/server/v1/im.js b/packages/rocketchat-api/server/v1/im.js index eb011021d119..074cd91ab50b 100644 --- a/packages/rocketchat-api/server/v1/im.js +++ b/packages/rocketchat-api/server/v1/im.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getRoomByNameOrIdWithOptionToJoin } from 'meteor/rocketchat:lib'; import { Subscriptions, Uploads, Users, Messages, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; @@ -11,7 +11,7 @@ function findDirectMessageRoom(params, user) { throw new Meteor.Error('error-room-param-not-provided', 'Body param "roomId" or "username" is required'); } - const room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ + const room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: params.username || params.roomId, type: 'd', diff --git a/packages/rocketchat-api/server/v1/users.js b/packages/rocketchat-api/server/v1/users.js index 178f5d5d108a..6d24bbb53dae 100644 --- a/packages/rocketchat-api/server/v1/users.js +++ b/packages/rocketchat-api/server/v1/users.js @@ -5,6 +5,14 @@ import { Users, Subscriptions } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { getURL } from 'meteor/rocketchat:utils'; +import { + validateCustomFields, + saveUser, + saveCustomFieldsWithoutValidation, + checkUsernameAvailability, + setUserAvatar, + saveCustomFields, +} from 'meteor/rocketchat:lib'; import { API } from '../api'; import _ from 'underscore'; import Busboy from 'busboy'; @@ -31,13 +39,13 @@ API.v1.addRoute('users.create', { authRequired: true }, { } if (this.bodyParams.customFields) { - RocketChat.validateCustomFields(this.bodyParams.customFields); + validateCustomFields(this.bodyParams.customFields); } - const newUserId = RocketChat.saveUser(this.userId, this.bodyParams); + const newUserId = saveUser(this.userId, this.bodyParams); if (this.bodyParams.customFields) { - RocketChat.saveCustomFieldsWithoutValidation(newUserId, this.bodyParams.customFields); + saveCustomFieldsWithoutValidation(newUserId, this.bodyParams.customFields); } @@ -191,7 +199,7 @@ API.v1.addRoute('users.register', { authRequired: false }, { username: String, })); - if (!RocketChat.checkUsernameAvailability(this.bodyParams.username)) { + if (!checkUsernameAvailability(this.bodyParams.username)) { return API.v1.failure('Username is already in use'); } @@ -246,7 +254,7 @@ API.v1.addRoute('users.setAvatar', { authRequired: true }, { Meteor.runAsUser(user._id, () => { if (this.bodyParams.avatarUrl) { - RocketChat.setUserAvatar(user, this.bodyParams.avatarUrl, '', 'url'); + setUserAvatar(user, this.bodyParams.avatarUrl, '', 'url'); } else { const busboy = new Busboy({ headers: this.request.headers }); const fields = {}; @@ -281,7 +289,7 @@ API.v1.addRoute('users.setAvatar', { authRequired: true }, { return callback(new Meteor.Error('error-not-allowed', 'Not allowed')); } } - RocketChat.setUserAvatar(user, Buffer.concat(imageData), mimetype, 'rest'); + setUserAvatar(user, Buffer.concat(imageData), mimetype, 'rest'); callback(); })); })); @@ -318,10 +326,10 @@ API.v1.addRoute('users.update', { authRequired: true }, { const userData = _.extend({ _id: this.bodyParams.userId }, this.bodyParams.data); - Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); + Meteor.runAsUser(this.userId, () => saveUser(this.userId, userData)); if (this.bodyParams.data.customFields) { - RocketChat.saveCustomFields(this.bodyParams.userId, this.bodyParams.data.customFields); + saveCustomFields(this.bodyParams.userId, this.bodyParams.data.customFields); } if (typeof this.bodyParams.data.active !== 'undefined') { @@ -440,7 +448,7 @@ API.v1.addRoute('users.setPreferences', { authRequired: true }, { userData.language = language; } - Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); + Meteor.runAsUser(this.userId, () => saveUser(this.userId, userData)); const user = Users.findOneById(userId, { fields: { 'settings.preferences': 1, diff --git a/packages/rocketchat-apps/client/admin/appInstall.js b/packages/rocketchat-apps/client/admin/appInstall.js index f5e15623ef51..df6ea61b65f7 100644 --- a/packages/rocketchat-apps/client/admin/appInstall.js +++ b/packages/rocketchat-apps/client/admin/appInstall.js @@ -10,6 +10,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; +import { API } from 'meteor/rocketchat:api'; Template.appInstall.helpers({ appFile() { @@ -72,9 +73,9 @@ Template.appInstall.events({ let result; if (isUpdating) { - result = await RocketChat.API.post(`apps/${ t.isUpdatingId.get() }`, { url }); + result = await API.post(`apps/${ t.isUpdatingId.get() }`, { url }); } else { - result = await RocketChat.API.post('apps', { url }); + result = await API.post('apps', { url }); } if (result.compilerErrors.length !== 0 || result.app.status === 'compiler_error') { @@ -115,9 +116,9 @@ Template.appInstall.events({ let result; if (isUpdating) { - result = await RocketChat.API.upload(`apps/${ t.isUpdatingId.get() }`, data); + result = await API.upload(`apps/${ t.isUpdatingId.get() }`, data); } else { - result = await RocketChat.API.upload('apps', data); + result = await API.upload('apps', data); } console.log('install result', result); diff --git a/packages/rocketchat-apps/client/admin/appLogs.js b/packages/rocketchat-apps/client/admin/appLogs.js index 865bf4dcbfab..11f1c419b951 100644 --- a/packages/rocketchat-apps/client/admin/appLogs.js +++ b/packages/rocketchat-apps/client/admin/appLogs.js @@ -2,6 +2,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; +import { API } from 'meteor/rocketchat:api'; import moment from 'moment'; import hljs from 'highlight.js'; @@ -17,8 +18,8 @@ Template.appLogs.onCreated(function() { const id = this.id.get(); Promise.all([ - RocketChat.API.get(`apps/${ id }`), - RocketChat.API.get(`apps/${ id }/logs`), + API.get(`apps/${ id }`), + API.get(`apps/${ id }/logs`), ]).then((results) => { instance.app.set(results[0].app); diff --git a/packages/rocketchat-apps/client/admin/appManage.js b/packages/rocketchat-apps/client/admin/appManage.js index 986cd135d9c8..b0a54ad45c36 100644 --- a/packages/rocketchat-apps/client/admin/appManage.js +++ b/packages/rocketchat-apps/client/admin/appManage.js @@ -5,6 +5,7 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { TAPi18next } from 'meteor/tap:i18n'; import { isEmail } from 'meteor/rocketchat:utils'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -21,7 +22,7 @@ function getApps(instance) { return Promise.all([ fetch(`${ HOST }/v1/apps/${ id }?version=${ RocketChat.Info.marketplaceApiVersion }`).then((data) => data.json()), - RocketChat.API.get('apps/').then((result) => result.apps.filter((app) => app.id === id)), + API.get('apps/').then((result) => result.apps.filter((app) => app.id === id)), ]).then(([remoteApps, [localApp]]) => { remoteApps = remoteApps.sort((a, b) => { if (semver.gt(a.version, b.version)) { @@ -114,7 +115,7 @@ Template.appManage.onCreated(function() { return; } - RocketChat.API.get(`apps/${ id }/settings`).then((result) => { + API.get(`apps/${ id }/settings`).then((result) => { _morphSettings(result.settings); }); }; @@ -263,7 +264,7 @@ async function setActivate(actiavate, e, t) { const status = actiavate ? 'manually_enabled' : 'manually_disabled'; try { - const result = await RocketChat.API.post(`apps/${ t.id.get() }/status`, { status }); + const result = await API.post(`apps/${ t.id.get() }/status`, { status }); const info = t.app.get(); info.status = result.status; t.app.set(info); @@ -301,7 +302,7 @@ Template.appManage.events({ 'click .js-uninstall': async(e, t) => { t.ready.set(false); try { - await RocketChat.API.delete(`apps/${ t.id.get() }`); + await API.delete(`apps/${ t.id.get() }`); FlowRouter.go('/admin/apps'); } catch (err) { console.warn('Error:', err); @@ -321,7 +322,7 @@ Template.appManage.events({ const api = app.newVersion ? `apps/${ t.id.get() }` : 'apps/'; - RocketChat.API.post(api, { url }).then(() => { + API.post(api, { url }).then(() => { getApps(t).then(() => { el.prop('disabled', false); el.removeClass('loading'); @@ -371,7 +372,7 @@ Template.appManage.events({ if (toSave.length === 0) { throw 'Nothing to save..'; } - const result = await RocketChat.API.post(`apps/${ t.id.get() }/settings`, undefined, { settings: toSave }); + const result = await API.post(`apps/${ t.id.get() }/settings`, undefined, { settings: toSave }); console.log('Updating results:', result); result.updated.forEach((setting) => { settings[setting.id].value = settings[setting.id].oldValue = setting.value; diff --git a/packages/rocketchat-apps/client/admin/apps.js b/packages/rocketchat-apps/client/admin/apps.js index a12d2a77db9d..929859561f65 100644 --- a/packages/rocketchat-apps/client/admin/apps.js +++ b/packages/rocketchat-apps/client/admin/apps.js @@ -4,6 +4,7 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { t } from 'meteor/rocketchat:utils'; import { AppEvents } from '../communication'; +import { API } from 'meteor/rocketchat:api'; const ENABLED_STATUS = ['auto_enabled', 'manually_enabled']; const HOST = 'https://marketplace.rocket.chat'; @@ -48,7 +49,7 @@ const getApps = (instance) => { const getInstalledApps = (instance) => { - RocketChat.API.get('apps').then((data) => { + API.get('apps').then((data) => { const apps = data.apps.map((app) => ({ latest: app })); instance.installedApps.set(apps); @@ -253,7 +254,7 @@ Template.apps.events({ const url = `${ HOST }/v1/apps/${ this.latest.id }/download/${ this.latest.version }`; - RocketChat.API.post('apps/', { url }).then(() => { + API.post('apps/', { url }).then(() => { getInstalledApps(template); }).catch((e) => { toastr.error((e.xhr.responseJSON && e.xhr.responseJSON.error) || e.message); diff --git a/packages/rocketchat-apps/client/communication/websockets.js b/packages/rocketchat-apps/client/communication/websockets.js index a43c8312c62a..248331cd0ff8 100644 --- a/packages/rocketchat-apps/client/communication/websockets.js +++ b/packages/rocketchat-apps/client/communication/websockets.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { API } from 'meteor/rocketchat:api'; export const AppEvents = Object.freeze({ APP_ADDED: 'app/added', @@ -49,7 +50,7 @@ export class AppWebsocketReceiver { } onAppAdded(appId) { - RocketChat.API.get(`apps/${ appId }/languages`).then((result) => { + API.get(`apps/${ appId }/languages`).then((result) => { this.orch.parseAndLoadLanguages(result.languages, appId); }); @@ -73,7 +74,7 @@ export class AppWebsocketReceiver { } onCommandAdded(command) { - RocketChat.API.v1.get('commands.get', { command }).then((result) => { + API.v1.get('commands.get', { command }).then((result) => { RocketChat.slashCommands.commands[command] = result.command; }); } @@ -83,7 +84,7 @@ export class AppWebsocketReceiver { } onCommandUpdated(command) { - RocketChat.API.v1.get('commands.get', { command }).then((result) => { + API.v1.get('commands.get', { command }).then((result) => { RocketChat.slashCommands.commands[command] = result.command; }); } diff --git a/packages/rocketchat-apps/client/orchestrator.js b/packages/rocketchat-apps/client/orchestrator.js index fb85e8da85a6..ebe4067a8540 100644 --- a/packages/rocketchat-apps/client/orchestrator.js +++ b/packages/rocketchat-apps/client/orchestrator.js @@ -4,6 +4,7 @@ import { Utilities } from '../lib/misc/Utilities'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { TAPi18next } from 'meteor/tap:i18n'; +import { API } from 'meteor/rocketchat:api'; class AppClientOrchestrator { constructor() { @@ -71,7 +72,7 @@ class AppClientOrchestrator { } _loadLanguages() { - return RocketChat.API.get('apps/languages').then((info) => { + return API.get('apps/languages').then((info) => { info.apps.forEach((rlInfo) => this.parseAndLoadLanguages(rlInfo.languages, rlInfo.id)); }); } @@ -92,7 +93,7 @@ class AppClientOrchestrator { } async getAppApis(appId) { - const result = await RocketChat.API.get(`apps/${ appId }/apis`); + const result = await API.get(`apps/${ appId }/apis`); return result.apis; } } diff --git a/packages/rocketchat-apps/server/communication/rest.js b/packages/rocketchat-apps/server/communication/rest.js index 68d30c1bf470..431956037a1f 100644 --- a/packages/rocketchat-apps/server/communication/rest.js +++ b/packages/rocketchat-apps/server/communication/rest.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; +import { API } from 'meteor/rocketchat:api'; import Busboy from 'busboy'; export class AppsRestApi { constructor(orch, manager) { this._orch = orch; this._manager = manager; - this.api = new RocketChat.API.ApiClass({ + this.api = new API.ApiClass({ version: 'apps', useDefaultAuth: true, prettyJson: false, enableCors: false, - auth: RocketChat.API.getUserAuth(), + auth: API.getUserAuth(), }); this.addManagementRoutes(); @@ -53,7 +54,7 @@ export class AppsRestApi { return info; }); - return RocketChat.API.v1.success({ apps }); + return API.v1.success({ apps }); }, post() { let buff; @@ -62,7 +63,7 @@ export class AppsRestApi { const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: 'base64' } }); if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') { - return RocketChat.API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); + return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); } buff = Buffer.from(result.content, 'base64'); @@ -71,7 +72,7 @@ export class AppsRestApi { } if (!buff) { - return RocketChat.API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); + return API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); } const aff = Promise.await(manager.add(buff.toString('base64'), false)); @@ -84,7 +85,7 @@ export class AppsRestApi { info.status = 'compiler_error'; } - return RocketChat.API.v1.success({ + return API.v1.success({ app: info, implemented: aff.getImplementedInferfaces(), compilerErrors: aff.getCompilerErrors(), @@ -99,7 +100,7 @@ export class AppsRestApi { languages: prl.getStorageItem().languageContent, })); - return RocketChat.API.v1.success({ apps }); + return API.v1.success({ apps }); }, }); @@ -112,9 +113,9 @@ export class AppsRestApi { const info = prl.getInfo(); info.status = prl.getStatus(); - return RocketChat.API.v1.success({ app: info }); + return API.v1.success({ app: info }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { @@ -127,7 +128,7 @@ export class AppsRestApi { const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: 'base64' } }); if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') { - return RocketChat.API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); + return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); } buff = Buffer.from(result.content, 'base64'); @@ -136,7 +137,7 @@ export class AppsRestApi { } if (!buff) { - return RocketChat.API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); + return API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); } const aff = Promise.await(manager.update(buff.toString('base64'))); @@ -149,7 +150,7 @@ export class AppsRestApi { info.status = 'compiler_error'; } - return RocketChat.API.v1.success({ + return API.v1.success({ app: info, implemented: aff.getImplementedInferfaces(), compilerErrors: aff.getCompilerErrors(), @@ -165,9 +166,9 @@ export class AppsRestApi { const info = prl.getInfo(); info.status = prl.getStatus(); - return RocketChat.API.v1.success({ app: info }); + return API.v1.success({ app: info }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -180,9 +181,9 @@ export class AppsRestApi { if (prl) { const info = prl.getInfo(); - return RocketChat.API.v1.success({ iconFileContent: info.iconFileContent }); + return API.v1.success({ iconFileContent: info.iconFileContent }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -195,9 +196,9 @@ export class AppsRestApi { if (prl) { const languages = prl.getStorageItem().languageContent || {}; - return RocketChat.API.v1.success({ languages }); + return API.v1.success({ languages }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -221,9 +222,9 @@ export class AppsRestApi { const logs = Promise.await(orchestrator.getLogStorage().find(ourQuery, options)); - return RocketChat.API.v1.success({ logs }); + return API.v1.success({ logs }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -242,21 +243,21 @@ export class AppsRestApi { } }); - return RocketChat.API.v1.success({ settings }); + return API.v1.success({ settings }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { console.log(`Updating ${ this.urlParams.id }'s settings..`); if (!this.bodyParams || !this.bodyParams.settings) { - return RocketChat.API.v1.failure('The settings to update must be present.'); + return API.v1.failure('The settings to update must be present.'); } const prl = manager.getOneById(this.urlParams.id); if (!prl) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } const { settings } = prl.getStorageItem(); @@ -270,7 +271,7 @@ export class AppsRestApi { } }); - return RocketChat.API.v1.success({ updated }); + return API.v1.success({ updated }); }, }); @@ -281,14 +282,14 @@ export class AppsRestApi { try { const setting = manager.getSettingsManager().getAppSetting(this.urlParams.id, this.urlParams.settingId); - RocketChat.API.v1.success({ setting }); + API.v1.success({ setting }); } catch (e) { if (e.message.includes('No setting found')) { - return RocketChat.API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); + return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); } else if (e.message.includes('No App found')) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } else { - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } } }, @@ -296,20 +297,20 @@ export class AppsRestApi { console.log(`Updating the App ${ this.urlParams.id }'s setting ${ this.urlParams.settingId }`); if (!this.bodyParams.setting) { - return RocketChat.API.v1.failure('Setting to update to must be present on the posted body.'); + return API.v1.failure('Setting to update to must be present on the posted body.'); } try { Promise.await(manager.getSettingsManager().updateAppSetting(this.urlParams.id, this.bodyParams.setting)); - return RocketChat.API.v1.success(); + return API.v1.success(); } catch (e) { if (e.message.includes('No setting found')) { - return RocketChat.API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); + return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); } else if (e.message.includes('No App found')) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } else { - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } } }, @@ -321,11 +322,11 @@ export class AppsRestApi { const prl = manager.getOneById(this.urlParams.id); if (prl) { - return RocketChat.API.v1.success({ + return API.v1.success({ apis: manager.apiManager.listApis(this.urlParams.id), }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -336,14 +337,14 @@ export class AppsRestApi { const prl = manager.getOneById(this.urlParams.id); if (prl) { - return RocketChat.API.v1.success({ status: prl.getStatus() }); + return API.v1.success({ status: prl.getStatus() }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { if (!this.bodyParams.status || typeof this.bodyParams.status !== 'string') { - return RocketChat.API.v1.failure('Invalid status provided, it must be "status" field and a string.'); + return API.v1.failure('Invalid status provided, it must be "status" field and a string.'); } console.log(`Updating ${ this.urlParams.id }'s status...`, this.bodyParams.status); @@ -352,9 +353,9 @@ export class AppsRestApi { if (prl) { const result = Promise.await(manager.changeStatus(prl.getID(), this.bodyParams.status)); - return RocketChat.API.v1.success({ status: result.getStatus() }); + return API.v1.success({ status: result.getStatus() }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); diff --git a/packages/rocketchat-graphql/package.js b/packages/rocketchat-graphql/package.js index 87b0c860d278..33c25e41e4ce 100644 --- a/packages/rocketchat-graphql/package.js +++ b/packages/rocketchat-graphql/package.js @@ -13,6 +13,7 @@ Package.onUse(function(api) { 'rocketchat:lib', 'rocketchat:api', 'rocketchat:accounts', + 'rocketchat:integrations', 'swydo:graphql', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js index 5d4c8a154df4..c74398268e84 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js @@ -1,5 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { API } from 'meteor/rocketchat:api'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/createChannel.graphqls'; @@ -7,7 +6,7 @@ const resolver = { Mutation: { createChannel: authenticated((root, args, { user }) => { try { - RocketChat.API.channels.create.validate({ + API.channels.create.validate({ user: { value: user._id, }, @@ -24,7 +23,7 @@ const resolver = { throw e; } - const { channel } = RocketChat.API.channels.create.execute(user._id, { + const { channel } = API.channels.create.execute(user._id, { name: args.name, members: args.membersId, }); diff --git a/packages/rocketchat-importer/client/admin/adminImportHistory.js b/packages/rocketchat-importer/client/admin/adminImportHistory.js index 5b2ee4d5dcfe..76f81a877753 100644 --- a/packages/rocketchat-importer/client/admin/adminImportHistory.js +++ b/packages/rocketchat-importer/client/admin/adminImportHistory.js @@ -7,6 +7,7 @@ import toastr from 'toastr'; import { ReactiveVar } from 'meteor/reactive-var'; import { ProgressStep } from '../../lib/ImporterProgressStep'; import { FlowRouter } from 'meteor/kadira:flow-router'; +import { API } from 'meteor/rocketchat:api'; Template.adminImportHistory.helpers({ isAdmin() { @@ -183,7 +184,7 @@ Template.adminImportHistory.onCreated(function() { this.preparing = new ReactiveVar(true); this.history = new ReactiveVar([]); - RocketChat.API.get('v1/getLatestImportOperations').then((data) => { + API.get('v1/getLatestImportOperations').then((data) => { instance.history.set(data); instance.preparing.set(false); }).catch((error) => { diff --git a/packages/rocketchat-importer/client/admin/adminImportPrepare.js b/packages/rocketchat-importer/client/admin/adminImportPrepare.js index 216301adcb5d..b58c95f61697 100644 --- a/packages/rocketchat-importer/client/admin/adminImportPrepare.js +++ b/packages/rocketchat-importer/client/admin/adminImportPrepare.js @@ -6,6 +6,7 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat, handleError } from 'meteor/rocketchat:lib'; import { t } from 'meteor/rocketchat:utils'; +import { API } from 'meteor/rocketchat:api'; import toastr from 'toastr'; Template.adminImportPrepare.helpers({ @@ -95,7 +96,7 @@ function showException(error, defaultErrorString) { } function getImportFileData(importer, template) { - RocketChat.API.get(`v1/getImportFileData?importerKey=${ importer.key }`).then((data) => { + API.get(`v1/getImportFileData?importerKey=${ importer.key }`).then((data) => { if (!data) { console.warn(`The importer ${ importer.key } is not set up correctly, as it did not return any data.`); toastr.error(t('Importer_not_setup')); @@ -148,7 +149,7 @@ Template.adminImportPrepare.events({ reader.readAsBinaryString(file); reader.onloadend = () => { - RocketChat.API.post('v1/uploadImportFile', { + API.post('v1/uploadImportFile', { binaryContent: reader.result, contentType: file.type, fileName: file.name, @@ -174,7 +175,7 @@ Template.adminImportPrepare.events({ template.preparing.set(true); - RocketChat.API.post('v1/downloadPublicImportFile', { + API.post('v1/downloadPublicImportFile', { fileUrl, importerKey: importer.key, }).then(() => { diff --git a/packages/rocketchat-importer/package.js b/packages/rocketchat-importer/package.js index 136826523918..71fe8869d538 100644 --- a/packages/rocketchat-importer/package.js +++ b/packages/rocketchat-importer/package.js @@ -12,6 +12,7 @@ Package.onUse(function(api) { 'check', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:logger', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-integrations/package.js b/packages/rocketchat-integrations/package.js index 43f897cb8e47..577a0ee92f32 100644 --- a/packages/rocketchat-integrations/package.js +++ b/packages/rocketchat-integrations/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'ecmascript', 'mongo', 'babel-compiler', + 'rocketchat:api', 'rocketchat:lib', 'rocketchat:authorization', 'rocketchat:theme', diff --git a/packages/rocketchat-integrations/server/api/api.js b/packages/rocketchat-integrations/server/api/api.js index d92b52664ea7..5b8b6b4a05c5 100644 --- a/packages/rocketchat-integrations/server/api/api.js +++ b/packages/rocketchat-integrations/server/api/api.js @@ -3,6 +3,7 @@ import { HTTP } from 'meteor/http'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; +import { API } from 'meteor/rocketchat:api'; import { logger } from '../logger'; import { processWebhookMessage } from '../processWebhookMessage'; import Fiber from 'fibers'; @@ -129,12 +130,12 @@ function getIntegrationScript(integration) { logger.incoming.error(script.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); - throw RocketChat.API.v1.failure('error-evaluating-script'); + throw API.v1.failure('error-evaluating-script'); } if (!sandbox.Script) { logger.incoming.error('[Class "Script" not in Trigger', integration.name, ']'); - throw RocketChat.API.v1.failure('class-script-not-found'); + throw API.v1.failure('class-script-not-found'); } } @@ -172,7 +173,7 @@ function createIntegration(options, user) { } }); - return RocketChat.API.v1.success(); + return API.v1.success(); } function removeIntegration(options, user) { @@ -185,7 +186,7 @@ function removeIntegration(options, user) { Meteor.runAsUser(user._id, () => Meteor.call('deleteOutgoingIntegration', integrationToRemove._id)); - return RocketChat.API.v1.success(); + return API.v1.success(); } function executeIntegrationRest() { @@ -213,7 +214,7 @@ function executeIntegrationRest() { script = getIntegrationScript(this.integration); } catch (e) { logger.incoming.warn(e); - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } this.request.setEncoding('utf8'); @@ -262,9 +263,9 @@ function executeIntegrationRest() { if (!result) { logger.incoming.debug('[Process Incoming Request result of Trigger', this.integration.name, ':] No data'); - return RocketChat.API.v1.success(); + return API.v1.success(); } else if (result && result.error) { - return RocketChat.API.v1.failure(result.error); + return API.v1.failure(result.error); } this.bodyParams = result && result.content; @@ -280,7 +281,7 @@ function executeIntegrationRest() { logger.incoming.error(this.integration.scriptCompiled.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); - return RocketChat.API.v1.failure('error-running-script'); + return API.v1.failure('error-running-script'); } } @@ -288,7 +289,7 @@ function executeIntegrationRest() { // TODO: Temporary fix for https://github.com/RocketChat/Rocket.Chat/issues/7770 until the above is implemented if (!this.bodyParams || (_.isEmpty(this.bodyParams) && !this.integration.scriptEnabled)) { // return RocketChat.API.v1.failure('body-empty'); - return RocketChat.API.v1.success(); + return API.v1.success(); } this.bodyParams.bot = { i: this.integration._id }; @@ -296,16 +297,16 @@ function executeIntegrationRest() { try { const message = processWebhookMessage(this.bodyParams, this.user, defaultValues); if (_.isEmpty(message)) { - return RocketChat.API.v1.failure('unknown-error'); + return API.v1.failure('unknown-error'); } if (this.scriptResponse) { logger.incoming.debug('response', this.scriptResponse); } - return RocketChat.API.v1.success(this.scriptResponse); + return API.v1.success(this.scriptResponse); } catch ({ error, message }) { - return RocketChat.API.v1.failure(error || message); + return API.v1.failure(error || message); } } diff --git a/packages/rocketchat-integrations/server/processWebhookMessage.js b/packages/rocketchat-integrations/server/processWebhookMessage.js index d72a96fb36ed..a0c36c660726 100644 --- a/packages/rocketchat-integrations/server/processWebhookMessage.js +++ b/packages/rocketchat-integrations/server/processWebhookMessage.js @@ -1,86 +1 @@ -import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import _ from 'underscore'; -import s from 'underscore.string'; - -export const processWebhookMessage = function(messageObj, user, defaultValues = { channel: '', alias: '', avatar: '', emoji: '' }, mustBeJoined = false) { - const sentData = []; - const channels = [].concat(messageObj.channel || messageObj.roomId || defaultValues.channel); - - for (const channel of channels) { - const channelType = channel[0]; - - let channelValue = channel.substr(1); - let room; - - switch (channelType) { - case '#': - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true }); - break; - case '@': - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd' }); - break; - default: - channelValue = channelType + channelValue; - - // Try to find the room by id or name if they didn't include the prefix. - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true, errorOnEmpty: false }); - if (room) { - break; - } - - // We didn't get a room, let's try finding direct messages - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd', tryDirectByUserIdOnly: true }); - if (room) { - break; - } - - // No room, so throw an error - throw new Meteor.Error('invalid-channel'); - } - - if (mustBeJoined && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { - // throw new Meteor.Error('invalid-room', 'Invalid room provided to send a message to, must be joined.'); - throw new Meteor.Error('invalid-channel'); // Throwing the generic one so people can't "brute force" find rooms - } - - if (messageObj.attachments && !_.isArray(messageObj.attachments)) { - console.log('Attachments should be Array, ignoring value'.red, messageObj.attachments); - messageObj.attachments = undefined; - } - - const message = { - alias: messageObj.username || messageObj.alias || defaultValues.alias, - msg: s.trim(messageObj.text || messageObj.msg || ''), - attachments: messageObj.attachments || [], - parseUrls: messageObj.parseUrls !== undefined ? messageObj.parseUrls : !messageObj.attachments, - bot: messageObj.bot, - groupable: (messageObj.groupable !== undefined) ? messageObj.groupable : false, - }; - - if (!_.isEmpty(messageObj.icon_url) || !_.isEmpty(messageObj.avatar)) { - message.avatar = messageObj.icon_url || messageObj.avatar; - } else if (!_.isEmpty(messageObj.icon_emoji) || !_.isEmpty(messageObj.emoji)) { - message.emoji = messageObj.icon_emoji || messageObj.emoji; - } else if (!_.isEmpty(defaultValues.avatar)) { - message.avatar = defaultValues.avatar; - } else if (!_.isEmpty(defaultValues.emoji)) { - message.emoji = defaultValues.emoji; - } - - if (_.isArray(message.attachments)) { - for (let i = 0; i < message.attachments.length; i++) { - const attachment = message.attachments[i]; - if (attachment.msg) { - attachment.text = s.trim(attachment.msg); - delete attachment.msg; - } - } - } - - const messageReturn = RocketChat.sendMessage(user, message, room); - sentData.push({ channel, message: messageReturn }); - } - - return sentData; -}; +export { processWebhookMessage } from 'meteor/rocketchat:lib'; diff --git a/packages/rocketchat-lib/client/lib/RestApiClient.js b/packages/rocketchat-lib/client/lib/RestApiClient.js deleted file mode 100644 index 9c2d7a9b86e9..000000000000 --- a/packages/rocketchat-lib/client/lib/RestApiClient.js +++ /dev/null @@ -1,3 +0,0 @@ -// import { API } from 'meteor/rocketchat:api'; - -// RocketChat.API = API; diff --git a/packages/rocketchat-lib/client/lib/startup/commands.js b/packages/rocketchat-lib/client/lib/startup/commands.js index 35cc4960da43..d07c7e670ce6 100644 --- a/packages/rocketchat-lib/client/lib/startup/commands.js +++ b/packages/rocketchat-lib/client/lib/startup/commands.js @@ -9,9 +9,11 @@ import { slashCommands } from 'meteor/rocketchat:utils'; Tracker.autorun(() => { const newUserId = Meteor.userId(); if (oldUserId === null && newUserId) { - RocketChat.API.v1.get('commands.list').then(function _loadedCommands(result) { - result.commands.forEach((command) => { - slashCommands.commands[command.command] = command; + import('meteor/rocketchat:api').then(({ API }) => { + API.v1.get('commands.list').then(function _loadedCommands(result) { + result.commands.forEach((command) => { + slashCommands.commands[command.command] = command; + }); }); }); } diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9947ebcd7751..c29baddb4e19 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -237,7 +237,6 @@ Package.onUse(function(api) { api.addFiles('client/Notifications.js', 'client'); api.addFiles('client/OAuthProxy.js', 'client'); api.addFiles('client/UserDeleted.js', 'client'); - api.addFiles('client/lib/RestApiClient.js', 'client'); api.addFiles('client/lib/TabBar.js', 'client'); api.addFiles('client/lib/RocketChatTabBar.js', 'client'); api.addFiles('client/lib/RocketChatAnnouncement.js', 'client'); diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js index c60ee0e9849d..5ff75d6934f9 100644 --- a/packages/rocketchat-lib/server/functions/index.js +++ b/packages/rocketchat-lib/server/functions/index.js @@ -24,3 +24,4 @@ export { unarchiveRoom } from './unarchiveRoom'; export { updateMessage } from './updateMessage'; export { validateCustomFields } from './validateCustomFields'; export { generateUsernameSuggestion } from './getUsernameSuggestion'; +export { processWebhookMessage } from './processWebhookMessage'; diff --git a/packages/rocketchat-lib/server/functions/processWebhookMessage.js b/packages/rocketchat-lib/server/functions/processWebhookMessage.js new file mode 100644 index 000000000000..ed87ef60468f --- /dev/null +++ b/packages/rocketchat-lib/server/functions/processWebhookMessage.js @@ -0,0 +1,88 @@ +import { Meteor } from 'meteor/meteor'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { getRoomByNameOrIdWithOptionToJoin } from './getRoomByNameOrIdWithOptionToJoin'; +import { sendMessage } from './sendMessage'; +import _ from 'underscore'; +import s from 'underscore.string'; + +export const processWebhookMessage = function(messageObj, user, defaultValues = { channel: '', alias: '', avatar: '', emoji: '' }, mustBeJoined = false) { + const sentData = []; + const channels = [].concat(messageObj.channel || messageObj.roomId || defaultValues.channel); + + for (const channel of channels) { + const channelType = channel[0]; + + let channelValue = channel.substr(1); + let room; + + switch (channelType) { + case '#': + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true }); + break; + case '@': + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd' }); + break; + default: + channelValue = channelType + channelValue; + + // Try to find the room by id or name if they didn't include the prefix. + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true, errorOnEmpty: false }); + if (room) { + break; + } + + // We didn't get a room, let's try finding direct messages + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd', tryDirectByUserIdOnly: true }); + if (room) { + break; + } + + // No room, so throw an error + throw new Meteor.Error('invalid-channel'); + } + + if (mustBeJoined && !Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { + // throw new Meteor.Error('invalid-room', 'Invalid room provided to send a message to, must be joined.'); + throw new Meteor.Error('invalid-channel'); // Throwing the generic one so people can't "brute force" find rooms + } + + if (messageObj.attachments && !_.isArray(messageObj.attachments)) { + console.log('Attachments should be Array, ignoring value'.red, messageObj.attachments); + messageObj.attachments = undefined; + } + + const message = { + alias: messageObj.username || messageObj.alias || defaultValues.alias, + msg: s.trim(messageObj.text || messageObj.msg || ''), + attachments: messageObj.attachments || [], + parseUrls: messageObj.parseUrls !== undefined ? messageObj.parseUrls : !messageObj.attachments, + bot: messageObj.bot, + groupable: (messageObj.groupable !== undefined) ? messageObj.groupable : false, + }; + + if (!_.isEmpty(messageObj.icon_url) || !_.isEmpty(messageObj.avatar)) { + message.avatar = messageObj.icon_url || messageObj.avatar; + } else if (!_.isEmpty(messageObj.icon_emoji) || !_.isEmpty(messageObj.emoji)) { + message.emoji = messageObj.icon_emoji || messageObj.emoji; + } else if (!_.isEmpty(defaultValues.avatar)) { + message.avatar = defaultValues.avatar; + } else if (!_.isEmpty(defaultValues.emoji)) { + message.emoji = defaultValues.emoji; + } + + if (_.isArray(message.attachments)) { + for (let i = 0; i < message.attachments.length; i++) { + const attachment = message.attachments[i]; + if (attachment.msg) { + attachment.text = s.trim(attachment.msg); + delete attachment.msg; + } + } + } + + const messageReturn = sendMessage(user, message, room); + sentData.push({ channel, message: messageReturn }); + } + + return sentData; +}; diff --git a/packages/rocketchat-livechat/imports/server/rest/departments.js b/packages/rocketchat-livechat/imports/server/rest/departments.js index 296cf37707b7..422d0f492102 100644 --- a/packages/rocketchat-livechat/imports/server/rest/departments.js +++ b/packages/rocketchat-livechat/imports/server/rest/departments.js @@ -1,19 +1,20 @@ import { check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/department', { authRequired: true }, { +API.v1.addRoute('livechat/department', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success({ + return API.v1.success({ departments: RocketChat.models.LivechatDepartment.find().fetch(), }); }, post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -25,23 +26,23 @@ RocketChat.API.v1.addRoute('livechat/department', { authRequired: true }, { const department = RocketChat.Livechat.saveDepartment(null, this.bodyParams.department, this.bodyParams.agents); if (department) { - return RocketChat.API.v1.success({ + return API.v1.success({ department, agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: department._id }).fetch(), }); } - RocketChat.API.v1.failure(); + API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { +API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -49,17 +50,17 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { _id: String, }); - return RocketChat.API.v1.success({ + return API.v1.success({ department: RocketChat.models.LivechatDepartment.findOneById(this.urlParams._id), agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: this.urlParams._id }).fetch(), }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, put() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -73,20 +74,20 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { }); if (RocketChat.Livechat.saveDepartment(this.urlParams._id, this.bodyParams.department, this.bodyParams.agents)) { - return RocketChat.API.v1.success({ + return API.v1.success({ department: RocketChat.models.LivechatDepartment.findOneById(this.urlParams._id), agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: this.urlParams._id }).fetch(), }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -95,12 +96,12 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { }); if (RocketChat.Livechat.removeDepartment(this.urlParams._id)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); diff --git a/packages/rocketchat-livechat/imports/server/rest/facebook.js b/packages/rocketchat-livechat/imports/server/rest/facebook.js index a083c649716f..0e05e98d2161 100644 --- a/packages/rocketchat-livechat/imports/server/rest/facebook.js +++ b/packages/rocketchat-livechat/imports/server/rest/facebook.js @@ -1,6 +1,7 @@ import crypto from 'crypto'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; @@ -17,7 +18,7 @@ import LivechatVisitors from '../../../server/models/LivechatVisitors'; * @apiParam {String} [text] Facebook message text * @apiParam {String} [attachments] Facebook message attachments */ -RocketChat.API.v1.addRoute('livechat/facebook', { +API.v1.addRoute('livechat/facebook', { post() { if (!this.bodyParams.text && !this.bodyParams.attachments) { return { diff --git a/packages/rocketchat-livechat/imports/server/rest/sms.js b/packages/rocketchat-livechat/imports/server/rest/sms.js index 4924d9b5cdfb..ce107e278848 100644 --- a/packages/rocketchat-livechat/imports/server/rest/sms.js +++ b/packages/rocketchat-livechat/imports/server/rest/sms.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; -RocketChat.API.v1.addRoute('livechat/sms-incoming/:service', { +API.v1.addRoute('livechat/sms-incoming/:service', { post() { const SMSService = RocketChat.SMS.getService(this.urlParams.service); diff --git a/packages/rocketchat-livechat/imports/server/rest/upload.js b/packages/rocketchat-livechat/imports/server/rest/upload.js index 88310a6e96db..61dd1438bb5f 100644 --- a/packages/rocketchat-livechat/imports/server/rest/upload.js +++ b/packages/rocketchat-livechat/imports/server/rest/upload.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { API } from 'meteor/rocketchat:api'; import Busboy from 'busboy'; import filesize from 'filesize'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; @@ -14,22 +15,22 @@ RocketChat.settings.get('FileUpload_MaxFileSize', function(key, value) { } }); -RocketChat.API.v1.addRoute('livechat/upload/:rid', { +API.v1.addRoute('livechat/upload/:rid', { post() { if (!this.request.headers['x-visitor-token']) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const visitorToken = this.request.headers['x-visitor-token']; const visitor = LivechatVisitors.getVisitorByToken(visitorToken); if (!visitor) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const room = RocketChat.models.Rooms.findOneOpenByRoomIdAndVisitorToken(this.urlParams.rid, visitorToken); if (!room) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const busboy = new Busboy({ headers: this.request.headers }); @@ -58,24 +59,24 @@ RocketChat.API.v1.addRoute('livechat/upload/:rid', { })(); if (files.length === 0) { - return RocketChat.API.v1.failure('File required'); + return API.v1.failure('File required'); } if (files.length > 1) { - return RocketChat.API.v1.failure('Just 1 file is allowed'); + return API.v1.failure('Just 1 file is allowed'); } const file = files[0]; if (!RocketChat.fileUploadIsValidContentType(file.mimetype)) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ reason: 'error-type-not-allowed', }); } // -1 maxFileSize means there is no limit if (maxFileSize > -1 && file.fileBuffer.length > maxFileSize) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ reason: 'error-size-not-allowed', sizeAllowed: filesize(maxFileSize), }); @@ -96,6 +97,6 @@ RocketChat.API.v1.addRoute('livechat/upload/:rid', { uploadedFile.description = fields.description; delete fields.description; - RocketChat.API.v1.success(Meteor.call('sendFileLivechatMessage', this.urlParams.rid, visitorToken, uploadedFile, fields)); + API.v1.success(Meteor.call('sendFileLivechatMessage', this.urlParams.rid, visitorToken, uploadedFile, fields)); }, }); diff --git a/packages/rocketchat-livechat/imports/server/rest/users.js b/packages/rocketchat-livechat/imports/server/rest/users.js index 3245793857e6..3892da0bbb53 100644 --- a/packages/rocketchat-livechat/imports/server/rest/users.js +++ b/packages/rocketchat-livechat/imports/server/rest/users.js @@ -1,11 +1,12 @@ import { check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; -RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { +API.v1.addRoute('livechat/users/:type', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -24,16 +25,16 @@ RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { const users = RocketChat.authz.getUsersInRole(role); - return RocketChat.API.v1.success({ + return API.v1.success({ users: users.fetch().map((user) => _.pick(user, '_id', 'username', 'name', 'status', 'statusLivechat')), }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { check(this.urlParams, { @@ -47,28 +48,28 @@ RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { if (this.urlParams.type === 'agent') { const user = RocketChat.Livechat.addAgent(this.bodyParams.username); if (user) { - return RocketChat.API.v1.success({ user }); + return API.v1.success({ user }); } } else if (this.urlParams.type === 'manager') { const user = RocketChat.Livechat.addManager(this.bodyParams.username); if (user) { - return RocketChat.API.v1.success({ user }); + return API.v1.success({ user }); } } else { throw 'Invalid type'; } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, { +API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -80,7 +81,7 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, const user = RocketChat.models.Users.findOneById(this.urlParams._id); if (!user) { - return RocketChat.API.v1.failure('User not found'); + return API.v1.failure('User not found'); } let role; @@ -94,21 +95,21 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, } if (user.roles.indexOf(role) !== -1) { - return RocketChat.API.v1.success({ + return API.v1.success({ user: _.pick(user, '_id', 'username'), }); } - return RocketChat.API.v1.success({ + return API.v1.success({ user: null, }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -120,24 +121,24 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, const user = RocketChat.models.Users.findOneById(this.urlParams._id); if (!user) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } if (this.urlParams.type === 'agent') { if (RocketChat.Livechat.removeAgent(user.username)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } } else if (this.urlParams.type === 'manager') { if (RocketChat.Livechat.removeManager(user.username)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } } else { throw 'Invalid type'; } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/agent.js b/packages/rocketchat-livechat/server/api/v1/agent.js index 655e8bb7db36..d9a50d533e70 100644 --- a/packages/rocketchat-livechat/server/api/v1/agent.js +++ b/packages/rocketchat-livechat/server/api/v1/agent.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findRoom, findGuest, findAgent, findOpenRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/agent.info/:rid/:token', { +API.v1.addRoute('livechat/agent.info/:rid/:token', { get() { try { check(this.urlParams, { @@ -26,14 +27,14 @@ RocketChat.API.v1.addRoute('livechat/agent.info/:rid/:token', { throw new Meteor.Error('invalid-agent'); } - return RocketChat.API.v1.success({ agent }); + return API.v1.success({ agent }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/agent.next/:token', { +API.v1.addRoute('livechat/agent.next/:token', { get() { try { check(this.urlParams, { @@ -68,9 +69,9 @@ RocketChat.API.v1.addRoute('livechat/agent.next/:token', { throw new Meteor.Error('invalid-agent'); } - return RocketChat.API.v1.success({ agent }); + return API.v1.success({ agent }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/config.js b/packages/rocketchat-livechat/server/api/v1/config.js index b59c679bf934..03e86c76128d 100644 --- a/packages/rocketchat-livechat/server/api/v1/config.js +++ b/packages/rocketchat-livechat/server/api/v1/config.js @@ -1,8 +1,9 @@ import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, settings, online, findOpenRoom } from '../lib/livechat'; import { Match, check } from 'meteor/check'; -RocketChat.API.v1.addRoute('livechat/config', { +API.v1.addRoute('livechat/config', { get() { try { check(this.queryParams, { @@ -11,7 +12,7 @@ RocketChat.API.v1.addRoute('livechat/config', { const config = settings(); if (!config.enabled) { - return RocketChat.API.v1.success({ config: { enabled: false } }); + return API.v1.success({ config: { enabled: false } }); } const status = online(); @@ -30,9 +31,9 @@ RocketChat.API.v1.addRoute('livechat/config', { Object.assign(config, { online: status, guest, room, agent }); - return RocketChat.API.v1.success({ config }); + return API.v1.success({ config }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/customField.js b/packages/rocketchat-livechat/server/api/v1/customField.js index bcb738428ba4..e2818fa2f466 100644 --- a/packages/rocketchat-livechat/server/api/v1/customField.js +++ b/packages/rocketchat-livechat/server/api/v1/customField.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/custom.field', { +API.v1.addRoute('livechat/custom.field', { post() { try { check(this.bodyParams, { @@ -21,17 +22,17 @@ RocketChat.API.v1.addRoute('livechat/custom.field', { } if (!RocketChat.Livechat.setCustomFields({ token, key, value, overwrite })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ field: { key, value, overwrite } }); + return API.v1.success({ field: { key, value, overwrite } }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/custom.fields', { +API.v1.addRoute('livechat/custom.fields', { post() { check(this.bodyParams, { token: String, @@ -53,13 +54,13 @@ RocketChat.API.v1.addRoute('livechat/custom.fields', { const fields = this.bodyParams.customFields.map((customField) => { const data = Object.assign({ token }, customField); if (!RocketChat.Livechat.setCustomFields(data)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } return { Key: customField.key, value: customField.value, overwrite: customField.overwrite }; }); - return RocketChat.API.v1.success({ fields }); + return API.v1.success({ fields }); }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/message.js b/packages/rocketchat-livechat/server/api/v1/message.js index 8acc1dd9da6d..8abdaa6b761c 100644 --- a/packages/rocketchat-livechat/server/api/v1/message.js +++ b/packages/rocketchat-livechat/server/api/v1/message.js @@ -2,10 +2,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; import { findGuest, findRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/message', { +API.v1.addRoute('livechat/message', { post() { try { check(this.bodyParams, { @@ -47,17 +48,17 @@ RocketChat.API.v1.addRoute('livechat/message', { const result = RocketChat.Livechat.sendMessage(sendMessage); if (result) { const message = { _id: result._id, rid: result.rid, msg: result.msg, u: result.u, ts: result.ts }; - return RocketChat.API.v1.success({ message }); + return API.v1.success({ message }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/message/:_id', { +API.v1.addRoute('livechat/message/:_id', { put() { try { check(this.urlParams, { @@ -93,14 +94,14 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { const result = RocketChat.Livechat.updateMessage({ guest, message }); if (result) { const data = RocketChat.models.Messages.findOneById(_id); - return RocketChat.API.v1.success({ + return API.v1.success({ message: { _id: data._id, rid: data.rid, msg: data.msg, u: data.u, ts: data.ts }, }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { @@ -134,7 +135,7 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { const result = RocketChat.Livechat.deleteMessage({ guest, message }); if (result) { - return RocketChat.API.v1.success({ + return API.v1.success({ message: { _id, ts: new Date().toISOString(), @@ -142,14 +143,14 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/messages.history/:rid', { +API.v1.addRoute('livechat/messages.history/:rid', { get() { try { check(this.urlParams, { @@ -189,33 +190,33 @@ RocketChat.API.v1.addRoute('livechat/messages.history/:rid', { } const messages = RocketChat.loadMessageHistory({ userId: guest._id, rid, end, limit, ls }); - return RocketChat.API.v1.success(messages); + return API.v1.success(messages); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/messages', { authRequired: true }, { +API.v1.addRoute('livechat/messages', { authRequired: true }, { post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } if (!this.bodyParams.visitor) { - return RocketChat.API.v1.failure('Body param "visitor" is required'); + return API.v1.failure('Body param "visitor" is required'); } if (!this.bodyParams.visitor.token) { - return RocketChat.API.v1.failure('Body param "visitor.token" is required'); + return API.v1.failure('Body param "visitor.token" is required'); } if (!this.bodyParams.messages) { - return RocketChat.API.v1.failure('Body param "messages" is required'); + return API.v1.failure('Body param "messages" is required'); } if (!(this.bodyParams.messages instanceof Array)) { - return RocketChat.API.v1.failure('Body param "messages" is not an array'); + return API.v1.failure('Body param "messages" is not an array'); } if (this.bodyParams.messages.length === 0) { - return RocketChat.API.v1.failure('Body param "messages" is empty'); + return API.v1.failure('Body param "messages" is empty'); } const visitorToken = this.bodyParams.visitor.token; @@ -253,7 +254,7 @@ RocketChat.API.v1.addRoute('livechat/messages', { authRequired: true }, { }; }); - return RocketChat.API.v1.success({ + return API.v1.success({ messages: sentMessages, }); }, diff --git a/packages/rocketchat-livechat/server/api/v1/offlineMessage.js b/packages/rocketchat-livechat/server/api/v1/offlineMessage.js index 6409ea0f5667..338573084ebe 100644 --- a/packages/rocketchat-livechat/server/api/v1/offlineMessage.js +++ b/packages/rocketchat-livechat/server/api/v1/offlineMessage.js @@ -1,8 +1,9 @@ import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/offline.message', { +API.v1.addRoute('livechat/offline.message', { post() { try { check(this.bodyParams, { @@ -13,12 +14,12 @@ RocketChat.API.v1.addRoute('livechat/offline.message', { const { name, email, message } = this.bodyParams; if (!RocketChat.Livechat.sendOfflineMessage({ name, email, message })) { - return RocketChat.API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_offline_message') }); + return API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_offline_message') }); } - return RocketChat.API.v1.success({ message: TAPi18n.__('Livechat_offline_message_sent') }); + return API.v1.success({ message: TAPi18n.__('Livechat_offline_message_sent') }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/pageVisited.js b/packages/rocketchat-livechat/server/api/v1/pageVisited.js index 906f3f783529..1a0fc1098b6e 100644 --- a/packages/rocketchat-livechat/server/api/v1/pageVisited.js +++ b/packages/rocketchat-livechat/server/api/v1/pageVisited.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; import { findGuest, findRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/page.visited', { +API.v1.addRoute('livechat/page.visited', { post() { try { check(this.bodyParams, { @@ -34,12 +35,12 @@ RocketChat.API.v1.addRoute('livechat/page.visited', { const obj = RocketChat.Livechat.savePageHistory(token, rid, pageInfo); if (obj) { const page = _.pick(obj, 'msg', 'navigation'); - return RocketChat.API.v1.success({ page }); + return API.v1.success({ page }); } - return RocketChat.API.v1.success(); + return API.v1.success(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/room.js b/packages/rocketchat-livechat/server/api/v1/room.js index 246f9451af11..d21bbc13f6bb 100644 --- a/packages/rocketchat-livechat/server/api/v1/room.js +++ b/packages/rocketchat-livechat/server/api/v1/room.js @@ -3,9 +3,10 @@ import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, findRoom, getRoom, settings } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/room', { +API.v1.addRoute('livechat/room', { get() { try { check(this.queryParams, { @@ -22,14 +23,14 @@ RocketChat.API.v1.addRoute('livechat/room', { const rid = this.queryParams.rid || Random.id(); const room = getRoom(guest, rid); - return RocketChat.API.v1.success(room); + return API.v1.success(room); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.close', { +API.v1.addRoute('livechat/room.close', { post() { try { check(this.bodyParams, { @@ -57,17 +58,17 @@ RocketChat.API.v1.addRoute('livechat/room.close', { const comment = TAPi18n.__('Closed_by_visitor', { lng: language }); if (!RocketChat.Livechat.closeRoom({ visitor, room, comment })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ rid, comment }); + return API.v1.success({ rid, comment }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.transfer', { +API.v1.addRoute('livechat/room.transfer', { post() { try { check(this.bodyParams, { @@ -92,18 +93,18 @@ RocketChat.API.v1.addRoute('livechat/room.transfer', { RocketChat.models.Messages.keepHistoryForToken(token); if (!RocketChat.Livechat.transfer(room, guest, { roomId: rid, departmentId: department })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } room = findRoom(token, rid); - return RocketChat.API.v1.success({ room }); + return API.v1.success({ room }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.survey', { +API.v1.addRoute('livechat/room.survey', { post() { try { check(this.bodyParams, { @@ -144,18 +145,18 @@ RocketChat.API.v1.addRoute('livechat/room.survey', { } if (!RocketChat.models.Rooms.updateSurveyFeedbackById(room._id, updateData)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ rid, data: updateData }); + return API.v1.success({ rid, data: updateData }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.forward', { authRequired: true }, { +API.v1.addRoute('livechat/room.forward', { authRequired: true }, { post() { - RocketChat.API.v1.success(Meteor.runAsUser(this.userId, () => Meteor.call('livechat:transfer', this.bodyParams))); + API.v1.success(Meteor.runAsUser(this.userId, () => Meteor.call('livechat:transfer', this.bodyParams))); }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/transcript.js b/packages/rocketchat-livechat/server/api/v1/transcript.js index 1dcb988c916b..efcf64e48bb0 100644 --- a/packages/rocketchat-livechat/server/api/v1/transcript.js +++ b/packages/rocketchat-livechat/server/api/v1/transcript.js @@ -1,8 +1,9 @@ import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/transcript', { +API.v1.addRoute('livechat/transcript', { post() { try { check(this.bodyParams, { @@ -13,12 +14,12 @@ RocketChat.API.v1.addRoute('livechat/transcript', { const { token, rid, email } = this.bodyParams; if (!RocketChat.Livechat.sendTranscript({ token, rid, email })) { - return RocketChat.API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_transcript') }); + return API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_transcript') }); } - return RocketChat.API.v1.success({ message: TAPi18n.__('Livechat_transcript_sent') }); + return API.v1.success({ message: TAPi18n.__('Livechat_transcript_sent') }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/videoCall.js b/packages/rocketchat-livechat/server/api/v1/videoCall.js index 01d7ce628412..aaa7e0521d3f 100644 --- a/packages/rocketchat-livechat/server/api/v1/videoCall.js +++ b/packages/rocketchat-livechat/server/api/v1/videoCall.js @@ -2,9 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, getRoom, settings } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/video.call/:token', { +API.v1.addRoute('livechat/video.call/:token', { get() { try { check(this.urlParams, { @@ -41,9 +42,9 @@ RocketChat.API.v1.addRoute('livechat/video.call/:token', { timeout: new Date(Date.now() + 3600 * 1000), }; - return RocketChat.API.v1.success({ videoCall }); + return API.v1.success({ videoCall }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/visitor.js b/packages/rocketchat-livechat/server/api/v1/visitor.js index 75dbc02997e3..f5c8a6b2e777 100644 --- a/packages/rocketchat-livechat/server/api/v1/visitor.js +++ b/packages/rocketchat-livechat/server/api/v1/visitor.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; import { findGuest } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/visitor', { +API.v1.addRoute('livechat/visitor', { post() { try { check(this.bodyParams, { @@ -49,20 +50,20 @@ RocketChat.API.v1.addRoute('livechat/visitor', { } const { key, value, overwrite } = field; if (customField.scope === 'visitor' && !LivechatVisitors.updateLivechatDataByToken(token, key, value, overwrite)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } }); } visitor = LivechatVisitors.findOneById(visitorId); - return RocketChat.API.v1.success({ visitor }); + return API.v1.success({ visitor }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/visitor/:token', { +API.v1.addRoute('livechat/visitor/:token', { get() { try { check(this.urlParams, { @@ -70,9 +71,9 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { }); const visitor = LivechatVisitors.getVisitorByToken(this.urlParams.token); - return RocketChat.API.v1.success({ visitor }); + return API.v1.success({ visitor }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { @@ -89,7 +90,7 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { const { _id } = visitor; const result = RocketChat.Livechat.removeGuest(_id); if (result) { - return RocketChat.API.v1.success({ + return API.v1.success({ visitor: { _id, ts: new Date().toISOString(), @@ -97,17 +98,17 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true }, { +API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const rooms = RocketChat.models.Rooms.findOpenByVisitorToken(this.urlParams.token, { @@ -120,11 +121,11 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true servedBy: 1, }, }).fetch(); - return RocketChat.API.v1.success({ rooms }); + return API.v1.success({ rooms }); }, }); -RocketChat.API.v1.addRoute('livechat/visitor.status', { +API.v1.addRoute('livechat/visitor.status', { post() { try { check(this.bodyParams, { @@ -141,9 +142,9 @@ RocketChat.API.v1.addRoute('livechat/visitor.status', { RocketChat.Livechat.notifyGuestStatusChanged(token, status); - return RocketChat.API.v1.success({ token, status }); + return API.v1.success({ token, status }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livestream/package.js b/packages/rocketchat-livestream/package.js index 2b22c85b851b..e99f39beae74 100644 --- a/packages/rocketchat-livestream/package.js +++ b/packages/rocketchat-livestream/package.js @@ -10,6 +10,7 @@ Package.onUse(function(api) { 'ecmascript', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:ui', 'templating', ]); diff --git a/packages/rocketchat-livestream/server/routes.js b/packages/rocketchat-livestream/server/routes.js index 5806dc03174a..92673e2bd370 100644 --- a/packages/rocketchat-livestream/server/routes.js +++ b/packages/rocketchat-livestream/server/routes.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import google from 'googleapis'; const { OAuth2 } = google.auth; -RocketChat.API.v1.addRoute('livestream/oauth', { +API.v1.addRoute('livestream/oauth', { get: function functionName() { const clientAuth = new OAuth2(RocketChat.settings.get('Broadcasting_client_id'), RocketChat.settings.get('Broadcasting_client_secret'), `${ RocketChat.settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api')); const { userId } = this.queryParams; @@ -24,7 +25,7 @@ RocketChat.API.v1.addRoute('livestream/oauth', { }, }); -RocketChat.API.v1.addRoute('livestream/oauth/callback', { +API.v1.addRoute('livestream/oauth/callback', { get: function functionName() { const { code, state } = this.queryParams; diff --git a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js index ec1da72899c6..b8b79807b1cd 100644 --- a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js +++ b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; import { RocketChat } from 'meteor/rocketchat:lib'; import { OAuth2Server } from 'meteor/rocketchat:oauth2-server'; +import { API } from 'meteor/rocketchat:api'; const oauth2server = new OAuth2Server({ accessTokensCollectionName: 'rocketchat_oauth_access_tokens', @@ -55,7 +56,7 @@ Meteor.publish('oauthClient', function(clientId) { }); }); -RocketChat.API.v1.addAuthMethod(function() { +API.v1.addAuthMethod(function() { let headerToken = this.request.headers.authorization; const getToken = this.request.query.access_token; if (headerToken != null) { diff --git a/packages/rocketchat-videobridge/package.js b/packages/rocketchat-videobridge/package.js index a455f5f047ab..7ac995888486 100644 --- a/packages/rocketchat-videobridge/package.js +++ b/packages/rocketchat-videobridge/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'less', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:bigbluebutton', 'templating', ]); diff --git a/packages/rocketchat-videobridge/server/methods/bbb.js b/packages/rocketchat-videobridge/server/methods/bbb.js index a0019961bb93..db8dc32351f6 100644 --- a/packages/rocketchat-videobridge/server/methods/bbb.js +++ b/packages/rocketchat-videobridge/server/methods/bbb.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import BigBlueButtonApi from 'meteor/rocketchat:bigbluebutton'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { HTTP } from 'meteor/http'; import xml2js from 'xml2js'; @@ -121,7 +122,7 @@ Meteor.methods({ }, }); -RocketChat.API.v1.addRoute('videoconference.bbb.update/:id', { authRequired: false }, { +API.v1.addRoute('videoconference.bbb.update/:id', { authRequired: false }, { post() { // TODO check checksum const event = JSON.parse(this.bodyParams.event)[0];