From 801ed018ffbce17f4f7f49dd5b997f4dfcc137e4 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 10:39:43 -0200 Subject: [PATCH 01/11] Move RestAPI client to rc-api package --- packages/rocketchat-api/client/index.js | 1 + .../client/lib/RestApiClient.js | 112 ++++++++++++++++++ packages/rocketchat-api/package.js | 1 + .../client/lib/RestApiClient.js | 112 +----------------- 4 files changed, 116 insertions(+), 110 deletions(-) create mode 100644 packages/rocketchat-api/client/index.js create mode 100644 packages/rocketchat-api/client/lib/RestApiClient.js diff --git a/packages/rocketchat-api/client/index.js b/packages/rocketchat-api/client/index.js new file mode 100644 index 000000000000..7e1df916437f --- /dev/null +++ b/packages/rocketchat-api/client/index.js @@ -0,0 +1 @@ +export { API } from './lib/RestApiClient'; diff --git a/packages/rocketchat-api/client/lib/RestApiClient.js b/packages/rocketchat-api/client/lib/RestApiClient.js new file mode 100644 index 000000000000..107462f2057d --- /dev/null +++ b/packages/rocketchat-api/client/lib/RestApiClient.js @@ -0,0 +1,112 @@ +export const API = { + delete(endpoint, params) { + return API._jqueryCall('DELETE', endpoint, params); + }, + + get(endpoint, params) { + return API._jqueryCall('GET', endpoint, params); + }, + + post(endpoint, params, body) { + if (!body) { + body = params; + params = {}; + } + + return API._jqueryCall('POST', endpoint, params, body); + }, + + upload(endpoint, params, formData) { + if (!formData) { + formData = params; + params = {}; + } + + return API._jqueryFormDataCall(endpoint, params, formData); + }, + + _generateQueryFromParams(params) { + let query = ''; + if (params && typeof params === 'object') { + Object.keys(params).forEach((key) => { + query += query === '' ? '?' : '&'; + + query += `${ key }=${ params[key] }`; + }); + } + + return query; + }, + + _jqueryCall(method, endpoint, params, body) { + const query = API._generateQueryFromParams(params); + + return new Promise(function _rlRestApiGet(resolve, reject) { + jQuery.ajax({ + method, + url: `${ document.baseURI }api/${ endpoint }${ query }`, + headers: { + 'Content-Type': 'application/json', + 'X-User-Id': localStorage['Meteor.userId'], + 'X-Auth-Token': localStorage['Meteor.loginToken'], + }, + data: JSON.stringify(body), + success: function _rlGetSuccess(result) { + resolve(result); + }, + error: function _rlGetFailure(xhr, status, errorThrown) { + const error = new Error(errorThrown); + error.xhr = xhr; + reject(error); + }, + }); + }); + }, + + _jqueryFormDataCall(endpoint, params, formData) { + const query = API._generateQueryFromParams(params); + + if (!(formData instanceof FormData)) { + throw new Error('The formData parameter MUST be an instance of the FormData class.'); + } + + return new Promise(function _jqueryFormDataPromise(resolve, reject) { + jQuery.ajax({ + url: `${ document.baseURI }api/${ endpoint }${ query }`, + headers: { + 'X-User-Id': localStorage['Meteor.userId'], + 'X-Auth-Token': localStorage['Meteor.loginToken'], + }, + data: formData, + processData: false, + contentType: false, + type: 'POST', + success: function _jqueryFormDataSuccess(result) { + resolve(result); + }, + error: function _jqueryFormDataError(xhr, status, errorThrown) { + reject(new Error(errorThrown)); + }, + }); + }); + }, + + v1: { + delete(endpoint, params) { + return API.delete(`v1/${ endpoint }`, params); + }, + + get(endpoint, params) { + return API.get(`v1/${ endpoint }`, params); + }, + + post(endpoint, params, body) { + return API.post(`v1/${ endpoint }`, params, body); + }, + + upload(endpoint, params, formData) { + return API.upload(`v1/${ endpoint }`, params, formData); + }, + }, +}; +RocketChat.API = API; diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index 1384ef6670d6..3844ff0909bb 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -16,5 +16,6 @@ Package.onUse(function(api) { 'rocketchat:file-upload', ]); + api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-lib/client/lib/RestApiClient.js b/packages/rocketchat-lib/client/lib/RestApiClient.js index 7226be0360d1..9c2d7a9b86e9 100644 --- a/packages/rocketchat-lib/client/lib/RestApiClient.js +++ b/packages/rocketchat-lib/client/lib/RestApiClient.js @@ -1,111 +1,3 @@ -RocketChat.API = { - delete(endpoint, params) { - return RocketChat.API._jqueryCall('DELETE', endpoint, params); - }, +// import { API } from 'meteor/rocketchat:api'; - get(endpoint, params) { - return RocketChat.API._jqueryCall('GET', endpoint, params); - }, - - post(endpoint, params, body) { - if (!body) { - body = params; - params = {}; - } - - return RocketChat.API._jqueryCall('POST', endpoint, params, body); - }, - - upload(endpoint, params, formData) { - if (!formData) { - formData = params; - params = {}; - } - - return RocketChat.API._jqueryFormDataCall(endpoint, params, formData); - }, - - _generateQueryFromParams(params) { - let query = ''; - if (params && typeof params === 'object') { - Object.keys(params).forEach((key) => { - query += query === '' ? '?' : '&'; - - query += `${ key }=${ params[key] }`; - }); - } - - return query; - }, - - _jqueryCall(method, endpoint, params, body) { - const query = RocketChat.API._generateQueryFromParams(params); - - return new Promise(function _rlRestApiGet(resolve, reject) { - jQuery.ajax({ - method, - url: `${ document.baseURI }api/${ endpoint }${ query }`, - headers: { - 'Content-Type': 'application/json', - 'X-User-Id': localStorage['Meteor.userId'], - 'X-Auth-Token': localStorage['Meteor.loginToken'], - }, - data: JSON.stringify(body), - success: function _rlGetSuccess(result) { - resolve(result); - }, - error: function _rlGetFailure(xhr, status, errorThrown) { - const error = new Error(errorThrown); - error.xhr = xhr; - reject(error); - }, - }); - }); - }, - - _jqueryFormDataCall(endpoint, params, formData) { - const query = RocketChat.API._generateQueryFromParams(params); - - if (!(formData instanceof FormData)) { - throw new Error('The formData parameter MUST be an instance of the FormData class.'); - } - - return new Promise(function _jqueryFormDataPromise(resolve, reject) { - jQuery.ajax({ - url: `${ document.baseURI }api/${ endpoint }${ query }`, - headers: { - 'X-User-Id': localStorage['Meteor.userId'], - 'X-Auth-Token': localStorage['Meteor.loginToken'], - }, - data: formData, - processData: false, - contentType: false, - type: 'POST', - success: function _jqueryFormDataSuccess(result) { - resolve(result); - }, - error: function _jqueryFormDataError(xhr, status, errorThrown) { - reject(new Error(errorThrown)); - }, - }); - }); - }, - - v1: { - delete(endpoint, params) { - return RocketChat.API.delete(`v1/${ endpoint }`, params); - }, - - get(endpoint, params) { - return RocketChat.API.get(`v1/${ endpoint }`, params); - }, - - post(endpoint, params, body) { - return RocketChat.API.post(`v1/${ endpoint }`, params, body); - }, - - upload(endpoint, params, formData) { - return RocketChat.API.upload(`v1/${ endpoint }`, params, formData); - }, - }, -}; +// RocketChat.API = API; From 1238c2c8835195cb8675871c47ffa390c7799519 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 10:40:31 -0200 Subject: [PATCH 02/11] Remove dependency of RC namespace in rc-api/helpers and api.js --- packages/rocketchat-api/package.js | 4 ++ packages/rocketchat-api/server/api.js | 57 +++++++++++-------- .../rocketchat-api/server/default/info.js | 16 +++--- .../helpers/composeRoomWithLastMessage.js | 7 ++- .../server/helpers/deprecationWarning.js | 4 +- .../server/helpers/getLoggedInUser.js | 7 ++- .../server/helpers/getPaginationItems.js | 11 ++-- .../server/helpers/getUserFromParams.js | 11 ++-- .../server/helpers/getUserInfo.js | 10 ++-- .../server/helpers/insertUserObject.js | 7 ++- .../server/helpers/isUserFromParams.js | 4 +- .../server/helpers/parseJsonQuery.js | 29 +++++----- .../server/helpers/requestParams.js | 4 +- packages/rocketchat-api/server/settings.js | 4 +- 14 files changed, 98 insertions(+), 77 deletions(-) diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index 3844ff0909bb..969cca9a542c 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -12,6 +12,10 @@ Package.onUse(function(api) { 'rate-limit', 'rocketchat:lib', 'rocketchat:models', + 'rocketchat:settings', + '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 e32407d689c3..a4ee71d3b9a6 100644 --- a/packages/rocketchat-api/server/api.js +++ b/packages/rocketchat-api/server/api.js @@ -5,17 +5,22 @@ 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'; +import { metrics } from 'meteor/rocketchat:metrics'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import { RateLimiter } from 'meteor/rate-limit'; import _ from 'underscore'; const logger = new Logger('API', {}); const rateLimiterDictionary = {}; const defaultRateLimiterOptions = { - numRequestsAllowed: RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default'), - intervalTimeInMS: RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'), + numRequestsAllowed: settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default'), + intervalTimeInMS: settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'), }; -class API extends Restivus { +export let API = {}; + +class APIClass extends Restivus { constructor(properties) { super(properties); this.authMethods = []; @@ -48,15 +53,15 @@ class API extends Restivus { } hasHelperMethods() { - return RocketChat.API.helperMethods.size !== 0; + return API.helperMethods.size !== 0; } getHelperMethods() { - return RocketChat.API.helperMethods; + return API.helperMethods; } getHelperMethod(name) { - return RocketChat.API.helperMethods.get(name); + return API.helperMethods.get(name); } addAuthMethod(method) { @@ -182,7 +187,7 @@ class API extends Restivus { // Add a try/catch for each endpoint const originalAction = endpoints[method].action; endpoints[method].action = function _internalRouteActionHandler() { - const rocketchatRestApiEnd = RocketChat.metrics.rocketchatRestApi.startTimer({ + const rocketchatRestApiEnd = metrics.rocketchatRestApi.startTimer({ method, version, user_agent: this.request.headers['user-agent'], @@ -198,8 +203,8 @@ class API extends Restivus { let result; try { const shouldVerifyRateLimit = rateLimiterDictionary.hasOwnProperty(objectForRateLimitMatch.route) - && (!this.userId || !RocketChat.authz.hasPermission(this.userId, 'api-bypass-rate-limit')) - && ((process.env.NODE_ENV === 'development' && RocketChat.settings.get('API_Enable_Rate_Limiter_Dev') === true) || process.env.NODE_ENV !== 'development'); + && (!this.userId || !hasPermission(this.userId, 'api-bypass-rate-limit')) + && ((process.env.NODE_ENV === 'development' && settings.get('API_Enable_Rate_Limiter_Dev') === true) || process.env.NODE_ENV !== 'development'); if (shouldVerifyRateLimit) { rateLimiterDictionary[objectForRateLimitMatch.route].rateLimiter.increment(objectForRateLimitMatch); const attemptResult = rateLimiterDictionary[objectForRateLimitMatch.route].rateLimiter.check(objectForRateLimitMatch); @@ -217,9 +222,9 @@ class API extends Restivus { result = originalAction.apply(this); } catch (e) { logger.debug(`${ method } ${ route } threw an error:`, e.stack); - result = RocketChat.API.v1.failure(e.message, e.error); + result = API.v1.failure(e.message, e.error); } - result = result || RocketChat.API.v1.success(); + result = result || API.v1.success(); rocketchatRestApiEnd({ status: result.statusCode, @@ -413,8 +418,8 @@ const getUserAuth = function _getUserAuth(...args) { this.bodyParams = JSON.parse(this.bodyParams.payload); } - for (let i = 0; i < RocketChat.API.v1.authMethods.length; i++) { - const method = RocketChat.API.v1.authMethods[i]; + for (let i = 0; i < API.v1.authMethods.length; i++) { + const method = API.v1.authMethods[i]; if (typeof method === 'function') { const result = method.apply(this, args); @@ -437,17 +442,19 @@ const getUserAuth = function _getUserAuth(...args) { }; }; -RocketChat.API = { +API = { helperMethods: new Map(), getUserAuth, - ApiClass: API, + ApiClass: APIClass, }; +RocketChat.API = API; + const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { if (this.request.method === 'OPTIONS' && this.request.headers['access-control-request-method']) { - if (RocketChat.settings.get('API_Enable_CORS') === true) { + if (settings.get('API_Enable_CORS') === true) { this.response.writeHead(200, { - 'Access-Control-Allow-Origin': RocketChat.settings.get('API_CORS_Origin'), + 'Access-Control-Allow-Origin': settings.get('API_CORS_Origin'), 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, HEAD, PATCH', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-User-Id, X-Auth-Token, x-visitor-token', }); @@ -462,8 +469,8 @@ const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { }; const createApi = function _createApi(enableCors) { - if (!RocketChat.API.v1 || RocketChat.API.v1._config.enableCors !== enableCors) { - RocketChat.API.v1 = new API({ + if (!API.v1 || API.v1._config.enableCors !== enableCors) { + API.v1 = new APIClass({ version: 'v1', useDefaultAuth: true, prettyJson: process.env.NODE_ENV === 'development', @@ -473,8 +480,8 @@ const createApi = function _createApi(enableCors) { }); } - if (!RocketChat.API.default || RocketChat.API.default._config.enableCors !== enableCors) { - RocketChat.API.default = new API({ + if (!API.default || API.default._config.enableCors !== enableCors) { + API.default = new APIClass({ useDefaultAuth: true, prettyJson: process.env.NODE_ENV === 'development', enableCors, @@ -485,19 +492,19 @@ const createApi = function _createApi(enableCors) { }; // register the API to be re-created once the CORS-setting changes. -RocketChat.settings.get('API_Enable_CORS', (key, value) => { +settings.get('API_Enable_CORS', (key, value) => { createApi(value); }); -RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Time_Default', (key, value) => { +settings.get('API_Enable_Rate_Limiter_Limit_Time_Default', (key, value) => { defaultRateLimiterOptions.intervalTimeInMS = value; createApi(value); }); -RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default', (key, value) => { +settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default', (key, value) => { defaultRateLimiterOptions.numRequestsAllowed = value; createApi(value); }); // also create the API immediately -createApi(!!RocketChat.settings.get('API_Enable_CORS')); +createApi(!!settings.get('API_Enable_CORS')); diff --git a/packages/rocketchat-api/server/default/info.js b/packages/rocketchat-api/server/default/info.js index 97b372dd42ad..f4bbcad21ec8 100644 --- a/packages/rocketchat-api/server/default/info.js +++ b/packages/rocketchat-api/server/default/info.js @@ -1,17 +1,19 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { Info } from 'meteor/rocketchat:utils'; +import { API } from '../api'; -RocketChat.API.default.addRoute('info', { authRequired: false }, { +API.default.addRoute('info', { authRequired: false }, { get() { const user = this.getLoggedInUser(); - if (user && RocketChat.authz.hasRole(user._id, 'admin')) { - return RocketChat.API.v1.success({ - info: RocketChat.Info, + if (user && hasRole(user._id, 'admin')) { + return API.v1.success({ + info: Info, }); } - return RocketChat.API.v1.success({ - version: RocketChat.Info.version, + return API.v1.success({ + version: Info.version, }); }, }); diff --git a/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js b/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js index f9a8e3a702c8..4c833d898709 100644 --- a/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js +++ b/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js @@ -1,8 +1,9 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('composeRoomWithLastMessage', function _composeRoomWithLastMessage(room, userId) { +API.helperMethods.set('composeRoomWithLastMessage', function _composeRoomWithLastMessage(room, userId) { if (room.lastMessage) { - room.lastMessage = RocketChat.composeMessageObjectWithUser(room.lastMessage, userId); + room.lastMessage = composeMessageObjectWithUser(room.lastMessage, userId); } return room; }); diff --git a/packages/rocketchat-api/server/helpers/deprecationWarning.js b/packages/rocketchat-api/server/helpers/deprecationWarning.js index ad2cb11a5131..06dc47c3f096 100644 --- a/packages/rocketchat-api/server/helpers/deprecationWarning.js +++ b/packages/rocketchat-api/server/helpers/deprecationWarning.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { +API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { const warningMessage = `The endpoint "${ endpoint }" is deprecated and will be removed after version ${ versionWillBeRemove }`; console.warn(warningMessage); if (process.env.NODE_ENV === 'development') { diff --git a/packages/rocketchat-api/server/helpers/getLoggedInUser.js b/packages/rocketchat-api/server/helpers/getLoggedInUser.js index 1ff50826b928..9406ff576f1f 100644 --- a/packages/rocketchat-api/server/helpers/getLoggedInUser.js +++ b/packages/rocketchat-api/server/helpers/getLoggedInUser.js @@ -1,11 +1,12 @@ import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('getLoggedInUser', function _getLoggedInUser() { +API.helperMethods.set('getLoggedInUser', function _getLoggedInUser() { let user; if (this.request.headers['x-auth-token'] && this.request.headers['x-user-id']) { - user = RocketChat.models.Users.findOne({ + user = Users.findOne({ _id: this.request.headers['x-user-id'], 'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(this.request.headers['x-auth-token']), }); diff --git a/packages/rocketchat-api/server/helpers/getPaginationItems.js b/packages/rocketchat-api/server/helpers/getPaginationItems.js index f7d3cff75d1e..0060155d0f0c 100644 --- a/packages/rocketchat-api/server/helpers/getPaginationItems.js +++ b/packages/rocketchat-api/server/helpers/getPaginationItems.js @@ -1,11 +1,12 @@ // If the count query param is higher than the "API_Upper_Count_Limit" setting, then we limit that // If the count query param isn't defined, then we set it to the "API_Default_Count" setting // If the count is zero, then that means unlimited and is only allowed if the setting "API_Allow_Infinite_Count" is true -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('getPaginationItems', function _getPaginationItems() { - const hardUpperLimit = RocketChat.settings.get('API_Upper_Count_Limit') <= 0 ? 100 : RocketChat.settings.get('API_Upper_Count_Limit'); - const defaultCount = RocketChat.settings.get('API_Default_Count') <= 0 ? 50 : RocketChat.settings.get('API_Default_Count'); +API.helperMethods.set('getPaginationItems', function _getPaginationItems() { + const hardUpperLimit = settings.get('API_Upper_Count_Limit') <= 0 ? 100 : settings.get('API_Upper_Count_Limit'); + const defaultCount = settings.get('API_Default_Count') <= 0 ? 50 : settings.get('API_Default_Count'); const offset = this.queryParams.offset ? parseInt(this.queryParams.offset) : 0; let count = defaultCount; @@ -20,7 +21,7 @@ RocketChat.API.helperMethods.set('getPaginationItems', function _getPaginationIt count = hardUpperLimit; } - if (count === 0 && !RocketChat.settings.get('API_Allow_Infinite_Count')) { + if (count === 0 && !settings.get('API_Allow_Infinite_Count')) { count = defaultCount; } diff --git a/packages/rocketchat-api/server/helpers/getUserFromParams.js b/packages/rocketchat-api/server/helpers/getUserFromParams.js index 54b884de6059..e9f49ca7cc61 100644 --- a/packages/rocketchat-api/server/helpers/getUserFromParams.js +++ b/packages/rocketchat-api/server/helpers/getUserFromParams.js @@ -1,18 +1,19 @@ // Convenience method, almost need to turn it into a middleware of sorts import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('getUserFromParams', function _getUserFromParams() { +API.helperMethods.set('getUserFromParams', function _getUserFromParams() { const doesntExist = { _doesntExist: true }; let user; const params = this.requestParams(); if (params.userId && params.userId.trim()) { - user = RocketChat.models.Users.findOneById(params.userId) || doesntExist; + user = Users.findOneById(params.userId) || doesntExist; } else if (params.username && params.username.trim()) { - user = RocketChat.models.Users.findOneByUsername(params.username) || doesntExist; + user = Users.findOneByUsername(params.username) || doesntExist; } else if (params.user && params.user.trim()) { - user = RocketChat.models.Users.findOneByUsername(params.user) || doesntExist; + user = Users.findOneByUsername(params.user) || doesntExist; } else { throw new Meteor.Error('error-user-param-not-provided', 'The required "userId" or "username" param was not provided'); } diff --git a/packages/rocketchat-api/server/helpers/getUserInfo.js b/packages/rocketchat-api/server/helpers/getUserInfo.js index c573a336ddd1..f7a76b35c14e 100644 --- a/packages/rocketchat-api/server/helpers/getUserInfo.js +++ b/packages/rocketchat-api/server/helpers/getUserInfo.js @@ -1,4 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { API } from '../api'; const getInfoFromUserObject = (user) => { const { @@ -32,7 +34,7 @@ const getInfoFromUserObject = (user) => { }; -RocketChat.API.helperMethods.set('getUserInfo', function _getUserInfo(user) { +API.helperMethods.set('getUserInfo', function _getUserInfo(user) { const me = getInfoFromUserObject(user); const isVerifiedEmail = () => { if (me && me.emails && Array.isArray(me.emails)) { @@ -42,11 +44,11 @@ RocketChat.API.helperMethods.set('getUserInfo', function _getUserInfo(user) { }; const getUserPreferences = () => { const defaultUserSettingPrefix = 'Accounts_Default_User_Preferences_'; - const allDefaultUserSettings = RocketChat.settings.get(new RegExp(`^${ defaultUserSettingPrefix }.*$`)); + const allDefaultUserSettings = settings.get(new RegExp(`^${ defaultUserSettingPrefix }.*$`)); return allDefaultUserSettings.reduce((accumulator, setting) => { const settingWithoutPrefix = setting.key.replace(defaultUserSettingPrefix, ' ').trim(); - accumulator[settingWithoutPrefix] = RocketChat.getUserPreference(user, settingWithoutPrefix); + accumulator[settingWithoutPrefix] = getUserPreference(user, settingWithoutPrefix); return accumulator; }, {}); }; diff --git a/packages/rocketchat-api/server/helpers/insertUserObject.js b/packages/rocketchat-api/server/helpers/insertUserObject.js index dfa6322099b9..9883f8f830fa 100644 --- a/packages/rocketchat-api/server/helpers/insertUserObject.js +++ b/packages/rocketchat-api/server/helpers/insertUserObject.js @@ -1,7 +1,8 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('insertUserObject', function _addUserToObject({ object, userId }) { - const user = RocketChat.models.Users.findOneById(userId); +API.helperMethods.set('insertUserObject', function _addUserToObject({ object, userId }) { + const user = Users.findOneById(userId); object.user = { }; if (user) { object.user = { diff --git a/packages/rocketchat-api/server/helpers/isUserFromParams.js b/packages/rocketchat-api/server/helpers/isUserFromParams.js index 79f3b90f3aef..a96779c2eedc 100644 --- a/packages/rocketchat-api/server/helpers/isUserFromParams.js +++ b/packages/rocketchat-api/server/helpers/isUserFromParams.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('isUserFromParams', function _isUserFromParams() { +API.helperMethods.set('isUserFromParams', function _isUserFromParams() { const params = this.requestParams(); return (!params.userId && !params.username && !params.user) || diff --git a/packages/rocketchat-api/server/helpers/parseJsonQuery.js b/packages/rocketchat-api/server/helpers/parseJsonQuery.js index 6b9caf541987..60bf964c3e22 100644 --- a/packages/rocketchat-api/server/helpers/parseJsonQuery.js +++ b/packages/rocketchat-api/server/helpers/parseJsonQuery.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import { EJSON } from 'meteor/ejson'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { +API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { let sort; if (this.queryParams.sort) { try { @@ -25,26 +26,26 @@ RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { // Verify the user's selected fields only contains ones which their role allows if (typeof fields === 'object') { - let nonSelectableFields = Object.keys(RocketChat.API.v1.defaultFieldsToExclude); + let nonSelectableFields = Object.keys(API.v1.defaultFieldsToExclude); if (this.request.route.includes('/v1/users.')) { - const getFields = () => Object.keys(RocketChat.authz.hasPermission(this.userId, 'view-full-other-user-info') ? RocketChat.API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser : RocketChat.API.v1.limitedUserFieldsToExclude); + const getFields = () => Object.keys(hasPermission(this.userId, 'view-full-other-user-info') ? API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser : API.v1.limitedUserFieldsToExclude); nonSelectableFields = nonSelectableFields.concat(getFields()); } Object.keys(fields).forEach((k) => { - if (nonSelectableFields.includes(k) || nonSelectableFields.includes(k.split(RocketChat.API.v1.fieldSeparator)[0])) { + if (nonSelectableFields.includes(k) || nonSelectableFields.includes(k.split(API.v1.fieldSeparator)[0])) { delete fields[k]; } }); } // Limit the fields by default - fields = Object.assign({}, fields, RocketChat.API.v1.defaultFieldsToExclude); + fields = Object.assign({}, fields, API.v1.defaultFieldsToExclude); if (this.request.route.includes('/v1/users.')) { - if (RocketChat.authz.hasPermission(this.userId, 'view-full-other-user-info')) { - fields = Object.assign(fields, RocketChat.API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser); + if (hasPermission(this.userId, 'view-full-other-user-info')) { + fields = Object.assign(fields, API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser); } else { - fields = Object.assign(fields, RocketChat.API.v1.limitedUserFieldsToExclude); + fields = Object.assign(fields, API.v1.limitedUserFieldsToExclude); } } @@ -60,17 +61,17 @@ RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { // Verify the user has permission to query the fields they are if (typeof query === 'object') { - let nonQueryableFields = Object.keys(RocketChat.API.v1.defaultFieldsToExclude); + let nonQueryableFields = Object.keys(API.v1.defaultFieldsToExclude); if (this.request.route.includes('/v1/users.')) { - if (RocketChat.authz.hasPermission(this.userId, 'view-full-other-user-info')) { - nonQueryableFields = nonQueryableFields.concat(Object.keys(RocketChat.API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser)); + if (hasPermission(this.userId, 'view-full-other-user-info')) { + nonQueryableFields = nonQueryableFields.concat(Object.keys(API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser)); } else { - nonQueryableFields = nonQueryableFields.concat(Object.keys(RocketChat.API.v1.limitedUserFieldsToExclude)); + nonQueryableFields = nonQueryableFields.concat(Object.keys(API.v1.limitedUserFieldsToExclude)); } } Object.keys(query).forEach((k) => { - if (nonQueryableFields.includes(k) || nonQueryableFields.includes(k.split(RocketChat.API.v1.fieldSeparator)[0])) { + if (nonQueryableFields.includes(k) || nonQueryableFields.includes(k.split(API.v1.fieldSeparator)[0])) { delete query[k]; } }); diff --git a/packages/rocketchat-api/server/helpers/requestParams.js b/packages/rocketchat-api/server/helpers/requestParams.js index fe70278dd463..2883c94a727e 100644 --- a/packages/rocketchat-api/server/helpers/requestParams.js +++ b/packages/rocketchat-api/server/helpers/requestParams.js @@ -1,5 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('requestParams', function _requestParams() { +API.helperMethods.set('requestParams', function _requestParams() { return ['POST', 'PUT'].includes(this.request.method) ? this.bodyParams : this.queryParams; }); diff --git a/packages/rocketchat-api/server/settings.js b/packages/rocketchat-api/server/settings.js index 6e17f1c91e05..5b2d3badb9e0 100644 --- a/packages/rocketchat-api/server/settings.js +++ b/packages/rocketchat-api/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.section('REST API', function() { this.add('API_Upper_Count_Limit', 100, { type: 'int', public: false }); this.add('API_Default_Count', 50, { type: 'int', public: false }); From dc8f61511f43311ae3ca90cccb387fc3ac084cb8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 12:58:51 -0200 Subject: [PATCH 03/11] Remove dependency of RC namespace on half of api files --- packages/rocketchat-api/package.js | 1 + packages/rocketchat-api/server/v1/assets.js | 15 +- packages/rocketchat-api/server/v1/channels.js | 293 +++++++++--------- packages/rocketchat-api/server/v1/chat.js | 129 ++++---- packages/rocketchat-api/server/v1/commands.js | 68 ++-- packages/rocketchat-api/server/v1/e2e.js | 28 +- .../rocketchat-api/server/v1/emoji-custom.js | 19 +- packages/rocketchat-api/server/v1/groups.js | 267 ++++++++-------- packages/rocketchat-api/server/v1/im.js | 103 +++--- packages/rocketchat-api/server/v1/import.js | 22 +- .../rocketchat-api/server/v1/integrations.js | 56 ++-- 11 files changed, 511 insertions(+), 490 deletions(-) diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index 969cca9a542c..a6664d10b8f1 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -13,6 +13,7 @@ Package.onUse(function(api) { 'rocketchat:lib', 'rocketchat:models', 'rocketchat:settings', + 'rocketchat:assets', 'rocketchat:utils', 'rocketchat:metrics', 'rocketchat:authorization', diff --git a/packages/rocketchat-api/server/v1/assets.js b/packages/rocketchat-api/server/v1/assets.js index 774ee3c8d58f..c69b619b27fe 100644 --- a/packages/rocketchat-api/server/v1/assets.js +++ b/packages/rocketchat-api/server/v1/assets.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; +import { RocketChatAssets } from 'meteor/rocketchat:assets'; import Busboy from 'busboy'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('assets.setAsset', { authRequired: true }, { +API.v1.addRoute('assets.setAsset', { authRequired: true }, { post() { const busboy = new Busboy({ headers: this.request.headers }); const fields = {}; @@ -11,7 +12,7 @@ RocketChat.API.v1.addRoute('assets.setAsset', { authRequired: true }, { Meteor.wrapAsync((callback) => { busboy.on('field', (fieldname, value) => fields[fieldname] = value); busboy.on('file', Meteor.bindEnvironment((fieldname, file, filename, encoding, mimetype) => { - const isValidAsset = Object.keys(RocketChat.Assets.assets).includes(fieldname); + const isValidAsset = Object.keys(RocketChatAssets.assets).includes(fieldname); if (!isValidAsset) { callback(new Meteor.Error('error-invalid-asset', 'Invalid asset')); } @@ -35,14 +36,14 @@ RocketChat.API.v1.addRoute('assets.setAsset', { authRequired: true }, { if (fields.refreshAllClients) { Meteor.runAsUser(this.userId, () => Meteor.call('refreshClients')); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('assets.unsetAsset', { authRequired: true }, { +API.v1.addRoute('assets.unsetAsset', { authRequired: true }, { post() { const { assetName, refreshAllClients } = this.bodyParams; - const isValidAsset = Object.keys(RocketChat.Assets.assets).includes(assetName); + const isValidAsset = Object.keys(RocketChatAssets.assets).includes(assetName); if (!isValidAsset) { throw new Meteor.Error('error-invalid-asset', 'Invalid asset'); } @@ -50,6 +51,6 @@ RocketChat.API.v1.addRoute('assets.unsetAsset', { authRequired: true }, { if (refreshAllClients) { Meteor.runAsUser(this.userId, () => Meteor.call('refreshClients')); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/channels.js b/packages/rocketchat-api/server/v1/channels.js index 6332e0ef840e..4fc61f4c6780 100644 --- a/packages/rocketchat-api/server/v1/channels.js +++ b/packages/rocketchat-api/server/v1/channels.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions, Messages, Uploads, Integrations, Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; import _ from 'underscore'; // Returns the channel IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property @@ -8,13 +11,13 @@ function findChannelByIdOrName({ params, checkedArchived = true, userId }) { throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" or "roomName" is required'); } - const fields = { ...RocketChat.API.v1.defaultFieldsToExclude }; + const fields = { ...API.v1.defaultFieldsToExclude }; let room; if (params.roomId) { - room = RocketChat.models.Rooms.findOneById(params.roomId, { fields }); + room = Rooms.findOneById(params.roomId, { fields }); } else if (params.roomName) { - room = RocketChat.models.Rooms.findOneByName(params.roomName, { fields }); + room = Rooms.findOneByName(params.roomName, { fields }); } if (!room || room.t !== 'c') { @@ -25,13 +28,13 @@ function findChannelByIdOrName({ params, checkedArchived = true, userId }) { throw new Meteor.Error('error-room-archived', `The channel, ${ room.name }, is archived`); } if (userId && room.lastMessage) { - room.lastMessage = RocketChat.composeMessageObjectWithUser(room.lastMessage, userId); + room.lastMessage = composeMessageObjectWithUser(room.lastMessage, userId); } return room; } -RocketChat.API.v1.addRoute('channels.addAll', { authRequired: true }, { +API.v1.addRoute('channels.addAll', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -39,13 +42,13 @@ RocketChat.API.v1.addRoute('channels.addAll', { authRequired: true }, { Meteor.call('addAllUserToRoom', findResult._id, this.bodyParams.activeUsersOnly); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.addModerator', { authRequired: true }, { +API.v1.addRoute('channels.addModerator', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -55,11 +58,11 @@ RocketChat.API.v1.addRoute('channels.addModerator', { authRequired: true }, { Meteor.call('addRoomModerator', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.addOwner', { authRequired: true }, { +API.v1.addRoute('channels.addOwner', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -69,11 +72,11 @@ RocketChat.API.v1.addRoute('channels.addOwner', { authRequired: true }, { Meteor.call('addRoomOwner', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.archive', { authRequired: true }, { +API.v1.addRoute('channels.archive', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -81,35 +84,35 @@ RocketChat.API.v1.addRoute('channels.archive', { authRequired: true }, { Meteor.call('archiveRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.close', { authRequired: true }, { +API.v1.addRoute('channels.close', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); + const sub = Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); if (!sub) { - return RocketChat.API.v1.failure(`The user/callee is not in the channel "${ findResult.name }.`); + return API.v1.failure(`The user/callee is not in the channel "${ findResult.name }.`); } if (!sub.open) { - return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is already closed to the sender`); + return API.v1.failure(`The channel, ${ findResult.name }, is already closed to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('hideRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { +API.v1.addRoute('channels.counters', { authRequired: true }, { get() { - const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration'); + const access = hasPermission(this.userId, 'view-room-administration'); const { userId } = this.requestParams(); let user = this.userId; let unreads = null; @@ -122,7 +125,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { if (userId) { if (!access) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } user = userId; } @@ -130,11 +133,11 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { params: this.requestParams(), returnUsernames: true, }); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user); const lm = room.lm ? room.lm : room._updatedAt; if (typeof subscription !== 'undefined' && subscription.open) { - unreads = RocketChat.models.Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, subscription.ls, lm); + unreads = Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, subscription.ls, lm); unreadsFrom = subscription.ls || subscription.ts; userMentions = subscription.userMentions; joined = true; @@ -146,7 +149,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { members = room.usersCount; } - return RocketChat.API.v1.success({ + return API.v1.success({ joined, members, unreads, @@ -161,7 +164,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { // Channel -> create function createChannelValidator(params) { - if (!RocketChat.authz.hasPermission(params.user.value, 'create-c')) { + if (!hasPermission(params.user.value, 'create-c')) { throw new Error('unauthorized'); } @@ -187,20 +190,20 @@ function createChannel(userId, params) { }; } -RocketChat.API.channels = {}; -RocketChat.API.channels.create = { +API.channels = {}; +API.channels.create = { validate: createChannelValidator, execute: createChannel, }; -RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, { +API.v1.addRoute('channels.create', { authRequired: true }, { post() { const { userId, bodyParams } = this; let error; try { - RocketChat.API.channels.create.validate({ + API.channels.create.validate({ user: { value: userId, }, @@ -215,9 +218,9 @@ RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, { }); } catch (e) { if (e.message === 'unauthorized') { - error = RocketChat.API.v1.unauthorized(); + error = API.v1.unauthorized(); } else { - error = RocketChat.API.v1.failure(e.message); + error = API.v1.failure(e.message); } } @@ -225,11 +228,11 @@ RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, { return error; } - return RocketChat.API.v1.success(RocketChat.API.channels.create.execute(userId, bodyParams)); + return API.v1.success(API.channels.create.execute(userId, bodyParams)); }, }); -RocketChat.API.v1.addRoute('channels.delete', { authRequired: true }, { +API.v1.addRoute('channels.delete', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); @@ -237,11 +240,11 @@ RocketChat.API.v1.addRoute('channels.delete', { authRequired: true }, { Meteor.call('eraseRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, { +API.v1.addRoute('channels.files', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); const addUserObjectToEveryObject = (file) => { @@ -260,27 +263,27 @@ RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult._id }); - const files = RocketChat.models.Uploads.find(ourQuery, { + const files = Uploads.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ files: files.map(addUserObjectToEveryObject), count: files.length, offset, - total: RocketChat.models.Uploads.find(ourQuery).count(), + total: Uploads.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, { +API.v1.addRoute('channels.getIntegrations', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); @@ -305,23 +308,23 @@ RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, { ourQuery = Object.assign({}, query, ourQuery); - const integrations = RocketChat.models.Integrations.find(ourQuery, { + const integrations = Integrations.find(ourQuery, { sort: sort ? sort : { _createdAt: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ integrations, count: integrations.length, offset, - total: RocketChat.models.Integrations.find(ourQuery).count(), + total: Integrations.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, { +API.v1.addRoute('channels.history', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); @@ -357,16 +360,16 @@ RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, { }); if (!result) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('channels.info', { authRequired: true }, { +API.v1.addRoute('channels.info', { authRequired: true }, { get() { - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false, @@ -376,7 +379,7 @@ RocketChat.API.v1.addRoute('channels.info', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.invite', { authRequired: true }, { +API.v1.addRoute('channels.invite', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -386,13 +389,13 @@ RocketChat.API.v1.addRoute('channels.invite', { authRequired: true }, { Meteor.call('addUserToRoom', { rid: findResult._id, username: user.username }); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.join', { authRequired: true }, { +API.v1.addRoute('channels.join', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -400,13 +403,13 @@ RocketChat.API.v1.addRoute('channels.join', { authRequired: true }, { Meteor.call('joinRoom', findResult._id, this.bodyParams.joinCode); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.kick', { authRequired: true }, { +API.v1.addRoute('channels.kick', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -416,13 +419,13 @@ RocketChat.API.v1.addRoute('channels.kick', { authRequired: true }, { Meteor.call('removeUserFromRoom', { rid: findResult._id, username: user.username }); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.leave', { authRequired: true }, { +API.v1.addRoute('channels.leave', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -430,31 +433,31 @@ RocketChat.API.v1.addRoute('channels.leave', { authRequired: true }, { Meteor.call('leaveRoom', findResult._id); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, { +API.v1.addRoute('channels.list', { authRequired: true }, { get: { // This is defined as such only to provide an example of how the routes can be defined :X action() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - const hasPermissionToSeeAllPublicChannels = RocketChat.authz.hasPermission(this.userId, 'view-c-room'); + const hasPermissionToSeeAllPublicChannels = hasPermission(this.userId, 'view-c-room'); const ourQuery = { ...query, t: 'c' }; if (!hasPermissionToSeeAllPublicChannels) { - if (!RocketChat.authz.hasPermission(this.userId, 'view-joined-room')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-joined-room')) { + return API.v1.unauthorized(); } - const roomIds = RocketChat.models.Subscriptions.findByUserIdAndType(this.userId, 'c', { fields: { rid: 1 } }).fetch().map((s) => s.rid); + const roomIds = Subscriptions.findByUserIdAndType(this.userId, 'c', { fields: { rid: 1 } }).fetch().map((s) => s.rid); ourQuery._id = { $in: roomIds }; } - const cursor = RocketChat.models.Rooms.find(ourQuery, { + const cursor = Rooms.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, @@ -465,7 +468,7 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, { const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ channels: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), count: rooms.length, offset, @@ -475,13 +478,13 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, { +API.v1.addRoute('channels.list.joined', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields } = this.parseJsonQuery(); // TODO: CACHE: Add Breacking notice since we removed the query param - const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('c', this.userId, { + const cursor = Rooms.findBySubscriptionTypeAndUserId('c', this.userId, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, @@ -491,7 +494,7 @@ RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, { const totalCount = cursor.count(); const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ channels: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -500,21 +503,21 @@ RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, { +API.v1.addRoute('channels.members', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false, }); - if (findResult.broadcast && !RocketChat.authz.hasPermission(this.userId, 'view-broadcast-member-list')) { - return RocketChat.API.v1.unauthorized(); + if (findResult.broadcast && !hasPermission(this.userId, 'view-broadcast-member-list')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort = {} } = this.parseJsonQuery(); - const subscriptions = RocketChat.models.Subscriptions.findByRoomId(findResult._id, { + const subscriptions = Subscriptions.findByRoomId(findResult._id, { fields: { 'u._id': 1 }, sort: { 'u.username': sort.username != null ? sort.username : 1 }, skip: offset, @@ -525,12 +528,12 @@ RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, { const members = subscriptions.fetch().map((s) => s.u && s.u._id); - const users = RocketChat.models.Users.find({ _id: { $in: members } }, { + const users = Users.find({ _id: { $in: members } }, { fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 }, sort: { username: sort.username != null ? sort.username : 1 }, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ members: users, count: users.length, offset, @@ -539,7 +542,7 @@ RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { +API.v1.addRoute('channels.messages', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), @@ -551,14 +554,14 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult._id }); // Special check for the permissions - if (RocketChat.authz.hasPermission(this.userId, 'view-joined-room') && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId, { fields: { _id: 1 } })) { - return RocketChat.API.v1.unauthorized(); + if (hasPermission(this.userId, 'view-joined-room') && !Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId, { fields: { _id: 1 } })) { + return API.v1.unauthorized(); } - if (!RocketChat.authz.hasPermission(this.userId, 'view-c-room')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-c-room')) { + return API.v1.unauthorized(); } - const cursor = RocketChat.models.Messages.find(ourQuery, { + const cursor = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, @@ -568,8 +571,8 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { const total = cursor.count(); const messages = cursor.fetch(); - return RocketChat.API.v1.success({ - messages: messages.map((record) => RocketChat.composeMessageObjectWithUser(record, this.userId)), + return API.v1.success({ + messages: messages.map((record) => composeMessageObjectWithUser(record, this.userId)), count: messages.length, offset, total, @@ -605,24 +608,24 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { // } // }); -RocketChat.API.v1.addRoute('channels.online', { authRequired: true }, { +API.v1.addRoute('channels.online', { authRequired: true }, { get() { const { query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { t: 'c' }); - const room = RocketChat.models.Rooms.findOne(ourQuery); + const room = Rooms.findOne(ourQuery); if (room == null) { - return RocketChat.API.v1.failure('Channel does not exists'); + return API.v1.failure('Channel does not exists'); } - const online = RocketChat.models.Users.findUsersNotOffline({ + const online = Users.findUsersNotOffline({ fields: { username: 1 }, }).fetch(); const onlineInRoom = []; online.forEach((user) => { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); if (subscription) { onlineInRoom.push({ _id: user._id, @@ -631,35 +634,35 @@ RocketChat.API.v1.addRoute('channels.online', { authRequired: true }, { } }); - return RocketChat.API.v1.success({ + return API.v1.success({ online: onlineInRoom, }); }, }); -RocketChat.API.v1.addRoute('channels.open', { authRequired: true }, { +API.v1.addRoute('channels.open', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); + const sub = Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); if (!sub) { - return RocketChat.API.v1.failure(`The user/callee is not in the channel "${ findResult.name }".`); + return API.v1.failure(`The user/callee is not in the channel "${ findResult.name }".`); } if (sub.open) { - return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is already open to the sender`); + return API.v1.failure(`The channel, ${ findResult.name }, is already open to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('openRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.removeModerator', { authRequired: true }, { +API.v1.addRoute('channels.removeModerator', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -669,11 +672,11 @@ RocketChat.API.v1.addRoute('channels.removeModerator', { authRequired: true }, { Meteor.call('removeRoomModerator', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.removeOwner', { authRequired: true }, { +API.v1.addRoute('channels.removeOwner', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -683,36 +686,36 @@ RocketChat.API.v1.addRoute('channels.removeOwner', { authRequired: true }, { Meteor.call('removeRoomOwner', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.rename', { authRequired: true }, { +API.v1.addRoute('channels.rename', { authRequired: true }, { post() { if (!this.bodyParams.name || !this.bodyParams.name.trim()) { - return RocketChat.API.v1.failure('The bodyParam "name" is required'); + return API.v1.failure('The bodyParam "name" is required'); } const findResult = findChannelByIdOrName({ params: { roomId: this.bodyParams.roomId } }); if (findResult.name === this.bodyParams.name) { - return RocketChat.API.v1.failure('The channel name is the same as what it would be renamed to.'); + return API.v1.failure('The channel name is the same as what it would be renamed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomName', this.bodyParams.name); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: { roomId: this.bodyParams.roomId }, userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setCustomFields', { authRequired: true }, { +API.v1.addRoute('channels.setCustomFields', { authRequired: true }, { post() { if (!this.bodyParams.customFields || !(typeof this.bodyParams.customFields === 'object')) { - return RocketChat.API.v1.failure('The bodyParam "customFields" is required with a type like object.'); + return API.v1.failure('The bodyParam "customFields" is required with a type like object.'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -721,60 +724,60 @@ RocketChat.API.v1.addRoute('channels.setCustomFields', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult._id, 'roomCustomFields', this.bodyParams.customFields); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setDefault', { authRequired: true }, { +API.v1.addRoute('channels.setDefault', { authRequired: true }, { post() { if (typeof this.bodyParams.default === 'undefined') { - return RocketChat.API.v1.failure('The bodyParam "default" is required', 'error-channels-setdefault-is-same'); + return API.v1.failure('The bodyParam "default" is required', 'error-channels-setdefault-is-same'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.default === this.bodyParams.default) { - return RocketChat.API.v1.failure('The channel default setting is the same as what it would be changed to.', 'error-channels-setdefault-missing-default-param'); + return API.v1.failure('The channel default setting is the same as what it would be changed to.', 'error-channels-setdefault-missing-default-param'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'default', this.bodyParams.default.toString()); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setDescription', { authRequired: true }, { +API.v1.addRoute('channels.setDescription', { authRequired: true }, { post() { if (!this.bodyParams.description || !this.bodyParams.description.trim()) { - return RocketChat.API.v1.failure('The bodyParam "description" is required'); + return API.v1.failure('The bodyParam "description" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.description === this.bodyParams.description) { - return RocketChat.API.v1.failure('The channel description is the same as what it would be changed to.'); + return API.v1.failure('The channel description is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomDescription', this.bodyParams.description); }); - return RocketChat.API.v1.success({ + return API.v1.success({ description: this.bodyParams.description, }); }, }); -RocketChat.API.v1.addRoute('channels.setJoinCode', { authRequired: true }, { +API.v1.addRoute('channels.setJoinCode', { authRequired: true }, { post() { if (!this.bodyParams.joinCode || !this.bodyParams.joinCode.trim()) { - return RocketChat.API.v1.failure('The bodyParam "joinCode" is required'); + return API.v1.failure('The bodyParam "joinCode" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -783,82 +786,82 @@ RocketChat.API.v1.addRoute('channels.setJoinCode', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult._id, 'joinCode', this.bodyParams.joinCode); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setPurpose', { authRequired: true }, { +API.v1.addRoute('channels.setPurpose', { authRequired: true }, { post() { if (!this.bodyParams.purpose || !this.bodyParams.purpose.trim()) { - return RocketChat.API.v1.failure('The bodyParam "purpose" is required'); + return API.v1.failure('The bodyParam "purpose" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.description === this.bodyParams.purpose) { - return RocketChat.API.v1.failure('The channel purpose (description) is the same as what it would be changed to.'); + return API.v1.failure('The channel purpose (description) is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomDescription', this.bodyParams.purpose); }); - return RocketChat.API.v1.success({ + return API.v1.success({ purpose: this.bodyParams.purpose, }); }, }); -RocketChat.API.v1.addRoute('channels.setReadOnly', { authRequired: true }, { +API.v1.addRoute('channels.setReadOnly', { authRequired: true }, { post() { if (typeof this.bodyParams.readOnly === 'undefined') { - return RocketChat.API.v1.failure('The bodyParam "readOnly" is required'); + return API.v1.failure('The bodyParam "readOnly" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.ro === this.bodyParams.readOnly) { - return RocketChat.API.v1.failure('The channel read only setting is the same as what it would be changed to.'); + return API.v1.failure('The channel read only setting is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'readOnly', this.bodyParams.readOnly); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setTopic', { authRequired: true }, { +API.v1.addRoute('channels.setTopic', { authRequired: true }, { post() { if (!this.bodyParams.topic || !this.bodyParams.topic.trim()) { - return RocketChat.API.v1.failure('The bodyParam "topic" is required'); + return API.v1.failure('The bodyParam "topic" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.topic === this.bodyParams.topic) { - return RocketChat.API.v1.failure('The channel topic is the same as what it would be changed to.'); + return API.v1.failure('The channel topic is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomTopic', this.bodyParams.topic); }); - return RocketChat.API.v1.success({ + return API.v1.success({ topic: this.bodyParams.topic, }); }, }); -RocketChat.API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, { +API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, { post() { if (!this.bodyParams.announcement || !this.bodyParams.announcement.trim()) { - return RocketChat.API.v1.failure('The bodyParam "announcement" is required'); + return API.v1.failure('The bodyParam "announcement" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -867,58 +870,58 @@ RocketChat.API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult._id, 'roomAnnouncement', this.bodyParams.announcement); }); - return RocketChat.API.v1.success({ + return API.v1.success({ announcement: this.bodyParams.announcement, }); }, }); -RocketChat.API.v1.addRoute('channels.setType', { authRequired: true }, { +API.v1.addRoute('channels.setType', { authRequired: true }, { post() { if (!this.bodyParams.type || !this.bodyParams.type.trim()) { - return RocketChat.API.v1.failure('The bodyParam "type" is required'); + return API.v1.failure('The bodyParam "type" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.t === this.bodyParams.type) { - return RocketChat.API.v1.failure('The channel type is the same as what it would be changed to.'); + return API.v1.failure('The channel type is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomType', this.bodyParams.type); }); - return RocketChat.API.v1.success({ - channel: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + channel: this.composeRoomWithLastMessage(Rooms.findOneById(findResult._id, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('channels.unarchive', { authRequired: true }, { +API.v1.addRoute('channels.unarchive', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); if (!findResult.archived) { - return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is not archived`); + return API.v1.failure(`The channel, ${ findResult.name }, is not archived`); } Meteor.runAsUser(this.userId, () => { Meteor.call('unarchiveRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequired: true }, { +API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequired: true }, { get() { const { roomId } = this.requestParams(); const { offset, count } = this.getPaginationItems(); const { sort } = this.parseJsonQuery(); if (!roomId) { - return RocketChat.API.v1.failure('The request param "roomId" is required'); + return API.v1.failure('The request param "roomId" is required'); } const mentions = Meteor.runAsUser(this.userId, () => Meteor.call('getUserMentionsByChannel', { @@ -935,7 +938,7 @@ RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequire options: {}, })); - return RocketChat.API.v1.success({ + return API.v1.success({ mentions, count: mentions.length, offset, @@ -944,25 +947,25 @@ RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequire }, }); -RocketChat.API.v1.addRoute('channels.roles', { authRequired: true }, { +API.v1.addRoute('channels.roles', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); const roles = Meteor.runAsUser(this.userId, () => Meteor.call('getRoomRoles', findResult._id)); - return RocketChat.API.v1.success({ + return API.v1.success({ roles, }); }, }); -RocketChat.API.v1.addRoute('channels.moderators', { authRequired: true }, { +API.v1.addRoute('channels.moderators', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); - const moderators = RocketChat.models.Subscriptions.findByRoomIdAndRoles(findResult._id, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); + const moderators = Subscriptions.findByRoomIdAndRoles(findResult._id, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); - return RocketChat.API.v1.success({ + return API.v1.success({ moderators, }); }, diff --git a/packages/rocketchat-api/server/v1/chat.js b/packages/rocketchat-api/server/v1/chat.js index f6f92ae02444..f83b8dc2c804 100644 --- a/packages/rocketchat-api/server/v1/chat.js +++ b/packages/rocketchat-api/server/v1/chat.js @@ -1,9 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; 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 { API } from '../api'; -RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { +API.v1.addRoute('chat.delete', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ msgId: String, @@ -11,25 +14,25 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { asUser: Match.Maybe(Boolean), })); - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 } }); + const msg = Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 } }); if (!msg) { - return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); + return API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); } if (this.bodyParams.roomId !== msg.rid) { - return RocketChat.API.v1.failure('The room id provided does not match where the message is from.'); + return API.v1.failure('The room id provided does not match where the message is from.'); } - if (this.bodyParams.asUser && msg.u._id !== this.userId && !RocketChat.authz.hasPermission(this.userId, 'force-delete-message', msg.rid)) { - return RocketChat.API.v1.failure('Unauthorized. You must have the permission "force-delete-message" to delete other\'s message as them.'); + if (this.bodyParams.asUser && msg.u._id !== this.userId && !hasPermission(this.userId, 'force-delete-message', msg.rid)) { + return API.v1.failure('Unauthorized. You must have the permission "force-delete-message" to delete other\'s message as them.'); } Meteor.runAsUser(this.bodyParams.asUser ? msg.u._id : this.userId, () => { Meteor.call('deleteMessage', { _id: msg._id }); }); - return RocketChat.API.v1.success({ + return API.v1.success({ _id: msg._id, ts: Date.now(), message: msg, @@ -37,7 +40,7 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('chat.syncMessages', { authRequired: true }, { +API.v1.addRoute('chat.syncMessages', { authRequired: true }, { get() { const { roomId, lastUpdate } = this.queryParams; @@ -57,22 +60,22 @@ RocketChat.API.v1.addRoute('chat.syncMessages', { authRequired: true }, { }); if (!result) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ + return API.v1.success({ result: { - updated: result.updated.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), - deleted: result.deleted.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + updated: result.updated.map((message) => composeMessageObjectWithUser(message, this.userId)), + deleted: result.deleted.map((message) => composeMessageObjectWithUser(message, this.userId)), }, }); }, }); -RocketChat.API.v1.addRoute('chat.getMessage', { authRequired: true }, { +API.v1.addRoute('chat.getMessage', { authRequired: true }, { get() { if (!this.queryParams.msgId) { - return RocketChat.API.v1.failure('The "msgId" query parameter must be provided.'); + return API.v1.failure('The "msgId" query parameter must be provided.'); } let msg; @@ -81,22 +84,22 @@ RocketChat.API.v1.addRoute('chat.getMessage', { authRequired: true }, { }); if (!msg) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(msg, this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(msg, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.pinMessage', { authRequired: true }, { +API.v1.addRoute('chat.pinMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is missing.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -105,29 +108,29 @@ RocketChat.API.v1.addRoute('chat.pinMessage', { authRequired: true }, { let pinnedMessage; Meteor.runAsUser(this.userId, () => pinnedMessage = Meteor.call('pinMessage', msg)); - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(pinnedMessage, this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(pinnedMessage, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.postMessage', { authRequired: true }, { +API.v1.addRoute('chat.postMessage', { authRequired: true }, { post() { const messageReturn = processWebhookMessage(this.bodyParams, this.user, undefined, true)[0]; if (!messageReturn) { - return RocketChat.API.v1.failure('unknown-error'); + return API.v1.failure('unknown-error'); } - return RocketChat.API.v1.success({ + return API.v1.success({ ts: Date.now(), channel: messageReturn.channel, - message: RocketChat.composeMessageObjectWithUser(messageReturn.message, this.userId), + message: composeMessageObjectWithUser(messageReturn.message, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, { +API.v1.addRoute('chat.search', { authRequired: true }, { get() { const { roomId, searchText } = this.queryParams; const { count } = this.getPaginationItems(); @@ -143,8 +146,8 @@ RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, { let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('messageSearch', searchText, roomId, count).message.docs); - return RocketChat.API.v1.success({ - messages: result.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: result.map((message) => composeMessageObjectWithUser(message, this.userId)), }); }, }); @@ -152,7 +155,7 @@ RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, { // The difference between `chat.postMessage` and `chat.sendMessage` is that `chat.sendMessage` allows // for passing a value for `_id` and the other one doesn't. Also, `chat.sendMessage` only sends it to // one channel whereas the other one allows for sending to more than one channel at a time. -RocketChat.API.v1.addRoute('chat.sendMessage', { authRequired: true }, { +API.v1.addRoute('chat.sendMessage', { authRequired: true }, { post() { if (!this.bodyParams.message) { throw new Meteor.Error('error-invalid-params', 'The "message" parameter must be provided.'); @@ -161,19 +164,19 @@ RocketChat.API.v1.addRoute('chat.sendMessage', { authRequired: true }, { let message; Meteor.runAsUser(this.userId, () => message = Meteor.call('sendMessage', this.bodyParams.message)); - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(message, this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(message, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.starMessage', { authRequired: true }, { +API.v1.addRoute('chat.starMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is required.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -185,17 +188,17 @@ RocketChat.API.v1.addRoute('chat.starMessage', { authRequired: true }, { starred: true, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.unPinMessage', { authRequired: true }, { +API.v1.addRoute('chat.unPinMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is required.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -203,17 +206,17 @@ RocketChat.API.v1.addRoute('chat.unPinMessage', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('unpinMessage', msg)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.unStarMessage', { authRequired: true }, { +API.v1.addRoute('chat.unStarMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is required.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -225,11 +228,11 @@ RocketChat.API.v1.addRoute('chat.unStarMessage', { authRequired: true }, { starred: false, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, { +API.v1.addRoute('chat.update', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ roomId: String, @@ -237,15 +240,15 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, { text: String, // Using text to be consistant with chat.postMessage })); - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId); + const msg = Messages.findOneById(this.bodyParams.msgId); // Ensure the message exists if (!msg) { - return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); + return API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); } if (this.bodyParams.roomId !== msg.rid) { - return RocketChat.API.v1.failure('The room id provided does not match where the message is from.'); + return API.v1.failure('The room id provided does not match where the message is from.'); } // Permission checks are already done in the updateMessage method, so no need to duplicate them @@ -253,19 +256,19 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, { Meteor.call('updateMessage', { _id: msg._id, msg: this.bodyParams.text, rid: msg.rid }); }); - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(RocketChat.models.Messages.findOneById(msg._id), this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(Messages.findOneById(msg._id), this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.react', { authRequired: true }, { +API.v1.addRoute('chat.react', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is missing.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -279,50 +282,50 @@ RocketChat.API.v1.addRoute('chat.react', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('setReaction', emoji, msg._id, this.bodyParams.shouldReact)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.getMessageReadReceipts', { authRequired: true }, { +API.v1.addRoute('chat.getMessageReadReceipts', { authRequired: true }, { get() { const { messageId } = this.queryParams; if (!messageId) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ error: 'The required \'messageId\' param is missing.', }); } try { const messageReadReceipts = Meteor.runAsUser(this.userId, () => Meteor.call('getReadReceipts', { messageId })); - return RocketChat.API.v1.success({ + return API.v1.success({ receipts: messageReadReceipts, }); } catch (error) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ error: error.message, }); } }, }); -RocketChat.API.v1.addRoute('chat.reportMessage', { authRequired: true }, { +API.v1.addRoute('chat.reportMessage', { authRequired: true }, { post() { const { messageId, description } = this.bodyParams; if (!messageId) { - return RocketChat.API.v1.failure('The required "messageId" param is missing.'); + return API.v1.failure('The required "messageId" param is missing.'); } if (!description) { - return RocketChat.API.v1.failure('The required "description" param is missing.'); + return API.v1.failure('The required "description" param is missing.'); } Meteor.runAsUser(this.userId, () => Meteor.call('reportMessage', messageId, description)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.ignoreUser', { authRequired: true }, { +API.v1.addRoute('chat.ignoreUser', { authRequired: true }, { get() { const { rid, userId } = this.queryParams; let { ignore = true } = this.queryParams; @@ -339,11 +342,11 @@ RocketChat.API.v1.addRoute('chat.ignoreUser', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('ignoreUser', { rid, userId, ignore })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { +API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { get() { const { roomId, since } = this.queryParams; const { offset, count } = this.getPaginationItems(); @@ -357,7 +360,7 @@ RocketChat.API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { } else if (isNaN(Date.parse(since))) { throw new Meteor.Error('The "since" query parameter must be a valid date.'); } - const cursor = RocketChat.models.Messages.trashFindDeletedAfter(new Date(since), { rid: roomId }, { + const cursor = Messages.trashFindDeletedAfter(new Date(since), { rid: roomId }, { skip: offset, limit: count, fields: { _id: 1 }, @@ -367,7 +370,7 @@ RocketChat.API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { const messages = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ messages, count: messages.length, offset, diff --git a/packages/rocketchat-api/server/v1/commands.js b/packages/rocketchat-api/server/v1/commands.js index bfac0b17d5aa..3fdd8f042c47 100644 --- a/packages/rocketchat-api/server/v1/commands.js +++ b/packages/rocketchat-api/server/v1/commands.js @@ -1,45 +1,47 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Rooms } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('commands.get', { authRequired: true }, { +API.v1.addRoute('commands.get', { authRequired: true }, { get() { const params = this.queryParams; if (typeof params.command !== 'string') { - return RocketChat.API.v1.failure('The query param "command" must be provided.'); + return API.v1.failure('The query param "command" must be provided.'); } - const cmd = RocketChat.slashCommands.commands[params.command.toLowerCase()]; + const cmd = slashCommands.commands[params.command.toLowerCase()]; if (!cmd) { - return RocketChat.API.v1.failure(`There is no command in the system by the name of: ${ params.command }`); + return API.v1.failure(`There is no command in the system by the name of: ${ params.command }`); } - return RocketChat.API.v1.success({ command: cmd }); + return API.v1.success({ command: cmd }); }, }); -RocketChat.API.v1.addRoute('commands.list', { authRequired: true }, { +API.v1.addRoute('commands.list', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - let commands = Object.values(RocketChat.slashCommands.commands); + let commands = Object.values(slashCommands.commands); if (query && query.command) { commands = commands.filter((command) => command.command === query.command); } const totalCount = commands.length; - commands = RocketChat.models.Rooms.processQueryOptionsOnResult(commands, { + commands = Rooms.processQueryOptionsOnResult(commands, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }); - return RocketChat.API.v1.success({ + return API.v1.success({ commands, offset, count: commands.length, @@ -49,26 +51,26 @@ RocketChat.API.v1.addRoute('commands.list', { authRequired: true }, { }); // Expects a body of: { command: 'gimme', params: 'any string value', roomId: 'value' } -RocketChat.API.v1.addRoute('commands.run', { authRequired: true }, { +API.v1.addRoute('commands.run', { authRequired: true }, { post() { const body = this.bodyParams; const user = this.getLoggedInUser(); if (typeof body.command !== 'string') { - return RocketChat.API.v1.failure('You must provide a command to run.'); + return API.v1.failure('You must provide a command to run.'); } if (body.params && typeof body.params !== 'string') { - return RocketChat.API.v1.failure('The parameters for the command must be a single string.'); + return API.v1.failure('The parameters for the command must be a single string.'); } if (typeof body.roomId !== 'string') { - return RocketChat.API.v1.failure('The room\'s id where to execute this command must be provided and be a string.'); + return API.v1.failure('The room\'s id where to execute this command must be provided and be a string.'); } const cmd = body.command.toLowerCase(); - if (!RocketChat.slashCommands.commands[body.command.toLowerCase()]) { - return RocketChat.API.v1.failure('The command provided does not exist (or is disabled).'); + if (!slashCommands.commands[body.command.toLowerCase()]) { + return API.v1.failure('The command provided does not exist (or is disabled).'); } // This will throw an error if they can't or the room is invalid @@ -78,38 +80,38 @@ RocketChat.API.v1.addRoute('commands.run', { authRequired: true }, { let result; Meteor.runAsUser(user._id, () => { - result = RocketChat.slashCommands.run(cmd, params, { + result = slashCommands.run(cmd, params, { _id: Random.id(), rid: body.roomId, msg: `/${ cmd } ${ params }`, }); }); - return RocketChat.API.v1.success({ result }); + return API.v1.success({ result }); }, }); -RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { +API.v1.addRoute('commands.preview', { authRequired: true }, { // Expects these query params: command: 'giphy', params: 'mine', roomId: 'value' get() { const query = this.queryParams; const user = this.getLoggedInUser(); if (typeof query.command !== 'string') { - return RocketChat.API.v1.failure('You must provide a command to get the previews from.'); + return API.v1.failure('You must provide a command to get the previews from.'); } if (query.params && typeof query.params !== 'string') { - return RocketChat.API.v1.failure('The parameters for the command must be a single string.'); + return API.v1.failure('The parameters for the command must be a single string.'); } if (typeof query.roomId !== 'string') { - return RocketChat.API.v1.failure('The room\'s id where the previews are being displayed must be provided and be a string.'); + return API.v1.failure('The room\'s id where the previews are being displayed must be provided and be a string.'); } const cmd = query.command.toLowerCase(); - if (!RocketChat.slashCommands.commands[cmd]) { - return RocketChat.API.v1.failure('The command provided does not exist (or is disabled).'); + if (!slashCommands.commands[cmd]) { + return API.v1.failure('The command provided does not exist (or is disabled).'); } // This will throw an error if they can't or the room is invalid @@ -122,7 +124,7 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { preview = Meteor.call('getSlashCommandPreviews', { cmd, params, msg: { rid: query.roomId } }); }); - return RocketChat.API.v1.success({ preview }); + return API.v1.success({ preview }); }, // Expects a body format of: { command: 'giphy', params: 'mine', roomId: 'value', previewItem: { id: 'sadf8' type: 'image', value: 'https://dev.null/gif } } post() { @@ -130,28 +132,28 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { const user = this.getLoggedInUser(); if (typeof body.command !== 'string') { - return RocketChat.API.v1.failure('You must provide a command to run the preview item on.'); + return API.v1.failure('You must provide a command to run the preview item on.'); } if (body.params && typeof body.params !== 'string') { - return RocketChat.API.v1.failure('The parameters for the command must be a single string.'); + return API.v1.failure('The parameters for the command must be a single string.'); } if (typeof body.roomId !== 'string') { - return RocketChat.API.v1.failure('The room\'s id where the preview is being executed in must be provided and be a string.'); + return API.v1.failure('The room\'s id where the preview is being executed in must be provided and be a string.'); } if (typeof body.previewItem === 'undefined') { - return RocketChat.API.v1.failure('The preview item being executed must be provided.'); + return API.v1.failure('The preview item being executed must be provided.'); } if (!body.previewItem.id || !body.previewItem.type || typeof body.previewItem.value === 'undefined') { - return RocketChat.API.v1.failure('The preview item being executed is in the wrong format.'); + return API.v1.failure('The preview item being executed is in the wrong format.'); } const cmd = body.command.toLowerCase(); - if (!RocketChat.slashCommands.commands[cmd]) { - return RocketChat.API.v1.failure('The command provided does not exist (or is disabled).'); + if (!slashCommands.commands[cmd]) { + return API.v1.failure('The command provided does not exist (or is disabled).'); } // This will throw an error if they can't or the room is invalid @@ -163,6 +165,6 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { Meteor.call('executeSlashCommandPreview', { cmd, params, msg: { rid: body.roomId } }, body.previewItem); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/e2e.js b/packages/rocketchat-api/server/v1/e2e.js index f21f55e6e294..c4974add4774 100644 --- a/packages/rocketchat-api/server/v1/e2e.js +++ b/packages/rocketchat-api/server/v1/e2e.js @@ -1,61 +1,61 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('e2e.fetchMyKeys', { authRequired: true }, { +API.v1.addRoute('e2e.fetchMyKeys', { authRequired: true }, { get() { let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('e2e.fetchMyKeys')); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('e2e.getUsersOfRoomWithoutKey', { authRequired: true }, { +API.v1.addRoute('e2e.getUsersOfRoomWithoutKey', { authRequired: true }, { get() { const { rid } = this.queryParams; let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('e2e.getUsersOfRoomWithoutKey', rid)); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('e2e.setRoomKeyID', { authRequired: true }, { +API.v1.addRoute('e2e.setRoomKeyID', { authRequired: true }, { post() { const { rid, keyID } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('e2e.setRoomKeyID', rid, keyID)); + API.v1.success(Meteor.call('e2e.setRoomKeyID', rid, keyID)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('e2e.setUserPublicAndPivateKeys', { authRequired: true }, { +API.v1.addRoute('e2e.setUserPublicAndPivateKeys', { authRequired: true }, { post() { const { public_key, private_key } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('e2e.setUserPublicAndPivateKeys', { + API.v1.success(Meteor.call('e2e.setUserPublicAndPivateKeys', { public_key, private_key, })); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('e2e.updateGroupKey', { authRequired: true }, { +API.v1.addRoute('e2e.updateGroupKey', { authRequired: true }, { post() { const { uid, rid, key } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('e2e.updateGroupKey', rid, uid, key)); + API.v1.success(Meteor.call('e2e.updateGroupKey', rid, uid, key)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/emoji-custom.js b/packages/rocketchat-api/server/v1/emoji-custom.js index 94f427511ba5..09c931370d86 100644 --- a/packages/rocketchat-api/server/v1/emoji-custom.js +++ b/packages/rocketchat-api/server/v1/emoji-custom.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { EmojiCustom } from 'meteor/rocketchat:models'; +import { API } from '../api'; import Busboy from 'busboy'; -RocketChat.API.v1.addRoute('emoji-custom', { authRequired: true }, { +API.v1.addRoute('emoji-custom', { authRequired: true }, { get() { const { query } = this.parseJsonQuery(); const emojis = Meteor.call('listEmojiCustom', query); - return RocketChat.API.v1.success({ emojis }); + return API.v1.success({ emojis }); }, }); -RocketChat.API.v1.addRoute('emoji-custom.create', { authRequired: true }, { +API.v1.addRoute('emoji-custom.create', { authRequired: true }, { post() { Meteor.runAsUser(this.userId, () => { const fields = {}; @@ -49,7 +50,7 @@ RocketChat.API.v1.addRoute('emoji-custom.create', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('emoji-custom.update', { authRequired: true }, { +API.v1.addRoute('emoji-custom.update', { authRequired: true }, { post() { Meteor.runAsUser(this.userId, () => { const fields = {}; @@ -78,7 +79,7 @@ RocketChat.API.v1.addRoute('emoji-custom.update', { authRequired: true }, { if (!fields._id) { return callback(new Meteor.Error('The required "_id" query param is missing.')); } - const emojiToUpdate = RocketChat.models.EmojiCustom.findOneByID(fields._id); + const emojiToUpdate = EmojiCustom.findOneByID(fields._id); if (!emojiToUpdate) { return callback(new Meteor.Error('Emoji not found.')); } @@ -102,15 +103,15 @@ RocketChat.API.v1.addRoute('emoji-custom.update', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('emoji-custom.delete', { authRequired: true }, { +API.v1.addRoute('emoji-custom.delete', { authRequired: true }, { post() { const { emojiId } = this.bodyParams; if (!emojiId) { - return RocketChat.API.v1.failure('The "emojiId" params is required!'); + return API.v1.failure('The "emojiId" params is required!'); } Meteor.runAsUser(this.userId, () => Meteor.call('deleteEmojiCustom', emojiId)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/groups.js b/packages/rocketchat-api/server/v1/groups.js index fc5430c1f6ce..96c23e42e726 100644 --- a/packages/rocketchat-api/server/v1/groups.js +++ b/packages/rocketchat-api/server/v1/groups.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Rooms, Messages, Uploads, Integrations, Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; import _ from 'underscore'; // Returns the private group subscription IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property @@ -10,9 +13,9 @@ function findPrivateGroupByIdOrName({ params, userId, checkedArchived = true }) let roomSub; if (params.roomId) { - roomSub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(params.roomId, userId); + roomSub = Subscriptions.findOneByRoomIdAndUserId(params.roomId, userId); } else if (params.roomName) { - roomSub = RocketChat.models.Subscriptions.findOneByRoomNameAndUserId(params.roomName, userId); + roomSub = Subscriptions.findOneByRoomNameAndUserId(params.roomName, userId); } if (!roomSub || roomSub.t !== 'p') { @@ -26,7 +29,7 @@ function findPrivateGroupByIdOrName({ params, userId, checkedArchived = true }) return roomSub; } -RocketChat.API.v1.addRoute('groups.addAll', { authRequired: true }, { +API.v1.addRoute('groups.addAll', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -34,13 +37,13 @@ RocketChat.API.v1.addRoute('groups.addAll', { authRequired: true }, { Meteor.call('addAllUserToRoom', findResult.rid, this.bodyParams.activeUsersOnly); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.addModerator', { authRequired: true }, { +API.v1.addRoute('groups.addModerator', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -50,11 +53,11 @@ RocketChat.API.v1.addRoute('groups.addModerator', { authRequired: true }, { Meteor.call('addRoomModerator', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.addOwner', { authRequired: true }, { +API.v1.addRoute('groups.addOwner', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -64,11 +67,11 @@ RocketChat.API.v1.addRoute('groups.addOwner', { authRequired: true }, { Meteor.call('addRoomOwner', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.addLeader', { authRequired: true }, { +API.v1.addRoute('groups.addLeader', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); const user = this.getUserFromParams(); @@ -76,12 +79,12 @@ RocketChat.API.v1.addRoute('groups.addLeader', { authRequired: true }, { Meteor.call('addRoomLeader', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); // Archives a private group only if it wasn't -RocketChat.API.v1.addRoute('groups.archive', { authRequired: true }, { +API.v1.addRoute('groups.archive', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -89,29 +92,29 @@ RocketChat.API.v1.addRoute('groups.archive', { authRequired: true }, { Meteor.call('archiveRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.close', { authRequired: true }, { +API.v1.addRoute('groups.close', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); if (!findResult.open) { - return RocketChat.API.v1.failure(`The private group, ${ findResult.name }, is already closed to the sender`); + return API.v1.failure(`The private group, ${ findResult.name }, is already closed to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('hideRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { +API.v1.addRoute('groups.counters', { authRequired: true }, { get() { - const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration'); + const access = hasPermission(this.userId, 'view-room-administration'); const params = this.requestParams(); let user = this.userId; let room; @@ -128,9 +131,9 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { } if (params.roomId) { - room = RocketChat.models.Rooms.findOneById(params.roomId); + room = Rooms.findOneById(params.roomId); } else if (params.roomName) { - room = RocketChat.models.Rooms.findOneByName(params.roomName); + room = Rooms.findOneByName(params.roomName); } if (!room || room.t !== 'p') { @@ -143,15 +146,15 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { if (params.userId) { if (!access) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } user = params.userId; } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user); const lm = room.lm ? room.lm : room._updatedAt; if (typeof subscription !== 'undefined' && subscription.open) { - unreads = RocketChat.models.Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, (subscription.ls || subscription.ts), lm); + unreads = Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, (subscription.ls || subscription.ts), lm); unreadsFrom = subscription.ls || subscription.ts; userMentions = subscription.userMentions; joined = true; @@ -163,7 +166,7 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { members = room.usersCount; } - return RocketChat.API.v1.success({ + return API.v1.success({ joined, members, unreads, @@ -176,22 +179,22 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { }); // Create Private Group -RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, { +API.v1.addRoute('groups.create', { authRequired: true }, { post() { - if (!RocketChat.authz.hasPermission(this.userId, 'create-p')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'create-p')) { + return API.v1.unauthorized(); } if (!this.bodyParams.name) { - return RocketChat.API.v1.failure('Body param "name" is required'); + return API.v1.failure('Body param "name" is required'); } if (this.bodyParams.members && !_.isArray(this.bodyParams.members)) { - return RocketChat.API.v1.failure('Body param "members" must be an array if provided'); + return API.v1.failure('Body param "members" must be an array if provided'); } if (this.bodyParams.customFields && !(typeof this.bodyParams.customFields === 'object')) { - return RocketChat.API.v1.failure('Body param "customFields" must be an object if provided'); + return API.v1.failure('Body param "customFields" must be an object if provided'); } const readOnly = typeof this.bodyParams.readOnly !== 'undefined' ? this.bodyParams.readOnly : false; @@ -201,13 +204,13 @@ RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, { id = Meteor.call('createPrivateGroup', this.bodyParams.name, this.bodyParams.members ? this.bodyParams.members : [], readOnly, this.bodyParams.customFields); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(id.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(id.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.delete', { authRequired: true }, { +API.v1.addRoute('groups.delete', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -215,11 +218,11 @@ RocketChat.API.v1.addRoute('groups.delete', { authRequired: true }, { Meteor.call('eraseRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.files', { authRequired: true }, { +API.v1.addRoute('groups.files', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); const addUserObjectToEveryObject = (file) => { @@ -234,26 +237,26 @@ RocketChat.API.v1.addRoute('groups.files', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult.rid }); - const files = RocketChat.models.Uploads.find(ourQuery, { + const files = Uploads.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ files: files.map(addUserObjectToEveryObject), count: files.length, offset, - total: RocketChat.models.Uploads.find(ourQuery).count(), + total: Uploads.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, { +API.v1.addRoute('groups.getIntegrations', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -272,23 +275,23 @@ RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, { const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { channel: { $in: channelsToSearch } }); - const integrations = RocketChat.models.Integrations.find(ourQuery, { + const integrations = Integrations.find(ourQuery, { sort: sort ? sort : { _createdAt: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ integrations, count: integrations.length, offset, - total: RocketChat.models.Integrations.find(ourQuery).count(), + total: Integrations.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, { +API.v1.addRoute('groups.history', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -317,24 +320,24 @@ RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, { }); if (!result) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('groups.info', { authRequired: true }, { +API.v1.addRoute('groups.info', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, { +API.v1.addRoute('groups.invite', { authRequired: true }, { post() { const { roomId = '', roomName = '' } = this.requestParams(); const idOrName = roomId || roomName; @@ -342,7 +345,7 @@ RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, { throw new Meteor.Error('error-room-param-not-provided', 'The parameter "roomId" or "roomName" is required'); } - const { _id: rid, t: type } = RocketChat.models.Rooms.findOneByIdOrName(idOrName) || {}; + const { _id: rid, t: type } = Rooms.findOneByIdOrName(idOrName) || {}; if (!rid || type !== 'p') { throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "roomName" param provided does not match any group'); @@ -352,13 +355,13 @@ RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('addUserToRoom', { rid, username })); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.kick', { authRequired: true }, { +API.v1.addRoute('groups.kick', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -368,11 +371,11 @@ RocketChat.API.v1.addRoute('groups.kick', { authRequired: true }, { Meteor.call('removeUserFromRoom', { rid: findResult.rid, username: user.username }); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.leave', { authRequired: true }, { +API.v1.addRoute('groups.leave', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -380,18 +383,18 @@ RocketChat.API.v1.addRoute('groups.leave', { authRequired: true }, { Meteor.call('leaveRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); // List Private Groups a user has access to -RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, { +API.v1.addRoute('groups.list', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields } = this.parseJsonQuery(); // TODO: CACHE: Add Breacking notice since we removed the query param - const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('p', this.userId, { + const cursor = Rooms.findBySubscriptionTypeAndUserId('p', this.userId, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, @@ -402,7 +405,7 @@ RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, { const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ groups: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -412,26 +415,26 @@ RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, { }); -RocketChat.API.v1.addRoute('groups.listAll', { authRequired: true }, { +API.v1.addRoute('groups.listAll', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-room-administration')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-room-administration')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { t: 'p' }); - let rooms = RocketChat.models.Rooms.find(ourQuery).fetch(); + let rooms = Rooms.find(ourQuery).fetch(); const totalCount = rooms.length; - rooms = RocketChat.models.Rooms.processQueryOptionsOnResult(rooms, { + rooms = Rooms.processQueryOptionsOnResult(rooms, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }); - return RocketChat.API.v1.success({ + return API.v1.success({ groups: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -440,19 +443,19 @@ RocketChat.API.v1.addRoute('groups.listAll', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, { +API.v1.addRoute('groups.members', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); - const room = RocketChat.models.Rooms.findOneById(findResult.rid, { fields: { broadcast: 1 } }); + const room = Rooms.findOneById(findResult.rid, { fields: { broadcast: 1 } }); - if (room.broadcast && !RocketChat.authz.hasPermission(this.userId, 'view-broadcast-member-list')) { - return RocketChat.API.v1.unauthorized(); + if (room.broadcast && !hasPermission(this.userId, 'view-broadcast-member-list')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort = {} } = this.parseJsonQuery(); - const subscriptions = RocketChat.models.Subscriptions.findByRoomId(findResult.rid, { + const subscriptions = Subscriptions.findByRoomId(findResult.rid, { fields: { 'u._id': 1 }, sort: { 'u.username': sort.username != null ? sort.username : 1 }, skip: offset, @@ -463,12 +466,12 @@ RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, { const members = subscriptions.fetch().map((s) => s.u && s.u._id); - const users = RocketChat.models.Users.find({ _id: { $in: members } }, { + const users = Users.find({ _id: { $in: members } }, { fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 }, sort: { username: sort.username != null ? sort.username : 1 }, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ members: users, count: users.length, offset, @@ -477,7 +480,7 @@ RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('groups.messages', { authRequired: true }, { +API.v1.addRoute('groups.messages', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); const { offset, count } = this.getPaginationItems(); @@ -485,34 +488,34 @@ RocketChat.API.v1.addRoute('groups.messages', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult.rid }); - const messages = RocketChat.models.Messages.find(ourQuery, { + const messages = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ - messages: messages.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: messages.map((message) => composeMessageObjectWithUser(message, this.userId)), count: messages.length, offset, - total: RocketChat.models.Messages.find(ourQuery).count(), + total: Messages.find(ourQuery).count(), }); }, }); // TODO: CACHE: same as channels.online -RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, { +API.v1.addRoute('groups.online', { authRequired: true }, { get() { const { query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { t: 'p' }); - const room = RocketChat.models.Rooms.findOne(ourQuery); + const room = Rooms.findOne(ourQuery); if (room == null) { - return RocketChat.API.v1.failure('Group does not exists'); + return API.v1.failure('Group does not exists'); } - const online = RocketChat.models.Users.findUsersNotOffline({ + const online = Users.findUsersNotOffline({ fields: { username: 1, }, @@ -520,7 +523,7 @@ RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, { const onlineInRoom = []; online.forEach((user) => { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); if (subscription) { onlineInRoom.push({ _id: user._id, @@ -529,29 +532,29 @@ RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, { } }); - return RocketChat.API.v1.success({ + return API.v1.success({ online: onlineInRoom, }); }, }); -RocketChat.API.v1.addRoute('groups.open', { authRequired: true }, { +API.v1.addRoute('groups.open', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); if (findResult.open) { - return RocketChat.API.v1.failure(`The private group, ${ findResult.name }, is already open for the sender`); + return API.v1.failure(`The private group, ${ findResult.name }, is already open for the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('openRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.removeModerator', { authRequired: true }, { +API.v1.addRoute('groups.removeModerator', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -561,11 +564,11 @@ RocketChat.API.v1.addRoute('groups.removeModerator', { authRequired: true }, { Meteor.call('removeRoomModerator', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.removeOwner', { authRequired: true }, { +API.v1.addRoute('groups.removeOwner', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -575,11 +578,11 @@ RocketChat.API.v1.addRoute('groups.removeOwner', { authRequired: true }, { Meteor.call('removeRoomOwner', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.removeLeader', { authRequired: true }, { +API.v1.addRoute('groups.removeLeader', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -589,14 +592,14 @@ RocketChat.API.v1.addRoute('groups.removeLeader', { authRequired: true }, { Meteor.call('removeRoomLeader', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.rename', { authRequired: true }, { +API.v1.addRoute('groups.rename', { authRequired: true }, { post() { if (!this.bodyParams.name || !this.bodyParams.name.trim()) { - return RocketChat.API.v1.failure('The bodyParam "name" is required'); + return API.v1.failure('The bodyParam "name" is required'); } const findResult = findPrivateGroupByIdOrName({ params: { roomId: this.bodyParams.roomId }, userId: this.userId }); @@ -605,16 +608,16 @@ RocketChat.API.v1.addRoute('groups.rename', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomName', this.bodyParams.name); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setCustomFields', { authRequired: true }, { +API.v1.addRoute('groups.setCustomFields', { authRequired: true }, { post() { if (!this.bodyParams.customFields || !(typeof this.bodyParams.customFields === 'object')) { - return RocketChat.API.v1.failure('The bodyParam "customFields" is required with a type like object.'); + return API.v1.failure('The bodyParam "customFields" is required with a type like object.'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -623,16 +626,16 @@ RocketChat.API.v1.addRoute('groups.setCustomFields', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomCustomFields', this.bodyParams.customFields); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setDescription', { authRequired: true }, { +API.v1.addRoute('groups.setDescription', { authRequired: true }, { post() { if (!this.bodyParams.description || !this.bodyParams.description.trim()) { - return RocketChat.API.v1.failure('The bodyParam "description" is required'); + return API.v1.failure('The bodyParam "description" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -641,16 +644,16 @@ RocketChat.API.v1.addRoute('groups.setDescription', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomDescription', this.bodyParams.description); }); - return RocketChat.API.v1.success({ + return API.v1.success({ description: this.bodyParams.description, }); }, }); -RocketChat.API.v1.addRoute('groups.setPurpose', { authRequired: true }, { +API.v1.addRoute('groups.setPurpose', { authRequired: true }, { post() { if (!this.bodyParams.purpose || !this.bodyParams.purpose.trim()) { - return RocketChat.API.v1.failure('The bodyParam "purpose" is required'); + return API.v1.failure('The bodyParam "purpose" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -659,38 +662,38 @@ RocketChat.API.v1.addRoute('groups.setPurpose', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomDescription', this.bodyParams.purpose); }); - return RocketChat.API.v1.success({ + return API.v1.success({ purpose: this.bodyParams.purpose, }); }, }); -RocketChat.API.v1.addRoute('groups.setReadOnly', { authRequired: true }, { +API.v1.addRoute('groups.setReadOnly', { authRequired: true }, { post() { if (typeof this.bodyParams.readOnly === 'undefined') { - return RocketChat.API.v1.failure('The bodyParam "readOnly" is required'); + return API.v1.failure('The bodyParam "readOnly" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); if (findResult.ro === this.bodyParams.readOnly) { - return RocketChat.API.v1.failure('The private group read only setting is the same as what it would be changed to.'); + return API.v1.failure('The private group read only setting is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult.rid, 'readOnly', this.bodyParams.readOnly); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setTopic', { authRequired: true }, { +API.v1.addRoute('groups.setTopic', { authRequired: true }, { post() { if (!this.bodyParams.topic || !this.bodyParams.topic.trim()) { - return RocketChat.API.v1.failure('The bodyParam "topic" is required'); + return API.v1.failure('The bodyParam "topic" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -699,38 +702,38 @@ RocketChat.API.v1.addRoute('groups.setTopic', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomTopic', this.bodyParams.topic); }); - return RocketChat.API.v1.success({ + return API.v1.success({ topic: this.bodyParams.topic, }); }, }); -RocketChat.API.v1.addRoute('groups.setType', { authRequired: true }, { +API.v1.addRoute('groups.setType', { authRequired: true }, { post() { if (!this.bodyParams.type || !this.bodyParams.type.trim()) { - return RocketChat.API.v1.failure('The bodyParam "type" is required'); + return API.v1.failure('The bodyParam "type" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); if (findResult.t === this.bodyParams.type) { - return RocketChat.API.v1.failure('The private group type is the same as what it would be changed to.'); + return API.v1.failure('The private group type is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult.rid, 'roomType', this.bodyParams.type); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setAnnouncement', { authRequired: true }, { +API.v1.addRoute('groups.setAnnouncement', { authRequired: true }, { post() { if (!this.bodyParams.announcement || !this.bodyParams.announcement.trim()) { - return RocketChat.API.v1.failure('The bodyParam "announcement" is required'); + return API.v1.failure('The bodyParam "announcement" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -739,13 +742,13 @@ RocketChat.API.v1.addRoute('groups.setAnnouncement', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomAnnouncement', this.bodyParams.announcement); }); - return RocketChat.API.v1.success({ + return API.v1.success({ announcement: this.bodyParams.announcement, }); }, }); -RocketChat.API.v1.addRoute('groups.unarchive', { authRequired: true }, { +API.v1.addRoute('groups.unarchive', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -753,29 +756,29 @@ RocketChat.API.v1.addRoute('groups.unarchive', { authRequired: true }, { Meteor.call('unarchiveRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.roles', { authRequired: true }, { +API.v1.addRoute('groups.roles', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); const roles = Meteor.runAsUser(this.userId, () => Meteor.call('getRoomRoles', findResult.rid)); - return RocketChat.API.v1.success({ + return API.v1.success({ roles, }); }, }); -RocketChat.API.v1.addRoute('groups.moderators', { authRequired: true }, { +API.v1.addRoute('groups.moderators', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); - const moderators = RocketChat.models.Subscriptions.findByRoomIdAndRoles(findResult.rid, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); + const moderators = Subscriptions.findByRoomIdAndRoles(findResult.rid, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); - return RocketChat.API.v1.success({ + return API.v1.success({ moderators, }); }, diff --git a/packages/rocketchat-api/server/v1/im.js b/packages/rocketchat-api/server/v1/im.js index f560bed0449e..763dc8def581 100644 --- a/packages/rocketchat-api/server/v1/im.js +++ b/packages/rocketchat-api/server/v1/im.js @@ -1,5 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } 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'; +import { settings } from 'meteor/rocketchat:settings'; +import { API } from '../api'; function findDirectMessageRoom(params, user) { if ((!params.roomId || !params.roomId.trim()) && (!params.username || !params.username.trim())) { @@ -16,7 +21,7 @@ function findDirectMessageRoom(params, user) { throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "username" param provided does not match any dirct message'); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user._id); return { room, @@ -24,35 +29,35 @@ function findDirectMessageRoom(params, user) { }; } -RocketChat.API.v1.addRoute(['dm.create', 'im.create'], { authRequired: true }, { +API.v1.addRoute(['dm.create', 'im.create'], { authRequired: true }, { post() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); - return RocketChat.API.v1.success({ + return API.v1.success({ room: findResult.room, }); }, }); -RocketChat.API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, { +API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, { post() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); if (!findResult.subscription.open) { - return RocketChat.API.v1.failure(`The direct message room, ${ this.bodyParams.name }, is already closed to the sender`); + return API.v1.failure(`The direct message room, ${ this.bodyParams.name }, is already closed to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('hideRoom', findResult.room._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, { +API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, { get() { - const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration'); + const access = hasPermission(this.userId, 'view-room-administration'); const ruserId = this.requestParams().userId; let user = this.userId; let unreads = null; @@ -66,7 +71,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true if (ruserId) { if (!access) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } user = ruserId; } @@ -90,7 +95,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true members = room.usersCount; } - return RocketChat.API.v1.success({ + return API.v1.success({ joined, members, unreads, @@ -102,7 +107,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, }); -RocketChat.API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, { +API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); const addUserObjectToEveryObject = (file) => { @@ -117,23 +122,23 @@ RocketChat.API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult.room._id }); - const files = RocketChat.models.Uploads.find(ourQuery, { + const files = Uploads.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ files: files.map(addUserObjectToEveryObject), count: files.length, offset, - total: RocketChat.models.Uploads.find(ourQuery).count(), + total: Uploads.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, { +API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -169,20 +174,20 @@ RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, }); if (!result) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, { +API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); const { offset, count } = this.getPaginationItems(); const { sort } = this.parseJsonQuery(); - const cursor = RocketChat.models.Subscriptions.findByRoomId(findResult.room._id, { + const cursor = Subscriptions.findByRoomId(findResult.room._id, { sort: { 'u.username': sort && sort.username ? sort.username : 1 }, skip: offset, limit: count, @@ -191,12 +196,12 @@ RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, const total = cursor.count(); const members = cursor.fetch().map((s) => s.u && s.u.username); - const users = RocketChat.models.Users.find({ username: { $in: members } }, { + const users = Users.find({ username: { $in: members } }, { fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 }, sort: { username: sort && sort.username ? sort.username : 1 }, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ members: users, count: members.length, offset, @@ -205,7 +210,7 @@ RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, }, }); -RocketChat.API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true }, { +API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -214,30 +219,30 @@ RocketChat.API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true const ourQuery = Object.assign({}, query, { rid: findResult.room._id }); - const messages = RocketChat.models.Messages.find(ourQuery, { + const messages = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ - messages: messages.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: messages.map((message) => composeMessageObjectWithUser(message, this.userId)), count: messages.length, offset, - total: RocketChat.models.Messages.find(ourQuery).count(), + total: Messages.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authRequired: true }, { +API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authRequired: true }, { get() { - if (RocketChat.settings.get('API_Enable_Direct_Message_History_EndPoint') !== true) { + if (settings.get('API_Enable_Direct_Message_History_EndPoint') !== true) { throw new Meteor.Error('error-endpoint-disabled', 'This endpoint is disabled', { route: '/api/v1/im.messages.others' }); } - if (!RocketChat.authz.hasPermission(this.userId, 'view-room-administration')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-room-administration')) { + return API.v1.unauthorized(); } const { roomId } = this.queryParams; @@ -245,7 +250,7 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" is required'); } - const room = RocketChat.models.Rooms.findOneById(roomId); + const room = Rooms.findOneById(roomId); if (!room || room.t !== 'd') { throw new Meteor.Error('error-room-not-found', `No direct message room found by the id of: ${ roomId }`); } @@ -254,30 +259,30 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { rid: room._id }); - const msgs = RocketChat.models.Messages.find(ourQuery, { + const msgs = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ - messages: msgs.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: msgs.map((message) => composeMessageObjectWithUser(message, this.userId)), offset, count: msgs.length, - total: RocketChat.models.Messages.find(ourQuery).count(), + total: Messages.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { +API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort = { name: 1 }, fields } = this.parseJsonQuery(); // TODO: CACHE: Add Breacking notice since we removed the query param - const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('d', this.userId, { + const cursor = Rooms.findBySubscriptionTypeAndUserId('d', this.userId, { sort, skip: offset, limit: count, @@ -287,7 +292,7 @@ RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { const total = cursor.count(); const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ ims: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -296,10 +301,10 @@ RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequired: true }, { +API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-room-administration')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-room-administration')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); @@ -307,23 +312,23 @@ RocketChat.API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequi const ourQuery = Object.assign({}, query, { t: 'd' }); - const rooms = RocketChat.models.Rooms.find(ourQuery, { + const rooms = Rooms.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ ims: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, - total: RocketChat.models.Rooms.find(ourQuery).count(), + total: Rooms.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, { +API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, { post() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -333,14 +338,14 @@ RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, { }); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true }, { +API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true }, { post() { if (!this.bodyParams.topic || !this.bodyParams.topic.trim()) { - return RocketChat.API.v1.failure('The bodyParam "topic" is required'); + return API.v1.failure('The bodyParam "topic" is required'); } const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -349,7 +354,7 @@ RocketChat.API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true Meteor.call('saveRoomSettings', findResult.room._id, 'roomTopic', this.bodyParams.topic); }); - return RocketChat.API.v1.success({ + return API.v1.success({ topic: this.bodyParams.topic, }); }, diff --git a/packages/rocketchat-api/server/v1/import.js b/packages/rocketchat-api/server/v1/import.js index acd596e47e83..a68788a40a55 100644 --- a/packages/rocketchat-api/server/v1/import.js +++ b/packages/rocketchat-api/server/v1/import.js @@ -1,33 +1,33 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('uploadImportFile', { authRequired: true }, { +API.v1.addRoute('uploadImportFile', { authRequired: true }, { post() { const { binaryContent, contentType, fileName, importerKey } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('uploadImportFile', binaryContent, contentType, fileName, importerKey)); + API.v1.success(Meteor.call('uploadImportFile', binaryContent, contentType, fileName, importerKey)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('downloadPublicImportFile', { authRequired: true }, { +API.v1.addRoute('downloadPublicImportFile', { authRequired: true }, { post() { const { fileUrl, importerKey } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('downloadPublicImportFile', fileUrl, importerKey)); + API.v1.success(Meteor.call('downloadPublicImportFile', fileUrl, importerKey)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('getImportFileData', { authRequired: true }, { +API.v1.addRoute('getImportFileData', { authRequired: true }, { get() { const { importerKey } = this.requestParams(); let result; @@ -35,16 +35,16 @@ RocketChat.API.v1.addRoute('getImportFileData', { authRequired: true }, { result = Meteor.call('getImportFileData', importerKey); }); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('getLatestImportOperations', { authRequired: true }, { +API.v1.addRoute('getLatestImportOperations', { authRequired: true }, { get() { let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('getLatestImportOperations')); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); diff --git a/packages/rocketchat-api/server/v1/integrations.js b/packages/rocketchat-api/server/v1/integrations.js index 8b47074daa6a..49e6e0a2c974 100644 --- a/packages/rocketchat-api/server/v1/integrations.js +++ b/packages/rocketchat-api/server/v1/integrations.js @@ -1,8 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { IntegrationHistory, Integrations } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('integrations.create', { authRequired: true }, { +API.v1.addRoute('integrations.create', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ type: String, @@ -36,21 +38,21 @@ RocketChat.API.v1.addRoute('integrations.create', { authRequired: true }, { }); break; default: - return RocketChat.API.v1.failure('Invalid integration type.'); + return API.v1.failure('Invalid integration type.'); } - return RocketChat.API.v1.success({ integration }); + return API.v1.success({ integration }); }, }); -RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, { +API.v1.addRoute('integrations.history', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } if (!this.queryParams.id || this.queryParams.id.trim() === '') { - return RocketChat.API.v1.failure('Invalid integration id.'); + return API.v1.failure('Invalid integration id.'); } const { id } = this.queryParams; @@ -58,49 +60,49 @@ RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, { const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { 'integration._id': id }); - const history = RocketChat.models.IntegrationHistory.find(ourQuery, { + const history = IntegrationHistory.find(ourQuery, { sort: sort ? sort : { _updatedAt: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ history, offset, items: history.length, - total: RocketChat.models.IntegrationHistory.find(ourQuery).count(), + total: IntegrationHistory.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('integrations.list', { authRequired: true }, { +API.v1.addRoute('integrations.list', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query); - const integrations = RocketChat.models.Integrations.find(ourQuery, { + const integrations = Integrations.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ integrations, offset, items: integrations.length, - total: RocketChat.models.Integrations.find(ourQuery).count(), + total: Integrations.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, { +API.v1.addRoute('integrations.remove', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ type: String, @@ -109,45 +111,45 @@ RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, { })); if (!this.bodyParams.target_url && !this.bodyParams.integrationId) { - return RocketChat.API.v1.failure('An integrationId or target_url needs to be provided.'); + return API.v1.failure('An integrationId or target_url needs to be provided.'); } let integration; switch (this.bodyParams.type) { case 'webhook-outgoing': if (this.bodyParams.target_url) { - integration = RocketChat.models.Integrations.findOne({ urls: this.bodyParams.target_url }); + integration = Integrations.findOne({ urls: this.bodyParams.target_url }); } else if (this.bodyParams.integrationId) { - integration = RocketChat.models.Integrations.findOne({ _id: this.bodyParams.integrationId }); + integration = Integrations.findOne({ _id: this.bodyParams.integrationId }); } if (!integration) { - return RocketChat.API.v1.failure('No integration found.'); + return API.v1.failure('No integration found.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('deleteOutgoingIntegration', integration._id); }); - return RocketChat.API.v1.success({ + return API.v1.success({ integration, }); case 'webhook-incoming': - integration = RocketChat.models.Integrations.findOne({ _id: this.bodyParams.integrationId }); + integration = Integrations.findOne({ _id: this.bodyParams.integrationId }); if (!integration) { - return RocketChat.API.v1.failure('No integration found.'); + return API.v1.failure('No integration found.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('deleteIncomingIntegration', integration._id); }); - return RocketChat.API.v1.success({ + return API.v1.success({ integration, }); default: - return RocketChat.API.v1.failure('Invalid integration type.'); + return API.v1.failure('Invalid integration type.'); } }, }); From c6db2d5766a19c57bb8fe5aa5f926228ec975b8b Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 13:41:14 -0200 Subject: [PATCH 04/11] Partial Remove dependency of RC namespace in rc-api --- packages/rocketchat-api/server/index.js | 2 +- packages/rocketchat-api/server/v1/misc.js | 48 +++--- .../rocketchat-api/server/v1/permissions.js | 34 ++-- packages/rocketchat-api/server/v1/push.js | 10 +- packages/rocketchat-api/server/v1/roles.js | 21 +-- packages/rocketchat-api/server/v1/rooms.js | 57 +++---- packages/rocketchat-api/server/v1/settings.js | 58 +++---- packages/rocketchat-api/server/v1/stats.js | 20 ++- .../rocketchat-api/server/v1/subscriptions.js | 25 +-- packages/rocketchat-api/server/v1/users.js | 156 +++++++++--------- .../server/v1/video-conference.js | 10 +- 11 files changed, 229 insertions(+), 212 deletions(-) diff --git a/packages/rocketchat-api/server/index.js b/packages/rocketchat-api/server/index.js index 1c6c5b0277c0..483de4253475 100644 --- a/packages/rocketchat-api/server/index.js +++ b/packages/rocketchat-api/server/index.js @@ -1,5 +1,5 @@ import './settings'; -import './api'; +export { API } from './api'; import './helpers/composeRoomWithLastMessage'; import './helpers/deprecationWarning'; import './helpers/getLoggedInUser'; diff --git a/packages/rocketchat-api/server/v1/misc.js b/packages/rocketchat-api/server/v1/misc.js index 97efb021f569..7528fe4f0bb9 100644 --- a/packages/rocketchat-api/server/v1/misc.js +++ b/packages/rocketchat-api/server/v1/misc.js @@ -1,50 +1,54 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { Info } from 'meteor/rocketchat:utils'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('info', { authRequired: false }, { +API.v1.addRoute('info', { authRequired: false }, { get() { const user = this.getLoggedInUser(); - if (user && RocketChat.authz.hasRole(user._id, 'admin')) { - return RocketChat.API.v1.success({ - info: RocketChat.Info, + if (user && hasRole(user._id, 'admin')) { + return API.v1.success({ + info: Info, }); } - return RocketChat.API.v1.success({ + return API.v1.success({ info: { - version: RocketChat.Info.version, + version: Info.version, }, }); }, }); -RocketChat.API.v1.addRoute('me', { authRequired: true }, { +API.v1.addRoute('me', { authRequired: true }, { get() { - return RocketChat.API.v1.success(this.getUserInfo(RocketChat.models.Users.findOneById(this.userId))); + return API.v1.success(this.getUserInfo(Users.findOneById(this.userId))); }, }); let onlineCache = 0; let onlineCacheDate = 0; const cacheInvalid = 60000; // 1 minute -RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { +API.v1.addRoute('shield.svg', { authRequired: false }, { get() { const { type, channel, name, icon } = this.queryParams; - if (!RocketChat.settings.get('API_Enable_Shields')) { + if (!settings.get('API_Enable_Shields')) { throw new Meteor.Error('error-endpoint-disabled', 'This endpoint is disabled', { route: '/api/v1/shield.svg' }); } - const types = RocketChat.settings.get('API_Shield_Types'); + const types = settings.get('API_Shield_Types'); if (type && (types !== '*' && !types.split(',').map((t) => t.trim()).includes(type))) { throw new Meteor.Error('error-shield-disabled', 'This shield type is disabled', { route: '/api/v1/shield.svg' }); } const hideIcon = icon === 'false'; if (hideIcon && (!name || !name.trim())) { - return RocketChat.API.v1.failure('Name cannot be empty when icon is hidden'); + return API.v1.failure('Name cannot be empty when icon is hidden'); } let text; @@ -52,7 +56,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { switch (type) { case 'online': if (Date.now() - onlineCacheDate > cacheInvalid) { - onlineCache = RocketChat.models.Users.findUsersNotOffline().count(); + onlineCache = Users.findUsersNotOffline().count(); onlineCacheDate = Date.now(); } @@ -60,7 +64,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { break; case 'channel': if (!channel) { - return RocketChat.API.v1.failure('Shield channel is required for type "channel"'); + return API.v1.failure('Shield channel is required for type "channel"'); } text = `#${ channel }`; @@ -69,7 +73,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { const user = this.getUserFromParams(); // Respect the server's choice for using their real names or not - if (user.name && RocketChat.settings.get('UI_Use_Real_Name')) { + if (user.name && settings.get('UI_Use_Real_Name')) { text = `${ user.name }`; } else { text = `@${ user.username }`; @@ -127,7 +131,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { }, }); -RocketChat.API.v1.addRoute('spotlight', { authRequired: true }, { +API.v1.addRoute('spotlight', { authRequired: true }, { get() { check(this.queryParams, { query: String, @@ -139,18 +143,18 @@ RocketChat.API.v1.addRoute('spotlight', { authRequired: true }, { Meteor.call('spotlight', query) ); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('directory', { authRequired: true }, { +API.v1.addRoute('directory', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, query } = this.parseJsonQuery(); const { text, type } = query; if (sort && Object.keys(sort).length > 1) { - return RocketChat.API.v1.failure('This method support only one "sort" parameter'); + return API.v1.failure('This method support only one "sort" parameter'); } const sortBy = sort ? Object.keys(sort)[0] : undefined; const sortDirection = sort && Object.values(sort)[0] === 1 ? 'asc' : 'desc'; @@ -165,9 +169,9 @@ RocketChat.API.v1.addRoute('directory', { authRequired: true }, { })); if (!result) { - return RocketChat.API.v1.failure('Please verify the parameters'); + return API.v1.failure('Please verify the parameters'); } - return RocketChat.API.v1.success({ + return API.v1.success({ result: result.results, count: result.results.length, offset, diff --git a/packages/rocketchat-api/server/v1/permissions.js b/packages/rocketchat-api/server/v1/permissions.js index 4bbe0707336b..369c72a73909 100644 --- a/packages/rocketchat-api/server/v1/permissions.js +++ b/packages/rocketchat-api/server/v1/permissions.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Permissions, Roles } from 'meteor/rocketchat:models'; +import { API } from '../api'; /** This API returns all permissions that exists @@ -9,24 +11,24 @@ import { RocketChat } from 'meteor/rocketchat:lib'; Method: GET Route: api/v1/permissions */ -RocketChat.API.v1.addRoute('permissions', { authRequired: true }, { +API.v1.addRoute('permissions', { authRequired: true }, { get() { const warningMessage = 'The endpoint "permissions" is deprecated and will be removed after version v0.69'; console.warn(warningMessage); const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get')); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); // DEPRECATED // TODO: Remove this after three versions have been released. That means at 0.85 this should be gone. -RocketChat.API.v1.addRoute('permissions.list', { authRequired: true }, { +API.v1.addRoute('permissions.list', { authRequired: true }, { get() { const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get')); - return RocketChat.API.v1.success(this.deprecationWarning({ + return API.v1.success(this.deprecationWarning({ endpoint: 'permissions.list', versionWillBeRemove: '0.85', response: { @@ -36,7 +38,7 @@ RocketChat.API.v1.addRoute('permissions.list', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('permissions.listAll', { authRequired: true }, { +API.v1.addRoute('permissions.listAll', { authRequired: true }, { get() { const { updatedSince } = this.queryParams; @@ -59,14 +61,14 @@ RocketChat.API.v1.addRoute('permissions.listAll', { authRequired: true }, { }; } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, { +API.v1.addRoute('permissions.update', { authRequired: true }, { post() { - if (!RocketChat.authz.hasPermission(this.userId, 'access-permissions')) { - return RocketChat.API.v1.failure('Editing permissions is not allowed', 'error-edit-permissions-not-allowed'); + if (!hasPermission(this.userId, 'access-permissions')) { + return API.v1.failure('Editing permissions is not allowed', 'error-edit-permissions-not-allowed'); } check(this.bodyParams, { @@ -83,34 +85,34 @@ RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, { Object.keys(this.bodyParams.permissions).forEach((key) => { const element = this.bodyParams.permissions[key]; - if (!RocketChat.models.Permissions.findOneById(element._id)) { + if (!Permissions.findOneById(element._id)) { permissionNotFound = true; } Object.keys(element.roles).forEach((key) => { const subelement = element.roles[key]; - if (!RocketChat.models.Roles.findOneById(subelement)) { + if (!Roles.findOneById(subelement)) { roleNotFound = true; } }); }); if (permissionNotFound) { - return RocketChat.API.v1.failure('Invalid permission', 'error-invalid-permission'); + return API.v1.failure('Invalid permission', 'error-invalid-permission'); } else if (roleNotFound) { - return RocketChat.API.v1.failure('Invalid role', 'error-invalid-role'); + return API.v1.failure('Invalid role', 'error-invalid-role'); } Object.keys(this.bodyParams.permissions).forEach((key) => { const element = this.bodyParams.permissions[key]; - RocketChat.models.Permissions.createOrUpdate(element._id, element.roles); + Permissions.createOrUpdate(element._id, element.roles); }); const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get')); - return RocketChat.API.v1.success({ + return API.v1.success({ permissions: result, }); }, diff --git a/packages/rocketchat-api/server/v1/push.js b/packages/rocketchat-api/server/v1/push.js index 50b46f79e62a..fa5b2a70f652 100644 --- a/packages/rocketchat-api/server/v1/push.js +++ b/packages/rocketchat-api/server/v1/push.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Push } from 'meteor/rocketchat:push'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('push.token', { authRequired: true }, { +API.v1.addRoute('push.token', { authRequired: true }, { post() { const { type, value, appName } = this.bodyParams; let { id } = this.bodyParams; @@ -35,7 +35,7 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, { userId: this.userId, })); - return RocketChat.API.v1.success({ result }); + return API.v1.success({ result }); }, delete() { const { token } = this.bodyParams; @@ -54,9 +54,9 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, { }); if (affectedRecords === 0) { - return RocketChat.API.v1.notFound(); + return API.v1.notFound(); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/roles.js b/packages/rocketchat-api/server/v1/roles.js index 08addfb62d80..e7fba691e97b 100644 --- a/packages/rocketchat-api/server/v1/roles.js +++ b/packages/rocketchat-api/server/v1/roles.js @@ -1,16 +1,17 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Roles } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('roles.list', { authRequired: true }, { +API.v1.addRoute('roles.list', { authRequired: true }, { get() { - const roles = RocketChat.models.Roles.find({}, { fields: { _updatedAt: 0 } }).fetch(); + const roles = Roles.find({}, { fields: { _updatedAt: 0 } }).fetch(); - return RocketChat.API.v1.success({ roles }); + return API.v1.success({ roles }); }, }); -RocketChat.API.v1.addRoute('roles.create', { authRequired: true }, { +API.v1.addRoute('roles.create', { authRequired: true }, { post() { check(this.bodyParams, { name: String, @@ -28,13 +29,13 @@ RocketChat.API.v1.addRoute('roles.create', { authRequired: true }, { Meteor.call('authorization:saveRole', roleData); }); - return RocketChat.API.v1.success({ - role: RocketChat.models.Roles.findOneByIdOrName(roleData.name, { fields: RocketChat.API.v1.defaultFieldsToExclude }), + return API.v1.success({ + role: Roles.findOneByIdOrName(roleData.name, { fields: API.v1.defaultFieldsToExclude }), }); }, }); -RocketChat.API.v1.addRoute('roles.addUserToRole', { authRequired: true }, { +API.v1.addRoute('roles.addUserToRole', { authRequired: true }, { post() { check(this.bodyParams, { roleName: String, @@ -48,8 +49,8 @@ RocketChat.API.v1.addRoute('roles.addUserToRole', { authRequired: true }, { Meteor.call('authorization:addUserToRole', this.bodyParams.roleName, user.username, this.bodyParams.roomId); }); - return RocketChat.API.v1.success({ - role: RocketChat.models.Roles.findOneByIdOrName(this.bodyParams.roleName, { fields: RocketChat.API.v1.defaultFieldsToExclude }), + return API.v1.success({ + role: Roles.findOneByIdOrName(this.bodyParams.roleName, { fields: API.v1.defaultFieldsToExclude }), }); }, }); diff --git a/packages/rocketchat-api/server/v1/rooms.js b/packages/rocketchat-api/server/v1/rooms.js index b913fe18ea0e..9a0b99984f2d 100644 --- a/packages/rocketchat-api/server/v1/rooms.js +++ b/packages/rocketchat-api/server/v1/rooms.js @@ -1,20 +1,21 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Rooms } from 'meteor/rocketchat:models'; import Busboy from 'busboy'; +import { API } from '../api'; function findRoomByIdOrName({ params, checkedArchived = true }) { if ((!params.roomId || !params.roomId.trim()) && (!params.roomName || !params.roomName.trim())) { throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" or "roomName" is required'); } - const fields = { ...RocketChat.API.v1.defaultFieldsToExclude }; + const fields = { ...API.v1.defaultFieldsToExclude }; let room; if (params.roomId) { - room = RocketChat.models.Rooms.findOneById(params.roomId, { fields }); + room = Rooms.findOneById(params.roomId, { fields }); } else if (params.roomName) { - room = RocketChat.models.Rooms.findOneByName(params.roomName, { fields }); + room = Rooms.findOneByName(params.roomName, { fields }); } if (!room) { throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "roomName" param provided does not match any channel'); @@ -26,7 +27,7 @@ function findRoomByIdOrName({ params, checkedArchived = true }) { return room; } -RocketChat.API.v1.addRoute('rooms.get', { authRequired: true }, { +API.v1.addRoute('rooms.get', { authRequired: true }, { get() { const { updatedSince } = this.queryParams; @@ -49,19 +50,19 @@ RocketChat.API.v1.addRoute('rooms.get', { authRequired: true }, { }; } - return RocketChat.API.v1.success({ + return API.v1.success({ update: result.update.map((room) => this.composeRoomWithLastMessage(room, this.userId)), remove: result.remove.map((room) => this.composeRoomWithLastMessage(room, this.userId)), }); }, }); -RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { +API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { post() { const room = Meteor.call('canAccessRoom', this.urlParams.rid, this.userId); if (!room) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const busboy = new Busboy({ headers: this.request.headers }); @@ -90,11 +91,11 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { })(); 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]; @@ -116,14 +117,14 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { delete fields.description; - RocketChat.API.v1.success(Meteor.call('sendFileMessage', this.urlParams.rid, null, uploadedFile, fields)); + API.v1.success(Meteor.call('sendFileMessage', this.urlParams.rid, null, uploadedFile, fields)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, { +API.v1.addRoute('rooms.saveNotification', { authRequired: true }, { post() { const saveNotifications = (notifications, roomId) => { Object.keys(notifications).forEach((notificationKey) => @@ -135,45 +136,45 @@ RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, { const { roomId, notifications } = this.bodyParams; if (!roomId) { - return RocketChat.API.v1.failure('The \'roomId\' param is required'); + return API.v1.failure('The \'roomId\' param is required'); } if (!notifications || Object.keys(notifications).length === 0) { - return RocketChat.API.v1.failure('The \'notifications\' param is required'); + return API.v1.failure('The \'notifications\' param is required'); } saveNotifications(notifications, roomId); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.favorite', { authRequired: true }, { +API.v1.addRoute('rooms.favorite', { authRequired: true }, { post() { const { favorite } = this.bodyParams; if (!this.bodyParams.hasOwnProperty('favorite')) { - return RocketChat.API.v1.failure('The \'favorite\' param is required'); + return API.v1.failure('The \'favorite\' param is required'); } const room = findRoomByIdOrName({ params: this.bodyParams }); Meteor.runAsUser(this.userId, () => Meteor.call('toggleFavorite', room._id, favorite)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, { +API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, { post() { const findResult = findRoomByIdOrName({ params: this.bodyParams }); if (!this.bodyParams.latest) { - return RocketChat.API.v1.failure('Body parameter "latest" is required.'); + return API.v1.failure('Body parameter "latest" is required.'); } if (!this.bodyParams.oldest) { - return RocketChat.API.v1.failure('Body parameter "oldest" is required.'); + return API.v1.failure('Body parameter "oldest" is required.'); } const latest = new Date(this.bodyParams.latest); @@ -192,28 +193,28 @@ RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, { fromUsers: this.bodyParams.users, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.info', { authRequired: true }, { +API.v1.addRoute('rooms.info', { authRequired: true }, { get() { const room = findRoomByIdOrName({ params: this.requestParams() }); const { fields } = this.parseJsonQuery(); if (!Meteor.call('canAccessRoom', room._id, this.userId, {})) { - return RocketChat.API.v1.failure('not-allowed', 'Not Allowed'); + return API.v1.failure('not-allowed', 'Not Allowed'); } - return RocketChat.API.v1.success({ room: RocketChat.models.Rooms.findOneByIdOrName(room._id, { fields }) }); + return API.v1.success({ room: Rooms.findOneByIdOrName(room._id, { fields }) }); }, }); -RocketChat.API.v1.addRoute('rooms.leave', { authRequired: true }, { +API.v1.addRoute('rooms.leave', { authRequired: true }, { post() { const room = findRoomByIdOrName({ params: this.bodyParams }); Meteor.runAsUser(this.userId, () => { Meteor.call('leaveRoom', room._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/settings.js b/packages/rocketchat-api/server/v1/settings.js index 3ed2a54e11e8..5069a2278dd2 100644 --- a/packages/rocketchat-api/server/v1/settings.js +++ b/packages/rocketchat-api/server/v1/settings.js @@ -1,11 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { ServiceConfiguration } from 'meteor/service-configuration'; +import { Settings } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { API } from '../api'; import _ from 'underscore'; // settings endpoints -RocketChat.API.v1.addRoute('settings.public', { authRequired: false }, { +API.v1.addRoute('settings.public', { authRequired: false }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); @@ -17,23 +19,23 @@ RocketChat.API.v1.addRoute('settings.public', { authRequired: false }, { ourQuery = Object.assign({}, query, ourQuery); - const settings = RocketChat.models.Settings.find(ourQuery, { + const settings = Settings.find(ourQuery, { sort: sort ? sort : { _id: 1 }, skip: offset, limit: count, fields: Object.assign({ _id: 1, value: 1 }, fields), }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ settings, count: settings.length, offset, - total: RocketChat.models.Settings.find(ourQuery).count(), + total: Settings.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('settings.oauth', { authRequired: false }, { +API.v1.addRoute('settings.oauth', { authRequired: false }, { get() { const mountOAuthServices = () => { const oAuthServicesEnabled = ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch(); @@ -55,13 +57,13 @@ RocketChat.API.v1.addRoute('settings.oauth', { authRequired: false }, { }); }; - return RocketChat.API.v1.success({ + return API.v1.success({ services: mountOAuthServices(), }); }, }); -RocketChat.API.v1.addRoute('settings', { authRequired: true }, { +API.v1.addRoute('settings', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); @@ -70,71 +72,71 @@ RocketChat.API.v1.addRoute('settings', { authRequired: true }, { hidden: { $ne: true }, }; - if (!RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting')) { + if (!hasPermission(this.userId, 'view-privileged-setting')) { ourQuery.public = true; } ourQuery = Object.assign({}, query, ourQuery); - const settings = RocketChat.models.Settings.find(ourQuery, { + const settings = Settings.find(ourQuery, { sort: sort ? sort : { _id: 1 }, skip: offset, limit: count, fields: Object.assign({ _id: 1, value: 1 }, fields), }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ settings, count: settings.length, offset, - total: RocketChat.models.Settings.find(ourQuery).count(), + total: Settings.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('settings/:_id', { authRequired: true }, { +API.v1.addRoute('settings/:_id', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-privileged-setting')) { + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(_.pick(RocketChat.models.Settings.findOneNotHiddenById(this.urlParams._id), '_id', 'value')); + return API.v1.success(_.pick(Settings.findOneNotHiddenById(this.urlParams._id), '_id', 'value')); }, post() { - if (!RocketChat.authz.hasPermission(this.userId, 'edit-privileged-setting')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'edit-privileged-setting')) { + return API.v1.unauthorized(); } // allow special handling of particular setting types - const setting = RocketChat.models.Settings.findOneNotHiddenById(this.urlParams._id); + const setting = Settings.findOneNotHiddenById(this.urlParams._id); if (setting.type === 'action' && this.bodyParams && this.bodyParams.execute) { // execute the configured method Meteor.call(setting.value); - return RocketChat.API.v1.success(); + return API.v1.success(); } if (setting.type === 'color' && this.bodyParams && this.bodyParams.editor && this.bodyParams.value) { - RocketChat.models.Settings.updateOptionsById(this.urlParams._id, { editor: this.bodyParams.editor }); - RocketChat.models.Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value); - return RocketChat.API.v1.success(); + Settings.updateOptionsById(this.urlParams._id, { editor: this.bodyParams.editor }); + Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value); + return API.v1.success(); } check(this.bodyParams, { value: Match.Any, }); - if (RocketChat.models.Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value)) { - return RocketChat.API.v1.success(); + if (Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value)) { + return API.v1.success(); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); }, }); -RocketChat.API.v1.addRoute('service.configurations', { authRequired: false }, { +API.v1.addRoute('service.configurations', { authRequired: false }, { get() { const { ServiceConfiguration } = Package['service-configuration']; - return RocketChat.API.v1.success({ + return API.v1.success({ configurations: ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch(), }); }, diff --git a/packages/rocketchat-api/server/v1/stats.js b/packages/rocketchat-api/server/v1/stats.js index d21a1a66174c..05c10167eb9b 100644 --- a/packages/rocketchat-api/server/v1/stats.js +++ b/packages/rocketchat-api/server/v1/stats.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Statistics } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('statistics', { authRequired: true }, { +API.v1.addRoute('statistics', { authRequired: true }, { get() { let refresh = false; if (typeof this.queryParams.refresh !== 'undefined' && this.queryParams.refresh === 'true') { @@ -13,33 +15,33 @@ RocketChat.API.v1.addRoute('statistics', { authRequired: true }, { stats = Meteor.call('getStatistics', refresh); }); - return RocketChat.API.v1.success({ + return API.v1.success({ statistics: stats, }); }, }); -RocketChat.API.v1.addRoute('statistics.list', { authRequired: true }, { +API.v1.addRoute('statistics.list', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-statistics')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-statistics')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - const statistics = RocketChat.models.Statistics.find(query, { + const statistics = Statistics.find(query, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ statistics, count: statistics.length, offset, - total: RocketChat.models.Statistics.find(query).count(), + total: Statistics.find(query).count(), }); }, }); diff --git a/packages/rocketchat-api/server/v1/subscriptions.js b/packages/rocketchat-api/server/v1/subscriptions.js index 9f82c57cf90f..37568d1413ad 100644 --- a/packages/rocketchat-api/server/v1/subscriptions.js +++ b/packages/rocketchat-api/server/v1/subscriptions.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('subscriptions.get', { authRequired: true }, { +API.v1.addRoute('subscriptions.get', { authRequired: true }, { get() { const { updatedSince } = this.queryParams; @@ -25,21 +26,21 @@ RocketChat.API.v1.addRoute('subscriptions.get', { authRequired: true }, { }; } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, { +API.v1.addRoute('subscriptions.getOne', { authRequired: true }, { get() { const { roomId } = this.requestParams(); if (!roomId) { - return RocketChat.API.v1.failure('The \'roomId\' param is required'); + return API.v1.failure('The \'roomId\' param is required'); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId); + const subscription = Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId); - return RocketChat.API.v1.success({ + return API.v1.success({ subscription, }); }, @@ -53,7 +54,7 @@ RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, { Params: - rid: The rid of the room to be marked as read. */ -RocketChat.API.v1.addRoute('subscriptions.read', { authRequired: true }, { +API.v1.addRoute('subscriptions.read', { authRequired: true }, { post() { check(this.bodyParams, { rid: String, @@ -63,22 +64,22 @@ RocketChat.API.v1.addRoute('subscriptions.read', { authRequired: true }, { Meteor.call('readMessages', this.bodyParams.rid) ); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('subscriptions.unread', { authRequired: true }, { +API.v1.addRoute('subscriptions.unread', { authRequired: true }, { post() { const { roomId, firstUnreadMessage } = this.bodyParams; if (!roomId && (firstUnreadMessage && !firstUnreadMessage._id)) { - return RocketChat.API.v1.failure('At least one of "roomId" or "firstUnreadMessage._id" params is required'); + return API.v1.failure('At least one of "roomId" or "firstUnreadMessage._id" params is required'); } Meteor.runAsUser(this.userId, () => Meteor.call('unreadMessages', firstUnreadMessage, roomId) ); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/users.js b/packages/rocketchat-api/server/v1/users.js index 6969d74d7663..178f5d5d108a 100644 --- a/packages/rocketchat-api/server/v1/users.js +++ b/packages/rocketchat-api/server/v1/users.js @@ -1,11 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +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 { API } from '../api'; import _ from 'underscore'; import Busboy from 'busboy'; -RocketChat.API.v1.addRoute('users.create', { authRequired: true }, { +API.v1.addRoute('users.create', { authRequired: true }, { post() { check(this.bodyParams, { email: String, @@ -43,14 +47,14 @@ RocketChat.API.v1.addRoute('users.create', { authRequired: true }, { }); } - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(newUserId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(newUserId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.delete', { authRequired: true }, { +API.v1.addRoute('users.delete', { authRequired: true }, { post() { - if (!RocketChat.authz.hasPermission(this.userId, 'delete-user')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'delete-user')) { + return API.v1.unauthorized(); } const user = this.getUserFromParams(); @@ -59,17 +63,17 @@ RocketChat.API.v1.addRoute('users.delete', { authRequired: true }, { Meteor.call('deleteUser', user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, { +API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, { post() { const { password } = this.bodyParams; if (!password) { - return RocketChat.API.v1.failure('Body parameter "password" is required.'); + return API.v1.failure('Body parameter "password" is required.'); } - if (!RocketChat.settings.get('Accounts_AllowDeleteOwnAccount')) { + if (!settings.get('Accounts_AllowDeleteOwnAccount')) { throw new Meteor.Error('error-not-allowed', 'Not allowed'); } @@ -77,15 +81,15 @@ RocketChat.API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, { Meteor.call('deleteUserOwnAccount', password); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, { +API.v1.addRoute('users.getAvatar', { authRequired: false }, { get() { const user = this.getUserFromParams(); - const url = RocketChat.getURL(`/avatar/${ user.username }`, { cdn: false, full: true }); + const url = getURL(`/avatar/${ user.username }`, { cdn: false, full: true }); this.response.setHeader('Location', url); return { @@ -95,11 +99,11 @@ RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, { }, }); -RocketChat.API.v1.addRoute('users.getPresence', { authRequired: true }, { +API.v1.addRoute('users.getPresence', { authRequired: true }, { get() { if (this.isUserFromParams()) { - const user = RocketChat.models.Users.findOneById(this.userId); - return RocketChat.API.v1.success({ + const user = Users.findOneById(this.userId); + return API.v1.success({ presence: user.status, connectionStatus: user.statusConnection, lastLogin: user.lastLogin, @@ -108,13 +112,13 @@ RocketChat.API.v1.addRoute('users.getPresence', { authRequired: true }, { const user = this.getUserFromParams(); - return RocketChat.API.v1.success({ + return API.v1.success({ presence: user.status, }); }, }); -RocketChat.API.v1.addRoute('users.info', { authRequired: true }, { +API.v1.addRoute('users.info', { authRequired: true }, { get() { const { username } = this.getUserFromParams(); const { fields } = this.parseJsonQuery(); @@ -125,12 +129,12 @@ RocketChat.API.v1.addRoute('users.info', { authRequired: true }, { }); if (!result || result.length !== 1) { - return RocketChat.API.v1.failure(`Failed to get the user data for the userId of "${ username }".`); + return API.v1.failure(`Failed to get the user data for the userId of "${ username }".`); } user = result[0]; - if (fields.userRooms === 1 && RocketChat.authz.hasPermission(this.userId, 'view-other-user-channels')) { - user.rooms = RocketChat.models.Subscriptions.findByUserId(user._id, { + if (fields.userRooms === 1 && hasPermission(this.userId, 'view-other-user-channels')) { + user.rooms = Subscriptions.findByUserId(user._id, { fields: { rid: 1, name: 1, @@ -144,41 +148,41 @@ RocketChat.API.v1.addRoute('users.info', { authRequired: true }, { }).fetch(); } - return RocketChat.API.v1.success({ + return API.v1.success({ user, }); }, }); -RocketChat.API.v1.addRoute('users.list', { authRequired: true }, { +API.v1.addRoute('users.list', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-d-room')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-d-room')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - const users = RocketChat.models.Users.find(query, { + const users = Users.find(query, { sort: sort ? sort : { username: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ users, count: users.length, offset, - total: RocketChat.models.Users.find(query).count(), + total: Users.find(query).count(), }); }, }); -RocketChat.API.v1.addRoute('users.register', { authRequired: false }, { +API.v1.addRoute('users.register', { authRequired: false }, { post() { if (this.userId) { - return RocketChat.API.v1.failure('Logged in users can not register again.'); + return API.v1.failure('Logged in users can not register again.'); } // We set their username here, so require it @@ -188,7 +192,7 @@ RocketChat.API.v1.addRoute('users.register', { authRequired: false }, { })); if (!RocketChat.checkUsernameAvailability(this.bodyParams.username)) { - return RocketChat.API.v1.failure('Username is already in use'); + return API.v1.failure('Username is already in use'); } // Register the user @@ -197,27 +201,27 @@ RocketChat.API.v1.addRoute('users.register', { authRequired: false }, { // Now set their username Meteor.runAsUser(userId, () => Meteor.call('setUsername', this.bodyParams.username)); - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(userId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.resetAvatar', { authRequired: true }, { +API.v1.addRoute('users.resetAvatar', { authRequired: true }, { post() { const user = this.getUserFromParams(); if (user._id === this.userId) { Meteor.runAsUser(this.userId, () => Meteor.call('resetAvatar')); - } else if (RocketChat.authz.hasPermission(this.userId, 'edit-other-user-info')) { + } else if (hasPermission(this.userId, 'edit-other-user-info')) { Meteor.runAsUser(user._id, () => Meteor.call('resetAvatar')); } else { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { +API.v1.addRoute('users.setAvatar', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ avatarUrl: Match.Maybe(String), @@ -225,7 +229,7 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { username: Match.Maybe(String), })); - if (!RocketChat.settings.get('Accounts_AllowUserAvatarChange')) { + if (!settings.get('Accounts_AllowUserAvatarChange')) { throw new Meteor.Error('error-not-allowed', 'Change avatar is not allowed', { method: 'users.setAvatar', }); @@ -234,10 +238,10 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { let user; if (this.isUserFromParams()) { user = Meteor.users.findOne(this.userId); - } else if (RocketChat.authz.hasPermission(this.userId, 'edit-other-user-info')) { + } else if (hasPermission(this.userId, 'edit-other-user-info')) { user = this.getUserFromParams(); } else { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } Meteor.runAsUser(user._id, () => { @@ -248,10 +252,10 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { const fields = {}; const getUserFromFormData = (fields) => { if (fields.userId) { - return RocketChat.models.Users.findOneById(fields.userId, { _id: 1 }); + return Users.findOneById(fields.userId, { _id: 1 }); } if (fields.username) { - return RocketChat.models.Users.findOneByUsername(fields.username, { _id: 1 }); + return Users.findOneByUsername(fields.username, { _id: 1 }); } }; @@ -273,7 +277,7 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { return callback(new Meteor.Error('error-invalid-user', 'The optional "userId" or "username" param provided does not match any users')); } const isAnotherUser = this.userId !== user._id; - if (isAnotherUser && !RocketChat.authz.hasPermission(this.userId, 'edit-other-user-info')) { + if (isAnotherUser && !hasPermission(this.userId, 'edit-other-user-info')) { return callback(new Meteor.Error('error-not-allowed', 'Not allowed')); } } @@ -289,11 +293,11 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { } }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.update', { authRequired: true }, { +API.v1.addRoute('users.update', { authRequired: true }, { post() { check(this.bodyParams, { userId: String, @@ -326,11 +330,11 @@ RocketChat.API.v1.addRoute('users.update', { authRequired: true }, { }); } - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(this.bodyParams.userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(this.bodyParams.userId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, { +API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, { post() { check(this.bodyParams, { data: Match.ObjectIncluding({ @@ -353,38 +357,38 @@ RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('saveUserProfile', userData, this.bodyParams.customFields)); - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(this.userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(this.userId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.createToken', { authRequired: true }, { +API.v1.addRoute('users.createToken', { authRequired: true }, { post() { const user = this.getUserFromParams(); let data; Meteor.runAsUser(this.userId, () => { data = Meteor.call('createToken', user._id); }); - return data ? RocketChat.API.v1.success({ data }) : RocketChat.API.v1.unauthorized(); + return data ? API.v1.success({ data }) : API.v1.unauthorized(); }, }); -RocketChat.API.v1.addRoute('users.getPreferences', { authRequired: true }, { +API.v1.addRoute('users.getPreferences', { authRequired: true }, { get() { - const user = RocketChat.models.Users.findOneById(this.userId); + const user = Users.findOneById(this.userId); if (user.settings) { const { preferences } = user.settings; preferences.language = user.language; - return RocketChat.API.v1.success({ + return API.v1.success({ preferences, }); } else { - return RocketChat.API.v1.failure(TAPi18n.__('Accounts_Default_User_Preferences_not_available').toUpperCase()); + return API.v1.failure(TAPi18n.__('Accounts_Default_User_Preferences_not_available').toUpperCase()); } }, }); -RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, { +API.v1.addRoute('users.setPreferences', { authRequired: true }, { post() { check(this.bodyParams, { userId: Match.Maybe(String), @@ -437,14 +441,14 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, { } Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); - const user = RocketChat.models.Users.findOneById(userId, { + const user = Users.findOneById(userId, { fields: { 'settings.preferences': 1, language: 1, }, }); - return RocketChat.API.v1.success({ + return API.v1.success({ user: { _id: user._id, settings: { @@ -458,59 +462,59 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('users.forgotPassword', { authRequired: false }, { +API.v1.addRoute('users.forgotPassword', { authRequired: false }, { post() { const { email } = this.bodyParams; if (!email) { - return RocketChat.API.v1.failure('The \'email\' param is required'); + return API.v1.failure('The \'email\' param is required'); } const emailSent = Meteor.call('sendForgotPasswordEmail', email); if (emailSent) { - return RocketChat.API.v1.success(); + return API.v1.success(); } - return RocketChat.API.v1.failure('User not found'); + return API.v1.failure('User not found'); }, }); -RocketChat.API.v1.addRoute('users.getUsernameSuggestion', { authRequired: true }, { +API.v1.addRoute('users.getUsernameSuggestion', { authRequired: true }, { get() { const result = Meteor.runAsUser(this.userId, () => Meteor.call('getUsernameSuggestion')); - return RocketChat.API.v1.success({ result }); + return API.v1.success({ result }); }, }); -RocketChat.API.v1.addRoute('users.generatePersonalAccessToken', { authRequired: true }, { +API.v1.addRoute('users.generatePersonalAccessToken', { authRequired: true }, { post() { const { tokenName } = this.bodyParams; if (!tokenName) { - return RocketChat.API.v1.failure('The \'tokenName\' param is required'); + return API.v1.failure('The \'tokenName\' param is required'); } const token = Meteor.runAsUser(this.userId, () => Meteor.call('personalAccessTokens:generateToken', { tokenName })); - return RocketChat.API.v1.success({ token }); + return API.v1.success({ token }); }, }); -RocketChat.API.v1.addRoute('users.regeneratePersonalAccessToken', { authRequired: true }, { +API.v1.addRoute('users.regeneratePersonalAccessToken', { authRequired: true }, { post() { const { tokenName } = this.bodyParams; if (!tokenName) { - return RocketChat.API.v1.failure('The \'tokenName\' param is required'); + return API.v1.failure('The \'tokenName\' param is required'); } const token = Meteor.runAsUser(this.userId, () => Meteor.call('personalAccessTokens:regenerateToken', { tokenName })); - return RocketChat.API.v1.success({ token }); + return API.v1.success({ token }); }, }); -RocketChat.API.v1.addRoute('users.getPersonalAccessTokens', { authRequired: true }, { +API.v1.addRoute('users.getPersonalAccessTokens', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'create-personal-access-tokens')) { + if (!hasPermission(this.userId, 'create-personal-access-tokens')) { throw new Meteor.Error('not-authorized', 'Not Authorized'); } - const loginTokens = RocketChat.models.Users.getLoginTokensByUserId(this.userId).fetch()[0]; + const loginTokens = Users.getLoginTokensByUserId(this.userId).fetch()[0]; const getPersonalAccessTokens = () => loginTokens.services.resume.loginTokens .filter((loginToken) => loginToken.type && loginToken.type === 'personalAccessToken') .map((loginToken) => ({ @@ -519,22 +523,22 @@ RocketChat.API.v1.addRoute('users.getPersonalAccessTokens', { authRequired: true lastTokenPart: loginToken.lastTokenPart, })); - return RocketChat.API.v1.success({ + return API.v1.success({ tokens: loginTokens ? getPersonalAccessTokens() : [], }); }, }); -RocketChat.API.v1.addRoute('users.removePersonalAccessToken', { authRequired: true }, { +API.v1.addRoute('users.removePersonalAccessToken', { authRequired: true }, { post() { const { tokenName } = this.bodyParams; if (!tokenName) { - return RocketChat.API.v1.failure('The \'tokenName\' param is required'); + return API.v1.failure('The \'tokenName\' param is required'); } Meteor.runAsUser(this.userId, () => Meteor.call('personalAccessTokens:removeToken', { tokenName, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/video-conference.js b/packages/rocketchat-api/server/v1/video-conference.js index 1bcf0ce52581..020f38aac336 100644 --- a/packages/rocketchat-api/server/v1/video-conference.js +++ b/packages/rocketchat-api/server/v1/video-conference.js @@ -1,21 +1,21 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Rooms } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('video-conference/jitsi.update-timeout', { authRequired: true }, { +API.v1.addRoute('video-conference/jitsi.update-timeout', { authRequired: true }, { post() { const { roomId } = this.bodyParams; if (!roomId) { - return RocketChat.API.v1.failure('The "roomId" parameter is required!'); + return API.v1.failure('The "roomId" parameter is required!'); } const room = Rooms.findOneById(roomId); if (!room) { - return RocketChat.API.v1.failure('Room does not exist!'); + return API.v1.failure('Room does not exist!'); } Meteor.runAsUser(this.userId, () => Meteor.call('jitsi:updateTimeout', roomId)); - return RocketChat.API.v1.success({ jitsiTimeout: Rooms.findOneById(roomId).jitsiTimeout }); + return API.v1.success({ jitsiTimeout: Rooms.findOneById(roomId).jitsiTimeout }); }, }); From 06f62e6d17672401c0b7c170f67c5c18805d2db1 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 14:40:45 -0200 Subject: [PATCH 05/11] import API where it was being used by the RC namespace --- .../client/admin/appInstall.js | 9 +- .../rocketchat-apps/client/admin/appLogs.js | 5 +- .../rocketchat-apps/client/admin/appManage.js | 13 +-- packages/rocketchat-apps/client/admin/apps.js | 5 +- .../client/communication/websockets.js | 7 +- .../rocketchat-apps/client/orchestrator.js | 5 +- .../server/communication/rest.js | 83 ++++++++++--------- packages/rocketchat-graphql/package.js | 1 + .../resolvers/channels/createChannel.js | 7 +- .../client/admin/adminImportHistory.js | 3 +- .../client/admin/adminImportPrepare.js | 7 +- packages/rocketchat-importer/package.js | 1 + packages/rocketchat-integrations/package.js | 1 + .../rocketchat-integrations/server/api/api.js | 25 +++--- .../client/lib/RestApiClient.js | 3 - .../client/lib/startup/commands.js | 8 +- packages/rocketchat-lib/package.js | 1 - .../imports/server/rest/departments.js | 39 ++++----- .../imports/server/rest/facebook.js | 3 +- .../imports/server/rest/sms.js | 3 +- .../imports/server/rest/upload.js | 19 +++-- .../imports/server/rest/users.js | 43 +++++----- .../server/api/v1/agent.js | 13 +-- .../server/api/v1/config.js | 9 +- .../server/api/v1/customField.js | 15 ++-- .../server/api/v1/message.js | 45 +++++----- .../server/api/v1/offlineMessage.js | 9 +- .../server/api/v1/pageVisited.js | 9 +- .../rocketchat-livechat/server/api/v1/room.js | 31 +++---- .../server/api/v1/transcript.js | 9 +- .../server/api/v1/videoCall.js | 7 +- .../server/api/v1/visitor.js | 33 ++++---- packages/rocketchat-livestream/package.js | 1 + .../rocketchat-livestream/server/routes.js | 5 +- .../server/oauth/oauth2-server.js | 3 +- packages/rocketchat-videobridge/package.js | 1 + .../server/methods/bbb.js | 3 +- 37 files changed, 257 insertions(+), 227 deletions(-) delete mode 100644 packages/rocketchat-lib/client/lib/RestApiClient.js 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-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 c8f66f40ee41..4e66b5c7f70a 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -236,7 +236,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-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 e2e544cfec18..6e9f3d6e98fa 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,12 +145,12 @@ 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); } }, }); 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]; From cd1930c68c95bde892c8a454c94fc62ee7b1d643 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 14:43:33 -0200 Subject: [PATCH 06/11] Move processWebhookMessage function to rc-lib package --- .../server/processWebhookMessage.js | 87 +----------------- .../rocketchat-lib/server/functions/index.js | 1 + .../server/functions/processWebhookMessage.js | 88 +++++++++++++++++++ 3 files changed, 90 insertions(+), 86 deletions(-) create mode 100644 packages/rocketchat-lib/server/functions/processWebhookMessage.js 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/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; +}; From d7eab39d477982d9a1835a6a7750f3994c2e2e29 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 14:45:01 -0200 Subject: [PATCH 07/11] Remove API from RC namespace and import missing function that was being used with namespace --- .../client/lib/RestApiClient.js | 1 - packages/rocketchat-api/package.js | 1 - packages/rocketchat-api/server/api.js | 3 --- packages/rocketchat-api/server/v1/chat.js | 2 +- packages/rocketchat-api/server/v1/im.js | 4 +-- packages/rocketchat-api/server/v1/users.js | 26 ++++++++++++------- 6 files changed, 20 insertions(+), 17 deletions(-) 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 763dc8def581..655b06ca8764 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, From 59bbccc10a34d8caeae0c3ba5d0974d1e919bc44 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 15:58:07 -0200 Subject: [PATCH 08/11] Remove dependency of RC namespace in rc-graphql --- packages/rocketchat-graphql/package.js | 3 +++ packages/rocketchat-graphql/server/api.js | 10 +++++----- .../server/resolvers/channels/Channel-type.js | 14 +++++++------- .../server/resolvers/channels/channelByName.js | 4 ++-- .../server/resolvers/channels/channels.js | 4 ++-- .../server/resolvers/channels/channelsByUser.js | 8 ++++---- .../server/resolvers/channels/deleteChannel.js | 6 +++--- .../server/resolvers/channels/directChannel.js | 4 ++-- .../server/resolvers/channels/hideChannel.js | 6 +++--- .../server/resolvers/channels/leaveChannel.js | 4 ++-- .../server/resolvers/messages/Message-type.js | 10 +++++----- .../resolvers/messages/addReactionToMessage.js | 4 ++-- .../server/resolvers/messages/chatMessageAdded.js | 7 ++++--- .../server/resolvers/messages/deleteMessage.js | 4 ++-- .../server/resolvers/messages/editMessage.js | 6 +++--- .../server/resolvers/messages/messages.js | 10 +++++----- .../server/resolvers/messages/sendMessage.js | 2 +- .../server/resolvers/users/User-type.js | 8 ++++---- .../server/resolvers/users/setStatus.js | 6 +++--- packages/rocketchat-graphql/server/settings.js | 4 ++-- 20 files changed, 64 insertions(+), 60 deletions(-) diff --git a/packages/rocketchat-graphql/package.js b/packages/rocketchat-graphql/package.js index 33c25e41e4ce..8ed9547bc74e 100644 --- a/packages/rocketchat-graphql/package.js +++ b/packages/rocketchat-graphql/package.js @@ -11,6 +11,9 @@ Package.onUse(function(api) { 'ecmascript', 'http', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:settings', 'rocketchat:api', 'rocketchat:accounts', 'rocketchat:integrations', diff --git a/packages/rocketchat-graphql/server/api.js b/packages/rocketchat-graphql/server/api.js index f0079592d348..734e524a90e0 100644 --- a/packages/rocketchat-graphql/server/api.js +++ b/packages/rocketchat-graphql/server/api.js @@ -4,24 +4,24 @@ import { SubscriptionServer } from 'subscriptions-transport-ws'; import { execute, subscribe } from 'graphql'; import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import bodyParser from 'body-parser'; import express from 'express'; import cors from 'cors'; import { executableSchema } from './schema'; -const subscriptionPort = RocketChat.settings.get('Graphql_Subscription_Port') || 3100; +const subscriptionPort = settings.get('Graphql_Subscription_Port') || 3100; // the Meteor GraphQL server is an Express server const graphQLServer = express(); -if (RocketChat.settings.get('Graphql_CORS')) { +if (settings.get('Graphql_CORS')) { graphQLServer.use(cors()); } graphQLServer.use('/api/graphql', (req, res, next) => { - if (RocketChat.settings.get('Graphql_Enabled')) { + if (settings.get('Graphql_Enabled')) { next(); } else { res.status(400).send('Graphql is not enabled in this server'); @@ -52,7 +52,7 @@ graphQLServer.use( ); const startSubscriptionServer = () => { - if (RocketChat.settings.get('Graphql_Enabled')) { + if (settings.get('Graphql_Enabled')) { SubscriptionServer.create({ schema: executableSchema, execute, diff --git a/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js b/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js index 098a08f5a13d..39945c10923e 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Users } from 'meteor/rocketchat:models'; import property from 'lodash.property'; import schema from '../../schemas/channels/Channel-type.graphqls'; @@ -14,10 +14,10 @@ const resolver = { return root.name; }, members: (root) => { - const ids = RocketChat.models.Subscriptions.findByRoomIdWhenUserIdExists(root._id, { fields: { 'u._id': 1 } }) + const ids = Subscriptions.findByRoomIdWhenUserIdExists(root._id, { fields: { 'u._id': 1 } }) .fetch() .map((sub) => sub.u._id); - return RocketChat.models.Users.findByIds(ids).fetch(); + return Users.findByIds(ids).fetch(); }, owners: (root) => { // there might be no owner @@ -25,20 +25,20 @@ const resolver = { return; } - return [RocketChat.models.Users.findOneByUsername(root.u.username)]; + return [Users.findOneByUsername(root.u.username)]; }, - numberOfMembers: (root) => RocketChat.models.Subscriptions.findByRoomId(root._id).count(), + numberOfMembers: (root) => Subscriptions.findByRoomId(root._id).count(), numberOfMessages: property('msgs'), readOnly: (root) => root.ro === true, direct: (root) => root.t === 'd', privateChannel: (root) => root.t === 'p', favourite: (root, args, { user }) => { - const room = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); + const room = Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); return room && room.f === true; }, unseenMessages: (root, args, { user }) => { - const room = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); + const room = Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); return (room || {}).unread; }, diff --git a/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js b/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js index 8bf960126130..972cc609c543 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -12,7 +12,7 @@ const resolver = { t: 'c', }; - return RocketChat.models.Rooms.findOne(query, { + return Rooms.findOne(query, { fields: roomPublicFields, }); }), diff --git a/packages/rocketchat-graphql/server/resolvers/channels/channels.js b/packages/rocketchat-graphql/server/resolvers/channels/channels.js index f9341e88b700..d5ac90da4e56 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/channels.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/channels.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -44,7 +44,7 @@ const resolver = { } } - return RocketChat.models.Rooms.find(query, options).fetch(); + return Rooms.find(query, options).fetch(); }), }, }; diff --git a/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js b/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js index 4b42e4339072..1c94c3e93eb4 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -7,14 +7,14 @@ import schema from '../../schemas/channels/channelsByUser.graphqls'; const resolver = { Query: { channelsByUser: authenticated((root, { userId }) => { - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); if (!user) { throw new Error('No user'); } - const roomIds = RocketChat.models.Subscriptions.findByUserId(userId, { fields: { rid: 1 } }).fetch().map((s) => s.rid); - const rooms = RocketChat.models.Rooms.findByIds(roomIds, { + const roomIds = Subscriptions.findByUserId(userId, { fields: { rid: 1 } }).fetch().map((s) => s.rid); + const rooms = Rooms.findByIds(roomIds, { sort: { name: 1, }, diff --git a/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js index 88dca7097998..b53bdd9ea072 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/deleteChannel.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/channels/deleteChannel.graphqls'; const resolver = { Mutation: { deleteChannel: authenticated((root, { channelId }, { user }) => { - const channel = RocketChat.models.Rooms.findOne({ + const channel = Rooms.findOne({ _id: channelId, t: 'c', }); @@ -16,7 +16,7 @@ const resolver = { throw new Error('error-room-not-found', 'The required "channelId" param provided does not match any channel'); } - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); + const sub = Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); if (!sub) { throw new Error(`The user/callee is not in the channel "${ channel.name }.`); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js index bbecd45dbb33..bb3f1b4bb680 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -24,7 +24,7 @@ const resolver = { throw new Error('Use one of those fields: username, channelId'); } - return RocketChat.models.Rooms.findOne(query, { + return Rooms.findOne(query, { fields: roomPublicFields, }); }), diff --git a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js index 19088eaf9140..4c5ebc4a2bef 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:lib'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/hideChannel.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/channels/hideChannel.graphqls'; const resolver = { Mutation: { hideChannel: authenticated((root, args, { user }) => { - const channel = RocketChat.models.Rooms.findOne({ + const channel = Rooms.findOne({ _id: args.channelId, t: 'c', }); @@ -16,7 +16,7 @@ const resolver = { throw new Error('error-room-not-found', 'The required "channelId" param provided does not match any channel'); } - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); + const sub = Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); if (!sub) { throw new Error(`The user/callee is not in the channel "${ channel.name }.`); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js index 863ace8354f2..98b1bfe9eb57 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/leaveChannel.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/channels/leaveChannel.graphqls'; const resolver = { Mutation: { leaveChannel: authenticated((root, args, { user }) => { - const channel = RocketChat.models.Rooms.findOne({ + const channel = Rooms.findOne({ _id: args.channelId, t: 'c', }); diff --git a/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js b/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js index 036ad99d0b5a..0a81f1881b3f 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Users } from 'meteor/rocketchat:models'; import property from 'lodash.property'; import { dateToFloat } from '../../helpers/dateToFloat'; @@ -10,11 +10,11 @@ const resolver = { content: property('msg'), creationTime: (root) => dateToFloat(root.ts), author: (root) => { - const user = RocketChat.models.Users.findOne(root.u._id); + const user = Users.findOne(root.u._id); return user || root.u; }, - channel: (root) => RocketChat.models.Rooms.findOne(root.rid), + channel: (root) => Rooms.findOne(root.rid), fromServer: (root) => typeof root.t !== 'undefined', // on a message sent by user `true` otherwise `false` type: property('t'), channelRef: (root) => { @@ -22,7 +22,7 @@ const resolver = { return; } - return RocketChat.models.Rooms.find({ + return Rooms.find({ _id: { $in: root.channels.map((c) => c._id), }, @@ -37,7 +37,7 @@ const resolver = { return; } - return RocketChat.models.Users.find({ + return Users.find({ _id: { $in: root.mentions.map((c) => c._id), }, diff --git a/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js index 39022bacc104..3d9b035b7854 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/addReactionToMessage.graphqls'; @@ -9,7 +9,7 @@ const resolver = { addReactionToMessage: authenticated((root, { id, icon, shouldReact }, { user }) => new Promise((resolve) => { Meteor.runAsUser(user._id, () => { Meteor.call('setReaction', icon, id.messageId, shouldReact, () => { - resolve(RocketChat.models.Messages.findOne(id.messageId)); + resolve(Messages.findOne(id.messageId)); }); }); })), diff --git a/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js b/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js index 3e2aa1f067d5..9574e2a5c121 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js @@ -1,5 +1,6 @@ import { withFilter } from 'graphql-subscriptions'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { pubsub } from '../../subscriptions'; import { authenticated } from '../../helpers/authenticated'; @@ -15,7 +16,7 @@ function shouldPublish(message, { id, directTo }, username) { if (id) { return message.rid === id; } else if (directTo) { - const room = RocketChat.models.Rooms.findOne({ + const room = Rooms.findOne({ usernames: { $all: [directTo, username] }, t: 'd', }); @@ -41,7 +42,7 @@ const resolver = { }, }; -RocketChat.callbacks.add('afterSaveMessage', (message) => { +callbacks.add('afterSaveMessage', (message) => { publishMessage(message); }, null, 'chatMessageAddedSubscription'); diff --git a/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js index 779836a8b6b8..4ff8d1041b8a 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/deleteMessage.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/messages/deleteMessage.graphqls'; const resolver = { Mutation: { deleteMessage: authenticated((root, { id }, { user }) => { - const msg = RocketChat.models.Messages.findOneById(id.messageId, { fields: { u: 1, rid: 1 } }); + const msg = Messages.findOneById(id.messageId, { fields: { u: 1, rid: 1 } }); if (!msg) { throw new Error(`No message found with the id of "${ id.messageId }".`); diff --git a/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js index 45a8fedd33a4..7d22829d3275 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/editMessage.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/messages/editMessage.graphqls'; const resolver = { Mutation: { editMessage: authenticated((root, { id, content }, { user }) => { - const msg = RocketChat.models.Messages.findOneById(id.messageId); + const msg = Messages.findOneById(id.messageId); // Ensure the message exists if (!msg) { @@ -23,7 +23,7 @@ const resolver = { Meteor.call('updateMessage', { _id: msg._id, msg: content, rid: msg.rid }); }); - return RocketChat.models.Messages.findOneById(msg._id); + return Messages.findOneById(msg._id); }), }, }; diff --git a/packages/rocketchat-graphql/server/resolvers/messages/messages.js b/packages/rocketchat-graphql/server/resolvers/messages/messages.js index 71a51cbb4eec..c331024a75d6 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/messages.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/messages.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/messages.graphqls'; @@ -30,14 +30,14 @@ const resolver = { return null; } - const channel = RocketChat.models.Rooms.findOne(channelQuery); + const channel = Rooms.findOne(channelQuery); let messagesArray = []; if (channel) { // cursor if (isPagination && args.cursor) { - const cursorMsg = RocketChat.models.Messages.findOne(args.cursor, { fields: { ts: 1 } }); + const cursorMsg = Messages.findOne(args.cursor, { fields: { ts: 1 } }); messagesQuery.ts = { $lt: cursorMsg.ts }; } @@ -61,7 +61,7 @@ const resolver = { // look for messages that belongs to specific channel messagesQuery.rid = channel._id; - const messages = RocketChat.models.Messages.find(messagesQuery, messagesOptions); + const messages = Messages.find(messagesQuery, messagesOptions); messagesArray = messages.fetch(); @@ -69,7 +69,7 @@ const resolver = { // oldest first (because of findOne) messagesOptions.sort.ts = 1; - const firstMessage = RocketChat.models.Messages.findOne(messagesQuery, messagesOptions); + const firstMessage = Messages.findOne(messagesQuery, messagesOptions); const lastId = (messagesArray[messagesArray.length - 1] || {})._id; cursor = !lastId || lastId === firstMessage._id ? null : lastId; diff --git a/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js index 13cfe4a82f29..5759e67ad310 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js @@ -1,4 +1,4 @@ -import { processWebhookMessage } from 'meteor/rocketchat:integrations'; +import { processWebhookMessage } from 'meteor/rocketchat:lib'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/sendMessage.graphqls'; diff --git a/packages/rocketchat-graphql/server/resolvers/users/User-type.js b/packages/rocketchat-graphql/server/resolvers/users/User-type.js index ed35be4b3b31..243c8b1128ab 100644 --- a/packages/rocketchat-graphql/server/resolvers/users/User-type.js +++ b/packages/rocketchat-graphql/server/resolvers/users/User-type.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Avatars, Rooms } from 'meteor/rocketchat:models'; import property from 'lodash.property'; import schema from '../../schemas/users/User-type.graphqls'; @@ -10,7 +10,7 @@ const resolver = { status: ({ status }) => status.toUpperCase(), avatar: async({ _id }) => { // XXX js-accounts/graphql#16 - const avatar = await RocketChat.models.Avatars.model.rawCollection().findOne({ + const avatar = await Avatars.model.rawCollection().findOne({ userId: _id, }, { fields: { url: 1 } }); @@ -18,8 +18,8 @@ const resolver = { return avatar.url; } }, - channels: Meteor.bindEnvironment(async({ _id }) => await RocketChat.models.Rooms.findBySubscriptionUserId(_id).fetch()), - directMessages: ({ username }) => RocketChat.models.Rooms.findDirectRoomContainingUsername(username).fetch(), + channels: Meteor.bindEnvironment(async({ _id }) => await Rooms.findBySubscriptionUserId(_id).fetch()), + directMessages: ({ username }) => Rooms.findDirectRoomContainingUsername(username).fetch(), }, }; diff --git a/packages/rocketchat-graphql/server/resolvers/users/setStatus.js b/packages/rocketchat-graphql/server/resolvers/users/setStatus.js index 1649929c7ce3..862b8abdbed3 100644 --- a/packages/rocketchat-graphql/server/resolvers/users/setStatus.js +++ b/packages/rocketchat-graphql/server/resolvers/users/setStatus.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/users/setStatus.graphqls'; @@ -6,13 +6,13 @@ import schema from '../../schemas/users/setStatus.graphqls'; const resolver = { Mutation: { setStatus: authenticated((root, { status }, { user }) => { - RocketChat.models.Users.update(user._id, { + Users.update(user._id, { $set: { status: status.toLowerCase(), }, }); - return RocketChat.models.Users.findOne(user._id); + return Users.findOne(user._id); }), }, }; diff --git a/packages/rocketchat-graphql/server/settings.js b/packages/rocketchat-graphql/server/settings.js index de2735d15995..56f285ed0023 100644 --- a/packages/rocketchat-graphql/server/settings.js +++ b/packages/rocketchat-graphql/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.section('GraphQL API', function() { this.add('Graphql_Enabled', false, { type: 'boolean', public: false }); this.add('Graphql_CORS', true, { type: 'boolean', public: false, enableQuery: { _id: 'Graphql_Enabled', value: true } }); From e90ab248f2df5f7b94c02b92c81237ef9d4a6a63 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 16:03:49 -0200 Subject: [PATCH 09/11] Fix import from wrong package --- .../rocketchat-graphql/server/resolvers/channels/hideChannel.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js index 4c5ebc4a2bef..221ae7377fd1 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { Rooms, Subscriptions } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/hideChannel.graphqls'; From fd4f74c5f43254de559801c02fba2634c08e8a5a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 16:19:49 -0200 Subject: [PATCH 10/11] Remove dependency of RC namespace in rc-importer --- .../client/ImporterWebsocketReceiver.js | 4 +-- .../client/admin/adminImport.js | 6 ++-- .../client/admin/adminImportHistory.js | 4 +-- .../client/admin/adminImportPrepare.js | 9 +++--- .../client/admin/adminImportProgress.js | 3 +- packages/rocketchat-importer/package.js | 4 +++ .../server/classes/ImporterBase.js | 29 ++++++++++--------- .../methods/downloadPublicImportFile.js | 3 +- .../server/methods/getImportFileData.js | 3 +- .../server/methods/getImportProgress.js | 4 +-- .../methods/getLatestImportOperations.js | 3 +- .../server/methods/getSelectionData.js | 4 +-- .../server/methods/prepareImport.js | 4 +-- .../server/methods/restartImport.js | 4 +-- .../server/methods/setupImporter.js | 4 +-- .../server/methods/startImport.js | 4 +-- .../server/methods/uploadImportFile.js | 3 +- .../server/models/Imports.js | 4 +-- .../server/models/RawImports.js | 4 +-- .../server/startup/store.js | 7 +++-- 20 files changed, 60 insertions(+), 50 deletions(-) diff --git a/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js b/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js index 7c0d52e781be..6751dff6689f 100644 --- a/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js +++ b/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { CachedCollectionManager } from 'meteor/rocketchat:ui-cached-collection'; class ImporterWebsocketReceiverDef { constructor() { this.streamer = new Meteor.Streamer('importers'); this.callbacks = []; - RocketChat.CachedCollectionManager.onLogin(() => { + CachedCollectionManager.onLogin(() => { this.streamer.on('progress', this.progressUpdated.bind(this)); }); } diff --git a/packages/rocketchat-importer/client/admin/adminImport.js b/packages/rocketchat-importer/client/admin/adminImport.js index 71ecda141480..0dbc3a5d63c6 100644 --- a/packages/rocketchat-importer/client/admin/adminImport.js +++ b/packages/rocketchat-importer/client/admin/adminImport.js @@ -3,12 +3,12 @@ import { Importers } from 'meteor/rocketchat:importer'; import { FlowRouter } from 'meteor/kadira:flow-router'; 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 { hasRole } from 'meteor/rocketchat:authorization'; +import { t, handleError } from 'meteor/rocketchat:utils'; Template.adminImport.helpers({ isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, getDescription(importer) { return TAPi18n.__('Importer_From_Description', { from: importer.name }); diff --git a/packages/rocketchat-importer/client/admin/adminImportHistory.js b/packages/rocketchat-importer/client/admin/adminImportHistory.js index 76f81a877753..9a33fd86ec99 100644 --- a/packages/rocketchat-importer/client/admin/adminImportHistory.js +++ b/packages/rocketchat-importer/client/admin/adminImportHistory.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; import { ReactiveVar } from 'meteor/reactive-var'; @@ -11,7 +11,7 @@ import { API } from 'meteor/rocketchat:api'; Template.adminImportHistory.helpers({ isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, importers() { return Importers.getAll(); diff --git a/packages/rocketchat-importer/client/admin/adminImportPrepare.js b/packages/rocketchat-importer/client/admin/adminImportPrepare.js index b58c95f61697..ff98bd19bc35 100644 --- a/packages/rocketchat-importer/client/admin/adminImportPrepare.js +++ b/packages/rocketchat-importer/client/admin/adminImportPrepare.js @@ -4,14 +4,15 @@ import { Importers } from 'meteor/rocketchat:importer'; import { FlowRouter } from 'meteor/kadira:flow-router'; 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 { hasRole } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { t, handleError } from 'meteor/rocketchat:utils'; import { API } from 'meteor/rocketchat:api'; import toastr from 'toastr'; Template.adminImportPrepare.helpers({ isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, importer() { const importerKey = FlowRouter.getParam('importer'); @@ -34,7 +35,7 @@ Template.adminImportPrepare.helpers({ return Template.instance().message_count.get(); }, fileSizeLimitMessage() { - const maxFileSize = RocketChat.settings.get('FileUpload_MaxFileSize'); + const maxFileSize = settings.get('FileUpload_MaxFileSize'); let message; if (maxFileSize > 0) { diff --git a/packages/rocketchat-importer/client/admin/adminImportProgress.js b/packages/rocketchat-importer/client/admin/adminImportProgress.js index 4c18ca511268..e3571a946a3d 100644 --- a/packages/rocketchat-importer/client/admin/adminImportProgress.js +++ b/packages/rocketchat-importer/client/admin/adminImportProgress.js @@ -3,8 +3,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Importers, ImporterWebsocketReceiver, ProgressStep } from 'meteor/rocketchat:importer'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { t } from 'meteor/rocketchat:utils'; -import { handleError } from 'meteor/rocketchat:lib'; +import { t, handleError } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; Template.adminImportProgress.helpers({ diff --git a/packages/rocketchat-importer/package.js b/packages/rocketchat-importer/package.js index 71fe8869d538..a936d939ea15 100644 --- a/packages/rocketchat-importer/package.js +++ b/packages/rocketchat-importer/package.js @@ -12,6 +12,10 @@ Package.onUse(function(api) { 'check', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:authorization', + 'rocketchat:ui-cached-collection', + 'rocketchat:settings', 'rocketchat:api', 'rocketchat:logger', 'rocketchat:file-upload', diff --git a/packages/rocketchat-importer/server/classes/ImporterBase.js b/packages/rocketchat-importer/server/classes/ImporterBase.js index 036161e3ffd6..a7853c1cc73b 100644 --- a/packages/rocketchat-importer/server/classes/ImporterBase.js +++ b/packages/rocketchat-importer/server/classes/ImporterBase.js @@ -6,9 +6,10 @@ import { Imports } from '../models/Imports'; import { ImporterInfo } from '../../lib/ImporterInfo'; import { RawImports } from '../models/RawImports'; import { ImporterWebsocket } from './ImporterWebsocket'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Settings } from 'meteor/rocketchat:models'; import { Logger } from 'meteor/rocketchat:logger'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { sendMessage } from 'meteor/rocketchat:lib'; import http from 'http'; import fs from 'fs'; import https from 'https'; @@ -230,24 +231,24 @@ export class Base { switch (step) { case ProgressStep.IMPORTING_STARTED: - this.oldSettings.Accounts_AllowedDomainsList = RocketChat.models.Settings.findOneById('Accounts_AllowedDomainsList').value; - RocketChat.models.Settings.updateValueById('Accounts_AllowedDomainsList', ''); + this.oldSettings.Accounts_AllowedDomainsList = Settings.findOneById('Accounts_AllowedDomainsList').value; + Settings.updateValueById('Accounts_AllowedDomainsList', ''); - this.oldSettings.Accounts_AllowUsernameChange = RocketChat.models.Settings.findOneById('Accounts_AllowUsernameChange').value; - RocketChat.models.Settings.updateValueById('Accounts_AllowUsernameChange', true); + this.oldSettings.Accounts_AllowUsernameChange = Settings.findOneById('Accounts_AllowUsernameChange').value; + Settings.updateValueById('Accounts_AllowUsernameChange', true); - this.oldSettings.FileUpload_MaxFileSize = RocketChat.models.Settings.findOneById('FileUpload_MaxFileSize').value; - RocketChat.models.Settings.updateValueById('FileUpload_MaxFileSize', -1); + this.oldSettings.FileUpload_MaxFileSize = Settings.findOneById('FileUpload_MaxFileSize').value; + Settings.updateValueById('FileUpload_MaxFileSize', -1); - this.oldSettings.FileUpload_MediaTypeWhiteList = RocketChat.models.Settings.findOneById('FileUpload_MediaTypeWhiteList').value; - RocketChat.models.Settings.updateValueById('FileUpload_MediaTypeWhiteList', '*'); + this.oldSettings.FileUpload_MediaTypeWhiteList = Settings.findOneById('FileUpload_MediaTypeWhiteList').value; + Settings.updateValueById('FileUpload_MediaTypeWhiteList', '*'); break; case ProgressStep.DONE: case ProgressStep.ERROR: - RocketChat.models.Settings.updateValueById('Accounts_AllowedDomainsList', this.oldSettings.Accounts_AllowedDomainsList); - RocketChat.models.Settings.updateValueById('Accounts_AllowUsernameChange', this.oldSettings.Accounts_AllowUsernameChange); - RocketChat.models.Settings.updateValueById('FileUpload_MaxFileSize', this.oldSettings.FileUpload_MaxFileSize); - RocketChat.models.Settings.updateValueById('FileUpload_MediaTypeWhiteList', this.oldSettings.FileUpload_MediaTypeWhiteList); + Settings.updateValueById('Accounts_AllowedDomainsList', this.oldSettings.Accounts_AllowedDomainsList); + Settings.updateValueById('Accounts_AllowUsernameChange', this.oldSettings.Accounts_AllowUsernameChange); + Settings.updateValueById('FileUpload_MaxFileSize', this.oldSettings.FileUpload_MaxFileSize); + Settings.updateValueById('FileUpload_MediaTypeWhiteList', this.oldSettings.FileUpload_MediaTypeWhiteList); break; } @@ -421,7 +422,7 @@ export class Base { msg._id = details.message_id; } - return RocketChat.sendMessage(user, msg, room, true); + return sendMessage(user, msg, room, true); } }); })); diff --git a/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js b/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js index 1f44d7a99d80..d45d3c7f2caa 100644 --- a/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js +++ b/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; import { RocketChatImportFileInstance } from '../startup/store'; import { ProgressStep } from '../../lib/ImporterProgressStep'; +import { hasRole } from 'meteor/rocketchat:authorization'; import http from 'http'; import fs from 'fs'; @@ -24,7 +25,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'downloadPublicImportFile' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'downloadPublicImportFile' }); } diff --git a/packages/rocketchat-importer/server/methods/getImportFileData.js b/packages/rocketchat-importer/server/methods/getImportFileData.js index 6e143aca2f8d..a58ffaec2235 100644 --- a/packages/rocketchat-importer/server/methods/getImportFileData.js +++ b/packages/rocketchat-importer/server/methods/getImportFileData.js @@ -1,6 +1,7 @@ import { RocketChatImportFileInstance } from '../startup/store'; import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; +import { hasRole } from 'meteor/rocketchat:authorization'; import { ProgressStep } from '../../lib/ImporterProgressStep'; import path from 'path'; @@ -12,7 +13,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getImportFileData' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'getImportFileData' }); } diff --git a/packages/rocketchat-importer/server/methods/getImportProgress.js b/packages/rocketchat-importer/server/methods/getImportProgress.js index 145003b24278..db5b8a9439a8 100644 --- a/packages/rocketchat-importer/server/methods/getImportProgress.js +++ b/packages/rocketchat-importer/server/methods/getImportProgress.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ getImportProgress(key) { @@ -8,7 +8,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getImportProgress' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/getLatestImportOperations.js b/packages/rocketchat-importer/server/methods/getLatestImportOperations.js index c6977dbc2727..78e83721c845 100644 --- a/packages/rocketchat-importer/server/methods/getLatestImportOperations.js +++ b/packages/rocketchat-importer/server/methods/getLatestImportOperations.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Imports } from '../models/Imports'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ getLatestImportOperations() { @@ -9,7 +10,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getLatestImportOperations' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'getLatestImportOperations' }); } diff --git a/packages/rocketchat-importer/server/methods/getSelectionData.js b/packages/rocketchat-importer/server/methods/getSelectionData.js index c8ff1f625949..e24a6d3819ac 100644 --- a/packages/rocketchat-importer/server/methods/getSelectionData.js +++ b/packages/rocketchat-importer/server/methods/getSelectionData.js @@ -3,7 +3,7 @@ import { Importers, ProgressStep, } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ getSelectionData(key) { @@ -11,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getSelectionData' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/prepareImport.js b/packages/rocketchat-importer/server/methods/prepareImport.js index 8f9c7e06036b..7a3677a4ac07 100644 --- a/packages/rocketchat-importer/server/methods/prepareImport.js +++ b/packages/rocketchat-importer/server/methods/prepareImport.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Importers } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ prepareImport(key, dataURI, contentType, fileName) { @@ -9,7 +9,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'prepareImport' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/restartImport.js b/packages/rocketchat-importer/server/methods/restartImport.js index 508fdaa352b0..e2c6733bf144 100644 --- a/packages/rocketchat-importer/server/methods/restartImport.js +++ b/packages/rocketchat-importer/server/methods/restartImport.js @@ -3,7 +3,7 @@ import { Importers, ProgressStep, } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ restartImport(key) { @@ -11,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'restartImport' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/setupImporter.js b/packages/rocketchat-importer/server/methods/setupImporter.js index 2498b8d950c1..5aac8afdbffe 100644 --- a/packages/rocketchat-importer/server/methods/setupImporter.js +++ b/packages/rocketchat-importer/server/methods/setupImporter.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ setupImporter(key) { @@ -8,7 +8,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setupImporter' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/startImport.js b/packages/rocketchat-importer/server/methods/startImport.js index 38a7911178ef..49ecfdfa7e9b 100644 --- a/packages/rocketchat-importer/server/methods/startImport.js +++ b/packages/rocketchat-importer/server/methods/startImport.js @@ -5,7 +5,7 @@ import { SelectionChannel, SelectionUser, } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ startImport(key, input) { @@ -14,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'startImport' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'startImport' }); } diff --git a/packages/rocketchat-importer/server/methods/uploadImportFile.js b/packages/rocketchat-importer/server/methods/uploadImportFile.js index ded0e5c3ab83..c2166e8ae736 100644 --- a/packages/rocketchat-importer/server/methods/uploadImportFile.js +++ b/packages/rocketchat-importer/server/methods/uploadImportFile.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; import { RocketChatFile } from 'meteor/rocketchat:file'; import { RocketChatImportFileInstance } from '../startup/store'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ uploadImportFile(binaryContent, contentType, fileName, importerKey) { @@ -11,7 +12,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'uploadImportFile' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'uploadImportFile' }); } diff --git a/packages/rocketchat-importer/server/models/Imports.js b/packages/rocketchat-importer/server/models/Imports.js index 06e06a5bab08..a50b27ddf963 100644 --- a/packages/rocketchat-importer/server/models/Imports.js +++ b/packages/rocketchat-importer/server/models/Imports.js @@ -1,7 +1,7 @@ import { ProgressStep } from '../../lib/ImporterProgressStep'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from 'meteor/rocketchat:models'; -class ImportsModel extends RocketChat.models._Base { +class ImportsModel extends Base { constructor() { super('import'); } diff --git a/packages/rocketchat-importer/server/models/RawImports.js b/packages/rocketchat-importer/server/models/RawImports.js index 3b850d80c6a9..3a761eb15dc4 100644 --- a/packages/rocketchat-importer/server/models/RawImports.js +++ b/packages/rocketchat-importer/server/models/RawImports.js @@ -1,6 +1,6 @@ -import { Base as _Base } from 'meteor/rocketchat:models'; +import { Base } from 'meteor/rocketchat:models'; -class RawImportsModel extends _Base { +class RawImportsModel extends Base { constructor() { super('raw_imports'); } diff --git a/packages/rocketchat-importer/server/startup/store.js b/packages/rocketchat-importer/server/startup/store.js index d996b1e9af2e..afe6b66139c5 100644 --- a/packages/rocketchat-importer/server/startup/store.js +++ b/packages/rocketchat-importer/server/startup/store.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { RocketChatFile } from 'meteor/rocketchat:file'; +import { settings } from 'meteor/rocketchat:settings'; export let RocketChatImportFileInstance; @@ -7,9 +8,9 @@ Meteor.startup(function() { const RocketChatStore = RocketChatFile.FileSystem; let path = '/tmp/rocketchat-importer'; - if (RocketChat.settings.get('ImportFile_FileSystemPath') != null) { - if (RocketChat.settings.get('ImportFile_FileSystemPath').trim() !== '') { - path = RocketChat.settings.get('ImportFile_FileSystemPath'); + if (settings.get('ImportFile_FileSystemPath') != null) { + if (settings.get('ImportFile_FileSystemPath').trim() !== '') { + path = settings.get('ImportFile_FileSystemPath'); } } From d39b6cd993d891f8f5b9733fd1db2b5821bf531d Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 13:50:01 -0200 Subject: [PATCH 11/11] Remove namespace in the new livechat endpoint --- packages/rocketchat-livechat/server/api/v1/room.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/rocketchat-livechat/server/api/v1/room.js b/packages/rocketchat-livechat/server/api/v1/room.js index 5f80d84aa59b..d21bbc13f6bb 100644 --- a/packages/rocketchat-livechat/server/api/v1/room.js +++ b/packages/rocketchat-livechat/server/api/v1/room.js @@ -155,8 +155,8 @@ API.v1.addRoute('livechat/room.survey', { }, }); -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))); }, });