From 171754ec0f941089facfac02a827a4a29b46240c Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Mon, 21 Jan 2019 17:01:40 -0200 Subject: [PATCH 01/33] Remove some dependencies inside rocketchat-lib/client (#13210) * Move function to rc-utils * Change import from to export directly * Removing duplicated dependency and remove old code * Import some variables to remove dependency of RC namespace --- .../client/CustomTranslations.js | 23 ++------ packages/rocketchat-lib/client/OAuthProxy.js | 7 +-- packages/rocketchat-lib/client/UserDeleted.js | 3 +- .../rocketchat-lib/client/defaultTabBars.js | 19 ++++--- .../client/lib/LoginPresence.js | 3 +- .../rocketchat-lib/client/lib/formatDate.js | 13 +++-- .../rocketchat-lib/client/lib/openRoom.js | 17 +++--- .../rocketchat-lib/client/lib/roomExit.js | 3 +- .../rocketchat-lib/client/lib/settings.js | 8 +-- .../client/lib/startup/commands.js | 3 +- .../rocketchat-lib/client/lib/userRoles.js | 4 +- .../client/methods/sendMessage.js | 13 +++-- .../client/views/customFieldsForm.js | 5 +- .../rocketchat-lib/lib/getUserPreference.js | 19 +------ packages/rocketchat-lib/package.js | 1 - packages/rocketchat-utils/client/index.js | 52 ++++++------------- .../client/lib/CustomTranslations.js | 21 ++++++++ 17 files changed, 101 insertions(+), 113 deletions(-) create mode 100644 packages/rocketchat-utils/client/lib/CustomTranslations.js diff --git a/packages/rocketchat-lib/client/CustomTranslations.js b/packages/rocketchat-lib/client/CustomTranslations.js index c895e26b6820..f3e9760d9d50 100644 --- a/packages/rocketchat-lib/client/CustomTranslations.js +++ b/packages/rocketchat-lib/client/CustomTranslations.js @@ -1,32 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { Session } from 'meteor/session'; import { TAPi18n } from 'meteor/tap:i18n'; -import { TAPi18next } from 'meteor/tap:i18n'; +import { applyCustomTranslations } from 'meteor/rocketchat:utils'; import { Tracker } from 'meteor/tracker'; -RocketChat.applyCustomTranslations = function applyCustomTranslations() { - let CustomTranslations = RocketChat.settings.get('Custom_Translations'); - if (typeof CustomTranslations === 'string' && CustomTranslations.trim() !== '') { - try { - CustomTranslations = JSON.parse(CustomTranslations); - - for (const lang in CustomTranslations) { - if (CustomTranslations.hasOwnProperty(lang)) { - const translations = CustomTranslations[lang]; - TAPi18next.addResourceBundle(lang, 'project', translations); - } - } - TAPi18n._language_changed_tracker.changed(); - } catch (e) { - console.error('Invalid setting Custom_Translations', e); - } - } -}; +RocketChat.applyCustomTranslations = applyCustomTranslations; Meteor.startup(function() { Tracker.autorun(function() { // Re apply translations if tap language was changed Session.get(TAPi18n._loaded_lang_session_key); - RocketChat.applyCustomTranslations(); + applyCustomTranslations(); }); }); diff --git a/packages/rocketchat-lib/client/OAuthProxy.js b/packages/rocketchat-lib/client/OAuthProxy.js index a923d3dded88..ac6a5ec33c91 100644 --- a/packages/rocketchat-lib/client/OAuthProxy.js +++ b/packages/rocketchat-lib/client/OAuthProxy.js @@ -1,13 +1,14 @@ import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; +import { settings } from 'meteor/rocketchat:settings'; OAuth.launchLogin = _.wrap(OAuth.launchLogin, function(func, options) { - const proxy = RocketChat.settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(','); + const proxy = settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(','); if (proxy.includes(options.loginService)) { const redirect_uri = options.loginUrl.match(/(&redirect_uri=)([^&]+|$)/)[2]; - options.loginUrl = options.loginUrl.replace(/(&redirect_uri=)([^&]+|$)/, `$1${ encodeURIComponent(RocketChat.settings.get('Accounts_OAuth_Proxy_host')) }/oauth_redirect`); + options.loginUrl = options.loginUrl.replace(/(&redirect_uri=)([^&]+|$)/, `$1${ encodeURIComponent(settings.get('Accounts_OAuth_Proxy_host')) }/oauth_redirect`); options.loginUrl = options.loginUrl.replace(/(&state=)([^&]+|$)/, `$1${ redirect_uri }!$2`); - options.loginUrl = `${ RocketChat.settings.get('Accounts_OAuth_Proxy_host') }/redirect/${ encodeURIComponent(options.loginUrl) }`; + options.loginUrl = `${ settings.get('Accounts_OAuth_Proxy_host') }/redirect/${ encodeURIComponent(options.loginUrl) }`; } return func(options); diff --git a/packages/rocketchat-lib/client/UserDeleted.js b/packages/rocketchat-lib/client/UserDeleted.js index 28eab20ce97f..ae7da4f57f94 100644 --- a/packages/rocketchat-lib/client/UserDeleted.js +++ b/packages/rocketchat-lib/client/UserDeleted.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { ChatMessage } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; Meteor.startup(function() { - RocketChat.Notifications.onLogged('Users:Deleted', ({ userId }) => + Notifications.onLogged('Users:Deleted', ({ userId }) => ChatMessage.remove({ 'u._id': userId, }) diff --git a/packages/rocketchat-lib/client/defaultTabBars.js b/packages/rocketchat-lib/client/defaultTabBars.js index 8ee2470b030d..fbb91f0da612 100644 --- a/packages/rocketchat-lib/client/defaultTabBars.js +++ b/packages/rocketchat-lib/client/defaultTabBars.js @@ -1,6 +1,9 @@ import { Session } from 'meteor/session'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; +import { Rooms } from 'meteor/rocketchat:models'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; -RocketChat.TabBar.addButton({ +TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'rocket-search', i18nTitle: 'Search_Messages', @@ -9,7 +12,7 @@ RocketChat.TabBar.addButton({ order: 1, }); -RocketChat.TabBar.addButton({ +TabBar.addButton({ groups: ['direct'], id: 'user-info', i18nTitle: 'User_Info', @@ -18,7 +21,7 @@ RocketChat.TabBar.addButton({ order: 2, }); -RocketChat.TabBar.addButton({ +TabBar.addButton({ groups: ['channel', 'group'], id: 'members-list', i18nTitle: 'Members_List', @@ -27,7 +30,7 @@ RocketChat.TabBar.addButton({ order: 2, condition() { const rid = Session.get('openedRoom'); - const room = RocketChat.models.Rooms.findOne({ + const room = Rooms.findOne({ _id: rid, }); @@ -35,11 +38,11 @@ RocketChat.TabBar.addButton({ return true; } - return RocketChat.authz.hasAllPermission('view-broadcast-member-list', rid); + return hasAllPermission('view-broadcast-member-list', rid); }, }); -RocketChat.TabBar.addButton({ +TabBar.addButton({ groups: ['channel', 'group'], id: 'addUsers', i18nTitle: 'Add_users', @@ -49,7 +52,7 @@ RocketChat.TabBar.addButton({ }); -RocketChat.TabBar.addButton({ +TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'uploaded-files-list', i18nTitle: 'Room_uploaded_file_list', @@ -58,7 +61,7 @@ RocketChat.TabBar.addButton({ order: 3, }); -RocketChat.TabBar.addButton({ +TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'keyboard-shortcut-list', i18nTitle: 'Keyboard_Shortcuts_Title', diff --git a/packages/rocketchat-lib/client/lib/LoginPresence.js b/packages/rocketchat-lib/client/lib/LoginPresence.js index 1f621d333c24..e33e020f53c4 100644 --- a/packages/rocketchat-lib/client/lib/LoginPresence.js +++ b/packages/rocketchat-lib/client/lib/LoginPresence.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; export const LoginPresence = { awayTime: 600000, // 10 minutes @@ -17,7 +18,7 @@ export const LoginPresence = { disconnect() { const status = Meteor.status(); if (status && status.status !== 'offline') { - if (!Meteor.userId() && RocketChat.settings.get('Accounts_AllowAnonymousRead') !== true) { + if (!Meteor.userId() && settings.get('Accounts_AllowAnonymousRead') !== true) { Meteor.disconnect(); } } diff --git a/packages/rocketchat-lib/client/lib/formatDate.js b/packages/rocketchat-lib/client/lib/formatDate.js index c6b34aef96a5..d264fb339585 100644 --- a/packages/rocketchat-lib/client/lib/formatDate.js +++ b/packages/rocketchat-lib/client/lib/formatDate.js @@ -1,25 +1,28 @@ import { Meteor } from 'meteor/meteor'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; import moment from 'moment'; + export const formatTime = (time) => { - switch (RocketChat.getUserPreference(Meteor.userId(), 'clockMode', false)) { + switch (getUserPreference(Meteor.userId(), 'clockMode', false)) { case 1: return moment(time).format('h:mm A'); case 2: return moment(time).format('H:mm'); default: - return moment(time).format(RocketChat.settings.get('Message_TimeFormat')); + return moment(time).format(settings.get('Message_TimeFormat')); } }; export const formatDateAndTime = (time) => { - switch (RocketChat.getUserPreference(Meteor.userId(), 'clockMode', false)) { + switch (getUserPreference(Meteor.userId(), 'clockMode', false)) { case 1: return moment(time).format('MMMM D, Y h:mm A'); case 2: return moment(time).format('MMMM D, Y H:mm'); default: - return moment(time).format(RocketChat.settings.get('Message_TimeAndDateFormat')); + return moment(time).format(settings.get('Message_TimeAndDateFormat')); } }; -export const formatDate = (time) => moment(time).format(RocketChat.settings.get('Message_DateFormat')); +export const formatDate = (time) => moment(time).format(settings.get('Message_DateFormat')); diff --git a/packages/rocketchat-lib/client/lib/openRoom.js b/packages/rocketchat-lib/client/lib/openRoom.js index 9be03e45dfcc..2ba6f4b4788f 100644 --- a/packages/rocketchat-lib/client/lib/openRoom.js +++ b/packages/rocketchat-lib/client/lib/openRoom.js @@ -3,8 +3,11 @@ import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { Session } from 'meteor/session'; -import { RoomManager, fireGlobalEvent, readMessage, RoomHistoryManager } from 'meteor/rocketchat:ui-utils'; -import { ChatSubscription } from 'meteor/rocketchat:models'; +import { RoomManager, fireGlobalEvent, readMessage, RoomHistoryManager, Layout } from 'meteor/rocketchat:ui-utils'; +import { ChatSubscription, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { roomTypes, handleError } from 'meteor/rocketchat:utils'; import _ from 'underscore'; export let currentTracker = undefined; @@ -15,13 +18,13 @@ openRoom = function(type, name) { return Meteor.defer(() => currentTracker = Tracker.autorun(function(c) { const user = Meteor.user(); - if ((user && user.username == null) || (user == null && RocketChat.settings.get('Accounts_AllowAnonymousRead') === false)) { + if ((user && user.username == null) || (user == null && settings.get('Accounts_AllowAnonymousRead') === false)) { BlazeLayout.render('main'); return; } if (RoomManager.open(type + name).ready() !== true) { - BlazeLayout.render('main', { modal: RocketChat.Layout.isEmbedded(), center: 'loading' }); + BlazeLayout.render('main', { modal: Layout.isEmbedded(), center: 'loading' }); return; } if (currentTracker) { @@ -29,7 +32,7 @@ openRoom = function(type, name) { } c.stop(); - const room = RocketChat.roomTypes.findRoom(type, name, user); + const room = roomTypes.findRoom(type, name, user); if (room == null) { if (type === 'd') { Meteor.call('createDirectMessage', name, function(error) { @@ -48,7 +51,7 @@ openRoom = function(type, name) { Session.set('roomNotFound', { type, name, error }); return BlazeLayout.render('main', { center: 'roomNotFound' }); } else { - RocketChat.models.Rooms.upsert({ _id: record._id }, _.omit(record, '_id')); + Rooms.upsert({ _id: record._id }, _.omit(record, '_id')); RoomManager.close(type + name); return openRoom(type, name); } @@ -93,7 +96,7 @@ openRoom = function(type, name) { RoomHistoryManager.getSurroundingMessages(msg); } - return RocketChat.callbacks.run('enter-room', sub); + return callbacks.run('enter-room', sub); }) ); }; diff --git a/packages/rocketchat-lib/client/lib/roomExit.js b/packages/rocketchat-lib/client/lib/roomExit.js index fabf375a6769..28bbfefa6c56 100644 --- a/packages/rocketchat-lib/client/lib/roomExit.js +++ b/packages/rocketchat-lib/client/lib/roomExit.js @@ -1,5 +1,6 @@ import { Blaze } from 'meteor/blaze'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { currentTracker } from './openRoom'; this.roomExit = function() { @@ -11,7 +12,7 @@ this.roomExit = function() { templateData && templateData.tabBar && templateData.tabBar.close(); } } - RocketChat.callbacks.run('roomExit'); + callbacks.run('roomExit'); BlazeLayout.render('main', { center: 'none', }); diff --git a/packages/rocketchat-lib/client/lib/settings.js b/packages/rocketchat-lib/client/lib/settings.js index e21d20b3f9ef..2acfd04d8b77 100644 --- a/packages/rocketchat-lib/client/lib/settings.js +++ b/packages/rocketchat-lib/client/lib/settings.js @@ -2,14 +2,16 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { t } from 'meteor/rocketchat:utils'; import { modal } from 'meteor/rocketchat:ui-utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.startup(function() { Tracker.autorun(function(c) { - const siteUrl = RocketChat.settings.get('Site_Url'); + const siteUrl = settings.get('Site_Url'); if (!siteUrl || (Meteor.userId() == null)) { return; } - if (RocketChat.authz.hasRole(Meteor.userId(), 'admin') === false || Meteor.settings.public.sandstorm) { + if (hasRole(Meteor.userId(), 'admin') === false || Meteor.settings.public.sandstorm) { return c.stop(); } Meteor.setTimeout(function() { @@ -36,7 +38,7 @@ Meteor.startup(function() { }); } }, 100); - const documentDomain = RocketChat.settings.get('Document_Domain'); + const documentDomain = settings.get('Document_Domain'); if (documentDomain) { window.document.domain = documentDomain; } diff --git a/packages/rocketchat-lib/client/lib/startup/commands.js b/packages/rocketchat-lib/client/lib/startup/commands.js index 2c4d90b86a3f..35cc4960da43 100644 --- a/packages/rocketchat-lib/client/lib/startup/commands.js +++ b/packages/rocketchat-lib/client/lib/startup/commands.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; +import { slashCommands } from 'meteor/rocketchat:utils'; // Track logins and when they login, get the commands (() => { @@ -10,7 +11,7 @@ import { Tracker } from 'meteor/tracker'; if (oldUserId === null && newUserId) { RocketChat.API.v1.get('commands.list').then(function _loadedCommands(result) { result.commands.forEach((command) => { - RocketChat.slashCommands.commands[command.command] = command; + slashCommands.commands[command.command] = command; }); }); } diff --git a/packages/rocketchat-lib/client/lib/userRoles.js b/packages/rocketchat-lib/client/lib/userRoles.js index ac95cb914a3b..579467929bf4 100644 --- a/packages/rocketchat-lib/client/lib/userRoles.js +++ b/packages/rocketchat-lib/client/lib/userRoles.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { UserRoles, RoomRoles, ChatMessage } from 'meteor/rocketchat:models'; +import { handleError } from 'meteor/rocketchat:utils'; +import { Notifications } from 'meteor/rocketchat:notifications'; Meteor.startup(function() { Tracker.autorun(function() { @@ -15,7 +17,7 @@ Meteor.startup(function() { } }); - RocketChat.Notifications.onLogged('roles-change', function(role) { + Notifications.onLogged('roles-change', function(role) { if (role.type === 'added') { if (role.scope) { RoomRoles.upsert({ rid: role.scope, 'u._id': role.u._id }, { $setOnInsert: { u: role.u }, $addToSet: { roles: role._id } }); diff --git a/packages/rocketchat-lib/client/methods/sendMessage.js b/packages/rocketchat-lib/client/methods/sendMessage.js index bf34d84c72b8..45f2f3af250b 100644 --- a/packages/rocketchat-lib/client/methods/sendMessage.js +++ b/packages/rocketchat-lib/client/methods/sendMessage.js @@ -1,6 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { TimeSync } from 'meteor/mizzao:timesync'; import { ChatMessage } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { promises } from 'meteor/rocketchat:promises'; import s from 'underscore.string'; Meteor.methods({ @@ -14,17 +17,17 @@ Meteor.methods({ _id: Meteor.userId(), username: user.username, }; - if (RocketChat.settings.get('UI_Use_Real_Name')) { + if (settings.get('UI_Use_Real_Name')) { message.u.name = user.name; } message.temp = true; - if (RocketChat.settings.get('Message_Read_Receipt_Enabled')) { + if (settings.get('Message_Read_Receipt_Enabled')) { message.unread = true; } - message = RocketChat.callbacks.run('beforeSaveMessage', message); - RocketChat.promises.run('onClientMessageReceived', message).then(function(message) { + message = callbacks.run('beforeSaveMessage', message); + promises.run('onClientMessageReceived', message).then(function(message) { ChatMessage.insert(message); - return RocketChat.callbacks.run('afterSaveMessage', message); + return callbacks.run('afterSaveMessage', message); }); }, }); diff --git a/packages/rocketchat-lib/client/views/customFieldsForm.js b/packages/rocketchat-lib/client/views/customFieldsForm.js index 52949d9eb722..aea80865ed20 100644 --- a/packages/rocketchat-lib/client/views/customFieldsForm.js +++ b/packages/rocketchat-lib/client/views/customFieldsForm.js @@ -1,6 +1,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; +import { settings } from 'meteor/rocketchat:settings'; Template.customFieldsForm.helpers({ new() { @@ -52,10 +53,10 @@ Template.customFieldsForm.onCreated(function() { this.formData = (currentData && currentData.formData) || {}; Tracker.autorun(() => { - const Accounts_CustomFields = RocketChat.settings.get('Accounts_CustomFields'); + const Accounts_CustomFields = settings.get('Accounts_CustomFields'); if (typeof Accounts_CustomFields === 'string' && Accounts_CustomFields.trim() !== '') { try { - this.customFields.set(JSON.parse(RocketChat.settings.get('Accounts_CustomFields'))); + this.customFields.set(JSON.parse(settings.get('Accounts_CustomFields'))); } catch (e) { console.error('Invalid JSON for Accounts_CustomFields'); } diff --git a/packages/rocketchat-lib/lib/getUserPreference.js b/packages/rocketchat-lib/lib/getUserPreference.js index 4037d3517cf9..a9c0f14e6a7a 100644 --- a/packages/rocketchat-lib/lib/getUserPreference.js +++ b/packages/rocketchat-lib/lib/getUserPreference.js @@ -1,18 +1,3 @@ -/** - * Tries to retrieve the user preference falling back to a default system - * value or to a default value if it is passed as argument -*/ -RocketChat.getUserPreference = function(user, key, defaultValue = undefined) { - let preference; - if (typeof user === typeof '') { - user = RocketChat.models.Users.findOne(user, { fields: { [`settings.preferences.${ key }`]: 1 } }); - } - if (user && user.settings && user.settings.preferences && - user.settings.preferences.hasOwnProperty(key)) { - preference = user.settings.preferences[key]; - } else if (defaultValue === undefined) { - preference = RocketChat.settings.get(`Accounts_Default_User_Preferences_${ key }`); - } +import { getUserPreference } from 'meteor/rocketchat:utils'; - return preference !== undefined ? preference : defaultValue; -}; +RocketChat.getUserPreference = getUserPreference; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index b7ebecbd8118..9784e41bedd6 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -36,7 +36,6 @@ Package.onUse(function(api) { api.use('rocketchat:emoji'); api.use('rocketchat:ui'); api.use('rocketchat:accounts'); - api.use('rocketchat:ui'); api.use('modules'); api.use('rocketchat:i18n'); api.use('rocketchat:streamer'); diff --git a/packages/rocketchat-utils/client/index.js b/packages/rocketchat-utils/client/index.js index 46e4fcde8708..97d18ad672b7 100644 --- a/packages/rocketchat-utils/client/index.js +++ b/packages/rocketchat-utils/client/index.js @@ -1,37 +1,15 @@ -import { t, isRtl } from '../lib/tapi18n'; -import { isChrome, isFirefox } from './lib/browsers'; -import { getDefaultSubscriptionPref } from '../lib/getDefaultSubscriptionPref'; -import { Info } from '../rocketchat.info'; -import { isEmail } from '../lib/isEmail'; -import { handleError } from './lib/handleError'; -import { getUserPreference } from '../lib/getUserPreference'; -import { fileUploadMediaWhiteList, fileUploadIsValidContentType } from '../lib/fileUploadRestrictions'; -import { roomTypes } from './lib/roomTypes'; -import { RoomTypeRouteConfig, RoomTypeConfig, RoomSettingsEnum, UiTextContext } from '../lib/RoomTypeConfig'; -import { RoomTypesCommon } from '../lib/RoomTypesCommon'; -import { getAvatarUrlFromUsername } from '../lib/getAvatarUrlFromUsername'; -import { slashCommands } from '../lib/slashCommand'; -import { getUserNotificationPreference } from '../lib/getUserNotificationPreference'; - -export { - t, - isRtl, - isChrome, - isFirefox, - getDefaultSubscriptionPref, - Info, - isEmail, - handleError, - getUserPreference, - fileUploadIsValidContentType, - fileUploadMediaWhiteList, - roomTypes, - RoomTypeRouteConfig, - RoomTypesCommon, - RoomTypeConfig, - RoomSettingsEnum, - UiTextContext, - getAvatarUrlFromUsername, - slashCommands, - getUserNotificationPreference, -}; +export { t, isRtl } from '../lib/tapi18n'; +export { isChrome, isFirefox } from './lib/browsers'; +export { getDefaultSubscriptionPref } from '../lib/getDefaultSubscriptionPref'; +export { Info } from '../rocketchat.info'; +export { isEmail } from '../lib/isEmail'; +export { handleError } from './lib/handleError'; +export { getUserPreference } from '../lib/getUserPreference'; +export { fileUploadMediaWhiteList, fileUploadIsValidContentType } from '../lib/fileUploadRestrictions'; +export { roomTypes } from './lib/roomTypes'; +export { RoomTypeRouteConfig, RoomTypeConfig, RoomSettingsEnum, UiTextContext } from '../lib/RoomTypeConfig'; +export { RoomTypesCommon } from '../lib/RoomTypesCommon'; +export { getAvatarUrlFromUsername } from '../lib/getAvatarUrlFromUsername'; +export { slashCommands } from '../lib/slashCommand'; +export { getUserNotificationPreference } from '../lib/getUserNotificationPreference'; +export { applyCustomTranslations } from './lib/CustomTranslations'; diff --git a/packages/rocketchat-utils/client/lib/CustomTranslations.js b/packages/rocketchat-utils/client/lib/CustomTranslations.js new file mode 100644 index 000000000000..0f424a13f2b7 --- /dev/null +++ b/packages/rocketchat-utils/client/lib/CustomTranslations.js @@ -0,0 +1,21 @@ +import { TAPi18n, TAPi18next } from 'meteor/tap:i18n'; +import { settings } from 'meteor/rocketchat:settings'; + +export function applyCustomTranslations() { + let CustomTranslations = settings.get('Custom_Translations'); + if (typeof CustomTranslations === 'string' && CustomTranslations.trim() !== '') { + try { + CustomTranslations = JSON.parse(CustomTranslations); + + for (const lang in CustomTranslations) { + if (CustomTranslations.hasOwnProperty(lang)) { + const translations = CustomTranslations[lang]; + TAPi18next.addResourceBundle(lang, 'project', translations); + } + } + TAPi18n._language_changed_tracker.changed(); + } catch (e) { + console.error('Invalid setting Custom_Translations', e); + } + } +} From f536345f17afc3922b74fd987c6abb557d0f9e2c Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Mon, 21 Jan 2019 17:50:50 -0200 Subject: [PATCH 02/33] Remove some dependencies inside rocketchat-lib/lib (#13212) * Move some functions from lib to rc-ui-utils * Move some functions from lib ro rc-utils * Remove hostname from RC namespace * Import variables to remove dependency of RC namespace --- packages/rocketchat-grant/server/grant.js | 5 +- .../rocketchat-lib/client/lib/openRoom.js | 103 +----------------- .../rocketchat-lib/client/lib/roomExit.js | 2 +- packages/rocketchat-lib/lib/Message.js | 33 +----- packages/rocketchat-lib/lib/MessageTypes.js | 31 +++--- packages/rocketchat-lib/lib/core.js | 3 +- packages/rocketchat-lib/lib/getAvatarColor.js | 6 +- packages/rocketchat-lib/lib/getURL.js | 22 +--- .../rocketchat-lib/lib/getValidRoomName.js | 50 +-------- packages/rocketchat-lib/lib/placeholders.js | 33 +----- .../lib/roomTypes/conversation.js | 3 +- .../rocketchat-lib/lib/roomTypes/direct.js | 28 +++-- .../rocketchat-lib/lib/roomTypes/favorite.js | 4 +- .../rocketchat-lib/lib/roomTypes/private.js | 16 ++- .../rocketchat-lib/lib/roomTypes/public.js | 14 ++- .../rocketchat-lib/lib/roomTypes/unread.js | 3 +- .../lib/startup/settingsOnLoadSiteUrl.js | 7 +- packages/rocketchat-lib/server/lib/index.js | 1 + packages/rocketchat-ui-utils/client/index.js | 2 + .../client/lib/openRoom.js | 102 +++++++++++++++++ packages/rocketchat-ui-utils/lib/Message.js | 34 ++++++ packages/rocketchat-ui-utils/package.js | 2 + packages/rocketchat-ui-utils/server/index.js | 1 + packages/rocketchat-utils/client/index.js | 4 + .../rocketchat-utils/lib/getAvatarColor.js | 3 + packages/rocketchat-utils/lib/getURL.js | 22 ++++ .../rocketchat-utils/lib/getValidRoomName.js | 51 +++++++++ packages/rocketchat-utils/lib/placeholders.js | 32 ++++++ packages/rocketchat-utils/server/index.js | 48 +++----- 29 files changed, 349 insertions(+), 316 deletions(-) create mode 100644 packages/rocketchat-ui-utils/client/lib/openRoom.js create mode 100644 packages/rocketchat-ui-utils/lib/Message.js create mode 100644 packages/rocketchat-utils/lib/getAvatarColor.js create mode 100644 packages/rocketchat-utils/lib/getURL.js create mode 100644 packages/rocketchat-utils/lib/getValidRoomName.js create mode 100644 packages/rocketchat-utils/lib/placeholders.js diff --git a/packages/rocketchat-grant/server/grant.js b/packages/rocketchat-grant/server/grant.js index 7cb9e29b63d9..b6a6e1d41885 100644 --- a/packages/rocketchat-grant/server/grant.js +++ b/packages/rocketchat-grant/server/grant.js @@ -1,5 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { hostname } from 'meteor/rocketchat:lib'; import Providers from './providers'; import Settings from './settings'; import { path, generateCallback, generateAppCallback } from './routes'; @@ -38,7 +37,7 @@ const config = {}; export function generateConfig() { config.server = { protocol: 'http', - host: RocketChat.hostname, + host: hostname, path, state: true, }; diff --git a/packages/rocketchat-lib/client/lib/openRoom.js b/packages/rocketchat-lib/client/lib/openRoom.js index 2ba6f4b4788f..e44424c18a83 100644 --- a/packages/rocketchat-lib/client/lib/openRoom.js +++ b/packages/rocketchat-lib/client/lib/openRoom.js @@ -1,102 +1,3 @@ -import { Meteor } from 'meteor/meteor'; -import { Tracker } from 'meteor/tracker'; -import { FlowRouter } from 'meteor/kadira:flow-router'; -import { BlazeLayout } from 'meteor/kadira:blaze-layout'; -import { Session } from 'meteor/session'; -import { RoomManager, fireGlobalEvent, readMessage, RoomHistoryManager, Layout } from 'meteor/rocketchat:ui-utils'; -import { ChatSubscription, Rooms } from 'meteor/rocketchat:models'; -import { settings } from 'meteor/rocketchat:settings'; -import { callbacks } from 'meteor/rocketchat:callbacks'; -import { roomTypes, handleError } from 'meteor/rocketchat:utils'; -import _ from 'underscore'; +import { openRoom as _openRoom } from 'meteor/rocketchat:ui-utils'; -export let currentTracker = undefined; - -openRoom = function(type, name) { - Session.set('openedRoom', null); - - return Meteor.defer(() => - currentTracker = Tracker.autorun(function(c) { - const user = Meteor.user(); - if ((user && user.username == null) || (user == null && settings.get('Accounts_AllowAnonymousRead') === false)) { - BlazeLayout.render('main'); - return; - } - - if (RoomManager.open(type + name).ready() !== true) { - BlazeLayout.render('main', { modal: Layout.isEmbedded(), center: 'loading' }); - return; - } - if (currentTracker) { - currentTracker = undefined; - } - c.stop(); - - const room = roomTypes.findRoom(type, name, user); - if (room == null) { - if (type === 'd') { - Meteor.call('createDirectMessage', name, function(error) { - if (!error) { - RoomManager.close(type + name); - return openRoom('d', name); - } else { - Session.set('roomNotFound', { type, name, error }); - BlazeLayout.render('main', { center: 'roomNotFound' }); - return; - } - }); - } else { - Meteor.call('getRoomByTypeAndName', type, name, function(error, record) { - if (error) { - Session.set('roomNotFound', { type, name, error }); - return BlazeLayout.render('main', { center: 'roomNotFound' }); - } else { - Rooms.upsert({ _id: record._id }, _.omit(record, '_id')); - RoomManager.close(type + name); - return openRoom(type, name); - } - }); - } - return; - } - - const mainNode = document.querySelector('.main-content'); - if (mainNode) { - for (const child of Array.from(mainNode.children)) { - if (child) { mainNode.removeChild(child); } - } - const roomDom = RoomManager.getDomOfRoom(type + name, room._id); - mainNode.appendChild(roomDom); - if (roomDom.classList.contains('room-container')) { - roomDom.querySelector('.messages-box > .wrapper').scrollTop = roomDom.oldScrollTop; - } - } - - Session.set('openedRoom', room._id); - RoomManager.openedRoom = room._id; - - fireGlobalEvent('room-opened', _.omit(room, 'usernames')); - - Session.set('editRoomTitle', false); - RoomManager.updateMentionsMarksOfRoom(type + name); - Meteor.setTimeout(() => readMessage.readNow(), 2000); - // KonchatNotification.removeRoomNotification(params._id) - // update user's room subscription - const sub = ChatSubscription.findOne({ rid: room._id }); - if (sub && sub.open === false) { - Meteor.call('openRoom', room._id, function(err) { - if (err) { - return handleError(err); - } - }); - } - - if (FlowRouter.getQueryParam('msg')) { - const msg = { _id: FlowRouter.getQueryParam('msg'), rid: room._id }; - RoomHistoryManager.getSurroundingMessages(msg); - } - - return callbacks.run('enter-room', sub); - }) - ); -}; +openRoom = _openRoom; diff --git a/packages/rocketchat-lib/client/lib/roomExit.js b/packages/rocketchat-lib/client/lib/roomExit.js index 28bbfefa6c56..89139fc589bc 100644 --- a/packages/rocketchat-lib/client/lib/roomExit.js +++ b/packages/rocketchat-lib/client/lib/roomExit.js @@ -1,7 +1,7 @@ import { Blaze } from 'meteor/blaze'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { callbacks } from 'meteor/rocketchat:callbacks'; -import { currentTracker } from './openRoom'; +import { currentTracker } from 'meteor/rocketchat:ui-utils'; this.roomExit = function() { // 7370 - Close flex-tab when opening a room on mobile UI diff --git a/packages/rocketchat-lib/lib/Message.js b/packages/rocketchat-lib/lib/Message.js index dbe0c18470a2..01cffb19bb53 100644 --- a/packages/rocketchat-lib/lib/Message.js +++ b/packages/rocketchat-lib/lib/Message.js @@ -1,32 +1,3 @@ -import { TAPi18n } from 'meteor/tap:i18n'; -import s from 'underscore.string'; +import { Message } from 'meteor/rocketchat:ui-utils'; -RocketChat.Message = { - parse(msg, language) { - const messageType = RocketChat.MessageTypes.getType(msg); - if (messageType) { - if (messageType.render) { - return messageType.render(msg); - } else if (messageType.template) { - // Render message - return; - } else if (messageType.message) { - if (!language && typeof localStorage !== 'undefined') { - language = localStorage.getItem('userLanguage'); - } - const data = (typeof messageType.data === 'function' && messageType.data(msg)) || {}; - return TAPi18n.__(messageType.message, data, language); - } - } - if (msg.u && msg.u.username === RocketChat.settings.get('Chatops_Username')) { - msg.html = msg.msg; - return msg.html; - } - msg.html = msg.msg; - if (s.trim(msg.html) !== '') { - msg.html = s.escapeHTML(msg.html); - } - msg.html = msg.html.replace(/\n/gm, '
'); - return msg.html; - }, -}; +RocketChat.Message = Message; diff --git a/packages/rocketchat-lib/lib/MessageTypes.js b/packages/rocketchat-lib/lib/MessageTypes.js index 6e773f5d54ab..95fc06858614 100644 --- a/packages/rocketchat-lib/lib/MessageTypes.js +++ b/packages/rocketchat-lib/lib/MessageTypes.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { MessageTypes } from 'meteor/rocketchat:ui-utils'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.MessageTypes = MessageTypes; Meteor.startup(function() { - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'r', system: true, message: 'Room_name_changed', @@ -15,7 +16,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'au', system: true, message: 'User_added_by', @@ -26,7 +27,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'ru', system: true, message: 'User_removed_by', @@ -37,7 +38,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'ul', system: true, message: 'User_left', @@ -47,7 +48,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'uj', system: true, message: 'User_joined_channel', @@ -57,7 +58,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'wm', system: true, message: 'Welcome', @@ -67,7 +68,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'rm', system: true, message: 'Message_removed', @@ -77,13 +78,13 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'rtc', render(message) { - return RocketChat.callbacks.run('renderRtcMessage', message); + return callbacks.run('renderRtcMessage', message); }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'user-muted', system: true, message: 'User_muted_by', @@ -94,7 +95,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'user-unmuted', system: true, message: 'User_unmuted_by', @@ -105,7 +106,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'subscription-role-added', system: true, message: '__username__was_set__role__by__user_by_', @@ -117,7 +118,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'subscription-role-removed', system: true, message: '__username__is_no_longer__role__defined_by__user_by_', @@ -129,7 +130,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'room-archived', system: true, message: 'This_room_has_been_archived_by__username_', @@ -139,7 +140,7 @@ Meteor.startup(function() { }; }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'room-unarchived', system: true, message: 'This_room_has_been_unarchived_by__username_', diff --git a/packages/rocketchat-lib/lib/core.js b/packages/rocketchat-lib/lib/core.js index 31abca0cce3d..54be4847bbd0 100644 --- a/packages/rocketchat-lib/lib/core.js +++ b/packages/rocketchat-lib/lib/core.js @@ -1,5 +1,4 @@ -import EventEmitter from 'wolfy87-eventemitter'; -RocketChat = new EventEmitter(); +RocketChat = {}; /* * Kick off the global namespace for RocketChat. * @namespace RocketChat diff --git a/packages/rocketchat-lib/lib/getAvatarColor.js b/packages/rocketchat-lib/lib/getAvatarColor.js index ccc93b345820..3e29088837b3 100644 --- a/packages/rocketchat-lib/lib/getAvatarColor.js +++ b/packages/rocketchat-lib/lib/getAvatarColor.js @@ -1,5 +1,3 @@ -const colors = ['#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFC107', '#FF9800', '#FF5722', '#795548', '#9E9E9E', '#607D8B']; +import { getAvatarColor } from 'meteor/rocketchat:utils'; -RocketChat.getAvatarColor = function(name) { - return colors[name.length % colors.length]; -}; +RocketChat.getAvatarColor = getAvatarColor; diff --git a/packages/rocketchat-lib/lib/getURL.js b/packages/rocketchat-lib/lib/getURL.js index 4948d6527245..572286bd8884 100644 --- a/packages/rocketchat-lib/lib/getURL.js +++ b/packages/rocketchat-lib/lib/getURL.js @@ -1,21 +1,3 @@ -import { Meteor } from 'meteor/meteor'; -import s from 'underscore.string'; +import { getURL } from 'meteor/rocketchat:utils'; -RocketChat.getURL = (path, { cdn = true, full = false } = {}) => { - const cdnPrefix = s.rtrim(s.trim(RocketChat.settings.get('CDN_PREFIX') || ''), '/'); - const pathPrefix = s.rtrim(s.trim(__meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''), '/'); - - let basePath; - - const finalPath = s.ltrim(s.trim(path), '/'); - - if (cdn && cdnPrefix !== '') { - basePath = cdnPrefix + pathPrefix; - } else if (full) { - return Meteor.absoluteUrl(finalPath); - } else { - basePath = pathPrefix; - } - - return `${ basePath }/${ finalPath }`; -}; +RocketChat.getURL = getURL; diff --git a/packages/rocketchat-lib/lib/getValidRoomName.js b/packages/rocketchat-lib/lib/getValidRoomName.js index e48a30e25b76..a24b42a00719 100644 --- a/packages/rocketchat-lib/lib/getValidRoomName.js +++ b/packages/rocketchat-lib/lib/getValidRoomName.js @@ -1,49 +1,3 @@ -import { Meteor } from 'meteor/meteor'; -import s from 'underscore.string'; +import { getValidRoomName } from 'meteor/rocketchat:utils'; -RocketChat.getValidRoomName = function getValidRoomName(displayName, rid = '') { - let slugifiedName = displayName; - - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { - const room = RocketChat.models.Rooms.findOneByDisplayName(displayName); - if (room && room._id !== rid) { - if (room.archived) { - throw new Meteor.Error('error-archived-duplicate-name', `There's an archived channel with name ${ displayName }`, { function: 'RocketChat.getValidRoomName', channel_name: displayName }); - } else { - throw new Meteor.Error('error-duplicate-channel-name', `A channel with name '${ displayName }' exists`, { function: 'RocketChat.getValidRoomName', channel_name: displayName }); - } - } - slugifiedName = s.slugify(displayName); - } - - let nameValidation; - try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); - } catch (error) { - nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); - } - if (!nameValidation.test(slugifiedName)) { - throw new Meteor.Error('error-invalid-room-name', `${ slugifiedName } is not a valid room name.`, { - function: 'RocketChat.getValidRoomName', - channel_name: slugifiedName, - }); - } - - const room = RocketChat.models.Rooms.findOneByName(slugifiedName); - if (room && room._id !== rid) { - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { - let tmpName = slugifiedName; - let next = 0; - while (RocketChat.models.Rooms.findOneByNameAndNotId(tmpName, rid)) { - tmpName = `${ slugifiedName }-${ ++next }`; - } - slugifiedName = tmpName; - } else if (room.archived) { - throw new Meteor.Error('error-archived-duplicate-name', `There's an archived channel with name ${ slugifiedName }`, { function: 'RocketChat.getValidRoomName', channel_name: slugifiedName }); - } else { - throw new Meteor.Error('error-duplicate-channel-name', `A channel with name '${ slugifiedName }' exists`, { function: 'RocketChat.getValidRoomName', channel_name: slugifiedName }); - } - } - - return slugifiedName; -}; +RocketChat.getValidRoomName = getValidRoomName; diff --git a/packages/rocketchat-lib/lib/placeholders.js b/packages/rocketchat-lib/lib/placeholders.js index 45f996e86173..ae636d79c21e 100644 --- a/packages/rocketchat-lib/lib/placeholders.js +++ b/packages/rocketchat-lib/lib/placeholders.js @@ -1,32 +1,3 @@ -import s from 'underscore.string'; +import { placeholders } from 'meteor/rocketchat:utils'; -RocketChat.placeholders = {}; - -RocketChat.placeholders.replace = function(str, data) { - if (!str) { - return ''; - } - - str = str.replace(/\[Site_Name\]/g, RocketChat.settings.get('Site_Name') || ''); - str = str.replace(/\[Site_URL\]/g, RocketChat.settings.get('Site_Url') || ''); - - if (data) { - str = str.replace(/\[name\]/g, data.name || ''); - str = str.replace(/\[fname\]/g, s.strLeft(data.name, ' ') || ''); - str = str.replace(/\[lname\]/g, s.strRightBack(data.name, ' ') || ''); - str = str.replace(/\[email\]/g, data.email || ''); - str = str.replace(/\[password\]/g, data.password || ''); - str = str.replace(/\[reason\]/g, data.reason || ''); - str = str.replace(/\[User\]/g, data.user || ''); - str = str.replace(/\[Room\]/g, data.room || ''); - - if (data.unsubscribe) { - str = str.replace(/\[unsubscribe\]/g, data.unsubscribe); - } - } - - str = str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '
' + '$2'); - - - return str; -}; +RocketChat.placeholders = placeholders; diff --git a/packages/rocketchat-lib/lib/roomTypes/conversation.js b/packages/rocketchat-lib/lib/roomTypes/conversation.js index 8f18930c5c68..66d737861d05 100644 --- a/packages/rocketchat-lib/lib/roomTypes/conversation.js +++ b/packages/rocketchat-lib/lib/roomTypes/conversation.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { getUserPreference } from 'meteor/rocketchat:utils'; import { RoomTypeConfig } from '../RoomTypeConfig'; export class ConversationRoomType extends RoomTypeConfig { @@ -12,6 +13,6 @@ export class ConversationRoomType extends RoomTypeConfig { condition() { // returns true only if sidebarGroupByType is not set - return !RocketChat.getUserPreference(Meteor.userId(), 'sidebarGroupByType'); + return !getUserPreference(Meteor.userId(), 'sidebarGroupByType'); } } diff --git a/packages/rocketchat-lib/lib/roomTypes/direct.js b/packages/rocketchat-lib/lib/roomTypes/direct.js index a259f09db136..3530f4a1930a 100644 --- a/packages/rocketchat-lib/lib/roomTypes/direct.js +++ b/packages/rocketchat-lib/lib/roomTypes/direct.js @@ -1,7 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Session } from 'meteor/session'; +import { ChatRoom, Subscriptions } from 'meteor/rocketchat:models'; +import { openRoom } from 'meteor/rocketchat:ui-utils'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { hasPermission, hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; import { RoomTypeConfig, RoomTypeRouteConfig, RoomSettingsEnum, UiTextContext } from '../RoomTypeConfig'; -import { ChatRoom } from 'meteor/rocketchat:models'; export class DirectMessageRoomRoute extends RoomTypeRouteConfig { constructor() { @@ -31,7 +35,7 @@ export class DirectMessageRoomType extends RoomTypeConfig { } findRoom(identifier) { - if (!RocketChat.authz.hasPermission('view-d-room')) { + if (!hasPermission('view-d-room')) { return null; } @@ -40,19 +44,19 @@ export class DirectMessageRoomType extends RoomTypeConfig { name: identifier, }; - const subscription = RocketChat.models.Subscriptions.findOne(query); + const subscription = Subscriptions.findOne(query); if (subscription && subscription.rid) { return ChatRoom.findOne(subscription.rid); } } roomName(roomData) { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: roomData._id }, { fields: { name: 1, fname: 1 } }); + const subscription = Subscriptions.findOne({ rid: roomData._id }, { fields: { name: 1, fname: 1 } }); if (!subscription) { return ''; } - if (RocketChat.settings.get('UI_Use_Real_Name') && subscription.fname) { + if (settings.get('UI_Use_Real_Name') && subscription.fname) { return subscription.fname; } @@ -60,19 +64,19 @@ export class DirectMessageRoomType extends RoomTypeConfig { } secondaryRoomName(roomData) { - if (RocketChat.settings.get('UI_Use_Real_Name')) { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: roomData._id }, { fields: { name: 1 } }); + if (settings.get('UI_Use_Real_Name')) { + const subscription = Subscriptions.findOne({ rid: roomData._id }, { fields: { name: 1 } }); return subscription && subscription.name; } } condition() { - const groupByType = RocketChat.getUserPreference(Meteor.userId(), 'sidebarGroupByType'); - return groupByType && RocketChat.authz.hasAtLeastOnePermission(['view-d-room', 'view-joined-room']); + const groupByType = getUserPreference(Meteor.userId(), 'sidebarGroupByType'); + return groupByType && hasAtLeastOnePermission(['view-d-room', 'view-joined-room']); } getUserStatus(roomId) { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: roomId }); + const subscription = Subscriptions.findOne({ rid: roomId }); if (subscription == null) { return; } @@ -95,7 +99,7 @@ export class DirectMessageRoomType extends RoomTypeConfig { case RoomSettingsEnum.JOIN_CODE: return false; case RoomSettingsEnum.E2E: - return RocketChat.settings.get('E2E_Enable') === true; + return settings.get('E2E_Enable') === true; default: return true; } @@ -133,7 +137,7 @@ export class DirectMessageRoomType extends RoomTypeConfig { return {}; } - const title = RocketChat.settings.get('UI_Use_Real_Name') ? user.name : `@${ user.username }`; + const title = settings.get('UI_Use_Real_Name') ? user.name : `@${ user.username }`; const text = notificationMessage; return { title, text }; diff --git a/packages/rocketchat-lib/lib/roomTypes/favorite.js b/packages/rocketchat-lib/lib/roomTypes/favorite.js index af598aca06c6..4aac1fd098b0 100644 --- a/packages/rocketchat-lib/lib/roomTypes/favorite.js +++ b/packages/rocketchat-lib/lib/roomTypes/favorite.js @@ -1,4 +1,6 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { getUserPreference } from 'meteor/rocketchat:utils'; import { RoomTypeConfig } from '../RoomTypeConfig'; export class FavoriteRoomType extends RoomTypeConfig { @@ -12,6 +14,6 @@ export class FavoriteRoomType extends RoomTypeConfig { }); } condition() { - return RocketChat.settings.get('Favorite_Rooms') && RocketChat.getUserPreference(Meteor.userId(), 'sidebarShowFavorites'); + return settings.get('Favorite_Rooms') && getUserPreference(Meteor.userId(), 'sidebarShowFavorites'); } } diff --git a/packages/rocketchat-lib/lib/roomTypes/private.js b/packages/rocketchat-lib/lib/roomTypes/private.js index 9a2eabc7c4ea..3618072f8729 100644 --- a/packages/rocketchat-lib/lib/roomTypes/private.js +++ b/packages/rocketchat-lib/lib/roomTypes/private.js @@ -1,6 +1,10 @@ import { Meteor } from 'meteor/meteor'; -import { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig, UiTextContext } from '../RoomTypeConfig'; import { ChatRoom } from 'meteor/rocketchat:models'; +import { openRoom } from 'meteor/rocketchat:ui-utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAtLeastOnePermission, hasPermission } from 'meteor/rocketchat:authorization'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig, UiTextContext } from '../RoomTypeConfig'; export class PrivateRoomRoute extends RoomTypeRouteConfig { constructor() { @@ -36,7 +40,7 @@ export class PrivateRoomType extends RoomTypeConfig { } roomName(roomData) { - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { + if (settings.get('UI_Allow_room_names_with_special_chars')) { return roomData.fname || roomData.name; } @@ -44,8 +48,8 @@ export class PrivateRoomType extends RoomTypeConfig { } condition() { - const groupByType = RocketChat.getUserPreference(Meteor.userId(), 'sidebarGroupByType'); - return groupByType && RocketChat.authz.hasPermission('view-p-room'); + const groupByType = getUserPreference(Meteor.userId(), 'sidebarGroupByType'); + return groupByType && hasPermission('view-p-room'); } isGroupChat() { @@ -53,7 +57,7 @@ export class PrivateRoomType extends RoomTypeConfig { } canAddUser(room) { - return RocketChat.authz.hasAtLeastOnePermission(['add-user-to-any-p-room', 'add-user-to-joined-room'], room._id); + return hasAtLeastOnePermission(['add-user-to-any-p-room', 'add-user-to-joined-room'], room._id); } allowRoomSettingChange(room, setting) { @@ -68,7 +72,7 @@ export class PrivateRoomType extends RoomTypeConfig { return !room.broadcast && room.ro; case RoomSettingsEnum.SYSTEM_MESSAGES: case RoomSettingsEnum.E2E: - return RocketChat.settings.get('E2E_Enable') === true; + return settings.get('E2E_Enable') === true; default: return true; } diff --git a/packages/rocketchat-lib/lib/roomTypes/public.js b/packages/rocketchat-lib/lib/roomTypes/public.js index 6ccc7cd1176a..c69a8086674c 100644 --- a/packages/rocketchat-lib/lib/roomTypes/public.js +++ b/packages/rocketchat-lib/lib/roomTypes/public.js @@ -1,6 +1,10 @@ import { Meteor } from 'meteor/meteor'; -import { RoomTypeConfig, RoomTypeRouteConfig, RoomSettingsEnum, UiTextContext } from '../RoomTypeConfig'; +import { openRoom } from 'meteor/rocketchat:ui-utils'; import { ChatRoom } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { RoomTypeConfig, RoomTypeRouteConfig, RoomSettingsEnum, UiTextContext } from '../RoomTypeConfig'; export class PublicRoomRoute extends RoomTypeRouteConfig { constructor() { @@ -35,15 +39,15 @@ export class PublicRoomType extends RoomTypeConfig { } roomName(roomData) { - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { + if (settings.get('UI_Allow_room_names_with_special_chars')) { return roomData.fname || roomData.name; } return roomData.name; } condition() { - const groupByType = RocketChat.getUserPreference(Meteor.userId(), 'sidebarGroupByType'); - return groupByType && (RocketChat.authz.hasAtLeastOnePermission(['view-c-room', 'view-joined-room']) || RocketChat.settings.get('Accounts_AllowAnonymousRead') === true); + const groupByType = getUserPreference(Meteor.userId(), 'sidebarGroupByType'); + return groupByType && (hasAtLeastOnePermission(['view-c-room', 'view-joined-room']) || settings.get('Accounts_AllowAnonymousRead') === true); } showJoinLink(roomId) { @@ -59,7 +63,7 @@ export class PublicRoomType extends RoomTypeConfig { } canAddUser(room) { - return RocketChat.authz.hasAtLeastOnePermission(['add-user-to-any-c-room', 'add-user-to-joined-room'], room._id); + return hasAtLeastOnePermission(['add-user-to-any-c-room', 'add-user-to-joined-room'], room._id); } enableMembersListProfile() { diff --git a/packages/rocketchat-lib/lib/roomTypes/unread.js b/packages/rocketchat-lib/lib/roomTypes/unread.js index 64926533670f..30c287bbe0b9 100644 --- a/packages/rocketchat-lib/lib/roomTypes/unread.js +++ b/packages/rocketchat-lib/lib/roomTypes/unread.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { getUserPreference } from 'meteor/rocketchat:utils'; import { RoomTypeConfig } from '../RoomTypeConfig'; export class UnreadRoomType extends RoomTypeConfig { @@ -13,6 +14,6 @@ export class UnreadRoomType extends RoomTypeConfig { } condition() { - return RocketChat.getUserPreference(Meteor.userId(), 'sidebarShowUnread'); + return getUserPreference(Meteor.userId(), 'sidebarShowUnread'); } } diff --git a/packages/rocketchat-lib/lib/startup/settingsOnLoadSiteUrl.js b/packages/rocketchat-lib/lib/startup/settingsOnLoadSiteUrl.js index 7d6aa29034a5..4a3ac0c967c2 100644 --- a/packages/rocketchat-lib/lib/startup/settingsOnLoadSiteUrl.js +++ b/packages/rocketchat-lib/lib/startup/settingsOnLoadSiteUrl.js @@ -1,7 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { WebAppInternals } from 'meteor/webapp'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.get('Site_Url', function(key, value) { +export let hostname; + +settings.get('Site_Url', function(key, value) { if (value == null || value.trim() === '') { return; } @@ -18,7 +21,7 @@ RocketChat.settings.get('Site_Url', function(key, value) { Meteor.absoluteUrl.defaultOptions.rootUrl = value; } if (Meteor.isServer) { - RocketChat.hostname = host.replace(/^https?:\/\//, ''); + hostname = host.replace(/^https?:\/\//, ''); process.env.MOBILE_ROOT_URL = host; process.env.MOBILE_DDP_URL = host; if (typeof WebAppInternals !== 'undefined' && WebAppInternals.generateBoilerplate) { diff --git a/packages/rocketchat-lib/server/lib/index.js b/packages/rocketchat-lib/server/lib/index.js index 7d9a272a1a8d..5cf680b6e8b9 100644 --- a/packages/rocketchat-lib/server/lib/index.js +++ b/packages/rocketchat-lib/server/lib/index.js @@ -8,6 +8,7 @@ import { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig } from '../../lib/RoomTypeConfig'; import { sendNotification } from './sendNotificationsOnMessage.js'; +export { hostname } from '../../lib/startup/settingsOnLoadSiteUrl'; export { RoomSettingsEnum, diff --git a/packages/rocketchat-ui-utils/client/index.js b/packages/rocketchat-ui-utils/client/index.js index add1d9559fbe..c440cbd9091c 100644 --- a/packages/rocketchat-ui-utils/client/index.js +++ b/packages/rocketchat-ui-utils/client/index.js @@ -23,3 +23,5 @@ export { popout } from './lib/popout'; export { messageProperties } from '../lib/MessageProperties'; export { MessageTypes } from '../lib/MessageTypes'; export { alerts } from './lib/alerts'; +export { Message } from '../lib/Message'; +export { currentTracker, openRoom } from './lib/openRoom'; diff --git a/packages/rocketchat-ui-utils/client/lib/openRoom.js b/packages/rocketchat-ui-utils/client/lib/openRoom.js new file mode 100644 index 000000000000..f139295111ab --- /dev/null +++ b/packages/rocketchat-ui-utils/client/lib/openRoom.js @@ -0,0 +1,102 @@ +import { Meteor } from 'meteor/meteor'; +import { Tracker } from 'meteor/tracker'; +import { FlowRouter } from 'meteor/kadira:flow-router'; +import { BlazeLayout } from 'meteor/kadira:blaze-layout'; +import { Session } from 'meteor/session'; +import { RoomManager, fireGlobalEvent, readMessage, RoomHistoryManager, Layout } from '..'; +import { ChatSubscription, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { roomTypes, handleError } from 'meteor/rocketchat:utils'; +import _ from 'underscore'; + +export let currentTracker = undefined; + +export const openRoom = function(type, name) { + Session.set('openedRoom', null); + + return Meteor.defer(() => + currentTracker = Tracker.autorun(function(c) { + const user = Meteor.user(); + if ((user && user.username == null) || (user == null && settings.get('Accounts_AllowAnonymousRead') === false)) { + BlazeLayout.render('main'); + return; + } + + if (RoomManager.open(type + name).ready() !== true) { + BlazeLayout.render('main', { modal: Layout.isEmbedded(), center: 'loading' }); + return; + } + if (currentTracker) { + currentTracker = undefined; + } + c.stop(); + + const room = roomTypes.findRoom(type, name, user); + if (room == null) { + if (type === 'd') { + Meteor.call('createDirectMessage', name, function(error) { + if (!error) { + RoomManager.close(type + name); + return openRoom('d', name); + } else { + Session.set('roomNotFound', { type, name, error }); + BlazeLayout.render('main', { center: 'roomNotFound' }); + return; + } + }); + } else { + Meteor.call('getRoomByTypeAndName', type, name, function(error, record) { + if (error) { + Session.set('roomNotFound', { type, name, error }); + return BlazeLayout.render('main', { center: 'roomNotFound' }); + } else { + Rooms.upsert({ _id: record._id }, _.omit(record, '_id')); + RoomManager.close(type + name); + return openRoom(type, name); + } + }); + } + return; + } + + const mainNode = document.querySelector('.main-content'); + if (mainNode) { + for (const child of Array.from(mainNode.children)) { + if (child) { mainNode.removeChild(child); } + } + const roomDom = RoomManager.getDomOfRoom(type + name, room._id); + mainNode.appendChild(roomDom); + if (roomDom.classList.contains('room-container')) { + roomDom.querySelector('.messages-box > .wrapper').scrollTop = roomDom.oldScrollTop; + } + } + + Session.set('openedRoom', room._id); + RoomManager.openedRoom = room._id; + + fireGlobalEvent('room-opened', _.omit(room, 'usernames')); + + Session.set('editRoomTitle', false); + RoomManager.updateMentionsMarksOfRoom(type + name); + Meteor.setTimeout(() => readMessage.readNow(), 2000); + // KonchatNotification.removeRoomNotification(params._id) + // update user's room subscription + const sub = ChatSubscription.findOne({ rid: room._id }); + if (sub && sub.open === false) { + Meteor.call('openRoom', room._id, function(err) { + if (err) { + return handleError(err); + } + }); + } + + if (FlowRouter.getQueryParam('msg')) { + const msg = { _id: FlowRouter.getQueryParam('msg'), rid: room._id }; + RoomHistoryManager.getSurroundingMessages(msg); + } + + return callbacks.run('enter-room', sub); + }) + ); +}; diff --git a/packages/rocketchat-ui-utils/lib/Message.js b/packages/rocketchat-ui-utils/lib/Message.js new file mode 100644 index 000000000000..6d595dc37804 --- /dev/null +++ b/packages/rocketchat-ui-utils/lib/Message.js @@ -0,0 +1,34 @@ +import { TAPi18n } from 'meteor/tap:i18n'; +import { settings } from 'meteor/rocketchat:settings'; +import s from 'underscore.string'; +import { MessageTypes } from './MessageTypes'; + +export const Message = { + parse(msg, language) { + const messageType = MessageTypes.getType(msg); + if (messageType) { + if (messageType.render) { + return messageType.render(msg); + } else if (messageType.template) { + // Render message + return; + } else if (messageType.message) { + if (!language && typeof localStorage !== 'undefined') { + language = localStorage.getItem('userLanguage'); + } + const data = (typeof messageType.data === 'function' && messageType.data(msg)) || {}; + return TAPi18n.__(messageType.message, data, language); + } + } + if (msg.u && msg.u.username === settings.get('Chatops_Username')) { + msg.html = msg.msg; + return msg.html; + } + msg.html = msg.msg; + if (s.trim(msg.html) !== '') { + msg.html = s.escapeHTML(msg.html); + } + msg.html = msg.html.replace(/\n/gm, '
'); + return msg.html; + }, +}; diff --git a/packages/rocketchat-ui-utils/package.js b/packages/rocketchat-ui-utils/package.js index aacd2e789d84..da1129cc1063 100644 --- a/packages/rocketchat-ui-utils/package.js +++ b/packages/rocketchat-ui-utils/package.js @@ -10,10 +10,12 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'http', + 'tap:i18n', 'templating', 'kadira:flow-router', 'kadira:blaze-layout', 'rocketchat:utils', + 'rocketchat:settings', 'rocketchat:promises', 'rocketchat:notifications', 'rocketchat:authorization', diff --git a/packages/rocketchat-ui-utils/server/index.js b/packages/rocketchat-ui-utils/server/index.js index d10c21758175..35066a1ea46d 100644 --- a/packages/rocketchat-ui-utils/server/index.js +++ b/packages/rocketchat-ui-utils/server/index.js @@ -1,2 +1,3 @@ export { messageProperties } from '../lib/MessageProperties'; export { MessageTypes } from '../lib/MessageTypes'; +export { Message } from '../lib/Message'; diff --git a/packages/rocketchat-utils/client/index.js b/packages/rocketchat-utils/client/index.js index 97d18ad672b7..3fc66523a403 100644 --- a/packages/rocketchat-utils/client/index.js +++ b/packages/rocketchat-utils/client/index.js @@ -13,3 +13,7 @@ export { getAvatarUrlFromUsername } from '../lib/getAvatarUrlFromUsername'; export { slashCommands } from '../lib/slashCommand'; export { getUserNotificationPreference } from '../lib/getUserNotificationPreference'; export { applyCustomTranslations } from './lib/CustomTranslations'; +export { getAvatarColor } from '../lib/getAvatarColor'; +export { getURL } from '../lib/getURL'; +export { getValidRoomName } from '../lib/getValidRoomName'; +export { placeholders } from '../lib/placeholders'; diff --git a/packages/rocketchat-utils/lib/getAvatarColor.js b/packages/rocketchat-utils/lib/getAvatarColor.js new file mode 100644 index 000000000000..867d9982e863 --- /dev/null +++ b/packages/rocketchat-utils/lib/getAvatarColor.js @@ -0,0 +1,3 @@ +const colors = ['#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3', '#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFC107', '#FF9800', '#FF5722', '#795548', '#9E9E9E', '#607D8B']; + +export const getAvatarColor = (name) => colors[name.length % colors.length]; diff --git a/packages/rocketchat-utils/lib/getURL.js b/packages/rocketchat-utils/lib/getURL.js new file mode 100644 index 000000000000..e314a6b58c80 --- /dev/null +++ b/packages/rocketchat-utils/lib/getURL.js @@ -0,0 +1,22 @@ +import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import s from 'underscore.string'; + +export const getURL = (path, { cdn = true, full = false } = {}) => { + const cdnPrefix = s.rtrim(s.trim(settings.get('CDN_PREFIX') || ''), '/'); + const pathPrefix = s.rtrim(s.trim(__meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''), '/'); + + let basePath; + + const finalPath = s.ltrim(s.trim(path), '/'); + + if (cdn && cdnPrefix !== '') { + basePath = cdnPrefix + pathPrefix; + } else if (full) { + return Meteor.absoluteUrl(finalPath); + } else { + basePath = pathPrefix; + } + + return `${ basePath }/${ finalPath }`; +}; diff --git a/packages/rocketchat-utils/lib/getValidRoomName.js b/packages/rocketchat-utils/lib/getValidRoomName.js new file mode 100644 index 000000000000..92306dc00983 --- /dev/null +++ b/packages/rocketchat-utils/lib/getValidRoomName.js @@ -0,0 +1,51 @@ +import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Rooms } from 'meteor/rocketchat:models'; +import s from 'underscore.string'; + +export const getValidRoomName = (displayName, rid = '') => { + let slugifiedName = displayName; + + if (settings.get('UI_Allow_room_names_with_special_chars')) { + const room = Rooms.findOneByDisplayName(displayName); + if (room && room._id !== rid) { + if (room.archived) { + throw new Meteor.Error('error-archived-duplicate-name', `There's an archived channel with name ${ displayName }`, { function: 'RocketChat.getValidRoomName', channel_name: displayName }); + } else { + throw new Meteor.Error('error-duplicate-channel-name', `A channel with name '${ displayName }' exists`, { function: 'RocketChat.getValidRoomName', channel_name: displayName }); + } + } + slugifiedName = s.slugify(displayName); + } + + let nameValidation; + try { + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); + } catch (error) { + nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); + } + if (!nameValidation.test(slugifiedName)) { + throw new Meteor.Error('error-invalid-room-name', `${ slugifiedName } is not a valid room name.`, { + function: 'RocketChat.getValidRoomName', + channel_name: slugifiedName, + }); + } + + const room = Rooms.findOneByName(slugifiedName); + if (room && room._id !== rid) { + if (settings.get('UI_Allow_room_names_with_special_chars')) { + let tmpName = slugifiedName; + let next = 0; + while (Rooms.findOneByNameAndNotId(tmpName, rid)) { + tmpName = `${ slugifiedName }-${ ++next }`; + } + slugifiedName = tmpName; + } else if (room.archived) { + throw new Meteor.Error('error-archived-duplicate-name', `There's an archived channel with name ${ slugifiedName }`, { function: 'RocketChat.getValidRoomName', channel_name: slugifiedName }); + } else { + throw new Meteor.Error('error-duplicate-channel-name', `A channel with name '${ slugifiedName }' exists`, { function: 'RocketChat.getValidRoomName', channel_name: slugifiedName }); + } + } + + return slugifiedName; +}; diff --git a/packages/rocketchat-utils/lib/placeholders.js b/packages/rocketchat-utils/lib/placeholders.js new file mode 100644 index 000000000000..274005672aa0 --- /dev/null +++ b/packages/rocketchat-utils/lib/placeholders.js @@ -0,0 +1,32 @@ +import { settings } from 'meteor/rocketchat:settings'; +import s from 'underscore.string'; + +export const placeholders = { + replace: (str, data) => { + if (!str) { + return ''; + } + + str = str.replace(/\[Site_Name\]/g, settings.get('Site_Name') || ''); + str = str.replace(/\[Site_URL\]/g, settings.get('Site_Url') || ''); + + if (data) { + str = str.replace(/\[name\]/g, data.name || ''); + str = str.replace(/\[fname\]/g, s.strLeft(data.name, ' ') || ''); + str = str.replace(/\[lname\]/g, s.strRightBack(data.name, ' ') || ''); + str = str.replace(/\[email\]/g, data.email || ''); + str = str.replace(/\[password\]/g, data.password || ''); + str = str.replace(/\[reason\]/g, data.reason || ''); + str = str.replace(/\[User\]/g, data.user || ''); + str = str.replace(/\[Room\]/g, data.room || ''); + + if (data.unsubscribe) { + str = str.replace(/\[unsubscribe\]/g, data.unsubscribe); + } + } + + str = str.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '
' + '$2'); + + return str; + }, +}; diff --git a/packages/rocketchat-utils/server/index.js b/packages/rocketchat-utils/server/index.js index e0585eebb4b4..48af9bdf8458 100644 --- a/packages/rocketchat-utils/server/index.js +++ b/packages/rocketchat-utils/server/index.js @@ -1,32 +1,16 @@ -import { t, isRtl } from '../lib/tapi18n'; -import { getDefaultSubscriptionPref } from '../lib/getDefaultSubscriptionPref'; -import { Info } from '../rocketchat.info'; -import { getUserPreference } from '../lib/getUserPreference'; -import { fileUploadMediaWhiteList, fileUploadIsValidContentType } from '../lib/fileUploadRestrictions'; -import { roomTypes } from './lib/roomTypes'; -import { RoomTypeRouteConfig, RoomTypeConfig, RoomSettingsEnum, UiTextContext } from '../lib/RoomTypeConfig'; -import { RoomTypesCommon } from '../lib/RoomTypesCommon'; -import { isDocker } from './functions/isDocker'; -import { getAvatarUrlFromUsername } from '../lib/getAvatarUrlFromUsername'; -import { slashCommands } from '../lib/slashCommand'; -import { getUserNotificationPreference } from '../lib/getUserNotificationPreference'; - -export { - t, - isRtl, - getDefaultSubscriptionPref, - Info, - getUserPreference, - fileUploadIsValidContentType, - fileUploadMediaWhiteList, - roomTypes, - RoomTypeRouteConfig, - RoomTypesCommon, - RoomTypeConfig, - RoomSettingsEnum, - UiTextContext, - isDocker, - getAvatarUrlFromUsername, - slashCommands, - getUserNotificationPreference, -}; +export { t, isRtl } from '../lib/tapi18n'; +export { getDefaultSubscriptionPref } from '../lib/getDefaultSubscriptionPref'; +export { Info } from '../rocketchat.info'; +export { getUserPreference } from '../lib/getUserPreference'; +export { fileUploadMediaWhiteList, fileUploadIsValidContentType } from '../lib/fileUploadRestrictions'; +export { roomTypes } from './lib/roomTypes'; +export { RoomTypeRouteConfig, RoomTypeConfig, RoomSettingsEnum, UiTextContext } from '../lib/RoomTypeConfig'; +export { RoomTypesCommon } from '../lib/RoomTypesCommon'; +export { isDocker } from './functions/isDocker'; +export { getAvatarUrlFromUsername } from '../lib/getAvatarUrlFromUsername'; +export { slashCommands } from '../lib/slashCommand'; +export { getUserNotificationPreference } from '../lib/getUserNotificationPreference'; +export { getAvatarColor } from '../lib/getAvatarColor'; +export { getURL } from '../lib/getURL'; +export { getValidRoomName } from '../lib/getValidRoomName'; +export { placeholders } from '../lib/placeholders'; From 118634cb43d118186bf11924a0cf516c79adb345 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Tue, 22 Jan 2019 14:57:11 -0200 Subject: [PATCH 03/33] Remove some dependencies inside rocketchat-lib/server/functions (#13214) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace --- .../rocketchat-integrations/server/index.js | 2 - packages/rocketchat-lib/package.js | 7 ++- .../functions/addUserToDefaultChannels.js | 18 +++++--- .../server/functions/addUserToRoom.js | 21 +++++---- .../server/functions/archiveRoom.js | 8 ++-- .../functions/checkUsernameAvailability.js | 4 +- .../server/functions/cleanRoomHistory.js | 12 ++--- .../functions/composeMessageObjectWithUser.js | 20 --------- .../composeMessageObjectWithUser_import.js | 3 ++ .../server/functions/createRoom.js | 28 +++++++----- .../server/functions/deleteMessage.js | 30 +++++++------ .../server/functions/deleteUser.js | 44 ++++++++++--------- .../server/functions/getFullUserData.js | 15 ++++--- .../getRoomByNameOrIdWithOptionToJoin.js | 15 ++++--- .../server/functions/isTheLastMessage.js | 4 +- .../server/functions/loadMessageHistory.js | 16 ++++--- .../server/functions/notifications/audio.js | 10 +++-- .../server/functions/notifications/desktop.js | 14 +++--- .../server/functions/notifications/email.js | 36 ++++++++------- .../server/functions/notifications/index.js | 5 ++- .../server/functions/notifications/mobile.js | 22 ++++++---- .../server/functions/removeUserFromRoom.js | 16 ++++--- .../server/functions/saveCustomFields.js | 3 +- .../saveCustomFieldsWithoutValidation.js | 12 ++--- .../server/functions/saveUser.js | 37 +++++++++------- .../server/functions/sendMessage.js | 13 +++--- .../server/functions/setEmail.js | 8 ++-- .../server/functions/setRealName.js | 16 ++++--- .../server/functions/setUserAvatar.js | 8 ++-- .../server/functions/setUsername.js | 33 +++++++------- .../server/functions/unarchiveRoom.js | 6 ++- .../server/functions/updateMessage.js | 17 ++++--- .../server/functions/validateCustomFields.js | 5 ++- .../server/lib/PushNotification_import.js | 3 ++ .../rocketchat-lib/server/models/index.js | 6 ++- packages/rocketchat-models/server/index.js | 4 ++ .../server/models/IntegrationHistory.js | 9 ++-- .../server/models/Integrations.js | 8 ++-- .../rocketchat-push-notifications/package.js | 2 + .../server/index.js | 5 +++ .../server/lib/PushNotification.js | 10 +++-- packages/rocketchat-utils/server/index.js | 1 + .../lib/composeMessageObjectWithUser.js | 23 ++++++++++ 43 files changed, 344 insertions(+), 235 deletions(-) delete mode 100644 packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js create mode 100644 packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js create mode 100644 packages/rocketchat-lib/server/lib/PushNotification_import.js rename packages/{rocketchat-integrations => rocketchat-models}/server/models/IntegrationHistory.js (85%) rename packages/{rocketchat-integrations => rocketchat-models}/server/models/Integrations.js (73%) rename packages/{rocketchat-lib => rocketchat-push-notifications}/server/lib/PushNotification.js (77%) create mode 100644 packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js diff --git a/packages/rocketchat-integrations/server/index.js b/packages/rocketchat-integrations/server/index.js index efaed5238b66..dae9d993637c 100644 --- a/packages/rocketchat-integrations/server/index.js +++ b/packages/rocketchat-integrations/server/index.js @@ -1,8 +1,6 @@ import '../lib/rocketchat'; import './logger'; import './lib/validation'; -import './models/Integrations'; -import './models/IntegrationHistory'; import './publications/integrations'; import './publications/integrationHistory'; import './methods/incoming/addIncomingIntegration'; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9784e41bedd6..9604a53f4ceb 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -49,8 +49,7 @@ Package.onUse(function(api) { api.use('konecty:multiple-instances-status'); api.use('rocketchat:file'); api.use('rocketchat:file-upload'); - api.use('rocketchat:push'); - api.use('rocketchat:push-notifications', { unordered: true }); + api.use('rocketchat:push-notifications'); api.use('templating', 'client'); api.use('kadira:flow-router'); @@ -111,7 +110,7 @@ Package.onUse(function(api) { api.addFiles('server/functions/archiveRoom.js', 'server'); api.addFiles('server/functions/checkUsernameAvailability.js', 'server'); api.addFiles('server/functions/checkEmailAvailability.js', 'server'); - api.addFiles('server/functions/composeMessageObjectWithUser.js', 'server'); + api.addFiles('server/functions/composeMessageObjectWithUser_import.js', 'server'); api.addFiles('server/functions/createRoom.js', 'server'); api.addFiles('server/functions/cleanRoomHistory.js', 'server'); api.addFiles('server/functions/deleteMessage.js', 'server'); @@ -137,7 +136,7 @@ Package.onUse(function(api) { // SERVER LIB api.addFiles('server/lib/configLogger.js', 'server'); - api.addFiles('server/lib/PushNotification.js', 'server'); + api.addFiles('server/lib/PushNotification_import.js', 'server'); api.addFiles('server/lib/defaultBlockedDomainsList.js', 'server'); api.addFiles('server/lib/interceptDirectReplyEmails.js', 'server'); api.addFiles('server/lib/loginErrorMessageOverride.js', 'server'); diff --git a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js index 0ad51cea050e..df411a6d0616 100644 --- a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js +++ b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js @@ -1,18 +1,22 @@ +import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; + RocketChat.addUserToDefaultChannels = function(user, silenced) { - RocketChat.callbacks.run('beforeJoinDefaultChannels', user); - const defaultRooms = RocketChat.models.Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch(); + callbacks.run('beforeJoinDefaultChannels', user); + const defaultRooms = Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch(); defaultRooms.forEach((room) => { // put user in default rooms - const muted = room.ro && !RocketChat.authz.hasPermission(user._id, 'post-readonly'); + const muted = room.ro && !hasPermission(user._id, 'post-readonly'); if (muted) { - RocketChat.models.Rooms.muteUsernameByRoomId(room._id, user.username); + Rooms.muteUsernameByRoomId(room._id, user.username); } - if (!RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id)) { + if (!Subscriptions.findOneByRoomIdAndUserId(room._id, user._id)) { // Add a subscription to this user - RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, { + Subscriptions.createWithRoomAndUser(room, user, { ts: new Date(), open: true, alert: true, @@ -23,7 +27,7 @@ RocketChat.addUserToDefaultChannels = function(user, silenced) { // Insert user joined message if (!silenced) { - RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(room._id, user); + Messages.createUserJoinWithRoomIdAndUser(room._id, user); } } }); diff --git a/packages/rocketchat-lib/server/functions/addUserToRoom.js b/packages/rocketchat-lib/server/functions/addUserToRoom.js index 26f8649c0f49..c9e22dbad3b0 100644 --- a/packages/rocketchat-lib/server/functions/addUserToRoom.js +++ b/packages/rocketchat-lib/server/functions/addUserToRoom.js @@ -1,25 +1,28 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { const now = new Date(); - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); // Check if user is already in room - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id); if (subscription) { return; } if (room.t === 'c' || room.t === 'p') { - RocketChat.callbacks.run('beforeJoinRoom', user, room); + callbacks.run('beforeJoinRoom', user, room); } - const muted = room.ro && !RocketChat.authz.hasPermission(user._id, 'post-readonly'); + const muted = room.ro && !hasPermission(user._id, 'post-readonly'); if (muted) { - RocketChat.models.Rooms.muteUsernameByRoomId(rid, user.username); + Rooms.muteUsernameByRoomId(rid, user.username); } - RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, { + Subscriptions.createWithRoomAndUser(room, user, { ts: now, open: true, alert: true, @@ -30,7 +33,7 @@ RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { if (!silenced) { if (inviter) { - RocketChat.models.Messages.createUserAddedWithRoomIdAndUser(rid, user, { + Messages.createUserAddedWithRoomIdAndUser(rid, user, { ts: now, u: { _id: inviter._id, @@ -38,13 +41,13 @@ RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { }, }); } else { - RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rid, user, { ts: now }); + Messages.createUserJoinWithRoomIdAndUser(rid, user, { ts: now }); } } if (room.t === 'c' || room.t === 'p') { Meteor.defer(function() { - RocketChat.callbacks.run('afterJoinRoom', user, room); + callbacks.run('afterJoinRoom', user, room); }); } diff --git a/packages/rocketchat-lib/server/functions/archiveRoom.js b/packages/rocketchat-lib/server/functions/archiveRoom.js index 26d756bd5e6e..c906746c9c42 100644 --- a/packages/rocketchat-lib/server/functions/archiveRoom.js +++ b/packages/rocketchat-lib/server/functions/archiveRoom.js @@ -1,8 +1,10 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.archiveRoom = function(rid) { - RocketChat.models.Rooms.archiveById(rid); - RocketChat.models.Subscriptions.archiveByRoomId(rid); + Rooms.archiveById(rid); + Subscriptions.archiveByRoomId(rid); - RocketChat.callbacks.run('afterRoomArchived', RocketChat.models.Rooms.findOneById(rid), Meteor.user()); + callbacks.run('afterRoomArchived', Rooms.findOneById(rid), Meteor.user()); }; diff --git a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js index 1aba54ba77f6..6a3027b773b3 100644 --- a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; import s from 'underscore.string'; - +import { settings } from 'meteor/rocketchat:settings'; let usernameBlackList = []; const toRegExp = (username) => new RegExp(`^${ s.escapeRegExp(username).trim() }$`, 'i'); -RocketChat.settings.get('Accounts_BlockedUsernameList', (key, value) => { +settings.get('Accounts_BlockedUsernameList', (key, value) => { usernameBlackList = value.split(',').map(toRegExp); }); diff --git a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js index c668b32191e2..2004db0157c0 100644 --- a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js @@ -1,5 +1,7 @@ import { TAPi18n } from 'meteor/tap:i18n'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Messages, Rooms } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new Date('0001-01-01T00:00:00Z'), inclusive = true, limit = 0, excludePinned = true, filesOnly = false, fromUsers = [] }) { const gt = inclusive ? '$gte' : '$gt'; @@ -10,7 +12,7 @@ RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new const text = `_${ TAPi18n.__('File_removed_by_prune') }_`; let fileCount = 0; - RocketChat.models.Messages.findFilesByRoomIdPinnedTimestampAndUsers( + Messages.findFilesByRoomIdPinnedTimestampAndUsers( rid, excludePinned, ts, @@ -20,18 +22,18 @@ RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new FileUpload.getStore('Uploads').deleteById(document.file._id); fileCount++; if (filesOnly) { - RocketChat.models.Messages.update({ _id: document._id }, { $unset: { file: 1 }, $set: { attachments: [{ color: '#FD745E', text }] } }); + Messages.update({ _id: document._id }, { $unset: { file: 1 }, $set: { attachments: [{ color: '#FD745E', text }] } }); } }); if (filesOnly) { return fileCount; } - const count = limit ? RocketChat.models.Messages.removeByIdPinnedTimestampLimitAndUsers(rid, excludePinned, ts, limit, fromUsers) : RocketChat.models.Messages.removeByIdPinnedTimestampAndUsers(rid, excludePinned, ts, fromUsers); + const count = limit ? Messages.removeByIdPinnedTimestampLimitAndUsers(rid, excludePinned, ts, limit, fromUsers) : Messages.removeByIdPinnedTimestampAndUsers(rid, excludePinned, ts, fromUsers); if (count) { - RocketChat.models.Rooms.resetLastMessageById(rid); - RocketChat.Notifications.notifyRoom(rid, 'deleteMessageBulk', { + Rooms.resetLastMessageById(rid); + Notifications.notifyRoom(rid, 'deleteMessageBulk', { rid, excludePinned, ts, diff --git a/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js b/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js deleted file mode 100644 index bb67bf6a9d9c..000000000000 --- a/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser.js +++ /dev/null @@ -1,20 +0,0 @@ -const getUser = (userId) => RocketChat.models.Users.findOneById(userId); - -RocketChat.composeMessageObjectWithUser = function(message, userId) { - if (message) { - if (message.starred && Array.isArray(message.starred)) { - message.starred = message.starred.filter((star) => star._id === userId); - } - if (message.u && message.u._id && RocketChat.settings.get('UI_Use_Real_Name')) { - const user = getUser(message.u._id); - message.u.name = user && user.name; - } - if (message.mentions && message.mentions.length && RocketChat.settings.get('UI_Use_Real_Name')) { - message.mentions.forEach((mention) => { - const user = getUser(mention._id); - mention.name = user && user.name; - }); - } - } - return message; -}; diff --git a/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js b/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js new file mode 100644 index 000000000000..89aab2f420ec --- /dev/null +++ b/packages/rocketchat-lib/server/functions/composeMessageObjectWithUser_import.js @@ -0,0 +1,3 @@ +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; + +RocketChat.composeMessageObjectWithUser = composeMessageObjectWithUser; diff --git a/packages/rocketchat-lib/server/functions/createRoom.js b/packages/rocketchat-lib/server/functions/createRoom.js index f901eb3e1b24..33293ceead7e 100644 --- a/packages/rocketchat-lib/server/functions/createRoom.js +++ b/packages/rocketchat-lib/server/functions/createRoom.js @@ -1,4 +1,8 @@ import { Meteor } from 'meteor/meteor'; +import { Users, Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { hasPermission, addUserRoles } from 'meteor/rocketchat:authorization'; +import { getValidRoomName } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; @@ -11,7 +15,7 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData throw new Meteor.Error('error-invalid-name', 'Invalid name', { function: 'RocketChat.createRoom' }); } - owner = RocketChat.models.Users.findOneByUsername(owner, { fields: { username: 1 } }); + owner = Users.findOneByUsername(owner, { fields: { username: 1 } }); if (!owner) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { function: 'RocketChat.createRoom' }); } @@ -27,7 +31,7 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData const now = new Date(); let room = Object.assign({ - name: RocketChat.getValidRoomName(name), + name: getValidRoomName(name), fname: name, t: type, msgs: 0, @@ -62,21 +66,21 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData } if (type === 'c') { - RocketChat.callbacks.run('beforeCreateChannel', owner, room); + callbacks.run('beforeCreateChannel', owner, room); } - room = RocketChat.models.Rooms.createWithFullRoomData(room); + room = Rooms.createWithFullRoomData(room); for (const username of members) { - const member = RocketChat.models.Users.findOneByUsername(username, { fields: { username: 1, 'settings.preferences': 1 } }); + const member = Users.findOneByUsername(username, { fields: { username: 1, 'settings.preferences': 1 } }); const isTheOwner = username === owner.username; if (!member) { continue; } // make all room members (Except the owner) muted by default, unless they have the post-readonly permission - if (readOnly === true && !RocketChat.authz.hasPermission(member._id, 'post-readonly') && !isTheOwner) { - RocketChat.models.Rooms.muteUsernameByRoomId(room._id, username); + if (readOnly === true && !hasPermission(member._id, 'post-readonly') && !isTheOwner) { + Rooms.muteUsernameByRoomId(room._id, username); } const extra = { open: true }; @@ -85,22 +89,22 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData extra.ls = now; } - RocketChat.models.Subscriptions.createWithRoomAndUser(room, member, extra); + Subscriptions.createWithRoomAndUser(room, member, extra); } - RocketChat.authz.addUserRoles(owner._id, ['owner'], room._id); + addUserRoles(owner._id, ['owner'], room._id); if (type === 'c') { Meteor.defer(() => { - RocketChat.callbacks.run('afterCreateChannel', owner, room); + callbacks.run('afterCreateChannel', owner, room); }); } else if (type === 'p') { Meteor.defer(() => { - RocketChat.callbacks.run('afterCreatePrivateGroup', owner, room); + callbacks.run('afterCreatePrivateGroup', owner, room); }); } Meteor.defer(() => { - RocketChat.callbacks.run('afterCreateRoom', owner, room); + callbacks.run('afterCreateRoom', owner, room); }); if (Apps && Apps.isLoaded()) { diff --git a/packages/rocketchat-lib/server/functions/deleteMessage.js b/packages/rocketchat-lib/server/functions/deleteMessage.js index 1f05cdd2975c..d34152a0e95b 100644 --- a/packages/rocketchat-lib/server/functions/deleteMessage.js +++ b/packages/rocketchat-lib/server/functions/deleteMessage.js @@ -1,10 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { settings } from 'meteor/rocketchat:settings'; +import { Messages, Uploads, Rooms } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.deleteMessage = function(message, user) { - const keepHistory = RocketChat.settings.get('Message_KeepHistory'); - const showDeletedStatus = RocketChat.settings.get('Message_ShowDeletedStatus'); - const deletedMsg = RocketChat.models.Messages.findOneById(message._id); + const keepHistory = settings.get('Message_KeepHistory'); + const showDeletedStatus = settings.get('Message_ShowDeletedStatus'); + const deletedMsg = Messages.findOneById(message._id); if (deletedMsg && Apps && Apps.isLoaded()) { const prevent = Promise.await(Apps.getBridges().getListenerBridge().messageEvent('IPreMessageDeletePrevent', deletedMsg)); @@ -15,17 +19,17 @@ RocketChat.deleteMessage = function(message, user) { if (keepHistory) { if (showDeletedStatus) { - RocketChat.models.Messages.cloneAndSaveAsHistoryById(message._id); + Messages.cloneAndSaveAsHistoryById(message._id); } else { - RocketChat.models.Messages.setHiddenById(message._id, true); + Messages.setHiddenById(message._id, true); } if (message.file && message.file._id) { - RocketChat.models.Uploads.update(message.file._id, { $set: { _hidden: true } }); + Uploads.update(message.file._id, { $set: { _hidden: true } }); } } else { if (!showDeletedStatus) { - RocketChat.models.Messages.removeById(message._id); + Messages.removeById(message._id); } if (message.file && message.file._id) { @@ -34,21 +38,21 @@ RocketChat.deleteMessage = function(message, user) { } Meteor.defer(function() { - RocketChat.callbacks.run('afterDeleteMessage', deletedMsg); + callbacks.run('afterDeleteMessage', deletedMsg); }); // update last message - if (RocketChat.settings.get('Store_Last_Message')) { - const room = RocketChat.models.Rooms.findOneById(message.rid, { fields: { lastMessage: 1 } }); + if (settings.get('Store_Last_Message')) { + const room = Rooms.findOneById(message.rid, { fields: { lastMessage: 1 } }); if (!room.lastMessage || room.lastMessage._id === message._id) { - RocketChat.models.Rooms.resetLastMessageById(message.rid, message._id); + Rooms.resetLastMessageById(message.rid, message._id); } } if (showDeletedStatus) { - RocketChat.models.Messages.setAsDeletedByIdAndUser(message._id, user); + Messages.setAsDeletedByIdAndUser(message._id, user); } else { - RocketChat.Notifications.notifyRoom(message.rid, 'deleteMessage', { _id: message._id }); + Notifications.notifyRoom(message.rid, 'deleteMessage', { _id: message._id }); } if (Apps && Apps.isLoaded()) { diff --git a/packages/rocketchat-lib/server/functions/deleteUser.js b/packages/rocketchat-lib/server/functions/deleteUser.js index 363a49f1c9e0..85a0445c7756 100644 --- a/packages/rocketchat-lib/server/functions/deleteUser.js +++ b/packages/rocketchat-lib/server/functions/deleteUser.js @@ -1,9 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Users, Subscriptions, Messages, Rooms, Integrations } from 'meteor/rocketchat:models'; +import { hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; RocketChat.deleteUser = function(userId) { - const user = RocketChat.models.Users.findOneById(userId, { + const user = Users.findOneById(userId, { fields: { username: 1, avatarOrigin: 1 }, }); @@ -12,7 +16,7 @@ RocketChat.deleteUser = function(userId) { const roomCache = []; // Iterate through all the rooms the user is subscribed to, to check if they are the last owner of any of them. - RocketChat.models.Subscriptions.db.findByUserId(userId).forEach((subscription) => { + Subscriptions.db.findByUserId(userId).forEach((subscription) => { const roomData = { rid: subscription.rid, t: subscription.t, @@ -22,9 +26,9 @@ RocketChat.deleteUser = function(userId) { // DMs can always be deleted, so let's ignore it on this check if (roomData.t !== 'd') { // If the user is an owner on this room - if (RocketChat.authz.hasRole(user._id, 'owner', subscription.rid)) { + if (hasRole(user._id, 'owner', subscription.rid)) { // Fetch the number of owners - const numOwners = RocketChat.authz.getUsersInRole('owner', subscription.rid).fetch().length; + const numOwners = getUsersInRole('owner', subscription.rid).fetch().length; // If it's only one, then this user is the only owner. if (numOwners === 1) { // If the user is the last owner of a public channel, then we need to abort the deletion @@ -35,7 +39,7 @@ RocketChat.deleteUser = function(userId) { } // For private groups, let's check how many subscribers it has. If the user is the only subscriber, then it will be eliminated and doesn't need to abort the deletion - roomData.subscribers = RocketChat.models.Subscriptions.findByRoomId(subscription.rid).count(); + roomData.subscribers = Subscriptions.findByRoomId(subscription.rid).count(); if (roomData.subscribers > 1) { throw new Meteor.Error('error-user-is-last-owner', `To delete this user you'll need to set a new owner to the following room: ${ subscription.name }.`, { @@ -49,47 +53,47 @@ RocketChat.deleteUser = function(userId) { roomCache.push(roomData); }); - const messageErasureType = RocketChat.settings.get('Message_ErasureType'); + const messageErasureType = settings.get('Message_ErasureType'); switch (messageErasureType) { case 'Delete': const store = FileUpload.getStore('Uploads'); - RocketChat.models.Messages.findFilesByUserId(userId).forEach(function({ file }) { + Messages.findFilesByUserId(userId).forEach(function({ file }) { store.deleteById(file._id); }); - RocketChat.models.Messages.removeByUserId(userId); + Messages.removeByUserId(userId); break; case 'Unlink': - const rocketCat = RocketChat.models.Users.findOneById('rocket.cat'); + const rocketCat = Users.findOneById('rocket.cat'); const nameAlias = TAPi18n.__('Removed_User'); - RocketChat.models.Messages.unlinkUserId(userId, rocketCat._id, rocketCat.username, nameAlias); + Messages.unlinkUserId(userId, rocketCat._id, rocketCat.username, nameAlias); break; } roomCache.forEach((roomData) => { if (roomData.subscribers === null && roomData.t !== 'd' && roomData.t !== 'c') { - roomData.subscribers = RocketChat.models.Subscriptions.findByRoomId(roomData.rid).count(); + roomData.subscribers = Subscriptions.findByRoomId(roomData.rid).count(); } // Remove DMs and non-channel rooms with only 1 user (the one being deleted) if (roomData.t === 'd' || (roomData.t !== 'c' && roomData.subscribers === 1)) { - RocketChat.models.Subscriptions.removeByRoomId(roomData.rid); - RocketChat.models.Messages.removeFilesByRoomId(roomData.rid); - RocketChat.models.Messages.removeByRoomId(roomData.rid); - RocketChat.models.Rooms.removeById(roomData.rid); + Subscriptions.removeByRoomId(roomData.rid); + Messages.removeFilesByRoomId(roomData.rid); + Messages.removeByRoomId(roomData.rid); + Rooms.removeById(roomData.rid); } }); - RocketChat.models.Subscriptions.removeByUserId(userId); // Remove user subscriptions - RocketChat.models.Rooms.removeDirectRoomContainingUsername(user.username); // Remove direct rooms with the user + Subscriptions.removeByUserId(userId); // Remove user subscriptions + Rooms.removeDirectRoomContainingUsername(user.username); // Remove direct rooms with the user // removes user's avatar if (user.avatarOrigin === 'upload' || user.avatarOrigin === 'url') { FileUpload.getStore('Avatars').deleteByName(user.username); } - RocketChat.models.Integrations.disableByUserId(userId); // Disables all the integrations which rely on the user being deleted. - RocketChat.Notifications.notifyLogged('Users:Deleted', { userId }); + Integrations.disableByUserId(userId); // Disables all the integrations which rely on the user being deleted. + Notifications.notifyLogged('Users:Deleted', { userId }); } - RocketChat.models.Users.removeById(userId); // Remove user from users database + Users.removeById(userId); // Remove user from users database }; diff --git a/packages/rocketchat-lib/server/functions/getFullUserData.js b/packages/rocketchat-lib/server/functions/getFullUserData.js index dfe562daf9e3..78ccac34e372 100644 --- a/packages/rocketchat-lib/server/functions/getFullUserData.js +++ b/packages/rocketchat-lib/server/functions/getFullUserData.js @@ -1,5 +1,8 @@ import s from 'underscore.string'; import { Logger } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; const logger = new Logger('getFullUserData'); @@ -28,7 +31,7 @@ const fullFields = { let publicCustomFields = {}; let customFields = {}; -RocketChat.settings.get('Accounts_CustomFields', (key, value) => { +settings.get('Accounts_CustomFields', (key, value) => { publicCustomFields = {}; customFields = {}; @@ -52,9 +55,9 @@ RocketChat.settings.get('Accounts_CustomFields', (key, value) => { RocketChat.getFullUserData = function({ userId, filter, limit: l }) { const username = s.trim(filter); - const userToRetrieveFullUserData = RocketChat.models.Users.findOneByUsername(username); + const userToRetrieveFullUserData = Users.findOneByUsername(username); const isMyOwnInfo = userToRetrieveFullUserData && userToRetrieveFullUserData._id === userId; - const viewFullOtherUserInfo = RocketChat.authz.hasPermission(userId, 'view-full-other-user-info'); + const viewFullOtherUserInfo = hasPermission(userId, 'view-full-other-user-info'); const limit = !viewFullOtherUserInfo ? 1 : l; if (!username && limit <= 1) { @@ -72,11 +75,11 @@ RocketChat.getFullUserData = function({ userId, filter, limit: l }) { }; if (!username) { - return RocketChat.models.Users.find({}, options); + return Users.find({}, options); } if (limit === 1) { - return RocketChat.models.Users.findByUsername(username, options); + return Users.findByUsername(username, options); } const usernameReg = new RegExp(s.escapeRegExp(username), 'i'); - return RocketChat.models.Users.findByUsernameNameOrEmailAddress(usernameReg, options); + return Users.findByUsernameNameOrEmailAddress(usernameReg, options); }; diff --git a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js index 89a88f11ad53..5a0ff29f2ed5 100644 --- a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js +++ b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Users, Subscriptions } from 'meteor/rocketchat:models'; import _ from 'underscore'; RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOptionToJoin({ currentUserId, nameOrId, type = '', tryDirectByUserIdOnly = false, joinChannel = true, errorOnEmpty = true }) { @@ -7,22 +8,22 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp // If the nameOrId starts with #, then let's try to find a channel or group if (nameOrId.startsWith('#')) { nameOrId = nameOrId.substring(1); - room = RocketChat.models.Rooms.findOneByIdOrName(nameOrId); + room = Rooms.findOneByIdOrName(nameOrId); } else if (nameOrId.startsWith('@') || type === 'd') { // If the nameOrId starts with @ OR type is 'd', then let's try just a direct message nameOrId = nameOrId.replace('@', ''); let roomUser; if (tryDirectByUserIdOnly) { - roomUser = RocketChat.models.Users.findOneById(nameOrId); + roomUser = Users.findOneById(nameOrId); } else { - roomUser = RocketChat.models.Users.findOne({ + roomUser = Users.findOne({ $or: [{ _id: nameOrId }, { username: nameOrId }], }); } const rid = _.isObject(roomUser) ? [currentUserId, roomUser._id].sort().join('') : nameOrId; - room = RocketChat.models.Rooms.findOneById(rid); + room = Rooms.findOneById(rid); // If the room hasn't been found yet, let's try some more if (!_.isObject(room)) { @@ -38,12 +39,12 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp room = Meteor.runAsUser(currentUserId, function() { const { rid } = Meteor.call('createDirectMessage', roomUser.username); - return RocketChat.models.Rooms.findOneById(rid); + return Rooms.findOneById(rid); }); } } else { // Otherwise, we'll treat this as a channel or group. - room = RocketChat.models.Rooms.findOneByIdOrName(nameOrId); + room = Rooms.findOneByIdOrName(nameOrId); } // If no room was found, handle the room return based upon errorOnEmpty @@ -67,7 +68,7 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp // If the room type is channel and joinChannel has been passed, try to join them // if they can't join the room, this will error out! if (room.t === 'c' && joinChannel) { - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, currentUserId); + const sub = Subscriptions.findOneByRoomIdAndUserId(room._id, currentUserId); if (!sub) { Meteor.runAsUser(currentUserId, function() { diff --git a/packages/rocketchat-lib/server/functions/isTheLastMessage.js b/packages/rocketchat-lib/server/functions/isTheLastMessage.js index c2bc6d0717f2..5fe73fb08de6 100644 --- a/packages/rocketchat-lib/server/functions/isTheLastMessage.js +++ b/packages/rocketchat-lib/server/functions/isTheLastMessage.js @@ -1 +1,3 @@ -RocketChat.isTheLastMessage = (room, message) => RocketChat.settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); +import { settings } from 'meteor/rocketchat:settings'; + +RocketChat.isTheLastMessage = (room, message) => settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); diff --git a/packages/rocketchat-lib/server/functions/loadMessageHistory.js b/packages/rocketchat-lib/server/functions/loadMessageHistory.js index 3110114b2f60..873a5aff01d9 100644 --- a/packages/rocketchat-lib/server/functions/loadMessageHistory.js +++ b/packages/rocketchat-lib/server/functions/loadMessageHistory.js @@ -1,6 +1,10 @@ +import { settings } from 'meteor/rocketchat:settings'; +import { Messages } from 'meteor/rocketchat:models'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; + const hideMessagesOfType = []; -RocketChat.settings.get(/Message_HideType_.+/, function(key, value) { +settings.get(/Message_HideType_.+/, function(key, value) { const type = key.replace('Message_HideType_', ''); const types = type === 'mute_unmute' ? ['user-muted', 'user-unmuted'] : [type]; @@ -25,7 +29,7 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit, }; - if (!RocketChat.settings.get('Message_ShowEditedStatus')) { + if (!settings.get('Message_ShowEditedStatus')) { options.fields = { editedAt: 0, }; @@ -33,11 +37,11 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, let records; if (end != null) { - records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestampNotContainingTypes(rid, end, hideMessagesOfType, options).fetch(); + records = Messages.findVisibleByRoomIdBeforeTimestampNotContainingTypes(rid, end, hideMessagesOfType, options).fetch(); } else { - records = RocketChat.models.Messages.findVisibleByRoomIdNotContainingTypes(rid, hideMessagesOfType, options).fetch(); + records = Messages.findVisibleByRoomIdNotContainingTypes(rid, hideMessagesOfType, options).fetch(); } - const messages = records.map((record) => RocketChat.composeMessageObjectWithUser(record, userId)); + const messages = records.map((record) => composeMessageObjectWithUser(record, userId)); let unreadNotLoaded = 0; let firstUnread; @@ -47,7 +51,7 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, if ((firstMessage != null ? firstMessage.ts : undefined) > ls) { delete options.limit; - const unreadMessages = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestampsNotContainingTypes(rid, ls, firstMessage.ts, hideMessagesOfType, { + const unreadMessages = Messages.findVisibleByRoomIdBetweenTimestampsNotContainingTypes(rid, ls, firstMessage.ts, hideMessagesOfType, { limit: 1, sort: { ts: 1, diff --git a/packages/rocketchat-lib/server/functions/notifications/audio.js b/packages/rocketchat-lib/server/functions/notifications/audio.js index 44b89a4acc64..737fbe219619 100644 --- a/packages/rocketchat-lib/server/functions/notifications/audio.js +++ b/packages/rocketchat-lib/server/functions/notifications/audio.js @@ -1,3 +1,7 @@ +import { metrics } from 'meteor/rocketchat:metrics'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; + export function shouldNotifyAudio({ disableAllMessageNotifications, status, @@ -17,7 +21,7 @@ export function shouldNotifyAudio({ return false; } - if (!audioNotifications && RocketChat.settings.get('Accounts_Default_User_Preferences_audioNotifications') === 'all') { + if (!audioNotifications && settings.get('Accounts_Default_User_Preferences_audioNotifications') === 'all') { return true; } @@ -25,8 +29,8 @@ export function shouldNotifyAudio({ } export function notifyAudioUser(userId, message, room) { - RocketChat.metrics.notificationsSent.inc({ notification_type: 'audio' }); - RocketChat.Notifications.notifyUser(userId, 'audioNotification', { + metrics.notificationsSent.inc({ notification_type: 'audio' }); + Notifications.notifyUser(userId, 'audioNotification', { payload: { _id: message._id, rid: message.rid, diff --git a/packages/rocketchat-lib/server/functions/notifications/desktop.js b/packages/rocketchat-lib/server/functions/notifications/desktop.js index 9ed6e61b1331..d95c833f6240 100644 --- a/packages/rocketchat-lib/server/functions/notifications/desktop.js +++ b/packages/rocketchat-lib/server/functions/notifications/desktop.js @@ -1,3 +1,7 @@ +import { metrics } from 'meteor/rocketchat:metrics'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { roomTypes } from 'meteor/rocketchat:utils'; /** * Send notification to user * @@ -16,10 +20,10 @@ export function notifyDesktopUser({ duration, notificationMessage, }) { - const { title, text } = RocketChat.roomTypes.getConfig(room.t).getNotificationDetails(room, user, notificationMessage); + const { title, text } = roomTypes.getConfig(room.t).getNotificationDetails(room, user, notificationMessage); - RocketChat.metrics.notificationsSent.inc({ notification_type: 'desktop' }); - RocketChat.Notifications.notifyUser(userId, 'notification', { + metrics.notificationsSent.inc({ notification_type: 'desktop' }); + Notifications.notifyUser(userId, 'notification', { title, text, duration, @@ -57,10 +61,10 @@ export function shouldNotifyDesktop({ } if (!desktopNotifications) { - if (RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'all') { + if (settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'all') { return true; } - if (RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'nothing') { + if (settings.get('Accounts_Default_User_Preferences_desktopNotifications') === 'nothing') { return false; } } diff --git a/packages/rocketchat-lib/server/functions/notifications/email.js b/packages/rocketchat-lib/server/functions/notifications/email.js index 98abcff2b18a..64ed6e2c7968 100644 --- a/packages/rocketchat-lib/server/functions/notifications/email.js +++ b/packages/rocketchat-lib/server/functions/notifications/email.js @@ -2,11 +2,15 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import s from 'underscore.string'; import * as Mailer from 'meteor/rocketchat:mailer'; +import { settings } from 'meteor/rocketchat:settings'; +import { roomTypes } from 'meteor/rocketchat:utils'; +import { metrics } from 'meteor/rocketchat:metrics'; +import { callbacks } from 'meteor/rocketchat:callbacks'; let advice = ''; let goToMessage = ''; Meteor.startup(() => { - RocketChat.settings.get('email_style', function() { + settings.get('email_style', function() { goToMessage = Mailer.inlinecss('

{Offline_Link_Message}

'); }); Mailer.getTemplate('Email_Footer_Direct_Reply', (value) => { @@ -15,10 +19,10 @@ Meteor.startup(() => { }); function getEmailContent({ message, user, room }) { - const lng = (user && user.language) || RocketChat.settings.get('language') || 'en'; + const lng = (user && user.language) || settings.get('language') || 'en'; - const roomName = s.escapeHTML(`#${ RocketChat.roomTypes.getRoomName(room.t, room) }`); - const userName = s.escapeHTML(RocketChat.settings.get('UI_Use_Real_Name') ? message.u.name || message.u.username : message.u.username); + const roomName = s.escapeHTML(`#${ roomTypes.getRoomName(room.t, room) }`); + const userName = s.escapeHTML(settings.get('UI_Use_Real_Name') ? message.u.name || message.u.username : message.u.username); const header = TAPi18n.__(room.t === 'd' ? 'User_sent_a_message_to_you' : 'User_sent_a_message_on_channel', { username: userName, @@ -33,7 +37,7 @@ function getEmailContent({ message, user, room }) { messageContent = TAPi18n.__('Encrypted_message', { lng }); } - message = RocketChat.callbacks.run('renderMessage', message); + message = callbacks.run('renderMessage', message); if (message.tokens && message.tokens.length > 0) { message.tokens.forEach((token) => { token.text = token.text.replace(/([^\$])(\$[^\$])/gm, '$1$$$2'); @@ -78,7 +82,7 @@ function getEmailContent({ message, user, room }) { } export function sendEmail({ message, user, subscription, room, emailAddress, hasMentionToUser }) { - const username = RocketChat.settings.get('UI_Use_Real_Name') ? message.u.name : message.u.username; + const username = settings.get('UI_Use_Real_Name') ? message.u.name : message.u.username; let subjectKey = 'Offline_Mention_All_Email'; if (room.t === 'd') { @@ -87,9 +91,9 @@ export function sendEmail({ message, user, subscription, room, emailAddress, has subjectKey = 'Offline_Mention_Email'; } - const emailSubject = Mailer.replace(RocketChat.settings.get(subjectKey), { + const emailSubject = Mailer.replace(settings.get(subjectKey), { user: username, - room: RocketChat.roomTypes.getRoomName(room.t, room), + room: roomTypes.getRoomName(room.t, room), }); const content = getEmailContent({ message, @@ -97,29 +101,29 @@ export function sendEmail({ message, user, subscription, room, emailAddress, has room, }); - const room_path = RocketChat.roomTypes.getURL(room.t, subscription); + const room_path = roomTypes.getURL(room.t, subscription); const email = { to: emailAddress, subject: emailSubject, - html: content + goToMessage + (RocketChat.settings.get('Direct_Reply_Enable') ? advice : ''), + html: content + goToMessage + (settings.get('Direct_Reply_Enable') ? advice : ''), data: { room_path, }, }; const from = room.t === 'd' ? message.u.name : room.name; // using user full-name/channel name in from address - email.from = `${ String(from).replace(/@/g, '%40').replace(/[<>,]/g, '') } <${ RocketChat.settings.get('From_Email') }>`; + email.from = `${ String(from).replace(/@/g, '%40').replace(/[<>,]/g, '') } <${ settings.get('From_Email') }>`; // If direct reply enabled, email content with headers - if (RocketChat.settings.get('Direct_Reply_Enable')) { - const replyto = RocketChat.settings.get('Direct_Reply_ReplyTo') || RocketChat.settings.get('Direct_Reply_Username'); + if (settings.get('Direct_Reply_Enable')) { + const replyto = settings.get('Direct_Reply_ReplyTo') || settings.get('Direct_Reply_Username'); email.headers = { // Reply-To header with format "username+messageId@domain" - 'Reply-To': `${ replyto.split('@')[0].split(RocketChat.settings.get('Direct_Reply_Separator'))[0] }${ RocketChat.settings.get('Direct_Reply_Separator') }${ message._id }@${ replyto.split('@')[1] }`, + 'Reply-To': `${ replyto.split('@')[0].split(settings.get('Direct_Reply_Separator'))[0] }${ settings.get('Direct_Reply_Separator') }${ message._id }@${ replyto.split('@')[1] }`, }; } - RocketChat.metrics.notificationsSent.inc({ notification_type: 'email' }); + metrics.notificationsSent.inc({ notification_type: 'email' }); return Mailer.send(email); } @@ -150,7 +154,7 @@ export function shouldNotifyEmail({ } // default server preference is disabled - if (RocketChat.settings.get('Accounts_Default_User_Preferences_emailNotificationMode') === 'nothing') { + if (settings.get('Accounts_Default_User_Preferences_emailNotificationMode') === 'nothing') { return false; } } diff --git a/packages/rocketchat-lib/server/functions/notifications/index.js b/packages/rocketchat-lib/server/functions/notifications/index.js index e2316590a351..8d71d8b28240 100644 --- a/packages/rocketchat-lib/server/functions/notifications/index.js +++ b/packages/rocketchat-lib/server/functions/notifications/index.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; /** @@ -9,13 +10,13 @@ import s from 'underscore.string'; */ export function parseMessageTextPerUser(messageText, message, receiver) { if (!message.msg && message.attachments && message.attachments[0]) { - const lng = receiver.language || RocketChat.settings.get('language') || 'en'; + const lng = receiver.language || settings.get('language') || 'en'; return message.attachments[0].image_type ? TAPi18n.__('User_uploaded_image', { lng }) : TAPi18n.__('User_uploaded_file', { lng }); } if (message.msg && message.t === 'e2e') { - const lng = receiver.language || RocketChat.settings.get('language') || 'en'; + const lng = receiver.language || settings.get('language') || 'en'; return TAPi18n.__('Encrypted_message', { lng }); } diff --git a/packages/rocketchat-lib/server/functions/notifications/mobile.js b/packages/rocketchat-lib/server/functions/notifications/mobile.js index 9bcf0ac494af..4460f4106eb4 100644 --- a/packages/rocketchat-lib/server/functions/notifications/mobile.js +++ b/packages/rocketchat-lib/server/functions/notifications/mobile.js @@ -1,16 +1,20 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { roomTypes } from 'meteor/rocketchat:utils'; +import { PushNotification } from 'meteor/rocketchat:push-notifications'; const CATEGORY_MESSAGE = 'MESSAGE'; const CATEGORY_MESSAGE_NOREPLY = 'MESSAGE_NOREPLY'; let alwaysNotifyMobileBoolean; -RocketChat.settings.get('Notifications_Always_Notify_Mobile', (key, value) => { +settings.get('Notifications_Always_Notify_Mobile', (key, value) => { alwaysNotifyMobileBoolean = value; }); let SubscriptionRaw; Meteor.startup(() => { - SubscriptionRaw = RocketChat.models.Subscriptions.model.rawCollection(); + SubscriptionRaw = Subscriptions.model.rawCollection(); }); async function getBadgeCount(userId) { @@ -34,11 +38,11 @@ function canSendMessageToRoom(room, username) { export async function sendSinglePush({ room, message, userId, receiverUsername, senderUsername, senderName, notificationMessage }) { let username = ''; - if (RocketChat.settings.get('Push_show_username_room')) { - username = RocketChat.settings.get('UI_Use_Real_Name') === true ? senderName : senderUsername; + if (settings.get('Push_show_username_room')) { + username = settings.get('UI_Use_Real_Name') === true ? senderName : senderUsername; } - RocketChat.PushNotification.send({ + PushNotification.send({ roomId: message.rid, payload: { host: Meteor.absoluteUrl(), @@ -49,9 +53,9 @@ export async function sendSinglePush({ room, message, userId, receiverUsername, messageType: message.t, messageId: message._id, }, - roomName: RocketChat.settings.get('Push_show_username_room') && room.t !== 'd' ? `#${ RocketChat.roomTypes.getRoomName(room.t, room) }` : '', + roomName: settings.get('Push_show_username_room') && room.t !== 'd' ? `#${ roomTypes.getRoomName(room.t, room) }` : '', username, - message: RocketChat.settings.get('Push_show_message') ? notificationMessage : ' ', + message: settings.get('Push_show_message') ? notificationMessage : ' ', badge: await getBadgeCount(userId), usersTo: { userId, @@ -82,10 +86,10 @@ export function shouldNotifyMobile({ } if (!mobilePushNotifications) { - if (RocketChat.settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'all') { + if (settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'all') { return true; } - if (RocketChat.settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'nothing') { + if (settings.get('Accounts_Default_User_Preferences_mobileNotifications') === 'nothing') { return false; } } diff --git a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js index f09aea6ad2ed..2eb8ceed6737 100644 --- a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js +++ b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js @@ -1,27 +1,29 @@ import { Meteor } from 'meteor/meteor'; +import { Rooms, Messages, Subscriptions } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.removeUserFromRoom = function(rid, user) { - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (room) { - RocketChat.callbacks.run('beforeLeaveRoom', user, room); + callbacks.run('beforeLeaveRoom', user, room); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); if (subscription) { const removedUser = user; - RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser(rid, removedUser); + Messages.createUserLeaveWithRoomIdAndUser(rid, removedUser); } if (room.t === 'l') { - RocketChat.models.Messages.createCommandWithRoomIdAndUser('survey', rid, user); + Messages.createCommandWithRoomIdAndUser('survey', rid, user); } - RocketChat.models.Subscriptions.removeByRoomIdAndUserId(rid, user._id); + Subscriptions.removeByRoomIdAndUserId(rid, user._id); Meteor.defer(function() { // TODO: CACHE: maybe a queue? - RocketChat.callbacks.run('afterLeaveRoom', user, room); + callbacks.run('afterLeaveRoom', user, room); }); } }; diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 7336a6056c53..86f9f3dab82a 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -1,7 +1,8 @@ +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; RocketChat.saveCustomFields = function(userId, formData) { - if (s.trim(RocketChat.settings.get('Accounts_CustomFields')) !== '') { + if (s.trim(settings.get('Accounts_CustomFields')) !== '') { RocketChat.validateCustomFields(formData); return RocketChat.saveCustomFieldsWithoutValidation(userId, formData); } diff --git a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js index f1c418193a34..e73019e5c14f 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js @@ -1,21 +1,23 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; import s from 'underscore.string'; RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { - if (s.trim(RocketChat.settings.get('Accounts_CustomFields')) !== '') { + if (s.trim(settings.get('Accounts_CustomFields')) !== '') { let customFieldsMeta; try { - customFieldsMeta = JSON.parse(RocketChat.settings.get('Accounts_CustomFields')); + customFieldsMeta = JSON.parse(settings.get('Accounts_CustomFields')); } catch (e) { throw new Meteor.Error('error-invalid-customfield-json', 'Invalid JSON for Custom Fields'); } const customFields = {}; Object.keys(customFieldsMeta).forEach((key) => customFields[key] = formData[key]); - RocketChat.models.Users.setCustomFields(userId, customFields); + Users.setCustomFields(userId, customFields); // Update customFields of all Direct Messages' Rooms for userId - RocketChat.models.Subscriptions.setCustomFieldsDirectMessagesByUserId(userId, customFields); + Subscriptions.setCustomFieldsDirectMessagesByUserId(userId, customFields); Object.keys(customFields).forEach((fieldName) => { if (!customFieldsMeta[fieldName].modifyRecordField) { @@ -32,7 +34,7 @@ RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { update.$set[modifyRecordField.field] = customFields[fieldName]; } - RocketChat.models.Users.update(userId, update); + Users.update(userId, update); }); } }; diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index e165382816cc..14aa68429611 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -4,6 +4,11 @@ import _ from 'underscore'; import s from 'underscore.string'; import * as Mailer from 'meteor/rocketchat:mailer'; import { Gravatar } from 'meteor/jparker:gravatar'; +import { getRoles, hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import PasswordPolicy from '../lib/PasswordPolicyClass'; + +const passwordPolicy = new PasswordPolicy(); let html = ''; Meteor.startup(() => { @@ -13,16 +18,16 @@ Meteor.startup(() => { }); function validateUserData(userId, userData) { - const existingRoles = _.pluck(RocketChat.authz.getRoles(), '_id'); + const existingRoles = _.pluck(getRoles(), '_id'); - if (userData._id && userId !== userData._id && !RocketChat.authz.hasPermission(userId, 'edit-other-user-info')) { + if (userData._id && userId !== userData._id && !hasPermission(userId, 'edit-other-user-info')) { throw new Meteor.Error('error-action-not-allowed', 'Editing user is not allowed', { method: 'insertOrUpdateUser', action: 'Editing_user', }); } - if (!userData._id && !RocketChat.authz.hasPermission(userId, 'create-user')) { + if (!userData._id && !hasPermission(userId, 'create-user')) { throw new Meteor.Error('error-action-not-allowed', 'Adding user is not allowed', { method: 'insertOrUpdateUser', action: 'Adding_user', @@ -36,7 +41,7 @@ function validateUserData(userId, userData) { }); } - if (userData.roles && _.indexOf(userData.roles, 'admin') >= 0 && !RocketChat.authz.hasPermission(userId, 'assign-admin-role')) { + if (userData.roles && _.indexOf(userData.roles, 'admin') >= 0 && !hasPermission(userId, 'assign-admin-role')) { throw new Meteor.Error('error-action-not-allowed', 'Assigning admin is not allowed', { method: 'insertOrUpdateUser', action: 'Assign_admin', @@ -60,7 +65,7 @@ function validateUserData(userId, userData) { let nameValidation; try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (e) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } @@ -100,38 +105,38 @@ function validateUserData(userId, userData) { function validateUserEditing(userId, userData) { const editingMyself = userData._id && userId === userData._id; - const canEditOtherUserInfo = RocketChat.authz.hasPermission(userId, 'edit-other-user-info'); - const canEditOtherUserPassword = RocketChat.authz.hasPermission(userId, 'edit-other-user-password'); + const canEditOtherUserInfo = hasPermission(userId, 'edit-other-user-info'); + const canEditOtherUserPassword = hasPermission(userId, 'edit-other-user-password'); - if (!RocketChat.settings.get('Accounts_AllowUserProfileChange') && !canEditOtherUserInfo && !canEditOtherUserPassword) { + if (!settings.get('Accounts_AllowUserProfileChange') && !canEditOtherUserInfo && !canEditOtherUserPassword) { throw new Meteor.Error('error-action-not-allowed', 'Edit user profile is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.username && !RocketChat.settings.get('Accounts_AllowUsernameChange') && (!canEditOtherUserInfo || editingMyself)) { + if (userData.username && !settings.get('Accounts_AllowUsernameChange') && (!canEditOtherUserInfo || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit username is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.name && !RocketChat.settings.get('Accounts_AllowRealNameChange') && (!canEditOtherUserInfo || editingMyself)) { + if (userData.name && !settings.get('Accounts_AllowRealNameChange') && (!canEditOtherUserInfo || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit user real name is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.email && !RocketChat.settings.get('Accounts_AllowEmailChange') && (!canEditOtherUserInfo || editingMyself)) { + if (userData.email && !settings.get('Accounts_AllowEmailChange') && (!canEditOtherUserInfo || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit user email is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', }); } - if (userData.password && !RocketChat.settings.get('Accounts_AllowPasswordChange') && (!canEditOtherUserPassword || editingMyself)) { + if (userData.password && !settings.get('Accounts_AllowPasswordChange') && (!canEditOtherUserPassword || editingMyself)) { throw new Meteor.Error('error-action-not-allowed', 'Edit user password is not allowed', { method: 'insertOrUpdateUser', action: 'Update_user', @@ -176,11 +181,11 @@ RocketChat.saveUser = function(userId, userData) { Meteor.users.update({ _id }, updateUser); if (userData.sendWelcomeEmail) { - const subject = RocketChat.settings.get('Accounts_UserAddedEmail_Subject'); + const subject = settings.get('Accounts_UserAddedEmail_Subject'); const email = { to: userData.email, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), subject, html, data: { @@ -202,7 +207,7 @@ RocketChat.saveUser = function(userId, userData) { userData._id = _id; - if (RocketChat.settings.get('Accounts_SetDefaultAvatar') === true && userData.email) { + if (settings.get('Accounts_SetDefaultAvatar') === true && userData.email) { const gravatarUrl = Gravatar.imageUrl(userData.email, { default: '404', size: 200, secure: true }); try { @@ -231,7 +236,7 @@ RocketChat.saveUser = function(userId, userData) { RocketChat.setEmail(userData._id, userData.email, shouldSendVerificationEmailToUser); } - if (userData.password && userData.password.trim() && RocketChat.authz.hasPermission(userId, 'edit-other-user-password') && RocketChat.passwordPolicy.validate(userData.password)) { + if (userData.password && userData.password.trim() && hasPermission(userId, 'edit-other-user-password') && passwordPolicy.validate(userData.password)) { Accounts.setPassword(userData._id, userData.password.trim()); } diff --git a/packages/rocketchat-lib/server/functions/sendMessage.js b/packages/rocketchat-lib/server/functions/sendMessage.js index 4a5218e7ad65..952b27895100 100644 --- a/packages/rocketchat-lib/server/functions/sendMessage.js +++ b/packages/rocketchat-lib/server/functions/sendMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Messages } from 'meteor/rocketchat:models'; const objectMaybeIncluding = (types) => Match.Where((value) => { Object.keys(types).forEach((field) => { @@ -113,7 +116,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { message.ts = new Date(); } - if (RocketChat.settings.get('Message_Read_Receipt_Enabled')) { + if (settings.get('Message_Read_Receipt_Enabled')) { message.unread = true; } @@ -148,7 +151,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { delete message.tokens; } - message = RocketChat.callbacks.run('beforeSaveMessage', message); + message = callbacks.run('beforeSaveMessage', message); if (message) { // Avoid saving sandstormSessionId to the database let sandstormSessionId = null; @@ -160,13 +163,13 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { if (message._id && upsert) { const { _id } = message; delete message._id; - RocketChat.models.Messages.upsert({ + Messages.upsert({ _id, 'u._id': message.u._id, }, message); message._id = _id; } else { - message._id = RocketChat.models.Messages.insert(message); + message._id = Messages.insert(message); } if (Apps && Apps.isLoaded()) { @@ -181,7 +184,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { Meteor.defer(() => { // Execute all callbacks message.sandstormSessionId = sandstormSessionId; - return RocketChat.callbacks.run('afterSaveMessage', message, room, user._id); + return callbacks.run('afterSaveMessage', message, room, user._id); }); return message; } diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index e947d5bfa514..ad05ef2fe3d7 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -1,4 +1,6 @@ import { Meteor } from 'meteor/meteor'; +import { Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = true) { @@ -13,7 +15,7 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru RocketChat.validateEmailDomain(email); - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); // User already has desired username, return if (user.emails && user.emails[0] && user.emails[0].address === email) { @@ -26,7 +28,7 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru } // Set new email - RocketChat.models.Users.setEmail(user._id, email); + Users.setEmail(user._id, email); user.email = email; if (shouldSendVerificationEmail === true) { Meteor.call('sendConfirmationEmail', user.email); @@ -35,5 +37,5 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru }; RocketChat.setEmail = RocketChat.RateLimiter.limitFunction(RocketChat._setEmail, 1, 60000, { - 0() { return !Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those + 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index 6bf2f183ef75..0cfac9bf3f87 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -1,4 +1,8 @@ import { Meteor } from 'meteor/meteor'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; RocketChat._setRealName = function(userId, name) { @@ -7,7 +11,7 @@ RocketChat._setRealName = function(userId, name) { return false; } - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); // User already has desired name, return if (user.name === name) { @@ -15,13 +19,13 @@ RocketChat._setRealName = function(userId, name) { } // Set new name - RocketChat.models.Users.setName(user._id, name); + Users.setName(user._id, name); user.name = name; - RocketChat.models.Subscriptions.updateDirectFNameByName(user.username, name); + Subscriptions.updateDirectFNameByName(user.username, name); - if (RocketChat.settings.get('UI_Use_Real_Name') === true) { - RocketChat.Notifications.notifyLogged('Users:NameChanged', { + if (settings.get('UI_Use_Real_Name') === true) { + Notifications.notifyLogged('Users:NameChanged', { _id: user._id, name: user.name, username: user.username, @@ -32,5 +36,5 @@ RocketChat._setRealName = function(userId, name) { }; RocketChat.setRealName = RocketChat.RateLimiter.limitFunction(RocketChat._setRealName, 1, 60000, { - 0() { return !Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those + 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setUserAvatar.js b/packages/rocketchat-lib/server/functions/setUserAvatar.js index df3b2e888cdb..4335123d0983 100644 --- a/packages/rocketchat-lib/server/functions/setUserAvatar.js +++ b/packages/rocketchat-lib/server/functions/setUserAvatar.js @@ -2,13 +2,15 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; import { RocketChatFile } from 'meteor/rocketchat:file'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Users } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { let encoding; let image; if (service === 'initials') { - return RocketChat.models.Users.setAvatarOrigin(user._id, service); + return Users.setAvatarOrigin(user._id, service); } else if (service === 'url') { let result = null; @@ -56,8 +58,8 @@ RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { fileStore.insert(file, buffer, () => { Meteor.setTimeout(function() { - RocketChat.models.Users.setAvatarOrigin(user._id, service); - RocketChat.Notifications.notifyLogged('updateAvatar', { username: user.username }); + Users.setAvatarOrigin(user._id, service); + Notifications.notifyLogged('updateAvatar', { username: user.username }); }, 500); }); }; diff --git a/packages/rocketchat-lib/server/functions/setUsername.js b/packages/rocketchat-lib/server/functions/setUsername.js index a0d45b3f03d6..6003a7abaa45 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.js +++ b/packages/rocketchat-lib/server/functions/setUsername.js @@ -1,6 +1,9 @@ import s from 'underscore.string'; import { Accounts } from 'meteor/accounts-base'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users, Messages, Subscriptions, Rooms } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; RocketChat._setUsername = function(userId, u) { const username = s.trim(u); @@ -9,14 +12,14 @@ RocketChat._setUsername = function(userId, u) { } let nameValidation; try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (error) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } if (!nameValidation.test(username)) { return false; } - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); // User already has desired username, return if (user.username === username) { return user; @@ -30,16 +33,16 @@ RocketChat._setUsername = function(userId, u) { } // If first time setting username, send Enrollment Email try { - if (!previousUsername && user.emails && user.emails.length > 0 && RocketChat.settings.get('Accounts_Enrollment_Email')) { + if (!previousUsername && user.emails && user.emails.length > 0 && settings.get('Accounts_Enrollment_Email')) { Accounts.sendEnrollmentEmail(user._id); } } catch (e) { console.error(e); } // Set new username* - RocketChat.models.Users.setUsername(user._id, username); + Users.setUsername(user._id, username); user.username = username; - if (!previousUsername && RocketChat.settings.get('Accounts_SetDefaultAvatar') === true) { + if (!previousUsername && settings.get('Accounts_SetDefaultAvatar') === true) { const avatarSuggestions = getAvatarSuggestionForUser(user); let gravatar; Object.keys(avatarSuggestions).some((service) => { @@ -58,17 +61,17 @@ RocketChat._setUsername = function(userId, u) { } // Username is available; if coming from old username, update all references if (previousUsername) { - RocketChat.models.Messages.updateAllUsernamesByUserId(user._id, username); - RocketChat.models.Messages.updateUsernameOfEditByUserId(user._id, username); - RocketChat.models.Messages.findByMention(previousUsername).forEach(function(msg) { + Messages.updateAllUsernamesByUserId(user._id, username); + Messages.updateUsernameOfEditByUserId(user._id, username); + Messages.findByMention(previousUsername).forEach(function(msg) { const updatedMsg = msg.msg.replace(new RegExp(`@${ previousUsername }`, 'ig'), `@${ username }`); - return RocketChat.models.Messages.updateUsernameAndMessageOfMentionByIdAndOldUsername(msg._id, previousUsername, username, updatedMsg); + return Messages.updateUsernameAndMessageOfMentionByIdAndOldUsername(msg._id, previousUsername, username, updatedMsg); }); - RocketChat.models.Rooms.replaceUsername(previousUsername, username); - RocketChat.models.Rooms.replaceMutedUsername(previousUsername, username); - RocketChat.models.Rooms.replaceUsernameOfUserByUserId(user._id, username); - RocketChat.models.Subscriptions.setUserUsernameByUserId(user._id, username); - RocketChat.models.Subscriptions.setNameForDirectRoomsWithOldName(previousUsername, username); + Rooms.replaceUsername(previousUsername, username); + Rooms.replaceMutedUsername(previousUsername, username); + Rooms.replaceUsernameOfUserByUserId(user._id, username); + Subscriptions.setUserUsernameByUserId(user._id, username); + Subscriptions.setNameForDirectRoomsWithOldName(previousUsername, username); RocketChat.models.LivechatDepartmentAgents.replaceUsernameOfAgentByUserId(user._id, username); const fileStore = FileUpload.getStore('Avatars'); @@ -82,6 +85,6 @@ RocketChat._setUsername = function(userId, u) { RocketChat.setUsername = RocketChat.RateLimiter.limitFunction(RocketChat._setUsername, 1, 60000, { [0](userId) { - return !userId || !RocketChat.authz.hasPermission(userId, 'edit-other-user-info'); + return !userId || !hasPermission(userId, 'edit-other-user-info'); }, }); diff --git a/packages/rocketchat-lib/server/functions/unarchiveRoom.js b/packages/rocketchat-lib/server/functions/unarchiveRoom.js index 3884e06c4041..9cce78e07e1d 100644 --- a/packages/rocketchat-lib/server/functions/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/functions/unarchiveRoom.js @@ -1,4 +1,6 @@ +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; + RocketChat.unarchiveRoom = function(rid) { - RocketChat.models.Rooms.unarchiveById(rid); - RocketChat.models.Subscriptions.unarchiveByRoomId(rid); + Rooms.unarchiveById(rid); + Subscriptions.unarchiveByRoomId(rid); }; diff --git a/packages/rocketchat-lib/server/functions/updateMessage.js b/packages/rocketchat-lib/server/functions/updateMessage.js index 950454594c95..82158b41dc12 100644 --- a/packages/rocketchat-lib/server/functions/updateMessage.js +++ b/packages/rocketchat-lib/server/functions/updateMessage.js @@ -1,8 +1,11 @@ import { Meteor } from 'meteor/meteor'; +import { Messages, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; RocketChat.updateMessage = function(message, user, originalMessage) { if (!originalMessage) { - originalMessage = RocketChat.models.Messages.findOneById(message._id); + originalMessage = Messages.findOneById(message._id); } // For the Rocket.Chat Apps :) @@ -24,8 +27,8 @@ RocketChat.updateMessage = function(message, user, originalMessage) { } // If we keep history of edits, insert a new message to store history information - if (RocketChat.settings.get('Message_KeepHistory')) { - RocketChat.models.Messages.cloneAndSaveAsHistoryById(message._id); + if (settings.get('Message_KeepHistory')) { + Messages.cloneAndSaveAsHistoryById(message._id); } message.editedAt = new Date(); @@ -37,14 +40,14 @@ RocketChat.updateMessage = function(message, user, originalMessage) { const urls = message.msg.match(/([A-Za-z]{3,9}):\/\/([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((\/[-\+=!:~%\/\.@\,\w]*)?\??([-\+=&!:;%@\/\.\,\w]+)?(?:#([^\s\)]+))?)?/g) || []; message.urls = urls.map((url) => ({ url })); - message = RocketChat.callbacks.run('beforeSaveMessage', message); + message = callbacks.run('beforeSaveMessage', message); const tempid = message._id; delete message._id; - RocketChat.models.Messages.update({ _id: tempid }, { $set: message }); + Messages.update({ _id: tempid }, { $set: message }); - const room = RocketChat.models.Rooms.findOneById(message.rid); + const room = Rooms.findOneById(message.rid); if (Apps && Apps.isLoaded()) { // This returns a promise, but it won't mutate anything about the message @@ -53,6 +56,6 @@ RocketChat.updateMessage = function(message, user, originalMessage) { } Meteor.defer(function() { - RocketChat.callbacks.run('afterSaveMessage', RocketChat.models.Messages.findOneById(tempid), room, user._id); + callbacks.run('afterSaveMessage', Messages.findOneById(tempid), room, user._id); }); }; diff --git a/packages/rocketchat-lib/server/functions/validateCustomFields.js b/packages/rocketchat-lib/server/functions/validateCustomFields.js index 26ccace4102b..f2d5bff1aba5 100644 --- a/packages/rocketchat-lib/server/functions/validateCustomFields.js +++ b/packages/rocketchat-lib/server/functions/validateCustomFields.js @@ -1,16 +1,17 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; RocketChat.validateCustomFields = function(fields) { // Special Case: // If an admin didn't set any custom fields there's nothing to validate against so consider any customFields valid - if (s.trim(RocketChat.settings.get('Accounts_CustomFields')) === '') { + if (s.trim(settings.get('Accounts_CustomFields')) === '') { return; } let customFieldsMeta; try { - customFieldsMeta = JSON.parse(RocketChat.settings.get('Accounts_CustomFields')); + customFieldsMeta = JSON.parse(settings.get('Accounts_CustomFields')); } catch (e) { throw new Meteor.Error('error-invalid-customfield-json', 'Invalid JSON for Custom Fields'); } diff --git a/packages/rocketchat-lib/server/lib/PushNotification_import.js b/packages/rocketchat-lib/server/lib/PushNotification_import.js new file mode 100644 index 000000000000..05c2ab4b2d11 --- /dev/null +++ b/packages/rocketchat-lib/server/lib/PushNotification_import.js @@ -0,0 +1,3 @@ +import { PushNotification } from 'meteor/rocketchat:push-notifications'; + +RocketChat.PushNotification = PushNotification; diff --git a/packages/rocketchat-lib/server/models/index.js b/packages/rocketchat-lib/server/models/index.js index a5602f4dfe8a..a7620e0667d1 100644 --- a/packages/rocketchat-lib/server/models/index.js +++ b/packages/rocketchat-lib/server/models/index.js @@ -10,8 +10,10 @@ import { UserDataFiles, Users, CustomSounds, + Integrations, + IntegrationHistory, + Base as _Base, } from 'meteor/rocketchat:models'; -import { Base as _Base } from 'meteor/rocketchat:models'; Object.assign(RocketChat.models, { _Base, @@ -26,4 +28,6 @@ Object.assign(RocketChat.models, { UserDataFiles, Users, CustomSounds, + Integrations, + IntegrationHistory, }); diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index d504e4720ca2..524abe1f5db4 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -14,6 +14,8 @@ import Statistics from './models/Statistics'; import Permissions from './models/Permissions'; import Roles from './models/Roles'; import CustomSounds from './models/CustomSounds'; +import Integrations from './models/Integrations'; +import IntegrationHistory from './models/IntegrationHistory'; export { Base, @@ -32,4 +34,6 @@ export { Permissions, Roles, CustomSounds, + Integrations, + IntegrationHistory, }; diff --git a/packages/rocketchat-integrations/server/models/IntegrationHistory.js b/packages/rocketchat-models/server/models/IntegrationHistory.js similarity index 85% rename from packages/rocketchat-integrations/server/models/IntegrationHistory.js rename to packages/rocketchat-models/server/models/IntegrationHistory.js index 138979e29939..bda9b16c5388 100644 --- a/packages/rocketchat-integrations/server/models/IntegrationHistory.js +++ b/packages/rocketchat-models/server/models/IntegrationHistory.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.IntegrationHistory = new class IntegrationHistory extends RocketChat.models._Base { +export class IntegrationHistory extends Base { constructor() { super('integration_history'); } @@ -37,4 +37,7 @@ RocketChat.models.IntegrationHistory = new class IntegrationHistory extends Rock removeByIntegrationId(integrationId) { return this.remove({ 'integration._id': integrationId }); } -}; +} + +export default new IntegrationHistory(); + diff --git a/packages/rocketchat-integrations/server/models/Integrations.js b/packages/rocketchat-models/server/models/Integrations.js similarity index 73% rename from packages/rocketchat-integrations/server/models/Integrations.js rename to packages/rocketchat-models/server/models/Integrations.js index 8759d25a1ca0..7686e7d56326 100644 --- a/packages/rocketchat-integrations/server/models/Integrations.js +++ b/packages/rocketchat-models/server/models/Integrations.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.Integrations = new class Integrations extends RocketChat.models._Base { +export class Integrations extends Base { constructor() { super('integrations'); } @@ -17,4 +17,6 @@ RocketChat.models.Integrations = new class Integrations extends RocketChat.model disableByUserId(userId) { return this.update({ userId }, { $set: { enabled: false } }, { multi: true }); } -}; +} + +export default new Integrations(); diff --git a/packages/rocketchat-push-notifications/package.js b/packages/rocketchat-push-notifications/package.js index acf4b16dabff..b920d7734a26 100644 --- a/packages/rocketchat-push-notifications/package.js +++ b/packages/rocketchat-push-notifications/package.js @@ -13,7 +13,9 @@ Package.onUse(function(api) { 'rocketchat:models', 'rocketchat:custom-sounds', 'rocketchat:settings', + 'rocketchat:metrics', 'rocketchat:ui', + 'rocketchat:push', 'templating', ]); api.addFiles('client/stylesheets/pushNotifications.css', 'client'); diff --git a/packages/rocketchat-push-notifications/server/index.js b/packages/rocketchat-push-notifications/server/index.js index 7ee7efc55a06..c7499a51ee6a 100644 --- a/packages/rocketchat-push-notifications/server/index.js +++ b/packages/rocketchat-push-notifications/server/index.js @@ -1 +1,6 @@ import './methods/saveNotificationSettings'; +import PushNotification from './lib/PushNotification'; + +export { + PushNotification, +}; diff --git a/packages/rocketchat-lib/server/lib/PushNotification.js b/packages/rocketchat-push-notifications/server/lib/PushNotification.js similarity index 77% rename from packages/rocketchat-lib/server/lib/PushNotification.js rename to packages/rocketchat-push-notifications/server/lib/PushNotification.js index fea610a53521..e1da63d9a9f4 100644 --- a/packages/rocketchat-lib/server/lib/PushNotification.js +++ b/packages/rocketchat-push-notifications/server/lib/PushNotification.js @@ -1,8 +1,10 @@ import { Push } from 'meteor/rocketchat:push'; +import { settings } from 'meteor/rocketchat:settings'; +import { metrics } from 'meteor/rocketchat:metrics'; -class PushNotification { +export class PushNotification { getNotificationId(roomId) { - const serverId = RocketChat.settings.get('uniqueID'); + const serverId = settings.get('uniqueID'); return this.hash(`${ serverId }|${ roomId }`); // hash } @@ -47,9 +49,9 @@ class PushNotification { }; } - RocketChat.metrics.notificationsSent.inc({ notification_type: 'mobile' }); + metrics.notificationsSent.inc({ notification_type: 'mobile' }); return Push.send(config); } } -RocketChat.PushNotification = new PushNotification(); +export default new PushNotification(); diff --git a/packages/rocketchat-utils/server/index.js b/packages/rocketchat-utils/server/index.js index 48af9bdf8458..c40c7e4517dc 100644 --- a/packages/rocketchat-utils/server/index.js +++ b/packages/rocketchat-utils/server/index.js @@ -14,3 +14,4 @@ export { getAvatarColor } from '../lib/getAvatarColor'; export { getURL } from '../lib/getURL'; export { getValidRoomName } from '../lib/getValidRoomName'; export { placeholders } from '../lib/placeholders'; +export { composeMessageObjectWithUser } from './lib/composeMessageObjectWithUser'; diff --git a/packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js b/packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js new file mode 100644 index 000000000000..af9c90df5ed9 --- /dev/null +++ b/packages/rocketchat-utils/server/lib/composeMessageObjectWithUser.js @@ -0,0 +1,23 @@ +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; + +const getUser = (userId) => Users.findOneById(userId); + +export const composeMessageObjectWithUser = function(message, userId) { + if (message) { + if (message.starred && Array.isArray(message.starred)) { + message.starred = message.starred.filter((star) => star._id === userId); + } + if (message.u && message.u._id && settings.get('UI_Use_Real_Name')) { + const user = getUser(message.u._id); + message.u.name = user && user.name; + } + if (message.mentions && message.mentions.length && settings.get('UI_Use_Real_Name')) { + message.mentions.forEach((mention) => { + const user = getUser(mention._id); + mention.name = user && user.name; + }); + } + } + return message; +}; From 2bf63fb89dbf5ae00d3bf7edeb8aad4aeab44c37 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Tue, 22 Jan 2019 16:35:35 -0200 Subject: [PATCH 04/33] Remove some dependencies inside rocketchat-lib/server/lib (#13217) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib --- packages/rocketchat-lib/server/lib/bugsnag.js | 8 ++-- .../rocketchat-lib/server/lib/configLogger.js | 7 ++-- packages/rocketchat-lib/server/lib/debug.js | 14 ++++--- .../server/lib/defaultBlockedDomainsList.js | 2 +- .../server/lib/interceptDirectReplyEmails.js | 27 +++++++------- .../server/lib/notifyUsersOnMessage.js | 37 ++++++++++--------- .../server/lib/passwordPolicy.js | 22 ++++++----- .../server/lib/processDirectEmail.js | 17 +++++---- .../server/lib/sendNotificationsOnMessage.js | 28 ++++++++------ .../server/lib/validateEmailDomain.js | 12 +++--- 10 files changed, 97 insertions(+), 77 deletions(-) diff --git a/packages/rocketchat-lib/server/lib/bugsnag.js b/packages/rocketchat-lib/server/lib/bugsnag.js index 8d123c88d512..0586eb52ff93 100644 --- a/packages/rocketchat-lib/server/lib/bugsnag.js +++ b/packages/rocketchat-lib/server/lib/bugsnag.js @@ -1,9 +1,11 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; import bugsnag from 'bugsnag'; RocketChat.bugsnag = bugsnag; -RocketChat.settings.get('Bugsnag_api_key', (key, value) => { +settings.get('Bugsnag_api_key', (key, value) => { if (value) { bugsnag.register(value); } @@ -14,8 +16,8 @@ const notify = function(message, stack) { message += ` ${ stack }`; } let options = {}; - if (RocketChat.Info) { - options = { app: { version: RocketChat.Info.version, info: RocketChat.Info } }; + if (Info) { + options = { app: { version: Info.version, info: Info } }; } const error = new Error(message); error.stack = stack; diff --git a/packages/rocketchat-lib/server/lib/configLogger.js b/packages/rocketchat-lib/server/lib/configLogger.js index e8d79ffe7b25..7a9c40ce2272 100644 --- a/packages/rocketchat-lib/server/lib/configLogger.js +++ b/packages/rocketchat-lib/server/lib/configLogger.js @@ -1,15 +1,16 @@ import { Meteor } from 'meteor/meteor'; import { LoggerManager } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.get('Log_Package', function(key, value) { +settings.get('Log_Package', function(key, value) { return LoggerManager.showPackage = value; }); -RocketChat.settings.get('Log_File', function(key, value) { +settings.get('Log_File', function(key, value) { return LoggerManager.showFileAndLine = value; }); -RocketChat.settings.get('Log_Level', function(key, value) { +settings.get('Log_Level', function(key, value) { if (value != null) { LoggerManager.logLevel = parseInt(value); Meteor.setTimeout(() => LoggerManager.enable(true), 200); diff --git a/packages/rocketchat-lib/server/lib/debug.js b/packages/rocketchat-lib/server/lib/debug.js index ca32e6a9f1ec..f821d2b2c1b4 100644 --- a/packages/rocketchat-lib/server/lib/debug.js +++ b/packages/rocketchat-lib/server/lib/debug.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; import { InstanceStatus } from 'meteor/konecty:multiple-instances-status'; +import { settings } from 'meteor/rocketchat:settings'; +import { metrics } from 'meteor/rocketchat:metrics'; import _ from 'underscore'; import { Logger } from 'meteor/rocketchat:logger'; @@ -17,13 +19,13 @@ const logger = new Logger('Meteor', { let Log_Trace_Methods; let Log_Trace_Subscriptions; -RocketChat.settings.get('Log_Trace_Methods', (key, value) => Log_Trace_Methods = value); -RocketChat.settings.get('Log_Trace_Subscriptions', (key, value) => Log_Trace_Subscriptions = value); +settings.get('Log_Trace_Methods', (key, value) => Log_Trace_Methods = value); +settings.get('Log_Trace_Subscriptions', (key, value) => Log_Trace_Subscriptions = value); let Log_Trace_Methods_Filter; let Log_Trace_Subscriptions_Filter; -RocketChat.settings.get('Log_Trace_Methods_Filter', (key, value) => Log_Trace_Methods_Filter = value ? new RegExp(value) : undefined); -RocketChat.settings.get('Log_Trace_Subscriptions_Filter', (key, value) => Log_Trace_Subscriptions_Filter = value ? new RegExp(value) : undefined); +settings.get('Log_Trace_Methods_Filter', (key, value) => Log_Trace_Methods_Filter = value ? new RegExp(value) : undefined); +settings.get('Log_Trace_Subscriptions_Filter', (key, value) => Log_Trace_Subscriptions_Filter = value ? new RegExp(value) : undefined); const traceConnection = (enable, filter, prefix, name, connection, userId) => { if (!enable) { @@ -49,7 +51,7 @@ const traceConnection = (enable, filter, prefix, name, connection, userId) => { const wrapMethods = function(name, originalHandler, methodsMap) { methodsMap[name] = function(...originalArgs) { traceConnection(Log_Trace_Methods, Log_Trace_Methods_Filter, 'method', name, this.connection, this.userId); - const end = RocketChat.metrics.meteorMethods.startTimer({ + const end = metrics.meteorMethods.startTimer({ method: name, has_connection: this.connection != null, has_user: this.userId != null, @@ -89,7 +91,7 @@ Meteor.publish = function(name, func) { return originalMeteorPublish(name, function(...args) { traceConnection(Log_Trace_Subscriptions, Log_Trace_Subscriptions_Filter, 'subscription', name, this.connection, this.userId); logger.publish(name, '-> userId:', this.userId, ', arguments: ', args); - const end = RocketChat.metrics.meteorSubscriptions.startTimer({ subscription: name }); + const end = metrics.meteorSubscriptions.startTimer({ subscription: name }); const originalReady = this.ready; this.ready = function() { diff --git a/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js b/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js index 23dc5b7b21d6..73334b3c9b92 100644 --- a/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js +++ b/packages/rocketchat-lib/server/lib/defaultBlockedDomainsList.js @@ -1,4 +1,4 @@ -RocketChat.emailDomainDefaultBlackList = [ +export const emailDomainDefaultBlackList = [ '0-mail.com', '0815.ru', '0815.su', diff --git a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js index 9b0bcb521c64..5e54bc901689 100644 --- a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js +++ b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import IMAP from 'imap'; import POP3 from 'poplib'; import { simpleParser } from 'mailparser'; @@ -6,17 +7,17 @@ import { simpleParser } from 'mailparser'; export class IMAPIntercepter { constructor() { this.imap = new IMAP({ - user: RocketChat.settings.get('Direct_Reply_Username'), - password: RocketChat.settings.get('Direct_Reply_Password'), - host: RocketChat.settings.get('Direct_Reply_Host'), - port: RocketChat.settings.get('Direct_Reply_Port'), - debug: RocketChat.settings.get('Direct_Reply_Debug') ? console.log : false, - tls: !RocketChat.settings.get('Direct_Reply_IgnoreTLS'), + user: settings.get('Direct_Reply_Username'), + password: settings.get('Direct_Reply_Password'), + host: settings.get('Direct_Reply_Host'), + port: settings.get('Direct_Reply_Port'), + debug: settings.get('Direct_Reply_Debug') ? console.log : false, + tls: !settings.get('Direct_Reply_IgnoreTLS'), connTimeout: 30000, keepalive: true, }); - this.delete = RocketChat.settings.get('Direct_Reply_Delete') ? RocketChat.settings.get('Direct_Reply_Delete') : true; + this.delete = settings.get('Direct_Reply_Delete') ? settings.get('Direct_Reply_Delete') : true; // On successfully connected. this.imap.on('ready', Meteor.bindEnvironment(() => { @@ -140,16 +141,16 @@ export class IMAPIntercepter { export class POP3Intercepter { constructor() { - this.pop3 = new POP3(RocketChat.settings.get('Direct_Reply_Port'), RocketChat.settings.get('Direct_Reply_Host'), { - enabletls: !RocketChat.settings.get('Direct_Reply_IgnoreTLS'), - debug: RocketChat.settings.get('Direct_Reply_Debug') ? console.log : false, + this.pop3 = new POP3(settings.get('Direct_Reply_Port'), settings.get('Direct_Reply_Host'), { + enabletls: !settings.get('Direct_Reply_IgnoreTLS'), + debug: settings.get('Direct_Reply_Debug') ? console.log : false, }); this.totalMsgCount = 0; this.currentMsgCount = 0; this.pop3.on('connect', Meteor.bindEnvironment(() => { - this.pop3.login(RocketChat.settings.get('Direct_Reply_Username'), RocketChat.settings.get('Direct_Reply_Password')); + this.pop3.login(settings.get('Direct_Reply_Username'), settings.get('Direct_Reply_Password')); })); this.pop3.on('login', Meteor.bindEnvironment((status) => { @@ -242,13 +243,13 @@ export class POP3Helper { start() { // run every x-minutes - if (RocketChat.settings.get('Direct_Reply_Frequency')) { + if (settings.get('Direct_Reply_Frequency')) { RocketChat.POP3 = new POP3Intercepter(); this.running = Meteor.setInterval(() => { // get new emails and process RocketChat.POP3 = new POP3Intercepter(); - }, Math.max(RocketChat.settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000)); + }, Math.max(settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000)); } } diff --git a/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js b/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js index b1a26e11cb93..ad4a75eb9b20 100644 --- a/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js +++ b/packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js @@ -1,6 +1,9 @@ import _ from 'underscore'; import s from 'underscore.string'; import moment from 'moment'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; /** * Chechs if a messages contains a user highlight @@ -24,19 +27,19 @@ function notifyUsersOnMessage(message, room) { // skips this callback if the message was edited and increments it if the edit was way in the past (aka imported) if (message.editedAt && Math.abs(moment(message.editedAt).diff()) > 60000) { // TODO: Review as I am not sure how else to get around this as the incrementing of the msgs count shouldn't be in this callback - RocketChat.models.Rooms.incMsgCountById(message.rid, 1); + Rooms.incMsgCountById(message.rid, 1); return message; } else if (message.editedAt) { // only updates last message if it was edited (skip rest of callback) - if (RocketChat.settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) { - RocketChat.models.Rooms.setLastMessageById(message.rid, message); + if (settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) { + Rooms.setLastMessageById(message.rid, message); } return message; } if (message.ts && Math.abs(moment(message.ts).diff()) > 60000) { - RocketChat.models.Rooms.incMsgCountById(message.rid, 1); + Rooms.incMsgCountById(message.rid, 1); return message; } @@ -45,7 +48,7 @@ function notifyUsersOnMessage(message, room) { let toHere = false; const mentionIds = []; const highlightsIds = []; - const highlights = RocketChat.models.Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch(); + const highlights = Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch(); if (message.mentions != null) { message.mentions.forEach(function(mention) { if (!toAll && mention._id === 'all') { @@ -69,47 +72,47 @@ function notifyUsersOnMessage(message, room) { }); if (room.t === 'd') { - const unreadCountDM = RocketChat.settings.get('Unread_Count_DM'); + const unreadCountDM = settings.get('Unread_Count_DM'); if (unreadCountDM === 'all_messages') { - RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); + Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); } else if (toAll || toHere) { - RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1); + Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1); } else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) { - RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1); + Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1); } } else { - const unreadCount = RocketChat.settings.get('Unread_Count'); + const unreadCount = settings.get('Unread_Count'); if (toAll || toHere) { let incUnread = 0; if (['all_messages', 'group_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) { incUnread = 1; } - RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread); + Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread); } else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) { let incUnread = 0; if (['all_messages', 'user_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) { incUnread = 1; } - RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread); + Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread); } else if (unreadCount === 'all_messages') { - RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); + Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id); } } } // Update all the room activity tracker fields // This method take so long to execute on gient rooms cuz it will trugger the cache rebuild for the releations of that room - RocketChat.models.Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, RocketChat.settings.get('Store_Last_Message') && message); + Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, settings.get('Store_Last_Message') && message); // Update all other subscriptions to alert their owners but witout incrementing // the unread counter, as it is only for mentions and direct messages // We now set alert and open properties in two separate update commands. This proved to be more efficient on MongoDB - because it uses a more efficient index. - RocketChat.models.Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id); - RocketChat.models.Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id); + Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id); + Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id); return message; } -RocketChat.callbacks.add('afterSaveMessage', notifyUsersOnMessage, RocketChat.callbacks.priority.LOW, 'notifyUsersOnMessage'); +callbacks.add('afterSaveMessage', notifyUsersOnMessage, callbacks.priority.LOW, 'notifyUsersOnMessage'); diff --git a/packages/rocketchat-lib/server/lib/passwordPolicy.js b/packages/rocketchat-lib/server/lib/passwordPolicy.js index 7ff442bc2ecc..cf741675b3dd 100644 --- a/packages/rocketchat-lib/server/lib/passwordPolicy.js +++ b/packages/rocketchat-lib/server/lib/passwordPolicy.js @@ -1,13 +1,15 @@ +import { settings } from 'meteor/rocketchat:settings'; import PasswordPolicy from './PasswordPolicyClass'; -RocketChat.passwordPolicy = new PasswordPolicy(); +const passwordPolicy = new PasswordPolicy(); +RocketChat.passwordPolicy = passwordPolicy; -RocketChat.settings.get('Accounts_Password_Policy_Enabled', (key, value) => RocketChat.passwordPolicy.enabled = value); -RocketChat.settings.get('Accounts_Password_Policy_MinLength', (key, value) => RocketChat.passwordPolicy.minLength = value); -RocketChat.settings.get('Accounts_Password_Policy_MaxLength', (key, value) => RocketChat.passwordPolicy.maxLength = value); -RocketChat.settings.get('Accounts_Password_Policy_ForbidRepeatingCharacters', (key, value) => RocketChat.passwordPolicy.forbidRepeatingCharacters = value); -RocketChat.settings.get('Accounts_Password_Policy_ForbidRepeatingCharactersCount', (key, value) => RocketChat.passwordPolicy.forbidRepeatingCharactersCount = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneLowercase', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneLowercase = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneUppercase', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneUppercase = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneNumber', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneNumber = value); -RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneSpecialCharacter', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneSpecialCharacter = value); +settings.get('Accounts_Password_Policy_Enabled', (key, value) => passwordPolicy.enabled = value); +settings.get('Accounts_Password_Policy_MinLength', (key, value) => passwordPolicy.minLength = value); +settings.get('Accounts_Password_Policy_MaxLength', (key, value) => passwordPolicy.maxLength = value); +settings.get('Accounts_Password_Policy_ForbidRepeatingCharacters', (key, value) => passwordPolicy.forbidRepeatingCharacters = value); +settings.get('Accounts_Password_Policy_ForbidRepeatingCharactersCount', (key, value) => passwordPolicy.forbidRepeatingCharactersCount = value); +settings.get('Accounts_Password_Policy_AtLeastOneLowercase', (key, value) => passwordPolicy.mustContainAtLeastOneLowercase = value); +settings.get('Accounts_Password_Policy_AtLeastOneUppercase', (key, value) => passwordPolicy.mustContainAtLeastOneUppercase = value); +settings.get('Accounts_Password_Policy_AtLeastOneNumber', (key, value) => passwordPolicy.mustContainAtLeastOneNumber = value); +settings.get('Accounts_Password_Policy_AtLeastOneSpecialCharacter', (key, value) => passwordPolicy.mustContainAtLeastOneSpecialCharacter = value); diff --git a/packages/rocketchat-lib/server/lib/processDirectEmail.js b/packages/rocketchat-lib/server/lib/processDirectEmail.js index 94f0bfe33e8d..36b5ab27f437 100644 --- a/packages/rocketchat-lib/server/lib/processDirectEmail.js +++ b/packages/rocketchat-lib/server/lib/processDirectEmail.js @@ -1,4 +1,7 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { Rooms, Messages, Users, Subscriptions } from 'meteor/rocketchat:models'; +import { metrics } from 'meteor/rocketchat:metrics'; import { EmailReplyParser as reply } from 'emailreplyparser'; import moment from 'moment'; @@ -20,14 +23,14 @@ RocketChat.processDirectEmail = function(email) { message.ts = new Date(); } - if (message.msg && message.msg.length > RocketChat.settings.get('Message_MaxAllowedSize')) { + if (message.msg && message.msg.length > settings.get('Message_MaxAllowedSize')) { return false; } // reduce new lines in multiline message message.msg = message.msg.split('\n\n').join('\n'); - const user = RocketChat.models.Users.findOneByEmailAddress(email.headers.from, { + const user = Users.findOneByEmailAddress(email.headers.from, { fields: { username: 1, name: 1, @@ -38,7 +41,7 @@ RocketChat.processDirectEmail = function(email) { return false; } - const prevMessage = RocketChat.models.Messages.findOneById(email.headers.mid, { + const prevMessage = Messages.findOneById(email.headers.mid, { rid: 1, u: 1, }); @@ -53,7 +56,7 @@ RocketChat.processDirectEmail = function(email) { return false; } - const roomInfo = RocketChat.models.Rooms.findOneById(message.rid, { + const roomInfo = Rooms.findOneById(message.rid, { t: 1, name: 1, }); @@ -75,7 +78,7 @@ RocketChat.processDirectEmail = function(email) { // add reply message link message.msg = prevMessageLink + message.msg; - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id); if (subscription && (subscription.blocked || subscription.blocker)) { // room is blocked return false; @@ -86,11 +89,11 @@ RocketChat.processDirectEmail = function(email) { return false; } - if (message.alias == null && RocketChat.settings.get('Message_SetNameToAliasEnabled')) { + if (message.alias == null && settings.get('Message_SetNameToAliasEnabled')) { message.alias = user.name; } - RocketChat.metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 + metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 return RocketChat.sendMessage(user, message, room); } diff --git a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js index 5319d753a1bf..0ee85ecddc51 100644 --- a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js +++ b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js @@ -1,6 +1,10 @@ import { Meteor } from 'meteor/meteor'; import moment from 'moment'; - +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { roomTypes } from 'meteor/rocketchat:utils'; import { callJoinRoom, messageContainsHighlight, parseMessageTextPerUser, replaceMentionedUsernamesWithFullNames } from '../functions/notifications/'; import { sendEmail, shouldNotifyEmail } from '../functions/notifications/email'; import { sendSinglePush, shouldNotifyMobile } from '../functions/notifications/mobile'; @@ -35,7 +39,7 @@ const sendNotification = async({ const roomType = room.t; // If the user doesn't have permission to view direct messages, don't send notification of direct messages. - if (roomType === 'd' && !RocketChat.authz.hasPermission(subscription.u._id, 'view-d-room')) { + if (roomType === 'd' && !hasPermission(subscription.u._id, 'view-d-room')) { return; } @@ -186,7 +190,7 @@ async function sendAllNotifications(message, room) { return message; } - const sender = RocketChat.roomTypes.getConfig(room.t).getMsgSender(message.u._id); + const sender = roomTypes.getConfig(room.t).getMsgSender(message.u._id); if (!sender) { return message; } @@ -196,14 +200,14 @@ async function sendAllNotifications(message, room) { const hasMentionToAll = mentionIds.includes('all'); const hasMentionToHere = mentionIds.includes('here'); - let notificationMessage = RocketChat.callbacks.run('beforeSendMessageNotifications', message.msg); - if (mentionIds.length > 0 && RocketChat.settings.get('UI_Use_Real_Name')) { + let notificationMessage = callbacks.run('beforeSendMessageNotifications', message.msg); + if (mentionIds.length > 0 && settings.get('UI_Use_Real_Name')) { notificationMessage = replaceMentionedUsernamesWithFullNames(message.msg, message.mentions); } // Don't fetch all users if room exceeds max members - const maxMembersForNotification = RocketChat.settings.get('Notifications_Max_Room_Members'); - const roomMembersCount = RocketChat.models.Subscriptions.findByRoomId(room._id).count(); + const maxMembersForNotification = settings.get('Notifications_Max_Room_Members'); + const roomMembersCount = Subscriptions.findByRoomId(room._id).count(); const disableAllMessageNotifications = roomMembersCount > maxMembersForNotification && maxMembersForNotification !== 0; const query = { @@ -238,7 +242,7 @@ async function sendAllNotifications(message, room) { } const serverField = kind === 'email' ? 'emailNotificationMode' : `${ kind }Notifications`; - const serverPreference = RocketChat.settings.get(`Accounts_Default_User_Preferences_${ serverField }`); + const serverPreference = settings.get(`Accounts_Default_User_Preferences_${ serverField }`); if ((room.t === 'd' && serverPreference !== 'nothing') || (!disableAllMessageNotifications && (serverPreference === 'all' || hasMentionToAll || hasMentionToHere))) { query.$or.push({ [notificationField]: { $exists: false }, @@ -254,7 +258,7 @@ async function sendAllNotifications(message, room) { // the find bellow is crucial. all subscription records returned will receive at least one kind of notification. // the query is defined by the server's default values and Notifications_Max_Room_Members setting. - const subscriptions = await RocketChat.models.Subscriptions.model.rawCollection().aggregate([ + const subscriptions = await Subscriptions.model.rawCollection().aggregate([ { $match: query }, lookup, filter, @@ -277,7 +281,7 @@ async function sendAllNotifications(message, room) { if (room.t === 'c') { // get subscriptions from users already in room (to not send them a notification) const mentions = [...mentionIdsWithoutGroups]; - RocketChat.models.Subscriptions.findByRoomIdAndUserIds(room._id, mentionIdsWithoutGroups, { fields: { 'u._id': 1 } }).forEach((subscription) => { + Subscriptions.findByRoomIdAndUserIds(room._id, mentionIdsWithoutGroups, { fields: { 'u._id': 1 } }).forEach((subscription) => { const index = mentions.indexOf(subscription.u._id); if (index !== -1) { mentions.splice(index, 1); @@ -292,7 +296,7 @@ async function sendAllNotifications(message, room) { }) ).then((users) => { users.forEach((userId) => { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, userId); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, userId); sendNotification({ subscription, @@ -313,6 +317,6 @@ async function sendAllNotifications(message, room) { return message; } -RocketChat.callbacks.add('afterSaveMessage', (message, room) => Promise.await(sendAllNotifications(message, room)), RocketChat.callbacks.priority.LOW, 'sendNotificationsOnMessage'); +callbacks.add('afterSaveMessage', (message, room) => Promise.await(sendAllNotifications(message, room)), callbacks.priority.LOW, 'sendNotificationsOnMessage'); export { sendNotification, sendAllNotifications }; diff --git a/packages/rocketchat-lib/server/lib/validateEmailDomain.js b/packages/rocketchat-lib/server/lib/validateEmailDomain.js index 005dab6506cb..da7d3ac2f98a 100644 --- a/packages/rocketchat-lib/server/lib/validateEmailDomain.js +++ b/packages/rocketchat-lib/server/lib/validateEmailDomain.js @@ -1,4 +1,6 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; +import { emailDomainDefaultBlackList } from './defaultBlockedDomainsList'; import _ from 'underscore'; import dns from 'dns'; @@ -7,16 +9,16 @@ let emailDomainWhiteList = []; let useDefaultBlackList = false; let useDNSDomainCheck = false; -RocketChat.settings.get('Accounts_BlockedDomainsList', function(key, value) { +settings.get('Accounts_BlockedDomainsList', function(key, value) { emailDomainBlackList = _.map(value.split(','), (domain) => domain.trim()); }); -RocketChat.settings.get('Accounts_AllowedDomainsList', function(key, value) { +settings.get('Accounts_AllowedDomainsList', function(key, value) { emailDomainWhiteList = _.map(value.split(','), (domain) => domain.trim()); }); -RocketChat.settings.get('Accounts_UseDefaultBlockedDomainsList', function(key, value) { +settings.get('Accounts_UseDefaultBlockedDomainsList', function(key, value) { useDefaultBlackList = value; }); -RocketChat.settings.get('Accounts_UseDNSDomainCheck', function(key, value) { +settings.get('Accounts_UseDNSDomainCheck', function(key, value) { useDNSDomainCheck = value; }); @@ -30,7 +32,7 @@ RocketChat.validateEmailDomain = function(email) { // if not in whitelist if (emailDomainWhiteList.indexOf(emailDomain) === -1) { - if (emailDomainBlackList.indexOf(emailDomain) !== -1 || (useDefaultBlackList && RocketChat.emailDomainDefaultBlackList.indexOf(emailDomain) !== -1)) { + if (emailDomainBlackList.indexOf(emailDomain) !== -1 || (useDefaultBlackList && emailDomainDefaultBlackList.indexOf(emailDomain) !== -1)) { throw new Meteor.Error('error-email-domain-blacklisted', 'The email domain is blacklisted', { function: 'RocketChat.validateEmailDomain' }); } } From 3f1451fbd54b13a016a27072639142a625482444 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Tue, 22 Jan 2019 17:06:57 -0200 Subject: [PATCH 05/33] Remove some dependencies inside rocketchat-lib/server/methods (#13218) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods --- .../server/methods/addOAuthService.js | 36 ++++++++++--------- .../server/methods/addUsersToRoom.js | 14 ++++---- .../server/methods/archiveRoom.js | 6 ++-- .../server/methods/blockUser.js | 7 ++-- .../methods/checkRegistrationSecretURL.js | 3 +- .../methods/checkUsernameAvailability.js | 3 +- .../server/methods/cleanRoomHistory.js | 3 +- .../server/methods/createChannel.js | 3 +- .../server/methods/createPrivateGroup.js | 3 +- .../server/methods/createToken.js | 3 +- .../server/methods/deleteMessage.js | 15 ++++---- .../server/methods/deleteUserOwnAccount.js | 6 ++-- .../methods/executeSlashCommandPreview.js | 7 ++-- .../server/methods/filterATAllTag.js | 12 ++++--- .../server/methods/filterATHereTag.js | 12 ++++--- .../server/methods/filterBadWords.js | 8 +++-- .../server/methods/getChannelHistory.js | 17 +++++---- .../server/methods/getRoomJoinCode.js | 6 ++-- .../server/methods/getRoomRoles.js | 12 ++++--- .../server/methods/getServerInfo.js | 3 +- .../server/methods/getSingleMessage.js | 3 +- .../server/methods/getSlashCommandPreviews.js | 7 ++-- .../server/methods/getUserRoles.js | 5 +-- .../rocketchat-lib/server/methods/joinRoom.js | 8 +++-- .../server/methods/leaveRoom.js | 12 ++++--- .../server/methods/refreshOAuthService.js | 6 ++-- .../server/methods/removeOAuthService.js | 36 ++++++++++--------- .../server/methods/restartServer.js | 3 +- .../server/methods/robotMethods.js | 8 +++-- .../server/methods/saveSetting.js | 9 +++-- .../server/methods/sendInvitationEmail.js | 8 +++-- .../server/methods/sendMessage.js | 24 ++++++++----- .../server/methods/sendSMTPTestEmail.js | 3 +- .../server/methods/setAdminStatus.js | 3 +- .../rocketchat-lib/server/methods/setEmail.js | 3 +- .../server/methods/setRealName.js | 3 +- .../server/methods/setUsername.js | 9 +++-- .../server/methods/unarchiveRoom.js | 6 ++-- .../server/methods/unblockUser.js | 7 ++-- .../server/methods/updateMessage.js | 13 ++++--- 40 files changed, 215 insertions(+), 140 deletions(-) diff --git a/packages/rocketchat-lib/server/methods/addOAuthService.js b/packages/rocketchat-lib/server/methods/addOAuthService.js index 75e3d28d085e..275cd2835e83 100644 --- a/packages/rocketchat-lib/server/methods/addOAuthService.js +++ b/packages/rocketchat-lib/server/methods/addOAuthService.js @@ -2,6 +2,8 @@ /* eslint comma-spacing: 0 */ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; Meteor.methods({ @@ -13,26 +15,26 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'addOAuthService' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { + if (hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { throw new Meteor.Error('error-action-not-allowed', 'Adding OAuth Services is not allowed', { method: 'addOAuthService', action: 'Adding_OAuth_Services' }); } name = name.toLowerCase().replace(/[^a-z0-9_]/g, ''); name = s.capitalize(name); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Enable', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-url` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'URL', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-token_path` , '/oauth/token' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Path', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-token_sent_via` , 'payload' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Sent_Via', persistent: true, values: [{ key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`, 'default' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Token_Sent_Via', persistent: true, values: [{ key: 'default', i18nLabel: 'Same_As_Token_Sent_Via' }, { key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-identity_path` , '/me' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Path', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-authorize_path` , '/oauth/authorize', { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Authorize_Path', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-scope` , 'openid' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Scope', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-id` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_id', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-secret` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Secret', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-login_style` , 'popup' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_label_text` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_label_color` , '#FFFFFF' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_color` , '#13679A' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-username_field` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Username_Field', persistent: true }); - RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-merge_users` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Merge_Users', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Enable', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-url` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'URL', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-token_path` , '/oauth/token' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Path', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-token_sent_via` , 'payload' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Sent_Via', persistent: true, values: [{ key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); + settings.add(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`, 'default' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Token_Sent_Via', persistent: true, values: [{ key: 'default', i18nLabel: 'Same_As_Token_Sent_Via' }, { key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' }] }); + settings.add(`Accounts_OAuth_Custom-${ name }-identity_path` , '/me' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Path', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-authorize_path` , '/oauth/authorize', { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Authorize_Path', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-scope` , 'openid' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Scope', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-id` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_id', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-secret` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Secret', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-login_style` , 'popup' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] }); + settings.add(`Accounts_OAuth_Custom-${ name }-button_label_text` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-button_label_color` , '#FFFFFF' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-button_color` , '#13679A' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-username_field` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Username_Field', persistent: true }); + settings.add(`Accounts_OAuth_Custom-${ name }-merge_users` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Merge_Users', persistent: true }); } }); diff --git a/packages/rocketchat-lib/server/methods/addUsersToRoom.js b/packages/rocketchat-lib/server/methods/addUsersToRoom.js index cd75a356ecea..dd16bfea969a 100644 --- a/packages/rocketchat-lib/server/methods/addUsersToRoom.js +++ b/packages/rocketchat-lib/server/methods/addUsersToRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; +import { Rooms, Subscriptions, Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ addUsersToRoom(data = {}) { @@ -17,9 +19,9 @@ Meteor.methods({ } // Get user and room details - const room = RocketChat.models.Rooms.findOneById(data.rid); + const room = Rooms.findOneById(data.rid); const userId = Meteor.userId(); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(data.rid, userId, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(data.rid, userId, { fields: { _id: 1 } }); const userInRoom = subscription != null; // Can't add to direct room ever @@ -31,11 +33,11 @@ Meteor.methods({ // Can add to any room you're in, with permission, otherwise need specific room type permission let canAddUser = false; - if (userInRoom && RocketChat.authz.hasPermission(userId, 'add-user-to-joined-room', room._id)) { + if (userInRoom && hasPermission(userId, 'add-user-to-joined-room', room._id)) { canAddUser = true; - } else if (room.t === 'c' && RocketChat.authz.hasPermission(userId, 'add-user-to-any-c-room')) { + } else if (room.t === 'c' && hasPermission(userId, 'add-user-to-any-c-room')) { canAddUser = true; - } else if (room.t === 'p' && RocketChat.authz.hasPermission(userId, 'add-user-to-any-p-room')) { + } else if (room.t === 'p' && hasPermission(userId, 'add-user-to-any-p-room')) { canAddUser = true; } @@ -56,7 +58,7 @@ Meteor.methods({ // Validate each user, then add to room const user = Meteor.user(); data.users.forEach((username) => { - const newUser = RocketChat.models.Users.findOneByUsername(username); + const newUser = Users.findOneByUsername(username); if (!newUser) { throw new Meteor.Error('error-invalid-username', 'Invalid username', { method: 'addUsersToRoom', diff --git a/packages/rocketchat-lib/server/methods/archiveRoom.js b/packages/rocketchat-lib/server/methods/archiveRoom.js index 217fd59e39a1..26d03e477746 100644 --- a/packages/rocketchat-lib/server/methods/archiveRoom.js +++ b/packages/rocketchat-lib/server/methods/archiveRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Rooms } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ archiveRoom(rid) { @@ -10,13 +12,13 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'archiveRoom' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'archiveRoom' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'archive-room', room._id)) { + if (!hasPermission(Meteor.userId(), 'archive-room', room._id)) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'archiveRoom' }); } diff --git a/packages/rocketchat-lib/server/methods/blockUser.js b/packages/rocketchat-lib/server/methods/blockUser.js index fd771a1dce68..0342cc17f874 100644 --- a/packages/rocketchat-lib/server/methods/blockUser.js +++ b/packages/rocketchat-lib/server/methods/blockUser.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ blockUser({ rid, blocked }) { @@ -11,14 +12,14 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'blockUser' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); - const subscription2 = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, blocked); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); + const subscription2 = Subscriptions.findOneByRoomIdAndUserId(rid, blocked); if (!subscription || !subscription2) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'blockUser' }); } - RocketChat.models.Subscriptions.setBlockedByRoomId(rid, blocked, Meteor.userId()); + Subscriptions.setBlockedByRoomId(rid, blocked, Meteor.userId()); return true; }, diff --git a/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js b/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js index 96739aa7f87d..c77fd6f223cc 100644 --- a/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js +++ b/packages/rocketchat-lib/server/methods/checkRegistrationSecretURL.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ checkRegistrationSecretURL(hash) { check(hash, String); - return hash === RocketChat.settings.get('Accounts_RegistrationForm_SecretURL'); + return hash === settings.get('Accounts_RegistrationForm_SecretURL'); }, }); diff --git a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js index 302b02647b77..a115878d3c5d 100644 --- a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ checkUsernameAvailability(username) { @@ -11,7 +12,7 @@ Meteor.methods({ const user = Meteor.user(); - if (user.username && !RocketChat.settings.get('Accounts_AllowUsernameChange')) { + if (user.username && !settings.get('Accounts_AllowUsernameChange')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setUsername' }); } diff --git a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js index b93cf480fa48..6e449f1a0353 100644 --- a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ cleanRoomHistory({ roomId, latest, oldest, inclusive = true, limit, excludePinned = false, filesOnly = false, fromUsers = [] }) { @@ -18,7 +19,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cleanRoomHistory' }); } - if (!RocketChat.authz.hasPermission(userId, 'clean-channel-history', roomId)) { + if (!hasPermission(userId, 'clean-channel-history', roomId)) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'cleanRoomHistory' }); } diff --git a/packages/rocketchat-lib/server/methods/createChannel.js b/packages/rocketchat-lib/server/methods/createChannel.js index df5b722cd407..df438753e028 100644 --- a/packages/rocketchat-lib/server/methods/createChannel.js +++ b/packages/rocketchat-lib/server/methods/createChannel.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -10,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createChannel' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'create-c')) { + if (!hasPermission(Meteor.userId(), 'create-c')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createChannel' }); } return RocketChat.createRoom('c', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); diff --git a/packages/rocketchat-lib/server/methods/createPrivateGroup.js b/packages/rocketchat-lib/server/methods/createPrivateGroup.js index cc75b89b5ef0..2a28cfd1f5b1 100644 --- a/packages/rocketchat-lib/server/methods/createPrivateGroup.js +++ b/packages/rocketchat-lib/server/methods/createPrivateGroup.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -10,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createPrivateGroup' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'create-p')) { + if (!hasPermission(Meteor.userId(), 'create-p')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createPrivateGroup' }); } diff --git a/packages/rocketchat-lib/server/methods/createToken.js b/packages/rocketchat-lib/server/methods/createToken.js index 249c039b4a61..9d17d463566d 100644 --- a/packages/rocketchat-lib/server/methods/createToken.js +++ b/packages/rocketchat-lib/server/methods/createToken.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ createToken(userId) { - if (Meteor.userId() !== userId && !RocketChat.authz.hasPermission(Meteor.userId(), 'user-generate-access-token')) { + if (Meteor.userId() !== userId && !hasPermission(Meteor.userId(), 'user-generate-access-token')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'createToken' }); } const token = Accounts._generateStampedLoginToken(); diff --git a/packages/rocketchat-lib/server/methods/deleteMessage.js b/packages/rocketchat-lib/server/methods/deleteMessage.js index 31e6c6b3300d..7dbed6f85c4c 100644 --- a/packages/rocketchat-lib/server/methods/deleteMessage.js +++ b/packages/rocketchat-lib/server/methods/deleteMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { Messages } from 'meteor/rocketchat:models'; import moment from 'moment'; Meteor.methods({ @@ -12,7 +15,7 @@ Meteor.methods({ method: 'deleteMessage', }); } - const originalMessage = RocketChat.models.Messages.findOneById(message._id, { + const originalMessage = Messages.findOneById(message._id, { fields: { u: 1, rid: 1, @@ -26,17 +29,17 @@ Meteor.methods({ action: 'Delete_message', }); } - const forceDelete = RocketChat.authz.hasPermission(Meteor.userId(), 'force-delete-message', originalMessage.rid); - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'delete-message', originalMessage.rid); - const deleteAllowed = RocketChat.settings.get('Message_AllowDeleting'); + const forceDelete = hasPermission(Meteor.userId(), 'force-delete-message', originalMessage.rid); + const _hasPermission = hasPermission(Meteor.userId(), 'delete-message', originalMessage.rid); + const deleteAllowed = settings.get('Message_AllowDeleting'); const deleteOwn = originalMessage && originalMessage.u && originalMessage.u._id === Meteor.userId(); - if (!(hasPermission || (deleteAllowed && deleteOwn)) && !(forceDelete)) { + if (!(_hasPermission || (deleteAllowed && deleteOwn)) && !(forceDelete)) { throw new Meteor.Error('error-action-not-allowed', 'Not allowed', { method: 'deleteMessage', action: 'Delete_message', }); } - const blockDeleteInMinutes = RocketChat.settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); + const blockDeleteInMinutes = settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); if (blockDeleteInMinutes != null && blockDeleteInMinutes !== 0 && !forceDelete) { if (originalMessage.ts == null) { return; diff --git a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js index 3d197e11cd04..4189d0dd6f32 100644 --- a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js +++ b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Accounts } from 'meteor/accounts-base'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; import s from 'underscore.string'; Meteor.methods({ @@ -12,12 +14,12 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'deleteUserOwnAccount' }); } - if (!RocketChat.settings.get('Accounts_AllowDeleteOwnAccount')) { + if (!settings.get('Accounts_AllowDeleteOwnAccount')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'deleteUserOwnAccount' }); } const userId = Meteor.userId(); - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); if (!user) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'deleteUserOwnAccount' }); diff --git a/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js b/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js index 50460526fd37..f10b62745566 100644 --- a/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js +++ b/packages/rocketchat-lib/server/methods/executeSlashCommandPreview.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { slashCommands } from 'meteor/rocketchat:utils'; Meteor.methods({ executeSlashCommandPreview(command, preview) { @@ -8,13 +9,13 @@ Meteor.methods({ }); } - if (!command || !command.cmd || !RocketChat.slashCommands.commands[command.cmd]) { + if (!command || !command.cmd || !slashCommands.commands[command.cmd]) { throw new Meteor.Error('error-invalid-command', 'Invalid Command Provided', { method: 'executeSlashCommandPreview', }); } - const theCmd = RocketChat.slashCommands.commands[command.cmd]; + const theCmd = slashCommands.commands[command.cmd]; if (!theCmd.providesPreview) { throw new Meteor.Error('error-invalid-command', 'Command Does Not Provide Previews', { method: 'executeSlashCommandPreview', @@ -27,6 +28,6 @@ Meteor.methods({ }); } - return RocketChat.slashCommands.executePreview(command.cmd, command.params, command.msg, preview); + return slashCommands.executePreview(command.cmd, command.params, command.msg, preview); }, }); diff --git a/packages/rocketchat-lib/server/methods/filterATAllTag.js b/packages/rocketchat-lib/server/methods/filterATAllTag.js index 7b48a7449c3a..ecbd08a87ae6 100644 --- a/packages/rocketchat-lib/server/methods/filterATAllTag.js +++ b/packages/rocketchat-lib/server/methods/filterATAllTag.js @@ -1,10 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; import moment from 'moment'; -RocketChat.callbacks.add('beforeSaveMessage', function(message) { +callbacks.add('beforeSaveMessage', function(message) { // If the message was edited, or is older than 60 seconds (imported) // the notifications will be skipped, so we can also skip this validation if (message.editedAt || (message.ts && Math.abs(moment(message.ts).diff()) > 60000)) { @@ -16,15 +20,15 @@ RocketChat.callbacks.add('beforeSaveMessage', function(message) { _.pluck(message.mentions, '_id').some((item) => item === 'all')) { // Check if the user has permissions to use @all in both global and room scopes. - if (!RocketChat.authz.hasPermission(message.u._id, 'mention-all') && !RocketChat.authz.hasPermission(message.u._id, 'mention-all', message.rid)) { + if (!hasPermission(message.u._id, 'mention-all') && !hasPermission(message.u._id, 'mention-all', message.rid)) { // Get the language of the user for the error notification. - const { language } = RocketChat.models.Users.findOneById(message.u._id); + const { language } = Users.findOneById(message.u._id); const action = TAPi18n.__('Notify_all_in_this_room', {}, language); // Add a notification to the chat, informing the user that this // action is not allowed. - RocketChat.Notifications.notifyUser(message.u._id, 'message', { + Notifications.notifyUser(message.u._id, 'message', { _id: Random.id(), rid: message.rid, ts: new Date, diff --git a/packages/rocketchat-lib/server/methods/filterATHereTag.js b/packages/rocketchat-lib/server/methods/filterATHereTag.js index 3586789e2eca..12b11659545d 100644 --- a/packages/rocketchat-lib/server/methods/filterATHereTag.js +++ b/packages/rocketchat-lib/server/methods/filterATHereTag.js @@ -1,10 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; import moment from 'moment'; -RocketChat.callbacks.add('beforeSaveMessage', function(message) { +callbacks.add('beforeSaveMessage', function(message) { // If the message was edited, or is older than 60 seconds (imported) // the notifications will be skipped, so we can also skip this validation if (message.editedAt || (message.ts && Math.abs(moment(message.ts).diff()) > 60000)) { @@ -15,15 +19,15 @@ RocketChat.callbacks.add('beforeSaveMessage', function(message) { if (message.mentions != null && _.pluck(message.mentions, '_id').some((item) => item === 'here')) { // Check if the user has permissions to use @here in both global and room scopes. - if (!RocketChat.authz.hasPermission(message.u._id, 'mention-here') && !RocketChat.authz.hasPermission(message.u._id, 'mention-here', message.rid)) { + if (!hasPermission(message.u._id, 'mention-here') && !hasPermission(message.u._id, 'mention-here', message.rid)) { // Get the language of the user for the error notification. - const { language } = RocketChat.models.Users.findOneById(message.u._id); + const { language } = Users.findOneById(message.u._id); const action = TAPi18n.__('Notify_active_in_this_room', {}, language); // Add a notification to the chat, informing the user that this // action is not allowed. - RocketChat.Notifications.notifyUser(message.u._id, 'message', { + Notifications.notifyUser(message.u._id, 'message', { _id: Random.id(), rid: message.rid, ts: new Date, diff --git a/packages/rocketchat-lib/server/methods/filterBadWords.js b/packages/rocketchat-lib/server/methods/filterBadWords.js index a3fafc63c55d..2a68d5eee942 100644 --- a/packages/rocketchat-lib/server/methods/filterBadWords.js +++ b/packages/rocketchat-lib/server/methods/filterBadWords.js @@ -1,9 +1,11 @@ import Filter from 'bad-words'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.callbacks.add('beforeSaveMessage', function(message) { +callbacks.add('beforeSaveMessage', function(message) { - if (RocketChat.settings.get('Message_AllowBadWordsFilter')) { - const badWordsList = RocketChat.settings.get('Message_BadWordsFilterList'); + if (settings.get('Message_AllowBadWordsFilter')) { + const badWordsList = settings.get('Message_BadWordsFilterList'); let options; // Add words to the blacklist diff --git a/packages/rocketchat-lib/server/methods/getChannelHistory.js b/packages/rocketchat-lib/server/methods/getChannelHistory.js index 06304ec04ab4..b9ba43432f16 100644 --- a/packages/rocketchat-lib/server/methods/getChannelHistory.js +++ b/packages/rocketchat-lib/server/methods/getChannelHistory.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; Meteor.methods({ @@ -17,7 +20,7 @@ Meteor.methods({ } // Make sure they can access the room - if (room.t === 'c' && !RocketChat.authz.hasPermission(fromUserId, 'preview-c-room') && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, fromUserId, { fields: { _id: 1 } })) { + if (room.t === 'c' && !hasPermission(fromUserId, 'preview-c-room') && !Subscriptions.findOneByRoomIdAndUserId(rid, fromUserId, { fields: { _id: 1 } })) { return false; } @@ -38,19 +41,19 @@ Meteor.methods({ limit: count, }; - if (!RocketChat.settings.get('Message_ShowEditedStatus')) { + if (!settings.get('Message_ShowEditedStatus')) { options.fields = { editedAt: 0 }; } let records = []; if (_.isUndefined(oldest) && inclusive) { - records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestampInclusive(rid, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBeforeTimestampInclusive(rid, latest, options).fetch(); } else if (_.isUndefined(oldest) && !inclusive) { - records = RocketChat.models.Messages.findVisibleByRoomIdBeforeTimestamp(rid, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBeforeTimestamp(rid, latest, options).fetch(); } else if (!_.isUndefined(oldest) && inclusive) { - records = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestampsInclusive(rid, oldest, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBetweenTimestampsInclusive(rid, oldest, latest, options).fetch(); } else { - records = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, latest, options).fetch(); + records = Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, latest, options).fetch(); } const messages = records.map((record) => RocketChat.composeMessageObjectWithUser(record, fromUserId)); @@ -62,7 +65,7 @@ Meteor.methods({ if (!_.isUndefined(oldest)) { const firstMsg = messages[messages.length - 1]; if (!_.isUndefined(firstMsg) && firstMsg.ts > oldest) { - const unreadMessages = RocketChat.models.Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, firstMsg.ts, { limit: 1, sort: { ts: 1 } }); + const unreadMessages = Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, firstMsg.ts, { limit: 1, sort: { ts: 1 } }); firstUnread = unreadMessages.fetch()[0]; unreadNotLoaded = unreadMessages.count(); } diff --git a/packages/rocketchat-lib/server/methods/getRoomJoinCode.js b/packages/rocketchat-lib/server/methods/getRoomJoinCode.js index 2b2da233bf39..4a6224b94795 100644 --- a/packages/rocketchat-lib/server/methods/getRoomJoinCode.js +++ b/packages/rocketchat-lib/server/methods/getRoomJoinCode.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ getRoomJoinCode(rid) { @@ -9,11 +11,11 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getJoinCode' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'view-join-code')) { + if (!hasPermission(Meteor.userId(), 'view-join-code')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'getJoinCode' }); } - const [room] = RocketChat.models.Rooms.findById(rid).fetch(); + const [room] = Rooms.findById(rid).fetch(); return room && room.joinCode; }, diff --git a/packages/rocketchat-lib/server/methods/getRoomRoles.js b/packages/rocketchat-lib/server/methods/getRoomRoles.js index 3a79f1551ddb..ee18758d9b44 100644 --- a/packages/rocketchat-lib/server/methods/getRoomRoles.js +++ b/packages/rocketchat-lib/server/methods/getRoomRoles.js @@ -1,12 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions, Users, Roles } from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ getRoomRoles(rid) { check(rid, String); - if (!Meteor.userId() && RocketChat.settings.get('Accounts_AllowAnonymousRead') === false) { + if (!Meteor.userId() && settings.get('Accounts_AllowAnonymousRead') === false) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getRoomRoles' }); } @@ -23,16 +25,16 @@ Meteor.methods({ }, }; - const UI_Use_Real_Name = RocketChat.settings.get('UI_Use_Real_Name') === true; + const UI_Use_Real_Name = settings.get('UI_Use_Real_Name') === true; - const roles = RocketChat.models.Roles.find({ scope: 'Subscriptions', description: { $exists: 1, $ne: '' } }).fetch(); - const subscriptions = RocketChat.models.Subscriptions.findByRoomIdAndRoles(rid, _.pluck(roles, '_id'), options).fetch(); + const roles = Roles.find({ scope: 'Subscriptions', description: { $exists: 1, $ne: '' } }).fetch(); + const subscriptions = Subscriptions.findByRoomIdAndRoles(rid, _.pluck(roles, '_id'), options).fetch(); if (!UI_Use_Real_Name) { return subscriptions; } else { return subscriptions.map((subscription) => { - const user = RocketChat.models.Users.findOneById(subscription.u._id); + const user = Users.findOneById(subscription.u._id); subscription.u.name = user && user.name; return subscription; }); diff --git a/packages/rocketchat-lib/server/methods/getServerInfo.js b/packages/rocketchat-lib/server/methods/getServerInfo.js index 7c91ded54a60..d1f786eca374 100644 --- a/packages/rocketchat-lib/server/methods/getServerInfo.js +++ b/packages/rocketchat-lib/server/methods/getServerInfo.js @@ -1,7 +1,8 @@ import { Meteor } from 'meteor/meteor'; +import { Info } from 'meteor/rocketchat:utils'; Meteor.methods({ getServerInfo() { - return RocketChat.Info; + return Info; }, }); diff --git a/packages/rocketchat-lib/server/methods/getSingleMessage.js b/packages/rocketchat-lib/server/methods/getSingleMessage.js index 294cf1002ffa..756f8478cbb7 100644 --- a/packages/rocketchat-lib/server/methods/getSingleMessage.js +++ b/packages/rocketchat-lib/server/methods/getSingleMessage.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Messages } from 'meteor/rocketchat:models'; Meteor.methods({ getSingleMessage(msgId) { @@ -9,7 +10,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getSingleMessage' }); } - const msg = RocketChat.models.Messages.findOneById(msgId); + const msg = Messages.findOneById(msgId); if (!msg || !msg.rid) { return undefined; diff --git a/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js b/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js index b3ddb974d683..28211e2182c8 100644 --- a/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js +++ b/packages/rocketchat-lib/server/methods/getSlashCommandPreviews.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { slashCommands } from 'meteor/rocketchat:utils'; Meteor.methods({ getSlashCommandPreviews(command) { @@ -8,19 +9,19 @@ Meteor.methods({ }); } - if (!command || !command.cmd || !RocketChat.slashCommands.commands[command.cmd]) { + if (!command || !command.cmd || !slashCommands.commands[command.cmd]) { throw new Meteor.Error('error-invalid-command', 'Invalid Command Provided', { method: 'executeSlashCommandPreview', }); } - const theCmd = RocketChat.slashCommands.commands[command.cmd]; + const theCmd = slashCommands.commands[command.cmd]; if (!theCmd.providesPreview) { throw new Meteor.Error('error-invalid-command', 'Command Does Not Provide Previews', { method: 'executeSlashCommandPreview', }); } - return RocketChat.slashCommands.getPreviews(command.cmd, command.params, command.msg); + return slashCommands.getPreviews(command.cmd, command.params, command.msg); }, }); diff --git a/packages/rocketchat-lib/server/methods/getUserRoles.js b/packages/rocketchat-lib/server/methods/getUserRoles.js index a0c5ad940f44..5d4c32283fa8 100644 --- a/packages/rocketchat-lib/server/methods/getUserRoles.js +++ b/packages/rocketchat-lib/server/methods/getUserRoles.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { Roles, Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ @@ -18,12 +19,12 @@ Meteor.methods({ }, }; - const roles = RocketChat.models.Roles.find({ scope: 'Users', description: { $exists: 1, $ne: '' } }).fetch(); + const roles = Roles.find({ scope: 'Users', description: { $exists: 1, $ne: '' } }).fetch(); const roleIds = _.pluck(roles, '_id'); // Security issue: we should not send all user's roles to all clients, only the 'public' roles // We must remove all roles that are not part of the query from the returned users - const users = RocketChat.models.Users.findUsersInRoles(roleIds, null, options).fetch(); + const users = Users.findUsersInRoles(roleIds, null, options).fetch(); for (const user of users) { user.roles = _.intersection(user.roles, roleIds); } diff --git a/packages/rocketchat-lib/server/methods/joinRoom.js b/packages/rocketchat-lib/server/methods/joinRoom.js index fd7a99b50400..c0f236564c34 100644 --- a/packages/rocketchat-lib/server/methods/joinRoom.js +++ b/packages/rocketchat-lib/server/methods/joinRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission, canAccessRoom } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ joinRoom(rid, code) { @@ -9,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'joinRoom' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'joinRoom' }); @@ -24,10 +26,10 @@ Meteor.methods({ throw new Meteor.Error('error-not-allowed', 'Token required', { method: 'joinRoom' }); } } else { - if (!RocketChat.authz.canAccessRoom(room, Meteor.user())) { + if (!canAccessRoom(room, Meteor.user())) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'joinRoom' }); } - if ((room.joinCodeRequired === true) && (code !== room.joinCode) && !RocketChat.authz.hasPermission(Meteor.userId(), 'join-without-join-code')) { + if ((room.joinCodeRequired === true) && (code !== room.joinCode) && !hasPermission(Meteor.userId(), 'join-without-join-code')) { throw new Meteor.Error('error-code-invalid', 'Invalid Room Password', { method: 'joinRoom' }); } } diff --git a/packages/rocketchat-lib/server/methods/leaveRoom.js b/packages/rocketchat-lib/server/methods/leaveRoom.js index b7fe5324ada9..9ef756b99915 100644 --- a/packages/rocketchat-lib/server/methods/leaveRoom.js +++ b/packages/rocketchat-lib/server/methods/leaveRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission, hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; +import { Subscriptions, Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ leaveRoom(rid) { @@ -12,21 +14,21 @@ Meteor.methods({ this.unblock(); - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); const user = Meteor.user(); - if (room.t === 'd' || (room.t === 'c' && !RocketChat.authz.hasPermission(user._id, 'leave-c')) || (room.t === 'p' && !RocketChat.authz.hasPermission(user._id, 'leave-p'))) { + if (room.t === 'd' || (room.t === 'c' && !hasPermission(user._id, 'leave-c')) || (room.t === 'p' && !hasPermission(user._id, 'leave-p'))) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'leaveRoom' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); if (!subscription) { throw new Meteor.Error('error-user-not-in-room', 'You are not in this room', { method: 'leaveRoom' }); } // If user is room owner, check if there are other owners. If there isn't anyone else, warn user to set a new owner. - if (RocketChat.authz.hasRole(user._id, 'owner', room._id)) { - const numOwners = RocketChat.authz.getUsersInRole('owner', room._id).count(); + if (hasRole(user._id, 'owner', room._id)) { + const numOwners = getUsersInRole('owner', room._id).count(); if (numOwners === 1) { throw new Meteor.Error('error-you-are-last-owner', 'You are the last owner. Please set new owner before leaving the room.', { method: 'leaveRoom' }); } diff --git a/packages/rocketchat-lib/server/methods/refreshOAuthService.js b/packages/rocketchat-lib/server/methods/refreshOAuthService.js index 50efc1764b75..68984d4b4b32 100644 --- a/packages/rocketchat-lib/server/methods/refreshOAuthService.js +++ b/packages/rocketchat-lib/server/methods/refreshOAuthService.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { ServiceConfiguration } from 'meteor/service-configuration'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Settings } from 'meteor/rocketchat:models'; Meteor.methods({ refreshOAuthService() { @@ -7,12 +9,12 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'refreshOAuthService' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { + if (hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { throw new Meteor.Error('error-action-not-allowed', 'Refresh OAuth Services is not allowed', { method: 'refreshOAuthService', action: 'Refreshing_OAuth_Services' }); } ServiceConfiguration.configurations.remove({}); - RocketChat.models.Settings.update({ _id: /^Accounts_OAuth_.+/ }, { $set: { _updatedAt: new Date } }, { multi: true }); + Settings.update({ _id: /^Accounts_OAuth_.+/ }, { $set: { _updatedAt: new Date } }, { multi: true }); }, }); diff --git a/packages/rocketchat-lib/server/methods/removeOAuthService.js b/packages/rocketchat-lib/server/methods/removeOAuthService.js index 86ae0a11abe1..edcafff193ca 100644 --- a/packages/rocketchat-lib/server/methods/removeOAuthService.js +++ b/packages/rocketchat-lib/server/methods/removeOAuthService.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; Meteor.methods({ @@ -11,27 +13,27 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'removeOAuthService' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { + if (hasPermission(Meteor.userId(), 'add-oauth-service') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'removeOAuthService' }); } name = name.toLowerCase().replace(/[^a-z0-9_]/g, ''); name = s.capitalize(name); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-url`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-token_path`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_path`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-authorize_path`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-scope`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-token_sent_via`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-id`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-secret`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_text`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_color`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_color`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-login_style`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-username_field`); - RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-merge_users`); + settings.removeById(`Accounts_OAuth_Custom-${ name }`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-url`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-token_path`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_path`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-authorize_path`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-scope`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-token_sent_via`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_token_sent_via`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-id`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-secret`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_text`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_color`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-button_color`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-login_style`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-username_field`); + settings.removeById(`Accounts_OAuth_Custom-${ name }-merge_users`); }, }); diff --git a/packages/rocketchat-lib/server/methods/restartServer.js b/packages/rocketchat-lib/server/methods/restartServer.js index dba153b4edb3..9573a9ff8f91 100644 --- a/packages/rocketchat-lib/server/methods/restartServer.js +++ b/packages/rocketchat-lib/server/methods/restartServer.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ restart_server() { @@ -6,7 +7,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'restart_server' }); } - if (RocketChat.authz.hasRole(Meteor.userId(), 'admin') !== true) { + if (hasRole(Meteor.userId(), 'admin') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'restart_server' }); } diff --git a/packages/rocketchat-lib/server/methods/robotMethods.js b/packages/rocketchat-lib/server/methods/robotMethods.js index a47fe562bd51..a17bd78159ac 100644 --- a/packages/rocketchat-lib/server/methods/robotMethods.js +++ b/packages/rocketchat-lib/server/methods/robotMethods.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import * as Models from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ @@ -11,19 +13,19 @@ Meteor.methods({ method: 'robot.modelCall', }); } - if (!RocketChat.authz.hasRole(Meteor.userId(), 'robot')) { + if (!hasRole(Meteor.userId(), 'robot')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'robot.modelCall', }); } - const m = RocketChat.models[model]; + const m = Models[model]; if (!m || !_.isFunction(m[method])) { throw new Meteor.Error('error-invalid-method', 'Invalid method', { method: 'robot.modelCall', }); } - const cursor = RocketChat.models[model][method].apply(RocketChat.models[model], args); + const cursor = Models[model][method].apply(Models[model], args); return cursor && cursor.fetch ? cursor.fetch() : cursor; }, }); diff --git a/packages/rocketchat-lib/server/methods/saveSetting.js b/packages/rocketchat-lib/server/methods/saveSetting.js index 724e24a494bb..1bb86e9fd138 100644 --- a/packages/rocketchat-lib/server/methods/saveSetting.js +++ b/packages/rocketchat-lib/server/methods/saveSetting.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings } from 'meteor/rocketchat:models'; Meteor.methods({ saveSetting(_id, value, editor) { @@ -9,7 +12,7 @@ Meteor.methods({ }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'edit-privileged-setting')) { + if (!hasPermission(Meteor.userId(), 'edit-privileged-setting')) { throw new Meteor.Error('error-action-not-allowed', 'Editing settings is not allowed', { method: 'saveSetting', }); @@ -18,7 +21,7 @@ Meteor.methods({ // Verify the _id passed in is a string. check(_id, String); - const setting = RocketChat.models.Settings.db.findOneById(_id); + const setting = Settings.db.findOneById(_id); // Verify the value is what it should be switch (setting.type) { @@ -36,7 +39,7 @@ Meteor.methods({ break; } - RocketChat.settings.updateById(_id, value, editor); + settings.updateById(_id, value, editor); return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/sendInvitationEmail.js b/packages/rocketchat-lib/server/methods/sendInvitationEmail.js index 1605855a812b..b6821a0b84d3 100644 --- a/packages/rocketchat-lib/server/methods/sendInvitationEmail.js +++ b/packages/rocketchat-lib/server/methods/sendInvitationEmail.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import * as Mailer from 'meteor/rocketchat:mailer'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; let html = ''; Meteor.startup(() => { @@ -17,20 +19,20 @@ Meteor.methods({ method: 'sendInvitationEmail', }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'bulk-register-user')) { + if (!hasPermission(Meteor.userId(), 'bulk-register-user')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'sendInvitationEmail', }); } const validEmails = emails.filter(Mailer.checkAddressFormat); - const subject = RocketChat.settings.get('Invitation_Subject'); + const subject = settings.get('Invitation_Subject'); return validEmails.filter((email) => { try { return Mailer.send({ to: email, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), subject, html, data: { diff --git a/packages/rocketchat-lib/server/methods/sendMessage.js b/packages/rocketchat-lib/server/methods/sendMessage.js index 20d7dd19ffdd..0e754b534395 100644 --- a/packages/rocketchat-lib/server/methods/sendMessage.js +++ b/packages/rocketchat-lib/server/methods/sendMessage.js @@ -2,6 +2,12 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { metrics } from 'meteor/rocketchat:metrics'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { messageProperties } from 'meteor/rocketchat:ui-utils'; +import { Subscriptions, Users } from 'meteor/rocketchat:models'; import moment from 'moment'; Meteor.methods({ @@ -34,16 +40,16 @@ Meteor.methods({ } if (message.msg) { - const adjustedMessage = RocketChat.messageProperties.messageWithoutEmojiShortnames(message.msg); + const adjustedMessage = messageProperties.messageWithoutEmojiShortnames(message.msg); - if (RocketChat.messageProperties.length(adjustedMessage) > RocketChat.settings.get('Message_MaxAllowedSize')) { + if (messageProperties.length(adjustedMessage) > settings.get('Message_MaxAllowedSize')) { throw new Meteor.Error('error-message-size-exceeded', 'Message size exceeds Message_MaxAllowedSize', { method: 'sendMessage', }); } } - const user = RocketChat.models.Users.findOneById(Meteor.userId(), { + const user = Users.findOneById(Meteor.userId(), { fields: { username: 1, name: 1, @@ -55,9 +61,9 @@ Meteor.methods({ return false; } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId()); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId()); if (subscription && (subscription.blocked || subscription.blocker)) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: room._id, ts: new Date, @@ -67,7 +73,7 @@ Meteor.methods({ } if ((room.muted || []).includes(user.username)) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: room._id, ts: new Date, @@ -76,7 +82,7 @@ Meteor.methods({ throw new Meteor.Error('You can\'t send messages because you have been muted'); } - if (message.alias == null && RocketChat.settings.get('Message_SetNameToAliasEnabled')) { + if (message.alias == null && settings.get('Message_SetNameToAliasEnabled')) { message.alias = user.name; } @@ -84,13 +90,13 @@ Meteor.methods({ message.sandstormSessionId = this.connection.sandstormSessionId(); } - RocketChat.metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 + metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 return RocketChat.sendMessage(user, message, room); }, }); // Limit a user, who does not have the "bot" role, to sending 5 msgs/second RocketChat.RateLimiter.limitMethod('sendMessage', 5, 1000, { userId(userId) { - return !RocketChat.authz.hasPermission(userId, 'send-many-messages'); + return !hasPermission(userId, 'send-many-messages'); }, }); diff --git a/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js b/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js index e29c73662321..4271ea921c83 100644 --- a/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js +++ b/packages/rocketchat-lib/server/methods/sendSMTPTestEmail.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; import * as Mailer from 'meteor/rocketchat:mailer'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ sendSMTPTestEmail() { @@ -18,7 +19,7 @@ Meteor.methods({ try { Mailer.send({ to: user.emails[0].address, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), subject: 'SMTP Test Email', html: '

You have successfully sent an email

', }); diff --git a/packages/rocketchat-lib/server/methods/setAdminStatus.js b/packages/rocketchat-lib/server/methods/setAdminStatus.js index 00a79d2f199e..dd72c83049cf 100644 --- a/packages/rocketchat-lib/server/methods/setAdminStatus.js +++ b/packages/rocketchat-lib/server/methods/setAdminStatus.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ setAdminStatus(userId, admin) { @@ -11,7 +12,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setAdminStatus' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'assign-admin-role') !== true) { + if (hasPermission(Meteor.userId(), 'assign-admin-role') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setAdminStatus' }); } diff --git a/packages/rocketchat-lib/server/methods/setEmail.js b/packages/rocketchat-lib/server/methods/setEmail.js index 7d13ad2bc81f..583526ca9129 100644 --- a/packages/rocketchat-lib/server/methods/setEmail.js +++ b/packages/rocketchat-lib/server/methods/setEmail.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ setEmail(email) { @@ -12,7 +13,7 @@ Meteor.methods({ const user = Meteor.user(); - if (!RocketChat.settings.get('Accounts_AllowEmailChange')) { + if (!settings.get('Accounts_AllowEmailChange')) { throw new Meteor.Error('error-action-not-allowed', 'Changing email is not allowed', { method: 'setEmail', action: 'Changing_email' }); } diff --git a/packages/rocketchat-lib/server/methods/setRealName.js b/packages/rocketchat-lib/server/methods/setRealName.js index bd1ddfd430ae..e7a8218ecc70 100644 --- a/packages/rocketchat-lib/server/methods/setRealName.js +++ b/packages/rocketchat-lib/server/methods/setRealName.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.methods({ setRealName(name) { @@ -10,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setRealName' }); } - if (!RocketChat.settings.get('Accounts_AllowRealNameChange')) { + if (!settings.get('Accounts_AllowRealNameChange')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setRealName' }); } diff --git a/packages/rocketchat-lib/server/methods/setUsername.js b/packages/rocketchat-lib/server/methods/setUsername.js index 4c6fb84eddc9..c964fb0ac82b 100644 --- a/packages/rocketchat-lib/server/methods/setUsername.js +++ b/packages/rocketchat-lib/server/methods/setUsername.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; Meteor.methods({ @@ -13,7 +16,7 @@ Meteor.methods({ const user = Meteor.user(); - if (user.username && !RocketChat.settings.get('Accounts_AllowUsernameChange')) { + if (user.username && !settings.get('Accounts_AllowUsernameChange')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setUsername' }); } @@ -23,7 +26,7 @@ Meteor.methods({ let nameValidation; try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (error) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } @@ -43,7 +46,7 @@ Meteor.methods({ if (!user.username) { Meteor.runAsUser(user._id, () => Meteor.call('joinDefaultChannels', joinDefaultChannelsSilenced)); Meteor.defer(function() { - return RocketChat.callbacks.run('afterCreateUser', RocketChat.models.Users.findOneById(user._id)); + return callbacks.run('afterCreateUser', Users.findOneById(user._id)); }); } diff --git a/packages/rocketchat-lib/server/methods/unarchiveRoom.js b/packages/rocketchat-lib/server/methods/unarchiveRoom.js index 975c3162c938..f9aafcc15f62 100644 --- a/packages/rocketchat-lib/server/methods/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/methods/unarchiveRoom.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ unarchiveRoom(rid) { @@ -10,13 +12,13 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'unarchiveRoom' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'unarchiveRoom' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'unarchive-room', room._id)) { + if (!hasPermission(Meteor.userId(), 'unarchive-room', room._id)) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'unarchiveRoom' }); } diff --git a/packages/rocketchat-lib/server/methods/unblockUser.js b/packages/rocketchat-lib/server/methods/unblockUser.js index 21c8895e9283..481be92fe1b2 100644 --- a/packages/rocketchat-lib/server/methods/unblockUser.js +++ b/packages/rocketchat-lib/server/methods/unblockUser.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ unblockUser({ rid, blocked }) { @@ -11,14 +12,14 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'blockUser' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); - const subscription2 = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, blocked); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); + const subscription2 = Subscriptions.findOneByRoomIdAndUserId(rid, blocked); if (!subscription || !subscription2) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'blockUser' }); } - RocketChat.models.Subscriptions.unsetBlockedByRoomId(rid, blocked, Meteor.userId()); + Subscriptions.unsetBlockedByRoomId(rid, blocked, Meteor.userId()); return true; }, diff --git a/packages/rocketchat-lib/server/methods/updateMessage.js b/packages/rocketchat-lib/server/methods/updateMessage.js index feb03bd6d547..f2a5116d880c 100644 --- a/packages/rocketchat-lib/server/methods/updateMessage.js +++ b/packages/rocketchat-lib/server/methods/updateMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import moment from 'moment'; Meteor.methods({ @@ -11,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'updateMessage' }); } - const originalMessage = RocketChat.models.Messages.findOneById(message._id); + const originalMessage = Messages.findOneById(message._id); if (!originalMessage || !originalMessage._id) { return; @@ -19,15 +22,15 @@ Meteor.methods({ if (originalMessage.msg === message.msg) { return; } - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'edit-message', message.rid); - const editAllowed = RocketChat.settings.get('Message_AllowEditing'); + const _hasPermission = hasPermission(Meteor.userId(), 'edit-message', message.rid); + const editAllowed = settings.get('Message_AllowEditing'); const editOwn = originalMessage.u && originalMessage.u._id === Meteor.userId(); - if (!hasPermission && (!editAllowed || !editOwn)) { + if (!_hasPermission && (!editAllowed || !editOwn)) { throw new Meteor.Error('error-action-not-allowed', 'Message editing not allowed', { method: 'updateMessage', action: 'Message_editing' }); } - const blockEditInMinutes = RocketChat.settings.get('Message_AllowEditing_BlockEditInMinutes'); + const blockEditInMinutes = settings.get('Message_AllowEditing_BlockEditInMinutes'); if (Match.test(blockEditInMinutes, Number) && blockEditInMinutes !== 0) { let currentTsDiff; let msgTs; From 23388c4f2936e49aa2b5820fb363dbbe277d5321 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Tue, 22 Jan 2019 18:14:36 -0200 Subject: [PATCH 06/33] Remove some dependencies inside rocketchat-lib/server/startup, publications... (#13222) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace --- packages/rocketchat-lib/package.js | 2 - .../server/models/Permissions.js | 3 -- .../rocketchat-lib/server/models/Roles.js | 3 -- .../rocketchat-lib/server/models/index.js | 4 ++ .../rocketchat-lib/server/oauth/facebook.js | 1 + packages/rocketchat-lib/server/oauth/proxy.js | 5 ++- .../server/publications/settings.js | 29 +++++++------ .../rocketchat-lib/server/startup/email.js | 4 +- .../server/startup/oAuthServicesUpdate.js | 41 ++++++++++--------- .../rocketchat-lib/server/startup/robots.js | 3 +- .../rocketchat-lib/server/startup/settings.js | 23 ++++++----- .../server/startup/settingsOnLoadCdnPrefix.js | 15 +++---- .../startup/settingsOnLoadDirectReply.js | 9 ++-- .../server/startup/settingsOnLoadSMTP.js | 33 +++++++-------- .../startup/defaultRoomTypes.js | 13 +++--- 15 files changed, 99 insertions(+), 89 deletions(-) delete mode 100644 packages/rocketchat-lib/server/models/Permissions.js delete mode 100644 packages/rocketchat-lib/server/models/Roles.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9604a53f4ceb..8d856d350958 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -150,8 +150,6 @@ Package.onUse(function(api) { // SERVER MODELS api.addFiles('server/models/index.js', 'server'); - api.addFiles('server/models/Permissions.js', 'server'); - api.addFiles('server/models/Roles.js', 'server'); api.addFiles('server/oauth/oauth.js', 'server'); api.addFiles('server/oauth/facebook.js', 'server'); diff --git a/packages/rocketchat-lib/server/models/Permissions.js b/packages/rocketchat-lib/server/models/Permissions.js deleted file mode 100644 index c171d3bd4a99..000000000000 --- a/packages/rocketchat-lib/server/models/Permissions.js +++ /dev/null @@ -1,3 +0,0 @@ -import { Permissions } from 'meteor/rocketchat:models'; - -RocketChat.models.Permissions = Permissions; diff --git a/packages/rocketchat-lib/server/models/Roles.js b/packages/rocketchat-lib/server/models/Roles.js deleted file mode 100644 index 88c23358a0ed..000000000000 --- a/packages/rocketchat-lib/server/models/Roles.js +++ /dev/null @@ -1,3 +0,0 @@ -import { Roles } from 'meteor/rocketchat:models'; - -RocketChat.models.Roles = Roles; diff --git a/packages/rocketchat-lib/server/models/index.js b/packages/rocketchat-lib/server/models/index.js index a7620e0667d1..ebb3c8bd4bc2 100644 --- a/packages/rocketchat-lib/server/models/index.js +++ b/packages/rocketchat-lib/server/models/index.js @@ -13,6 +13,8 @@ import { Integrations, IntegrationHistory, Base as _Base, + Permissions, + Roles, } from 'meteor/rocketchat:models'; Object.assign(RocketChat.models, { @@ -30,4 +32,6 @@ Object.assign(RocketChat.models, { CustomSounds, Integrations, IntegrationHistory, + Permissions, + Roles, }); diff --git a/packages/rocketchat-lib/server/oauth/facebook.js b/packages/rocketchat-lib/server/oauth/facebook.js index 0bb04873083d..132fdc524c67 100644 --- a/packages/rocketchat-lib/server/oauth/facebook.js +++ b/packages/rocketchat-lib/server/oauth/facebook.js @@ -2,6 +2,7 @@ import { Match, check } from 'meteor/check'; import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; import { HTTP } from 'meteor/http'; + const crypto = Npm.require('crypto'); const whitelisted = [ 'id', diff --git a/packages/rocketchat-lib/server/oauth/proxy.js b/packages/rocketchat-lib/server/oauth/proxy.js index 7770f8fbc13e..31bd5061324d 100644 --- a/packages/rocketchat-lib/server/oauth/proxy.js +++ b/packages/rocketchat-lib/server/oauth/proxy.js @@ -1,10 +1,11 @@ import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; +import { settings } from 'meteor/rocketchat:settings'; OAuth._redirectUri = _.wrap(OAuth._redirectUri, function(func, serviceName, ...args) { - const proxy = RocketChat.settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(','); + const proxy = settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(','); if (proxy.includes(serviceName)) { - return `${ RocketChat.settings.get('Accounts_OAuth_Proxy_host') }/oauth_redirect`; + return `${ settings.get('Accounts_OAuth_Proxy_host') }/oauth_redirect`; } else { return func(serviceName, ...args); } diff --git a/packages/rocketchat-lib/server/publications/settings.js b/packages/rocketchat-lib/server/publications/settings.js index f15667be700d..64aefc717a09 100644 --- a/packages/rocketchat-lib/server/publications/settings.js +++ b/packages/rocketchat-lib/server/publications/settings.js @@ -1,16 +1,19 @@ import { Meteor } from 'meteor/meteor'; +import { Settings } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Notifications } from 'meteor/rocketchat:notifications'; Meteor.methods({ 'public-settings/get'(updatedAt) { this.unblock(); - const records = RocketChat.models.Settings.findNotHiddenPublic().fetch(); + const records = Settings.findNotHiddenPublic().fetch(); if (updatedAt instanceof Date) { return { update: records.filter(function(record) { return record._updatedAt > updatedAt; }), - remove: RocketChat.models.Settings.trashFindDeletedAfter(updatedAt, { + remove: Settings.trashFindDeletedAfter(updatedAt, { hidden: { $ne: true, }, @@ -30,16 +33,16 @@ Meteor.methods({ return []; } this.unblock(); - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'view-privileged-setting')) { + if (!hasPermission(Meteor.userId(), 'view-privileged-setting')) { return []; } - const records = RocketChat.models.Settings.findNotHidden().fetch(); + const records = Settings.findNotHidden().fetch(); if (updatedAt instanceof Date) { return { update: records.filter(function(record) { return record._updatedAt > updatedAt; }), - remove: RocketChat.models.Settings.trashFindDeletedAfter(updatedAt, { + remove: Settings.trashFindDeletedAfter(updatedAt, { hidden: { $ne: true, }, @@ -55,14 +58,14 @@ Meteor.methods({ }, }); -RocketChat.models.Settings.on('change', ({ clientAction, id, data, diff }) => { +Settings.on('change', ({ clientAction, id, data, diff }) => { if (diff && Object.keys(diff).length === 1 && diff._updatedAt) { // avoid useless changes return; } switch (clientAction) { case 'updated': case 'inserted': - const setting = data || RocketChat.models.Settings.findOneById(id); + const setting = data || Settings.findOneById(id); const value = { _id: setting._id, value: setting.value, @@ -71,22 +74,22 @@ RocketChat.models.Settings.on('change', ({ clientAction, id, data, diff }) => { }; if (setting.public === true) { - RocketChat.Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, value); + Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, value); } else { - RocketChat.Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, setting); + Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, setting); } break; case 'removed': - RocketChat.Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, { _id: id }); - RocketChat.Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, { _id: id }); + Notifications.notifyLoggedInThisInstance('private-settings-changed', clientAction, { _id: id }); + Notifications.notifyAllInThisInstance('public-settings-changed', clientAction, { _id: id }); break; } }); -RocketChat.Notifications.streamAll.allowRead('private-settings-changed', function() { +Notifications.streamAll.allowRead('private-settings-changed', function() { if (this.userId == null) { return false; } - return RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting'); + return hasPermission(this.userId, 'view-privileged-setting'); }); diff --git a/packages/rocketchat-lib/server/startup/email.js b/packages/rocketchat-lib/server/startup/email.js index 49c1252d0f98..1c63fcc4d1a6 100644 --- a/packages/rocketchat-lib/server/startup/email.js +++ b/packages/rocketchat-lib/server/startup/email.js @@ -1,4 +1,6 @@ -RocketChat.settings.addGroup('Email', function() { +import { settings } from 'meteor/rocketchat:settings'; + +settings.addGroup('Email', function() { this.section('Style', function() { this.add('email_style', `html, body, .body { font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Helvetica Neue','Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol','Meiryo UI',Arial,sans-serif; } diff --git a/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js b/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js index d320b580ee3c..8496d5623511 100644 --- a/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js +++ b/packages/rocketchat-lib/server/startup/oAuthServicesUpdate.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { ServiceConfiguration } from 'meteor/service-configuration'; import { CustomOAuth } from 'meteor/rocketchat:custom-oauth'; import { Logger } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; const logger = new Logger('rocketchat:lib', { @@ -13,7 +14,7 @@ const logger = new Logger('rocketchat:lib', { }); function _OAuthServicesUpdate() { - const services = RocketChat.settings.get(/^(Accounts_OAuth_|Accounts_OAuth_Custom-)[a-z0-9_]+$/i); + const services = settings.get(/^(Accounts_OAuth_|Accounts_OAuth_Custom-)[a-z0-9_]+$/i); services.forEach((service) => { logger.oauth_updated(service.key); let serviceName = service.key.replace('Accounts_OAuth_', ''); @@ -25,26 +26,26 @@ function _OAuthServicesUpdate() { } if (service.value === true) { const data = { - clientId: RocketChat.settings.get(`${ service.key }_id`), - secret: RocketChat.settings.get(`${ service.key }_secret`), + clientId: settings.get(`${ service.key }_id`), + secret: settings.get(`${ service.key }_secret`), }; if (/Accounts_OAuth_Custom-/.test(service.key)) { data.custom = true; - data.clientId = RocketChat.settings.get(`${ service.key }-id`); - data.secret = RocketChat.settings.get(`${ service.key }-secret`); - data.serverURL = RocketChat.settings.get(`${ service.key }-url`); - data.tokenPath = RocketChat.settings.get(`${ service.key }-token_path`); - data.identityPath = RocketChat.settings.get(`${ service.key }-identity_path`); - data.authorizePath = RocketChat.settings.get(`${ service.key }-authorize_path`); - data.scope = RocketChat.settings.get(`${ service.key }-scope`); - data.buttonLabelText = RocketChat.settings.get(`${ service.key }-button_label_text`); - data.buttonLabelColor = RocketChat.settings.get(`${ service.key }-button_label_color`); - data.loginStyle = RocketChat.settings.get(`${ service.key }-login_style`); - data.buttonColor = RocketChat.settings.get(`${ service.key }-button_color`); - data.tokenSentVia = RocketChat.settings.get(`${ service.key }-token_sent_via`); - data.identityTokenSentVia = RocketChat.settings.get(`${ service.key }-identity_token_sent_via`); - data.usernameField = RocketChat.settings.get(`${ service.key }-username_field`); - data.mergeUsers = RocketChat.settings.get(`${ service.key }-merge_users`); + data.clientId = settings.get(`${ service.key }-id`); + data.secret = settings.get(`${ service.key }-secret`); + data.serverURL = settings.get(`${ service.key }-url`); + data.tokenPath = settings.get(`${ service.key }-token_path`); + data.identityPath = settings.get(`${ service.key }-identity_path`); + data.authorizePath = settings.get(`${ service.key }-authorize_path`); + data.scope = settings.get(`${ service.key }-scope`); + data.buttonLabelText = settings.get(`${ service.key }-button_label_text`); + data.buttonLabelColor = settings.get(`${ service.key }-button_label_color`); + data.loginStyle = settings.get(`${ service.key }-login_style`); + data.buttonColor = settings.get(`${ service.key }-button_color`); + data.tokenSentVia = settings.get(`${ service.key }-token_sent_via`); + data.identityTokenSentVia = settings.get(`${ service.key }-identity_token_sent_via`); + data.usernameField = settings.get(`${ service.key }-username_field`); + data.mergeUsers = settings.get(`${ service.key }-merge_users`); new CustomOAuth(serviceName.toLowerCase(), { serverURL: data.serverURL, tokenPath: data.tokenPath, @@ -88,11 +89,11 @@ function OAuthServicesRemove(_id) { }); } -RocketChat.settings.get(/^Accounts_OAuth_.+/, function() { +settings.get(/^Accounts_OAuth_.+/, function() { return OAuthServicesUpdate(); // eslint-disable-line new-cap }); -RocketChat.settings.get(/^Accounts_OAuth_Custom-[a-z0-9_]+/, function(key, value) { +settings.get(/^Accounts_OAuth_Custom-[a-z0-9_]+/, function(key, value) { if (!value) { return OAuthServicesRemove(key);// eslint-disable-line new-cap } diff --git a/packages/rocketchat-lib/server/startup/robots.js b/packages/rocketchat-lib/server/startup/robots.js index 524020ff2dce..44573705b126 100644 --- a/packages/rocketchat-lib/server/startup/robots.js +++ b/packages/rocketchat-lib/server/startup/robots.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { return WebApp.connectHandlers.use('/robots.txt', Meteor.bindEnvironment(function(req, res/* , next*/) { res.writeHead(200); - res.end(RocketChat.settings.get('Robot_Instructions_File_Content')); + res.end(settings.get('Robot_Instructions_File_Content')); })); }); diff --git a/packages/rocketchat-lib/server/startup/settings.js b/packages/rocketchat-lib/server/startup/settings.js index 6204b2c91593..27e72232f85a 100644 --- a/packages/rocketchat-lib/server/startup/settings.js +++ b/packages/rocketchat-lib/server/startup/settings.js @@ -1,8 +1,9 @@ import { Random } from 'meteor/random'; +import { settings } from 'meteor/rocketchat:settings'; import './email'; // Insert server unique id if it doesn't exist -RocketChat.settings.add('uniqueID', process.env.DEPLOYMENT_ID || Random.id(), { +settings.add('uniqueID', process.env.DEPLOYMENT_ID || Random.id(), { public: true, hidden: true, }); @@ -10,7 +11,7 @@ RocketChat.settings.add('uniqueID', process.env.DEPLOYMENT_ID || Random.id(), { // When you define a setting and want to add a description, you don't need to automatically define the i18nDescription // if you add a node to the i18n.json with the same setting name but with `_Description` it will automatically work. -RocketChat.settings.addGroup('Accounts', function() { +settings.addGroup('Accounts', function() { this.add('Accounts_AllowAnonymousRead', false, { type: 'boolean', public: true, @@ -535,7 +536,7 @@ RocketChat.settings.addGroup('Accounts', function() { }); }); -RocketChat.settings.addGroup('OAuth', function() { +settings.addGroup('OAuth', function() { this.section('Facebook', function() { const enableQuery = { _id: 'Accounts_OAuth_Facebook', @@ -692,7 +693,7 @@ RocketChat.settings.addGroup('OAuth', function() { }); }); -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.add('Show_Setup_Wizard', 'pending', { type: 'select', public: true, @@ -898,7 +899,7 @@ RocketChat.settings.addGroup('General', function() { }); }); -RocketChat.settings.addGroup('Message', function() { +settings.addGroup('Message', function() { this.section('Message_Attachments', function() { this.add('Message_Attachments_GroupAttach', false, { type: 'boolean', @@ -1076,7 +1077,7 @@ RocketChat.settings.addGroup('Message', function() { }); }); -RocketChat.settings.addGroup('Meta', function() { +settings.addGroup('Meta', function() { this.add('Meta_language', '', { type: 'string', }); @@ -1099,7 +1100,7 @@ RocketChat.settings.addGroup('Meta', function() { }); }); -RocketChat.settings.addGroup('Push', function() { +settings.addGroup('Push', function() { this.add('Push_enable', true, { type: 'boolean', public: true, @@ -1200,7 +1201,7 @@ RocketChat.settings.addGroup('Push', function() { }); }); -RocketChat.settings.addGroup('Layout', function() { +settings.addGroup('Layout', function() { this.section('Content', function() { this.add('Layout_Home_Title', 'Home', { type: 'string', @@ -1289,7 +1290,7 @@ RocketChat.settings.addGroup('Layout', function() { }); }); -RocketChat.settings.addGroup('Logs', function() { +settings.addGroup('Logs', function() { this.add('Log_Level', '0', { type: 'select', values: [ @@ -1355,7 +1356,7 @@ RocketChat.settings.addGroup('Logs', function() { }); }); -RocketChat.settings.addGroup('Setup_Wizard', function() { +settings.addGroup('Setup_Wizard', function() { this.section('Organization_Info', function() { this.add('Organization_Type', '', { type: 'select', @@ -2666,4 +2667,4 @@ RocketChat.settings.addGroup('Setup_Wizard', function() { }); }); -RocketChat.settings.init(); +settings.init(); diff --git a/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js b/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js index bf8c2bbc9a52..94cc87095f6f 100644 --- a/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js +++ b/packages/rocketchat-lib/server/startup/settingsOnLoadCdnPrefix.js @@ -1,28 +1,29 @@ import { Meteor } from 'meteor/meteor'; import { WebAppInternals } from 'meteor/webapp'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; function testWebAppInternals(fn) { typeof WebAppInternals !== 'undefined' && fn(WebAppInternals); } -RocketChat.settings.onload('CDN_PREFIX', function(key, value) { - const useForAll = RocketChat.settings.get('CDN_PREFIX_ALL'); +settings.onload('CDN_PREFIX', function(key, value) { + const useForAll = settings.get('CDN_PREFIX_ALL'); if (_.isString(value) && value.trim() && useForAll) { return testWebAppInternals((WebAppInternals) => WebAppInternals.setBundledJsCssPrefix(value)); } }); -RocketChat.settings.onload('CDN_JSCSS_PREFIX', function(key, value) { - const useForAll = RocketChat.settings.get('CDN_PREFIX_ALL'); +settings.onload('CDN_JSCSS_PREFIX', function(key, value) { + const useForAll = settings.get('CDN_PREFIX_ALL'); if (_.isString(value) && value.trim() && !useForAll) { return testWebAppInternals((WebAppInternals) => WebAppInternals.setBundledJsCssPrefix(value)); } }); Meteor.startup(function() { - const cdnValue = RocketChat.settings.get('CDN_PREFIX'); - const useForAll = RocketChat.settings.get('CDN_PREFIX_ALL'); - const cdnJsCss = RocketChat.settings.get('CDN_JSCSS_PREFIX'); + const cdnValue = settings.get('CDN_PREFIX'); + const useForAll = settings.get('CDN_PREFIX_ALL'); + const cdnJsCss = settings.get('CDN_JSCSS_PREFIX'); if (_.isString(cdnValue) && cdnValue.trim()) { if (useForAll) { return testWebAppInternals((WebAppInternals) => WebAppInternals.setBundledJsCssPrefix(cdnValue)); diff --git a/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js b/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js index b0a532295b21..8886d01c331e 100644 --- a/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js +++ b/packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; import { IMAPIntercepter, POP3Helper } from '../lib/interceptDirectReplyEmails.js'; const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() { console.log('Starting Email Intercepter...'); - if (RocketChat.settings.get('Direct_Reply_Enable') && RocketChat.settings.get('Direct_Reply_Protocol') && RocketChat.settings.get('Direct_Reply_Host') && RocketChat.settings.get('Direct_Reply_Port') && RocketChat.settings.get('Direct_Reply_Username') && RocketChat.settings.get('Direct_Reply_Password')) { - if (RocketChat.settings.get('Direct_Reply_Protocol') === 'IMAP') { + if (settings.get('Direct_Reply_Enable') && settings.get('Direct_Reply_Protocol') && settings.get('Direct_Reply_Host') && settings.get('Direct_Reply_Port') && settings.get('Direct_Reply_Username') && settings.get('Direct_Reply_Password')) { + if (settings.get('Direct_Reply_Protocol') === 'IMAP') { // stop already running IMAP instance if (RocketChat.IMAP && RocketChat.IMAP.isActive()) { console.log('Disconnecting already running IMAP instance...'); @@ -30,7 +31,7 @@ const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() { RocketChat.IMAP.start(); return true; } - } else if (RocketChat.settings.get('Direct_Reply_Protocol') === 'POP') { + } else if (settings.get('Direct_Reply_Protocol') === 'POP') { // stop already running POP instance if (RocketChat.POP3 && RocketChat.POP3Helper && RocketChat.POP3Helper.isActive()) { console.log('Disconnecting already running POP instance...'); @@ -64,4 +65,4 @@ const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() { } }), 1000); -RocketChat.settings.onload(/^Direct_Reply_.+/, startEmailIntercepter); +settings.onload(/^Direct_Reply_.+/, startEmailIntercepter); diff --git a/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js b/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js index bab4eac13ba2..2abd41e01b11 100644 --- a/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js +++ b/packages/rocketchat-lib/server/startup/settingsOnLoadSMTP.js @@ -1,25 +1,26 @@ import { Meteor } from 'meteor/meteor'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; const buildMailURL = _.debounce(function() { console.log('Updating process.env.MAIL_URL'); - if (RocketChat.settings.get('SMTP_Host')) { - process.env.MAIL_URL = `${ RocketChat.settings.get('SMTP_Protocol') }://`; + if (settings.get('SMTP_Host')) { + process.env.MAIL_URL = `${ settings.get('SMTP_Protocol') }://`; - if (RocketChat.settings.get('SMTP_Username') && RocketChat.settings.get('SMTP_Password')) { - process.env.MAIL_URL += `${ encodeURIComponent(RocketChat.settings.get('SMTP_Username')) }:${ encodeURIComponent(RocketChat.settings.get('SMTP_Password')) }@`; + if (settings.get('SMTP_Username') && settings.get('SMTP_Password')) { + process.env.MAIL_URL += `${ encodeURIComponent(settings.get('SMTP_Username')) }:${ encodeURIComponent(settings.get('SMTP_Password')) }@`; } - process.env.MAIL_URL += encodeURIComponent(RocketChat.settings.get('SMTP_Host')); + process.env.MAIL_URL += encodeURIComponent(settings.get('SMTP_Host')); - if (RocketChat.settings.get('SMTP_Port')) { - process.env.MAIL_URL += `:${ parseInt(RocketChat.settings.get('SMTP_Port')) }`; + if (settings.get('SMTP_Port')) { + process.env.MAIL_URL += `:${ parseInt(settings.get('SMTP_Port')) }`; } - process.env.MAIL_URL += `?pool=${ RocketChat.settings.get('SMTP_Pool') }`; + process.env.MAIL_URL += `?pool=${ settings.get('SMTP_Pool') }`; - if (RocketChat.settings.get('SMTP_Protocol') === 'smtp' && RocketChat.settings.get('SMTP_IgnoreTLS')) { + if (settings.get('SMTP_Protocol') === 'smtp' && settings.get('SMTP_IgnoreTLS')) { process.env.MAIL_URL += '&secure=false&ignoreTLS=true'; } @@ -27,37 +28,37 @@ const buildMailURL = _.debounce(function() { } }, 500); -RocketChat.settings.onload('SMTP_Host', function(key, value) { +settings.onload('SMTP_Host', function(key, value) { if (_.isString(value)) { return buildMailURL(); } }); -RocketChat.settings.onload('SMTP_Port', function() { +settings.onload('SMTP_Port', function() { return buildMailURL(); }); -RocketChat.settings.onload('SMTP_Username', function(key, value) { +settings.onload('SMTP_Username', function(key, value) { if (_.isString(value)) { return buildMailURL(); } }); -RocketChat.settings.onload('SMTP_Password', function(key, value) { +settings.onload('SMTP_Password', function(key, value) { if (_.isString(value)) { return buildMailURL(); } }); -RocketChat.settings.onload('SMTP_Protocol', function() { +settings.onload('SMTP_Protocol', function() { return buildMailURL(); }); -RocketChat.settings.onload('SMTP_Pool', function() { +settings.onload('SMTP_Pool', function() { return buildMailURL(); }); -RocketChat.settings.onload('SMTP_IgnoreTLS', function() { +settings.onload('SMTP_IgnoreTLS', function() { return buildMailURL(); }); diff --git a/packages/rocketchat-lib/startup/defaultRoomTypes.js b/packages/rocketchat-lib/startup/defaultRoomTypes.js index 9defe836af70..047b0465dd94 100644 --- a/packages/rocketchat-lib/startup/defaultRoomTypes.js +++ b/packages/rocketchat-lib/startup/defaultRoomTypes.js @@ -1,3 +1,4 @@ +import { roomTypes } from 'meteor/rocketchat:utils'; import { ConversationRoomType, DirectMessageRoomType, @@ -7,9 +8,9 @@ import { UnreadRoomType, } from '../lib/roomTypes'; -RocketChat.roomTypes.add(new UnreadRoomType()); -RocketChat.roomTypes.add(new FavoriteRoomType()); -RocketChat.roomTypes.add(new ConversationRoomType()); -RocketChat.roomTypes.add(new PublicRoomType()); -RocketChat.roomTypes.add(new PrivateRoomType()); -RocketChat.roomTypes.add(new DirectMessageRoomType()); +roomTypes.add(new UnreadRoomType()); +roomTypes.add(new FavoriteRoomType()); +roomTypes.add(new ConversationRoomType()); +roomTypes.add(new PublicRoomType()); +roomTypes.add(new PrivateRoomType()); +roomTypes.add(new DirectMessageRoomType()); From 23547e904f23a2709e72077883d2938c814e4abd Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Tue, 22 Jan 2019 18:42:39 -0200 Subject: [PATCH 07/33] Remove duplicated server settings (#13223) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib --- packages/rocketchat-lib/package.js | 1 - .../server/functions/settings.js | 297 ------------------ packages/rocketchat-lib/startup/index.js | 3 +- packages/rocketchat-models/package.js | 1 - .../server/models/Messages.js | 13 +- .../rocketchat-models/server/models/Users.js | 11 +- .../server/models/_BaseDb.js | 15 +- packages/rocketchat-settings/package.js | 1 + .../server/functions/settings.js | 63 +--- 9 files changed, 50 insertions(+), 355 deletions(-) delete mode 100644 packages/rocketchat-lib/server/functions/settings.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 8d856d350958..80a3bf8ee166 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -123,7 +123,6 @@ Package.onUse(function(api) { api.addFiles('server/functions/saveCustomFields.js', 'server'); api.addFiles('server/functions/saveCustomFieldsWithoutValidation.js', 'server'); api.addFiles('server/functions/sendMessage.js', 'server'); - api.addFiles('server/functions/settings.js', 'server'); api.addFiles('server/functions/setUserAvatar.js', 'server'); api.addFiles('server/functions/setUsername.js', 'server'); api.addFiles('server/functions/setRealName.js', 'server'); diff --git a/packages/rocketchat-lib/server/functions/settings.js b/packages/rocketchat-lib/server/functions/settings.js deleted file mode 100644 index 4ffe64fc9250..000000000000 --- a/packages/rocketchat-lib/server/functions/settings.js +++ /dev/null @@ -1,297 +0,0 @@ -import { Meteor } from 'meteor/meteor'; -import _ from 'underscore'; - -const blockedSettings = {}; - -if (process.env.SETTINGS_BLOCKED) { - process.env.SETTINGS_BLOCKED.split(',').forEach((settingId) => blockedSettings[settingId] = 1); -} - -const hiddenSettings = {}; -if (process.env.SETTINGS_HIDDEN) { - process.env.SETTINGS_HIDDEN.split(',').forEach((settingId) => hiddenSettings[settingId] = 1); -} - -RocketChat.settings._sorter = {}; - - -/* -* Add a setting -* @param {String} _id -* @param {Mixed} value -* @param {Object} setting -*/ - -RocketChat.settings.add = function(_id, value, options = {}) { - if (options == null) { - options = {}; - } - if (!_id || value == null) { - return false; - } - if (RocketChat.settings._sorter[options.group] == null) { - RocketChat.settings._sorter[options.group] = 0; - } - options.packageValue = value; - options.valueSource = 'packageValue'; - options.hidden = options.hidden || false; - options.blocked = options.blocked || false; - if (options.sorter == null) { - options.sorter = RocketChat.settings._sorter[options.group]++; - } - if (options.enableQuery != null) { - options.enableQuery = JSON.stringify(options.enableQuery); - } - if (options.i18nDefaultQuery != null) { - options.i18nDefaultQuery = JSON.stringify(options.i18nDefaultQuery); - } - if (typeof process !== 'undefined' && process.env && process.env[_id]) { - value = process.env[_id]; - if (value.toLowerCase() === 'true') { - value = true; - } else if (value.toLowerCase() === 'false') { - value = false; - } else if (options.type === 'int') { - value = parseInt(value); - } - options.processEnvValue = value; - options.valueSource = 'processEnvValue'; - } else if (Meteor.settings && typeof Meteor.settings[_id] !== 'undefined') { - if (Meteor.settings[_id] == null) { - return false; - } - - value = Meteor.settings[_id]; - options.meteorSettingsValue = value; - options.valueSource = 'meteorSettingsValue'; - } - if (options.i18nLabel == null) { - options.i18nLabel = _id; - } - if (options.i18nDescription == null) { - options.i18nDescription = `${ _id }_Description`; - } - if (blockedSettings[_id] != null) { - options.blocked = true; - } - if (hiddenSettings[_id] != null) { - options.hidden = true; - } - if (options.autocomplete == null) { - options.autocomplete = true; - } - if (typeof process !== 'undefined' && process.env && process.env[`OVERWRITE_SETTING_${ _id }`]) { - let value = process.env[`OVERWRITE_SETTING_${ _id }`]; - if (value.toLowerCase() === 'true') { - value = true; - } else if (value.toLowerCase() === 'false') { - value = false; - } else if (options.type === 'int') { - value = parseInt(value); - } - options.value = value; - options.processEnvValue = value; - options.valueSource = 'processEnvValue'; - } - const updateOperations = { - $set: options, - $setOnInsert: { - createdAt: new Date, - }, - }; - if (options.editor != null) { - updateOperations.$setOnInsert.editor = options.editor; - delete options.editor; - } - if (options.value == null) { - if (options.force === true) { - updateOperations.$set.value = options.packageValue; - } else { - updateOperations.$setOnInsert.value = value; - } - } - const query = _.extend({ - _id, - }, updateOperations.$set); - if (options.section == null) { - updateOperations.$unset = { - section: 1, - }; - query.section = { - $exists: false, - }; - } - const existantSetting = RocketChat.models.Settings.db.findOne(query); - if (existantSetting != null) { - if (existantSetting.editor == null && updateOperations.$setOnInsert.editor != null) { - updateOperations.$set.editor = updateOperations.$setOnInsert.editor; - delete updateOperations.$setOnInsert.editor; - } - } else { - updateOperations.$set.ts = new Date; - } - return RocketChat.models.Settings.upsert({ - _id, - }, updateOperations); -}; - - -/* -* Add a setting group -* @param {String} _id -*/ - -RocketChat.settings.addGroup = function(_id, options = {}, cb) { - if (!_id) { - return false; - } - if (_.isFunction(options)) { - cb = options; - options = {}; - } - if (options.i18nLabel == null) { - options.i18nLabel = _id; - } - if (options.i18nDescription == null) { - options.i18nDescription = `${ _id }_Description`; - } - options.ts = new Date; - options.blocked = false; - options.hidden = false; - if (blockedSettings[_id] != null) { - options.blocked = true; - } - if (hiddenSettings[_id] != null) { - options.hidden = true; - } - RocketChat.models.Settings.upsert({ - _id, - }, { - $set: options, - $setOnInsert: { - type: 'group', - createdAt: new Date, - }, - }); - if (cb != null) { - cb.call({ - add(id, value, options) { - if (options == null) { - options = {}; - } - options.group = _id; - return RocketChat.settings.add(id, value, options); - }, - section(section, cb) { - return cb.call({ - add(id, value, options) { - if (options == null) { - options = {}; - } - options.group = _id; - options.section = section; - return RocketChat.settings.add(id, value, options); - }, - }); - }, - }); - } -}; - - -/* -* Remove a setting by id -* @param {String} _id -*/ - -RocketChat.settings.removeById = function(_id) { - if (!_id) { - return false; - } - return RocketChat.models.Settings.removeById(_id); -}; - - -/* -* Update a setting by id -* @param {String} _id -*/ - -RocketChat.settings.updateById = function(_id, value, editor) { - if (!_id || value == null) { - return false; - } - if (editor != null) { - return RocketChat.models.Settings.updateValueAndEditorById(_id, value, editor); - } - return RocketChat.models.Settings.updateValueById(_id, value); -}; - - -/* -* Update options of a setting by id -* @param {String} _id -*/ - -RocketChat.settings.updateOptionsById = function(_id, options) { - if (!_id || options == null) { - return false; - } - return RocketChat.models.Settings.updateOptionsById(_id, options); -}; - - -/* -* Update a setting by id -* @param {String} _id -*/ - -RocketChat.settings.clearById = function(_id) { - if (_id == null) { - return false; - } - return RocketChat.models.Settings.updateValueById(_id, undefined); -}; - - -/* -* Update a setting by id -*/ - -RocketChat.settings.init = function() { - RocketChat.settings.initialLoad = true; - RocketChat.models.Settings.find().observe({ - added(record) { - Meteor.settings[record._id] = record.value; - if (record.env === true) { - process.env[record._id] = record.value; - } - return RocketChat.settings.load(record._id, record.value, RocketChat.settings.initialLoad); - }, - changed(record) { - Meteor.settings[record._id] = record.value; - if (record.env === true) { - process.env[record._id] = record.value; - } - return RocketChat.settings.load(record._id, record.value, RocketChat.settings.initialLoad); - }, - removed(record) { - delete Meteor.settings[record._id]; - if (record.env === true) { - delete process.env[record._id]; - } - return RocketChat.settings.load(record._id, undefined, RocketChat.settings.initialLoad); - }, - }); - RocketChat.settings.initialLoad = false; - RocketChat.settings.afterInitialLoad.forEach((fn) => fn(Meteor.settings)); -}; - -RocketChat.settings.afterInitialLoad = []; - -RocketChat.settings.onAfterInitialLoad = function(fn) { - RocketChat.settings.afterInitialLoad.push(fn); - if (RocketChat.settings.initialLoad === false) { - return fn(Meteor.settings); - } -}; diff --git a/packages/rocketchat-lib/startup/index.js b/packages/rocketchat-lib/startup/index.js index ebfc1a2c6047..90c94606f7c8 100644 --- a/packages/rocketchat-lib/startup/index.js +++ b/packages/rocketchat-lib/startup/index.js @@ -1,3 +1,4 @@ import * as Mailer from 'meteor/rocketchat:mailer'; +import { settings } from 'meteor/rocketchat:settings'; -Mailer.setSettings(RocketChat.settings); +Mailer.setSettings(settings); diff --git a/packages/rocketchat-models/package.js b/packages/rocketchat-models/package.js index f09b9482f4aa..63cd19c90037 100755 --- a/packages/rocketchat-models/package.js +++ b/packages/rocketchat-models/package.js @@ -8,7 +8,6 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:settings', 'rocketchat:callbacks', 'rocketchat:ui-cached-collection', 'konecty:multiple-instances-status', diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index d56c4a255ba3..de009f321fef 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -1,6 +1,5 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { settings } from 'meteor/rocketchat:settings'; import { Base } from './_Base'; import Rooms from './Rooms'; import Users from './Users'; @@ -24,6 +23,14 @@ export class Messages extends Base { this.tryEnsureIndex({ snippeted: 1 }, { sparse: 1 }); this.tryEnsureIndex({ location: '2dsphere' }); this.tryEnsureIndex({ slackBotId: 1, slackTs: 1 }, { sparse: 1 }); + this.loadSettings(); + } + + loadSettings() { + Meteor.startup(async() => { + const { settings } = await import('meteor/rocketchat:settings'); + this.settings = settings; + }); } countVisibleByRoomIdBetweenTimestampsInclusive(roomId, afterTimestamp, beforeTimestamp, options) { @@ -600,7 +607,7 @@ export class Messages extends Base { groupable: false, }; - if (settings.get('Message_Read_Receipt_Enabled')) { + if (this.settings.get('Message_Read_Receipt_Enabled')) { record.unread = true; } @@ -629,7 +636,7 @@ export class Messages extends Base { groupable: false, }; - if (settings.get('Message_Read_Receipt_Enabled')) { + if (this.settings.get('Message_Read_Receipt_Enabled')) { record.unread = true; } diff --git a/packages/rocketchat-models/server/models/Users.js b/packages/rocketchat-models/server/models/Users.js index 7206dd9d9f6e..f90e64fa4a93 100644 --- a/packages/rocketchat-models/server/models/Users.js +++ b/packages/rocketchat-models/server/models/Users.js @@ -1,6 +1,5 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { settings } from 'meteor/rocketchat:settings'; import { Base } from './_Base'; import Subscriptions from './Subscriptions'; import _ from 'underscore'; @@ -17,6 +16,14 @@ export class Users extends Base { this.tryEnsureIndex({ active: 1 }, { sparse: 1 }); this.tryEnsureIndex({ statusConnection: 1 }, { sparse: 1 }); this.tryEnsureIndex({ type: 1 }); + this.loadSettings(); + } + + loadSettings() { + Meteor.startup(async() => { + const { settings } = await import('meteor/rocketchat:settings'); + this.settings = settings; + }); } roleBaseQuery(userId) { @@ -200,7 +207,7 @@ export class Users extends Base { const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i'); - const orStmt = _.reduce(settings.get('Accounts_SearchFields').trim().split(','), function(acc, el) { + const orStmt = _.reduce(this.settings.get('Accounts_SearchFields').trim().split(','), function(acc, el) { acc.push({ [el.trim()]: termRegex }); return acc; }, []); diff --git a/packages/rocketchat-models/server/models/_BaseDb.js b/packages/rocketchat-models/server/models/_BaseDb.js index fea2c84cab0a..d32642bcc145 100644 --- a/packages/rocketchat-models/server/models/_BaseDb.js +++ b/packages/rocketchat-models/server/models/_BaseDb.js @@ -1,6 +1,6 @@ +import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Mongo, MongoInternals } from 'meteor/mongo'; -import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; import { EventEmitter } from 'events'; @@ -16,9 +16,6 @@ try { const isOplogAvailable = MongoInternals.defaultRemoteCollectionDriver().mongo._oplogHandle && !!MongoInternals.defaultRemoteCollectionDriver().mongo._oplogHandle.onOplogEntry; let isOplogEnabled = isOplogAvailable; -settings.get('Force_Disable_OpLog_For_Cache', (key, value) => { - isOplogEnabled = isOplogAvailable && value === false; -}); export class BaseDb extends EventEmitter { constructor(model, baseModel) { @@ -39,6 +36,7 @@ export class BaseDb extends EventEmitter { this.wrapModel(); let alreadyListeningToOplog = false; + this.listenSettings(); // When someone start listening for changes we start oplog if available this.on('newListener', (event/* , listener*/) => { if (event === 'change' && alreadyListeningToOplog === false) { @@ -57,6 +55,15 @@ export class BaseDb extends EventEmitter { this.tryEnsureIndex({ _updatedAt: 1 }); } + listenSettings() { + Meteor.startup(async() => { + const { settings } = await import('meteor/rocketchat:settings'); + settings.get('Force_Disable_OpLog_For_Cache', (key, value) => { + isOplogEnabled = isOplogAvailable && value === false; + }); + }); + } + get baseName() { return baseName; } diff --git a/packages/rocketchat-settings/package.js b/packages/rocketchat-settings/package.js index 227969519e91..577c3640ce3e 100644 --- a/packages/rocketchat-settings/package.js +++ b/packages/rocketchat-settings/package.js @@ -9,6 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:ui-cached-collection', + 'rocketchat:models', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-settings/server/functions/settings.js b/packages/rocketchat-settings/server/functions/settings.js index 408e31c4450f..ba37d75c9d63 100644 --- a/packages/rocketchat-settings/server/functions/settings.js +++ b/packages/rocketchat-settings/server/functions/settings.js @@ -1,9 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { settings } from '../../lib/settings'; +import { Settings } from 'meteor/rocketchat:models'; import _ from 'underscore'; -let _Settings; - const blockedSettings = {}; if (process.env.SETTINGS_BLOCKED) { @@ -25,11 +24,7 @@ settings._sorter = {}; * @param {Object} setting */ -settings.add = async function(_id, value, options = {}) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.add = function(_id, value, options = {}) { if (options == null) { options = {}; } @@ -128,7 +123,7 @@ settings.add = async function(_id, value, options = {}) { $exists: false, }; } - const existantSetting = _Settings.db.findOne(query); + const existantSetting = Settings.db.findOne(query); if (existantSetting != null) { if (existantSetting.editor == null && updateOperations.$setOnInsert.editor != null) { updateOperations.$set.editor = updateOperations.$setOnInsert.editor; @@ -137,7 +132,7 @@ settings.add = async function(_id, value, options = {}) { } else { updateOperations.$set.ts = new Date; } - return _Settings.upsert({ + return Settings.upsert({ _id, }, updateOperations); }; @@ -148,11 +143,7 @@ settings.add = async function(_id, value, options = {}) { * @param {String} _id */ -settings.addGroup = async function(_id, options = {}, cb) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.addGroup = function(_id, options = {}, cb) { if (!_id) { return false; } @@ -175,7 +166,7 @@ settings.addGroup = async function(_id, options = {}, cb) { if (hiddenSettings[_id] != null) { options.hidden = true; } - _Settings.upsert({ + Settings.upsert({ _id, }, { $set: options, @@ -215,15 +206,11 @@ settings.addGroup = async function(_id, options = {}, cb) { * @param {String} _id */ -settings.removeById = async function(_id) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.removeById = function(_id) { if (!_id) { return false; } - return _Settings.removeById(_id); + return Settings.removeById(_id); }; @@ -232,18 +219,14 @@ settings.removeById = async function(_id) { * @param {String} _id */ -settings.updateById = async function(_id, value, editor) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.updateById = function(_id, value, editor) { if (!_id || value == null) { return false; } if (editor != null) { - return _Settings.updateValueAndEditorById(_id, value, editor); + return Settings.updateValueAndEditorById(_id, value, editor); } - return _Settings.updateValueById(_id, value); + return Settings.updateValueById(_id, value); }; @@ -252,15 +235,11 @@ settings.updateById = async function(_id, value, editor) { * @param {String} _id */ -settings.updateOptionsById = async function(_id, options) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.updateOptionsById = function(_id, options) { if (!_id || options == null) { return false; } - return _Settings.updateOptionsById(_id, options); + return Settings.updateOptionsById(_id, options); }; @@ -269,15 +248,11 @@ settings.updateOptionsById = async function(_id, options) { * @param {String} _id */ -settings.clearById = async function(_id) { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.clearById = function(_id) { if (_id == null) { return false; } - return _Settings.updateValueById(_id, undefined); + return Settings.updateValueById(_id, undefined); }; @@ -285,13 +260,9 @@ settings.clearById = async function(_id) { * Update a setting by id */ -settings.init = async function() { - if (!_Settings) { - const { Settings } = await import('meteor/rocketchat:models'); - _Settings = Settings; - } +settings.init = function() { settings.initialLoad = true; - _Settings.find().observe({ + Settings.find().observe({ added(record) { Meteor.settings[record._id] = record.value; if (record.env === true) { From 45b5dd00bf7762cc4e5767bbd750c118f5ef6b7d Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 14:39:29 -0200 Subject: [PATCH 08/33] Export functions and lib function of rc-lib but keep it inside RC namespace (#13225) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Fix missed exports and re-add some functions to RC namespace --- .../functions/addUserToDefaultChannels.js | 5 +++- .../server/functions/addUserToRoom.js | 4 ++- .../server/functions/archiveRoom.js | 4 ++- .../functions/checkEmailAvailability.js | 4 ++- .../functions/checkUsernameAvailability.js | 4 ++- .../server/functions/cleanRoomHistory.js | 4 ++- .../server/functions/createRoom.js | 4 ++- .../server/functions/deleteMessage.js | 4 ++- .../server/functions/deleteUser.js | 4 ++- .../server/functions/getFullUserData.js | 5 +++- .../getRoomByNameOrIdWithOptionToJoin.js | 4 ++- .../rocketchat-lib/server/functions/index.js | 25 +++++++++++++++++++ .../server/functions/isTheLastMessage.js | 4 ++- .../server/functions/loadMessageHistory.js | 4 ++- .../server/functions/removeUserFromRoom.js | 4 ++- .../server/functions/saveCustomFields.js | 4 ++- .../saveCustomFieldsWithoutValidation.js | 4 ++- .../server/functions/saveUser.js | 4 ++- .../server/functions/sendMessage.js | 4 ++- .../server/functions/setEmail.js | 6 +++-- .../server/functions/setRealName.js | 7 ++++-- .../server/functions/setUserAvatar.js | 4 ++- .../server/functions/setUsername.js | 7 ++++-- .../server/functions/unarchiveRoom.js | 4 ++- .../server/functions/updateMessage.js | 4 ++- .../server/functions/validateCustomFields.js | 4 ++- .../rocketchat-lib/server/lib/RateLimiter.js | 4 ++- packages/rocketchat-lib/server/lib/index.js | 8 ++++++ .../server/lib/passwordPolicy.js | 2 +- .../server/lib/processDirectEmail.js | 4 ++- .../server/lib/validateEmailDomain.js | 4 ++- 31 files changed, 125 insertions(+), 32 deletions(-) create mode 100644 packages/rocketchat-lib/server/functions/index.js diff --git a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js index df411a6d0616..e967b22e280a 100644 --- a/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js +++ b/packages/rocketchat-lib/server/functions/addUserToDefaultChannels.js @@ -2,7 +2,7 @@ import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.addUserToDefaultChannels = function(user, silenced) { +export const addUserToDefaultChannels = function(user, silenced) { callbacks.run('beforeJoinDefaultChannels', user); const defaultRooms = Rooms.findByDefaultAndTypes(true, ['c', 'p'], { fields: { usernames: 0 } }).fetch(); defaultRooms.forEach((room) => { @@ -32,3 +32,6 @@ RocketChat.addUserToDefaultChannels = function(user, silenced) { } }); }; + +RocketChat.addUserToDefaultChannels = addUserToDefaultChannels; + diff --git a/packages/rocketchat-lib/server/functions/addUserToRoom.js b/packages/rocketchat-lib/server/functions/addUserToRoom.js index c9e22dbad3b0..d67cd6dfd555 100644 --- a/packages/rocketchat-lib/server/functions/addUserToRoom.js +++ b/packages/rocketchat-lib/server/functions/addUserToRoom.js @@ -3,7 +3,7 @@ import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { +export const addUserToRoom = function(rid, user, inviter, silenced) { const now = new Date(); const room = Rooms.findOneById(rid); @@ -53,3 +53,5 @@ RocketChat.addUserToRoom = function(rid, user, inviter, silenced) { return true; }; + +RocketChat.addUserToRoom = addUserToRoom; diff --git a/packages/rocketchat-lib/server/functions/archiveRoom.js b/packages/rocketchat-lib/server/functions/archiveRoom.js index c906746c9c42..40a76a95f12d 100644 --- a/packages/rocketchat-lib/server/functions/archiveRoom.js +++ b/packages/rocketchat-lib/server/functions/archiveRoom.js @@ -2,9 +2,11 @@ import { Meteor } from 'meteor/meteor'; import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.archiveRoom = function(rid) { +export const archiveRoom = function(rid) { Rooms.archiveById(rid); Subscriptions.archiveByRoomId(rid); callbacks.run('afterRoomArchived', Rooms.findOneById(rid), Meteor.user()); }; + +RocketChat.archiveRoom = archiveRoom; diff --git a/packages/rocketchat-lib/server/functions/checkEmailAvailability.js b/packages/rocketchat-lib/server/functions/checkEmailAvailability.js index 3e892c5f19ac..6c5263c4f730 100644 --- a/packages/rocketchat-lib/server/functions/checkEmailAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkEmailAvailability.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import s from 'underscore.string'; -RocketChat.checkEmailAvailability = function(email) { +export const checkEmailAvailability = function(email) { return !Meteor.users.findOne({ 'emails.address': { $regex : new RegExp(`^${ s.trim(s.escapeRegExp(email)) }$`, 'i') } }); }; + +RocketChat.checkEmailAvailability = checkEmailAvailability; diff --git a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js index 6a3027b773b3..8f4509cb8be0 100644 --- a/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkUsernameAvailability.js @@ -13,7 +13,7 @@ settings.get('Accounts_BlockedUsernameList', (key, value) => { const usernameIsBlocked = (username, usernameBlackList) => usernameBlackList.length && usernameBlackList.some((restrictedUsername) => restrictedUsername.test(s.trim(s.escapeRegExp(username)))); -RocketChat.checkUsernameAvailability = function(username) { +export const checkUsernameAvailability = function(username) { if (usernameIsBlocked(username, usernameBlackList)) { return false; @@ -25,3 +25,5 @@ RocketChat.checkUsernameAvailability = function(username) { }, }, { fields: { _id: 1 } }); }; + +RocketChat.checkUsernameAvailability = checkUsernameAvailability; diff --git a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js index 2004db0157c0..967e7105415a 100644 --- a/packages/rocketchat-lib/server/functions/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/functions/cleanRoomHistory.js @@ -3,7 +3,7 @@ import { FileUpload } from 'meteor/rocketchat:file-upload'; import { Messages, Rooms } from 'meteor/rocketchat:models'; import { Notifications } from 'meteor/rocketchat:notifications'; -RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new Date('0001-01-01T00:00:00Z'), inclusive = true, limit = 0, excludePinned = true, filesOnly = false, fromUsers = [] }) { +export const cleanRoomHistory = function({ rid, latest = new Date(), oldest = new Date('0001-01-01T00:00:00Z'), inclusive = true, limit = 0, excludePinned = true, filesOnly = false, fromUsers = [] }) { const gt = inclusive ? '$gte' : '$gt'; const lt = inclusive ? '$lte' : '$lt'; @@ -42,3 +42,5 @@ RocketChat.cleanRoomHistory = function({ rid, latest = new Date(), oldest = new } return count; }; + +RocketChat.cleanRoomHistory = cleanRoomHistory; diff --git a/packages/rocketchat-lib/server/functions/createRoom.js b/packages/rocketchat-lib/server/functions/createRoom.js index 33293ceead7e..ca2154fd8290 100644 --- a/packages/rocketchat-lib/server/functions/createRoom.js +++ b/packages/rocketchat-lib/server/functions/createRoom.js @@ -6,7 +6,7 @@ import { getValidRoomName } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; -RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData = {}) { +export const createRoom = function(type, name, owner, members, readOnly, extraData = {}) { name = s.trim(name); owner = s.trim(owner); members = [].concat(members); @@ -118,3 +118,5 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData name: room.name, }; }; + +RocketChat.createRoom = createRoom; diff --git a/packages/rocketchat-lib/server/functions/deleteMessage.js b/packages/rocketchat-lib/server/functions/deleteMessage.js index d34152a0e95b..5c0c634d8d45 100644 --- a/packages/rocketchat-lib/server/functions/deleteMessage.js +++ b/packages/rocketchat-lib/server/functions/deleteMessage.js @@ -5,7 +5,7 @@ import { Messages, Uploads, Rooms } from 'meteor/rocketchat:models'; import { Notifications } from 'meteor/rocketchat:notifications'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.deleteMessage = function(message, user) { +export const deleteMessage = function(message, user) { const keepHistory = settings.get('Message_KeepHistory'); const showDeletedStatus = settings.get('Message_ShowDeletedStatus'); const deletedMsg = Messages.findOneById(message._id); @@ -59,3 +59,5 @@ RocketChat.deleteMessage = function(message, user) { Apps.getBridges().getListenerBridge().messageEvent('IPostMessageDeleted', deletedMsg); } }; + +RocketChat.deleteMessage = deleteMessage; diff --git a/packages/rocketchat-lib/server/functions/deleteUser.js b/packages/rocketchat-lib/server/functions/deleteUser.js index 85a0445c7756..6fe92b5ac8dd 100644 --- a/packages/rocketchat-lib/server/functions/deleteUser.js +++ b/packages/rocketchat-lib/server/functions/deleteUser.js @@ -6,7 +6,7 @@ import { hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { Notifications } from 'meteor/rocketchat:notifications'; -RocketChat.deleteUser = function(userId) { +export const deleteUser = function(userId) { const user = Users.findOneById(userId, { fields: { username: 1, avatarOrigin: 1 }, }); @@ -97,3 +97,5 @@ RocketChat.deleteUser = function(userId) { Users.removeById(userId); // Remove user from users database }; + +RocketChat.deleteUser = deleteUser; diff --git a/packages/rocketchat-lib/server/functions/getFullUserData.js b/packages/rocketchat-lib/server/functions/getFullUserData.js index 78ccac34e372..502ba1555286 100644 --- a/packages/rocketchat-lib/server/functions/getFullUserData.js +++ b/packages/rocketchat-lib/server/functions/getFullUserData.js @@ -53,7 +53,7 @@ settings.get('Accounts_CustomFields', (key, value) => { } }); -RocketChat.getFullUserData = function({ userId, filter, limit: l }) { +export const getFullUserData = function({ userId, filter, limit: l }) { const username = s.trim(filter); const userToRetrieveFullUserData = Users.findOneByUsername(username); const isMyOwnInfo = userToRetrieveFullUserData && userToRetrieveFullUserData._id === userId; @@ -83,3 +83,6 @@ RocketChat.getFullUserData = function({ userId, filter, limit: l }) { const usernameReg = new RegExp(s.escapeRegExp(username), 'i'); return Users.findByUsernameNameOrEmailAddress(usernameReg, options); }; + +RocketChat.getFullUserData = getFullUserData; + diff --git a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js index 5a0ff29f2ed5..88299f99598b 100644 --- a/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js +++ b/packages/rocketchat-lib/server/functions/getRoomByNameOrIdWithOptionToJoin.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Rooms, Users, Subscriptions } from 'meteor/rocketchat:models'; import _ from 'underscore'; -RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOptionToJoin({ currentUserId, nameOrId, type = '', tryDirectByUserIdOnly = false, joinChannel = true, errorOnEmpty = true }) { +export const getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOptionToJoin({ currentUserId, nameOrId, type = '', tryDirectByUserIdOnly = false, joinChannel = true, errorOnEmpty = true }) { let room; // If the nameOrId starts with #, then let's try to find a channel or group @@ -79,3 +79,5 @@ RocketChat.getRoomByNameOrIdWithOptionToJoin = function _getRoomByNameOrIdWithOp return room; }; + +RocketChat.getRoomByNameOrIdWithOptionToJoin = getRoomByNameOrIdWithOptionToJoin; diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js new file mode 100644 index 000000000000..11eac02244a3 --- /dev/null +++ b/packages/rocketchat-lib/server/functions/index.js @@ -0,0 +1,25 @@ +export { addUserToDefaultChannels } from './addUserToDefaultChannels'; +export { addUserToRoom } from './addUserToRoom'; +export { archiveRoom } from './archiveRoom'; +export { checkEmailAvailability } from './checkEmailAvailability'; +export { checkUsernameAvailability } from './checkUsernameAvailability'; +export { cleanRoomHistory } from './cleanRoomHistory'; +export { createRoom } from './createRoom'; +export { deleteMessage } from './deleteMessage'; +export { deleteUser } from './deleteUser'; +export { getFullUserData } from './getFullUserData'; +export { getRoomByNameOrIdWithOptionToJoin } from './getRoomByNameOrIdWithOptionToJoin'; +export { isTheLastMessage } from './isTheLastMessage'; +export { loadMessageHistory } from './loadMessageHistory'; +export { removeUserFromRoom } from './removeUserFromRoom'; +export { saveCustomFields } from './saveCustomFields'; +export { saveCustomFieldsWithoutValidation } from './saveCustomFieldsWithoutValidation'; +export { saveUser } from './saveUser'; +export { sendMessage } from './sendMessage'; +export { setEmail } from './setEmail'; +export { setRealName } from './setRealName'; +export { setUserAvatar } from './setUserAvatar'; +export { setUsername } from './setUsername'; +export { unarchiveRoom } from './unarchiveRoom'; +export { updateMessage } from './updateMessage'; +export { validateCustomFields } from './validateCustomFields'; diff --git a/packages/rocketchat-lib/server/functions/isTheLastMessage.js b/packages/rocketchat-lib/server/functions/isTheLastMessage.js index 5fe73fb08de6..57300e5e061d 100644 --- a/packages/rocketchat-lib/server/functions/isTheLastMessage.js +++ b/packages/rocketchat-lib/server/functions/isTheLastMessage.js @@ -1,3 +1,5 @@ import { settings } from 'meteor/rocketchat:settings'; -RocketChat.isTheLastMessage = (room, message) => settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); +export const isTheLastMessage = (room, message) => settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id); + +RocketChat.isTheLastMessage = isTheLastMessage; diff --git a/packages/rocketchat-lib/server/functions/loadMessageHistory.js b/packages/rocketchat-lib/server/functions/loadMessageHistory.js index 873a5aff01d9..421f39d5fbd6 100644 --- a/packages/rocketchat-lib/server/functions/loadMessageHistory.js +++ b/packages/rocketchat-lib/server/functions/loadMessageHistory.js @@ -21,7 +21,7 @@ settings.get(/Message_HideType_.+/, function(key, value) { }); }); -RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit = 20, ls }) { +export const loadMessageHistory = function loadMessageHistory({ userId, rid, end, limit = 20, ls }) { const options = { sort: { ts: -1, @@ -69,3 +69,5 @@ RocketChat.loadMessageHistory = function loadMessageHistory({ userId, rid, end, unreadNotLoaded, }; }; + +RocketChat.loadMessageHistory = loadMessageHistory; diff --git a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js index 2eb8ceed6737..0f100783447c 100644 --- a/packages/rocketchat-lib/server/functions/removeUserFromRoom.js +++ b/packages/rocketchat-lib/server/functions/removeUserFromRoom.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Rooms, Messages, Subscriptions } from 'meteor/rocketchat:models'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.removeUserFromRoom = function(rid, user) { +export const removeUserFromRoom = function(rid, user) { const room = Rooms.findOneById(rid); if (room) { @@ -27,3 +27,5 @@ RocketChat.removeUserFromRoom = function(rid, user) { }); } }; + +RocketChat.removeUserFromRoom = removeUserFromRoom; diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 86f9f3dab82a..292ddfbbdee8 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -1,9 +1,11 @@ import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; -RocketChat.saveCustomFields = function(userId, formData) { +export const saveCustomFields = function(userId, formData) { if (s.trim(settings.get('Accounts_CustomFields')) !== '') { RocketChat.validateCustomFields(formData); return RocketChat.saveCustomFieldsWithoutValidation(userId, formData); } }; + +RocketChat.saveCustomFields = saveCustomFields; diff --git a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js index e73019e5c14f..65a7b68a457e 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js @@ -3,7 +3,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { Users, Subscriptions } from 'meteor/rocketchat:models'; import s from 'underscore.string'; -RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { +export const saveCustomFieldsWithoutValidation = function(userId, formData) { if (s.trim(settings.get('Accounts_CustomFields')) !== '') { let customFieldsMeta; try { @@ -38,3 +38,5 @@ RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) { }); } }; + +RocketChat.saveCustomFieldsWithoutValidation = saveCustomFieldsWithoutValidation; diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index 14aa68429611..4f687b08164d 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -144,7 +144,7 @@ function validateUserEditing(userId, userData) { } } -RocketChat.saveUser = function(userId, userData) { +export const saveUser = function(userId, userData) { validateUserData(userId, userData); if (!userData._id) { @@ -267,3 +267,5 @@ RocketChat.saveUser = function(userId, userData) { return true; }; + +RocketChat.saveUser = saveUser; diff --git a/packages/rocketchat-lib/server/functions/sendMessage.js b/packages/rocketchat-lib/server/functions/sendMessage.js index 952b27895100..808613060a9a 100644 --- a/packages/rocketchat-lib/server/functions/sendMessage.js +++ b/packages/rocketchat-lib/server/functions/sendMessage.js @@ -78,7 +78,7 @@ const validateAttachment = (attachment) => { const validateBodyAttachments = (attachments) => attachments.map(validateAttachment); -RocketChat.sendMessage = function(user, message, room, upsert = false) { +export const sendMessage = function(user, message, room, upsert = false) { if (!user || !message || !room._id) { return false; } @@ -189,3 +189,5 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) { return message; } }; + +RocketChat.sendMessage = sendMessage; diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index ad05ef2fe3d7..91ff18fc41d1 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -3,7 +3,7 @@ import { Users } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; -RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = true) { +const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { email = s.trim(email); if (!userId) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { function: '_setEmail' }); @@ -36,6 +36,8 @@ RocketChat._setEmail = function(userId, email, shouldSendVerificationEmail = tru return user; }; -RocketChat.setEmail = RocketChat.RateLimiter.limitFunction(RocketChat._setEmail, 1, 60000, { +export const setEmail = RocketChat.RateLimiter.limitFunction(_setEmail, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those }); + +RocketChat.setEmail = setEmail; diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index 0cfac9bf3f87..d142e5d29416 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -5,7 +5,7 @@ import { Notifications } from 'meteor/rocketchat:notifications'; import { hasPermission } from 'meteor/rocketchat:authorization'; import s from 'underscore.string'; -RocketChat._setRealName = function(userId, name) { +const _setRealName = function(userId, name) { name = s.trim(name); if (!userId || !name) { return false; @@ -35,6 +35,9 @@ RocketChat._setRealName = function(userId, name) { return user; }; -RocketChat.setRealName = RocketChat.RateLimiter.limitFunction(RocketChat._setRealName, 1, 60000, { +export const setRealName = RocketChat.RateLimiter.limitFunction(_setRealName, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those }); + +RocketChat.setRealName = setRealName; +RocketChat._setRealName = _setRealName; diff --git a/packages/rocketchat-lib/server/functions/setUserAvatar.js b/packages/rocketchat-lib/server/functions/setUserAvatar.js index 4335123d0983..e32ce7f76171 100644 --- a/packages/rocketchat-lib/server/functions/setUserAvatar.js +++ b/packages/rocketchat-lib/server/functions/setUserAvatar.js @@ -5,7 +5,7 @@ import { FileUpload } from 'meteor/rocketchat:file-upload'; import { Users } from 'meteor/rocketchat:models'; import { Notifications } from 'meteor/rocketchat:notifications'; -RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { +export const setUserAvatar = function(user, dataURI, contentType, service) { let encoding; let image; @@ -63,3 +63,5 @@ RocketChat.setUserAvatar = function(user, dataURI, contentType, service) { }, 500); }); }; + +RocketChat.setUserAvatar = setUserAvatar; diff --git a/packages/rocketchat-lib/server/functions/setUsername.js b/packages/rocketchat-lib/server/functions/setUsername.js index 6003a7abaa45..ef6ec8a94f38 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.js +++ b/packages/rocketchat-lib/server/functions/setUsername.js @@ -5,7 +5,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { Users, Messages, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; -RocketChat._setUsername = function(userId, u) { +const _setUsername = function(userId, u) { const username = s.trim(u); if (!userId || !username) { return false; @@ -83,8 +83,11 @@ RocketChat._setUsername = function(userId, u) { return user; }; -RocketChat.setUsername = RocketChat.RateLimiter.limitFunction(RocketChat._setUsername, 1, 60000, { +export const setUsername = RocketChat.RateLimiter.limitFunction(_setUsername, 1, 60000, { [0](userId) { return !userId || !hasPermission(userId, 'edit-other-user-info'); }, }); + +RocketChat.setUsername = setUsername; +RocketChat._setUsername = _setUsername; diff --git a/packages/rocketchat-lib/server/functions/unarchiveRoom.js b/packages/rocketchat-lib/server/functions/unarchiveRoom.js index 9cce78e07e1d..93728e0a1018 100644 --- a/packages/rocketchat-lib/server/functions/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/functions/unarchiveRoom.js @@ -1,6 +1,8 @@ import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; -RocketChat.unarchiveRoom = function(rid) { +export const unarchiveRoom = function(rid) { Rooms.unarchiveById(rid); Subscriptions.unarchiveByRoomId(rid); }; + +RocketChat.unarchiveRoom = unarchiveRoom; diff --git a/packages/rocketchat-lib/server/functions/updateMessage.js b/packages/rocketchat-lib/server/functions/updateMessage.js index 82158b41dc12..a412cdfd5ef9 100644 --- a/packages/rocketchat-lib/server/functions/updateMessage.js +++ b/packages/rocketchat-lib/server/functions/updateMessage.js @@ -3,7 +3,7 @@ import { Messages, Rooms } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.updateMessage = function(message, user, originalMessage) { +export const updateMessage = function(message, user, originalMessage) { if (!originalMessage) { originalMessage = Messages.findOneById(message._id); } @@ -59,3 +59,5 @@ RocketChat.updateMessage = function(message, user, originalMessage) { callbacks.run('afterSaveMessage', Messages.findOneById(tempid), room, user._id); }); }; + +RocketChat.updateMessage = updateMessage; diff --git a/packages/rocketchat-lib/server/functions/validateCustomFields.js b/packages/rocketchat-lib/server/functions/validateCustomFields.js index f2d5bff1aba5..fca8829289d8 100644 --- a/packages/rocketchat-lib/server/functions/validateCustomFields.js +++ b/packages/rocketchat-lib/server/functions/validateCustomFields.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; -RocketChat.validateCustomFields = function(fields) { +export const validateCustomFields = function(fields) { // Special Case: // If an admin didn't set any custom fields there's nothing to validate against so consider any customFields valid if (s.trim(settings.get('Accounts_CustomFields')) === '') { @@ -41,3 +41,5 @@ RocketChat.validateCustomFields = function(fields) { } }); }; + +RocketChat.validateCustomFields = validateCustomFields; diff --git a/packages/rocketchat-lib/server/lib/RateLimiter.js b/packages/rocketchat-lib/server/lib/RateLimiter.js index dcbb7ce5a0c1..4099a430478e 100644 --- a/packages/rocketchat-lib/server/lib/RateLimiter.js +++ b/packages/rocketchat-lib/server/lib/RateLimiter.js @@ -3,7 +3,7 @@ import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; import { RateLimiter } from 'meteor/rate-limit'; import _ from 'underscore'; -RocketChat.RateLimiter = new class { +export const RateLimiterClass = new class { limitFunction(fn, numRequests, timeInterval, matchers) { if (process.env.TEST_MODE === 'true') { return fn; @@ -43,3 +43,5 @@ RocketChat.RateLimiter = new class { } }; + +RocketChat.RateLimiter = RateLimiterClass; diff --git a/packages/rocketchat-lib/server/lib/index.js b/packages/rocketchat-lib/server/lib/index.js index 5cf680b6e8b9..2c20567bc166 100644 --- a/packages/rocketchat-lib/server/lib/index.js +++ b/packages/rocketchat-lib/server/lib/index.js @@ -9,10 +9,18 @@ import { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig } from '../../lib/RoomTypeConfig'; import { sendNotification } from './sendNotificationsOnMessage.js'; export { hostname } from '../../lib/startup/settingsOnLoadSiteUrl'; +import { passwordPolicy } from './passwordPolicy'; +import { validateEmailDomain } from './validateEmailDomain'; +import { RateLimiterClass as RateLimiter } from './RateLimiter'; +import { processDirectEmail } from './processDirectEmail'; export { RoomSettingsEnum, RoomTypeConfig, RoomTypeRouteConfig, sendNotification, + passwordPolicy, + validateEmailDomain, + RateLimiter, + processDirectEmail, }; diff --git a/packages/rocketchat-lib/server/lib/passwordPolicy.js b/packages/rocketchat-lib/server/lib/passwordPolicy.js index cf741675b3dd..5f94dc7356b8 100644 --- a/packages/rocketchat-lib/server/lib/passwordPolicy.js +++ b/packages/rocketchat-lib/server/lib/passwordPolicy.js @@ -1,7 +1,7 @@ import { settings } from 'meteor/rocketchat:settings'; import PasswordPolicy from './PasswordPolicyClass'; -const passwordPolicy = new PasswordPolicy(); +export const passwordPolicy = new PasswordPolicy(); RocketChat.passwordPolicy = passwordPolicy; settings.get('Accounts_Password_Policy_Enabled', (key, value) => passwordPolicy.enabled = value); diff --git a/packages/rocketchat-lib/server/lib/processDirectEmail.js b/packages/rocketchat-lib/server/lib/processDirectEmail.js index 36b5ab27f437..d66e9e53b519 100644 --- a/packages/rocketchat-lib/server/lib/processDirectEmail.js +++ b/packages/rocketchat-lib/server/lib/processDirectEmail.js @@ -5,7 +5,7 @@ import { metrics } from 'meteor/rocketchat:metrics'; import { EmailReplyParser as reply } from 'emailreplyparser'; import moment from 'moment'; -RocketChat.processDirectEmail = function(email) { +export const processDirectEmail = function(email) { function sendMessage(email) { const message = { ts: new Date(email.headers.date), @@ -120,3 +120,5 @@ RocketChat.processDirectEmail = function(email) { console.log('Invalid Email....If not. Please report it.'); } }; + +RocketChat.processDirectEmail = processDirectEmail; diff --git a/packages/rocketchat-lib/server/lib/validateEmailDomain.js b/packages/rocketchat-lib/server/lib/validateEmailDomain.js index da7d3ac2f98a..f335c81716e9 100644 --- a/packages/rocketchat-lib/server/lib/validateEmailDomain.js +++ b/packages/rocketchat-lib/server/lib/validateEmailDomain.js @@ -22,7 +22,7 @@ settings.get('Accounts_UseDNSDomainCheck', function(key, value) { useDNSDomainCheck = value; }); -RocketChat.validateEmailDomain = function(email) { +export const validateEmailDomain = function(email) { const emailValidation = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; if (!emailValidation.test(email)) { throw new Meteor.Error('error-invalid-email', `Invalid email ${ email }`, { function: 'RocketChat.validateEmailDomain', email }); @@ -45,3 +45,5 @@ RocketChat.validateEmailDomain = function(email) { } } }; + +RocketChat.validateEmailDomain = validateEmailDomain; From a233ad7e279b979ed016af97316e99c4b8062b3f Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 15:12:36 -0200 Subject: [PATCH 09/33] Import variables from functions and lib to remove RC namespace dependency (#13226) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency --- .../server/functions/saveCustomFields.js | 5 +++-- .../rocketchat-lib/server/functions/saveUser.js | 16 +++++++++------- .../rocketchat-lib/server/functions/setEmail.js | 8 +++++--- .../server/functions/setRealName.js | 3 ++- .../server/functions/setUsername.js | 10 ++++++---- packages/rocketchat-lib/server/lib/bugsnag.js | 4 +--- .../server/lib/interceptDirectReplyEmails.js | 5 +++-- .../server/lib/processDirectEmail.js | 3 ++- .../server/methods/addUsersToRoom.js | 3 ++- .../rocketchat-lib/server/methods/archiveRoom.js | 3 ++- .../server/methods/checkUsernameAvailability.js | 6 ++++-- .../server/methods/cleanRoomHistory.js | 3 ++- .../server/methods/createChannel.js | 3 ++- .../server/methods/createPrivateGroup.js | 3 ++- .../server/methods/deleteMessage.js | 3 ++- .../server/methods/deleteUserOwnAccount.js | 3 ++- .../server/methods/getChannelHistory.js | 3 ++- .../server/methods/getFullUserData.js | 3 ++- .../server/methods/insertOrUpdateUser.js | 3 ++- .../server/methods/joinDefaultChannels.js | 3 ++- .../rocketchat-lib/server/methods/joinRoom.js | 3 ++- .../rocketchat-lib/server/methods/leaveRoom.js | 3 ++- .../rocketchat-lib/server/methods/sendMessage.js | 6 ++++-- .../rocketchat-lib/server/methods/setEmail.js | 6 ++++-- .../rocketchat-lib/server/methods/setRealName.js | 6 ++++-- .../rocketchat-lib/server/methods/setUsername.js | 8 +++++--- .../server/methods/unarchiveRoom.js | 3 ++- .../server/methods/updateMessage.js | 3 ++- packages/rocketchat-lib/server/oauth/facebook.js | 3 ++- packages/rocketchat-lib/server/oauth/google.js | 3 ++- packages/rocketchat-lib/server/oauth/oauth.js | 2 +- packages/rocketchat-lib/server/oauth/twitter.js | 3 ++- 32 files changed, 89 insertions(+), 53 deletions(-) diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 292ddfbbdee8..87eeb8f63b9e 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -1,10 +1,11 @@ import { settings } from 'meteor/rocketchat:settings'; +import { validateCustomFields, saveCustomFieldsWithoutValidation } from '.'; import s from 'underscore.string'; export const saveCustomFields = function(userId, formData) { if (s.trim(settings.get('Accounts_CustomFields')) !== '') { - RocketChat.validateCustomFields(formData); - return RocketChat.saveCustomFieldsWithoutValidation(userId, formData); + validateCustomFields(formData); + return saveCustomFieldsWithoutValidation(userId, formData); } }; diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index 4f687b08164d..b9264ac3e0a4 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -7,6 +7,8 @@ import { Gravatar } from 'meteor/jparker:gravatar'; import { getRoles, hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import PasswordPolicy from '../lib/PasswordPolicyClass'; +import { checkEmailAvailability, checkUsernameAvailability, setUserAvatar, setEmail, setRealName, setUsername } from '.'; +import { validateEmailDomain } from '../lib'; const passwordPolicy = new PasswordPolicy(); @@ -86,14 +88,14 @@ function validateUserData(userId, userData) { } if (!userData._id) { - if (!RocketChat.checkUsernameAvailability(userData.username)) { + if (!checkUsernameAvailability(userData.username)) { throw new Meteor.Error('error-field-unavailable', `${ _.escape(userData.username) } is already in use :(`, { method: 'insertOrUpdateUser', field: userData.username, }); } - if (userData.email && !RocketChat.checkEmailAvailability(userData.email)) { + if (userData.email && !checkEmailAvailability(userData.email)) { throw new Meteor.Error('error-field-unavailable', `${ _.escape(userData.email) } is already in use :(`, { method: 'insertOrUpdateUser', field: userData.email, @@ -148,7 +150,7 @@ export const saveUser = function(userId, userData) { validateUserData(userId, userData); if (!userData._id) { - RocketChat.validateEmailDomain(userData.email); + validateEmailDomain(userData.email); // insert user const createUser = { @@ -211,7 +213,7 @@ export const saveUser = function(userId, userData) { const gravatarUrl = Gravatar.imageUrl(userData.email, { default: '404', size: 200, secure: true }); try { - RocketChat.setUserAvatar(userData, gravatarUrl, '', 'url'); + setUserAvatar(userData, gravatarUrl, '', 'url'); } catch (e) { // Ignore this error for now, as it not being successful isn't bad } @@ -224,16 +226,16 @@ export const saveUser = function(userId, userData) { // update user if (userData.username) { - RocketChat.setUsername(userData._id, userData.username); + setUsername(userData._id, userData.username); } if (userData.name) { - RocketChat.setRealName(userData._id, userData.name); + setRealName(userData._id, userData.name); } if (userData.email) { const shouldSendVerificationEmailToUser = userData.verified !== true; - RocketChat.setEmail(userData._id, userData.email, shouldSendVerificationEmailToUser); + setEmail(userData._id, userData.email, shouldSendVerificationEmailToUser); } if (userData.password && userData.password.trim() && hasPermission(userId, 'edit-other-user-password') && passwordPolicy.validate(userData.password)) { diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index 91ff18fc41d1..55d1b9797162 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Users } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { RateLimiter, validateEmailDomain } from '../lib'; +import { checkEmailAvailability } from '.'; import s from 'underscore.string'; const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { @@ -13,7 +15,7 @@ const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { throw new Meteor.Error('error-invalid-email', 'Invalid email', { function: '_setEmail' }); } - RocketChat.validateEmailDomain(email); + validateEmailDomain(email); const user = Users.findOneById(userId); @@ -23,7 +25,7 @@ const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { } // Check email availability - if (!RocketChat.checkEmailAvailability(email)) { + if (!checkEmailAvailability(email)) { throw new Meteor.Error('error-field-unavailable', `${ email } is already in use :(`, { function: '_setEmail', field: email }); } @@ -36,7 +38,7 @@ const _setEmail = function(userId, email, shouldSendVerificationEmail = true) { return user; }; -export const setEmail = RocketChat.RateLimiter.limitFunction(_setEmail, 1, 60000, { +export const setEmail = RateLimiter.limitFunction(_setEmail, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others emails, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index d142e5d29416..6bafcb066b4e 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -3,6 +3,7 @@ import { Users, Subscriptions } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; import { Notifications } from 'meteor/rocketchat:notifications'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { RateLimiter } from '../lib'; import s from 'underscore.string'; const _setRealName = function(userId, name) { @@ -35,7 +36,7 @@ const _setRealName = function(userId, name) { return user; }; -export const setRealName = RocketChat.RateLimiter.limitFunction(_setRealName, 1, 60000, { +export const setRealName = RateLimiter.limitFunction(_setRealName, 1, 60000, { 0() { return !Meteor.userId() || !hasPermission(Meteor.userId(), 'edit-other-user-info'); }, // Administrators have permission to change others names, so don't limit those }); diff --git a/packages/rocketchat-lib/server/functions/setUsername.js b/packages/rocketchat-lib/server/functions/setUsername.js index ef6ec8a94f38..6e656a1c5856 100644 --- a/packages/rocketchat-lib/server/functions/setUsername.js +++ b/packages/rocketchat-lib/server/functions/setUsername.js @@ -4,6 +4,8 @@ import { FileUpload } from 'meteor/rocketchat:file-upload'; import { settings } from 'meteor/rocketchat:settings'; import { Users, Messages, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { RateLimiter } from '../lib'; +import { checkUsernameAvailability, setUserAvatar } from '.'; const _setUsername = function(userId, u) { const username = s.trim(u); @@ -27,7 +29,7 @@ const _setUsername = function(userId, u) { const previousUsername = user.username; // Check username availability or if the user already owns a different casing of the name if (!previousUsername || !(username.toLowerCase() === previousUsername.toLowerCase())) { - if (!RocketChat.checkUsernameAvailability(username)) { + if (!checkUsernameAvailability(username)) { return false; } } @@ -48,7 +50,7 @@ const _setUsername = function(userId, u) { Object.keys(avatarSuggestions).some((service) => { const avatarData = avatarSuggestions[service]; if (service !== 'gravatar') { - RocketChat.setUserAvatar(user, avatarData.blob, avatarData.contentType, service); + setUserAvatar(user, avatarData.blob, avatarData.contentType, service); gravatar = null; return true; } @@ -56,7 +58,7 @@ const _setUsername = function(userId, u) { return false; }); if (gravatar != null) { - RocketChat.setUserAvatar(user, gravatar.blob, gravatar.contentType, 'gravatar'); + setUserAvatar(user, gravatar.blob, gravatar.contentType, 'gravatar'); } } // Username is available; if coming from old username, update all references @@ -83,7 +85,7 @@ const _setUsername = function(userId, u) { return user; }; -export const setUsername = RocketChat.RateLimiter.limitFunction(_setUsername, 1, 60000, { +export const setUsername = RateLimiter.limitFunction(_setUsername, 1, 60000, { [0](userId) { return !userId || !hasPermission(userId, 'edit-other-user-info'); }, diff --git a/packages/rocketchat-lib/server/lib/bugsnag.js b/packages/rocketchat-lib/server/lib/bugsnag.js index 0586eb52ff93..58bd16ebde15 100644 --- a/packages/rocketchat-lib/server/lib/bugsnag.js +++ b/packages/rocketchat-lib/server/lib/bugsnag.js @@ -3,8 +3,6 @@ import { settings } from 'meteor/rocketchat:settings'; import { Info } from 'meteor/rocketchat:utils'; import bugsnag from 'bugsnag'; -RocketChat.bugsnag = bugsnag; - settings.get('Bugsnag_api_key', (key, value) => { if (value) { bugsnag.register(value); @@ -21,7 +19,7 @@ const notify = function(message, stack) { } const error = new Error(message); error.stack = stack; - RocketChat.bugsnag.notify(error, options); + bugsnag.notify(error, options); }; process.on('uncaughtException', Meteor.bindEnvironment((error) => { diff --git a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js index 5e54bc901689..05aaf79aa4f6 100644 --- a/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js +++ b/packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js @@ -3,6 +3,7 @@ import { settings } from 'meteor/rocketchat:settings'; import IMAP from 'imap'; import POP3 from 'poplib'; import { simpleParser } from 'mailparser'; +import { processDirectEmail } from '.'; export class IMAPIntercepter { constructor() { @@ -128,7 +129,7 @@ export class IMAPIntercepter { if (err) { console.log(`Mark deleted error: ${ err }`); } }); } - RocketChat.processDirectEmail(email); + processDirectEmail(email); })); })); f.once('error', (err) => { @@ -232,7 +233,7 @@ export class POP3Intercepter { body: mail.text, }; - RocketChat.processDirectEmail(email); + processDirectEmail(email); } } diff --git a/packages/rocketchat-lib/server/lib/processDirectEmail.js b/packages/rocketchat-lib/server/lib/processDirectEmail.js index d66e9e53b519..5c64c67af410 100644 --- a/packages/rocketchat-lib/server/lib/processDirectEmail.js +++ b/packages/rocketchat-lib/server/lib/processDirectEmail.js @@ -3,6 +3,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { Rooms, Messages, Users, Subscriptions } from 'meteor/rocketchat:models'; import { metrics } from 'meteor/rocketchat:metrics'; import { EmailReplyParser as reply } from 'emailreplyparser'; +import { sendMessage as _sendMessage } from '../functions'; import moment from 'moment'; export const processDirectEmail = function(email) { @@ -95,7 +96,7 @@ export const processDirectEmail = function(email) { metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 - return RocketChat.sendMessage(user, message, room); + return _sendMessage(user, message, room); } // Extract/parse reply from email body diff --git a/packages/rocketchat-lib/server/methods/addUsersToRoom.js b/packages/rocketchat-lib/server/methods/addUsersToRoom.js index dd16bfea969a..22c1a2000ca4 100644 --- a/packages/rocketchat-lib/server/methods/addUsersToRoom.js +++ b/packages/rocketchat-lib/server/methods/addUsersToRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Rooms, Subscriptions, Users } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { addUserToRoom } from '../functions'; Meteor.methods({ addUsersToRoom(data = {}) { @@ -64,7 +65,7 @@ Meteor.methods({ method: 'addUsersToRoom', }); } - RocketChat.addUserToRoom(data.rid, newUser, user); + addUserToRoom(data.rid, newUser, user); }); return true; diff --git a/packages/rocketchat-lib/server/methods/archiveRoom.js b/packages/rocketchat-lib/server/methods/archiveRoom.js index 26d03e477746..d8b8e503764a 100644 --- a/packages/rocketchat-lib/server/methods/archiveRoom.js +++ b/packages/rocketchat-lib/server/methods/archiveRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { archiveRoom } from '../functions'; Meteor.methods({ archiveRoom(rid) { @@ -26,6 +27,6 @@ Meteor.methods({ throw new Meteor.Error('error-direct-message-room', 'Direct Messages can not be archived', { method: 'archiveRoom' }); } - return RocketChat.archiveRoom(rid); + return archiveRoom(rid); }, }); diff --git a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js index a115878d3c5d..2dbf05c3f4a8 100644 --- a/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js +++ b/packages/rocketchat-lib/server/methods/checkUsernameAvailability.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; +import { checkUsernameAvailability } from '../functions'; +import { RateLimiter } from '../lib'; Meteor.methods({ checkUsernameAvailability(username) { @@ -19,10 +21,10 @@ Meteor.methods({ if (user.username === username) { return true; } - return RocketChat.checkUsernameAvailability(username); + return checkUsernameAvailability(username); }, }); -RocketChat.RateLimiter.limitMethod('checkUsernameAvailability', 1, 1000, { +RateLimiter.limitMethod('checkUsernameAvailability', 1, 1000, { userId() { return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js index 6e449f1a0353..baf50abfc0cc 100644 --- a/packages/rocketchat-lib/server/methods/cleanRoomHistory.js +++ b/packages/rocketchat-lib/server/methods/cleanRoomHistory.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { cleanRoomHistory } from '../functions'; Meteor.methods({ cleanRoomHistory({ roomId, latest, oldest, inclusive = true, limit, excludePinned = false, filesOnly = false, fromUsers = [] }) { @@ -23,6 +24,6 @@ Meteor.methods({ throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'cleanRoomHistory' }); } - return RocketChat.cleanRoomHistory({ rid: roomId, latest, oldest, inclusive, limit, excludePinned, filesOnly, fromUsers }); + return cleanRoomHistory({ rid: roomId, latest, oldest, inclusive, limit, excludePinned, filesOnly, fromUsers }); }, }); diff --git a/packages/rocketchat-lib/server/methods/createChannel.js b/packages/rocketchat-lib/server/methods/createChannel.js index df438753e028..56cff282b8de 100644 --- a/packages/rocketchat-lib/server/methods/createChannel.js +++ b/packages/rocketchat-lib/server/methods/createChannel.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { createRoom } from '../functions'; Meteor.methods({ createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -14,6 +15,6 @@ Meteor.methods({ if (!hasPermission(Meteor.userId(), 'create-c')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createChannel' }); } - return RocketChat.createRoom('c', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); + return createRoom('c', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); }, }); diff --git a/packages/rocketchat-lib/server/methods/createPrivateGroup.js b/packages/rocketchat-lib/server/methods/createPrivateGroup.js index 2a28cfd1f5b1..63ff39c41eb0 100644 --- a/packages/rocketchat-lib/server/methods/createPrivateGroup.js +++ b/packages/rocketchat-lib/server/methods/createPrivateGroup.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; +import { createRoom } from '../functions'; Meteor.methods({ createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) { @@ -26,6 +27,6 @@ Meteor.methods({ }), })); - return RocketChat.createRoom('p', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); + return createRoom('p', name, Meteor.user() && Meteor.user().username, members, readOnly, { customFields, ...extraData }); }, }); diff --git a/packages/rocketchat-lib/server/methods/deleteMessage.js b/packages/rocketchat-lib/server/methods/deleteMessage.js index 7dbed6f85c4c..97ed8f7f17b0 100644 --- a/packages/rocketchat-lib/server/methods/deleteMessage.js +++ b/packages/rocketchat-lib/server/methods/deleteMessage.js @@ -3,6 +3,7 @@ import { Match, check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { Messages } from 'meteor/rocketchat:models'; +import { deleteMessage } from '../functions'; import moment from 'moment'; Meteor.methods({ @@ -55,6 +56,6 @@ Meteor.methods({ }); } } - return RocketChat.deleteMessage(originalMessage, Meteor.user()); + return deleteMessage(originalMessage, Meteor.user()); }, }); diff --git a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js index 4189d0dd6f32..febe39cf61dc 100644 --- a/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js +++ b/packages/rocketchat-lib/server/methods/deleteUserOwnAccount.js @@ -3,6 +3,7 @@ import { check } from 'meteor/check'; import { Accounts } from 'meteor/accounts-base'; import { settings } from 'meteor/rocketchat:settings'; import { Users } from 'meteor/rocketchat:models'; +import { deleteUser } from '../functions'; import s from 'underscore.string'; Meteor.methods({ @@ -35,7 +36,7 @@ Meteor.methods({ } Meteor.defer(function() { - RocketChat.deleteUser(userId); + deleteUser(userId); }); return true; diff --git a/packages/rocketchat-lib/server/methods/getChannelHistory.js b/packages/rocketchat-lib/server/methods/getChannelHistory.js index b9ba43432f16..776d521233d0 100644 --- a/packages/rocketchat-lib/server/methods/getChannelHistory.js +++ b/packages/rocketchat-lib/server/methods/getChannelHistory.js @@ -3,6 +3,7 @@ import { check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { Subscriptions, Messages } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; import _ from 'underscore'; Meteor.methods({ @@ -56,7 +57,7 @@ Meteor.methods({ records = Messages.findVisibleByRoomIdBetweenTimestamps(rid, oldest, latest, options).fetch(); } - const messages = records.map((record) => RocketChat.composeMessageObjectWithUser(record, fromUserId)); + const messages = records.map((record) => composeMessageObjectWithUser(record, fromUserId)); if (unreads) { let unreadNotLoaded = 0; diff --git a/packages/rocketchat-lib/server/methods/getFullUserData.js b/packages/rocketchat-lib/server/methods/getFullUserData.js index e65628ecc7f0..9661f032b108 100644 --- a/packages/rocketchat-lib/server/methods/getFullUserData.js +++ b/packages/rocketchat-lib/server/methods/getFullUserData.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; +import { getFullUserData } from '../functions'; Meteor.methods({ getFullUserData({ filter = '', username = '', limit = 1 }) { - const result = RocketChat.getFullUserData({ userId: Meteor.userId(), filter: filter || username, limit }); + const result = getFullUserData({ userId: Meteor.userId(), filter: filter || username, limit }); return result && result.fetch(); }, }); diff --git a/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js b/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js index c024e6ee242d..aba6e0bc6485 100644 --- a/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js +++ b/packages/rocketchat-lib/server/methods/insertOrUpdateUser.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { saveUser } from '../functions'; Meteor.methods({ insertOrUpdateUser(userData) { @@ -10,6 +11,6 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'insertOrUpdateUser' }); } - return RocketChat.saveUser(Meteor.userId(), userData); + return saveUser(Meteor.userId(), userData); }, }); diff --git a/packages/rocketchat-lib/server/methods/joinDefaultChannels.js b/packages/rocketchat-lib/server/methods/joinDefaultChannels.js index 4e309f1d217a..2f1cdbdf24be 100644 --- a/packages/rocketchat-lib/server/methods/joinDefaultChannels.js +++ b/packages/rocketchat-lib/server/methods/joinDefaultChannels.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { addUserToDefaultChannels } from '../functions'; Meteor.methods({ joinDefaultChannels(silenced) { @@ -10,6 +11,6 @@ Meteor.methods({ } this.unblock(); - return RocketChat.addUserToDefaultChannels(Meteor.user(), silenced); + return addUserToDefaultChannels(Meteor.user(), silenced); }, }); diff --git a/packages/rocketchat-lib/server/methods/joinRoom.js b/packages/rocketchat-lib/server/methods/joinRoom.js index c0f236564c34..56e1fcbb46d5 100644 --- a/packages/rocketchat-lib/server/methods/joinRoom.js +++ b/packages/rocketchat-lib/server/methods/joinRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission, canAccessRoom } from 'meteor/rocketchat:authorization'; import { Rooms } from 'meteor/rocketchat:models'; +import { addUserToRoom } from '../functions'; Meteor.methods({ joinRoom(rid, code) { @@ -34,6 +35,6 @@ Meteor.methods({ } } - return RocketChat.addUserToRoom(rid, user); + return addUserToRoom(rid, user); }, }); diff --git a/packages/rocketchat-lib/server/methods/leaveRoom.js b/packages/rocketchat-lib/server/methods/leaveRoom.js index 9ef756b99915..7b8f5728c4e1 100644 --- a/packages/rocketchat-lib/server/methods/leaveRoom.js +++ b/packages/rocketchat-lib/server/methods/leaveRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission, hasRole, getUsersInRole } from 'meteor/rocketchat:authorization'; import { Subscriptions, Rooms } from 'meteor/rocketchat:models'; +import { removeUserFromRoom } from '../functions'; Meteor.methods({ leaveRoom(rid) { @@ -34,6 +35,6 @@ Meteor.methods({ } } - return RocketChat.removeUserFromRoom(rid, user); + return removeUserFromRoom(rid, user); }, }); diff --git a/packages/rocketchat-lib/server/methods/sendMessage.js b/packages/rocketchat-lib/server/methods/sendMessage.js index 0e754b534395..268f42bd119f 100644 --- a/packages/rocketchat-lib/server/methods/sendMessage.js +++ b/packages/rocketchat-lib/server/methods/sendMessage.js @@ -8,6 +8,8 @@ import { settings } from 'meteor/rocketchat:settings'; import { Notifications } from 'meteor/rocketchat:notifications'; import { messageProperties } from 'meteor/rocketchat:ui-utils'; import { Subscriptions, Users } from 'meteor/rocketchat:models'; +import { sendMessage } from '../functions'; +import { RateLimiter } from '../lib'; import moment from 'moment'; Meteor.methods({ @@ -91,11 +93,11 @@ Meteor.methods({ } metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736 - return RocketChat.sendMessage(user, message, room); + return sendMessage(user, message, room); }, }); // Limit a user, who does not have the "bot" role, to sending 5 msgs/second -RocketChat.RateLimiter.limitMethod('sendMessage', 5, 1000, { +RateLimiter.limitMethod('sendMessage', 5, 1000, { userId(userId) { return !hasPermission(userId, 'send-many-messages'); }, diff --git a/packages/rocketchat-lib/server/methods/setEmail.js b/packages/rocketchat-lib/server/methods/setEmail.js index 583526ca9129..38ea7387fae2 100644 --- a/packages/rocketchat-lib/server/methods/setEmail.js +++ b/packages/rocketchat-lib/server/methods/setEmail.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; +import { setEmail } from '../functions'; +import { RateLimiter } from '../lib'; Meteor.methods({ setEmail(email) { @@ -21,7 +23,7 @@ Meteor.methods({ return email; } - if (!RocketChat.setEmail(user._id, email)) { + if (!setEmail(user._id, email)) { throw new Meteor.Error('error-could-not-change-email', 'Could not change email', { method: 'setEmail' }); } @@ -29,6 +31,6 @@ Meteor.methods({ }, }); -RocketChat.RateLimiter.limitMethod('setEmail', 1, 1000, { +RateLimiter.limitMethod('setEmail', 1, 1000, { userId(/* userId*/) { return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/setRealName.js b/packages/rocketchat-lib/server/methods/setRealName.js index e7a8218ecc70..3b300ad723d9 100644 --- a/packages/rocketchat-lib/server/methods/setRealName.js +++ b/packages/rocketchat-lib/server/methods/setRealName.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; +import { setRealName } from '../functions'; +import { RateLimiter } from '../lib'; Meteor.methods({ setRealName(name) { @@ -15,7 +17,7 @@ Meteor.methods({ throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setRealName' }); } - if (!RocketChat.setRealName(Meteor.userId(), name)) { + if (!setRealName(Meteor.userId(), name)) { throw new Meteor.Error('error-could-not-change-name', 'Could not change name', { method: 'setRealName' }); } @@ -23,6 +25,6 @@ Meteor.methods({ }, }); -RocketChat.RateLimiter.limitMethod('setRealName', 1, 1000, { +RateLimiter.limitMethod('setRealName', 1, 1000, { userId: () => true, }); diff --git a/packages/rocketchat-lib/server/methods/setUsername.js b/packages/rocketchat-lib/server/methods/setUsername.js index c964fb0ac82b..c498bb99e2fb 100644 --- a/packages/rocketchat-lib/server/methods/setUsername.js +++ b/packages/rocketchat-lib/server/methods/setUsername.js @@ -3,6 +3,8 @@ import { check } from 'meteor/check'; import { settings } from 'meteor/rocketchat:settings'; import { Users } from 'meteor/rocketchat:models'; import { callbacks } from 'meteor/rocketchat:callbacks'; +import { setUsername, checkUsernameAvailability } from '../functions'; +import { RateLimiter } from '../lib'; import _ from 'underscore'; Meteor.methods({ @@ -35,11 +37,11 @@ Meteor.methods({ throw new Meteor.Error('username-invalid', `${ _.escape(username) } is not a valid username, use only letters, numbers, dots, hyphens and underscores`); } - if (!RocketChat.checkUsernameAvailability(username)) { + if (!checkUsernameAvailability(username)) { throw new Meteor.Error('error-field-unavailable', `${ _.escape(username) } is already in use :(`, { method: 'setUsername', field: username }); } - if (!RocketChat.setUsername(user._id, username)) { + if (!setUsername(user._id, username)) { throw new Meteor.Error('error-could-not-change-username', 'Could not change username', { method: 'setUsername' }); } @@ -54,6 +56,6 @@ Meteor.methods({ }, }); -RocketChat.RateLimiter.limitMethod('setUsername', 1, 1000, { +RateLimiter.limitMethod('setUsername', 1, 1000, { userId() { return true; }, }); diff --git a/packages/rocketchat-lib/server/methods/unarchiveRoom.js b/packages/rocketchat-lib/server/methods/unarchiveRoom.js index f9aafcc15f62..eda64b58e370 100644 --- a/packages/rocketchat-lib/server/methods/unarchiveRoom.js +++ b/packages/rocketchat-lib/server/methods/unarchiveRoom.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { Rooms } from 'meteor/rocketchat:models'; +import { unarchiveRoom } from '../functions'; Meteor.methods({ unarchiveRoom(rid) { @@ -22,6 +23,6 @@ Meteor.methods({ throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'unarchiveRoom' }); } - return RocketChat.unarchiveRoom(rid); + return unarchiveRoom(rid); }, }); diff --git a/packages/rocketchat-lib/server/methods/updateMessage.js b/packages/rocketchat-lib/server/methods/updateMessage.js index f2a5116d880c..5cee9e83aa29 100644 --- a/packages/rocketchat-lib/server/methods/updateMessage.js +++ b/packages/rocketchat-lib/server/methods/updateMessage.js @@ -4,6 +4,7 @@ import { Messages } from 'meteor/rocketchat:models'; import { settings } from 'meteor/rocketchat:settings'; import { hasPermission } from 'meteor/rocketchat:authorization'; import moment from 'moment'; +import { updateMessage } from '../functions'; Meteor.methods({ updateMessage(message) { @@ -55,6 +56,6 @@ Meteor.methods({ message.u = originalMessage.u; - return RocketChat.updateMessage(message, Meteor.user(), originalMessage); + return updateMessage(message, Meteor.user(), originalMessage); }, }); diff --git a/packages/rocketchat-lib/server/oauth/facebook.js b/packages/rocketchat-lib/server/oauth/facebook.js index 132fdc524c67..b35d116d8b38 100644 --- a/packages/rocketchat-lib/server/oauth/facebook.js +++ b/packages/rocketchat-lib/server/oauth/facebook.js @@ -2,6 +2,7 @@ import { Match, check } from 'meteor/check'; import _ from 'underscore'; import { OAuth } from 'meteor/oauth'; import { HTTP } from 'meteor/http'; +import { registerAccessTokenService } from './oauth'; const crypto = Npm.require('crypto'); const whitelisted = [ @@ -36,7 +37,7 @@ const getIdentity = function(accessToken, fields, secret) { } }; -RocketChat.registerAccessTokenService('facebook', function(options) { +registerAccessTokenService('facebook', function(options) { check(options, Match.ObjectIncluding({ accessToken: String, secret: String, diff --git a/packages/rocketchat-lib/server/oauth/google.js b/packages/rocketchat-lib/server/oauth/google.js index cdb50a05daed..7bccf9487761 100644 --- a/packages/rocketchat-lib/server/oauth/google.js +++ b/packages/rocketchat-lib/server/oauth/google.js @@ -2,6 +2,7 @@ import { Match, check } from 'meteor/check'; import _ from 'underscore'; import { HTTP } from 'meteor/http'; import { Google } from 'meteor/google-oauth'; +import { registerAccessTokenService } from './oauth'; function getIdentity(accessToken) { try { @@ -24,7 +25,7 @@ function getScopes(accessToken) { } -RocketChat.registerAccessTokenService('google', function(options) { +registerAccessTokenService('google', function(options) { check(options, Match.ObjectIncluding({ accessToken: String, idToken: String, diff --git a/packages/rocketchat-lib/server/oauth/oauth.js b/packages/rocketchat-lib/server/oauth/oauth.js index eef4e31739f8..c735ff0cc5b3 100644 --- a/packages/rocketchat-lib/server/oauth/oauth.js +++ b/packages/rocketchat-lib/server/oauth/oauth.js @@ -6,7 +6,7 @@ import _ from 'underscore'; const AccessTokenServices = {}; -RocketChat.registerAccessTokenService = function(serviceName, handleAccessTokenRequest) { +export const registerAccessTokenService = function(serviceName, handleAccessTokenRequest) { AccessTokenServices[serviceName] = { serviceName, handleAccessTokenRequest, diff --git a/packages/rocketchat-lib/server/oauth/twitter.js b/packages/rocketchat-lib/server/oauth/twitter.js index 38d1bd9cb30a..67ebca490495 100644 --- a/packages/rocketchat-lib/server/oauth/twitter.js +++ b/packages/rocketchat-lib/server/oauth/twitter.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; +import { registerAccessTokenService } from './oauth'; import Twit from 'twit'; import _ from 'underscore'; @@ -29,7 +30,7 @@ const getIdentity = function(accessToken, appId, appSecret, accessTokenSecret) { } }; -RocketChat.registerAccessTokenService('twitter', function(options) { +registerAccessTokenService('twitter', function(options) { check(options, Match.ObjectIncluding({ accessToken: String, appSecret: String, From 96f6fa13a290dcb6fa94e4ced13964bf001b2d99 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 15:39:26 -0200 Subject: [PATCH 10/33] Remove dependency of RC namespace in rc-sandstorm (#13227) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm --- packages/rocketchat-lib/client/lib/sandstorm.js | 3 +++ packages/rocketchat-lib/package.js | 3 +++ packages/rocketchat-lib/server/lib/sandstorm.js | 3 +++ .../server/lib/sendNotificationsOnMessage.js | 3 ++- packages/rocketchat-sandstorm/client/index.js | 6 +++++- packages/rocketchat-sandstorm/client/powerboxListener.js | 7 +++---- packages/rocketchat-sandstorm/package.js | 1 - packages/rocketchat-sandstorm/server/events.js | 6 +++--- packages/rocketchat-sandstorm/server/index.js | 6 +++++- packages/rocketchat-sandstorm/server/lib.js | 3 +-- packages/rocketchat-sandstorm/server/powerbox.js | 8 ++++---- 11 files changed, 32 insertions(+), 17 deletions(-) create mode 100644 packages/rocketchat-lib/client/lib/sandstorm.js create mode 100644 packages/rocketchat-lib/server/lib/sandstorm.js diff --git a/packages/rocketchat-lib/client/lib/sandstorm.js b/packages/rocketchat-lib/client/lib/sandstorm.js new file mode 100644 index 000000000000..c2a9a45ee5eb --- /dev/null +++ b/packages/rocketchat-lib/client/lib/sandstorm.js @@ -0,0 +1,3 @@ +import { Sandstorm } from 'meteor/rocketchat:sandstorm'; + +RocketChat.Sandstorm = Sandstorm; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 80a3bf8ee166..b68485aab8d7 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -43,6 +43,7 @@ Package.onUse(function(api) { api.use('rocketchat:logger'); api.use('rocketchat:mailer'); api.use('rocketchat:settings'); + api.use('rocketchat:sandstorm'); api.use('rocketchat:authorization'); api.use('mizzao:timesync'); api.use('rocketchat:custom-oauth'); @@ -146,6 +147,7 @@ Package.onUse(function(api) { api.addFiles('server/lib/validateEmailDomain.js', 'server'); api.addFiles('server/lib/passwordPolicy.js', 'server'); api.addFiles('server/lib/migrations.js', 'server'); + api.addFiles('server/lib/sandstorm.js', 'server'); // SERVER MODELS api.addFiles('server/models/index.js', 'server'); @@ -238,6 +240,7 @@ Package.onUse(function(api) { api.addFiles('client/lib/tooltip.js', 'client'); api.addFiles('client/lib/EmojiPicker.js', 'client'); api.addFiles('client/lib/ui-buttons.js', 'client'); + api.addFiles('client/lib/sandstorm.js', 'client'); // CLIENT LIB STARTUP api.addFiles('client/lib/startup/commands.js', 'client'); diff --git a/packages/rocketchat-lib/server/lib/sandstorm.js b/packages/rocketchat-lib/server/lib/sandstorm.js new file mode 100644 index 000000000000..c2a9a45ee5eb --- /dev/null +++ b/packages/rocketchat-lib/server/lib/sandstorm.js @@ -0,0 +1,3 @@ +import { Sandstorm } from 'meteor/rocketchat:sandstorm'; + +RocketChat.Sandstorm = Sandstorm; diff --git a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js index 0ee85ecddc51..2a2736fdcda4 100644 --- a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js +++ b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js @@ -5,6 +5,7 @@ import { settings } from 'meteor/rocketchat:settings'; import { callbacks } from 'meteor/rocketchat:callbacks'; import { Subscriptions } from 'meteor/rocketchat:models'; import { roomTypes } from 'meteor/rocketchat:utils'; +import { Sandstorm } from 'meteor/rocketchat:sandstorm'; import { callJoinRoom, messageContainsHighlight, parseMessageTextPerUser, replaceMentionedUsernamesWithFullNames } from '../functions/notifications/'; import { sendEmail, shouldNotifyEmail } from '../functions/notifications/email'; import { sendSinglePush, shouldNotifyMobile } from '../functions/notifications/mobile'; @@ -136,7 +137,7 @@ const sendNotification = async({ } if (notificationSent) { - RocketChat.Sandstorm.notify(message, [subscription.u._id], `@${ sender.username }: ${ message.msg }`, room.t === 'p' ? 'privateMessage' : 'message'); + Sandstorm.notify(message, [subscription.u._id], `@${ sender.username }: ${ message.msg }`, room.t === 'p' ? 'privateMessage' : 'message'); } }; diff --git a/packages/rocketchat-sandstorm/client/index.js b/packages/rocketchat-sandstorm/client/index.js index 4747a9261afc..11c6e2993767 100644 --- a/packages/rocketchat-sandstorm/client/index.js +++ b/packages/rocketchat-sandstorm/client/index.js @@ -1,2 +1,6 @@ -import './powerboxListener'; +import { Sandstorm } from './powerboxListener'; import './setPath'; + +export { + Sandstorm, +}; diff --git a/packages/rocketchat-sandstorm/client/powerboxListener.js b/packages/rocketchat-sandstorm/client/powerboxListener.js index 203c392fdde7..2bdef7411b05 100644 --- a/packages/rocketchat-sandstorm/client/powerboxListener.js +++ b/packages/rocketchat-sandstorm/client/powerboxListener.js @@ -1,9 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -RocketChat.Sandstorm = RocketChat.Sandstorm || {}; +export const Sandstorm = {}; -RocketChat.Sandstorm.request = function() {}; +Sandstorm.request = function() {}; if (Meteor.settings.public.sandstorm) { const callbackMap = {}; @@ -20,7 +19,7 @@ if (Meteor.settings.public.sandstorm) { uiView: 'EAZQAQEAABEBF1EEAQH_5-Jn6pjXtNsAAAA', }; - RocketChat.Sandstorm.request = function(interfaceName, cb) { + Sandstorm.request = function(interfaceName, cb) { const rpcId = Math.random().toString(); callbackMap[rpcId] = cb; window.parent.postMessage({ powerboxRequest: { diff --git a/packages/rocketchat-sandstorm/package.js b/packages/rocketchat-sandstorm/package.js index 78cf693797ca..20ed7713efa7 100644 --- a/packages/rocketchat-sandstorm/package.js +++ b/packages/rocketchat-sandstorm/package.js @@ -8,7 +8,6 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', 'jalik:ufs', 'kadira:flow-router', ]); diff --git a/packages/rocketchat-sandstorm/server/events.js b/packages/rocketchat-sandstorm/server/events.js index 5607afdea542..1d40e7c6add4 100644 --- a/packages/rocketchat-sandstorm/server/events.js +++ b/packages/rocketchat-sandstorm/server/events.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { getHttpBridge, waitPromise } from './lib'; +import { Sandstorm } from './lib'; import _ from 'underscore'; -RocketChat.Sandstorm.notify = function() {}; +Sandstorm.notify = function() {}; if (process.env.SANDSTORM === '1') { const ACTIVITY_TYPES = { @@ -11,7 +11,7 @@ if (process.env.SANDSTORM === '1') { privateMessage: 1, }; - RocketChat.Sandstorm.notify = function(message, userIds, caption, type) { + Sandstorm.notify = function(message, userIds, caption, type) { const sessionId = message.sandstormSessionId; if (!sessionId) { return; diff --git a/packages/rocketchat-sandstorm/server/index.js b/packages/rocketchat-sandstorm/server/index.js index a7cb461eb0b8..21d3801e191f 100644 --- a/packages/rocketchat-sandstorm/server/index.js +++ b/packages/rocketchat-sandstorm/server/index.js @@ -1,3 +1,7 @@ -import './lib'; +import { Sandstorm } from './lib'; import './events'; import './powerbox'; + +export { + Sandstorm, +}; diff --git a/packages/rocketchat-sandstorm/server/lib.js b/packages/rocketchat-sandstorm/server/lib.js index b12aac9ca88f..41c9fec79e11 100644 --- a/packages/rocketchat-sandstorm/server/lib.js +++ b/packages/rocketchat-sandstorm/server/lib.js @@ -1,8 +1,7 @@ import Future from 'fibers/future'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { UploadFS } from 'meteor/jalik:ufs'; -RocketChat.Sandstorm = {}; +export const Sandstorm = {}; export let getHttpBridge; export let waitPromise; diff --git a/packages/rocketchat-sandstorm/server/powerbox.js b/packages/rocketchat-sandstorm/server/powerbox.js index c74f37c766c4..efa9f2d9f2d3 100644 --- a/packages/rocketchat-sandstorm/server/powerbox.js +++ b/packages/rocketchat-sandstorm/server/powerbox.js @@ -1,15 +1,15 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Sandstorm } from './lib'; import { getHttpBridge, waitPromise } from './lib'; -RocketChat.Sandstorm.offerUiView = function() {}; +Sandstorm.offerUiView = function() {}; if (process.env.SANDSTORM === '1') { const Capnp = require('capnp'); const Powerbox = Capnp.importSystem('sandstorm/powerbox.capnp'); const Grain = Capnp.importSystem('sandstorm/grain.capnp'); - RocketChat.Sandstorm.offerUiView = function(token, serializedDescriptor, sessionId) { + Sandstorm.offerUiView = function(token, serializedDescriptor, sessionId) { const httpBridge = getHttpBridge(); const session = httpBridge.getSessionContext(sessionId).context; const { api } = httpBridge.getSandstormApi(sessionId); @@ -43,7 +43,7 @@ if (process.env.SANDSTORM === '1') { }; }, sandstormOffer(token, serializedDescriptor) { - RocketChat.Sandstorm.offerUiView(token, serializedDescriptor, + Sandstorm.offerUiView(token, serializedDescriptor, this.connection.sandstormSessionId()); }, }); From 4a3c69a17f2cd0fa970ce240cd78ad79128882cd Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 16:04:28 -0200 Subject: [PATCH 11/33] Remove dependency of RC namespace in chatpal-search (#13231) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search --- .../chatpal-search/client/template/admin.js | 7 ++++--- .../chatpal-search/client/template/result.js | 17 +++++++++-------- packages/chatpal-search/package.js | 3 +++ .../chatpal-search/server/provider/provider.js | 4 ++-- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/packages/chatpal-search/client/template/admin.js b/packages/chatpal-search/client/template/admin.js index d104c08311d3..3b51e8825245 100644 --- a/packages/chatpal-search/client/template/admin.js +++ b/packages/chatpal-search/client/template/admin.js @@ -2,7 +2,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasRole } from 'meteor/rocketchat:authorization'; import toastr from 'toastr'; Template.ChatpalAdmin.onCreated(function() { @@ -13,7 +14,7 @@ Template.ChatpalAdmin.onCreated(function() { this.apiKey = new ReactiveVar(); - const lang = RocketChat.settings.get('Language'); + const lang = settings.get('Language'); this.lang = (lang === 'de' || lang === 'en') ? lang : 'en'; @@ -58,7 +59,7 @@ Template.ChatpalAdmin.helpers({ return Template.instance().apiKey.get(); }, isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, tac() { return Template.instance().tac.get(); diff --git a/packages/chatpal-search/client/template/result.js b/packages/chatpal-search/client/template/result.js index 6028c81a6e6b..750fa9a83028 100644 --- a/packages/chatpal-search/client/template/result.js +++ b/packages/chatpal-search/client/template/result.js @@ -3,7 +3,8 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { roomTypes } from 'meteor/rocketchat:utils'; +import { Subscriptions } from 'meteor/rocketchat:models'; Template.ChatpalSearchResultTemplate.onCreated(function() { this.badRequest = new ReactiveVar(false); @@ -91,17 +92,17 @@ Template.ChatpalSearchSingleMessage.helpers({ if (room && room.t === 'd') { return 'at'; } - return RocketChat.roomTypes.getIcon(room && room.t); + return roomTypes.getIcon(room && room.t); }, roomLink() { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this.rid }); - return RocketChat.roomTypes.getRouteLink(subscription.t, subscription); + const subscription = Subscriptions.findOne({ rid: this.rid }); + return roomTypes.getRouteLink(subscription.t, subscription); }, roomName() { const room = Session.get(`roomData${ this.rid }`); - return RocketChat.roomTypes.getRoomName(room.t, room); + return roomTypes.getRoomName(room.t, room); }, time() { @@ -118,11 +119,11 @@ Template.ChatpalSearchSingleRoom.helpers({ if (room && room.t === 'd') { return 'at'; } - return RocketChat.roomTypes.getIcon(room && room.t); + return roomTypes.getIcon(room && room.t); }, roomLink() { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this._id }); - return RocketChat.roomTypes.getRouteLink(subscription.t, subscription); + const subscription = Subscriptions.findOne({ rid: this._id }); + return roomTypes.getRouteLink(subscription.t, subscription); }, }); diff --git a/packages/chatpal-search/package.js b/packages/chatpal-search/package.js index 06f5fe53821a..cdbfd317716f 100644 --- a/packages/chatpal-search/package.js +++ b/packages/chatpal-search/package.js @@ -10,6 +10,9 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:authorization', ]); api.addAssets([ 'server/asset/chatpal-enter.svg', diff --git a/packages/chatpal-search/server/provider/provider.js b/packages/chatpal-search/server/provider/provider.js index d6175f48c318..a7c732c269ef 100644 --- a/packages/chatpal-search/server/provider/provider.js +++ b/packages/chatpal-search/server/provider/provider.js @@ -2,7 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { searchProviderService, SearchProvider } from 'meteor/rocketchat:search'; import Index from './index'; import ChatpalLogger from '../utils/logger'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions } from 'meteor/rocketchat:models'; /** * The chatpal search provider enables chatpal search. An appropriate backedn has to be specified by settings. @@ -301,7 +301,7 @@ class ChatpalProvider extends SearchProvider { * @private */ _getAcl(context) { - return RocketChat.models.Subscriptions.find({ 'u._id': context.uid }).fetch().map((room) => room.rid); + return Subscriptions.find({ 'u._id': context.uid }).fetch().map((room) => room.rid); } /** From 54b152fbe57064a38d9660d00c7da2ca961cf103 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 16:28:16 -0200 Subject: [PATCH 12/33] Remove dependency of RC namespace in meteor saml (#13233) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml --- packages/meteor-accounts-saml/package.js | 2 +- .../server/saml_rocketchat.js | 62 +++++++++---------- .../server/saml_server.js | 11 ++-- packages/rocketchat-cas/server/index.js | 1 - packages/rocketchat-lib/package.js | 5 +- .../functions}/getUsernameSuggestion.js | 28 +++------ .../rocketchat-lib/server/functions/index.js | 1 + packages/rocketchat-lib/server/index.js | 2 + .../server/methods/getUsernameSuggestion.js | 16 +++++ packages/rocketchat-models/server/index.js | 2 + .../server/models/CredentialTokens.js | 8 ++- 11 files changed, 76 insertions(+), 62 deletions(-) rename {server/methods => packages/rocketchat-lib/server/functions}/getUsernameSuggestion.js (69%) create mode 100644 packages/rocketchat-lib/server/index.js create mode 100644 packages/rocketchat-lib/server/methods/getUsernameSuggestion.js rename packages/{rocketchat-cas => rocketchat-models}/server/models/CredentialTokens.js (78%) diff --git a/packages/meteor-accounts-saml/package.js b/packages/meteor-accounts-saml/package.js index 4c080b8739d2..467f0580c3bc 100644 --- a/packages/meteor-accounts-saml/package.js +++ b/packages/meteor-accounts-saml/package.js @@ -15,9 +15,9 @@ Package.on_use(function(api) { 'routepolicy', 'webapp', 'rocketchat:lib', + 'rocketchat:models', 'service-configuration', ], 'server'); - api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/meteor-accounts-saml/server/saml_rocketchat.js b/packages/meteor-accounts-saml/server/saml_rocketchat.js index 4b08f8f0e5c4..6132ba251946 100644 --- a/packages/meteor-accounts-saml/server/saml_rocketchat.js +++ b/packages/meteor-accounts-saml/server/saml_rocketchat.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Logger } from 'meteor/rocketchat:logger'; import { ServiceConfiguration } from 'meteor/service-configuration'; +import { settings } from 'meteor/rocketchat:settings'; const logger = new Logger('steffo:meteor-accounts-saml', { methods: { @@ -12,92 +12,92 @@ const logger = new Logger('steffo:meteor-accounts-saml', { }, }); -RocketChat.settings.addGroup('SAML'); +settings.addGroup('SAML'); Meteor.methods({ addSamlService(name) { - RocketChat.settings.add(`SAML_Custom_${ name }`, false, { + settings.add(`SAML_Custom_${ name }`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Enable', }); - RocketChat.settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', { + settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Provider', }); - RocketChat.settings.add(`SAML_Custom_${ name }_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', { + settings.add(`SAML_Custom_${ name }_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Entry_point', }); - RocketChat.settings.add(`SAML_Custom_${ name }_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', { + settings.add(`SAML_Custom_${ name }_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_IDP_SLO_Redirect_URL', }); - RocketChat.settings.add(`SAML_Custom_${ name }_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', { + settings.add(`SAML_Custom_${ name }_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Issuer', }); - RocketChat.settings.add(`SAML_Custom_${ name }_cert`, '', { + settings.add(`SAML_Custom_${ name }_cert`, '', { type: 'string', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Cert', multiline: true, }); - RocketChat.settings.add(`SAML_Custom_${ name }_public_cert`, '', { + settings.add(`SAML_Custom_${ name }_public_cert`, '', { type: 'string', group: 'SAML', section: name, multiline: true, i18nLabel: 'SAML_Custom_Public_Cert', }); - RocketChat.settings.add(`SAML_Custom_${ name }_private_key`, '', { + settings.add(`SAML_Custom_${ name }_private_key`, '', { type: 'string', group: 'SAML', section: name, multiline: true, i18nLabel: 'SAML_Custom_Private_Key', }); - RocketChat.settings.add(`SAML_Custom_${ name }_button_label_text`, '', { + settings.add(`SAML_Custom_${ name }_button_label_text`, '', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', }); - RocketChat.settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', { + settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', }); - RocketChat.settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', { + settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', { type: 'string', group: 'SAML', section: name, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', }); - RocketChat.settings.add(`SAML_Custom_${ name }_generate_username`, false, { + settings.add(`SAML_Custom_${ name }_generate_username`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Generate_Username', }); - RocketChat.settings.add(`SAML_Custom_${ name }_debug`, false, { + settings.add(`SAML_Custom_${ name }_debug`, false, { type: 'boolean', group: 'SAML', section: name, i18nLabel: 'SAML_Custom_Debug', }); - RocketChat.settings.add(`SAML_Custom_${ name }_logout_behaviour`, 'SAML', { + settings.add(`SAML_Custom_${ name }_logout_behaviour`, 'SAML', { type: 'select', values: [ { key: 'SAML', i18nLabel: 'SAML_Custom_Logout_Behaviour_Terminate_SAML_Session' }, @@ -112,22 +112,22 @@ Meteor.methods({ const getSamlConfigs = function(service) { return { - buttonLabelText: RocketChat.settings.get(`${ service.key }_button_label_text`), - buttonLabelColor: RocketChat.settings.get(`${ service.key }_button_label_color`), - buttonColor: RocketChat.settings.get(`${ service.key }_button_color`), + buttonLabelText: settings.get(`${ service.key }_button_label_text`), + buttonLabelColor: settings.get(`${ service.key }_button_label_color`), + buttonColor: settings.get(`${ service.key }_button_color`), clientConfig: { - provider: RocketChat.settings.get(`${ service.key }_provider`), + provider: settings.get(`${ service.key }_provider`), }, - entryPoint: RocketChat.settings.get(`${ service.key }_entry_point`), - idpSLORedirectURL: RocketChat.settings.get(`${ service.key }_idp_slo_redirect_url`), - generateUsername: RocketChat.settings.get(`${ service.key }_generate_username`), - debug: RocketChat.settings.get(`${ service.key }_debug`), - issuer: RocketChat.settings.get(`${ service.key }_issuer`), - logoutBehaviour: RocketChat.settings.get(`${ service.key }_logout_behaviour`), + entryPoint: settings.get(`${ service.key }_entry_point`), + idpSLORedirectURL: settings.get(`${ service.key }_idp_slo_redirect_url`), + generateUsername: settings.get(`${ service.key }_generate_username`), + debug: settings.get(`${ service.key }_debug`), + issuer: settings.get(`${ service.key }_issuer`), + logoutBehaviour: settings.get(`${ service.key }_logout_behaviour`), secret: { - privateKey: RocketChat.settings.get(`${ service.key }_private_key`), - publicCert: RocketChat.settings.get(`${ service.key }_public_cert`), - cert: RocketChat.settings.get(`${ service.key }_cert`), + privateKey: settings.get(`${ service.key }_private_key`), + publicCert: settings.get(`${ service.key }_public_cert`), + cert: settings.get(`${ service.key }_cert`), }, }; }; @@ -168,7 +168,7 @@ const configureSamlService = function(samlConfigs) { }; const updateServices = debounce(() => { - const services = RocketChat.settings.get(/^(SAML_Custom_)[a-z]+$/i); + const services = settings.get(/^(SAML_Custom_)[a-z]+$/i); Accounts.saml.settings.providers = services.map((service) => { if (service.value === true) { const samlConfigs = getSamlConfigs(service); @@ -187,7 +187,7 @@ const updateServices = debounce(() => { }, 2000); -RocketChat.settings.get(/^SAML_.+/, updateServices); +settings.get(/^SAML_.+/, updateServices); Meteor.startup(() => Meteor.call('addSamlService', 'Default')); diff --git a/packages/meteor-accounts-saml/server/saml_server.js b/packages/meteor-accounts-saml/server/saml_server.js index 8d4ccddde087..9f88f108e044 100644 --- a/packages/meteor-accounts-saml/server/saml_server.js +++ b/packages/meteor-accounts-saml/server/saml_server.js @@ -2,8 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { RoutePolicy } from 'meteor/routepolicy'; +import { CredentialTokens } from 'meteor/rocketchat:models'; +import { generateUsernameSuggestion } from 'meteor/rocketchat:lib'; import bodyParser from 'body-parser'; import { SAML } from './saml_utils'; import _ from 'underscore'; @@ -126,7 +127,7 @@ Accounts.registerLoginHandler(function(loginRequest) { }; if (Accounts.saml.settings.generateUsername === true) { - const username = RocketChat.generateUsernameSuggestion(newUser); + const username = generateUsernameSuggestion(newUser); if (username) { newUser.username = username; } @@ -176,19 +177,19 @@ Accounts.registerLoginHandler(function(loginRequest) { }); Accounts.saml.hasCredential = function(credentialToken) { - return RocketChat.models.CredentialTokens.findOneById(credentialToken) != null; + return CredentialTokens.findOneById(credentialToken) != null; }; Accounts.saml.retrieveCredential = function(credentialToken) { // The credentialToken in all these functions corresponds to SAMLs inResponseTo field and is mandatory to check. - const data = RocketChat.models.CredentialTokens.findOneById(credentialToken); + const data = CredentialTokens.findOneById(credentialToken); if (data) { return data.userInfo; } }; Accounts.saml.storeCredential = function(credentialToken, loginResult) { - RocketChat.models.CredentialTokens.create(credentialToken, loginResult); + CredentialTokens.create(credentialToken, loginResult); }; const closePopup = function(res, err) { diff --git a/packages/rocketchat-cas/server/index.js b/packages/rocketchat-cas/server/index.js index 451c7d5a8aa0..0ad22d77b198 100644 --- a/packages/rocketchat-cas/server/index.js +++ b/packages/rocketchat-cas/server/index.js @@ -1,3 +1,2 @@ -import './models/CredentialTokens'; import './cas_rocketchat'; import './cas_server'; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index b68485aab8d7..8639b3ad7d6d 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -22,6 +22,7 @@ Package.onUse(function(api) { api.use('mongo'); api.use('oauth'); api.use('matb33:collection-hooks'); + api.use('yasaricli:slugify'); api.use('service-configuration'); api.use('check'); api.use('rocketchat:utils'); @@ -133,6 +134,7 @@ Package.onUse(function(api) { api.addFiles('server/functions/validateCustomFields.js', 'server'); api.addFiles('server/functions/Notifications.js', 'server'); api.addFiles('server/functions/authorization.js', 'server'); + api.addFiles('server/functions/getUsernameSuggestion.js', 'server'); // SERVER LIB api.addFiles('server/lib/configLogger.js', 'server'); @@ -209,6 +211,7 @@ Package.onUse(function(api) { api.addFiles('server/methods/unarchiveRoom.js', 'server'); api.addFiles('server/methods/unblockUser.js', 'server'); api.addFiles('server/methods/updateMessage.js', 'server'); + api.addFiles('server/methods/getUsernameSuggestion.js', 'server'); // SERVER STARTUP api.addFiles('server/startup/settingsOnLoadCdnPrefix.js', 'server'); @@ -275,7 +278,7 @@ Package.onUse(function(api) { api.export('openRoom', 'client'); // exports - api.mainModule('server/lib/index.js', 'server'); + api.mainModule('server/index.js', 'server'); api.mainModule('client/lib/index.js', 'client'); api.imply('tap:i18n'); diff --git a/server/methods/getUsernameSuggestion.js b/packages/rocketchat-lib/server/functions/getUsernameSuggestion.js similarity index 69% rename from server/methods/getUsernameSuggestion.js rename to packages/rocketchat-lib/server/functions/getUsernameSuggestion.js index 076bd08e0523..30958d22743b 100644 --- a/server/methods/getUsernameSuggestion.js +++ b/packages/rocketchat-lib/server/functions/getUsernameSuggestion.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { slugify } from 'meteor/yasaricli:slugify'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; function slug(text) { return slugify(text, '.').replace(/[^0-9a-z-_.]/g, ''); @@ -14,13 +16,13 @@ function usernameIsAvaliable(username) { return false; } - return !RocketChat.models.Users.findOneByUsername(username); + return !Users.findOneByUsername(username); } -const name = (username) => (RocketChat.settings.get('UTF8_Names_Slugify') ? slug(username) : username); +const name = (username) => (settings.get('UTF8_Names_Slugify') ? slug(username) : username); -function generateSuggestion(user) { +export function generateUsernameSuggestion(user) { let usernames = []; if (Meteor.settings.public.sandstorm) { @@ -67,9 +69,9 @@ function generateSuggestion(user) { } } - usernames.push(RocketChat.settings.get('Accounts_DefaultUsernamePrefixSuggestion')); + usernames.push(settings.get('Accounts_DefaultUsernamePrefixSuggestion')); - let index = RocketChat.models.Users.find({ username: new RegExp(`^${ usernames[0] }-[0-9]+`) }).count(); + let index = Users.find({ username: new RegExp(`^${ usernames[0] }-[0-9]+`) }).count(); const username = ''; while (!username) { if (usernameIsAvaliable(`${ usernames[0] }-${ index }`)) { @@ -79,18 +81,4 @@ function generateSuggestion(user) { } } -RocketChat.generateUsernameSuggestion = generateSuggestion; - -Meteor.methods({ - getUsernameSuggestion() { - if (!Meteor.userId()) { - throw new Meteor.Error('error-invalid-user', 'Invalid user', { - method: 'getUsernameSuggestion', - }); - } - - const user = Meteor.user(); - - return generateSuggestion(user); - }, -}); +RocketChat.generateUsernameSuggestion = generateUsernameSuggestion; diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js index 11eac02244a3..de83cbb57af4 100644 --- a/packages/rocketchat-lib/server/functions/index.js +++ b/packages/rocketchat-lib/server/functions/index.js @@ -23,3 +23,4 @@ export { setUsername } from './setUsername'; export { unarchiveRoom } from './unarchiveRoom'; export { updateMessage } from './updateMessage'; export { validateCustomFields } from './validateCustomFields'; +export { generateUsernameSuggestion } from './getUsernameSuggestion'; diff --git a/packages/rocketchat-lib/server/index.js b/packages/rocketchat-lib/server/index.js new file mode 100644 index 000000000000..d43727359c92 --- /dev/null +++ b/packages/rocketchat-lib/server/index.js @@ -0,0 +1,2 @@ +export * from './lib'; +export * from './functions'; diff --git a/packages/rocketchat-lib/server/methods/getUsernameSuggestion.js b/packages/rocketchat-lib/server/methods/getUsernameSuggestion.js new file mode 100644 index 000000000000..1e736489136c --- /dev/null +++ b/packages/rocketchat-lib/server/methods/getUsernameSuggestion.js @@ -0,0 +1,16 @@ +import { Meteor } from 'meteor/meteor'; +import { generateUsernameSuggestion } from '../functions'; + +Meteor.methods({ + getUsernameSuggestion() { + if (!Meteor.userId()) { + throw new Meteor.Error('error-invalid-user', 'Invalid user', { + method: 'getUsernameSuggestion', + }); + } + + const user = Meteor.user(); + + return generateUsernameSuggestion(user); + }, +}); diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index 524abe1f5db4..54b5dfc3289c 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -16,6 +16,7 @@ import Roles from './models/Roles'; import CustomSounds from './models/CustomSounds'; import Integrations from './models/Integrations'; import IntegrationHistory from './models/IntegrationHistory'; +import CredentialTokens from './models/CredentialTokens'; export { Base, @@ -36,4 +37,5 @@ export { CustomSounds, Integrations, IntegrationHistory, + CredentialTokens, }; diff --git a/packages/rocketchat-cas/server/models/CredentialTokens.js b/packages/rocketchat-models/server/models/CredentialTokens.js similarity index 78% rename from packages/rocketchat-cas/server/models/CredentialTokens.js rename to packages/rocketchat-models/server/models/CredentialTokens.js index a484eb978b39..7659538e032e 100644 --- a/packages/rocketchat-cas/server/models/CredentialTokens.js +++ b/packages/rocketchat-models/server/models/CredentialTokens.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.CredentialTokens = new class extends RocketChat.models._Base { +export class CredentialTokens extends Base { constructor() { super('credential_tokens'); @@ -27,4 +27,6 @@ RocketChat.models.CredentialTokens = new class extends RocketChat.models._Base { return this.findOne(query); } -}; +} + +export default new CredentialTokens(); From b3906faa32e6cf99fac0e2a0fac6f0ac101897e8 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 18:01:22 -0200 Subject: [PATCH 13/33] Remove dependency of RC namespace in rc-theme (#13234) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme --- packages/rocketchat_theme/package.js | 2 +- packages/rocketchat_theme/server/server.js | 101 +++++++++--------- packages/rocketchat_theme/server/variables.js | 15 +-- 3 files changed, 60 insertions(+), 58 deletions(-) diff --git a/packages/rocketchat_theme/package.js b/packages/rocketchat_theme/package.js index 4509cc69be44..ebad7deda55f 100644 --- a/packages/rocketchat_theme/package.js +++ b/packages/rocketchat_theme/package.js @@ -10,7 +10,7 @@ Package.onUse(function(api) { 'less', 'webapp', 'webapp-hashing', - 'rocketchat:lib', + 'rocketchat:settings', 'rocketchat:logger', 'rocketchat:assets', 'templating', diff --git a/packages/rocketchat_theme/server/server.js b/packages/rocketchat_theme/server/server.js index 977d9cfb2023..a13dc5f07480 100644 --- a/packages/rocketchat_theme/server/server.js +++ b/packages/rocketchat_theme/server/server.js @@ -1,6 +1,6 @@ import { WebApp } from 'meteor/webapp'; import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { Logger } from 'meteor/rocketchat:logger'; import { WebAppHashing } from 'meteor/webapp-hashing'; import _ from 'underscore'; @@ -16,54 +16,15 @@ const logger = new Logger('rocketchat:theme', { }, }); -WebApp.rawConnectHandlers.use(function(req, res, next) { - const path = req.url.split('?')[0]; - const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; - if (path === `${ prefix }/theme.css`) { - const css = RocketChat.theme.getCss(); - const hash = crypto.createHash('sha1').update(css).digest('hex'); - res.setHeader('Content-Type', 'text/css; charset=UTF-8'); - res.setHeader('ETag', `"${ hash }"`); - res.write(css); - return res.end(); - } else { - return next(); - } -}); - -const { calculateClientHash } = WebAppHashing; - -WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) { - const css = RocketChat.theme.getCss(); - if (css.trim() !== '') { - const hash = crypto.createHash('sha1').update(css).digest('hex'); - let themeManifestItem = _.find(manifest, function(item) { - return item.path === 'app/theme.css'; - }); - if (themeManifestItem == null) { - themeManifestItem = {}; - manifest.push(themeManifestItem); - } - themeManifestItem.path = 'app/theme.css'; - themeManifestItem.type = 'css'; - themeManifestItem.cacheable = true; - themeManifestItem.where = 'client'; - themeManifestItem.url = `/theme.css?${ hash }`; - themeManifestItem.size = css.length; - themeManifestItem.hash = hash; - } - return calculateClientHash.call(this, manifest, includeFilter, runtimeConfigOverride); -}; - -RocketChat.theme = new class { +export const theme = new class { constructor() { this.variables = {}; this.packageCallbacks = []; this.files = ['server/colors.less']; this.customCSS = ''; - RocketChat.settings.add('css', ''); - RocketChat.settings.addGroup('Layout'); - RocketChat.settings.onload('css', Meteor.bindEnvironment((key, value, initialLoad) => { + settings.add('css', ''); + settings.addGroup('Layout'); + settings.onload('css', Meteor.bindEnvironment((key, value, initialLoad) => { if (!initialLoad) { Meteor.startup(function() { process.emit('message', { @@ -74,8 +35,8 @@ RocketChat.theme = new class { })); this.compileDelayed = _.debounce(Meteor.bindEnvironment(this.compile.bind(this)), 100); Meteor.startup(() => { - RocketChat.settings.onAfterInitialLoad(() => { - RocketChat.settings.get(/^theme-./, Meteor.bindEnvironment((key, value) => { + settings.onAfterInitialLoad(() => { + settings.get(/^theme-./, Meteor.bindEnvironment((key, value) => { if (key === 'theme-custom-css' && value != null) { this.customCSS = value; } else { @@ -110,7 +71,7 @@ RocketChat.theme = new class { if (err != null) { return console.log(err); } - RocketChat.settings.updateById('css', data.css); + settings.updateById('css', data.css); return Meteor.startup(function() { return Meteor.setTimeout(function() { return process.emit('message', { @@ -131,7 +92,7 @@ RocketChat.theme = new class { section, }; - return RocketChat.settings.add(`theme-color-${ name }`, value, config); + return settings.add(`theme-color-${ name }`, value, config); } addVariable(type, name, value, section, persist = true, editor, allowedTypes, property) { @@ -149,7 +110,7 @@ RocketChat.theme = new class { allowedTypes, property, }; - return RocketChat.settings.add(`theme-${ type }-${ name }`, value, config); + return settings.add(`theme-${ type }-${ name }`, value, config); } } @@ -182,7 +143,47 @@ RocketChat.theme = new class { } getCss() { - return RocketChat.settings.get('css') || ''; + return settings.get('css') || ''; } }; + + +WebApp.rawConnectHandlers.use(function(req, res, next) { + const path = req.url.split('?')[0]; + const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; + if (path === `${ prefix }/theme.css`) { + const css = theme.getCss(); + const hash = crypto.createHash('sha1').update(css).digest('hex'); + res.setHeader('Content-Type', 'text/css; charset=UTF-8'); + res.setHeader('ETag', `"${ hash }"`); + res.write(css); + return res.end(); + } else { + return next(); + } +}); + +const { calculateClientHash } = WebAppHashing; + +WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) { + const css = theme.getCss(); + if (css.trim() !== '') { + const hash = crypto.createHash('sha1').update(css).digest('hex'); + let themeManifestItem = _.find(manifest, function(item) { + return item.path === 'app/theme.css'; + }); + if (themeManifestItem == null) { + themeManifestItem = {}; + manifest.push(themeManifestItem); + } + themeManifestItem.path = 'app/theme.css'; + themeManifestItem.type = 'css'; + themeManifestItem.cacheable = true; + themeManifestItem.where = 'client'; + themeManifestItem.url = `/theme.css?${ hash }`; + themeManifestItem.size = css.length; + themeManifestItem.hash = hash; + } + return calculateClientHash.call(this, manifest, includeFilter, runtimeConfigOverride); +}; diff --git a/packages/rocketchat_theme/server/variables.js b/packages/rocketchat_theme/server/variables.js index 8596dbbb8ea6..0206233a9e36 100644 --- a/packages/rocketchat_theme/server/variables.js +++ b/packages/rocketchat_theme/server/variables.js @@ -1,4 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { theme } from './server'; // TODO: Define registers/getters/setters for packages to work with established // heirarchy of colors instead of making duplicate definitions // TODO: Settings pages to show simple separation of major/minor/addon colors @@ -21,9 +22,9 @@ const colors = [...Assets.getText('client/imports/general/variables.css').match( colors.forEach(([key, color]) => { if (/var/.test(color)) { const [, value] = color.match(/var\(--(.*?)\)/i); - return RocketChat.theme.addPublicColor(key, value, 'Colors', 'expression'); + return theme.addPublicColor(key, value, 'Colors', 'expression'); } - RocketChat.theme.addPublicColor(key, color, 'Colors'); + theme.addPublicColor(key, color, 'Colors'); }); const majorColors = { @@ -58,17 +59,17 @@ const minorColors = { // Bulk-add settings for color scheme Object.keys(majorColors).forEach((key) => { const value = majorColors[key]; - RocketChat.theme.addPublicColor(key, value, 'Old Colors'); + theme.addPublicColor(key, value, 'Old Colors'); }); Object.keys(minorColors).forEach((key) => { const value = minorColors[key]; - RocketChat.theme.addPublicColor(key, value, 'Old Colors (minor)', 'expression'); + theme.addPublicColor(key, value, 'Old Colors (minor)', 'expression'); }); -RocketChat.theme.addPublicFont('body-font-family', '-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen, Ubuntu, Cantarell, \'Helvetica Neue\', \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Meiryo UI\', Arial, sans-serif'); +theme.addPublicFont('body-font-family', '-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen, Ubuntu, Cantarell, \'Helvetica Neue\', \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Meiryo UI\', Arial, sans-serif'); -RocketChat.settings.add('theme-custom-css', '', { +settings.add('theme-custom-css', '', { group: 'Layout', type: 'code', code: 'text/css', From 9bd766a95837ce5825e9e6513a4b4a43bb8b9d03 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 18:21:31 -0200 Subject: [PATCH 14/33] Remove dependency of RC namespace in rc-2fa (#13235) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa --- .../rocketchat-2fa/client/TOTPPassword.js | 2 +- .../rocketchat-2fa/client/accountSecurity.js | 6 +-- packages/rocketchat-2fa/package.js | 6 ++- packages/rocketchat-2fa/server/index.js | 2 - packages/rocketchat-2fa/server/lib/totp.js | 9 ++-- .../rocketchat-2fa/server/loginHandler.js | 10 ++-- .../rocketchat-2fa/server/methods/disable.js | 7 +-- .../rocketchat-2fa/server/methods/enable.js | 9 ++-- .../server/methods/regenerateCodes.js | 9 ++-- .../server/methods/validateTempToken.js | 9 ++-- .../rocketchat-2fa/server/models/users.js | 51 ------------------- .../rocketchat-2fa/server/startup/settings.js | 4 +- .../rocketchat-models/server/models/Users.js | 50 ++++++++++++++++++ 13 files changed, 90 insertions(+), 84 deletions(-) delete mode 100644 packages/rocketchat-2fa/server/models/users.js diff --git a/packages/rocketchat-2fa/client/TOTPPassword.js b/packages/rocketchat-2fa/client/TOTPPassword.js index 7bb15b1fa738..50bb8e31ccb3 100644 --- a/packages/rocketchat-2fa/client/TOTPPassword.js +++ b/packages/rocketchat-2fa/client/TOTPPassword.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { modal } from 'meteor/rocketchat:ui'; +import { modal } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; diff --git a/packages/rocketchat-2fa/client/accountSecurity.js b/packages/rocketchat-2fa/client/accountSecurity.js index b99fb2fc3e49..3a530bd7b2ab 100644 --- a/packages/rocketchat-2fa/client/accountSecurity.js +++ b/packages/rocketchat-2fa/client/accountSecurity.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { modal } from 'meteor/rocketchat:ui'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { modal } from 'meteor/rocketchat:ui-utils'; +import { settings } from 'meteor/rocketchat:settings'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; import qrcode from 'yaqrcode'; @@ -27,7 +27,7 @@ Template.accountSecurity.helpers({ return Template.instance().state.get() === 'registering'; }, isAllowed() { - return RocketChat.settings.get('Accounts_TwoFactorAuthentication_Enabled'); + return settings.get('Accounts_TwoFactorAuthentication_Enabled'); }, codesRemaining() { if (Template.instance().codesRemaining.get()) { diff --git a/packages/rocketchat-2fa/package.js b/packages/rocketchat-2fa/package.js index 71f3cf76599f..889045bb342c 100644 --- a/packages/rocketchat-2fa/package.js +++ b/packages/rocketchat-2fa/package.js @@ -11,11 +11,13 @@ Package.onUse(function(api) { 'accounts-base', 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:settings', 'sha', 'random', - 'rocketchat:ui', + 'rocketchat:ui-utils', 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:callbacks', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-2fa/server/index.js b/packages/rocketchat-2fa/server/index.js index 2f088d337986..e5d5ab3fc445 100644 --- a/packages/rocketchat-2fa/server/index.js +++ b/packages/rocketchat-2fa/server/index.js @@ -1,6 +1,4 @@ import './startup/settings'; -import './lib/totp'; -import './models/users'; import './methods/checkCodesRemaining'; import './methods/disable'; import './methods/enable'; diff --git a/packages/rocketchat-2fa/server/lib/totp.js b/packages/rocketchat-2fa/server/lib/totp.js index 8d794d9ec359..2a1273c74ae8 100644 --- a/packages/rocketchat-2fa/server/lib/totp.js +++ b/packages/rocketchat-2fa/server/lib/totp.js @@ -1,9 +1,10 @@ import { SHA256 } from 'meteor/sha'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import speakeasy from 'speakeasy'; -RocketChat.TOTP = { +export const TOTP = { generateSecret() { return speakeasy.generateSecret(); }, @@ -25,14 +26,14 @@ RocketChat.TOTP = { backupTokens.splice(usedCode, 1); // mark the code as used (remove it from the list) - RocketChat.models.Users.update2FABackupCodesByUserId(userId, backupTokens); + Users.update2FABackupCodesByUserId(userId, backupTokens); return true; } return false; } - const maxDelta = RocketChat.settings.get('Accounts_TwoFactorAuthentication_MaxDelta'); + const maxDelta = settings.get('Accounts_TwoFactorAuthentication_MaxDelta'); if (maxDelta) { const verifiedDelta = speakeasy.totp.verifyDelta({ secret, diff --git a/packages/rocketchat-2fa/server/loginHandler.js b/packages/rocketchat-2fa/server/loginHandler.js index 1060d218cb7a..31b9b37516c8 100644 --- a/packages/rocketchat-2fa/server/loginHandler.js +++ b/packages/rocketchat-2fa/server/loginHandler.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { TOTP } from './lib/totp'; Accounts.registerLoginHandler('totp', function(options) { if (!options.totp || !options.totp.code) { @@ -10,8 +12,8 @@ Accounts.registerLoginHandler('totp', function(options) { return Accounts._runLoginHandlers(this, options.totp.login); }); -RocketChat.callbacks.add('onValidateLogin', (login) => { - if (!RocketChat.settings.get('Accounts_TwoFactorAuthentication_Enabled')) { +callbacks.add('onValidateLogin', (login) => { + if (!settings.get('Accounts_TwoFactorAuthentication_Enabled')) { return; } @@ -22,7 +24,7 @@ RocketChat.callbacks.add('onValidateLogin', (login) => { throw new Meteor.Error('totp-required', 'TOTP Required'); } - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: login.user.services.totp.secret, token: totp.code, userId: login.user._id, diff --git a/packages/rocketchat-2fa/server/methods/disable.js b/packages/rocketchat-2fa/server/methods/disable.js index ac68d9ddc5eb..ebec075d936e 100644 --- a/packages/rocketchat-2fa/server/methods/disable.js +++ b/packages/rocketchat-2fa/server/methods/disable.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:disable'(code) { @@ -9,7 +10,7 @@ Meteor.methods({ const user = Meteor.user(); - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: user.services.totp.secret, token: code, userId: Meteor.userId(), @@ -20,6 +21,6 @@ Meteor.methods({ return false; } - return RocketChat.models.Users.disable2FAByUserId(Meteor.userId()); + return Users.disable2FAByUserId(Meteor.userId()); }, }); diff --git a/packages/rocketchat-2fa/server/methods/enable.js b/packages/rocketchat-2fa/server/methods/enable.js index a2b984a4c1f1..4d73afc1ce84 100644 --- a/packages/rocketchat-2fa/server/methods/enable.js +++ b/packages/rocketchat-2fa/server/methods/enable.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:enable'() { @@ -9,13 +10,13 @@ Meteor.methods({ const user = Meteor.user(); - const secret = RocketChat.TOTP.generateSecret(); + const secret = TOTP.generateSecret(); - RocketChat.models.Users.disable2FAAndSetTempSecretByUserId(Meteor.userId(), secret.base32); + Users.disable2FAAndSetTempSecretByUserId(Meteor.userId(), secret.base32); return { secret: secret.base32, - url: RocketChat.TOTP.generateOtpauthURL(secret, user.username), + url: TOTP.generateOtpauthURL(secret, user.username), }; }, }); diff --git a/packages/rocketchat-2fa/server/methods/regenerateCodes.js b/packages/rocketchat-2fa/server/methods/regenerateCodes.js index 750879b8c60b..330b70c4bd57 100644 --- a/packages/rocketchat-2fa/server/methods/regenerateCodes.js +++ b/packages/rocketchat-2fa/server/methods/regenerateCodes.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:regenerateCodes'(userToken) { @@ -13,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('invalid-totp'); } - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: user.services.totp.secret, token: userToken, userId: Meteor.userId(), @@ -21,9 +22,9 @@ Meteor.methods({ }); if (verified) { - const { codes, hashedCodes } = RocketChat.TOTP.generateCodes(); + const { codes, hashedCodes } = TOTP.generateCodes(); - RocketChat.models.Users.update2FABackupCodesByUserId(Meteor.userId(), hashedCodes); + Users.update2FABackupCodesByUserId(Meteor.userId(), hashedCodes); return { codes }; } }, diff --git a/packages/rocketchat-2fa/server/methods/validateTempToken.js b/packages/rocketchat-2fa/server/methods/validateTempToken.js index a224f7b88b03..779b73bd73e7 100644 --- a/packages/rocketchat-2fa/server/methods/validateTempToken.js +++ b/packages/rocketchat-2fa/server/methods/validateTempToken.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { TOTP } from '../lib/totp'; Meteor.methods({ '2fa:validateTempToken'(userToken) { @@ -13,15 +14,15 @@ Meteor.methods({ throw new Meteor.Error('invalid-totp'); } - const verified = RocketChat.TOTP.verify({ + const verified = TOTP.verify({ secret: user.services.totp.tempSecret, token: userToken, }); if (verified) { - const { codes, hashedCodes } = RocketChat.TOTP.generateCodes(); + const { codes, hashedCodes } = TOTP.generateCodes(); - RocketChat.models.Users.enable2FAAndSetSecretAndCodesByUserId(Meteor.userId(), user.services.totp.tempSecret, hashedCodes); + Users.enable2FAAndSetSecretAndCodesByUserId(Meteor.userId(), user.services.totp.tempSecret, hashedCodes); return { codes }; } }, diff --git a/packages/rocketchat-2fa/server/models/users.js b/packages/rocketchat-2fa/server/models/users.js deleted file mode 100644 index 80190c9cc3a1..000000000000 --- a/packages/rocketchat-2fa/server/models/users.js +++ /dev/null @@ -1,51 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Users.disable2FAAndSetTempSecretByUserId = function(userId, tempToken) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp': { - enabled: false, - tempSecret: tempToken, - }, - }, - }); -}; - -RocketChat.models.Users.enable2FAAndSetSecretAndCodesByUserId = function(userId, secret, backupCodes) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp.enabled': true, - 'services.totp.secret': secret, - 'services.totp.hashedBackup': backupCodes, - }, - $unset: { - 'services.totp.tempSecret': 1, - }, - }); -}; - -RocketChat.models.Users.disable2FAByUserId = function(userId) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp': { - enabled: false, - }, - }, - }); -}; - -RocketChat.models.Users.update2FABackupCodesByUserId = function(userId, backupCodes) { - return this.update({ - _id: userId, - }, { - $set: { - 'services.totp.hashedBackup': backupCodes, - }, - }); -}; diff --git a/packages/rocketchat-2fa/server/startup/settings.js b/packages/rocketchat-2fa/server/startup/settings.js index 63d5c6e37b15..18e3550e0b31 100644 --- a/packages/rocketchat-2fa/server/startup/settings.js +++ b/packages/rocketchat-2fa/server/startup/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('Accounts', function() { +settings.addGroup('Accounts', function() { this.section('Two Factor Authentication', function() { this.add('Accounts_TwoFactorAuthentication_Enabled', true, { type: 'boolean', diff --git a/packages/rocketchat-models/server/models/Users.js b/packages/rocketchat-models/server/models/Users.js index f90e64fa4a93..770c4a8ad9f5 100644 --- a/packages/rocketchat-models/server/models/Users.js +++ b/packages/rocketchat-models/server/models/Users.js @@ -52,6 +52,56 @@ export class Users extends Base { }; } + disable2FAAndSetTempSecretByUserId(userId, tempToken) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp': { + enabled: false, + tempSecret: tempToken, + }, + }, + }); + } + + enable2FAAndSetSecretAndCodesByUserId(userId, secret, backupCodes) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp.enabled': true, + 'services.totp.secret': secret, + 'services.totp.hashedBackup': backupCodes, + }, + $unset: { + 'services.totp.tempSecret': 1, + }, + }); + } + + disable2FAByUserId(userId) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp': { + enabled: false, + }, + }, + }); + } + + update2FABackupCodesByUserId(userId, backupCodes) { + return this.update({ + _id: userId, + }, { + $set: { + 'services.totp.hashedBackup': backupCodes, + }, + }); + } + findByIdsWithPublicE2EKey(ids, options) { const query = { _id: { From 86ae7c846237a73e32005098cae2e820964f8786 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 23 Jan 2019 18:49:09 -0200 Subject: [PATCH 15/33] Remove dependency of RC namespace in rc-action-links (#13236) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace --- .../rocketchat-action-links/both/lib/actionLinks.js | 10 +++++----- packages/rocketchat-action-links/client/index.js | 6 +++++- packages/rocketchat-action-links/client/init.js | 9 +++++---- .../rocketchat-action-links/client/lib/actionLinks.js | 11 ++++++----- packages/rocketchat-action-links/package.js | 5 +++-- .../server/actionLinkHandler.js | 6 +++--- packages/rocketchat-action-links/server/index.js | 6 +++++- packages/rocketchat-lib/lib/actionLinks.js | 3 +++ packages/rocketchat-lib/package.js | 2 ++ packages/rocketchat_theme/package.js | 1 - 10 files changed, 37 insertions(+), 22 deletions(-) create mode 100644 packages/rocketchat-lib/lib/actionLinks.js diff --git a/packages/rocketchat-action-links/both/lib/actionLinks.js b/packages/rocketchat-action-links/both/lib/actionLinks.js index 1ca27418a05a..0cba301c0795 100644 --- a/packages/rocketchat-action-links/both/lib/actionLinks.js +++ b/packages/rocketchat-action-links/both/lib/actionLinks.js @@ -1,11 +1,11 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, Subscriptions } from 'meteor/rocketchat:models'; // Action Links namespace creation. -RocketChat.actionLinks = { +export const actionLinks = { actions: {}, register(name, funct) { - RocketChat.actionLinks.actions[name] = funct; + actionLinks.actions[name] = funct; }, getMessage(name, messageId) { const userId = Meteor.userId(); @@ -13,12 +13,12 @@ RocketChat.actionLinks = { throw new Meteor.Error('error-invalid-user', 'Invalid user', { function: 'actionLinks.getMessage' }); } - const message = RocketChat.models.Messages.findOne({ _id: messageId }); + const message = Messages.findOne({ _id: messageId }); if (!message) { throw new Meteor.Error('error-invalid-message', 'Invalid message', { function: 'actionLinks.getMessage' }); } - const subscription = RocketChat.models.Subscriptions.findOne({ + const subscription = Subscriptions.findOne({ rid: message.rid, 'u._id': userId, }); diff --git a/packages/rocketchat-action-links/client/index.js b/packages/rocketchat-action-links/client/index.js index 940c2db77dcc..f49166a5c811 100644 --- a/packages/rocketchat-action-links/client/index.js +++ b/packages/rocketchat-action-links/client/index.js @@ -1,3 +1,7 @@ -import '../both/lib/actionLinks'; +import { actionLinks } from '../both/lib/actionLinks'; import './lib/actionLinks'; import './init'; + +export { + actionLinks, +}; diff --git a/packages/rocketchat-action-links/client/init.js b/packages/rocketchat-action-links/client/init.js index 67332f38482b..050eb95f797d 100644 --- a/packages/rocketchat-action-links/client/init.js +++ b/packages/rocketchat-action-links/client/init.js @@ -1,7 +1,8 @@ import { Blaze } from 'meteor/blaze'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { fireGlobalEvent } from 'meteor/rocketchat:ui'; +import { handleError } from 'meteor/rocketchat:utils'; +import { fireGlobalEvent, Layout } from 'meteor/rocketchat:ui-utils'; +import { actionLinks } from '../both/lib/actionLinks'; Template.room.events({ 'click .action-link'(event, instance) { @@ -10,7 +11,7 @@ Template.room.events({ const data = Blaze.getData(event.currentTarget); - if (RocketChat.Layout.isEmbedded()) { + if (Layout.isEmbedded()) { return fireGlobalEvent('click-action-link', { actionlink: $(event.currentTarget).data('actionlink'), value: data._arguments[1]._id, @@ -19,7 +20,7 @@ Template.room.events({ } if (data && data._arguments && data._arguments[1] && data._arguments[1]._id) { - RocketChat.actionLinks.run($(event.currentTarget).data('actionlink'), data._arguments[1]._id, instance, (err) => { + actionLinks.run($(event.currentTarget).data('actionlink'), data._arguments[1]._id, instance, (err) => { if (err) { handleError(err); } diff --git a/packages/rocketchat-action-links/client/lib/actionLinks.js b/packages/rocketchat-action-links/client/lib/actionLinks.js index fdda77593980..a3379e61ce24 100644 --- a/packages/rocketchat-action-links/client/lib/actionLinks.js +++ b/packages/rocketchat-action-links/client/lib/actionLinks.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; +import { handleError } from 'meteor/rocketchat:utils'; +import { actionLinks } from '../../both/lib/actionLinks'; // Action Links Handler. This method will be called off the client. -RocketChat.actionLinks.run = (name, messageId, instance) => { - const message = RocketChat.actionLinks.getMessage(name, messageId); +actionLinks.run = (name, messageId, instance) => { + const message = actionLinks.getMessage(name, messageId); const actionLink = message.actionLinks[name]; let ranClient = false; - if (RocketChat.actionLinks && RocketChat.actionLinks.actions && RocketChat.actionLinks.actions[actionLink.method_id]) { + if (actionLinks && actionLinks.actions && actionLinks.actions[actionLink.method_id]) { // run just on client side - RocketChat.actionLinks.actions[actionLink.method_id](message, actionLink.params, instance); + actionLinks.actions[actionLink.method_id](message, actionLink.params, instance); ranClient = true; } diff --git a/packages/rocketchat-action-links/package.js b/packages/rocketchat-action-links/package.js index 87870adc7f60..2cc5b9f6a6ee 100644 --- a/packages/rocketchat-action-links/package.js +++ b/packages/rocketchat-action-links/package.js @@ -9,9 +9,10 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:ui-utils', + 'rocketchat:utils', 'rocketchat:theme', - 'rocketchat:ui', + 'rocketchat:models', ]); api.addFiles('client/stylesheets/actionLinks.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-action-links/server/actionLinkHandler.js b/packages/rocketchat-action-links/server/actionLinkHandler.js index 7fd102c29436..8940e1c8150d 100644 --- a/packages/rocketchat-action-links/server/actionLinkHandler.js +++ b/packages/rocketchat-action-links/server/actionLinkHandler.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { actionLinks } from '../both/lib/actionLinks'; // Action Links Handler. This method will be called off the client. Meteor.methods({ @@ -8,10 +8,10 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'actionLinkHandler' }); } - const message = RocketChat.actionLinks.getMessage(name, messageId); + const message = actionLinks.getMessage(name, messageId); const actionLink = message.actionLinks[name]; - RocketChat.actionLinks.actions[actionLink.method_id](message, actionLink.params); + actionLinks.actions[actionLink.method_id](message, actionLink.params); }, }); diff --git a/packages/rocketchat-action-links/server/index.js b/packages/rocketchat-action-links/server/index.js index 8db8549e10d7..b1c484f79888 100644 --- a/packages/rocketchat-action-links/server/index.js +++ b/packages/rocketchat-action-links/server/index.js @@ -1,2 +1,6 @@ -import '../both/lib/actionLinks'; +import { actionLinks } from '../both/lib/actionLinks'; import './actionLinkHandler'; + +export { + actionLinks, +}; diff --git a/packages/rocketchat-lib/lib/actionLinks.js b/packages/rocketchat-lib/lib/actionLinks.js new file mode 100644 index 000000000000..33baaddc399b --- /dev/null +++ b/packages/rocketchat-lib/lib/actionLinks.js @@ -0,0 +1,3 @@ +import { actionLinks } from 'meteor/rocketchat:action-links'; + +RocketChat.actionLinks = actionLinks; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 8639b3ad7d6d..3083ad613a15 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -52,6 +52,7 @@ Package.onUse(function(api) { api.use('rocketchat:file'); api.use('rocketchat:file-upload'); api.use('rocketchat:push-notifications'); + api.use('rocketchat:action-links'); api.use('templating', 'client'); api.use('kadira:flow-router'); @@ -94,6 +95,7 @@ Package.onUse(function(api) { api.addFiles('lib/templateVarHandler.js'); api.addFiles('lib/info.js'); api.addFiles('lib/authorization.js'); + api.addFiles('lib/actionLinks.js'); api.addFiles('lib/getUserNotificationPreference.js'); api.addFiles('lib/getUserPreference.js'); diff --git a/packages/rocketchat_theme/package.js b/packages/rocketchat_theme/package.js index ebad7deda55f..4c895fa85ab2 100644 --- a/packages/rocketchat_theme/package.js +++ b/packages/rocketchat_theme/package.js @@ -12,7 +12,6 @@ Package.onUse(function(api) { 'webapp-hashing', 'rocketchat:settings', 'rocketchat:logger', - 'rocketchat:assets', 'templating', 'juliancwirko:postcss', ]); From ed81de853c650c52ef7c3c9551183ac3e408163f Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 14:10:52 -0200 Subject: [PATCH 16/33] Remove dependency of RC namespace in rc-analytics and rc-assets (#13237) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Rename Assets variable to avoid conflicts * Fix rename Assets --- .../rocketchat-analytics/client/loadScript.js | 16 +-- .../client/trackEvents.js | 101 +++++++++--------- packages/rocketchat-analytics/package.js | 4 +- .../rocketchat-analytics/server/settings.js | 4 +- packages/rocketchat-assets/package.js | 5 +- packages/rocketchat-assets/server/assets.js | 57 +++++----- packages/rocketchat-assets/server/index.js | 2 +- packages/rocketchat-lib/package.js | 2 + packages/rocketchat-lib/server/lib/Assets.js | 3 + 9 files changed, 103 insertions(+), 91 deletions(-) create mode 100644 packages/rocketchat-lib/server/lib/Assets.js diff --git a/packages/rocketchat-analytics/client/loadScript.js b/packages/rocketchat-analytics/client/loadScript.js index 19c7f95b8413..1a067627406c 100644 --- a/packages/rocketchat-analytics/client/loadScript.js +++ b/packages/rocketchat-analytics/client/loadScript.js @@ -1,17 +1,17 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.body.onRendered(() => { Tracker.autorun((c) => { - const piwikUrl = RocketChat.settings.get('PiwikAnalytics_enabled') && RocketChat.settings.get('PiwikAnalytics_url'); - const piwikSiteId = piwikUrl && RocketChat.settings.get('PiwikAnalytics_siteId'); - const piwikPrependDomain = piwikUrl && RocketChat.settings.get('PiwikAnalytics_prependDomain'); - const piwikCookieDomain = piwikUrl && RocketChat.settings.get('PiwikAnalytics_cookieDomain'); - const piwikDomains = piwikUrl && RocketChat.settings.get('PiwikAnalytics_domains'); - const piwikAdditionalTracker = piwikUrl && RocketChat.settings.get('PiwikAdditionalTrackers'); - const googleId = RocketChat.settings.get('GoogleAnalytics_enabled') && RocketChat.settings.get('GoogleAnalytics_ID'); + const piwikUrl = settings.get('PiwikAnalytics_enabled') && settings.get('PiwikAnalytics_url'); + const piwikSiteId = piwikUrl && settings.get('PiwikAnalytics_siteId'); + const piwikPrependDomain = piwikUrl && settings.get('PiwikAnalytics_prependDomain'); + const piwikCookieDomain = piwikUrl && settings.get('PiwikAnalytics_cookieDomain'); + const piwikDomains = piwikUrl && settings.get('PiwikAnalytics_domains'); + const piwikAdditionalTracker = piwikUrl && settings.get('PiwikAdditionalTrackers'); + const googleId = settings.get('GoogleAnalytics_enabled') && settings.get('GoogleAnalytics_ID'); if (piwikSiteId || googleId) { c.stop(); diff --git a/packages/rocketchat-analytics/client/trackEvents.js b/packages/rocketchat-analytics/client/trackEvents.js index dedeb8b1dd9c..6e738cffaf99 100644 --- a/packages/rocketchat-analytics/client/trackEvents.js +++ b/packages/rocketchat-analytics/client/trackEvents.js @@ -1,7 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { FlowRouter } from 'meteor/kadira:flow-router'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatRoom } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { ChatRoom } from 'meteor/rocketchat:models'; import { Tracker } from 'meteor/tracker'; function trackEvent(category, action, label) { @@ -29,60 +30,60 @@ if (!window._paq || window.ga) { }]); // Login page has manual switches - RocketChat.callbacks.add('loginPageStateChange', (state) => { + callbacks.add('loginPageStateChange', (state) => { trackEvent('Navigation', 'Login Page State Change', state); - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-login-state-change'); + }, callbacks.priority.MEDIUM, 'analytics-login-state-change'); // Messsages - RocketChat.callbacks.add('afterSaveMessage', (message) => { - if ((window._paq || window.ga) && RocketChat.settings.get('Analytics_features_messages')) { + callbacks.add('afterSaveMessage', (message) => { + if ((window._paq || window.ga) && settings.get('Analytics_features_messages')) { const room = ChatRoom.findOne({ _id: message.rid }); trackEvent('Message', 'Send', `${ room.name } (${ room._id })`); } }, 2000, 'trackEvents'); // Rooms - RocketChat.callbacks.add('afterCreateChannel', (owner, room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('afterCreateChannel', (owner, room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Create', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-after-create-channel'); + }, callbacks.priority.MEDIUM, 'analytics-after-create-channel'); - RocketChat.callbacks.add('roomNameChanged', (room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('roomNameChanged', (room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Changed Name', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-name-changed'); + }, callbacks.priority.MEDIUM, 'analytics-room-name-changed'); - RocketChat.callbacks.add('roomTopicChanged', (room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('roomTopicChanged', (room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Changed Topic', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-topic-changed'); + }, callbacks.priority.MEDIUM, 'analytics-room-topic-changed'); - RocketChat.callbacks.add('roomAnnouncementChanged', (room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('roomAnnouncementChanged', (room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Changed Announcement', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-announcement-changed'); + }, callbacks.priority.MEDIUM, 'analytics-room-announcement-changed'); - RocketChat.callbacks.add('roomTypeChanged', (room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('roomTypeChanged', (room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Changed Room Type', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-type-changed'); + }, callbacks.priority.MEDIUM, 'analytics-room-type-changed'); - RocketChat.callbacks.add('archiveRoom', (room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('archiveRoom', (room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Archived', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-archive-room'); + }, callbacks.priority.MEDIUM, 'analytics-archive-room'); - RocketChat.callbacks.add('unarchiveRoom', (room) => { - if (RocketChat.settings.get('Analytics_features_rooms')) { + callbacks.add('unarchiveRoom', (room) => { + if (settings.get('Analytics_features_rooms')) { trackEvent('Room', 'Unarchived', `${ room.name } (${ room._id })`); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-unarchive-room'); + }, callbacks.priority.MEDIUM, 'analytics-unarchive-room'); // Users // Track logins and associate user ids with piwik @@ -92,12 +93,12 @@ if (!window._paq || window.ga) { Tracker.autorun(() => { const newUserId = Meteor.userId(); if (oldUserId === null && newUserId) { - if (window._paq && RocketChat.settings.get('Analytics_features_users')) { + if (window._paq && settings.get('Analytics_features_users')) { trackEvent('User', 'Login', newUserId); window._paq.push(['setUserId', newUserId]); } } else if (newUserId === null && oldUserId) { - if (window._paq && RocketChat.settings.get('Analytics_features_users')) { + if (window._paq && settings.get('Analytics_features_users')) { trackEvent('User', 'Logout', oldUserId); } } @@ -105,45 +106,45 @@ if (!window._paq || window.ga) { }); })(); - RocketChat.callbacks.add('userRegistered', () => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('userRegistered', () => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Registered'); } - }, RocketChat.callbacks.priority.MEDIUM, 'piwik-user-resitered'); + }, callbacks.priority.MEDIUM, 'piwik-user-resitered'); - RocketChat.callbacks.add('usernameSet', () => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('usernameSet', () => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Username Set'); } - }, RocketChat.callbacks.priority.MEDIUM, 'piweik-username-set'); + }, callbacks.priority.MEDIUM, 'piweik-username-set'); - RocketChat.callbacks.add('userPasswordReset', () => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('userPasswordReset', () => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Reset Password'); } - }, RocketChat.callbacks.priority.MEDIUM, 'piwik-user-password-reset'); + }, callbacks.priority.MEDIUM, 'piwik-user-password-reset'); - RocketChat.callbacks.add('userConfirmationEmailRequested', () => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('userConfirmationEmailRequested', () => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Confirmation Email Requested'); } - }, RocketChat.callbacks.priority.MEDIUM, 'piwik-user-confirmation-email-requested'); + }, callbacks.priority.MEDIUM, 'piwik-user-confirmation-email-requested'); - RocketChat.callbacks.add('userForgotPasswordEmailRequested', () => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('userForgotPasswordEmailRequested', () => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Forgot Password Email Requested'); } - }, RocketChat.callbacks.priority.MEDIUM, 'piwik-user-forgot-password-email-requested'); + }, callbacks.priority.MEDIUM, 'piwik-user-forgot-password-email-requested'); - RocketChat.callbacks.add('userStatusManuallySet', (status) => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('userStatusManuallySet', (status) => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Status Manually Changed', status); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-user-status-manually-set'); + }, callbacks.priority.MEDIUM, 'analytics-user-status-manually-set'); - RocketChat.callbacks.add('userAvatarSet', (service) => { - if (RocketChat.settings.get('Analytics_features_users')) { + callbacks.add('userAvatarSet', (service) => { + if (settings.get('Analytics_features_users')) { trackEvent('User', 'Avatar Changed', service); } - }, RocketChat.callbacks.priority.MEDIUM, 'analytics-user-avatar-set'); + }, callbacks.priority.MEDIUM, 'analytics-user-avatar-set'); } diff --git a/packages/rocketchat-analytics/package.js b/packages/rocketchat-analytics/package.js index 3c5f1e62a65e..0f1411bc7815 100644 --- a/packages/rocketchat-analytics/package.js +++ b/packages/rocketchat-analytics/package.js @@ -10,7 +10,9 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:settings', 'tracker', ]); api.use([ diff --git a/packages/rocketchat-analytics/server/settings.js b/packages/rocketchat-analytics/server/settings.js index d37d2a561497..7d03ac9d3312 100644 --- a/packages/rocketchat-analytics/server/settings.js +++ b/packages/rocketchat-analytics/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('Analytics', function addSettings() { +settings.addGroup('Analytics', function addSettings() { this.section('Piwik', function() { const enableQuery = { _id: 'PiwikAnalytics_enabled', value: true }; this.add('PiwikAnalytics_enabled', false, { diff --git a/packages/rocketchat-assets/package.js b/packages/rocketchat-assets/package.js index 79b76ed1c1c8..ab7681c3ad2b 100644 --- a/packages/rocketchat-assets/package.js +++ b/packages/rocketchat-assets/package.js @@ -10,7 +10,10 @@ Package.onUse(function(api) { 'ecmascript', 'webapp', 'rocketchat:file', - 'rocketchat:lib', + 'rocketchat:authorization', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:utils', 'webapp-hashing', ]); diff --git a/packages/rocketchat-assets/server/assets.js b/packages/rocketchat-assets/server/assets.js index 7f41d6624b2d..46825f7e46d2 100644 --- a/packages/rocketchat-assets/server/assets.js +++ b/packages/rocketchat-assets/server/assets.js @@ -1,6 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings } from 'meteor/rocketchat:models'; +import { getURL } from 'meteor/rocketchat:utils'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import { RocketChatFile } from 'meteor/rocketchat:file'; import { WebAppHashing } from 'meteor/webapp-hashing'; import { WebAppInternals } from 'meteor/webapp'; @@ -16,8 +19,6 @@ const RocketChatAssetsInstance = new RocketChatFile.GridFS({ name: 'assets', }); -this.RocketChatAssetsInstance = RocketChatAssetsInstance; - const assets = { logo: { label: 'logo (svg, png, jpg)', @@ -185,7 +186,7 @@ const assets = { }, }; -RocketChat.Assets = new (class { +export const RocketChatAssets = new (class { get mime() { return mime; } @@ -234,8 +235,8 @@ RocketChat.Assets = new (class { defaultUrl: assets[asset].defaultUrl, }; - RocketChat.settings.updateById(key, value); - return RocketChat.Assets.processAsset(key, value); + settings.updateById(key, value); + return RocketChatAssets.processAsset(key, value); }, 200); })); @@ -255,8 +256,8 @@ RocketChat.Assets = new (class { defaultUrl: assets[asset].defaultUrl, }; - RocketChat.settings.updateById(key, value); - RocketChat.Assets.processAsset(key, value); + settings.updateById(key, value); + RocketChatAssets.processAsset(key, value); } refreshClients() { @@ -308,16 +309,16 @@ RocketChat.Assets = new (class { } getURL(assetName, options = { cdn: false, full: true }) { - const asset = RocketChat.settings.get(assetName); + const asset = settings.get(assetName); const url = asset.url || asset.defaultUrl; - return RocketChat.getURL(url, options); + return getURL(url, options); } }); -RocketChat.settings.addGroup('Assets'); +settings.addGroup('Assets'); -RocketChat.settings.add('Assets_SvgFavicon_Enable', true, { +settings.add('Assets_SvgFavicon_Enable', true, { type: 'boolean', group: 'Assets', i18nLabel: 'Enable_Svg_Favicon', @@ -326,7 +327,7 @@ RocketChat.settings.add('Assets_SvgFavicon_Enable', true, { function addAssetToSetting(asset, value) { const key = `Assets_${ asset }`; - RocketChat.settings.add(key, { + settings.add(key, { defaultUrl: value.defaultUrl, }, { type: 'asset', @@ -338,11 +339,11 @@ function addAssetToSetting(asset, value) { wizard: value.wizard, }); - const currentValue = RocketChat.settings.get(key); + const currentValue = settings.get(key); if (typeof currentValue === 'object' && currentValue.defaultUrl !== assets[asset].defaultUrl) { currentValue.defaultUrl = assets[asset].defaultUrl; - RocketChat.settings.updateById(key, currentValue); + settings.updateById(key, currentValue); } } @@ -351,17 +352,17 @@ for (const key of Object.keys(assets)) { addAssetToSetting(key, value); } -RocketChat.models.Settings.find().observe({ +Settings.find().observe({ added(record) { - return RocketChat.Assets.processAsset(record._id, record.value); + return RocketChatAssets.processAsset(record._id, record.value); }, changed(record) { - return RocketChat.Assets.processAsset(record._id, record.value); + return RocketChatAssets.processAsset(record._id, record.value); }, removed(record) { - return RocketChat.Assets.processAsset(record._id, undefined); + return RocketChatAssets.processAsset(record._id, undefined); }, }); @@ -430,15 +431,15 @@ Meteor.methods({ }); } - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'manage-assets'); - if (!hasPermission) { + const _hasPermission = hasPermission(Meteor.userId(), 'manage-assets'); + if (!_hasPermission) { throw new Meteor.Error('error-action-not-allowed', 'Managing assets not allowed', { method: 'refreshClients', action: 'Managing_assets', }); } - return RocketChat.Assets.refreshClients(); + return RocketChatAssets.refreshClients(); }, unsetAsset(asset) { @@ -448,15 +449,15 @@ Meteor.methods({ }); } - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'manage-assets'); - if (!hasPermission) { + const _hasPermission = hasPermission(Meteor.userId(), 'manage-assets'); + if (!_hasPermission) { throw new Meteor.Error('error-action-not-allowed', 'Managing assets not allowed', { method: 'unsetAsset', action: 'Managing_assets', }); } - return RocketChat.Assets.unsetAsset(asset); + return RocketChatAssets.unsetAsset(asset); }, setAsset(binaryContent, contentType, asset) { @@ -466,15 +467,15 @@ Meteor.methods({ }); } - const hasPermission = RocketChat.authz.hasPermission(Meteor.userId(), 'manage-assets'); - if (!hasPermission) { + const _hasPermission = hasPermission(Meteor.userId(), 'manage-assets'); + if (!_hasPermission) { throw new Meteor.Error('error-action-not-allowed', 'Managing assets not allowed', { method: 'setAsset', action: 'Managing_assets', }); } - RocketChat.Assets.setAsset(binaryContent, contentType, asset); + RocketChatAssets.setAsset(binaryContent, contentType, asset); }, }); diff --git a/packages/rocketchat-assets/server/index.js b/packages/rocketchat-assets/server/index.js index 5b8e85c9ffd4..8e5b30ff6b6f 100644 --- a/packages/rocketchat-assets/server/index.js +++ b/packages/rocketchat-assets/server/index.js @@ -1 +1 @@ -import './assets'; +export { RocketChatAssets } from './assets'; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 3083ad613a15..72f5237ddeab 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -53,6 +53,7 @@ Package.onUse(function(api) { api.use('rocketchat:file-upload'); api.use('rocketchat:push-notifications'); api.use('rocketchat:action-links'); + api.use('rocketchat:assets'); api.use('templating', 'client'); api.use('kadira:flow-router'); @@ -152,6 +153,7 @@ Package.onUse(function(api) { api.addFiles('server/lib/passwordPolicy.js', 'server'); api.addFiles('server/lib/migrations.js', 'server'); api.addFiles('server/lib/sandstorm.js', 'server'); + api.addFiles('server/lib/Assets.js', 'server'); // SERVER MODELS api.addFiles('server/models/index.js', 'server'); diff --git a/packages/rocketchat-lib/server/lib/Assets.js b/packages/rocketchat-lib/server/lib/Assets.js new file mode 100644 index 000000000000..3be7174e0a35 --- /dev/null +++ b/packages/rocketchat-lib/server/lib/Assets.js @@ -0,0 +1,3 @@ +import { RocketChatAssets } from 'meteor/rocketchat:assets'; + +RocketChat.Assets = RocketChatAssets; From a5e4f439657b0750d69ceb8fea07a0ff6156f682 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 15:00:51 -0200 Subject: [PATCH 17/33] Remove dependency of RC namespace in rc-markdown, rc-autolinker and rc-autotranslate (#13240) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Fix wrong imports --- .../rocketchat-autolinker/client/client.js | 23 ++++---- packages/rocketchat-autolinker/package.js | 3 +- .../rocketchat-autolinker/server/settings.js | 18 +++--- .../rocketchat-autotranslate/client/index.js | 2 +- .../client/lib/actionButton.js | 22 +++++--- .../client/lib/autotranslate.js | 38 +++++++------ .../client/lib/tabBar.js | 10 ++-- .../client/views/autoTranslateFlexTab.js | 9 ++- packages/rocketchat-autotranslate/package.js | 8 ++- .../server/autotranslate.js | 27 +++++---- .../rocketchat-autotranslate/server/index.js | 2 - .../server/methods/getSupportedLanguages.js | 7 ++- .../server/methods/saveSettings.js | 13 +++-- .../server/methods/translateMessage.js | 9 +-- .../server/models/Messages.js | 19 ------- .../server/models/Subscriptions.js | 50 ----------------- .../server/permissions.js | 8 +-- .../server/settings.js | 6 +- packages/rocketchat-lib/lib/Markdown.js | 3 + packages/rocketchat-lib/package.js | 2 + packages/rocketchat-markdown/client/index.js | 2 +- packages/rocketchat-markdown/lib/markdown.js | 9 ++- .../lib/parser/marked/marked.js | 14 ++--- .../lib/parser/original/markdown.js | 6 +- packages/rocketchat-markdown/package.js | 3 +- packages/rocketchat-markdown/server/index.js | 2 +- .../rocketchat-markdown/server/settings.js | 20 +++---- .../rocketchat-markdown/tests/client.mocks.js | 55 ++++++++++--------- .../server/models/Messages.js | 18 ++++++ .../server/models/Subscriptions.js | 49 +++++++++++++++++ .../rocketchat-ui-message/client/message.js | 3 +- packages/rocketchat-ui-message/package.js | 1 + 32 files changed, 244 insertions(+), 217 deletions(-) delete mode 100644 packages/rocketchat-autotranslate/server/models/Messages.js delete mode 100644 packages/rocketchat-autotranslate/server/models/Subscriptions.js create mode 100644 packages/rocketchat-lib/lib/Markdown.js diff --git a/packages/rocketchat-autolinker/client/client.js b/packages/rocketchat-autolinker/client/client.js index 2afe8f89f7c0..100973b3dfa9 100644 --- a/packages/rocketchat-autolinker/client/client.js +++ b/packages/rocketchat-autolinker/client/client.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import s from 'underscore.string'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; // // AutoLinker is a named function that will replace links on messages @@ -10,22 +11,22 @@ import { RocketChat } from 'meteor/rocketchat:lib'; import Autolinker from 'autolinker'; function AutoLinker(message) { - if (RocketChat.settings.get('AutoLinker') !== true) { + if (settings.get('AutoLinker') !== true) { return message; } if (s.trim(message.html)) { - const regUrls = new RegExp(RocketChat.settings.get('AutoLinker_UrlsRegExp')); + const regUrls = new RegExp(settings.get('AutoLinker_UrlsRegExp')); const autolinker = new Autolinker({ - stripPrefix: RocketChat.settings.get('AutoLinker_StripPrefix'), + stripPrefix: settings.get('AutoLinker_StripPrefix'), urls: { - schemeMatches: RocketChat.settings.get('AutoLinker_Urls_Scheme'), - wwwMatches: RocketChat.settings.get('AutoLinker_Urls_www'), - tldMatches: RocketChat.settings.get('AutoLinker_Urls_TLD'), + schemeMatches: settings.get('AutoLinker_Urls_Scheme'), + wwwMatches: settings.get('AutoLinker_Urls_www'), + tldMatches: settings.get('AutoLinker_Urls_TLD'), }, - email: RocketChat.settings.get('AutoLinker_Email'), - phone: RocketChat.settings.get('AutoLinker_Phone'), + email: settings.get('AutoLinker_Email'), + phone: settings.get('AutoLinker_Phone'), twitter: false, stripTrailingSlash: false, replaceFn(match) { @@ -48,7 +49,7 @@ function AutoLinker(message) { }); let regNonAutoLink = /(```\w*[\n ]?[\s\S]*?```+?)|(`(?:[^`]+)`)/; - if (RocketChat.settings.get('Katex_Enabled')) { + if (settings.get('Katex_Enabled')) { regNonAutoLink = /(```\w*[\n ]?[\s\S]*?```+?)|(`(?:[^`]+)`)|(\\\(\w*[\n ]?[\s\S]*?\\\)+?)/; } @@ -72,4 +73,4 @@ function AutoLinker(message) { return message; } -RocketChat.callbacks.add('renderMessage', AutoLinker, RocketChat.callbacks.priority.LOW, 'autolinker'); +callbacks.add('renderMessage', AutoLinker, callbacks.priority.LOW, 'autolinker'); diff --git a/packages/rocketchat-autolinker/package.js b/packages/rocketchat-autolinker/package.js index d9fc4b56e131..c7db032bd59e 100644 --- a/packages/rocketchat-autolinker/package.js +++ b/packages/rocketchat-autolinker/package.js @@ -8,7 +8,8 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-autolinker/server/settings.js b/packages/rocketchat-autolinker/server/settings.js index 03e94fd74888..eb0f63e0ece2 100644 --- a/packages/rocketchat-autolinker/server/settings.js +++ b/packages/rocketchat-autolinker/server/settings.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { const enableQuery = { @@ -7,13 +7,13 @@ Meteor.startup(function() { value: true, }; - RocketChat.settings.add('AutoLinker', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, i18nLabel: 'Enabled' }); + settings.add('AutoLinker', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, i18nLabel: 'Enabled' }); - RocketChat.settings.add('AutoLinker_StripPrefix', false, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, i18nDescription: 'AutoLinker_StripPrefix_Description', enableQuery }); - RocketChat.settings.add('AutoLinker_Urls_Scheme', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); - RocketChat.settings.add('AutoLinker_Urls_www', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); - RocketChat.settings.add('AutoLinker_Urls_TLD', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); - RocketChat.settings.add('AutoLinker_UrlsRegExp', '(://|www\\.).+', { type: 'string', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); - RocketChat.settings.add('AutoLinker_Email', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); - RocketChat.settings.add('AutoLinker_Phone', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, i18nDescription: 'AutoLinker_Phone_Description', enableQuery }); + settings.add('AutoLinker_StripPrefix', false, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, i18nDescription: 'AutoLinker_StripPrefix_Description', enableQuery }); + settings.add('AutoLinker_Urls_Scheme', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); + settings.add('AutoLinker_Urls_www', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); + settings.add('AutoLinker_Urls_TLD', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); + settings.add('AutoLinker_UrlsRegExp', '(://|www\\.).+', { type: 'string', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); + settings.add('AutoLinker_Email', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, enableQuery }); + settings.add('AutoLinker_Phone', true, { type: 'boolean', group: 'Message', section: 'AutoLinker', public: true, i18nDescription: 'AutoLinker_Phone_Description', enableQuery }); }); diff --git a/packages/rocketchat-autotranslate/client/index.js b/packages/rocketchat-autotranslate/client/index.js index e09da56abcf4..9852ca567287 100644 --- a/packages/rocketchat-autotranslate/client/index.js +++ b/packages/rocketchat-autotranslate/client/index.js @@ -1,5 +1,5 @@ import './lib/actionButton'; -import './lib/autotranslate'; +export { AutoTranslate } from './lib/autotranslate'; import './lib/tabBar'; import './views/autoTranslateFlexTab.html'; import './views/autoTranslateFlexTab'; diff --git a/packages/rocketchat-autotranslate/client/lib/actionButton.js b/packages/rocketchat-autotranslate/client/lib/actionButton.js index f6e727e76f44..e17d2cee3b2b 100644 --- a/packages/rocketchat-autotranslate/client/lib/actionButton.js +++ b/packages/rocketchat-autotranslate/client/lib/actionButton.js @@ -1,11 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { MessageAction } from 'meteor/rocketchat:ui-utils'; +import { Messages } from 'meteor/rocketchat:models'; +import { AutoTranslate } from './autotranslate'; Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('AutoTranslate_Enabled') && RocketChat.authz.hasAtLeastOnePermission(['auto-translate'])) { - RocketChat.MessageAction.addButton({ + if (settings.get('AutoTranslate_Enabled') && hasAtLeastOnePermission(['auto-translate'])) { + MessageAction.addButton({ id: 'toggle-language', icon: 'language', label: 'Toggle_original_translated', @@ -15,15 +19,15 @@ Meteor.startup(function() { ], action() { const message = this._arguments[1]; - const language = RocketChat.AutoTranslate.getLanguage(message.rid); + const language = AutoTranslate.getLanguage(message.rid); if ((!message.translations || !message.translations[language])) { // } && !_.find(message.attachments, attachment => { return attachment.translations && attachment.translations[language]; })) { - RocketChat.AutoTranslate.messageIdsToWait[message._id] = true; - RocketChat.models.Messages.update({ _id: message._id }, { $set: { autoTranslateFetching: true } }); + AutoTranslate.messageIdsToWait[message._id] = true; + Messages.update({ _id: message._id }, { $set: { autoTranslateFetching: true } }); Meteor.call('autoTranslate.translateMessage', message, language); } else if (message.autoTranslateShowInverse) { - RocketChat.models.Messages.update({ _id: message._id }, { $unset: { autoTranslateShowInverse: true } }); + Messages.update({ _id: message._id }, { $unset: { autoTranslateShowInverse: true } }); } else { - RocketChat.models.Messages.update({ _id: message._id }, { $set: { autoTranslateShowInverse: true } }); + Messages.update({ _id: message._id }, { $set: { autoTranslateShowInverse: true } }); } }, condition(message) { @@ -32,7 +36,7 @@ Meteor.startup(function() { order: 90, }); } else { - RocketChat.MessageAction.removeButton('toggle-language'); + MessageAction.removeButton('toggle-language'); } }); }); diff --git a/packages/rocketchat-autotranslate/client/lib/autotranslate.js b/packages/rocketchat-autotranslate/client/lib/autotranslate.js index 0e606971120c..6572d4fc2cc2 100644 --- a/packages/rocketchat-autotranslate/client/lib/autotranslate.js +++ b/packages/rocketchat-autotranslate/client/lib/autotranslate.js @@ -1,16 +1,20 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { CachedCollectionManager } from 'meteor/rocketchat:ui-cached-collection'; import _ from 'underscore'; -RocketChat.AutoTranslate = { +export const AutoTranslate = { messageIdsToWait: {}, supportedLanguages: [], getLanguage(rid) { let subscription = {}; if (rid) { - subscription = RocketChat.models.Subscriptions.findOne({ rid }, { fields: { autoTranslateLanguage: 1 } }); + subscription = Subscriptions.findOne({ rid }, { fields: { autoTranslateLanguage: 1 } }); } const language = (subscription && subscription.autoTranslateLanguage) || Meteor.user().language || window.defaultUserLanguage(); if (language.indexOf('-') !== -1) { @@ -46,9 +50,9 @@ RocketChat.AutoTranslate = { }); Tracker.autorun(() => { - if (RocketChat.settings.get('AutoTranslate_Enabled') && RocketChat.authz.hasAtLeastOnePermission(['auto-translate'])) { - RocketChat.callbacks.add('renderMessage', (message) => { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: message.rid }, { fields: { autoTranslate: 1, autoTranslateLanguage: 1 } }); + if (settings.get('AutoTranslate_Enabled') && hasAtLeastOnePermission(['auto-translate'])) { + callbacks.add('renderMessage', (message) => { + const subscription = Subscriptions.findOne({ rid: message.rid }, { fields: { autoTranslate: 1, autoTranslateLanguage: 1 } }); const autoTranslateLanguage = this.getLanguage(message.rid); if (message.u && message.u._id !== Meteor.userId()) { if (!message.translations) { @@ -68,32 +72,32 @@ RocketChat.AutoTranslate = { message.attachments = this.translateAttachments(message.attachments, autoTranslateLanguage); } return message; - }, RocketChat.callbacks.priority.HIGH - 3, 'autotranslate'); + }, callbacks.priority.HIGH - 3, 'autotranslate'); - RocketChat.callbacks.add('streamMessage', (message) => { + callbacks.add('streamMessage', (message) => { if (message.u && message.u._id !== Meteor.userId()) { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: message.rid }, { fields: { autoTranslate: 1, autoTranslateLanguage: 1 } }); + const subscription = Subscriptions.findOne({ rid: message.rid }, { fields: { autoTranslate: 1, autoTranslateLanguage: 1 } }); const language = this.getLanguage(message.rid); if (subscription && subscription.autoTranslate === true && ((message.msg && (!message.translations || !message.translations[language])))) { // || (message.attachments && !_.find(message.attachments, attachment => { return attachment.translations && attachment.translations[language]; })) - RocketChat.models.Messages.update({ _id: message._id }, { $set: { autoTranslateFetching: true } }); + Messages.update({ _id: message._id }, { $set: { autoTranslateFetching: true } }); } else if (this.messageIdsToWait[message._id] !== undefined && subscription && subscription.autoTranslate !== true) { - RocketChat.models.Messages.update({ _id: message._id }, { $set: { autoTranslateShowInverse: true }, $unset: { autoTranslateFetching: true } }); + Messages.update({ _id: message._id }, { $set: { autoTranslateShowInverse: true }, $unset: { autoTranslateFetching: true } }); delete this.messageIdsToWait[message._id]; } else if (message.autoTranslateFetching === true) { - RocketChat.models.Messages.update({ _id: message._id }, { $unset: { autoTranslateFetching: true } }); + Messages.update({ _id: message._id }, { $unset: { autoTranslateFetching: true } }); } } - }, RocketChat.callbacks.priority.HIGH - 3, 'autotranslate-stream'); + }, callbacks.priority.HIGH - 3, 'autotranslate-stream'); } else { - RocketChat.callbacks.remove('renderMessage', 'autotranslate'); - RocketChat.callbacks.remove('streamMessage', 'autotranslate-stream'); + callbacks.remove('renderMessage', 'autotranslate'); + callbacks.remove('streamMessage', 'autotranslate-stream'); } }); }, }; Meteor.startup(function() { - RocketChat.CachedCollectionManager.onLogin(() => { - RocketChat.AutoTranslate.init(); + CachedCollectionManager.onLogin(() => { + AutoTranslate.init(); }); }); diff --git a/packages/rocketchat-autotranslate/client/lib/tabBar.js b/packages/rocketchat-autotranslate/client/lib/tabBar.js index 170c37c04bb4..74717229d7d9 100644 --- a/packages/rocketchat-autotranslate/client/lib/tabBar.js +++ b/packages/rocketchat-autotranslate/client/lib/tabBar.js @@ -1,11 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('AutoTranslate_Enabled') && RocketChat.authz.hasAtLeastOnePermission(['auto-translate'])) { - RocketChat.TabBar.addButton({ + if (settings.get('AutoTranslate_Enabled') && hasAtLeastOnePermission(['auto-translate'])) { + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'autotranslate', i18nTitle: 'Auto_Translate', @@ -14,7 +16,7 @@ Meteor.startup(function() { order: 20, }); } else { - RocketChat.TabBar.removeButton('autotranslate'); + TabBar.removeButton('autotranslate'); } }); }); diff --git a/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js b/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js index 4ffcc9cae97c..cad53ee61181 100644 --- a/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js +++ b/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js @@ -2,8 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Random } from 'meteor/random'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatSubscription } from 'meteor/rocketchat:ui'; +import { ChatSubscription, Subscriptions, Messages } from 'meteor/rocketchat:models'; import { t } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import toastr from 'toastr'; @@ -98,7 +97,7 @@ Template.autoTranslateFlexTab.onCreated(function() { this.saveSetting = () => { const field = this.editing.get(); - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this.rid, 'u._id': Meteor.userId() }); + const subscription = Subscriptions.findOne({ rid: this.rid, 'u._id': Meteor.userId() }); const previousLanguage = subscription.autoTranslateLanguage; let value; switch (field) { @@ -124,7 +123,7 @@ Template.autoTranslateFlexTab.onCreated(function() { } if (field === 'autoTranslate' && value === '0') { - RocketChat.models.Messages.update(query, { $unset: { autoTranslateShowInverse: 1 } }, { multi: true }); + Messages.update(query, { $unset: { autoTranslateShowInverse: 1 } }, { multi: true }); } const display = field === 'autoTranslate' ? true : subscription && subscription.autoTranslate; @@ -134,7 +133,7 @@ Template.autoTranslateFlexTab.onCreated(function() { query.autoTranslateShowInverse = true; } - RocketChat.models.Messages.update(query, { $set: { random: Random.id() } }, { multi: true }); + Messages.update(query, { $set: { random: Random.id() } }, { multi: true }); this.editing.set(); }); diff --git a/packages/rocketchat-autotranslate/package.js b/packages/rocketchat-autotranslate/package.js index 45a9beeeb0a7..0dd6ba8c7f4c 100644 --- a/packages/rocketchat-autotranslate/package.js +++ b/packages/rocketchat-autotranslate/package.js @@ -9,9 +9,15 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'ddp-rate-limiter', - 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:authorization', + 'rocketchat:ui-utils', + 'rocketchat:ui-cached-collection', 'templating', 'rocketchat:utils', + 'rocketchat:markdown', ]); api.addFiles('client/stylesheets/autotranslate.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-autotranslate/server/autotranslate.js b/packages/rocketchat-autotranslate/server/autotranslate.js index d42da9982d6b..914949644ccf 100644 --- a/packages/rocketchat-autotranslate/server/autotranslate.js +++ b/packages/rocketchat-autotranslate/server/autotranslate.js @@ -1,21 +1,24 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { Markdown } from 'meteor/rocketchat:markdown'; import _ from 'underscore'; import s from 'underscore.string'; class AutoTranslate { constructor() { this.languages = []; - this.enabled = RocketChat.settings.get('AutoTranslate_Enabled'); - this.apiKey = RocketChat.settings.get('AutoTranslate_GoogleAPIKey'); + this.enabled = settings.get('AutoTranslate_Enabled'); + this.apiKey = settings.get('AutoTranslate_GoogleAPIKey'); this.supportedLanguages = {}; - RocketChat.callbacks.add('afterSaveMessage', this.translateMessage.bind(this), RocketChat.callbacks.priority.MEDIUM, 'AutoTranslate'); + callbacks.add('afterSaveMessage', this.translateMessage.bind(this), callbacks.priority.MEDIUM, 'AutoTranslate'); - RocketChat.settings.get('AutoTranslate_Enabled', (key, value) => { + settings.get('AutoTranslate_Enabled', (key, value) => { this.enabled = value; }); - RocketChat.settings.get('AutoTranslate_GoogleAPIKey', (key, value) => { + settings.get('AutoTranslate_GoogleAPIKey', (key, value) => { this.apiKey = value; }); } @@ -48,7 +51,7 @@ class AutoTranslate { tokenizeURLs(message) { let count = message.tokens.length; - const schemes = RocketChat.settings.get('Markdown_SupportSchemesForLink').split(',').join('|'); + const schemes = settings.get('Markdown_SupportSchemesForLink').split(',').join('|'); // Support ![alt text](http://image url) and [text](http://link) message.msg = message.msg.replace(new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${ schemes }):\\/\\/[^\\)]+\\))`, 'gm'), function(match, pre, text, post) { @@ -91,7 +94,7 @@ class AutoTranslate { let count = message.tokens.length; message.html = message.msg; - message = RocketChat.Markdown.parseMessageNotEscaped(message); + message = Markdown.parseMessageNotEscaped(message); message.msg = message.html; for (const tokenIndex in message.tokens) { @@ -155,7 +158,7 @@ class AutoTranslate { if (targetLanguage) { targetLanguages = [targetLanguage]; } else { - targetLanguages = RocketChat.models.Subscriptions.getAutoTranslateLanguagesByRoomAndNotUser(room._id, message.u && message.u._id); + targetLanguages = Subscriptions.getAutoTranslateLanguagesByRoomAndNotUser(room._id, message.u && message.u._id); } if (message.msg) { Meteor.defer(() => { @@ -187,7 +190,7 @@ class AutoTranslate { } }); if (!_.isEmpty(translations)) { - RocketChat.models.Messages.addTranslations(message._id, translations); + Messages.addTranslations(message._id, translations); } }); } @@ -212,7 +215,7 @@ class AutoTranslate { } }); if (!_.isEmpty(translations)) { - RocketChat.models.Messages.addAttachmentTranslations(message._id, index, translations); + Messages.addAttachmentTranslations(message._id, index, translations); } } } @@ -257,4 +260,4 @@ class AutoTranslate { } } -RocketChat.AutoTranslate = new AutoTranslate; +export default new AutoTranslate(); diff --git a/packages/rocketchat-autotranslate/server/index.js b/packages/rocketchat-autotranslate/server/index.js index 23f718330015..a3692f29c722 100644 --- a/packages/rocketchat-autotranslate/server/index.js +++ b/packages/rocketchat-autotranslate/server/index.js @@ -1,5 +1,3 @@ -import './models/Messages'; -import './models/Subscriptions'; import './settings'; import './permissions'; import './autotranslate'; diff --git a/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js b/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js index b2b79b9c7522..e860c8d64956 100644 --- a/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js +++ b/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js @@ -1,14 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import AutoTranslate from '../autotranslate'; Meteor.methods({ 'autoTranslate.getSupportedLanguages'(targetLanguage) { - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'auto-translate')) { + if (!hasPermission(Meteor.userId(), 'auto-translate')) { throw new Meteor.Error('error-action-not-allowed', 'Auto-Translate is not allowed', { method: 'autoTranslate.saveSettings' }); } - return RocketChat.AutoTranslate.getSupportedLanguages(targetLanguage); + return AutoTranslate.getSupportedLanguages(targetLanguage); }, }); diff --git a/packages/rocketchat-autotranslate/server/methods/saveSettings.js b/packages/rocketchat-autotranslate/server/methods/saveSettings.js index 0298c39a784e..1b700c5badee 100644 --- a/packages/rocketchat-autotranslate/server/methods/saveSettings.js +++ b/packages/rocketchat-autotranslate/server/methods/saveSettings.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ 'autoTranslate.saveSettings'(rid, field, value, options) { @@ -8,7 +9,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'saveAutoTranslateSettings' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'auto-translate')) { + if (!hasPermission(Meteor.userId(), 'auto-translate')) { throw new Meteor.Error('error-action-not-allowed', 'Auto-Translate is not allowed', { method: 'autoTranslate.saveSettings' }); } @@ -20,20 +21,20 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-settings', 'Invalid settings field', { method: 'saveAutoTranslateSettings' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, Meteor.userId()); if (!subscription) { throw new Meteor.Error('error-invalid-subscription', 'Invalid subscription', { method: 'saveAutoTranslateSettings' }); } switch (field) { case 'autoTranslate': - RocketChat.models.Subscriptions.updateAutoTranslateById(subscription._id, value === '1'); + Subscriptions.updateAutoTranslateById(subscription._id, value === '1'); if (!subscription.autoTranslateLanguage && options.defaultLanguage) { - RocketChat.models.Subscriptions.updateAutoTranslateLanguageById(subscription._id, options.defaultLanguage); + Subscriptions.updateAutoTranslateLanguageById(subscription._id, options.defaultLanguage); } break; case 'autoTranslateLanguage': - RocketChat.models.Subscriptions.updateAutoTranslateLanguageById(subscription._id, value); + Subscriptions.updateAutoTranslateLanguageById(subscription._id, value); break; } diff --git a/packages/rocketchat-autotranslate/server/methods/translateMessage.js b/packages/rocketchat-autotranslate/server/methods/translateMessage.js index 77f1dce763be..78813eb1a135 100644 --- a/packages/rocketchat-autotranslate/server/methods/translateMessage.js +++ b/packages/rocketchat-autotranslate/server/methods/translateMessage.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import AutoTranslate from '../autotranslate'; Meteor.methods({ 'autoTranslate.translateMessage'(message, targetLanguage) { - const room = RocketChat.models.Rooms.findOneById(message && message.rid); - if (message && room && RocketChat.AutoTranslate) { - return RocketChat.AutoTranslate.translateMessage(message, room, targetLanguage); + const room = Rooms.findOneById(message && message.rid); + if (message && room && AutoTranslate) { + return AutoTranslate.translateMessage(message, room, targetLanguage); } }, }); diff --git a/packages/rocketchat-autotranslate/server/models/Messages.js b/packages/rocketchat-autotranslate/server/models/Messages.js deleted file mode 100644 index d2c945676502..000000000000 --- a/packages/rocketchat-autotranslate/server/models/Messages.js +++ /dev/null @@ -1,19 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.addTranslations = function(messageId, translations) { - const updateObj = {}; - Object.keys(translations).forEach((key) => { - const translation = translations[key]; - updateObj[`translations.${ key }`] = translation; - }); - return this.update({ _id: messageId }, { $set: updateObj }); -}; - -RocketChat.models.Messages.addAttachmentTranslations = function(messageId, attachmentIndex, translations) { - const updateObj = {}; - Object.keys(translations).forEach((key) => { - const translation = translations[key]; - updateObj[`attachments.${ attachmentIndex }.translations.${ key }`] = translation; - }); - return this.update({ _id: messageId }, { $set: updateObj }); -}; diff --git a/packages/rocketchat-autotranslate/server/models/Subscriptions.js b/packages/rocketchat-autotranslate/server/models/Subscriptions.js deleted file mode 100644 index 28bd43da9ebc..000000000000 --- a/packages/rocketchat-autotranslate/server/models/Subscriptions.js +++ /dev/null @@ -1,50 +0,0 @@ -import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Subscriptions.updateAutoTranslateById = function(_id, autoTranslate) { - const query = { - _id, - }; - - let update; - if (autoTranslate) { - update = { - $set: { - autoTranslate, - }, - }; - } else { - update = { - $unset: { - autoTranslate: 1, - }, - }; - } - - return this.update(query, update); -}; - -RocketChat.models.Subscriptions.updateAutoTranslateLanguageById = function(_id, autoTranslateLanguage) { - const query = { - _id, - }; - - const update = { - $set: { - autoTranslateLanguage, - }, - }; - - return this.update(query, update); -}; - -RocketChat.models.Subscriptions.getAutoTranslateLanguagesByRoomAndNotUser = function(rid, userId) { - const subscriptionsRaw = RocketChat.models.Subscriptions.model.rawCollection(); - const distinct = Meteor.wrapAsync(subscriptionsRaw.distinct, subscriptionsRaw); - const query = { - rid, - 'u._id': { $ne: userId }, - autoTranslate: true, - }; - return distinct('autoTranslateLanguage', query); -}; diff --git a/packages/rocketchat-autotranslate/server/permissions.js b/packages/rocketchat-autotranslate/server/permissions.js index 35536af4427a..891b0e7bb3f3 100644 --- a/packages/rocketchat-autotranslate/server/permissions.js +++ b/packages/rocketchat-autotranslate/server/permissions.js @@ -1,10 +1,10 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Permissions } from 'meteor/rocketchat:models'; Meteor.startup(() => { - if (RocketChat.models && RocketChat.models.Permissions) { - if (!RocketChat.models.Permissions.findOne({ _id: 'auto-translate' })) { - RocketChat.models.Permissions.insert({ _id: 'auto-translate', roles: ['admin'] }); + if (Permissions) { + if (!Permissions.findOne({ _id: 'auto-translate' })) { + Permissions.insert({ _id: 'auto-translate', roles: ['admin'] }); } } }); diff --git a/packages/rocketchat-autotranslate/server/settings.js b/packages/rocketchat-autotranslate/server/settings.js index 813f6f08f992..8f84b0100961 100644 --- a/packages/rocketchat-autotranslate/server/settings.js +++ b/packages/rocketchat-autotranslate/server/settings.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.add('AutoTranslate_Enabled', false, { type: 'boolean', group: 'Message', section: 'AutoTranslate', public: true }); - RocketChat.settings.add('AutoTranslate_GoogleAPIKey', '', { type: 'string', group: 'Message', section: 'AutoTranslate', enableQuery: { _id: 'AutoTranslate_Enabled', value: true } }); + settings.add('AutoTranslate_Enabled', false, { type: 'boolean', group: 'Message', section: 'AutoTranslate', public: true }); + settings.add('AutoTranslate_GoogleAPIKey', '', { type: 'string', group: 'Message', section: 'AutoTranslate', enableQuery: { _id: 'AutoTranslate_Enabled', value: true } }); }); diff --git a/packages/rocketchat-lib/lib/Markdown.js b/packages/rocketchat-lib/lib/Markdown.js new file mode 100644 index 000000000000..2c41733304ae --- /dev/null +++ b/packages/rocketchat-lib/lib/Markdown.js @@ -0,0 +1,3 @@ +import { Markdown } from 'meteor/rocketchat:markdown'; + +RocketChat.Markdown = Markdown; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 72f5237ddeab..ec54d31666c1 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -54,6 +54,7 @@ Package.onUse(function(api) { api.use('rocketchat:push-notifications'); api.use('rocketchat:action-links'); api.use('rocketchat:assets'); + api.use('rocketchat:markdown'); api.use('templating', 'client'); api.use('kadira:flow-router'); @@ -97,6 +98,7 @@ Package.onUse(function(api) { api.addFiles('lib/info.js'); api.addFiles('lib/authorization.js'); api.addFiles('lib/actionLinks.js'); + api.addFiles('lib/Markdown.js'); api.addFiles('lib/getUserNotificationPreference.js'); api.addFiles('lib/getUserPreference.js'); diff --git a/packages/rocketchat-markdown/client/index.js b/packages/rocketchat-markdown/client/index.js index c73efc672f25..33d93bded040 100644 --- a/packages/rocketchat-markdown/client/index.js +++ b/packages/rocketchat-markdown/client/index.js @@ -1 +1 @@ -import '../lib/markdown'; +export { Markdown } from '../lib/markdown'; diff --git a/packages/rocketchat-markdown/lib/markdown.js b/packages/rocketchat-markdown/lib/markdown.js index a063236c2639..c38b475b37e3 100644 --- a/packages/rocketchat-markdown/lib/markdown.js +++ b/packages/rocketchat-markdown/lib/markdown.js @@ -5,8 +5,8 @@ import s from 'underscore.string'; import { Meteor } from 'meteor/meteor'; import { Blaze } from 'meteor/blaze'; -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { marked } from './parser/marked/marked.js'; import { original } from './parser/original/original.js'; @@ -33,7 +33,7 @@ class MarkdownClass { } parseMessageNotEscaped(message) { - const parser = RocketChat.settings.get('Markdown_Parser'); + const parser = settings.get('Markdown_Parser'); if (parser === 'disabled') { return message; @@ -79,7 +79,6 @@ class MarkdownClass { } export const Markdown = new MarkdownClass; -RocketChat.Markdown = Markdown; // renderMessage already did html escape const MarkdownMessage = (message) => { @@ -90,7 +89,7 @@ const MarkdownMessage = (message) => { return message; }; -RocketChat.callbacks.add('renderMessage', MarkdownMessage, RocketChat.callbacks.priority.HIGH, 'markdown'); +callbacks.add('renderMessage', MarkdownMessage, callbacks.priority.HIGH, 'markdown'); if (Meteor.isClient) { Blaze.registerHelper('RocketChatMarkdown', (text) => Markdown.parse(text)); diff --git a/packages/rocketchat-markdown/lib/parser/marked/marked.js b/packages/rocketchat-markdown/lib/parser/marked/marked.js index f8ebd9949233..ef246abd69b1 100644 --- a/packages/rocketchat-markdown/lib/parser/marked/marked.js +++ b/packages/rocketchat-markdown/lib/parser/marked/marked.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { Random } from 'meteor/random'; import _ from 'underscore'; import s from 'underscore.string'; @@ -85,12 +85,12 @@ export const marked = (message) => { msg.tokens = []; } - if (gfm == null) { gfm = RocketChat.settings.get('Markdown_Marked_GFM'); } - if (tables == null) { tables = RocketChat.settings.get('Markdown_Marked_Tables'); } - if (breaks == null) { breaks = RocketChat.settings.get('Markdown_Marked_Breaks'); } - if (pedantic == null) { pedantic = RocketChat.settings.get('Markdown_Marked_Pedantic'); } - if (smartLists == null) { smartLists = RocketChat.settings.get('Markdown_Marked_SmartLists'); } - if (smartypants == null) { smartypants = RocketChat.settings.get('Markdown_Marked_Smartypants'); } + if (gfm == null) { gfm = settings.get('Markdown_Marked_GFM'); } + if (tables == null) { tables = settings.get('Markdown_Marked_Tables'); } + if (breaks == null) { breaks = settings.get('Markdown_Marked_Breaks'); } + if (pedantic == null) { pedantic = settings.get('Markdown_Marked_Pedantic'); } + if (smartLists == null) { smartLists = settings.get('Markdown_Marked_SmartLists'); } + if (smartypants == null) { smartypants = settings.get('Markdown_Marked_Smartypants'); } msg.html = _marked(s.unescapeHTML(msg.html), { gfm, diff --git a/packages/rocketchat-markdown/lib/parser/original/markdown.js b/packages/rocketchat-markdown/lib/parser/original/markdown.js index 75c286325db7..db7105eb6183 100644 --- a/packages/rocketchat-markdown/lib/parser/original/markdown.js +++ b/packages/rocketchat-markdown/lib/parser/original/markdown.js @@ -4,7 +4,7 @@ */ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import s from 'underscore.string'; const parseNotEscaped = function(msg, message) { @@ -22,9 +22,9 @@ const parseNotEscaped = function(msg, message) { return token; }; - const schemes = RocketChat.settings.get('Markdown_SupportSchemesForLink').split(',').join('|'); + const schemes = settings.get('Markdown_SupportSchemesForLink').split(',').join('|'); - if (RocketChat.settings.get('Markdown_Headers')) { + if (settings.get('Markdown_Headers')) { // Support # Text for h1 msg = msg.replace(/^# (([\S\w\d-_\/\*\.,\\][ \u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]?)+)/gm, '

$1

'); diff --git a/packages/rocketchat-markdown/package.js b/packages/rocketchat-markdown/package.js index c7283d5d87c8..5baa2bbd78c2 100644 --- a/packages/rocketchat-markdown/package.js +++ b/packages/rocketchat-markdown/package.js @@ -9,7 +9,8 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-markdown/server/index.js b/packages/rocketchat-markdown/server/index.js index a385a44d9a79..f4d1855ab52a 100644 --- a/packages/rocketchat-markdown/server/index.js +++ b/packages/rocketchat-markdown/server/index.js @@ -1,2 +1,2 @@ import './settings'; -import '../lib/markdown'; +export { Markdown } from '../lib/markdown'; diff --git a/packages/rocketchat-markdown/server/settings.js b/packages/rocketchat-markdown/server/settings.js index 8652c70763a6..a9b7592c1594 100644 --- a/packages/rocketchat-markdown/server/settings.js +++ b/packages/rocketchat-markdown/server/settings.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(() => { - RocketChat.settings.add('Markdown_Parser', 'original', { + settings.add('Markdown_Parser', 'original', { type: 'select', values: [{ key: 'disabled', @@ -20,14 +20,14 @@ Meteor.startup(() => { }); const enableQueryOriginal = { _id: 'Markdown_Parser', value: 'original' }; - RocketChat.settings.add('Markdown_Headers', false, { + settings.add('Markdown_Headers', false, { type: 'boolean', group: 'Message', section: 'Markdown', public: true, enableQuery: enableQueryOriginal, }); - RocketChat.settings.add('Markdown_SupportSchemesForLink', 'http,https', { + settings.add('Markdown_SupportSchemesForLink', 'http,https', { type: 'string', group: 'Message', section: 'Markdown', @@ -37,28 +37,28 @@ Meteor.startup(() => { }); const enableQueryMarked = { _id: 'Markdown_Parser', value: 'marked' }; - RocketChat.settings.add('Markdown_Marked_GFM', true, { + settings.add('Markdown_Marked_GFM', true, { type: 'boolean', group: 'Message', section: 'Markdown', public: true, enableQuery: enableQueryMarked, }); - RocketChat.settings.add('Markdown_Marked_Tables', true, { + settings.add('Markdown_Marked_Tables', true, { type: 'boolean', group: 'Message', section: 'Markdown', public: true, enableQuery: enableQueryMarked, }); - RocketChat.settings.add('Markdown_Marked_Breaks', true, { + settings.add('Markdown_Marked_Breaks', true, { type: 'boolean', group: 'Message', section: 'Markdown', public: true, enableQuery: enableQueryMarked, }); - RocketChat.settings.add('Markdown_Marked_Pedantic', false, { + settings.add('Markdown_Marked_Pedantic', false, { type: 'boolean', group: 'Message', section: 'Markdown', @@ -71,14 +71,14 @@ Meteor.startup(() => { value: false, }], }); - RocketChat.settings.add('Markdown_Marked_SmartLists', true, { + settings.add('Markdown_Marked_SmartLists', true, { type: 'boolean', group: 'Message', section: 'Markdown', public: true, enableQuery: enableQueryMarked, }); - RocketChat.settings.add('Markdown_Marked_Smartypants', true, { + settings.add('Markdown_Marked_Smartypants', true, { type: 'boolean', group: 'Message', section: 'Markdown', diff --git a/packages/rocketchat-markdown/tests/client.mocks.js b/packages/rocketchat-markdown/tests/client.mocks.js index 07eb25de3a19..1347ca8b2b93 100644 --- a/packages/rocketchat-markdown/tests/client.mocks.js +++ b/packages/rocketchat-markdown/tests/client.mocks.js @@ -15,35 +15,36 @@ mock('meteor/blaze', { Blaze: {}, }); -mock('meteor/rocketchat:lib', { - RocketChat: { - settings: { - get(setting) { - switch (setting) { - case 'Markdown_SupportSchemesForLink': - return 'http,https'; - case 'Markdown_Parser': - return 'original'; - case 'Markdown_Headers': - // case 'Markdown_Marked_GFM': - // case 'Markdown_Marked_Tables': - // case 'Markdown_Marked_Breaks': - // case 'Markdown_Marked_Pedantic': - // case 'Markdown_Marked_SmartLists': - // case 'Markdown_Marked_Smartypants': - return true; - default: - throw new Error(`Missing setting mock ${ setting }`); - } - }, +mock('meteor/rocketchat:settings', { + settings: { + get(setting) { + switch (setting) { + case 'Markdown_SupportSchemesForLink': + return 'http,https'; + case 'Markdown_Parser': + return 'original'; + case 'Markdown_Headers': + // case 'Markdown_Marked_GFM': + // case 'Markdown_Marked_Tables': + // case 'Markdown_Marked_Breaks': + // case 'Markdown_Marked_Pedantic': + // case 'Markdown_Marked_SmartLists': + // case 'Markdown_Marked_Smartypants': + return true; + default: + throw new Error(`Missing setting mock ${ setting }`); + } }, - callbacks: { - add() { + }, +}); - }, - priority: { - HIGH: 1, - }, +mock('meteor/rocketchat:callbacks', { + callbacks: { + add() { + + }, + priority: { + HIGH: 1, }, }, }); diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index de009f321fef..72a7fd18b5c5 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -33,6 +33,24 @@ export class Messages extends Base { }); } + addTranslations(messageId, translations) { + const updateObj = {}; + Object.keys(translations).forEach((key) => { + const translation = translations[key]; + updateObj[`translations.${ key }`] = translation; + }); + return this.update({ _id: messageId }, { $set: updateObj }); + } + + addAttachmentTranslations = function(messageId, attachmentIndex, translations) { + const updateObj = {}; + Object.keys(translations).forEach((key) => { + const translation = translations[key]; + updateObj[`attachments.${ attachmentIndex }.translations.${ key }`] = translation; + }); + return this.update({ _id: messageId }, { $set: updateObj }); + } + countVisibleByRoomIdBetweenTimestampsInclusive(roomId, afterTimestamp, beforeTimestamp, options) { const query = { _hidden: { diff --git a/packages/rocketchat-models/server/models/Subscriptions.js b/packages/rocketchat-models/server/models/Subscriptions.js index f706e3f04ddb..0ccfade3d72e 100644 --- a/packages/rocketchat-models/server/models/Subscriptions.js +++ b/packages/rocketchat-models/server/models/Subscriptions.js @@ -1,3 +1,4 @@ +import { Meteor } from 'meteor/meteor'; import { Base } from './_Base'; import { Match } from 'meteor/check'; import Rooms from './Rooms'; @@ -29,6 +30,54 @@ export class Subscriptions extends Base { this.tryEnsureIndex({ 'userHighlights.0': 1 }, { sparse: 1 }); } + updateAutoTranslateById(_id, autoTranslate) { + const query = { + _id, + }; + + let update; + if (autoTranslate) { + update = { + $set: { + autoTranslate, + }, + }; + } else { + update = { + $unset: { + autoTranslate: 1, + }, + }; + } + + return this.update(query, update); + } + + updateAutoTranslateLanguageById(_id, autoTranslateLanguage) { + const query = { + _id, + }; + + const update = { + $set: { + autoTranslateLanguage, + }, + }; + + return this.update(query, update); + } + + getAutoTranslateLanguagesByRoomAndNotUser(rid, userId) { + const subscriptionsRaw = this.model.rawCollection(); + const distinct = Meteor.wrapAsync(subscriptionsRaw.distinct, subscriptionsRaw); + const query = { + rid, + 'u._id': { $ne: userId }, + autoTranslate: true, + }; + return distinct('autoTranslateLanguage', query); + } + roleBaseQuery(userId, scope) { if (scope == null) { return; diff --git a/packages/rocketchat-ui-message/client/message.js b/packages/rocketchat-ui-message/client/message.js index 38f4c7437c2f..be794edea2e5 100644 --- a/packages/rocketchat-ui-message/client/message.js +++ b/packages/rocketchat-ui-message/client/message.js @@ -10,6 +10,7 @@ import { renderEmoji } from 'meteor/rocketchat:emoji'; import { renderMessageBody } from 'meteor/rocketchat:ui-utils'; import { RocketChat } from 'meteor/rocketchat:lib'; import { RoomRoles, UserRoles } from 'meteor/rocketchat:ui'; +import { AutoTranslate } from 'meteor/rocketchat:autotranslate'; import { t } from 'meteor/rocketchat:utils'; async function renderPdfToCanvas(canvasId, pdfLink) { @@ -192,7 +193,7 @@ Template.message.helpers({ autoTranslateLanguage: 1, }, }); - const language = RocketChat.AutoTranslate.getLanguage(this.rid); + const language = AutoTranslate.getLanguage(this.rid); return this.autoTranslateFetching || (subscription && subscription.autoTranslate !== this.autoTranslateShowInverse && this.translations && this.translations[language]); } }, diff --git a/packages/rocketchat-ui-message/package.js b/packages/rocketchat-ui-message/package.js index bc563d9e2f19..2ed826cf9223 100644 --- a/packages/rocketchat-ui-message/package.js +++ b/packages/rocketchat-ui-message/package.js @@ -26,6 +26,7 @@ Package.onUse(function(api) { 'rocketchat:ui-vrecord', 'rocketchat:ui-sidenav', 'rocketchat:file-upload', + 'rocketchat:autotranslate', ]); api.addAssets('../../node_modules/pdfjs-dist/build/pdf.worker.js', 'client'); api.mainModule('client/index.js', 'client'); From 258d2584a10586faa0b24b8cfec0dfb837faca74 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 15:20:57 -0200 Subject: [PATCH 18/33] Remove dependency of RC namespace in rc-blockstack, bot-helpers and cas (#13246) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Fix wrong imports --- packages/rocketchat-blockstack/package.js | 10 ++++-- .../server/loginHandler.js | 11 ++++--- .../rocketchat-blockstack/server/routes.js | 9 +++--- .../rocketchat-blockstack/server/settings.js | 15 +++++---- .../server/tokenHandler.js | 1 - .../server/userHandler.js | 4 +-- packages/rocketchat-bot-helpers/package.js | 4 ++- .../rocketchat-bot-helpers/server/index.js | 16 +++++----- .../rocketchat-bot-helpers/server/settings.js | 4 +-- packages/rocketchat-cas/client/cas_client.js | 8 ++--- packages/rocketchat-cas/package.js | 2 ++ .../rocketchat-cas/server/cas_rocketchat.js | 24 +++++++------- packages/rocketchat-cas/server/cas_server.js | 31 ++++++++++--------- .../rocketchat-lib/server/functions/index.js | 2 +- .../server/functions/setRealName.js | 2 +- 15 files changed, 77 insertions(+), 66 deletions(-) diff --git a/packages/rocketchat-blockstack/package.js b/packages/rocketchat-blockstack/package.js index 9d1ed4677d84..cd7f4e3ad162 100644 --- a/packages/rocketchat-blockstack/package.js +++ b/packages/rocketchat-blockstack/package.js @@ -6,9 +6,13 @@ Package.describe({ }); Package.onUse((api) => { - api.use('ecmascript'); - + api.use([ + 'ecmascript', + 'rocketchat:settings', + 'rocketchat:assets', + 'rocketchat:models', + 'rocketchat:lib', + ]); api.mainModule('server/main.js', 'server'); - api.mainModule('client/main.js', 'client'); }); diff --git a/packages/rocketchat-blockstack/server/loginHandler.js b/packages/rocketchat-blockstack/server/loginHandler.js index 971d3ba42c91..74c3b1bcbe0a 100644 --- a/packages/rocketchat-blockstack/server/loginHandler.js +++ b/packages/rocketchat-blockstack/server/loginHandler.js @@ -1,7 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; +import { setUserAvatar } from 'meteor/rocketchat:lib'; import { updateOrCreateUser } from './userHandler'; import { handleAccessToken } from './tokenHandler'; import { logger } from './logger'; @@ -12,7 +13,7 @@ Accounts.registerLoginHandler('blockstack', (loginRequest) => { return; } - if (!RocketChat.settings.get('Blockstack_Enable')) { + if (!settings.get('Blockstack_Enable')) { return; } @@ -35,10 +36,10 @@ Accounts.registerLoginHandler('blockstack', (loginRequest) => { if (result.isNew) { try { - const user = RocketChat.models.Users.findOneById(result.userId, { fields: { 'services.blockstack.image': 1, username: 1 } }); + const user = Users.findOneById(result.userId, { fields: { 'services.blockstack.image': 1, username: 1 } }); if (user && user.services && user.services.blockstack && user.services.blockstack.image) { Meteor.runAsUser(user._id, () => { - RocketChat.setUserAvatar(user, user.services.blockstack.image, undefined, 'url'); + setUserAvatar(user, user.services.blockstack.image, undefined, 'url'); }); } } catch (e) { diff --git a/packages/rocketchat-blockstack/server/routes.js b/packages/rocketchat-blockstack/server/routes.js index b117f7c460b7..5abfbb931233 100644 --- a/packages/rocketchat-blockstack/server/routes.js +++ b/packages/rocketchat-blockstack/server/routes.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { RocketChatAssets } from 'meteor/rocketchat:assets'; WebApp.connectHandlers.use('/_blockstack/manifest', Meteor.bindEnvironment(function(req, res) { - const name = RocketChat.settings.get('Site_Name'); + const name = settings.get('Site_Name'); const startUrl = Meteor.absoluteUrl(); - const description = RocketChat.settings.get('Blockstack_Auth_Description'); - const iconUrl = RocketChat.Assets.getURL('Assets_favicon_192'); + const description = settings.get('Blockstack_Auth_Description'); + const iconUrl = RocketChatAssets.getURL('Assets_favicon_192'); res.writeHead(200, { 'Content-Type': 'application/json', diff --git a/packages/rocketchat-blockstack/server/settings.js b/packages/rocketchat-blockstack/server/settings.js index 62be821bc401..39881e698522 100644 --- a/packages/rocketchat-blockstack/server/settings.js +++ b/packages/rocketchat-blockstack/server/settings.js @@ -1,7 +1,6 @@ import _ from 'underscore'; import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { settings } from 'meteor/rocketchat:settings'; import { ServiceConfiguration } from 'meteor/service-configuration'; import { logger } from './logger'; @@ -18,7 +17,7 @@ const defaults = { }; Meteor.startup(() => { - RocketChat.settings.addGroup('Blockstack', function() { + settings.addGroup('Blockstack', function() { this.add('Blockstack_Enable', defaults.enable, { type: 'boolean', i18nLabel: 'Enable', @@ -37,10 +36,10 @@ Meteor.startup(() => { // Helper to return all Blockstack settings const getSettings = () => Object.assign({}, defaults, { - enable: RocketChat.settings.get('Blockstack_Enable'), - authDescription: RocketChat.settings.get('Blockstack_Auth_Description'), - buttonLabelText: RocketChat.settings.get('Blockstack_ButtonLabelText'), - generateUsername: RocketChat.settings.get('Blockstack_Generate_Username'), + enable: settings.get('Blockstack_Enable'), + authDescription: settings.get('Blockstack_Auth_Description'), + buttonLabelText: settings.get('Blockstack_ButtonLabelText'), + generateUsername: settings.get('Blockstack_Generate_Username'), }); const configureService = _.debounce(Meteor.bindEnvironment(() => { @@ -64,7 +63,7 @@ const configureService = _.debounce(Meteor.bindEnvironment(() => { // Add settings to auth provider configs on startup Meteor.startup(() => { - RocketChat.settings.get(/^Blockstack_.+/, () => { + settings.get(/^Blockstack_.+/, () => { configureService(); }); }); diff --git a/packages/rocketchat-blockstack/server/tokenHandler.js b/packages/rocketchat-blockstack/server/tokenHandler.js index 30686814b113..bfe1afe7ccc1 100644 --- a/packages/rocketchat-blockstack/server/tokenHandler.js +++ b/packages/rocketchat-blockstack/server/tokenHandler.js @@ -1,5 +1,4 @@ import { decodeToken } from 'blockstack'; - import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Match, check } from 'meteor/check'; diff --git a/packages/rocketchat-blockstack/server/userHandler.js b/packages/rocketchat-blockstack/server/userHandler.js index 8e23773b2735..c2c026bee3a2 100644 --- a/packages/rocketchat-blockstack/server/userHandler.js +++ b/packages/rocketchat-blockstack/server/userHandler.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { ServiceConfiguration } from 'meteor/service-configuration'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { generateUsernameSuggestion } from 'meteor/rocketchat:lib'; import { logger } from './logger'; // Updates or creates a user after we authenticate with Blockstack @@ -53,7 +53,7 @@ export const updateOrCreateUser = (serviceData, options) => { if (profile.username && profile.username !== '') { newUser.username = profile.username; } else if (serviceConfig.generateUsername === true) { - newUser.username = RocketChat.generateUsernameSuggestion(newUser); + newUser.username = generateUsernameSuggestion(newUser); } // If no username at this point it will suggest one from the name diff --git a/packages/rocketchat-bot-helpers/package.js b/packages/rocketchat-bot-helpers/package.js index f5d8654dd4e1..5d1f2cc9433e 100644 --- a/packages/rocketchat-bot-helpers/package.js +++ b/packages/rocketchat-bot-helpers/package.js @@ -8,7 +8,9 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:authorization', 'accounts-base', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-bot-helpers/server/index.js b/packages/rocketchat-bot-helpers/server/index.js index 085a85284353..e633fb4e1d57 100644 --- a/packages/rocketchat-bot-helpers/server/index.js +++ b/packages/rocketchat-bot-helpers/server/index.js @@ -1,6 +1,8 @@ import './settings'; import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasRole } from 'meteor/rocketchat:authorization'; import _ from 'underscore'; /** @@ -25,8 +27,8 @@ class BotHelpers { fieldsSetting.forEach((n) => { this.userFields[n.trim()] = 1; }); - this._allUsers = RocketChat.models.Users.find(this.queries.users, { fields: this.userFields }); - this._onlineUsers = RocketChat.models.Users.find({ $and: [this.queries.users, this.queries.online] }, { fields: this.userFields }); + this._allUsers = Users.find(this.queries.users, { fields: this.userFields }); + this._onlineUsers = Users.find({ $and: [this.queries.users, this.queries.online] }, { fields: this.userFields }); } // request methods or props as arguments to Meteor.call @@ -49,7 +51,7 @@ class BotHelpers { } addUserToRoom(userName, room) { - const foundRoom = RocketChat.models.Rooms.findOneByIdOrName(room); + const foundRoom = Rooms.findOneByIdOrName(room); if (!_.isObject(foundRoom)) { throw new Meteor.Error('invalid-channel'); @@ -62,7 +64,7 @@ class BotHelpers { } removeUserFromRoom(userName, room) { - const foundRoom = RocketChat.models.Rooms.findOneByIdOrName(room); + const foundRoom = Rooms.findOneByIdOrName(room); if (!_.isObject(foundRoom)) { throw new Meteor.Error('invalid-channel'); @@ -150,14 +152,14 @@ class BotHelpers { const botHelpers = new BotHelpers(); // init cursors with fields setting and update on setting change -RocketChat.settings.get('BotHelpers_userFields', function(settingKey, settingValue) { +settings.get('BotHelpers_userFields', function(settingKey, settingValue) { botHelpers.setupCursors(settingValue); }); Meteor.methods({ botRequest: (...args) => { const userID = Meteor.userId(); - if (userID && RocketChat.authz.hasRole(userID, 'bot')) { + if (userID && hasRole(userID, 'bot')) { return botHelpers.request(...args); } else { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'botRequest' }); diff --git a/packages/rocketchat-bot-helpers/server/settings.js b/packages/rocketchat-bot-helpers/server/settings.js index f2dab1624e96..6d654a2b6d30 100644 --- a/packages/rocketchat-bot-helpers/server/settings.js +++ b/packages/rocketchat-bot-helpers/server/settings.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.addGroup('Bots', function() { + settings.addGroup('Bots', function() { this.add('BotHelpers_userFields', '_id, name, username, emails, language, utcOffset', { type: 'string', section: 'Helpers', diff --git a/packages/rocketchat-cas/client/cas_client.js b/packages/rocketchat-cas/client/cas_client.js index 4722bf13ccfd..f9c187e796c2 100644 --- a/packages/rocketchat-cas/client/cas_client.js +++ b/packages/rocketchat-cas/client/cas_client.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; const openCenteredPopup = function(url, width, height) { @@ -29,9 +29,9 @@ Meteor.loginWithCas = function(options, callback) { options = options || {}; const credentialToken = Random.id(); - const login_url = RocketChat.settings.get('CAS_login_url'); - const popup_width = RocketChat.settings.get('CAS_popup_width'); - const popup_height = RocketChat.settings.get('CAS_popup_height'); + const login_url = settings.get('CAS_login_url'); + const popup_width = settings.get('CAS_popup_width'); + const popup_height = settings.get('CAS_popup_height'); if (!login_url) { return; diff --git a/packages/rocketchat-cas/package.js b/packages/rocketchat-cas/package.js index 25096d4fd1f5..5803f060e859 100644 --- a/packages/rocketchat-cas/package.js +++ b/packages/rocketchat-cas/package.js @@ -9,6 +9,8 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:settings', 'rocketchat:logger', 'service-configuration', 'routepolicy', diff --git a/packages/rocketchat-cas/server/cas_rocketchat.js b/packages/rocketchat-cas/server/cas_rocketchat.js index 3d96e1d4d39d..aca1adc615d6 100644 --- a/packages/rocketchat-cas/server/cas_rocketchat.js +++ b/packages/rocketchat-cas/server/cas_rocketchat.js @@ -1,11 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Logger } from 'meteor/rocketchat:logger'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { ServiceConfiguration } from 'meteor/service-configuration'; export const logger = new Logger('CAS', {}); Meteor.startup(function() { - RocketChat.settings.addGroup('CAS', function() { + settings.addGroup('CAS', function() { this.add('CAS_enabled', false, { type: 'boolean', group: 'CAS', public: true }); this.add('CAS_base_url', '', { type: 'string', group: 'CAS', public: true }); this.add('CAS_login_url', '', { type: 'string', group: 'CAS', public: true }); @@ -39,16 +39,16 @@ function updateServices(/* record*/) { timer = Meteor.setTimeout(function() { const data = { // These will pe passed to 'node-cas' as options - enabled: RocketChat.settings.get('CAS_enabled'), - base_url: RocketChat.settings.get('CAS_base_url'), - login_url: RocketChat.settings.get('CAS_login_url'), + enabled: settings.get('CAS_enabled'), + base_url: settings.get('CAS_base_url'), + login_url: settings.get('CAS_login_url'), // Rocketchat Visuals - buttonLabelText: RocketChat.settings.get('CAS_button_label_text'), - buttonLabelColor: RocketChat.settings.get('CAS_button_label_color'), - buttonColor: RocketChat.settings.get('CAS_button_color'), - width: RocketChat.settings.get('CAS_popup_width'), - height: RocketChat.settings.get('CAS_popup_height'), - autoclose: RocketChat.settings.get('CAS_autoclose'), + buttonLabelText: settings.get('CAS_button_label_text'), + buttonLabelColor: settings.get('CAS_button_label_color'), + buttonColor: settings.get('CAS_button_color'), + width: settings.get('CAS_popup_width'), + height: settings.get('CAS_popup_height'), + autoclose: settings.get('CAS_autoclose'), }; // Either register or deregister the CAS login service based upon its configuration @@ -62,6 +62,6 @@ function updateServices(/* record*/) { }, 2000); } -RocketChat.settings.get(/^CAS_.+/, (key, value) => { +settings.get(/^CAS_.+/, (key, value) => { updateServices(value); }); diff --git a/packages/rocketchat-cas/server/cas_server.js b/packages/rocketchat-cas/server/cas_server.js index e52283ca7579..3f9669a130b5 100644 --- a/packages/rocketchat-cas/server/cas_server.js +++ b/packages/rocketchat-cas/server/cas_server.js @@ -2,11 +2,12 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { RoutePolicy } from 'meteor/routepolicy'; +import { Rooms, Subscriptions, CredentialTokens } from 'meteor/rocketchat:models'; +import { _setRealName } from 'meteor/rocketchat:lib'; import { logger } from './cas_rocketchat'; import _ from 'underscore'; - import fiber from 'fibers'; import url from 'url'; import CAS from 'cas'; @@ -22,7 +23,7 @@ const closePopup = function(res) { const casTicket = function(req, token, callback) { // get configuration - if (!RocketChat.settings.get('CAS_enabled')) { + if (!settings.get('CAS_enabled')) { logger.error('Got ticket validation request, but CAS is not enabled'); callback(); } @@ -30,8 +31,8 @@ const casTicket = function(req, token, callback) { // get ticket and validate. const parsedUrl = url.parse(req.url, true); const ticketId = parsedUrl.query.ticket; - const baseUrl = RocketChat.settings.get('CAS_base_url'); - const cas_version = parseFloat(RocketChat.settings.get('CAS_version')); + const baseUrl = settings.get('CAS_base_url'); + const cas_version = parseFloat(settings.get('CAS_version')); const appUrl = Meteor.absoluteUrl().replace(/\/$/, '') + __meteor_runtime_config__.ROOT_URL_PATH_PREFIX; logger.debug(`Using CAS_base_url: ${ baseUrl }`); @@ -52,7 +53,7 @@ const casTicket = function(req, token, callback) { if (details && details.attributes) { _.extend(user_info, { attributes: details.attributes }); } - RocketChat.models.CredentialTokens.create(token, user_info); + CredentialTokens.create(token, user_info); } else { logger.error(`Unable to validate ticket: ${ ticketId }`); } @@ -116,16 +117,16 @@ Accounts.registerLoginHandler(function(options) { return undefined; } - const credentials = RocketChat.models.CredentialTokens.findOneById(options.cas.credentialToken); + const credentials = CredentialTokens.findOneById(options.cas.credentialToken); if (credentials === undefined) { throw new Meteor.Error(Accounts.LoginCancelledError.numericError, 'no matching login attempt found'); } const result = credentials.userInfo; - const syncUserDataFieldMap = RocketChat.settings.get('CAS_Sync_User_Data_FieldMap').trim(); - const cas_version = parseFloat(RocketChat.settings.get('CAS_version')); - const sync_enabled = RocketChat.settings.get('CAS_Sync_User_Data_Enabled'); + const syncUserDataFieldMap = settings.get('CAS_Sync_User_Data_FieldMap').trim(); + const cas_version = parseFloat(settings.get('CAS_version')); + const sync_enabled = settings.get('CAS_Sync_User_Data_Enabled'); // We have these const ext_attrs = { @@ -196,7 +197,7 @@ Accounts.registerLoginHandler(function(options) { logger.debug('Syncing user attributes'); // Update name if (int_attrs.name) { - RocketChat._setRealName(user._id, int_attrs.name); + _setRealName(user._id, int_attrs.name); } // Update email @@ -248,13 +249,13 @@ Accounts.registerLoginHandler(function(options) { if (int_attrs.rooms) { _.each(int_attrs.rooms.split(','), function(room_name) { if (room_name) { - let room = RocketChat.models.Rooms.findOneByNameAndType(room_name, 'c'); + let room = Rooms.findOneByNameAndType(room_name, 'c'); if (!room) { - room = RocketChat.models.Rooms.createWithIdTypeAndName(Random.id(), 'c', room_name); + room = Rooms.createWithIdTypeAndName(Random.id(), 'c', room_name); } - if (!RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, userId)) { - RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, { + if (!Subscriptions.findOneByRoomIdAndUserId(room._id, userId)) { + Subscriptions.createWithRoomAndUser(room, user, { ts: new Date(), open: true, alert: true, diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js index de83cbb57af4..c60ee0e9849d 100644 --- a/packages/rocketchat-lib/server/functions/index.js +++ b/packages/rocketchat-lib/server/functions/index.js @@ -17,7 +17,7 @@ export { saveCustomFieldsWithoutValidation } from './saveCustomFieldsWithoutVali export { saveUser } from './saveUser'; export { sendMessage } from './sendMessage'; export { setEmail } from './setEmail'; -export { setRealName } from './setRealName'; +export { setRealName, _setRealName } from './setRealName'; export { setUserAvatar } from './setUserAvatar'; export { setUsername } from './setUsername'; export { unarchiveRoom } from './unarchiveRoom'; diff --git a/packages/rocketchat-lib/server/functions/setRealName.js b/packages/rocketchat-lib/server/functions/setRealName.js index 6bafcb066b4e..cd9719233c51 100644 --- a/packages/rocketchat-lib/server/functions/setRealName.js +++ b/packages/rocketchat-lib/server/functions/setRealName.js @@ -6,7 +6,7 @@ import { hasPermission } from 'meteor/rocketchat:authorization'; import { RateLimiter } from '../lib'; import s from 'underscore.string'; -const _setRealName = function(userId, name) { +export const _setRealName = function(userId, name) { name = s.trim(name); if (!userId || !name) { return false; From b9e1538ccbe86fe49b5c72263fe58ed6d34e432a Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 18:49:35 -0200 Subject: [PATCH 19/33] Remove dependency of RC namespace in rc-channel-settings (#13251) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * readd saveRoomName to RC namespace --- .../client/index.js | 2 +- .../client/lib/ChannelSettings.js | 3 +- .../client/startup/messageTypes.js | 10 +- .../client/startup/tabBar.js | 4 +- .../client/startup/trackSettingsChange.js | 9 +- .../client/views/channelSettings.js | 139 +++++++++--------- .../rocketchat-channel-settings/package.js | 4 +- .../server/functions/saveReactWhenReadOnly.js | 6 +- .../server/functions/saveRoomAnnouncement.js | 8 +- .../server/functions/saveRoomCustomFields.js | 8 +- .../server/functions/saveRoomDescription.js | 8 +- .../server/functions/saveRoomName.js | 15 +- .../server/functions/saveRoomReadOnly.js | 7 +- .../functions/saveRoomSystemMessages.js | 6 +- .../server/functions/saveRoomTokens.js | 6 +- .../server/functions/saveRoomTopic.js | 8 +- .../server/functions/saveRoomType.js | 15 +- .../server/functions/saveStreamingOptions.js | 6 +- .../server/index.js | 14 +- .../server/methods/saveRoomSettings.js | 70 +++++---- .../server/models/Messages.js | 9 -- .../server/models/Rooms.js | 67 --------- .../server/startup.js | 8 +- .../client/lib/ChannelSettings.js | 3 + packages/rocketchat-lib/package.js | 4 + .../server/functions/saveRoomName.js | 3 + .../server/functions/saveRoomTopic.js | 3 + .../server/functions/saveStreamingOptions.js | 3 + .../rocketchat-livestream/server/index.js | 2 - .../server/models/Rooms.js | 10 -- .../server/models/Messages.js | 8 + .../rocketchat-models/server/models/Rooms.js | 88 +++++++++++ packages/rocketchat-tokenpass/server/index.js | 1 - .../server/models/Rooms.js | 10 -- 34 files changed, 295 insertions(+), 272 deletions(-) rename packages/{rocketchat-tokenpass => rocketchat-channel-settings}/server/functions/saveRoomTokens.js (56%) rename packages/{rocketchat-livestream => rocketchat-channel-settings}/server/functions/saveStreamingOptions.js (72%) delete mode 100644 packages/rocketchat-channel-settings/server/models/Messages.js delete mode 100644 packages/rocketchat-channel-settings/server/models/Rooms.js create mode 100644 packages/rocketchat-lib/client/lib/ChannelSettings.js create mode 100644 packages/rocketchat-lib/server/functions/saveRoomName.js create mode 100644 packages/rocketchat-lib/server/functions/saveRoomTopic.js create mode 100644 packages/rocketchat-lib/server/functions/saveStreamingOptions.js delete mode 100644 packages/rocketchat-livestream/server/models/Rooms.js diff --git a/packages/rocketchat-channel-settings/client/index.js b/packages/rocketchat-channel-settings/client/index.js index 78bfbc38ef21..5f84cf2870b3 100644 --- a/packages/rocketchat-channel-settings/client/index.js +++ b/packages/rocketchat-channel-settings/client/index.js @@ -1,6 +1,6 @@ import './startup/messageTypes'; import './startup/tabBar'; import './startup/trackSettingsChange'; -import './lib/ChannelSettings'; +export { ChannelSettings } from './lib/ChannelSettings'; import './views/channelSettings.html'; import './views/channelSettings'; diff --git a/packages/rocketchat-channel-settings/client/lib/ChannelSettings.js b/packages/rocketchat-channel-settings/client/lib/ChannelSettings.js index f643d2c6674b..b705c206b20d 100644 --- a/packages/rocketchat-channel-settings/client/lib/ChannelSettings.js +++ b/packages/rocketchat-channel-settings/client/lib/ChannelSettings.js @@ -1,9 +1,8 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; import _ from 'underscore'; -RocketChat.ChannelSettings = new class { +export const ChannelSettings = new class { constructor() { this.options = new ReactiveVar({}); } diff --git a/packages/rocketchat-channel-settings/client/startup/messageTypes.js b/packages/rocketchat-channel-settings/client/startup/messageTypes.js index 1fe5f21590ed..3ee05065a5a0 100644 --- a/packages/rocketchat-channel-settings/client/startup/messageTypes.js +++ b/packages/rocketchat-channel-settings/client/startup/messageTypes.js @@ -1,10 +1,10 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { MessageTypes } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import s from 'underscore.string'; Meteor.startup(function() { - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'room_changed_privacy', system: true, message: 'room_changed_privacy', @@ -16,7 +16,7 @@ Meteor.startup(function() { }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'room_changed_topic', system: true, message: 'room_changed_topic', @@ -28,7 +28,7 @@ Meteor.startup(function() { }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'room_changed_announcement', system: true, message: 'room_changed_announcement', @@ -40,7 +40,7 @@ Meteor.startup(function() { }, }); - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'room_changed_description', system: true, message: 'room_changed_description', diff --git a/packages/rocketchat-channel-settings/client/startup/tabBar.js b/packages/rocketchat-channel-settings/client/startup/tabBar.js index 4f61bca98c57..d0509709288d 100644 --- a/packages/rocketchat-channel-settings/client/startup/tabBar.js +++ b/packages/rocketchat-channel-settings/client/startup/tabBar.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; Meteor.startup(() => { - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'channel-settings', anonymous: true, diff --git a/packages/rocketchat-channel-settings/client/startup/trackSettingsChange.js b/packages/rocketchat-channel-settings/client/startup/trackSettingsChange.js index b87a0ecee8ce..a6c5091040dc 100644 --- a/packages/rocketchat-channel-settings/client/startup/trackSettingsChange.js +++ b/packages/rocketchat-channel-settings/client/startup/trackSettingsChange.js @@ -2,8 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { RoomManager } from 'meteor/rocketchat:ui-utils'; +import { roomTypes } from 'meteor/rocketchat:utils'; import { ChatRoom, ChatSubscription } from 'meteor/rocketchat:models'; Meteor.startup(function() { @@ -24,7 +25,7 @@ Meteor.startup(function() { return msg; }; - RocketChat.callbacks.add('streamMessage', roomSettingsChangedCallback, RocketChat.callbacks.priority.HIGH, 'room-settings-changed'); + callbacks.add('streamMessage', roomSettingsChangedCallback, callbacks.priority.HIGH, 'room-settings-changed'); const roomNameChangedCallback = (msg) => { Tracker.nonreactive(() => { @@ -33,7 +34,7 @@ Meteor.startup(function() { const room = ChatRoom.findOne(msg.rid); if (room.name !== FlowRouter.getParam('name')) { RoomManager.close(room.t + FlowRouter.getParam('name')); - RocketChat.roomTypes.openRouteLink(room.t, room, FlowRouter.current().queryParams); + roomTypes.openRouteLink(room.t, room, FlowRouter.current().queryParams); } } } @@ -42,5 +43,5 @@ Meteor.startup(function() { return msg; }; - RocketChat.callbacks.add('streamMessage', roomNameChangedCallback, RocketChat.callbacks.priority.HIGH, 'room-name-changed'); + callbacks.add('streamMessage', roomNameChangedCallback, callbacks.priority.HIGH, 'room-name-changed'); }); diff --git a/packages/rocketchat-channel-settings/client/views/channelSettings.js b/packages/rocketchat-channel-settings/client/views/channelSettings.js index 2884bff26f93..7d3a58ca77df 100644 --- a/packages/rocketchat-channel-settings/client/views/channelSettings.js +++ b/packages/rocketchat-channel-settings/client/views/channelSettings.js @@ -5,10 +5,13 @@ import { TAPi18n } from 'meteor/tap:i18n'; import toastr from 'toastr'; import moment from 'moment'; import s from 'underscore.string'; -import { call, erase, hide, leave, RocketChat, RoomSettingsEnum } from 'meteor/rocketchat:lib'; -import { modal, ChatRoom, popover } from 'meteor/rocketchat:ui'; -import { hasPermission } from 'meteor/rocketchat:authorization'; -import { t } from 'meteor/rocketchat:utils'; +import { modal, popover, call, erase, hide, leave } from 'meteor/rocketchat:ui-utils'; +import { ChatRoom, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { hasPermission, hasAllPermission, hasRole, hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { t, roomTypes, RoomSettingsEnum } from 'meteor/rocketchat:utils'; +import { ChannelSettings } from '../lib/ChannelSettings'; const common = { canLeaveRoom() { @@ -23,11 +26,11 @@ const common = { }); const roomType = room && room.t; - return roomType && RocketChat.roomTypes.roomTypes[roomType].canBeDeleted(hasPermission, room); + return roomType && roomTypes.roomTypes[roomType].canBeDeleted(hasPermission, room); }, canEditRoom() { const { _id } = Template.instance().room; - return RocketChat.authz.hasAllPermission('edit-room', _id); + return hasAllPermission('edit-room', _id); }, isDirectMessage() { const { room } = Template.instance(); @@ -44,7 +47,7 @@ function roomFilesOnly(room) { return room.retention.filesOnly; } - return RocketChat.settings.get('RetentionPolicy_FilesOnly'); + return settings.get('RetentionPolicy_FilesOnly'); } function roomExcludePinned(room) { @@ -56,27 +59,27 @@ function roomExcludePinned(room) { return room.retention.excludePinned; } - return RocketChat.settings.get('RetentionPolicy_ExcludePinned'); + return settings.get('RetentionPolicy_ExcludePinned'); } function roomHasGlobalPurge(room) { - if (!RocketChat.settings.get('RetentionPolicy_Enabled')) { + if (!settings.get('RetentionPolicy_Enabled')) { return false; } switch (room.t) { case 'c': - return RocketChat.settings.get('RetentionPolicy_AppliesToChannels'); + return settings.get('RetentionPolicy_AppliesToChannels'); case 'p': - return RocketChat.settings.get('RetentionPolicy_AppliesToGroups'); + return settings.get('RetentionPolicy_AppliesToGroups'); case 'd': - return RocketChat.settings.get('RetentionPolicy_AppliesToDMs'); + return settings.get('RetentionPolicy_AppliesToDMs'); } return false; } function roomHasPurge(room) { - if (!room || !RocketChat.settings.get('RetentionPolicy_Enabled')) { + if (!room || !settings.get('RetentionPolicy_Enabled')) { return false; } @@ -90,11 +93,11 @@ function roomHasPurge(room) { function retentionEnabled({ t: type }) { switch (type) { case 'c': - return RocketChat.settings.get('RetentionPolicy_AppliesToChannels'); + return settings.get('RetentionPolicy_AppliesToChannels'); case 'p': - return RocketChat.settings.get('RetentionPolicy_AppliesToGroups'); + return settings.get('RetentionPolicy_AppliesToGroups'); case 'd': - return RocketChat.settings.get('RetentionPolicy_AppliesToDMs'); + return settings.get('RetentionPolicy_AppliesToDMs'); } return false; } @@ -102,11 +105,11 @@ function retentionEnabled({ t: type }) { function roomMaxAgeDefault(type) { switch (type) { case 'c': - return RocketChat.settings.get('RetentionPolicy_MaxAge_Channels'); + return settings.get('RetentionPolicy_MaxAge_Channels'); case 'p': - return RocketChat.settings.get('RetentionPolicy_MaxAge_Groups'); + return settings.get('RetentionPolicy_MaxAge_Groups'); case 'd': - return RocketChat.settings.get('RetentionPolicy_MaxAge_DMs'); + return settings.get('RetentionPolicy_MaxAge_DMs'); default: return 30; // days } @@ -125,10 +128,10 @@ function roomMaxAge(room) { } const fixRoomName = (old) => { - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { + if (settings.get('UI_Allow_room_names_with_special_chars')) { return old; } - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return [...old.replace(' ', '').toLocaleLowerCase()].filter((f) => reg.test(f)).join(''); }; @@ -210,13 +213,13 @@ Template.channelSettingsEditing.onCreated(function() { type: 'text', label: 'Name', canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.NAME); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.NAME); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, getValue() { - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { + if (settings.get('UI_Allow_room_names_with_special_chars')) { return room.fname || room.name; } @@ -225,9 +228,9 @@ Template.channelSettingsEditing.onCreated(function() { save(value) { let nameValidation; - if (!RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { + if (!settings.get('UI_Allow_room_names_with_special_chars')) { try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (error1) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } @@ -241,7 +244,7 @@ Template.channelSettingsEditing.onCreated(function() { } } return call('saveRoomSettings', room._id, RoomSettingsEnum.NAME, value).then(function() { - RocketChat.callbacks.run('roomNameChanged', { + callbacks.run('roomNameChanged', { _id: room._id, name: value, }); @@ -254,15 +257,15 @@ Template.channelSettingsEditing.onCreated(function() { type: 'markdown', label: 'Topic', canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.TOPIC); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.TOPIC); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, RoomSettingsEnum.TOPIC, value).then(function() { toastr.success(t('Room_topic_changed_successfully')); - return RocketChat.callbacks.run('roomTopicChanged', room); + return callbacks.run('roomTopicChanged', room); }); }, }, @@ -273,15 +276,15 @@ Template.channelSettingsEditing.onCreated(function() { return Template.instance().room.announcement; }, canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.ANNOUNCEMENT); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.ANNOUNCEMENT); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, RoomSettingsEnum.ANNOUNCEMENT, value).then(() => { toastr.success(t('Room_announcement_changed_successfully')); - return RocketChat.callbacks.run('roomAnnouncementChanged', room); + return callbacks.run('roomAnnouncementChanged', room); }); }, }, @@ -289,10 +292,10 @@ Template.channelSettingsEditing.onCreated(function() { type: 'text', label: 'Description', canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.DESCRIPTION); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.DESCRIPTION); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, RoomSettingsEnum.DESCRIPTION, value).then(function() { @@ -311,11 +314,11 @@ Template.channelSettingsEditing.onCreated(function() { return room.t === 'p'; }, disabled() { - return room.default && !RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return room.default && !hasRole(Meteor.userId(), 'admin'); }, message() { - if (RocketChat.authz.hasAllPermission('edit-room', room._id) && room.default) { - if (!RocketChat.authz.hasRole(Meteor.userId(), 'admin')) { + if (hasAllPermission('edit-room', room._id) && room.default) { + if (!hasRole(Meteor.userId(), 'admin')) { return 'Room_type_of_default_rooms_cant_be_changed'; } } @@ -323,24 +326,24 @@ Template.channelSettingsEditing.onCreated(function() { canView() { if (!['c', 'p'].includes(room.t)) { return false; - } else if (room.t === 'p' && !RocketChat.authz.hasAllPermission('create-c')) { + } else if (room.t === 'p' && !hasAllPermission('create-c')) { return false; - } else if (room.t === 'c' && !RocketChat.authz.hasAllPermission('create-p')) { + } else if (room.t === 'c' && !hasAllPermission('create-p')) { return false; } return true; }, canEdit() { - return (RocketChat.authz.hasAllPermission('edit-room', room._id) && !room.default) || RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return (hasAllPermission('edit-room', room._id) && !room.default) || hasRole(Meteor.userId(), 'admin'); }, save(value) { const saveRoomSettings = () => { value = value ? 'p' : 'c'; - RocketChat.callbacks.run('roomTypeChanged', room); + callbacks.run('roomTypeChanged', room); return call('saveRoomSettings', room._id, 'roomType', value).then(() => toastr.success(t('Room_type_changed_successfully'))); }; if (room.default) { - if (RocketChat.authz.hasRole(Meteor.userId(), 'admin')) { + if (hasRole(Meteor.userId(), 'admin')) { return new Promise((resolve, reject) => { modal.open({ title: t('Room_default_change_to_private_will_be_default_no_more'), @@ -371,10 +374,10 @@ Template.channelSettingsEditing.onCreated(function() { isToggle: true, processing: new ReactiveVar(false), canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.READ_ONLY); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.READ_ONLY); }, canEdit() { - return !room.broadcast && RocketChat.authz.hasAllPermission('set-readonly', room._id); + return !room.broadcast && hasAllPermission('set-readonly', room._id); }, save(value) { return call('saveRoomSettings', room._id, RoomSettingsEnum.READ_ONLY, value).then(() => toastr.success(t('Read_only_changed_successfully'))); @@ -386,10 +389,10 @@ Template.channelSettingsEditing.onCreated(function() { isToggle: true, processing: new ReactiveVar(false), canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.REACT_WHEN_READ_ONLY); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.REACT_WHEN_READ_ONLY); }, canEdit() { - return !room.broadcast && RocketChat.authz.hasAllPermission('set-react-when-readonly', room._id); + return !room.broadcast && hasAllPermission('set-react-when-readonly', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'reactWhenReadOnly', value).then(() => { @@ -403,7 +406,7 @@ Template.channelSettingsEditing.onCreated(function() { isToggle: true, processing: new ReactiveVar(false), canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange( + return roomTypes.roomTypes[room.t].allowRoomSettingChange( room, RoomSettingsEnum.SYSTEM_MESSAGES ); @@ -412,7 +415,7 @@ Template.channelSettingsEditing.onCreated(function() { return room.sysMes !== false; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'systemMessages', value).then( @@ -430,10 +433,10 @@ Template.channelSettingsEditing.onCreated(function() { isToggle: true, processing: new ReactiveVar(false), canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.ARCHIVE_OR_UNARCHIVE); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.ARCHIVE_OR_UNARCHIVE); }, canEdit() { - return RocketChat.authz.hasAtLeastOnePermission(['archive-room', 'unarchive-room'], room._id); + return hasAtLeastOnePermission(['archive-room', 'unarchive-room'], room._id); }, save(value) { return new Promise((resolve, reject) => { @@ -457,7 +460,7 @@ Template.channelSettingsEditing.onCreated(function() { timer: 2000, showConfirmButton: false, }); - return RocketChat.callbacks.run(action, room); + return callbacks.run(action, room); })); } return reject(); @@ -471,7 +474,7 @@ Template.channelSettingsEditing.onCreated(function() { isToggle: true, processing: new ReactiveVar(false), canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.BROADCAST); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.BROADCAST); }, canEdit() { return false; @@ -486,10 +489,10 @@ Template.channelSettingsEditing.onCreated(function() { showingValue: new ReactiveVar(false), realValue: null, canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.JOIN_CODE) && RocketChat.authz.hasAllPermission('edit-room', room._id); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.JOIN_CODE) && hasAllPermission('edit-room', room._id); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, getValue() { if (this.showingValue.get()) { @@ -522,7 +525,7 @@ Template.channelSettingsEditing.onCreated(function() { save(value) { return call('saveRoomSettings', room._id, 'joinCode', value).then(function() { toastr.success(t('Room_password_changed_successfully')); - return RocketChat.callbacks.run('roomCodeChanged', room); + return callbacks.run('roomCodeChanged', room); }); }, }, @@ -538,7 +541,7 @@ Template.channelSettingsEditing.onCreated(function() { return true; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'retentionEnabled', value).then(() => toastr.success(t('Retention_setting_changed_successfully'))); @@ -556,10 +559,10 @@ Template.channelSettingsEditing.onCreated(function() { return true; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-privileged-setting', room._id); + return hasAllPermission('edit-privileged-setting', room._id); }, disabled() { - return !RocketChat.authz.hasAllPermission('edit-privileged-setting', room._id); + return !hasAllPermission('edit-privileged-setting', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'retentionOverrideGlobal', value).then( @@ -583,7 +586,7 @@ Template.channelSettingsEditing.onCreated(function() { return true; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'retentionMaxAge', value).then( @@ -607,7 +610,7 @@ Template.channelSettingsEditing.onCreated(function() { return true; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'retentionExcludePinned', value).then( @@ -631,7 +634,7 @@ Template.channelSettingsEditing.onCreated(function() { return true; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'retentionFilesOnly', value).then( @@ -649,10 +652,10 @@ Template.channelSettingsEditing.onCreated(function() { isToggle: true, processing: new ReactiveVar(false), canView() { - return RocketChat.roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.E2E); + return roomTypes.roomTypes[room.t].allowRoomSettingChange(room, RoomSettingsEnum.E2E); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', room._id); + return hasAllPermission('edit-room', room._id); }, save(value) { return call('saveRoomSettings', room._id, 'encrypted', value).then(() => { @@ -693,7 +696,7 @@ Template.channelSettingsEditing.helpers({ return text === text2 ? '' : ret; }, getIcon(room) { - const roomType = RocketChat.models.Rooms.findOne(room._id).t; + const roomType = Rooms.findOne(room._id).t; switch (roomType) { case 'd': return 'at'; @@ -715,7 +718,7 @@ Template.channelSettingsEditing.helpers({ }, isDisabled(field, room) { const setting = Template.instance().settings[field]; - return (typeof setting.disabled === 'function' && setting.disabled(room)) || setting.processing.get() || !RocketChat.authz.hasAllPermission('edit-room', room._id); + return (typeof setting.disabled === 'function' && setting.disabled(room)) || setting.processing.get() || !hasAllPermission('edit-room', room._id); }, unscape(value) { return s.unescapeHTML(value); @@ -723,7 +726,7 @@ Template.channelSettingsEditing.helpers({ hasRetentionPermission() { const { room } = Template.instance(); - return RocketChat.settings.get('RetentionPolicy_Enabled') && RocketChat.authz.hasAllPermission('edit-room-retention-policy', room._id); + return settings.get('RetentionPolicy_Enabled') && hasAllPermission('edit-room-retention-policy', room._id); }, subValue(value) { if (value === undefined) { @@ -792,7 +795,7 @@ Template.channelSettingsInfo.helpers({ return s.unescapeHTML(value); }, channelSettings() { - return RocketChat.ChannelSettings.getOptions(Template.currentData(), 'room'); + return ChannelSettings.getOptions(Template.currentData(), 'room'); }, name() { return Template.instance().room.name; diff --git a/packages/rocketchat-channel-settings/package.js b/packages/rocketchat-channel-settings/package.js index a64ec9158090..0c0406a1da5a 100644 --- a/packages/rocketchat-channel-settings/package.js +++ b/packages/rocketchat-channel-settings/package.js @@ -11,9 +11,9 @@ Package.onUse(function(api) { 'reactive-var', 'tracker', 'templating', - 'rocketchat:lib', 'rocketchat:authorization', - 'rocketchat:ui', + 'rocketchat:settings', + 'rocketchat:callbacks', 'rocketchat:ui-utils', 'rocketchat:utils', 'rocketchat:models', diff --git a/packages/rocketchat-channel-settings/server/functions/saveReactWhenReadOnly.js b/packages/rocketchat-channel-settings/server/functions/saveReactWhenReadOnly.js index 23237f9316bf..e7716b8148c2 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveReactWhenReadOnly.js +++ b/packages/rocketchat-channel-settings/server/functions/saveReactWhenReadOnly.js @@ -1,11 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; -RocketChat.saveReactWhenReadOnly = function(rid, allowReact) { +export const saveReactWhenReadOnly = function(rid, allowReact) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveReactWhenReadOnly' }); } - return RocketChat.models.Rooms.setAllowReactingWhenReadOnlyById(rid, allowReact); + return Rooms.setAllowReactingWhenReadOnlyById(rid, allowReact); }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomAnnouncement.js b/packages/rocketchat-channel-settings/server/functions/saveRoomAnnouncement.js index 82c7621936a2..666d5347d3c7 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomAnnouncement.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomAnnouncement.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; -RocketChat.saveRoomAnnouncement = function(rid, roomAnnouncement, user, sendMessage = true) { +export const saveRoomAnnouncement = function(rid, roomAnnouncement, user, sendMessage = true) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomAnnouncement' }); } @@ -15,9 +15,9 @@ RocketChat.saveRoomAnnouncement = function(rid, roomAnnouncement, user, sendMess ({ message, ...announcementDetails } = roomAnnouncement); } - const updated = RocketChat.models.Rooms.setAnnouncementById(rid, message, announcementDetails); + const updated = Rooms.setAnnouncementById(rid, message, announcementDetails); if (updated && sendMessage) { - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_announcement', rid, message, user); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_announcement', rid, message, user); } return updated; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomCustomFields.js b/packages/rocketchat-channel-settings/server/functions/saveRoomCustomFields.js index c39dc662a7f6..550203975ac9 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomCustomFields.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomCustomFields.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; -RocketChat.saveRoomCustomFields = function(rid, roomCustomFields) { +export const saveRoomCustomFields = function(rid, roomCustomFields) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomCustomFields', @@ -13,10 +13,10 @@ RocketChat.saveRoomCustomFields = function(rid, roomCustomFields) { function: 'RocketChat.saveRoomCustomFields', }); } - const ret = RocketChat.models.Rooms.setCustomFieldsById(rid, roomCustomFields); + const ret = Rooms.setCustomFieldsById(rid, roomCustomFields); // Update customFields of any user's Subscription related with this rid - RocketChat.models.Subscriptions.updateCustomFieldsByRoomId(rid, roomCustomFields); + Subscriptions.updateCustomFieldsByRoomId(rid, roomCustomFields); return ret; }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomDescription.js b/packages/rocketchat-channel-settings/server/functions/saveRoomDescription.js index c515e6b44eaf..4c472db0c1ec 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomDescription.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomDescription.js @@ -1,15 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; -RocketChat.saveRoomDescription = function(rid, roomDescription, user) { +export const saveRoomDescription = function(rid, roomDescription, user) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomDescription', }); } - const update = RocketChat.models.Rooms.setDescriptionById(rid, roomDescription); - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_description', rid, roomDescription, user); + const update = Rooms.setDescriptionById(rid, roomDescription); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_description', rid, roomDescription, user); return update; }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomName.js b/packages/rocketchat-channel-settings/server/functions/saveRoomName.js index 32c9f9aaf7a1..0848cb7ca9db 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomName.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomName.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages, Subscriptions } from 'meteor/rocketchat:models'; +import { roomTypes, getValidRoomName } from 'meteor/rocketchat:utils'; -RocketChat.saveRoomName = function(rid, displayName, user, sendMessage = true) { - const room = RocketChat.models.Rooms.findOneById(rid); - if (RocketChat.roomTypes.roomTypes[room.t].preventRenaming()) { +export const saveRoomName = function(rid, displayName, user, sendMessage = true) { + const room = Rooms.findOneById(rid); + if (roomTypes.roomTypes[room.t].preventRenaming()) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { function: 'RocketChat.saveRoomdisplayName', }); @@ -12,12 +13,12 @@ RocketChat.saveRoomName = function(rid, displayName, user, sendMessage = true) { return; } - const slugifiedRoomName = RocketChat.getValidRoomName(displayName, rid); + const slugifiedRoomName = getValidRoomName(displayName, rid); - const update = RocketChat.models.Rooms.setNameById(rid, slugifiedRoomName, displayName) && RocketChat.models.Subscriptions.updateNameAndAlertByRoomId(rid, slugifiedRoomName, displayName); + const update = Rooms.setNameById(rid, slugifiedRoomName, displayName) && Subscriptions.updateNameAndAlertByRoomId(rid, slugifiedRoomName, displayName); if (update && sendMessage) { - RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser(rid, displayName, user); + Messages.createRoomRenamedWithRoomIdRoomNameAndUser(rid, displayName, user); } return displayName; }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomReadOnly.js b/packages/rocketchat-channel-settings/server/functions/saveRoomReadOnly.js index 7db4b0610afd..4710d035b80b 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomReadOnly.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomReadOnly.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; -RocketChat.saveRoomReadOnly = function(rid, readOnly) { +export const saveRoomReadOnly = function(rid, readOnly) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomReadOnly', }); } - return RocketChat.models.Rooms.setReadOnlyById(rid, readOnly); + return Rooms.setReadOnlyById(rid, readOnly, hasPermission); }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomSystemMessages.js b/packages/rocketchat-channel-settings/server/functions/saveRoomSystemMessages.js index 26bc61e1e03d..7f29eb05f015 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomSystemMessages.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomSystemMessages.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; -RocketChat.saveRoomSystemMessages = function(rid, systemMessages) { +export const saveRoomSystemMessages = function(rid, systemMessages) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomSystemMessages', }); } - return RocketChat.models.Rooms.setSystemMessagesById(rid, systemMessages); + return Rooms.setSystemMessagesById(rid, systemMessages); }; diff --git a/packages/rocketchat-tokenpass/server/functions/saveRoomTokens.js b/packages/rocketchat-channel-settings/server/functions/saveRoomTokens.js similarity index 56% rename from packages/rocketchat-tokenpass/server/functions/saveRoomTokens.js rename to packages/rocketchat-channel-settings/server/functions/saveRoomTokens.js index 8347954d1bbb..dfb431751929 100644 --- a/packages/rocketchat-tokenpass/server/functions/saveRoomTokens.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomTokens.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; -RocketChat.saveRoomTokenpass = function(rid, tokenpass) { +export const saveRoomTokenpass = function(rid, tokenpass) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomTokens', }); } - return RocketChat.models.Rooms.setTokenpassById(rid, tokenpass); + return Rooms.setTokenpassById(rid, tokenpass); }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomTopic.js b/packages/rocketchat-channel-settings/server/functions/saveRoomTopic.js index 7a76f6fb6f97..527ae6465f02 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomTopic.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomTopic.js @@ -1,17 +1,17 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; -RocketChat.saveRoomTopic = function(rid, roomTopic, user, sendMessage = true) { +export const saveRoomTopic = function(rid, roomTopic, user, sendMessage = true) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomTopic', }); } - const update = RocketChat.models.Rooms.setTopicById(rid, roomTopic); + const update = Rooms.setTopicById(rid, roomTopic); if (update && sendMessage) { - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', rid, roomTopic, user); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', rid, roomTopic, user); } return update; }; diff --git a/packages/rocketchat-channel-settings/server/functions/saveRoomType.js b/packages/rocketchat-channel-settings/server/functions/saveRoomType.js index a495c2b270b8..1ef3166115ef 100644 --- a/packages/rocketchat-channel-settings/server/functions/saveRoomType.js +++ b/packages/rocketchat-channel-settings/server/functions/saveRoomType.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions, Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.saveRoomType = function(rid, roomType, user, sendMessage = true) { +export const saveRoomType = function(rid, roomType, user, sendMessage = true) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomType', @@ -15,7 +16,7 @@ RocketChat.saveRoomType = function(rid, roomType, user, sendMessage = true) { type: roomType, }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (room == null) { throw new Meteor.Error('error-invalid-room', 'error-invalid-room', { function: 'RocketChat.saveRoomType', @@ -27,19 +28,19 @@ RocketChat.saveRoomType = function(rid, roomType, user, sendMessage = true) { function: 'RocketChat.saveRoomType', }); } - const result = RocketChat.models.Rooms.setTypeById(rid, roomType) && RocketChat.models.Subscriptions.updateTypeByRoomId(rid, roomType); + const result = Rooms.setTypeById(rid, roomType) && Subscriptions.updateTypeByRoomId(rid, roomType); if (result && sendMessage) { let message; if (roomType === 'c') { message = TAPi18n.__('Channel', { - lng: (user && user.language) || RocketChat.settings.get('language') || 'en', + lng: (user && user.language) || settings.get('language') || 'en', }); } else { message = TAPi18n.__('Private_Group', { - lng: (user && user.language) || RocketChat.settings.get('language') || 'en', + lng: (user && user.language) || settings.get('language') || 'en', }); } - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_privacy', rid, message, user); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_privacy', rid, message, user); } return result; }; diff --git a/packages/rocketchat-livestream/server/functions/saveStreamingOptions.js b/packages/rocketchat-channel-settings/server/functions/saveStreamingOptions.js similarity index 72% rename from packages/rocketchat-livestream/server/functions/saveStreamingOptions.js rename to packages/rocketchat-channel-settings/server/functions/saveStreamingOptions.js index dd99a85d16e2..bc7add5ceacf 100644 --- a/packages/rocketchat-livestream/server/functions/saveStreamingOptions.js +++ b/packages/rocketchat-channel-settings/server/functions/saveStreamingOptions.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; -RocketChat.saveStreamingOptions = function(rid, options) { +export const saveStreamingOptions = function(rid, options) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveStreamingOptions', @@ -18,5 +18,5 @@ RocketChat.saveStreamingOptions = function(rid, options) { message: Match.Optional(String), }); - RocketChat.models.Rooms.setStreamingOptionsById(rid, options); + Rooms.setStreamingOptionsById(rid, options); }; diff --git a/packages/rocketchat-channel-settings/server/index.js b/packages/rocketchat-channel-settings/server/index.js index 02ce04779f0d..9b86dcca63f5 100644 --- a/packages/rocketchat-channel-settings/server/index.js +++ b/packages/rocketchat-channel-settings/server/index.js @@ -1,13 +1,5 @@ import './startup'; -import './models/Messages'; -import './models/Rooms'; -import './functions/saveReactWhenReadOnly'; -import './functions/saveRoomAnnouncement'; -import './functions/saveRoomCustomFields'; -import './functions/saveRoomDescription'; -import './functions/saveRoomName'; -import './functions/saveRoomReadOnly'; -import './functions/saveRoomSystemMessages'; -import './functions/saveRoomTopic'; -import './functions/saveRoomType'; +export { saveRoomTopic } from './functions/saveRoomTopic'; +export { saveStreamingOptions } from './functions/saveStreamingOptions'; +export { saveRoomName } from './functions/saveRoomName'; import './methods/saveRoomSettings'; diff --git a/packages/rocketchat-channel-settings/server/methods/saveRoomSettings.js b/packages/rocketchat-channel-settings/server/methods/saveRoomSettings.js index ec4370040806..4477411577d1 100644 --- a/packages/rocketchat-channel-settings/server/methods/saveRoomSettings.js +++ b/packages/rocketchat-channel-settings/server/methods/saveRoomSettings.js @@ -1,6 +1,18 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; +import { saveRoomName } from '../functions/saveRoomName'; +import { saveRoomTopic } from '../functions/saveRoomTopic'; +import { saveRoomAnnouncement } from '../functions/saveRoomAnnouncement'; +import { saveRoomCustomFields } from '../functions/saveRoomCustomFields'; +import { saveRoomDescription } from '../functions/saveRoomDescription'; +import { saveRoomType } from '../functions/saveRoomType'; +import { saveRoomReadOnly } from '../functions/saveRoomReadOnly'; +import { saveReactWhenReadOnly } from '../functions/saveReactWhenReadOnly'; +import { saveRoomSystemMessages } from '../functions/saveRoomSystemMessages'; +import { saveRoomTokenpass } from '../functions/saveRoomTokens'; +import { saveStreamingOptions } from '../functions/saveStreamingOptions'; const fields = ['roomName', 'roomTopic', 'roomAnnouncement', 'roomCustomFields', 'roomDescription', 'roomType', 'readOnly', 'reactWhenReadOnly', 'systemMessages', 'default', 'joinCode', 'tokenpass', 'streamingOptions', 'retentionEnabled', 'retentionMaxAge', 'retentionExcludePinned', 'retentionFilesOnly', 'retentionOverrideGlobal', 'encrypted']; Meteor.methods({ @@ -30,14 +42,14 @@ Meteor.methods({ }); } - if (!RocketChat.authz.hasPermission(userId, 'edit-room', rid)) { + if (!hasPermission(userId, 'edit-room', rid)) { throw new Meteor.Error('error-action-not-allowed', 'Editing room is not allowed', { method: 'saveRoomSettings', action: 'Editing_room', }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { @@ -58,19 +70,19 @@ Meteor.methods({ Object.keys(settings).forEach((setting) => { const value = settings[setting]; - if (settings === 'default' && !RocketChat.authz.hasPermission(userId, 'view-room-administration')) { + if (settings === 'default' && !hasPermission(userId, 'view-room-administration')) { throw new Meteor.Error('error-action-not-allowed', 'Viewing room administration is not allowed', { method: 'saveRoomSettings', action: 'Viewing_room_administration', }); } - if (setting === 'roomType' && value !== room.t && value === 'c' && !RocketChat.authz.hasPermission(userId, 'create-c')) { + if (setting === 'roomType' && value !== room.t && value === 'c' && !hasPermission(userId, 'create-c')) { throw new Meteor.Error('error-action-not-allowed', 'Changing a private group to a public channel is not allowed', { method: 'saveRoomSettings', action: 'Change_Room_Type', }); } - if (setting === 'roomType' && value !== room.t && value === 'p' && !RocketChat.authz.hasPermission(userId, 'create-p')) { + if (setting === 'roomType' && value !== room.t && value === 'p' && !hasPermission(userId, 'create-p')) { throw new Meteor.Error('error-action-not-allowed', 'Changing a public channel to a private room is not allowed', { method: 'saveRoomSettings', action: 'Change_Room_Type', @@ -83,25 +95,25 @@ Meteor.methods({ }); } - if (setting === 'retentionEnabled' && !RocketChat.authz.hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.enabled) { + if (setting === 'retentionEnabled' && !hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.enabled) { throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', { method: 'saveRoomSettings', action: 'Editing_room', }); } - if (setting === 'retentionMaxAge' && !RocketChat.authz.hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.maxAge) { + if (setting === 'retentionMaxAge' && !hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.maxAge) { throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', { method: 'saveRoomSettings', action: 'Editing_room', }); } - if (setting === 'retentionExcludePinned' && !RocketChat.authz.hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.excludePinned) { + if (setting === 'retentionExcludePinned' && !hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.excludePinned) { throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', { method: 'saveRoomSettings', action: 'Editing_room', }); } - if (setting === 'retentionFilesOnly' && !RocketChat.authz.hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.filesOnly) { + if (setting === 'retentionFilesOnly' && !hasPermission(userId, 'edit-room-retention-policy', rid) && value !== room.retention.filesOnly) { throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', { method: 'saveRoomSettings', action: 'Editing_room', @@ -118,31 +130,31 @@ Meteor.methods({ const value = settings[setting]; switch (setting) { case 'roomName': - RocketChat.saveRoomName(rid, value, user); + saveRoomName(rid, value, user); break; case 'roomTopic': if (value !== room.topic) { - RocketChat.saveRoomTopic(rid, value, user); + saveRoomTopic(rid, value, user); } break; case 'roomAnnouncement': if (value !== room.announcement) { - RocketChat.saveRoomAnnouncement(rid, value, user); + saveRoomAnnouncement(rid, value, user); } break; case 'roomCustomFields': if (value !== room.customFields) { - RocketChat.saveRoomCustomFields(rid, value); + saveRoomCustomFields(rid, value); } break; case 'roomDescription': if (value !== room.description) { - RocketChat.saveRoomDescription(rid, value, user); + saveRoomDescription(rid, value, user); } break; case 'roomType': if (value !== room.t) { - RocketChat.saveRoomType(rid, value, user); + saveRoomType(rid, value, user); } break; case 'tokenpass': @@ -153,49 +165,49 @@ Meteor.methods({ balance: String, }], }); - RocketChat.saveRoomTokenpass(rid, value); + saveRoomTokenpass(rid, value); break; case 'streamingOptions': - RocketChat.saveStreamingOptions(rid, value); + saveStreamingOptions(rid, value); break; case 'readOnly': if (value !== room.ro) { - RocketChat.saveRoomReadOnly(rid, value, user); + saveRoomReadOnly(rid, value, user); } break; case 'reactWhenReadOnly': if (value !== room.reactWhenReadOnly) { - RocketChat.saveReactWhenReadOnly(rid, value, user); + saveReactWhenReadOnly(rid, value, user); } break; case 'systemMessages': if (value !== room.sysMes) { - RocketChat.saveRoomSystemMessages(rid, value, user); + saveRoomSystemMessages(rid, value, user); } break; case 'joinCode': - RocketChat.models.Rooms.setJoinCodeById(rid, String(value)); + Rooms.setJoinCodeById(rid, String(value)); break; case 'default': - RocketChat.models.Rooms.saveDefaultById(rid, value); + Rooms.saveDefaultById(rid, value); break; case 'retentionEnabled': - RocketChat.models.Rooms.saveRetentionEnabledById(rid, value); + Rooms.saveRetentionEnabledById(rid, value); break; case 'retentionMaxAge': - RocketChat.models.Rooms.saveRetentionMaxAgeById(rid, value); + Rooms.saveRetentionMaxAgeById(rid, value); break; case 'retentionExcludePinned': - RocketChat.models.Rooms.saveRetentionExcludePinnedById(rid, value); + Rooms.saveRetentionExcludePinnedById(rid, value); break; case 'retentionFilesOnly': - RocketChat.models.Rooms.saveRetentionFilesOnlyById(rid, value); + Rooms.saveRetentionFilesOnlyById(rid, value); break; case 'retentionOverrideGlobal': - RocketChat.models.Rooms.saveRetentionOverrideGlobalById(rid, value); + Rooms.saveRetentionOverrideGlobalById(rid, value); break; case 'encrypted': - RocketChat.models.Rooms.saveEncryptedById(rid, value); + Rooms.saveEncryptedById(rid, value); break; } }); diff --git a/packages/rocketchat-channel-settings/server/models/Messages.js b/packages/rocketchat-channel-settings/server/models/Messages.js deleted file mode 100644 index 2e8b4ee5812c..000000000000 --- a/packages/rocketchat-channel-settings/server/models/Messages.js +++ /dev/null @@ -1,9 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser = function(type, roomId, message, user, extraData) { - return this.createWithTypeRoomIdMessageAndUser(type, roomId, message, user, extraData); -}; - -RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser = function(roomId, roomName, user, extraData) { - return this.createWithTypeRoomIdMessageAndUser('r', roomId, roomName, user, extraData); -}; diff --git a/packages/rocketchat-channel-settings/server/models/Rooms.js b/packages/rocketchat-channel-settings/server/models/Rooms.js deleted file mode 100644 index 6dae5225e441..000000000000 --- a/packages/rocketchat-channel-settings/server/models/Rooms.js +++ /dev/null @@ -1,67 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.setDescriptionById = function(_id, description) { - const query = { - _id, - }; - const update = { - $set: { - description, - }, - }; - return this.update(query, update); -}; - -RocketChat.models.Rooms.setReadOnlyById = function(_id, readOnly) { - const query = { - _id, - }; - const update = { - $set: { - ro: readOnly, - muted: [], - }, - }; - if (readOnly) { - RocketChat.models.Subscriptions.findByRoomIdWhenUsernameExists(_id, { fields: { 'u._id': 1, 'u.username': 1 } }).forEach(function({ u: user }) { - if (RocketChat.authz.hasPermission(user._id, 'post-readonly')) { - return; - } - return update.$set.muted.push(user.username); - }); - } else { - update.$unset = { - muted: '', - }; - } - - if (update.$set.muted.length === 0) { - delete update.$set.muted; - } - - return this.update(query, update); -}; - -RocketChat.models.Rooms.setAllowReactingWhenReadOnlyById = function(_id, allowReacting) { - const query = { - _id, - }; - const update = { - $set: { - reactWhenReadOnly: allowReacting, - }, - }; - return this.update(query, update); -}; - -RocketChat.models.Rooms.setSystemMessagesById = function(_id, systemMessages) { - const query = { - _id, - }; - const update = { - $set: { - sysMes: systemMessages, - }, - }; - return this.update(query, update); -}; diff --git a/packages/rocketchat-channel-settings/server/startup.js b/packages/rocketchat-channel-settings/server/startup.js index 81e6fde8d366..3f8b133568ee 100644 --- a/packages/rocketchat-channel-settings/server/startup.js +++ b/packages/rocketchat-channel-settings/server/startup.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Permissions } from 'meteor/rocketchat:models'; Meteor.startup(function() { - RocketChat.models.Permissions.upsert('post-readonly', { $setOnInsert: { roles: ['admin', 'owner', 'moderator'] } }); - RocketChat.models.Permissions.upsert('set-readonly', { $setOnInsert: { roles: ['admin', 'owner'] } }); - RocketChat.models.Permissions.upsert('set-react-when-readonly', { $setOnInsert: { roles: ['admin', 'owner'] } }); + Permissions.upsert('post-readonly', { $setOnInsert: { roles: ['admin', 'owner', 'moderator'] } }); + Permissions.upsert('set-readonly', { $setOnInsert: { roles: ['admin', 'owner'] } }); + Permissions.upsert('set-react-when-readonly', { $setOnInsert: { roles: ['admin', 'owner'] } }); }); diff --git a/packages/rocketchat-lib/client/lib/ChannelSettings.js b/packages/rocketchat-lib/client/lib/ChannelSettings.js new file mode 100644 index 000000000000..18d993c4ac86 --- /dev/null +++ b/packages/rocketchat-lib/client/lib/ChannelSettings.js @@ -0,0 +1,3 @@ +import { ChannelSettings } from 'meteor/rocketchat:channel-settings'; + +RocketChat.ChannelSettings = ChannelSettings; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index ec54d31666c1..c8f66f40ee41 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -55,6 +55,7 @@ Package.onUse(function(api) { api.use('rocketchat:action-links'); api.use('rocketchat:assets'); api.use('rocketchat:markdown'); + api.use('rocketchat:channel-settings'); api.use('templating', 'client'); api.use('kadira:flow-router'); @@ -140,6 +141,8 @@ Package.onUse(function(api) { api.addFiles('server/functions/Notifications.js', 'server'); api.addFiles('server/functions/authorization.js', 'server'); api.addFiles('server/functions/getUsernameSuggestion.js', 'server'); + api.addFiles('server/functions/saveRoomTopic.js', 'server'); + api.addFiles('server/functions/saveRoomName.js', 'server'); // SERVER LIB api.addFiles('server/lib/configLogger.js', 'server'); @@ -250,6 +253,7 @@ Package.onUse(function(api) { api.addFiles('client/lib/EmojiPicker.js', 'client'); api.addFiles('client/lib/ui-buttons.js', 'client'); api.addFiles('client/lib/sandstorm.js', 'client'); + api.addFiles('client/lib/ChannelSettings.js', 'client'); // CLIENT LIB STARTUP api.addFiles('client/lib/startup/commands.js', 'client'); diff --git a/packages/rocketchat-lib/server/functions/saveRoomName.js b/packages/rocketchat-lib/server/functions/saveRoomName.js new file mode 100644 index 000000000000..2737abf35298 --- /dev/null +++ b/packages/rocketchat-lib/server/functions/saveRoomName.js @@ -0,0 +1,3 @@ +import { saveRoomName } from 'meteor/rocketchat:channel-settings'; + +RocketChat.saveRoomName = saveRoomName; diff --git a/packages/rocketchat-lib/server/functions/saveRoomTopic.js b/packages/rocketchat-lib/server/functions/saveRoomTopic.js new file mode 100644 index 000000000000..1717eb9e5db5 --- /dev/null +++ b/packages/rocketchat-lib/server/functions/saveRoomTopic.js @@ -0,0 +1,3 @@ +import { saveRoomTopic } from 'meteor/rocketchat:channel-settings'; + +RocketChat.saveRoomTopic = saveRoomTopic; diff --git a/packages/rocketchat-lib/server/functions/saveStreamingOptions.js b/packages/rocketchat-lib/server/functions/saveStreamingOptions.js new file mode 100644 index 000000000000..cfd15ceced6b --- /dev/null +++ b/packages/rocketchat-lib/server/functions/saveStreamingOptions.js @@ -0,0 +1,3 @@ +import { saveStreamingOptions } from 'meteor/rocketchat:channel-settings'; + +RocketChat.saveStreamingOptions = saveStreamingOptions; diff --git a/packages/rocketchat-livestream/server/index.js b/packages/rocketchat-livestream/server/index.js index 0f5c850442a4..9254662a155a 100644 --- a/packages/rocketchat-livestream/server/index.js +++ b/packages/rocketchat-livestream/server/index.js @@ -1,5 +1,3 @@ -import './models/Rooms'; -import './functions/saveStreamingOptions'; import './routes.js'; import './methods.js'; import './settings'; diff --git a/packages/rocketchat-livestream/server/models/Rooms.js b/packages/rocketchat-livestream/server/models/Rooms.js deleted file mode 100644 index 24857be9004c..000000000000 --- a/packages/rocketchat-livestream/server/models/Rooms.js +++ /dev/null @@ -1,10 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.setStreamingOptionsById = function(_id, streamingOptions) { - const update = { - $set: { - streamingOptions, - }, - }; - return this.update({ _id }, update); -}; diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index 72a7fd18b5c5..fb4196f84c79 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -33,6 +33,14 @@ export class Messages extends Base { }); } + createRoomSettingsChangedWithTypeRoomIdMessageAndUser(type, roomId, message, user, extraData) { + return this.createWithTypeRoomIdMessageAndUser(type, roomId, message, user, extraData); + } + + createRoomRenamedWithRoomIdRoomNameAndUser(roomId, roomName, user, extraData) { + return this.createWithTypeRoomIdMessageAndUser('r', roomId, roomName, user, extraData); + } + addTranslations(messageId, translations) { const updateObj = {}; Object.keys(translations).forEach((key) => { diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index de8e7d452296..cd6fb7ff5419 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,94 @@ export class Rooms extends Base { return this.findOne(query, options); } + setDescriptionById(_id, description) { + const query = { + _id, + }; + const update = { + $set: { + description, + }, + }; + return this.update(query, update); + } + + setStreamingOptionsById(_id, streamingOptions) { + const update = { + $set: { + streamingOptions, + }, + }; + return this.update({ _id }, update); + } + + setTokenpassById(_id, tokenpass) { + const update = { + $set: { + tokenpass, + }, + }; + + return this.update({ _id }, update); + } + + setReadOnlyById(_id, readOnly, hasPermission) { + if (!hasPermission) { + throw new Error('You must provide "hasPermission" function to be able to call this method'); + } + const query = { + _id, + }; + const update = { + $set: { + ro: readOnly, + muted: [], + }, + }; + if (readOnly) { + Subscriptions.findByRoomIdWhenUsernameExists(_id, { fields: { 'u._id': 1, 'u.username': 1 } }).forEach(function({ u: user }) { + if (hasPermission(user._id, 'post-readonly')) { + return; + } + return update.$set.muted.push(user.username); + }); + } else { + update.$unset = { + muted: '', + }; + } + + if (update.$set.muted.length === 0) { + delete update.$set.muted; + } + + return this.update(query, update); + } + + setAllowReactingWhenReadOnlyById = function(_id, allowReacting) { + const query = { + _id, + }; + const update = { + $set: { + reactWhenReadOnly: allowReacting, + }, + }; + return this.update(query, update); + } + + setSystemMessagesById = function(_id, systemMessages) { + const query = { + _id, + }; + const update = { + $set: { + sysMes: systemMessages, + }, + }; + return this.update(query, update); + } + setE2eKeyId(_id, e2eKeyId, options) { const query = { _id, diff --git a/packages/rocketchat-tokenpass/server/index.js b/packages/rocketchat-tokenpass/server/index.js index a66961b4bdf9..f0d554955087 100644 --- a/packages/rocketchat-tokenpass/server/index.js +++ b/packages/rocketchat-tokenpass/server/index.js @@ -2,7 +2,6 @@ import '../lib/common'; import './startup'; import './functions/getProtectedTokenpassBalances'; import './functions/getPublicTokenpassBalances'; -import './functions/saveRoomTokens'; import './functions/saveRoomTokensMinimumBalance'; import './functions/updateUserTokenpassBalances'; import './models/indexes'; diff --git a/packages/rocketchat-tokenpass/server/models/Rooms.js b/packages/rocketchat-tokenpass/server/models/Rooms.js index 0919943d7b86..bb7838a3965b 100644 --- a/packages/rocketchat-tokenpass/server/models/Rooms.js +++ b/packages/rocketchat-tokenpass/server/models/Rooms.js @@ -20,16 +20,6 @@ RocketChat.models.Rooms.setTokensById = function(_id, tokens) { return this.update({ _id }, update); }; -RocketChat.models.Rooms.setTokenpassById = function(_id, tokenpass) { - const update = { - $set: { - tokenpass, - }, - }; - - return this.update({ _id }, update); -}; - RocketChat.models.Rooms.findAllTokenChannels = function() { const query = { tokenpass: { $exists: true }, From aff4cfedda4961019c1039e9e8717e53e112ee4a Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 19:22:41 -0200 Subject: [PATCH 20/33] Remove dependency of RC namespace in rc-channel-mail-messages and cloud (#13254) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * Remove dependency of RC namespace in rc-channel-mail-messages * Remove dependency of RC namespace in rc-cloud --- .../client/lib/startup.js | 7 +++--- .../client/views/mailMessagesInstructions.js | 10 ++++---- .../package.js | 6 +++-- .../server/lib/startup.js | 4 +-- .../server/methods/mailMessages.js | 15 ++++++----- packages/rocketchat-cloud/client/index.js | 6 +++-- packages/rocketchat-cloud/package.js | 8 +++++- .../server/functions/connectWorkspace.js | 25 +++++++++++-------- .../functions/finishOAuthAuthorization.js | 14 ++++++----- .../functions/getOAuthAuthorizationUrl.js | 8 +++--- .../server/functions/getRedirectUri.js | 4 ++- .../functions/getWorkspaceAccessTokens.js | 19 ++++++++------ .../server/functions/getWorkspaceLicense.js | 8 +++--- .../functions/retrieveRegistrationStatus.js | 15 ++++++----- packages/rocketchat-cloud/server/index.js | 6 +++-- packages/rocketchat-cloud/server/methods.js | 14 ++++++----- 16 files changed, 102 insertions(+), 67 deletions(-) diff --git a/packages/rocketchat-channel-settings-mail-messages/client/lib/startup.js b/packages/rocketchat-channel-settings-mail-messages/client/lib/startup.js index d255479029d7..9797de2157ec 100644 --- a/packages/rocketchat-channel-settings-mail-messages/client/lib/startup.js +++ b/packages/rocketchat-channel-settings-mail-messages/client/lib/startup.js @@ -1,9 +1,10 @@ // import resetSelection from '../resetSelection'; import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; Meteor.startup(() => { - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'mail-messages', anonymous: true, @@ -11,7 +12,7 @@ Meteor.startup(() => { icon: 'mail', template: 'mailMessagesInstructions', order: 10, - condition: () => RocketChat.authz.hasAllPermission('mail-messages'), + condition: () => hasAllPermission('mail-messages'), }); // RocketChat.callbacks.add('roomExit', () => resetSelection(false), RocketChat.callbacks.priority.MEDIUM, 'room-exit-mail-messages'); diff --git a/packages/rocketchat-channel-settings-mail-messages/client/views/mailMessagesInstructions.js b/packages/rocketchat-channel-settings-mail-messages/client/views/mailMessagesInstructions.js index a21bc68db689..7652e161a4c0 100644 --- a/packages/rocketchat-channel-settings-mail-messages/client/views/mailMessagesInstructions.js +++ b/packages/rocketchat-channel-settings-mail-messages/client/views/mailMessagesInstructions.js @@ -4,15 +4,15 @@ import { Blaze } from 'meteor/blaze'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { AutoComplete } from 'meteor/mizzao:autocomplete'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { ChatRoom } from 'meteor/rocketchat:ui'; -import { t, isEmail } from 'meteor/rocketchat:utils'; +import { ChatRoom } from 'meteor/rocketchat:models'; +import { t, isEmail, handleError, roomTypes } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; import { Deps } from 'meteor/deps'; import toastr from 'toastr'; import resetSelection from '../resetSelection'; const filterNames = (old) => { - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return [...old.replace(' ', '').toLocaleLowerCase()].filter((f) => reg.test(f)).join(''); }; @@ -26,7 +26,7 @@ Template.mailMessagesInstructions.helpers({ }, roomName() { const room = ChatRoom.findOne(Session.get('openedRoom')); - return room && RocketChat.roomTypes.getRoomName(room.t, room); + return room && roomTypes.getRoomName(room.t, room); }, erroredEmails() { const instance = Template.instance(); diff --git a/packages/rocketchat-channel-settings-mail-messages/package.js b/packages/rocketchat-channel-settings-mail-messages/package.js index efd2f3c6e2b8..987adc06f655 100644 --- a/packages/rocketchat-channel-settings-mail-messages/package.js +++ b/packages/rocketchat-channel-settings-mail-messages/package.js @@ -11,8 +11,10 @@ Package.onUse(function(api) { 'templating', 'reactive-var', 'less', - 'rocketchat:lib', - 'rocketchat:channel-settings', + 'rocketchat:ui-utils', + 'rocketchat:models', + 'rocketchat:authorization', + 'rocketchat:settings', 'mizzao:autocomplete', 'mongo', 'rocketchat:utils', diff --git a/packages/rocketchat-channel-settings-mail-messages/server/lib/startup.js b/packages/rocketchat-channel-settings-mail-messages/server/lib/startup.js index 80c7f8e63595..46059654ebd4 100644 --- a/packages/rocketchat-channel-settings-mail-messages/server/lib/startup.js +++ b/packages/rocketchat-channel-settings-mail-messages/server/lib/startup.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Permissions } from 'meteor/rocketchat:models'; Meteor.startup(function() { const permission = { _id: 'mail-messages', roles: ['admin'], }; - return RocketChat.models.Permissions.upsert(permission._id, { + return Permissions.upsert(permission._id, { $setOnInsert: permission, }); }); diff --git a/packages/rocketchat-channel-settings-mail-messages/server/methods/mailMessages.js b/packages/rocketchat-channel-settings-mail-messages/server/methods/mailMessages.js index 1ad34a81a0f8..dc7474961821 100644 --- a/packages/rocketchat-channel-settings-mail-messages/server/methods/mailMessages.js +++ b/packages/rocketchat-channel-settings-mail-messages/server/methods/mailMessages.js @@ -1,6 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Users, Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { Message } from 'meteor/rocketchat:ui-utils'; import _ from 'underscore'; import moment from 'moment'; import * as Mailer from 'meteor/rocketchat:mailer'; @@ -27,7 +30,7 @@ Meteor.methods({ method: 'mailMessages', }); } - if (!RocketChat.authz.hasPermission(userId, 'mail-messages')) { + if (!hasPermission(userId, 'mail-messages')) { throw new Meteor.Error('error-action-not-allowed', 'Mailing is not allowed', { method: 'mailMessages', action: 'Mailing', @@ -38,7 +41,7 @@ Meteor.methods({ const missing = []; if (data.to_users.length > 0) { _.each(data.to_users, (username) => { - const user = RocketChat.models.Users.findOneByUsername(username); + const user = Users.findOneByUsername(username); if (user && user.emails && user.emails[0] && user.emails[0].address) { emails.push(user.emails[0].address); } else { @@ -65,16 +68,16 @@ Meteor.methods({ } } - const html = RocketChat.models.Messages.findByRoomIdAndMessageIds(data.rid, data.messages, { + const html = Messages.findByRoomIdAndMessageIds(data.rid, data.messages, { sort: { ts: 1 }, }).map(function(message) { const dateTime = moment(message.ts).locale(data.language).format('L LT'); - return `

${ message.u.username } ${ dateTime }
${ RocketChat.Message.parse(message, data.language) }

`; + return `

${ message.u.username } ${ dateTime }
${ Message.parse(message, data.language) }

`; }).join(''); Mailer.send({ to: emails, - from: RocketChat.settings.get('From_Email'), + from: settings.get('From_Email'), replyTo: email, subject: data.subject, html, diff --git a/packages/rocketchat-cloud/client/index.js b/packages/rocketchat-cloud/client/index.js index e5dddf8944bf..a96708e89792 100644 --- a/packages/rocketchat-cloud/client/index.js +++ b/packages/rocketchat-cloud/client/index.js @@ -3,6 +3,8 @@ import './admin/cloud'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { FlowRouter } from 'meteor/kadira:flow-router'; +import { AdminBox } from 'meteor/rocketchat:ui-utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; FlowRouter.route('/admin/cloud', { name: 'cloud-config', @@ -18,11 +20,11 @@ FlowRouter.route('/admin/cloud/oauth-callback', { }, }); -RocketChat.AdminBox.addOption({ +AdminBox.addOption({ icon: 'cloud-plus', href: 'admin/cloud', i18nLabel: 'Cloud', permissionGranted() { - return RocketChat.authz.hasAtLeastOnePermission(['manage-cloud']); + return hasAtLeastOnePermission(['manage-cloud']); }, }); diff --git a/packages/rocketchat-cloud/package.js b/packages/rocketchat-cloud/package.js index 52480e9e66d6..5b4307e6f961 100644 --- a/packages/rocketchat-cloud/package.js +++ b/packages/rocketchat-cloud/package.js @@ -8,8 +8,14 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:authorization', + 'rocketchat:models', + 'rocketchat:utils', + 'rocketchat:ui-utils', + 'rocketchat:settings', 'templating', + 'kadira:flow-router', + 'kadira:blaze-layout', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-cloud/server/functions/connectWorkspace.js b/packages/rocketchat-cloud/server/functions/connectWorkspace.js index f34cecd22449..e51e8cb957e0 100644 --- a/packages/rocketchat-cloud/server/functions/connectWorkspace.js +++ b/packages/rocketchat-cloud/server/functions/connectWorkspace.js @@ -1,5 +1,8 @@ import querystring from 'querystring'; + import { HTTP } from 'meteor/http'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings } from 'meteor/rocketchat:models'; import { getRedirectUri } from './getRedirectUri'; import { retrieveRegistrationStatus } from './retrieveRegistrationStatus'; @@ -13,12 +16,12 @@ export function connectWorkspace(token) { const redirectUri = getRedirectUri(); const regInfo = { - email: RocketChat.settings.get('Organization_Email'), - client_name: RocketChat.settings.get('Site_Name'), + email: settings.get('Organization_Email'), + client_name: settings.get('Site_Name'), redirect_uris: [redirectUri], }; - const cloudUrl = RocketChat.settings.get('Cloud_Url'); + const cloudUrl = settings.get('Cloud_Url'); let result; try { result = HTTP.post(`${ cloudUrl }/api/oauth/clients`, { @@ -37,12 +40,12 @@ export function connectWorkspace(token) { return false; } - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Id', data.workspaceId); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Name', data.client_name); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Client_Id', data.client_id); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Client_Secret', data.client_secret); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Client_Secret_Expires_At', data.client_secret_expires_at); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Registration_Client_Uri', data.registration_client_uri); + Settings.updateValueById('Cloud_Workspace_Id', data.workspaceId); + Settings.updateValueById('Cloud_Workspace_Name', data.client_name); + Settings.updateValueById('Cloud_Workspace_Client_Id', data.client_id); + Settings.updateValueById('Cloud_Workspace_Client_Secret', data.client_secret); + Settings.updateValueById('Cloud_Workspace_Client_Secret_Expires_At', data.client_secret_expires_at); + Settings.updateValueById('Cloud_Workspace_Registration_Client_Uri', data.registration_client_uri); // Now that we have the client id and secret, let's get the access token let authTokenResult; @@ -63,8 +66,8 @@ export function connectWorkspace(token) { const expiresAt = new Date(); expiresAt.setSeconds(expiresAt.getSeconds() + authTokenResult.data.expires_in); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Access_Token', authTokenResult.data.access_token); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Access_Token_Expires_At', expiresAt); + Settings.updateValueById('Cloud_Workspace_Access_Token', authTokenResult.data.access_token); + Settings.updateValueById('Cloud_Workspace_Access_Token_Expires_At', expiresAt); return true; } diff --git a/packages/rocketchat-cloud/server/functions/finishOAuthAuthorization.js b/packages/rocketchat-cloud/server/functions/finishOAuthAuthorization.js index 80e2a67e17ea..b1b7484060a0 100644 --- a/packages/rocketchat-cloud/server/functions/finishOAuthAuthorization.js +++ b/packages/rocketchat-cloud/server/functions/finishOAuthAuthorization.js @@ -2,17 +2,19 @@ import querystring from 'querystring'; import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings, Users } from 'meteor/rocketchat:models'; import { getRedirectUri } from './getRedirectUri'; export function finishOAuthAuthorization(code, state) { - if (RocketChat.settings.get('Cloud_Workspace_Registration_State') !== state) { + if (settings.get('Cloud_Workspace_Registration_State') !== state) { throw new Meteor.Error('error-invalid-state', 'Invalid state provided', { method: 'cloud:finishOAuthAuthorization' }); } - const cloudUrl = RocketChat.settings.get('Cloud_Url'); - const clientId = RocketChat.settings.get('Cloud_Workspace_Client_Id'); - const clientSecret = RocketChat.settings.get('Cloud_Workspace_Client_Secret'); + const cloudUrl = settings.get('Cloud_Url'); + const clientId = settings.get('Cloud_Workspace_Client_Id'); + const clientSecret = settings.get('Cloud_Workspace_Client_Secret'); let result; try { @@ -33,8 +35,8 @@ export function finishOAuthAuthorization(code, state) { const expiresAt = new Date(); expiresAt.setSeconds(expiresAt.getSeconds() + result.data.expires_in); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Account_Associated', true); - RocketChat.models.Users.update({ _id: Meteor.userId() }, { + Settings.updateValueById('Cloud_Workspace_Account_Associated', true); + Users.update({ _id: Meteor.userId() }, { $set: { 'services.cloud': { accessToken: result.data.access_token, diff --git a/packages/rocketchat-cloud/server/functions/getOAuthAuthorizationUrl.js b/packages/rocketchat-cloud/server/functions/getOAuthAuthorizationUrl.js index b3edc95090f9..63248e26638d 100644 --- a/packages/rocketchat-cloud/server/functions/getOAuthAuthorizationUrl.js +++ b/packages/rocketchat-cloud/server/functions/getOAuthAuthorizationUrl.js @@ -1,14 +1,16 @@ import { Random } from 'meteor/random'; +import { Settings } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import { getRedirectUri } from './getRedirectUri'; export function getOAuthAuthorizationUrl() { const state = Random.id(); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Registration_State', state); + Settings.updateValueById('Cloud_Workspace_Registration_State', state); - const cloudUrl = RocketChat.settings.get('Cloud_Url'); - const client_id = RocketChat.settings.get('Cloud_Workspace_Client_Id'); + const cloudUrl = settings.get('Cloud_Url'); + const client_id = settings.get('Cloud_Workspace_Client_Id'); const redirectUri = getRedirectUri(); return `${ cloudUrl }/authorize?response_type=code&client_id=${ client_id }&redirect_uri=${ redirectUri }&scope=offline_access&state=${ state }`; diff --git a/packages/rocketchat-cloud/server/functions/getRedirectUri.js b/packages/rocketchat-cloud/server/functions/getRedirectUri.js index 21a219791c9e..2d8342af6590 100644 --- a/packages/rocketchat-cloud/server/functions/getRedirectUri.js +++ b/packages/rocketchat-cloud/server/functions/getRedirectUri.js @@ -1,3 +1,5 @@ +import { settings } from 'meteor/rocketchat:settings'; + export function getRedirectUri() { - return `${ RocketChat.settings.get('Site_Url') }/admin/cloud/oauth-callback`.replace(/\/\/admin+/g, '/admin'); + return `${ settings.get('Site_Url') }/admin/cloud/oauth-callback`.replace(/\/\/admin+/g, '/admin'); } diff --git a/packages/rocketchat-cloud/server/functions/getWorkspaceAccessTokens.js b/packages/rocketchat-cloud/server/functions/getWorkspaceAccessTokens.js index d853ce5b6df3..c80be9216aa8 100644 --- a/packages/rocketchat-cloud/server/functions/getWorkspaceAccessTokens.js +++ b/packages/rocketchat-cloud/server/functions/getWorkspaceAccessTokens.js @@ -1,27 +1,30 @@ import querystring from 'querystring'; + import { HTTP } from 'meteor/http'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings } from 'meteor/rocketchat:models'; import { getRedirectUri } from './getRedirectUri'; export function getWorkspaceAccessToken() { - if (!RocketChat.settings.get('Register_Server')) { + if (!settings.get('Register_Server')) { return ''; } - const client_id = RocketChat.settings.get('Cloud_Workspace_Client_Id'); + const client_id = settings.get('Cloud_Workspace_Client_Id'); if (!client_id) { return ''; } - const expires = RocketChat.models.Settings.findOneById('Cloud_Workspace_Access_Token_Expires_At'); + const expires = Settings.findOneById('Cloud_Workspace_Access_Token_Expires_At'); const now = new Date(); if (now < expires.value) { - return RocketChat.settings.get('Cloud_Workspace_Access_Token'); + return settings.get('Cloud_Workspace_Access_Token'); } - const cloudUrl = RocketChat.settings.get('Cloud_Url'); - const client_secret = RocketChat.settings.get('Cloud_Workspace_Client_Secret'); + const cloudUrl = settings.get('Cloud_Url'); + const client_secret = settings.get('Cloud_Workspace_Client_Secret'); const redirectUri = getRedirectUri(); let authTokenResult; @@ -42,8 +45,8 @@ export function getWorkspaceAccessToken() { const expiresAt = new Date(); expiresAt.setSeconds(expiresAt.getSeconds() + authTokenResult.data.expires_in); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Access_Token', authTokenResult.data.access_token); - RocketChat.models.Settings.updateValueById('Cloud_Workspace_Access_Token_Expires_At', expiresAt); + Settings.updateValueById('Cloud_Workspace_Access_Token', authTokenResult.data.access_token); + Settings.updateValueById('Cloud_Workspace_Access_Token_Expires_At', expiresAt); return authTokenResult.data.access_token; diff --git a/packages/rocketchat-cloud/server/functions/getWorkspaceLicense.js b/packages/rocketchat-cloud/server/functions/getWorkspaceLicense.js index d9278a65d519..ef72bde8a19d 100644 --- a/packages/rocketchat-cloud/server/functions/getWorkspaceLicense.js +++ b/packages/rocketchat-cloud/server/functions/getWorkspaceLicense.js @@ -1,4 +1,6 @@ import { HTTP } from 'meteor/http'; +import { settings } from 'meteor/rocketchat:settings'; +import { Settings } from 'meteor/rocketchat:models'; import { getWorkspaceAccessToken } from './getWorkspaceAccessToken'; @@ -12,7 +14,7 @@ export function getWorkspaceLicense() { let licenseResult; try { - licenseResult = HTTP.get(`${ RocketChat.settings.get('Cloud_Workspace_Registration_Client_Uri') }/license`, { + licenseResult = HTTP.get(`${ settings.get('Cloud_Workspace_Registration_Client_Uri') }/license`, { headers: { Authorization: `Bearer ${ token }`, }, @@ -22,13 +24,13 @@ export function getWorkspaceLicense() { } const remoteLicense = licenseResult.data; - const currentLicense = RocketChat.settings.get('Cloud_Workspace_License'); + const currentLicense = settings.get('Cloud_Workspace_License'); if (remoteLicense.updatedAt <= currentLicense._updatedAt) { return { updated: false, license: '' }; } - RocketChat.models.Settings.updateValueById('Cloud_Workspace_License', remoteLicense.license); + Settings.updateValueById('Cloud_Workspace_License', remoteLicense.license); return { updated: true, license: remoteLicense.license }; } diff --git a/packages/rocketchat-cloud/server/functions/retrieveRegistrationStatus.js b/packages/rocketchat-cloud/server/functions/retrieveRegistrationStatus.js index dd109853234e..c8d6c6dc4ddf 100644 --- a/packages/rocketchat-cloud/server/functions/retrieveRegistrationStatus.js +++ b/packages/rocketchat-cloud/server/functions/retrieveRegistrationStatus.js @@ -1,17 +1,20 @@ +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; + export function retrieveRegistrationStatus() { const info = { - registeredWithWizard: RocketChat.settings.get('Register_Server'), - workspaceConnected: (RocketChat.settings.get('Cloud_Workspace_Client_Id')) ? true : false, - userAssociated: (RocketChat.settings.get('Cloud_Workspace_Account_Associated')) ? true : false, + registeredWithWizard: settings.get('Register_Server'), + workspaceConnected: (settings.get('Cloud_Workspace_Client_Id')) ? true : false, + userAssociated: (settings.get('Cloud_Workspace_Account_Associated')) ? true : false, token: '', email: '', }; - const firstUser = RocketChat.models.Users.getOldest({ emails: 1 }); + const firstUser = Users.getOldest({ emails: 1 }); info.email = firstUser && firstUser.emails[0].address; - if (RocketChat.settings.get('Organization_Email')) { - info.email = RocketChat.settings.get('Organization_Email'); + if (settings.get('Organization_Email')) { + info.email = settings.get('Organization_Email'); } return info; diff --git a/packages/rocketchat-cloud/server/index.js b/packages/rocketchat-cloud/server/index.js index c64f14941528..c482aa40ac42 100644 --- a/packages/rocketchat-cloud/server/index.js +++ b/packages/rocketchat-cloud/server/index.js @@ -1,8 +1,10 @@ import './methods'; import { getWorkspaceAccessToken } from './functions/getWorkspaceAccessTokens'; -if (RocketChat.models && RocketChat.models.Permissions) { - RocketChat.models.Permissions.createOrUpdate('manage-cloud', ['admin']); +import { Permissions } from 'meteor/rocketchat:models'; + +if (Permissions) { + Permissions.createOrUpdate('manage-cloud', ['admin']); } // Ensure the client/workspace access token is valid diff --git a/packages/rocketchat-cloud/server/methods.js b/packages/rocketchat-cloud/server/methods.js index 480274bd14ab..e496d0457251 100644 --- a/packages/rocketchat-cloud/server/methods.js +++ b/packages/rocketchat-cloud/server/methods.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Settings } from 'meteor/rocketchat:models'; import { retrieveRegistrationStatus } from './functions/retrieveRegistrationStatus'; import { connectWorkspace } from './functions/connectWorkspace'; @@ -12,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cloud:checkRegisterStatus' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'manage-cloud')) { + if (!hasPermission(Meteor.userId(), 'manage-cloud')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'cloud:checkRegisterStatus' }); } @@ -25,11 +27,11 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cloud:updateEmail' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'manage-cloud')) { + if (!hasPermission(Meteor.userId(), 'manage-cloud')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'cloud:updateEmail' }); } - RocketChat.models.Settings.updateValueById('Organization_Email', email); + Settings.updateValueById('Organization_Email', email); }, 'cloud:connectWorkspace'(token) { check(token, String); @@ -38,7 +40,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cloud:connectServer' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'manage-cloud')) { + if (!hasPermission(Meteor.userId(), 'manage-cloud')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'cloud:connectServer' }); } @@ -49,7 +51,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cloud:connectServer' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'manage-cloud')) { + if (!hasPermission(Meteor.userId(), 'manage-cloud')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'cloud:connectServer' }); } @@ -63,7 +65,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cloud:finishOAuthAuthorization' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'manage-cloud')) { + if (!hasPermission(Meteor.userId(), 'manage-cloud')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'cloud:connectServer' }); } From 02436bee238a232228cc9a5ba90485804583b991 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 21:27:30 -0200 Subject: [PATCH 21/33] Remove dependency of RC namespace in rc-colors, cors, crowd and dolphin (#13255) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * Remove dependency of RC namespace in rc-channel-mail-messages * Remove dependency of RC namespace in rc-cloud * Remove dependency of RC namespace in rc-colors * Remove dependency of RC namespace in rc-cors * Remove dependency of RC namespace in rc-crowd * Remove dependency of RC namespace in rc-dolphin --- packages/rocketchat-colors/client/client.js | 7 +-- packages/rocketchat-colors/package.js | 3 +- packages/rocketchat-colors/server/settings.js | 4 +- packages/rocketchat-cors/lib/common.js | 4 +- packages/rocketchat-cors/package.js | 1 + packages/rocketchat-cors/server/cors.js | 22 +++++----- packages/rocketchat-crowd/package.js | 3 ++ packages/rocketchat-crowd/server/crowd.js | 43 ++++++++++--------- packages/rocketchat-crowd/server/settings.js | 4 +- packages/rocketchat-dolphin/lib/common.js | 32 +++++++------- packages/rocketchat-dolphin/package.js | 4 +- packages/rocketchat-dolphin/server/startup.js | 18 ++++---- 12 files changed, 78 insertions(+), 67 deletions(-) diff --git a/packages/rocketchat-colors/client/client.js b/packages/rocketchat-colors/client/client.js index e257c90cd2d9..f4620a60611c 100644 --- a/packages/rocketchat-colors/client/client.js +++ b/packages/rocketchat-colors/client/client.js @@ -1,4 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import s from 'underscore.string'; // @@ -8,7 +9,7 @@ import s from 'underscore.string'; function HexColorPreview(message) { let msg; - if (s.trim(message.html) && RocketChat.settings.get('HexColorPreview_Enabled')) { + if (s.trim(message.html) && settings.get('HexColorPreview_Enabled')) { msg = message.html; msg = msg.replace(/(?:^|\s|\n)(#[A-Fa-f0-9]{3}([A-Fa-f0-9]{3})?)\b/g, function(match, completeColor) { return match.replace(completeColor, `
${ completeColor.toUpperCase() }
`); @@ -18,4 +19,4 @@ function HexColorPreview(message) { return message; } -RocketChat.callbacks.add('renderMessage', HexColorPreview, RocketChat.callbacks.priority.MEDIUM, 'hexcolor'); +callbacks.add('renderMessage', HexColorPreview, callbacks.priority.MEDIUM, 'hexcolor'); diff --git a/packages/rocketchat-colors/package.js b/packages/rocketchat-colors/package.js index e7513c0b5114..4831dbdb2744 100644 --- a/packages/rocketchat-colors/package.js +++ b/packages/rocketchat-colors/package.js @@ -8,7 +8,8 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', ]); api.addFiles('client/style.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-colors/server/settings.js b/packages/rocketchat-colors/server/settings.js index 96b69bce9ce7..09b19e982b55 100644 --- a/packages/rocketchat-colors/server/settings.js +++ b/packages/rocketchat-colors/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.add('HexColorPreview_Enabled', true, { +settings.add('HexColorPreview_Enabled', true, { type: 'boolean', i18nLabel: 'Enabled', group: 'Message', diff --git a/packages/rocketchat-cors/lib/common.js b/packages/rocketchat-cors/lib/common.js index ffc05767ff76..d26c41502b0c 100644 --- a/packages/rocketchat-cors/lib/common.js +++ b/packages/rocketchat-cors/lib/common.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.onload('Force_SSL', function(key, value) { + settings.onload('Force_SSL', function(key, value) { Meteor.absoluteUrl.defaultOptions.secure = value; }); }); diff --git a/packages/rocketchat-cors/package.js b/packages/rocketchat-cors/package.js index 72a4c4c28a6c..3ed3f79c44b6 100644 --- a/packages/rocketchat-cors/package.js +++ b/packages/rocketchat-cors/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'webapp', 'mongo', 'rocketchat:lib', + 'rocketchat:settings', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-cors/server/cors.js b/packages/rocketchat-cors/server/cors.js index 7fb553f8c89c..a3e36d816210 100644 --- a/packages/rocketchat-cors/server/cors.js +++ b/packages/rocketchat-cors/server/cors.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { WebApp, WebAppInternals } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { Mongo } from 'meteor/mongo'; +import { Logger } from 'meteor/rocketchat:logger'; +const logger = new Logger('CORS', {}); import _ from 'underscore'; import url from 'url'; @@ -46,9 +48,7 @@ WebApp.rawConnectHandlers.use(Meteor.bindEnvironment(function(req, res, next) { }); req.on('end', function() { - if (RocketChat && RocketChat.debugLevel === 'debug') { - console.log('[request]'.green, req.method, req.url, '\nheaders ->', req.headers, '\nbody ->', buf); - } + logger.debug('[request]'.green, req.method, req.url, '\nheaders ->', req.headers, '\nbody ->', buf); try { req.body = JSON.parse(buf); @@ -94,7 +94,7 @@ WebApp.httpServer.addListener('request', function(req, res, ...args) { } }; - if (RocketChat.settings.get('Force_SSL') !== true) { + if (settings.get('Force_SSL') !== true) { next(); return; } @@ -108,13 +108,11 @@ WebApp.httpServer.addListener('request', function(req, res, ...args) { const isLocal = localhostRegexp.test(remoteAddress) && (!req.headers['x-forwarded-for'] || _.all(req.headers['x-forwarded-for'].split(','), localhostTest)); const isSsl = req.connection.pair || (req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'].indexOf('https') !== -1); - if (RocketChat && RocketChat.debugLevel === 'debug') { - console.log('req.url', req.url); - console.log('remoteAddress', remoteAddress); - console.log('isLocal', isLocal); - console.log('isSsl', isSsl); - console.log('req.headers', req.headers); - } + logger.debug('req.url', req.url); + logger.debug('remoteAddress', remoteAddress); + logger.debug('isLocal', isLocal); + logger.debug('isSsl', isSsl); + logger.debug('req.headers', req.headers); if (!isLocal && !isSsl) { let host = req.headers.host || url.parse(Meteor.absoluteUrl()).hostname; diff --git a/packages/rocketchat-crowd/package.js b/packages/rocketchat-crowd/package.js index 83c5bcd53537..87abe3071cbe 100644 --- a/packages/rocketchat-crowd/package.js +++ b/packages/rocketchat-crowd/package.js @@ -9,6 +9,9 @@ Package.onUse(function(api) { api.use([ 'rocketchat:logger', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:authorization', 'ecmascript', 'sha', 'templating', diff --git a/packages/rocketchat-crowd/server/crowd.js b/packages/rocketchat-crowd/server/crowd.js index dafef53d226f..380f2e20b75c 100644 --- a/packages/rocketchat-crowd/server/crowd.js +++ b/packages/rocketchat-crowd/server/crowd.js @@ -3,7 +3,10 @@ import { SHA256 } from 'meteor/sha'; import { SyncedCron } from 'meteor/littledata:synced-cron'; import { Accounts } from 'meteor/accounts-base'; import { Logger } from 'meteor/rocketchat:logger'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { _setRealName } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasRole } from 'meteor/rocketchat:authorization'; import _ from 'underscore'; const logger = new Logger('CROWD', {}); @@ -33,17 +36,17 @@ function fallbackDefaultAccountSystem(bind, username, password) { export class CROWD { constructor() { const AtlassianCrowd = require('atlassian-crowd'); - let url = RocketChat.settings.get('CROWD_URL'); + let url = settings.get('CROWD_URL'); this.options = { crowd: { base: (!/\/$/.test(url) ? url += '/' : url), }, application: { - name: RocketChat.settings.get('CROWD_APP_USERNAME'), - password: RocketChat.settings.get('CROWD_APP_PASSWORD'), + name: settings.get('CROWD_APP_USERNAME'), + password: settings.get('CROWD_APP_PASSWORD'), }, - rejectUnauthorized: RocketChat.settings.get('CROWD_Reject_Unauthorized'), + rejectUnauthorized: settings.get('CROWD_Reject_Unauthorized'), }; this.crowdClient = new AtlassianCrowd(this.options); @@ -107,11 +110,11 @@ export class CROWD { logout: false, }); - RocketChat.models.Users.unsetRequirePasswordChange(id); + Users.unsetRequirePasswordChange(id); } if (crowdUser.displayname) { - RocketChat._setRealName(id, crowdUser.displayname); + _setRealName(id, crowdUser.displayname); } Meteor.users.update(id, { @@ -121,12 +124,12 @@ export class CROWD { sync() { // if crowd is disabled bail out - if (RocketChat.settings.get('CROWD_Enable') !== true) { + if (settings.get('CROWD_Enable') !== true) { return; } const self = this; - const users = RocketChat.models.Users.findCrowdUsers() || []; + const users = Users.findCrowdUsers() || []; logger.info('Sync started...'); @@ -161,7 +164,7 @@ export class CROWD { } cleanUsername(username) { - if (RocketChat.settings.get('CROWD_Clean_Usernames') === true) { + if (settings.get('CROWD_Clean_Usernames') === true) { return username.split('@')[0]; } return username; @@ -216,7 +219,7 @@ Accounts.registerLoginHandler('crowd', function(loginRequest) { logger.info('Init CROWD login', loginRequest.username); - if (RocketChat.settings.get('CROWD_Enable') !== true) { + if (settings.get('CROWD_Enable') !== true) { return fallbackDefaultAccountSystem(this, loginRequest.username, loginRequest.crowdPassword); } @@ -236,7 +239,7 @@ Accounts.registerLoginHandler('crowd', function(loginRequest) { const jobName = 'CROWD_Sync'; const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounced() { - if (RocketChat.settings.get('CROWD_Sync_User_Data') !== true) { + if (settings.get('CROWD_Sync_User_Data') !== true) { logger.info('Disabling CROWD Background Sync'); if (SyncedCron.nextScheduledAtDate(jobName)) { SyncedCron.remove(jobName); @@ -246,11 +249,11 @@ const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounce const crowd = new CROWD(); - if (RocketChat.settings.get('CROWD_Sync_Interval')) { + if (settings.get('CROWD_Sync_Interval')) { logger.info('Enabling CROWD Background Sync'); SyncedCron.add({ name: jobName, - schedule: (parser) => parser.text(RocketChat.settings.get('CROWD_Sync_Interval')), + schedule: (parser) => parser.text(settings.get('CROWD_Sync_Interval')), job() { crowd.sync(); }, @@ -261,8 +264,8 @@ const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounce Meteor.startup(() => { Meteor.defer(() => { - RocketChat.settings.get('CROWD_Sync_Interval', addCronJob); - RocketChat.settings.get('CROWD_Sync_User_Data', addCronJob); + settings.get('CROWD_Sync_Interval', addCronJob); + settings.get('CROWD_Sync_User_Data', addCronJob); }); }); @@ -273,11 +276,11 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'crowd_test_connection' }); } - if (!RocketChat.authz.hasRole(user._id, 'admin')) { + if (!hasRole(user._id, 'admin')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'crowd_test_connection' }); } - if (RocketChat.settings.get('CROWD_Enable') !== true) { + if (settings.get('CROWD_Enable') !== true) { throw new Meteor.Error('crowd_disabled'); } @@ -296,11 +299,11 @@ Meteor.methods({ }, crowd_sync_users() { const user = Meteor.user(); - if (RocketChat.settings.get('CROWD_Enable') !== true) { + if (settings.get('CROWD_Enable') !== true) { throw new Meteor.Error('crowd_disabled'); } - if (!RocketChat.authz.hasRole(user._id, 'admin')) { + if (!hasRole(user._id, 'admin')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'crowd_sync_users' }); } diff --git a/packages/rocketchat-crowd/server/settings.js b/packages/rocketchat-crowd/server/settings.js index 960a80f687dc..ca441bf205f9 100644 --- a/packages/rocketchat-crowd/server/settings.js +++ b/packages/rocketchat-crowd/server/settings.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.addGroup('AtlassianCrowd', function() { + settings.addGroup('AtlassianCrowd', function() { const enableQuery = { _id: 'CROWD_Enable', value: true }; const enableSyncQuery = [enableQuery, { _id: 'CROWD_Sync_User_Data', value: true }]; diff --git a/packages/rocketchat-dolphin/lib/common.js b/packages/rocketchat-dolphin/lib/common.js index 7d7b634c7880..f4afc14dbfef 100644 --- a/packages/rocketchat-dolphin/lib/common.js +++ b/packages/rocketchat-dolphin/lib/common.js @@ -1,8 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { ServiceConfiguration } from 'meteor/service-configuration'; import { CustomOAuth } from 'meteor/rocketchat:custom-oauth'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Settings } from 'meteor/rocketchat:models'; const config = { serverURL: '', @@ -27,38 +29,38 @@ function DolphinOnCreateUser(options, user) { if (Meteor.isServer) { Meteor.startup(() => - RocketChat.models.Settings.find({ _id: 'Accounts_OAuth_Dolphin_URL' }).observe({ + Settings.find({ _id: 'Accounts_OAuth_Dolphin_URL' }).observe({ added() { - config.serverURL = RocketChat.settings.get('Accounts_OAuth_Dolphin_URL'); + config.serverURL = settings.get('Accounts_OAuth_Dolphin_URL'); return Dolphin.configure(config); }, changed() { - config.serverURL = RocketChat.settings.get('Accounts_OAuth_Dolphin_URL'); + config.serverURL = settings.get('Accounts_OAuth_Dolphin_URL'); return Dolphin.configure(config); }, }) ); - if (RocketChat.settings.get('Accounts_OAuth_Dolphin_URL')) { + if (settings.get('Accounts_OAuth_Dolphin_URL')) { const data = { - buttonLabelText: RocketChat.settings.get('Accounts_OAuth_Dolphin_button_label_text'), - buttonColor: RocketChat.settings.get('Accounts_OAuth_Dolphin_button_color'), - buttonLabelColor: RocketChat.settings.get('Accounts_OAuth_Dolphin_button_label_color'), - clientId: RocketChat.settings.get('Accounts_OAuth_Dolphin_id'), - secret: RocketChat.settings.get('Accounts_OAuth_Dolphin_secret'), - serverURL: RocketChat.settings.get('Accounts_OAuth_Dolphin_URL'), - loginStyle: RocketChat.settings.get('Accounts_OAuth_Dolphin_login_style'), + buttonLabelText: settings.get('Accounts_OAuth_Dolphin_button_label_text'), + buttonColor: settings.get('Accounts_OAuth_Dolphin_button_color'), + buttonLabelColor: settings.get('Accounts_OAuth_Dolphin_button_label_color'), + clientId: settings.get('Accounts_OAuth_Dolphin_id'), + secret: settings.get('Accounts_OAuth_Dolphin_secret'), + serverURL: settings.get('Accounts_OAuth_Dolphin_URL'), + loginStyle: settings.get('Accounts_OAuth_Dolphin_login_style'), }; ServiceConfiguration.configurations.upsert({ service: 'dolphin' }, { $set: data }); } - RocketChat.callbacks.add('beforeCreateUser', DolphinOnCreateUser, RocketChat.callbacks.priority.HIGH); + callbacks.add('beforeCreateUser', DolphinOnCreateUser, callbacks.priority.HIGH); } else { Meteor.startup(() => Tracker.autorun(function() { - if (RocketChat.settings.get('Accounts_OAuth_Dolphin_URL')) { - config.serverURL = RocketChat.settings.get('Accounts_OAuth_Dolphin_URL'); + if (settings.get('Accounts_OAuth_Dolphin_URL')) { + config.serverURL = settings.get('Accounts_OAuth_Dolphin_URL'); return Dolphin.configure(config); } }) diff --git a/packages/rocketchat-dolphin/package.js b/packages/rocketchat-dolphin/package.js index 751718742c4e..bd86c9561a3c 100644 --- a/packages/rocketchat-dolphin/package.js +++ b/packages/rocketchat-dolphin/package.js @@ -10,7 +10,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'service-configuration', - 'rocketchat:lib@0.0.1', + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:models', 'rocketchat:custom-oauth', 'templating', ]); diff --git a/packages/rocketchat-dolphin/server/startup.js b/packages/rocketchat-dolphin/server/startup.js index c993175df623..07a2be60a9f4 100644 --- a/packages/rocketchat-dolphin/server/startup.js +++ b/packages/rocketchat-dolphin/server/startup.js @@ -1,10 +1,10 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.add('Accounts_OAuth_Dolphin_URL', '', { type: 'string', group: 'OAuth', public: true, section: 'Dolphin', i18nLabel: 'URL' }); -RocketChat.settings.add('Accounts_OAuth_Dolphin', false, { type: 'boolean', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Enable' }); -RocketChat.settings.add('Accounts_OAuth_Dolphin_id', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_id' }); -RocketChat.settings.add('Accounts_OAuth_Dolphin_secret', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Secret' }); -RocketChat.settings.add('Accounts_OAuth_Dolphin_login_style', 'redirect', { type: 'select', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] }); -RocketChat.settings.add('Accounts_OAuth_Dolphin_button_label_text', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true }); -RocketChat.settings.add('Accounts_OAuth_Dolphin_button_label_color', '#FFFFFF', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true }); -RocketChat.settings.add('Accounts_OAuth_Dolphin_button_color', '#13679A', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true }); +settings.add('Accounts_OAuth_Dolphin_URL', '', { type: 'string', group: 'OAuth', public: true, section: 'Dolphin', i18nLabel: 'URL' }); +settings.add('Accounts_OAuth_Dolphin', false, { type: 'boolean', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Enable' }); +settings.add('Accounts_OAuth_Dolphin_id', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_id' }); +settings.add('Accounts_OAuth_Dolphin_secret', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Secret' }); +settings.add('Accounts_OAuth_Dolphin_login_style', 'redirect', { type: 'select', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [{ key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' }] }); +settings.add('Accounts_OAuth_Dolphin_button_label_text', '', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true }); +settings.add('Accounts_OAuth_Dolphin_button_label_color', '#FFFFFF', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true }); +settings.add('Accounts_OAuth_Dolphin_button_color', '#13679A', { type: 'string', group: 'OAuth', section: 'Dolphin', i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true }); From 5528c0f98a2a857b9a2edad5c2b9a44e78daf326 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 22:46:15 -0200 Subject: [PATCH 22/33] Remove dependency of RC namespace in rc-emoji-custom and drupal (#13256) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * Remove dependency of RC namespace in rc-channel-mail-messages * Remove dependency of RC namespace in rc-cloud * Remove dependency of RC namespace in rc-colors * Remove dependency of RC namespace in rc-cors * Remove dependency of RC namespace in rc-crowd * Remove dependency of RC namespace in rc-dolphin * Remove dependency of RC namespace in rc-drupal * Move Emoji custom server and client models to rc-models * Remove dependency of RC namespace in rc-emoji-custom --- packages/rocketchat-drupal/lib/common.js | 8 +- packages/rocketchat-drupal/package.js | 2 +- packages/rocketchat-drupal/server/startup.js | 4 +- .../client/admin/adminEmoji.js | 12 +-- .../client/admin/emojiEdit.js | 3 +- .../client/admin/emojiInfo.js | 5 +- .../client/admin/startup.js | 7 +- .../rocketchat-emoji-custom/client/index.js | 1 - .../client/lib/emojiCustom.js | 93 ++++++++++--------- .../client/notifications/deleteEmojiCustom.js | 4 +- .../client/notifications/updateEmojiCustom.js | 4 +- packages/rocketchat-emoji-custom/package.js | 7 +- .../rocketchat-emoji-custom/server/index.js | 1 - .../server/methods/deleteEmojiCustom.js | 12 ++- .../server/methods/insertOrUpdateEmoji.js | 28 +++--- .../server/methods/listEmojiCustom.js | 4 +- .../server/methods/uploadEmojiCustom.js | 7 +- .../server/publications/fullEmojiData.js | 6 +- .../server/startup/emoji-custom.js | 12 +-- .../server/startup/settings.js | 4 +- .../rocketchat-lib/client/models/index.js | 3 +- .../rocketchat-lib/server/models/index.js | 2 + packages/rocketchat-models/client/index.js | 2 + .../client/models/EmojiCustom.js | 6 +- packages/rocketchat-models/server/index.js | 2 + .../server/models/EmojiCustom.js | 6 +- 26 files changed, 130 insertions(+), 115 deletions(-) rename packages/{rocketchat-emoji-custom => rocketchat-models}/client/models/EmojiCustom.js (59%) rename packages/{rocketchat-emoji-custom => rocketchat-models}/server/models/EmojiCustom.js (88%) diff --git a/packages/rocketchat-drupal/lib/common.js b/packages/rocketchat-drupal/lib/common.js index 6386d9de4061..32c0a5e80682 100644 --- a/packages/rocketchat-drupal/lib/common.js +++ b/packages/rocketchat-drupal/lib/common.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { CustomOAuth } from 'meteor/rocketchat:custom-oauth'; // Drupal Server CallBack URL needs to be http(s)://{rocketchat.server}[:port]/_oauth/drupal @@ -25,7 +25,7 @@ const Drupal = new CustomOAuth('drupal', config); if (Meteor.isServer) { Meteor.startup(function() { - RocketChat.settings.get('API_Drupal_URL', function(key, value) { + settings.get('API_Drupal_URL', function(key, value) { config.serverURL = value; Drupal.configure(config); }); @@ -33,8 +33,8 @@ if (Meteor.isServer) { } else { Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('API_Drupal_URL')) { - config.serverURL = RocketChat.settings.get('API_Drupal_URL'); + if (settings.get('API_Drupal_URL')) { + config.serverURL = settings.get('API_Drupal_URL'); Drupal.configure(config); } }); diff --git a/packages/rocketchat-drupal/package.js b/packages/rocketchat-drupal/package.js index 5841812c23e7..4b14e98941ee 100644 --- a/packages/rocketchat-drupal/package.js +++ b/packages/rocketchat-drupal/package.js @@ -9,7 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'service-configuration', - 'rocketchat:lib@0.0.1', + 'rocketchat:settings', 'rocketchat:custom-oauth', 'templating', ]); diff --git a/packages/rocketchat-drupal/server/startup.js b/packages/rocketchat-drupal/server/startup.js index 389c2d06dbf1..186ccf6dae9b 100644 --- a/packages/rocketchat-drupal/server/startup.js +++ b/packages/rocketchat-drupal/server/startup.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('OAuth', function() { +settings.addGroup('OAuth', function() { this.section('Drupal', function() { const enableQuery = { _id: 'Accounts_OAuth_Drupal', diff --git a/packages/rocketchat-emoji-custom/client/admin/adminEmoji.js b/packages/rocketchat-emoji-custom/client/admin/adminEmoji.js index b73fe2b8829a..09cc41bcfb58 100644 --- a/packages/rocketchat-emoji-custom/client/admin/adminEmoji.js +++ b/packages/rocketchat-emoji-custom/client/admin/adminEmoji.js @@ -1,9 +1,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; -import { RocketChat, RocketChatTabBar } from 'meteor/rocketchat:lib'; +import { RocketChatTabBar, SideNav, TabBar } from 'meteor/rocketchat:ui-utils'; import { Tracker } from 'meteor/tracker'; +import { EmojiCustom } from 'meteor/rocketchat:models'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { SideNav } from 'meteor/rocketchat:ui'; import s from 'underscore.string'; Template.adminEmoji.helpers({ @@ -49,7 +49,7 @@ Template.adminEmoji.onCreated(function() { this.tabBar.showGroup(FlowRouter.current().route.name); this.tabBarData = new ReactiveVar(); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['emoji-custom'], id: 'add-emoji', i18nTitle: 'Custom_Emoji_Add', @@ -58,7 +58,7 @@ Template.adminEmoji.onCreated(function() { order: 1, }); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['emoji-custom'], id: 'admin-emoji-info', i18nTitle: 'Custom_Emoji_Info', @@ -85,7 +85,7 @@ Template.adminEmoji.onCreated(function() { const limit = (instance.limit != null) ? instance.limit.get() : 0; - return RocketChat.models.EmojiCustom.find(query, { limit, sort: { name: 1 } }).fetch(); + return EmojiCustom.find(query, { limit, sort: { name: 1 } }).fetch(); }; }); @@ -113,7 +113,7 @@ Template.adminEmoji.events({ 'click .emoji-info'(e, instance) { e.preventDefault(); - instance.tabBarData.set(RocketChat.models.EmojiCustom.findOne({ _id: this._id })); + instance.tabBarData.set(EmojiCustom.findOne({ _id: this._id })); instance.tabBar.open('admin-emoji-info'); }, diff --git a/packages/rocketchat-emoji-custom/client/admin/emojiEdit.js b/packages/rocketchat-emoji-custom/client/admin/emojiEdit.js index b318029e4dd6..105089915506 100644 --- a/packages/rocketchat-emoji-custom/client/admin/emojiEdit.js +++ b/packages/rocketchat-emoji-custom/client/admin/emojiEdit.js @@ -1,8 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; import s from 'underscore.string'; diff --git a/packages/rocketchat-emoji-custom/client/admin/emojiInfo.js b/packages/rocketchat-emoji-custom/client/admin/emojiInfo.js index 3fb81a237eeb..f1564fa520ce 100644 --- a/packages/rocketchat-emoji-custom/client/admin/emojiInfo.js +++ b/packages/rocketchat-emoji-custom/client/admin/emojiInfo.js @@ -1,9 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { handleError } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { handleError, t } from 'meteor/rocketchat:utils'; +import { modal } from 'meteor/rocketchat:ui-utils'; Template.emojiInfo.helpers({ name() { diff --git a/packages/rocketchat-emoji-custom/client/admin/startup.js b/packages/rocketchat-emoji-custom/client/admin/startup.js index 0d6b232eb9a5..294fd023c190 100644 --- a/packages/rocketchat-emoji-custom/client/admin/startup.js +++ b/packages/rocketchat-emoji-custom/client/admin/startup.js @@ -1,10 +1,11 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { AdminBox } from 'meteor/rocketchat:ui-utils'; +import { hasPermission } from 'meteor/rocketchat:authorization'; -RocketChat.AdminBox.addOption({ +AdminBox.addOption({ href: 'emoji-custom', i18nLabel: 'Custom_Emoji', icon: 'emoji', permissionGranted() { - return RocketChat.authz.hasPermission('manage-emoji'); + return hasPermission('manage-emoji'); }, }); diff --git a/packages/rocketchat-emoji-custom/client/index.js b/packages/rocketchat-emoji-custom/client/index.js index 9688848698dd..06b377694769 100644 --- a/packages/rocketchat-emoji-custom/client/index.js +++ b/packages/rocketchat-emoji-custom/client/index.js @@ -1,4 +1,3 @@ -import './models/EmojiCustom'; import './lib/emojiCustom'; import './notifications/deleteEmojiCustom'; import './notifications/updateEmojiCustom'; diff --git a/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js b/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js index c60674a2ac44..515f504e2159 100644 --- a/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js +++ b/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Blaze } from 'meteor/blaze'; import { Session } from 'meteor/session'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { isSetNotNull } from '../lib/function-isSet'; -import { RoomManager } from 'meteor/rocketchat:ui'; +import { RoomManager } from 'meteor/rocketchat:ui-utils'; +import { emoji, EmojiPicker } from 'meteor/rocketchat:emoji'; +import { CachedCollectionManager } from 'meteor/rocketchat:ui-cached-collection'; export const getEmojiUrlFromName = function(name, extension) { Session.get; @@ -25,25 +26,25 @@ export const getEmojiUrlFromName = function(name, extension) { Blaze.registerHelper('emojiUrlFromName', getEmojiUrlFromName); export const deleteEmojiCustom = function(emojiData) { - delete RocketChat.emoji.list[`:${ emojiData.name }:`]; - const arrayIndex = RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.name); + delete emoji.list[`:${ emojiData.name }:`]; + const arrayIndex = emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.name); if (arrayIndex !== -1) { - RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1); + emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1); } - const arrayIndexList = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.name }:`); + const arrayIndexList = emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.name }:`); if (arrayIndexList !== -1) { - RocketChat.emoji.packages.emojiCustom.list.splice(arrayIndexList, 1); + emoji.packages.emojiCustom.list.splice(arrayIndexList, 1); } if (isSetNotNull(() => emojiData.aliases)) { for (const alias of emojiData.aliases) { - delete RocketChat.emoji.list[`:${ alias }:`]; - const aliasIndex = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`); + delete emoji.list[`:${ alias }:`]; + const aliasIndex = emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`); if (aliasIndex !== -1) { - RocketChat.emoji.packages.emojiCustom.list.splice(aliasIndex, 1); + emoji.packages.emojiCustom.list.splice(aliasIndex, 1); } } } - RocketChat.EmojiPicker.updateRecent(); + EmojiPicker.updateRecent(); }; export const updateEmojiCustom = function(emojiData) { @@ -53,40 +54,40 @@ export const updateEmojiCustom = function(emojiData) { const previousExists = isSetNotNull(() => emojiData.previousName); const currentAliases = isSetNotNull(() => emojiData.aliases); - if (previousExists && isSetNotNull(() => RocketChat.emoji.list[`:${ emojiData.previousName }:`].aliases)) { - for (const alias of RocketChat.emoji.list[`:${ emojiData.previousName }:`].aliases) { - delete RocketChat.emoji.list[`:${ alias }:`]; - const aliasIndex = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`); + if (previousExists && isSetNotNull(() => emoji.list[`:${ emojiData.previousName }:`].aliases)) { + for (const alias of emoji.list[`:${ emojiData.previousName }:`].aliases) { + delete emoji.list[`:${ alias }:`]; + const aliasIndex = emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`); if (aliasIndex !== -1) { - RocketChat.emoji.packages.emojiCustom.list.splice(aliasIndex, 1); + emoji.packages.emojiCustom.list.splice(aliasIndex, 1); } } } if (previousExists && emojiData.name !== emojiData.previousName) { - const arrayIndex = RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.previousName); + const arrayIndex = emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.previousName); if (arrayIndex !== -1) { - RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1); + emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1); } - const arrayIndexList = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.previousName }:`); + const arrayIndexList = emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.previousName }:`); if (arrayIndexList !== -1) { - RocketChat.emoji.packages.emojiCustom.list.splice(arrayIndexList, 1); + emoji.packages.emojiCustom.list.splice(arrayIndexList, 1); } - delete RocketChat.emoji.list[`:${ emojiData.previousName }:`]; + delete emoji.list[`:${ emojiData.previousName }:`]; } - const categoryIndex = RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(`${ emojiData.name }`); + const categoryIndex = emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(`${ emojiData.name }`); if (categoryIndex === -1) { - RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.push(`${ emojiData.name }`); - RocketChat.emoji.packages.emojiCustom.list.push(`:${ emojiData.name }:`); + emoji.packages.emojiCustom.emojisByCategory.rocket.push(`${ emojiData.name }`); + emoji.packages.emojiCustom.list.push(`:${ emojiData.name }:`); } - RocketChat.emoji.list[`:${ emojiData.name }:`] = Object.assign({ emojiPackage: 'emojiCustom' }, RocketChat.emoji.list[`:${ emojiData.name }:`], emojiData); + emoji.list[`:${ emojiData.name }:`] = Object.assign({ emojiPackage: 'emojiCustom' }, emoji.list[`:${ emojiData.name }:`], emojiData); if (currentAliases) { for (const alias of emojiData.aliases) { - RocketChat.emoji.packages.emojiCustom.list.push(`:${ alias }:`); - RocketChat.emoji.list[`:${ alias }:`] = {}; - RocketChat.emoji.list[`:${ alias }:`].emojiPackage = 'emojiCustom'; - RocketChat.emoji.list[`:${ alias }:`].aliasOf = emojiData.name; + emoji.packages.emojiCustom.list.push(`:${ alias }:`); + emoji.list[`:${ alias }:`] = {}; + emoji.list[`:${ alias }:`].emojiPackage = 'emojiCustom'; + emoji.list[`:${ alias }:`].aliasOf = emojiData.name; } } @@ -119,30 +120,30 @@ export const updateEmojiCustom = function(emojiData) { } } - RocketChat.EmojiPicker.updateRecent(); + EmojiPicker.updateRecent(); }; -RocketChat.emoji.packages.emojiCustom = { +emoji.packages.emojiCustom = { emojiCategories: { rocket: 'Custom' }, toneList: {}, list: [], render(html) { - const regShortNames = new RegExp(`]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(${ RocketChat.emoji.packages.emojiCustom.list.join('|') })`, 'gi'); + const regShortNames = new RegExp(`]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(${ emoji.packages.emojiCustom.list.join('|') })`, 'gi'); // replace regular shortnames first html = html.replace(regShortNames, function(shortname) { // console.log('shortname (preif) ->', shortname, html); - if ((typeof shortname === 'undefined') || (shortname === '') || (RocketChat.emoji.packages.emojiCustom.list.indexOf(shortname) === -1)) { + if ((typeof shortname === 'undefined') || (shortname === '') || (emoji.packages.emojiCustom.list.indexOf(shortname) === -1)) { // if the shortname doesnt exist just return the entire match return shortname; } else { let emojiAlias = shortname.replace(/:/g, ''); - let dataCheck = RocketChat.emoji.list[shortname]; + let dataCheck = emoji.list[shortname]; if (dataCheck.hasOwnProperty('aliasOf')) { emojiAlias = dataCheck.aliasOf; - dataCheck = RocketChat.emoji.list[`:${ emojiAlias }:`]; + dataCheck = emoji.list[`:${ emojiAlias }:`]; } return `${ shortname }`; @@ -154,19 +155,19 @@ RocketChat.emoji.packages.emojiCustom = { }; Meteor.startup(() => - RocketChat.CachedCollectionManager.onLogin(() => { + CachedCollectionManager.onLogin(() => { Meteor.call('listEmojiCustom', (error, result) => { - RocketChat.emoji.packages.emojiCustom.emojisByCategory = { rocket: [] }; - for (const emoji of result) { - RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.push(emoji.name); - RocketChat.emoji.packages.emojiCustom.list.push(`:${ emoji.name }:`); - RocketChat.emoji.list[`:${ emoji.name }:`] = emoji; - RocketChat.emoji.list[`:${ emoji.name }:`].emojiPackage = 'emojiCustom'; - for (const alias of emoji.aliases) { - RocketChat.emoji.packages.emojiCustom.list.push(`:${ alias }:`); - RocketChat.emoji.list[`:${ alias }:`] = { + emoji.packages.emojiCustom.emojisByCategory = { rocket: [] }; + for (const currentEmoji of result) { + emoji.packages.emojiCustom.emojisByCategory.rocket.push(currentEmoji.name); + emoji.packages.emojiCustom.list.push(`:${ currentEmoji.name }:`); + emoji.list[`:${ currentEmoji.name }:`] = currentEmoji; + emoji.list[`:${ currentEmoji.name }:`].emojiPackage = 'emojiCustom'; + for (const alias of currentEmoji.aliases) { + emoji.packages.emojiCustom.list.push(`:${ alias }:`); + emoji.list[`:${ alias }:`] = { emojiPackage: 'emojiCustom', - aliasOf: emoji.name, + aliasOf: currentEmoji.name, }; } } diff --git a/packages/rocketchat-emoji-custom/client/notifications/deleteEmojiCustom.js b/packages/rocketchat-emoji-custom/client/notifications/deleteEmojiCustom.js index bcff8efd765e..54a1f446757f 100644 --- a/packages/rocketchat-emoji-custom/client/notifications/deleteEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/client/notifications/deleteEmojiCustom.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Notifications } from 'meteor/rocketchat:notifications'; import { deleteEmojiCustom } from '../lib/emojiCustom'; Meteor.startup(() => - RocketChat.Notifications.onLogged('deleteEmojiCustom', (data) => deleteEmojiCustom(data.emojiData)) + Notifications.onLogged('deleteEmojiCustom', (data) => deleteEmojiCustom(data.emojiData)) ); diff --git a/packages/rocketchat-emoji-custom/client/notifications/updateEmojiCustom.js b/packages/rocketchat-emoji-custom/client/notifications/updateEmojiCustom.js index f6e33743339d..6ee84095130d 100644 --- a/packages/rocketchat-emoji-custom/client/notifications/updateEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/client/notifications/updateEmojiCustom.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Notifications } from 'meteor/rocketchat:notifications'; import { updateEmojiCustom } from '../lib/emojiCustom'; Meteor.startup(() => - RocketChat.Notifications.onLogged('updateEmojiCustom', (data) => updateEmojiCustom(data.emojiData)) + Notifications.onLogged('updateEmojiCustom', (data) => updateEmojiCustom(data.emojiData)) ); diff --git a/packages/rocketchat-emoji-custom/package.js b/packages/rocketchat-emoji-custom/package.js index 87f122eb2bc3..0bbb099c27ea 100644 --- a/packages/rocketchat-emoji-custom/package.js +++ b/packages/rocketchat-emoji-custom/package.js @@ -10,8 +10,13 @@ Package.onUse(function(api) { 'ecmascript', 'rocketchat:emoji', 'rocketchat:file', - 'rocketchat:lib', 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:authorization', + 'rocketchat:notifications', + 'rocketchat:ui-cached-collection', + 'rocketchat:ui-utils', 'templating', 'webapp', 'kadira:flow-router', diff --git a/packages/rocketchat-emoji-custom/server/index.js b/packages/rocketchat-emoji-custom/server/index.js index cc0b89be8d5b..162ae9a35d14 100644 --- a/packages/rocketchat-emoji-custom/server/index.js +++ b/packages/rocketchat-emoji-custom/server/index.js @@ -1,6 +1,5 @@ import './startup/emoji-custom'; import './startup/settings'; -import './models/EmojiCustom'; import './publications/fullEmojiData'; import './methods/listEmojiCustom'; import './methods/deleteEmojiCustom'; diff --git a/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js b/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js index 38d4b6c6ee15..b4f1df41cf38 100644 --- a/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js @@ -1,13 +1,15 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { EmojiCustom } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; import { RocketChatFileEmojiCustomInstance } from '../startup/emoji-custom'; Meteor.methods({ deleteEmojiCustom(emojiID) { let emoji = null; - if (RocketChat.authz.hasPermission(this.userId, 'manage-emoji')) { - emoji = RocketChat.models.EmojiCustom.findOneByID(emojiID); + if (hasPermission(this.userId, 'manage-emoji')) { + emoji = EmojiCustom.findOneByID(emojiID); } else { throw new Meteor.Error('not_authorized'); } @@ -17,8 +19,8 @@ Meteor.methods({ } RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emoji.name }.${ emoji.extension }`)); - RocketChat.models.EmojiCustom.removeByID(emojiID); - RocketChat.Notifications.notifyLogged('deleteEmojiCustom', { emojiData: emoji }); + EmojiCustom.removeByID(emojiID); + Notifications.notifyLogged('deleteEmojiCustom', { emojiData: emoji }); return true; }, diff --git a/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js b/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js index 09112918bb5b..40d07322f4ba 100644 --- a/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js +++ b/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js @@ -1,12 +1,14 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { EmojiCustom } from 'meteor/rocketchat:models'; import { RocketChatFileEmojiCustomInstance } from '../startup/emoji-custom'; import _ from 'underscore'; import s from 'underscore.string'; Meteor.methods({ insertOrUpdateEmoji(emojiData) { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-emoji')) { + if (!hasPermission(this.userId, 'manage-emoji')) { throw new Meteor.Error('not_authorized'); } @@ -41,14 +43,14 @@ Meteor.methods({ let matchingResults = []; if (emojiData._id) { - matchingResults = RocketChat.models.EmojiCustom.findByNameOrAliasExceptID(emojiData.name, emojiData._id).fetch(); + matchingResults = EmojiCustom.findByNameOrAliasExceptID(emojiData.name, emojiData._id).fetch(); for (const alias of emojiData.aliases) { - matchingResults = matchingResults.concat(RocketChat.models.EmojiCustom.findByNameOrAliasExceptID(alias, emojiData._id).fetch()); + matchingResults = matchingResults.concat(EmojiCustom.findByNameOrAliasExceptID(alias, emojiData._id).fetch()); } } else { - matchingResults = RocketChat.models.EmojiCustom.findByNameOrAlias(emojiData.name).fetch(); + matchingResults = EmojiCustom.findByNameOrAlias(emojiData.name).fetch(); for (const alias of emojiData.aliases) { - matchingResults = matchingResults.concat(RocketChat.models.EmojiCustom.findByNameOrAlias(alias).fetch()); + matchingResults = matchingResults.concat(EmojiCustom.findByNameOrAlias(alias).fetch()); } } @@ -64,9 +66,9 @@ Meteor.methods({ extension: emojiData.extension, }; - const _id = RocketChat.models.EmojiCustom.create(createEmoji); + const _id = EmojiCustom.create(createEmoji); - RocketChat.Notifications.notifyLogged('updateEmojiCustom', { emojiData: createEmoji }); + Notifications.notifyLogged('updateEmojiCustom', { emojiData: createEmoji }); return _id; } else { @@ -77,7 +79,7 @@ Meteor.methods({ RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.extension }`)); RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`)); - RocketChat.models.EmojiCustom.setExtension(emojiData._id, emojiData.extension); + EmojiCustom.setExtension(emojiData._id, emojiData.extension); } else if (emojiData.name !== emojiData.previousName) { const rs = RocketChatFileEmojiCustomInstance.getFileWithReadStream(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`)); if (rs !== null) { @@ -91,16 +93,16 @@ Meteor.methods({ } if (emojiData.name !== emojiData.previousName) { - RocketChat.models.EmojiCustom.setName(emojiData._id, emojiData.name); + EmojiCustom.setName(emojiData._id, emojiData.name); } if (emojiData.aliases) { - RocketChat.models.EmojiCustom.setAliases(emojiData._id, emojiData.aliases); + EmojiCustom.setAliases(emojiData._id, emojiData.aliases); } else { - RocketChat.models.EmojiCustom.setAliases(emojiData._id, []); + EmojiCustom.setAliases(emojiData._id, []); } - RocketChat.Notifications.notifyLogged('updateEmojiCustom', { emojiData }); + Notifications.notifyLogged('updateEmojiCustom', { emojiData }); return true; } diff --git a/packages/rocketchat-emoji-custom/server/methods/listEmojiCustom.js b/packages/rocketchat-emoji-custom/server/methods/listEmojiCustom.js index 876555266596..ebc34347fa1a 100644 --- a/packages/rocketchat-emoji-custom/server/methods/listEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/server/methods/listEmojiCustom.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { EmojiCustom } from 'meteor/rocketchat:models'; Meteor.methods({ listEmojiCustom(options = {}) { - return RocketChat.models.EmojiCustom.find(options).fetch(); + return EmojiCustom.find(options).fetch(); }, }); diff --git a/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js b/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js index a99da17ffa23..a8d27d449056 100644 --- a/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import { RocketChatFile } from 'meteor/rocketchat:file'; import { RocketChatFileEmojiCustomInstance } from '../startup/emoji-custom'; Meteor.methods({ uploadEmojiCustom(binaryContent, contentType, emojiData) { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-emoji')) { + if (!hasPermission(this.userId, 'manage-emoji')) { throw new Meteor.Error('not_authorized'); } @@ -17,7 +18,7 @@ Meteor.methods({ RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`)); const ws = RocketChatFileEmojiCustomInstance.createWriteStream(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`), contentType); ws.on('end', Meteor.bindEnvironment(() => - Meteor.setTimeout(() => RocketChat.Notifications.notifyLogged('updateEmojiCustom', { emojiData }), 500) + Meteor.setTimeout(() => Notifications.notifyLogged('updateEmojiCustom', { emojiData }), 500) )); rs.pipe(ws); diff --git a/packages/rocketchat-emoji-custom/server/publications/fullEmojiData.js b/packages/rocketchat-emoji-custom/server/publications/fullEmojiData.js index daffef5d2b52..3d5f9ca7ed85 100644 --- a/packages/rocketchat-emoji-custom/server/publications/fullEmojiData.js +++ b/packages/rocketchat-emoji-custom/server/publications/fullEmojiData.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { EmojiCustom } from 'meteor/rocketchat:models'; import s from 'underscore.string'; Meteor.publish('fullEmojiData', function(filter, limit) { @@ -23,8 +23,8 @@ Meteor.publish('fullEmojiData', function(filter, limit) { if (filter) { const filterReg = new RegExp(s.escapeRegExp(filter), 'i'); - return RocketChat.models.EmojiCustom.findByNameOrAlias(filterReg, options); + return EmojiCustom.findByNameOrAlias(filterReg, options); } - return RocketChat.models.EmojiCustom.find({}, options); + return EmojiCustom.find({}, options); }); diff --git a/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js b/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js index 7d4ea3b7906c..e58ba8336ad6 100644 --- a/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js +++ b/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { RocketChatFile } from 'meteor/rocketchat:file'; import _ from 'underscore'; @@ -9,8 +9,8 @@ export let RocketChatFileEmojiCustomInstance; Meteor.startup(function() { let storeType = 'GridFS'; - if (RocketChat.settings.get('EmojiUpload_Storage_Type')) { - storeType = RocketChat.settings.get('EmojiUpload_Storage_Type'); + if (settings.get('EmojiUpload_Storage_Type')) { + storeType = settings.get('EmojiUpload_Storage_Type'); } const RocketChatStore = RocketChatFile[storeType]; @@ -22,9 +22,9 @@ Meteor.startup(function() { console.log(`Using ${ storeType } for custom emoji storage`.green); let path = '~/uploads'; - if (RocketChat.settings.get('EmojiUpload_FileSystemPath') != null) { - if (RocketChat.settings.get('EmojiUpload_FileSystemPath').trim() !== '') { - path = RocketChat.settings.get('EmojiUpload_FileSystemPath'); + if (settings.get('EmojiUpload_FileSystemPath') != null) { + if (settings.get('EmojiUpload_FileSystemPath').trim() !== '') { + path = settings.get('EmojiUpload_FileSystemPath'); } } diff --git a/packages/rocketchat-emoji-custom/server/startup/settings.js b/packages/rocketchat-emoji-custom/server/startup/settings.js index 2b3e516e8e84..7329bff949c9 100644 --- a/packages/rocketchat-emoji-custom/server/startup/settings.js +++ b/packages/rocketchat-emoji-custom/server/startup/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('EmojiCustomFilesystem', function() { +settings.addGroup('EmojiCustomFilesystem', function() { this.add('EmojiUpload_Storage_Type', 'GridFS', { type: 'select', values: [{ diff --git a/packages/rocketchat-lib/client/models/index.js b/packages/rocketchat-lib/client/models/index.js index bcf24e138126..9f619d8adc6a 100644 --- a/packages/rocketchat-lib/client/models/index.js +++ b/packages/rocketchat-lib/client/models/index.js @@ -1,4 +1,4 @@ -import { Base as _Base, Avatars, Uploads, UserDataFiles, CustomSounds } from 'meteor/rocketchat:models'; +import { Base as _Base, Avatars, Uploads, UserDataFiles, CustomSounds, EmojiCustom } from 'meteor/rocketchat:models'; Object.assign(RocketChat.models, { _Base, @@ -6,4 +6,5 @@ Object.assign(RocketChat.models, { Uploads, UserDataFiles, CustomSounds, + EmojiCustom, }); diff --git a/packages/rocketchat-lib/server/models/index.js b/packages/rocketchat-lib/server/models/index.js index ebb3c8bd4bc2..09ea0d36112d 100644 --- a/packages/rocketchat-lib/server/models/index.js +++ b/packages/rocketchat-lib/server/models/index.js @@ -15,6 +15,7 @@ import { Base as _Base, Permissions, Roles, + EmojiCustom, } from 'meteor/rocketchat:models'; Object.assign(RocketChat.models, { @@ -34,4 +35,5 @@ Object.assign(RocketChat.models, { IntegrationHistory, Permissions, Roles, + EmojiCustom, }); diff --git a/packages/rocketchat-models/client/index.js b/packages/rocketchat-models/client/index.js index f6fbaee7114a..0185653df2e1 100644 --- a/packages/rocketchat-models/client/index.js +++ b/packages/rocketchat-models/client/index.js @@ -18,6 +18,7 @@ import { UserAndRoom } from './models/UserAndRoom'; import { UserRoles } from './models/UserRoles'; import { AuthzCachedCollection, ChatPermissions } from './models/ChatPermissions'; import CustomSounds from './models/CustomSounds'; +import EmojiCustom from './models/EmojiCustom'; import _ from 'underscore'; const Users = _.extend({}, users, Meteor.users); @@ -49,4 +50,5 @@ export { ChatSubscription, Rooms, CustomSounds, + EmojiCustom, }; diff --git a/packages/rocketchat-emoji-custom/client/models/EmojiCustom.js b/packages/rocketchat-models/client/models/EmojiCustom.js similarity index 59% rename from packages/rocketchat-emoji-custom/client/models/EmojiCustom.js rename to packages/rocketchat-models/client/models/EmojiCustom.js index 79794f59848e..bb70c24fa1a5 100644 --- a/packages/rocketchat-emoji-custom/client/models/EmojiCustom.js +++ b/packages/rocketchat-models/client/models/EmojiCustom.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -class EmojiCustom extends RocketChat.models._Base { +export class EmojiCustom extends Base { constructor() { super(); this._initModel('custom_emoji'); @@ -19,4 +19,4 @@ class EmojiCustom extends RocketChat.models._Base { } } -RocketChat.models.EmojiCustom = new EmojiCustom(); +export default new EmojiCustom(); diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index 54b5dfc3289c..3d3d9e52b3c4 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -17,6 +17,7 @@ import CustomSounds from './models/CustomSounds'; import Integrations from './models/Integrations'; import IntegrationHistory from './models/IntegrationHistory'; import CredentialTokens from './models/CredentialTokens'; +import EmojiCustom from './models/EmojiCustom'; export { Base, @@ -38,4 +39,5 @@ export { Integrations, IntegrationHistory, CredentialTokens, + EmojiCustom, }; diff --git a/packages/rocketchat-emoji-custom/server/models/EmojiCustom.js b/packages/rocketchat-models/server/models/EmojiCustom.js similarity index 88% rename from packages/rocketchat-emoji-custom/server/models/EmojiCustom.js rename to packages/rocketchat-models/server/models/EmojiCustom.js index babaf960fba0..8f9f676072f5 100644 --- a/packages/rocketchat-emoji-custom/server/models/EmojiCustom.js +++ b/packages/rocketchat-models/server/models/EmojiCustom.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -class EmojiCustom extends RocketChat.models._Base { +class EmojiCustom extends Base { constructor() { super('custom_emoji'); @@ -88,4 +88,4 @@ class EmojiCustom extends RocketChat.models._Base { } } -RocketChat.models.EmojiCustom = new EmojiCustom(); +export default new EmojiCustom(); From c70a809ac418dd68f53c15a0bb59b4d1ca837119 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 22:46:29 -0200 Subject: [PATCH 23/33] Remove dependency of RC namespace in rc-emojione, error-handler, gh-enterprise and gitlab (#13257) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * Remove dependency of RC namespace in rc-channel-mail-messages * Remove dependency of RC namespace in rc-cloud * Remove dependency of RC namespace in rc-colors * Remove dependency of RC namespace in rc-cors * Remove dependency of RC namespace in rc-crowd * Remove dependency of RC namespace in rc-dolphin * Remove dependency of RC namespace in rc-drupal * Move Emoji custom server and client models to rc-models * Remove dependency of RC namespace in rc-emoji-custom * Remove dependency of RC namespace in rc-emojione * Remove dependency of RC namespace in rc-error-handler * Remove dependency of RC namespace in rc-gh-enterprise * Remove dependency of RC namespace in rc-gitlab --- .../lib/rocketchat.js | 31 ++++++++++--------- packages/rocketchat-emoji-emojione/package.js | 3 +- .../server/callbacks.js | 4 +-- packages/rocketchat-error-handler/package.js | 2 ++ .../rocketchat-error-handler/server/index.js | 6 +++- .../server/lib/RocketChat.ErrorHandler.js | 14 +++++---- .../server/startup/settings.js | 4 +-- .../lib/common.js | 8 ++--- .../rocketchat-github-enterprise/package.js | 2 +- .../server/startup.js | 4 +-- packages/rocketchat-gitlab/lib/common.js | 8 ++--- packages/rocketchat-gitlab/package.js | 2 +- packages/rocketchat-gitlab/server/startup.js | 4 +-- .../rocketchat-lib/server/lib/ErrorHandler.js | 3 ++ 14 files changed, 54 insertions(+), 41 deletions(-) create mode 100644 packages/rocketchat-lib/server/lib/ErrorHandler.js diff --git a/packages/rocketchat-emoji-emojione/lib/rocketchat.js b/packages/rocketchat-emoji-emojione/lib/rocketchat.js index 552cac6ee8a4..1aa06e0deeea 100644 --- a/packages/rocketchat-emoji-emojione/lib/rocketchat.js +++ b/packages/rocketchat-emoji-emojione/lib/rocketchat.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { emoji } from 'meteor/rocketchat:emoji'; +import { getUserPreference } from 'meteor/rocketchat:utils'; import { emojione } from 'meteor/emojione:emojione'; import { emojisByCategory, emojiCategories, toneList } from './emojiPicker'; -RocketChat.emoji.packages.emojione = emojione; -RocketChat.emoji.packages.emojione.imageType = 'png'; -RocketChat.emoji.packages.emojione.sprites = true; -RocketChat.emoji.packages.emojione.emojisByCategory = emojisByCategory; -RocketChat.emoji.packages.emojione.emojiCategories = emojiCategories; -RocketChat.emoji.packages.emojione.toneList = toneList; +emoji.packages.emojione = emojione; +emoji.packages.emojione.imageType = 'png'; +emoji.packages.emojione.sprites = true; +emoji.packages.emojione.emojisByCategory = emojisByCategory; +emoji.packages.emojione.emojiCategories = emojiCategories; +emoji.packages.emojione.toneList = toneList; -RocketChat.emoji.packages.emojione.render = function(emoji) { +emoji.packages.emojione.render = function(emoji) { return emojione.toImage(emoji); }; @@ -30,20 +31,20 @@ function isSetNotNull(fn) { // RocketChat.emoji.list is the collection of emojis from all emoji packages for (const key in emojione.emojioneList) { if (emojione.emojioneList.hasOwnProperty(key)) { - const emoji = emojione.emojioneList[key]; - emoji.emojiPackage = 'emojione'; - RocketChat.emoji.list[key] = emoji; + const currentEmoji = emojione.emojioneList[key]; + currentEmoji.emojiPackage = 'emojione'; + emoji.list[key] = currentEmoji; } } // Additional settings -- ascii emojis Meteor.startup(function() { Tracker.autorun(function() { - if (isSetNotNull(() => RocketChat.emoji.packages.emojione)) { - if (isSetNotNull(() => RocketChat.getUserPreference(Meteor.userId(), 'convertAsciiEmoji'))) { - RocketChat.emoji.packages.emojione.ascii = RocketChat.getUserPreference(Meteor.userId(), 'convertAsciiEmoji'); + if (isSetNotNull(() => emoji.packages.emojione)) { + if (isSetNotNull(() => getUserPreference(Meteor.userId(), 'convertAsciiEmoji'))) { + emoji.packages.emojione.ascii = getUserPreference(Meteor.userId(), 'convertAsciiEmoji'); } else { - RocketChat.emoji.packages.emojione.ascii = true; + emoji.packages.emojione.ascii = true; } } }); diff --git a/packages/rocketchat-emoji-emojione/package.js b/packages/rocketchat-emoji-emojione/package.js index 2314d203164d..1f4c2be79c26 100644 --- a/packages/rocketchat-emoji-emojione/package.js +++ b/packages/rocketchat-emoji-emojione/package.js @@ -10,7 +10,8 @@ Package.onUse(function(api) { 'ecmascript', 'emojione:emojione@2.2.6', 'rocketchat:emoji', - 'rocketchat:lib', + 'rocketchat:callbacks', + 'rocketchat:utils', ]); api.addFiles('client/sprites.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-emoji-emojione/server/callbacks.js b/packages/rocketchat-emoji-emojione/server/callbacks.js index 2c0edcadee73..1f18a75e032b 100644 --- a/packages/rocketchat-emoji-emojione/server/callbacks.js +++ b/packages/rocketchat-emoji-emojione/server/callbacks.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { emojione } from 'meteor/emojione:emojione'; Meteor.startup(function() { - RocketChat.callbacks.add('beforeSendMessageNotifications', (message) => emojione.shortnameToUnicode(message)); + callbacks.add('beforeSendMessageNotifications', (message) => emojione.shortnameToUnicode(message)); }); diff --git a/packages/rocketchat-error-handler/package.js b/packages/rocketchat-error-handler/package.js index 77dada968925..de99c694aa3a 100644 --- a/packages/rocketchat-error-handler/package.js +++ b/packages/rocketchat-error-handler/package.js @@ -8,7 +8,9 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', + 'rocketchat:settings', 'rocketchat:lib', + 'rocketchat:models', 'templating', ]); diff --git a/packages/rocketchat-error-handler/server/index.js b/packages/rocketchat-error-handler/server/index.js index 183513dd2b60..3f74d5012161 100644 --- a/packages/rocketchat-error-handler/server/index.js +++ b/packages/rocketchat-error-handler/server/index.js @@ -1,2 +1,6 @@ -import './lib/RocketChat.ErrorHandler'; +import ErrorHandler from './lib/RocketChat.ErrorHandler'; import './startup/settings'; + +export { + ErrorHandler, +}; diff --git a/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js b/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js index 10443e051adb..83c90fb94d47 100644 --- a/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js +++ b/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users, Rooms } from 'meteor/rocketchat:models'; +import { sendMessage } from 'meteor/rocketchat:lib'; class ErrorHandler { constructor() { @@ -10,7 +12,7 @@ class ErrorHandler { Meteor.startup(() => { this.registerHandlers(); - RocketChat.settings.get('Log_Exceptions_to_Channel', (key, value) => { + settings.get('Log_Exceptions_to_Channel', (key, value) => { this.rid = null; const roomName = value.trim(); if (roomName) { @@ -47,7 +49,7 @@ class ErrorHandler { getRoomId(roomName) { roomName = roomName.replace('#'); - const room = RocketChat.models.Rooms.findOneByName(roomName, { fields: { _id: 1, t: 1 } }); + const room = Rooms.findOneByName(roomName, { fields: { _id: 1, t: 1 } }); if (!room || (room.t !== 'c' && room.t !== 'p')) { return; } @@ -59,14 +61,14 @@ class ErrorHandler { return; } this.lastError = message; - const user = RocketChat.models.Users.findOneById('rocket.cat'); + const user = Users.findOneById('rocket.cat'); if (stack) { message = `${ message }\n\`\`\`\n${ stack }\n\`\`\``; } - RocketChat.sendMessage(user, { msg: message }, { _id: this.rid }); + sendMessage(user, { msg: message }, { _id: this.rid }); } } -RocketChat.ErrorHandler = new ErrorHandler; +export default new ErrorHandler; diff --git a/packages/rocketchat-error-handler/server/startup/settings.js b/packages/rocketchat-error-handler/server/startup/settings.js index 558340c60a8b..e79851f779a0 100644 --- a/packages/rocketchat-error-handler/server/startup/settings.js +++ b/packages/rocketchat-error-handler/server/startup/settings.js @@ -1,5 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('Logs', function() { +settings.addGroup('Logs', function() { this.add('Log_Exceptions_to_Channel', '', { type: 'string' }); }); diff --git a/packages/rocketchat-github-enterprise/lib/common.js b/packages/rocketchat-github-enterprise/lib/common.js index 86060ab94265..6f91e1efd589 100644 --- a/packages/rocketchat-github-enterprise/lib/common.js +++ b/packages/rocketchat-github-enterprise/lib/common.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { CustomOAuth } from 'meteor/rocketchat:custom-oauth'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; // GitHub Enterprise Server CallBack URL needs to be http(s)://{rocketchat.server}[:port]/_oauth/github_enterprise // In RocketChat -> Administration the URL needs to be http(s)://{github.enterprise.server}/ @@ -21,7 +21,7 @@ const GitHubEnterprise = new CustomOAuth('github_enterprise', config); if (Meteor.isServer) { Meteor.startup(function() { - RocketChat.settings.get('API_GitHub_Enterprise_URL', function(key, value) { + settings.get('API_GitHub_Enterprise_URL', function(key, value) { config.serverURL = value; GitHubEnterprise.configure(config); }); @@ -29,8 +29,8 @@ if (Meteor.isServer) { } else { Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('API_GitHub_Enterprise_URL')) { - config.serverURL = RocketChat.settings.get('API_GitHub_Enterprise_URL'); + if (settings.get('API_GitHub_Enterprise_URL')) { + config.serverURL = settings.get('API_GitHub_Enterprise_URL'); GitHubEnterprise.configure(config); } }); diff --git a/packages/rocketchat-github-enterprise/package.js b/packages/rocketchat-github-enterprise/package.js index f4b1a620dd06..0e46f0058fa5 100644 --- a/packages/rocketchat-github-enterprise/package.js +++ b/packages/rocketchat-github-enterprise/package.js @@ -7,7 +7,7 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', 'rocketchat:custom-oauth', 'templating', ]); diff --git a/packages/rocketchat-github-enterprise/server/startup.js b/packages/rocketchat-github-enterprise/server/startup.js index 9f20e8ab0fb3..1e63e0376ecb 100644 --- a/packages/rocketchat-github-enterprise/server/startup.js +++ b/packages/rocketchat-github-enterprise/server/startup.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('OAuth', function() { +settings.addGroup('OAuth', function() { this.section('GitHub Enterprise', function() { const enableQuery = { _id: 'Accounts_OAuth_GitHub_Enterprise', diff --git a/packages/rocketchat-gitlab/lib/common.js b/packages/rocketchat-gitlab/lib/common.js index e187ef50e7b8..9871f5bccc92 100644 --- a/packages/rocketchat-gitlab/lib/common.js +++ b/packages/rocketchat-gitlab/lib/common.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { CustomOAuth } from 'meteor/rocketchat:custom-oauth'; const config = { @@ -17,7 +17,7 @@ const Gitlab = new CustomOAuth('gitlab', config); if (Meteor.isServer) { Meteor.startup(function() { - RocketChat.settings.get('API_Gitlab_URL', function(key, value) { + settings.get('API_Gitlab_URL', function(key, value) { config.serverURL = value.trim().replace(/\/*$/, ''); Gitlab.configure(config); }); @@ -25,8 +25,8 @@ if (Meteor.isServer) { } else { Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('API_Gitlab_URL')) { - config.serverURL = RocketChat.settings.get('API_Gitlab_URL').trim().replace(/\/*$/, ''); + if (settings.get('API_Gitlab_URL')) { + config.serverURL = settings.get('API_Gitlab_URL').trim().replace(/\/*$/, ''); Gitlab.configure(config); } }); diff --git a/packages/rocketchat-gitlab/package.js b/packages/rocketchat-gitlab/package.js index 2afca082d079..ed1ce14b30e9 100644 --- a/packages/rocketchat-gitlab/package.js +++ b/packages/rocketchat-gitlab/package.js @@ -7,7 +7,7 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', 'rocketchat:custom-oauth', 'templating', ]); diff --git a/packages/rocketchat-gitlab/server/startup.js b/packages/rocketchat-gitlab/server/startup.js index 843b10015b9e..62068ea061ee 100644 --- a/packages/rocketchat-gitlab/server/startup.js +++ b/packages/rocketchat-gitlab/server/startup.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('OAuth', function() { +settings.addGroup('OAuth', function() { this.section('GitLab', function() { const enableQuery = { _id: 'Accounts_OAuth_Gitlab', diff --git a/packages/rocketchat-lib/server/lib/ErrorHandler.js b/packages/rocketchat-lib/server/lib/ErrorHandler.js new file mode 100644 index 000000000000..88b5d92f994e --- /dev/null +++ b/packages/rocketchat-lib/server/lib/ErrorHandler.js @@ -0,0 +1,3 @@ +import { ErrorHandler } from 'meteor/rocketchat:error-handler'; + +RocketChat.ErrorHandler = ErrorHandler; From ffa094515650383781057dd91b6d115151e7a8c9 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 22:46:42 -0200 Subject: [PATCH 24/33] Remove dependency of RC namespace in rc-google-natural-language, grant, google-vision and highlight-words (#13258) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * Remove dependency of RC namespace in rc-channel-mail-messages * Remove dependency of RC namespace in rc-cloud * Remove dependency of RC namespace in rc-colors * Remove dependency of RC namespace in rc-cors * Remove dependency of RC namespace in rc-crowd * Remove dependency of RC namespace in rc-dolphin * Remove dependency of RC namespace in rc-drupal * Move Emoji custom server and client models to rc-models * Remove dependency of RC namespace in rc-emoji-custom * Remove dependency of RC namespace in rc-emojione * Remove dependency of RC namespace in rc-error-handler * Remove dependency of RC namespace in rc-gh-enterprise * Remove dependency of RC namespace in rc-gitlab * Remove dependency of RC namespace in rc-google-natural-language * Remove dependency of RC namespace in rc-grant * Remove dependency of RC namespace in rc-highlight-words * Remove dependency of RC namespace in rc-google-vision * Fix lint --- .../client/index.js | 6 +- .../package.js | 9 ++- .../server/index.js | 15 ++--- .../server/models/Rooms.js | 5 -- .../server/settings.js | 6 +- .../client/googlevision.js | 21 ++++--- packages/rocketchat-google-vision/package.js | 5 +- .../server/googlevision.js | 61 ++++++++++--------- .../rocketchat-google-vision/server/index.js | 1 - .../server/models/Messages.js | 12 ---- .../server/settings.js | 30 ++++----- packages/rocketchat-grant/package.js | 3 +- .../rocketchat-grant/server/authenticate.js | 14 ++--- .../client/client.js | 7 ++- .../rocketchat-highlight-words/package.js | 3 +- .../server/models/Messages.js | 11 ++++ .../rocketchat-models/server/models/Rooms.js | 4 ++ 17 files changed, 109 insertions(+), 104 deletions(-) delete mode 100644 packages/rocketchat-google-natural-language/server/models/Rooms.js delete mode 100644 packages/rocketchat-google-vision/server/models/Messages.js diff --git a/packages/rocketchat-google-natural-language/client/index.js b/packages/rocketchat-google-natural-language/client/index.js index b2be0f808eec..144d68e62d9c 100644 --- a/packages/rocketchat-google-natural-language/client/index.js +++ b/packages/rocketchat-google-natural-language/client/index.js @@ -1,10 +1,10 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatRoom } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { ChatRoom } from 'meteor/rocketchat:models'; Template.room.helpers({ sentimentSmile() { - if (!RocketChat.settings.get('GoogleNaturalLanguage_Enabled')) { + if (!settings.get('GoogleNaturalLanguage_Enabled')) { return; } diff --git a/packages/rocketchat-google-natural-language/package.js b/packages/rocketchat-google-natural-language/package.js index fb548c473646..31c32abd2fec 100644 --- a/packages/rocketchat-google-natural-language/package.js +++ b/packages/rocketchat-google-natural-language/package.js @@ -9,12 +9,11 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'http', - 'rocketchat:lib', - ]); - api.use([ + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:models', 'templating', - 'rocketchat:ui', - ], 'client'); + ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-google-natural-language/server/index.js b/packages/rocketchat-google-natural-language/server/index.js index 8172b58ea06d..36ddc43dbb20 100644 --- a/packages/rocketchat-google-natural-language/server/index.js +++ b/packages/rocketchat-google-natural-language/server/index.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import './settings.js'; -import './models/Rooms.js'; import googleLanguage from '@google-cloud/language'; let languageClient; -RocketChat.settings.get('GoogleNaturalLanguage_ServiceAccount', (key, value) => { +settings.get('GoogleNaturalLanguage_ServiceAccount', (key, value) => { if (value) { try { languageClient = googleLanguage({ @@ -26,17 +27,17 @@ const setRoomSentiment = function(message) { languageClient.detectSentiment(message.msg, Meteor.bindEnvironment((error, result) => { if (!error) { - RocketChat.models.Rooms.setSentiment(message.rid, result); + Rooms.setSentiment(message.rid, result); } })); return message; }; -RocketChat.settings.get('GoogleNaturalLanguage_Enabled', (key, value) => { +settings.get('GoogleNaturalLanguage_Enabled', (key, value) => { if (value) { - RocketChat.callbacks.add('afterSaveMessage', setRoomSentiment, RocketChat.callbacks.priority.MEDIUM, 'GoogleNaturalLanguage'); + callbacks.add('afterSaveMessage', setRoomSentiment, callbacks.priority.MEDIUM, 'GoogleNaturalLanguage'); } else { - RocketChat.callbacks.remove('afterSaveMessage', 'GoogleNaturalLanguage'); + callbacks.remove('afterSaveMessage', 'GoogleNaturalLanguage'); } }); diff --git a/packages/rocketchat-google-natural-language/server/models/Rooms.js b/packages/rocketchat-google-natural-language/server/models/Rooms.js deleted file mode 100644 index bf97b3d7feb1..000000000000 --- a/packages/rocketchat-google-natural-language/server/models/Rooms.js +++ /dev/null @@ -1,5 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.setSentiment = function(roomId, sentiment) { - return this.update({ _id: roomId }, { $set: { sentiment } }); -}; diff --git a/packages/rocketchat-google-natural-language/server/settings.js b/packages/rocketchat-google-natural-language/server/settings.js index 7d8784c783ad..6f880cd40ca9 100644 --- a/packages/rocketchat-google-natural-language/server/settings.js +++ b/packages/rocketchat-google-natural-language/server/settings.js @@ -1,15 +1,15 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.add('GoogleNaturalLanguage_Enabled', false, { + settings.add('GoogleNaturalLanguage_Enabled', false, { type: 'boolean', group: 'Message', section: 'Google Natural Language', public: true, i18nLabel: 'Enabled', }); - RocketChat.settings.add('GoogleNaturalLanguage_ServiceAccount', '', { + settings.add('GoogleNaturalLanguage_ServiceAccount', '', { type: 'string', group: 'Message', section: 'Google Natural Language', diff --git a/packages/rocketchat-google-vision/client/googlevision.js b/packages/rocketchat-google-vision/client/googlevision.js index bcd115b781a4..5c9d0b7b92e3 100644 --- a/packages/rocketchat-google-vision/client/googlevision.js +++ b/packages/rocketchat-google-vision/client/googlevision.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; -RocketChat.GoogleVision = { +const GoogleVision = { getVisionAttributes(attachment) { const attributes = {}; const labels = []; @@ -52,8 +53,8 @@ RocketChat.GoogleVision = { init() { Tracker.autorun(() => { - if (RocketChat.settings.get('GoogleVision_Enable')) { - RocketChat.callbacks.add('renderMessage', (message) => { + if (settings.get('GoogleVision_Enable')) { + callbacks.add('renderMessage', (message) => { if (message.attachments && message.attachments.length > 0) { for (const index in message.attachments) { if (message.attachments.hasOwnProperty(index)) { @@ -63,9 +64,9 @@ RocketChat.GoogleVision = { } } return message; - }, RocketChat.callbacks.priority.HIGH - 3, 'googlevision'); + }, callbacks.priority.HIGH - 3, 'googlevision'); - RocketChat.callbacks.add('streamMessage', (message) => { + callbacks.add('streamMessage', (message) => { if (message.attachments && message.attachments.length > 0) { for (const index in message.attachments) { if (message.attachments.hasOwnProperty(index)) { @@ -74,15 +75,15 @@ RocketChat.GoogleVision = { } } } - }, RocketChat.callbacks.priority.HIGH - 3, 'googlevision-stream'); + }, callbacks.priority.HIGH - 3, 'googlevision-stream'); } else { - RocketChat.callbacks.remove('renderMessage', 'googlevision'); - RocketChat.callbacks.remove('streamMessage', 'googlevision-stream'); + callbacks.remove('renderMessage', 'googlevision'); + callbacks.remove('streamMessage', 'googlevision-stream'); } }); }, }; Meteor.startup(function() { - RocketChat.GoogleVision.init(); + GoogleVision.init(); }); diff --git a/packages/rocketchat-google-vision/package.js b/packages/rocketchat-google-vision/package.js index 50cbf897c353..fcdcb96ad762 100644 --- a/packages/rocketchat-google-vision/package.js +++ b/packages/rocketchat-google-vision/package.js @@ -8,7 +8,10 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:notifications', 'rocketchat:file-upload', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-google-vision/server/googlevision.js b/packages/rocketchat-google-vision/server/googlevision.js index 4b7b047b0d48..5fe3dff4c879 100644 --- a/packages/rocketchat-google-vision/server/googlevision.js +++ b/packages/rocketchat-google-vision/server/googlevision.js @@ -1,7 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Uploads, Settings, Users, Messages } from 'meteor/rocketchat:models'; import { FileUpload } from 'meteor/rocketchat:file-upload'; class GoogleVision { @@ -10,12 +13,12 @@ class GoogleVision { this.vision = require('@google-cloud/vision'); this.storageClient = {}; this.visionClient = {}; - this.enabled = RocketChat.settings.get('GoogleVision_Enable'); + this.enabled = settings.get('GoogleVision_Enable'); this.serviceAccount = {}; - RocketChat.settings.get('GoogleVision_Enable', (key, value) => { + settings.get('GoogleVision_Enable', (key, value) => { this.enabled = value; }); - RocketChat.settings.get('GoogleVision_ServiceAccount', (key, value) => { + settings.get('GoogleVision_ServiceAccount', (key, value) => { try { this.serviceAccount = JSON.parse(value); this.storageClient = this.storage({ credentials: this.serviceAccount }); @@ -24,46 +27,46 @@ class GoogleVision { this.serviceAccount = {}; } }); - RocketChat.settings.get('GoogleVision_Block_Adult_Images', (key, value) => { + settings.get('GoogleVision_Block_Adult_Images', (key, value) => { if (value) { - RocketChat.callbacks.add('beforeSaveMessage', this.blockUnsafeImages.bind(this), RocketChat.callbacks.priority.MEDIUM, 'googlevision-blockunsafe'); + callbacks.add('beforeSaveMessage', this.blockUnsafeImages.bind(this), callbacks.priority.MEDIUM, 'googlevision-blockunsafe'); } else { - RocketChat.callbacks.remove('beforeSaveMessage', 'googlevision-blockunsafe'); + callbacks.remove('beforeSaveMessage', 'googlevision-blockunsafe'); } }); - RocketChat.callbacks.add('afterFileUpload', this.annotate.bind(this)); + callbacks.add('afterFileUpload', this.annotate.bind(this)); } incCallCount(count) { const currentMonth = new Date().getMonth(); - const maxMonthlyCalls = RocketChat.settings.get('GoogleVision_Max_Monthly_Calls') || 0; + const maxMonthlyCalls = settings.get('GoogleVision_Max_Monthly_Calls') || 0; if (maxMonthlyCalls > 0) { - if (RocketChat.settings.get('GoogleVision_Current_Month') !== currentMonth) { - RocketChat.settings.set('GoogleVision_Current_Month', currentMonth); + if (settings.get('GoogleVision_Current_Month') !== currentMonth) { + settings.set('GoogleVision_Current_Month', currentMonth); if (count > maxMonthlyCalls) { return false; } - } else if (count + (RocketChat.settings.get('GoogleVision_Current_Month_Calls') || 0) > maxMonthlyCalls) { + } else if (count + (settings.get('GoogleVision_Current_Month_Calls') || 0) > maxMonthlyCalls) { return false; } } - RocketChat.models.Settings.update({ _id: 'GoogleVision_Current_Month_Calls' }, { $inc: { value: count } }); + Settings.update({ _id: 'GoogleVision_Current_Month_Calls' }, { $inc: { value: count } }); return true; } blockUnsafeImages(message) { if (this.enabled && this.serviceAccount && message && message.file && message.file._id) { - const file = RocketChat.models.Uploads.findOne({ _id: message.file._id }); + const file = Uploads.findOne({ _id: message.file._id }); if (file && file.type && file.type.indexOf('image') !== -1 && file.store === 'GoogleCloudStorage:Uploads' && file.GoogleStorage) { if (this.incCallCount(1)) { - const bucket = this.storageClient.bucket(RocketChat.settings.get('FileUpload_GoogleStorage_Bucket')); + const bucket = this.storageClient.bucket(settings.get('FileUpload_GoogleStorage_Bucket')); const bucketFile = bucket.file(file.GoogleStorage.path); const results = Meteor.wrapAsync(this.visionClient.detectSafeSearch, this.visionClient)(bucketFile); if (results && results.adult === true) { FileUpload.getStore('Uploads').deleteById(file._id); - const user = RocketChat.models.Users.findOneById(message.u && message.u._id); + const user = Users.findOneById(message.u && message.u._id); if (user) { - RocketChat.Notifications.notifyUser(user._id, 'message', { + Notifications.notifyUser(user._id, 'message', { _id: Random.id(), rid: message.rid, ts: new Date, @@ -82,39 +85,39 @@ class GoogleVision { annotate({ message }) { const visionTypes = []; - if (RocketChat.settings.get('GoogleVision_Type_Document')) { + if (settings.get('GoogleVision_Type_Document')) { visionTypes.push('document'); } - if (RocketChat.settings.get('GoogleVision_Type_Faces')) { + if (settings.get('GoogleVision_Type_Faces')) { visionTypes.push('faces'); } - if (RocketChat.settings.get('GoogleVision_Type_Landmarks')) { + if (settings.get('GoogleVision_Type_Landmarks')) { visionTypes.push('landmarks'); } - if (RocketChat.settings.get('GoogleVision_Type_Labels')) { + if (settings.get('GoogleVision_Type_Labels')) { visionTypes.push('labels'); } - if (RocketChat.settings.get('GoogleVision_Type_Logos')) { + if (settings.get('GoogleVision_Type_Logos')) { visionTypes.push('logos'); } - if (RocketChat.settings.get('GoogleVision_Type_Properties')) { + if (settings.get('GoogleVision_Type_Properties')) { visionTypes.push('properties'); } - if (RocketChat.settings.get('GoogleVision_Type_SafeSearch')) { + if (settings.get('GoogleVision_Type_SafeSearch')) { visionTypes.push('safeSearch'); } - if (RocketChat.settings.get('GoogleVision_Type_Similar')) { + if (settings.get('GoogleVision_Type_Similar')) { visionTypes.push('similar'); } if (this.enabled && this.serviceAccount && visionTypes.length > 0 && message.file && message.file._id) { - const file = RocketChat.models.Uploads.findOne({ _id: message.file._id }); + const file = Uploads.findOne({ _id: message.file._id }); if (file && file.type && file.type.indexOf('image') !== -1 && file.store === 'GoogleCloudStorage:Uploads' && file.GoogleStorage) { if (this.incCallCount(visionTypes.length)) { - const bucket = this.storageClient.bucket(RocketChat.settings.get('FileUpload_GoogleStorage_Bucket')); + const bucket = this.storageClient.bucket(settings.get('FileUpload_GoogleStorage_Bucket')); const bucketFile = bucket.file(file.GoogleStorage.path); this.visionClient.detect(bucketFile, visionTypes, Meteor.bindEnvironment((error, results) => { if (!error) { - RocketChat.models.Messages.setGoogleVisionData(message._id, this.getAnnotations(visionTypes, results)); + Messages.setGoogleVisionData(message._id, this.getAnnotations(visionTypes, results)); } else { console.trace('GoogleVision error: ', error.stack); } @@ -156,4 +159,4 @@ class GoogleVision { } } -RocketChat.GoogleVision = new GoogleVision; +export default new GoogleVision; diff --git a/packages/rocketchat-google-vision/server/index.js b/packages/rocketchat-google-vision/server/index.js index df4e64972a9d..95ffc9e6e508 100644 --- a/packages/rocketchat-google-vision/server/index.js +++ b/packages/rocketchat-google-vision/server/index.js @@ -1,3 +1,2 @@ import './settings'; import './googlevision'; -import './models/Messages'; diff --git a/packages/rocketchat-google-vision/server/models/Messages.js b/packages/rocketchat-google-vision/server/models/Messages.js deleted file mode 100644 index 257949dd213b..000000000000 --- a/packages/rocketchat-google-vision/server/models/Messages.js +++ /dev/null @@ -1,12 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.setGoogleVisionData = function(messageId, visionData) { - const updateObj = {}; - for (const index in visionData) { - if (visionData.hasOwnProperty(index)) { - updateObj[`attachments.0.${ index }`] = visionData[index]; - } - } - - return this.update({ _id: messageId }, { $set: updateObj }); -}; diff --git a/packages/rocketchat-google-vision/server/settings.js b/packages/rocketchat-google-vision/server/settings.js index e3934ed9a60d..a8c0fe366367 100644 --- a/packages/rocketchat-google-vision/server/settings.js +++ b/packages/rocketchat-google-vision/server/settings.js @@ -1,88 +1,88 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.add('GoogleVision_Enable', false, { + settings.add('GoogleVision_Enable', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', public: true, enableQuery: { _id: 'FileUpload_Storage_Type', value: 'GoogleCloudStorage' }, }); - RocketChat.settings.add('GoogleVision_ServiceAccount', '', { + settings.add('GoogleVision_ServiceAccount', '', { type: 'string', group: 'FileUpload', section: 'Google Vision', multiline: true, enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Max_Monthly_Calls', 0, { + settings.add('GoogleVision_Max_Monthly_Calls', 0, { type: 'int', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Current_Month', 0, { + settings.add('GoogleVision_Current_Month', 0, { type: 'int', group: 'FileUpload', section: 'Google Vision', hidden: true, }); - RocketChat.settings.add('GoogleVision_Current_Month_Calls', 0, { + settings.add('GoogleVision_Current_Month_Calls', 0, { type: 'int', group: 'FileUpload', section: 'Google Vision', blocked: true, }); - RocketChat.settings.add('GoogleVision_Type_Document', false, { + settings.add('GoogleVision_Type_Document', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Type_Faces', false, { + settings.add('GoogleVision_Type_Faces', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Type_Landmarks', false, { + settings.add('GoogleVision_Type_Landmarks', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Type_Labels', false, { + settings.add('GoogleVision_Type_Labels', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Type_Logos', false, { + settings.add('GoogleVision_Type_Logos', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Type_Properties', false, { + settings.add('GoogleVision_Type_Properties', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Type_SafeSearch', false, { + settings.add('GoogleVision_Type_SafeSearch', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: { _id: 'GoogleVision_Enable', value: true }, }); - RocketChat.settings.add('GoogleVision_Block_Adult_Images', false, { + settings.add('GoogleVision_Block_Adult_Images', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', enableQuery: [{ _id: 'GoogleVision_Enable', value: true }, { _id: 'GoogleVision_Type_SafeSearch', value: true }], }); - RocketChat.settings.add('GoogleVision_Type_Similar', false, { + settings.add('GoogleVision_Type_Similar', false, { type: 'boolean', group: 'FileUpload', section: 'Google Vision', diff --git a/packages/rocketchat-grant/package.js b/packages/rocketchat-grant/package.js index 6438b3cf5072..91c5b6f22aa2 100644 --- a/packages/rocketchat-grant/package.js +++ b/packages/rocketchat-grant/package.js @@ -12,9 +12,8 @@ Package.onUse(function(api) { 'check', 'ecmascript', 'rocketchat:utils', - 'rocketchat:lib', 'rocketchat:accounts', - 'rocketchat:ui', + 'rocketchat:models', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-grant/server/authenticate.js b/packages/rocketchat-grant/server/authenticate.js index 077065114836..494d6316010a 100644 --- a/packages/rocketchat-grant/server/authenticate.js +++ b/packages/rocketchat-grant/server/authenticate.js @@ -1,5 +1,5 @@ import { AccountsServer } from 'meteor/rocketchat:accounts'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; import { Accounts } from 'meteor/accounts-base'; import { Meteor } from 'meteor/meteor'; import { GrantError } from './error'; @@ -24,7 +24,7 @@ const setAvatarFromUrl = (userId, url) => new Promise((resolve, reject) => { }); }); -const findUserByOAuthId = (providerName, id) => RocketChat.models.Users.findOne({ [`settings.profile.oauth.${ providerName }`]: id }); +const findUserByOAuthId = (providerName, id) => Users.findOne({ [`settings.profile.oauth.${ providerName }`]: id }); const addOAuthIdToUserProfile = (user, providerName, providerId) => { const profile = Object.assign({}, user.settings.profile, { @@ -34,7 +34,7 @@ const addOAuthIdToUserProfile = (user, providerName, providerId) => { }, }); - RocketChat.models.Users.setProfile(user.id, profile); + Users.setProfile(user.id, profile); }; function getAccessToken(req) { @@ -69,7 +69,7 @@ export async function authenticate(providerName, req) { if (user) { user.id = user._id; } else { - user = RocketChat.models.Users.findOneByEmailAddress(userData.email); + user = Users.findOneByEmailAddress(userData.email); if (user) { user.id = user._id; } @@ -87,14 +87,14 @@ export async function authenticate(providerName, req) { username: userData.username, }); - RocketChat.models.Users.setProfile(id, { + Users.setProfile(id, { avatar: userData.avatar, oauth: { [providerName]: userData.id, }, }); - RocketChat.models.Users.setName(id, userData.name); - RocketChat.models.Users.setEmailVerified(id, userData.email); + Users.setName(id, userData.name); + Users.setEmailVerified(id, userData.email); await setAvatarFromUrl(id, userData.avatar); diff --git a/packages/rocketchat-highlight-words/client/client.js b/packages/rocketchat-highlight-words/client/client.js index 727d3e16aa15..5012b4a2dc9a 100644 --- a/packages/rocketchat-highlight-words/client/client.js +++ b/packages/rocketchat-highlight-words/client/client.js @@ -3,7 +3,8 @@ * @param {Object} message - The message object */ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { getUserPreference } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; import { highlightWords } from './helper'; @@ -18,11 +19,11 @@ function HighlightWordsClient(message) { } } - const to_highlight = RocketChat.getUserPreference(Meteor.user(), 'highlights'); + const to_highlight = getUserPreference(Meteor.user(), 'highlights'); msg = highlightWords(msg, to_highlight); message.html = msg; return message; } -RocketChat.callbacks.add('renderMessage', HighlightWordsClient, RocketChat.callbacks.priority.MEDIUM + 1, 'highlight-words'); +callbacks.add('renderMessage', HighlightWordsClient, callbacks.priority.MEDIUM + 1, 'highlight-words'); diff --git a/packages/rocketchat-highlight-words/package.js b/packages/rocketchat-highlight-words/package.js index 65fe19bdb3e6..814e324332d7 100644 --- a/packages/rocketchat-highlight-words/package.js +++ b/packages/rocketchat-highlight-words/package.js @@ -13,7 +13,8 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:callbacks', + 'rocketchat:utils', ]); api.mainModule('client/index.js', 'client'); }); diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index fb4196f84c79..2ccc8d21c8ba 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -33,6 +33,17 @@ export class Messages extends Base { }); } + setGoogleVisionData(messageId, visionData) { + const updateObj = {}; + for (const index in visionData) { + if (visionData.hasOwnProperty(index)) { + updateObj[`attachments.0.${ index }`] = visionData[index]; + } + } + + return this.update({ _id: messageId }, { $set: updateObj }); + } + createRoomSettingsChangedWithTypeRoomIdMessageAndUser(type, roomId, message, user, extraData) { return this.createWithTypeRoomIdMessageAndUser(type, roomId, message, user, extraData); } diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index cd6fb7ff5419..1e8600f944a6 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,10 @@ export class Rooms extends Base { return this.findOne(query, options); } + setSentiment(roomId, sentiment) { + return this.update({ _id: roomId }, { $set: { sentiment } }); + } + setDescriptionById(_id, description) { const query = { _id, From 9ea630659eb869827a87dc6308a14620b6bdb3f1 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Thu, 24 Jan 2019 22:46:56 -0200 Subject: [PATCH 25/33] Remove dependency of RC namespace in rc-iframe-login and all imports, except hipchat-enterprise (#13259) * Move integrations models to rc-models * Move composeMessage function to rc-utils * Move PushNotifications class to push-notifications package * Import variables to remove dependency of RC namespace * Import variables to remove RC namespace dependency inside rc-lib/server/lib * Import variables to remove RC namespace inside rc-lib/server/methods * Import variables to remove dependency with RC namespace * Remove duplicated server settings located in rc-lib * Export function and lib function of rc-lib but keep it inside RC namespace * Import variables from functions and lib to remove RC namespace dependency * Remove dependency of RC namespace in rc-sandstorm * Remove dependency of RC namespace in chatpal-search * Move CreadentialTokens model to rc-models * Move getUsernameSuggestion function and method from server/ to rc-lib * Remove dependency of RC namespace in meteor saml * Remove dependency of RC namespace in rc-theme * Move 2FA Users model to rc-models * Remove dependency of RC namespace in rc-2fa * Remove dependency of RC namespace in rc-action-links * Add action links in the RC namespace * Remove dependency of RC namespace in rc-analytics * Remove dependency of RC namespace in rc-assets * Add Assets in RC namespace * Remove dependency of RC namespace in rc-autolinker * Move autotranslate models to rc-models * Partial remove dependency of Rc namespace in rc-autotranslate * Remove dependency of RC namespace in rc-markdown * Finish of remotion of RC namespace in rc-autotranslate * Import Autotranslate where it has been used * Fix lint * Rename Assets variable to avoid conflicts * Fix rename Assets * Remove dependency of RC namespace in rc-blockstack * Remove RC dependency in bot-helpers * Remove RC dependency in rc-cas * Move some functions from tokenpass to channel settings and models * Move some function from livestream to channel settings * Remove dependency of RC namespace in rc-channel-settings * Fix wrong imports * Remove dependency of RC namespace in rc-channel-mail-messages * Remove dependency of RC namespace in rc-cloud * Remove dependency of RC namespace in rc-colors * Remove dependency of RC namespace in rc-cors * Remove dependency of RC namespace in rc-crowd * Remove dependency of RC namespace in rc-dolphin * Remove dependency of RC namespace in rc-drupal * Move Emoji custom server and client models to rc-models * Remove dependency of RC namespace in rc-emoji-custom * Remove dependency of RC namespace in rc-emojione * Remove dependency of RC namespace in rc-error-handler * Remove dependency of RC namespace in rc-gh-enterprise * Remove dependency of RC namespace in rc-gitlab * Remove dependency of RC namespace in rc-google-natural-language * Remove dependency of RC namespace in rc-grant * Remove dependency of RC namespace in rc-highlight-words * Remove dependency of RC namespace in rc-google-vision * Fix lint * Remove dependency of RC namespace in rc-iframe-login * Remove dependency of RC namespace in all importes, except hipchat-enterprise --- .../client/iframe_client.js | 10 ++--- packages/rocketchat-iframe-login/package.js | 2 +- .../server/iframe_rocketchat.js | 4 +- packages/rocketchat-importer-csv/package.js | 1 + .../server/importer.js | 29 +++++++------ .../rocketchat-importer-hipchat/package.js | 1 + .../server/importer.js | 17 ++++---- .../package.js | 1 + .../server/importer.js | 18 ++++---- packages/rocketchat-importer-slack/package.js | 1 + .../server/importer.js | 43 ++++++++++--------- 11 files changed, 67 insertions(+), 60 deletions(-) diff --git a/packages/rocketchat-iframe-login/client/iframe_client.js b/packages/rocketchat-iframe-login/client/iframe_client.js index 3e2a47805e2f..5814ad912a47 100644 --- a/packages/rocketchat-iframe-login/client/iframe_client.js +++ b/packages/rocketchat-iframe-login/client/iframe_client.js @@ -1,15 +1,15 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; import { Accounts } from 'meteor/accounts-base'; import { IframeLogin } from 'meteor/rocketchat:ui-utils'; import _ from 'underscore'; +const iframeLogin = new IframeLogin(); + const { _unstoreLoginToken } = Accounts; Accounts._unstoreLoginToken = function(...args) { - RocketChat.iframeLogin.tryLogin(); + iframeLogin.tryLogin(); _unstoreLoginToken.apply(Accounts, args); }; -RocketChat.iframeLogin = new IframeLogin(); window.addEventListener('message', (e) => { if (! _.isObject(e.data)) { @@ -18,7 +18,7 @@ window.addEventListener('message', (e) => { switch (e.data.event) { case 'try-iframe-login': - RocketChat.iframeLogin.tryLogin((error) => { + iframeLogin.tryLogin((error) => { if (error) { e.source.postMessage({ event: 'login-error', @@ -29,7 +29,7 @@ window.addEventListener('message', (e) => { break; case 'login-with-token': - RocketChat.iframeLogin.loginWithToken(e.data, (error) => { + iframeLogin.loginWithToken(e.data, (error) => { if (error) { e.source.postMessage({ event: 'login-error', diff --git a/packages/rocketchat-iframe-login/package.js b/packages/rocketchat-iframe-login/package.js index 9c4e35cc77d3..72c14ccfaf4c 100644 --- a/packages/rocketchat-iframe-login/package.js +++ b/packages/rocketchat-iframe-login/package.js @@ -8,7 +8,7 @@ Package.onUse(function(api) { api.use([ 'rocketchat:logger', 'kadira:flow-router', - 'rocketchat:lib', + 'rocketchat:settings', 'rocketchat:ui-utils', 'accounts-base', 'ecmascript', diff --git a/packages/rocketchat-iframe-login/server/iframe_rocketchat.js b/packages/rocketchat-iframe-login/server/iframe_rocketchat.js index d19634650c37..39afef234bff 100644 --- a/packages/rocketchat-iframe-login/server/iframe_rocketchat.js +++ b/packages/rocketchat-iframe-login/server/iframe_rocketchat.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.addGroup('Accounts', function() { + settings.addGroup('Accounts', function() { this.section('Iframe', function() { this.add('Accounts_iframe_enabled', false, { type: 'boolean', public: true }); this.add('Accounts_iframe_url', '', { type: 'string', public: true }); diff --git a/packages/rocketchat-importer-csv/package.js b/packages/rocketchat-importer-csv/package.js index 0e52f630d893..4d8f4c2df42c 100644 --- a/packages/rocketchat-importer-csv/package.js +++ b/packages/rocketchat-importer-csv/package.js @@ -9,6 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:lib', + 'rocketchat:models', 'rocketchat:importer', 'rocketchat:logger', ]); diff --git a/packages/rocketchat-importer-csv/server/importer.js b/packages/rocketchat-importer-csv/server/importer.js index 07c43c9ad53b..d37523540098 100644 --- a/packages/rocketchat-importer-csv/server/importer.js +++ b/packages/rocketchat-importer-csv/server/importer.js @@ -8,7 +8,8 @@ import { SelectionUser, } from 'meteor/rocketchat:importer'; import { RocketChatFile } from 'meteor/rocketchat:file'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Rooms } from 'meteor/rocketchat:models'; +import { sendMessage } from 'meteor/rocketchat:lib'; export class CsvImporter extends Base { constructor(info) { @@ -180,23 +181,23 @@ export class CsvImporter extends Base { } Meteor.runAsUser(startedByUserId, () => { - let existantUser = RocketChat.models.Users.findOneByEmailAddress(u.email); + let existantUser = Users.findOneByEmailAddress(u.email); // If we couldn't find one by their email address, try to find an existing user by their username if (!existantUser) { - existantUser = RocketChat.models.Users.findOneByUsername(u.username); + existantUser = Users.findOneByUsername(u.username); } if (existantUser) { // since we have an existing user, let's try a few things u.rocketId = existantUser._id; - RocketChat.models.Users.update({ _id: u.rocketId }, { $addToSet: { importIds: u.id } }); + Users.update({ _id: u.rocketId }, { $addToSet: { importIds: u.id } }); } else { const userId = Accounts.createUser({ email: u.email, password: Date.now() + u.name + u.email.toUpperCase() }); Meteor.runAsUser(userId, () => { Meteor.call('setUsername', u.username, { joinDefaultChannelsSilenced: true }); - RocketChat.models.Users.setName(userId, u.name); - RocketChat.models.Users.update({ _id: userId }, { $addToSet: { importIds: u.id } }); + Users.setName(userId, u.name); + Users.update({ _id: userId }, { $addToSet: { importIds: u.id } }); u.rocketId = userId; }); } @@ -214,11 +215,11 @@ export class CsvImporter extends Base { } Meteor.runAsUser(startedByUserId, () => { - const existantRoom = RocketChat.models.Rooms.findOneByName(c.name); + const existantRoom = Rooms.findOneByName(c.name); // If the room exists or the name of it is 'general', then we don't need to create it again if (existantRoom || c.name.toUpperCase() === 'GENERAL') { c.rocketId = c.name.toUpperCase() === 'GENERAL' ? 'GENERAL' : existantRoom._id; - RocketChat.models.Rooms.update({ _id: c.rocketId }, { $addToSet: { importIds: c.id } }); + Rooms.update({ _id: c.rocketId }, { $addToSet: { importIds: c.id } }); } else { // Find the rocketchatId of the user who created this channel let creatorId = startedByUserId; @@ -234,7 +235,7 @@ export class CsvImporter extends Base { c.rocketId = roomInfo.rid; }); - RocketChat.models.Rooms.update({ _id: c.rocketId }, { $addToSet: { importIds: c.id } }); + Rooms.update({ _id: c.rocketId }, { $addToSet: { importIds: c.id } }); } super.addCountCompleted(1); @@ -246,7 +247,7 @@ export class CsvImporter extends Base { if (this.channels.channels.length === 0) { for (const cname of this.messages.keys()) { Meteor.runAsUser(startedByUserId, () => { - const existantRoom = RocketChat.models.Rooms.findOneByName(cname); + const existantRoom = Rooms.findOneByName(cname); if (existantRoom || cname.toUpperCase() === 'GENERAL') { this.channels.channels.push({ id: cname.replace('.', '_'), @@ -270,7 +271,7 @@ export class CsvImporter extends Base { for (const msgs of messagesMap.values()) { for (const msg of msgs.messages) { if (!this.getUserFromUsername(msg.username)) { - const user = RocketChat.models.Users.findOneByUsername(msg.username); + const user = Users.findOneByUsername(msg.username); if (user) { this.users.users.push({ rocketId: user._id, @@ -292,7 +293,7 @@ export class CsvImporter extends Base { continue; } - const room = RocketChat.models.Rooms.findOneById(csvChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } }); + const room = Rooms.findOneById(csvChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } }); Meteor.runAsUser(startedByUserId, () => { const timestamps = {}; for (const [msgGroupData, msgs] of messagesMap.entries()) { @@ -324,7 +325,7 @@ export class CsvImporter extends Base { }, }; - RocketChat.sendMessage(creator, msgObj, room, true); + sendMessage(creator, msgObj, room, true); } super.addCountCompleted(1); @@ -366,7 +367,7 @@ export class CsvImporter extends Base { getUserFromUsername(username) { for (const u of this.users.users) { if (u.username === username) { - return RocketChat.models.Users.findOneById(u.rocketId, { fields: { username: 1 } }); + return Users.findOneById(u.rocketId, { fields: { username: 1 } }); } } } diff --git a/packages/rocketchat-importer-hipchat/package.js b/packages/rocketchat-importer-hipchat/package.js index e98cab765961..4cc9004aa27e 100644 --- a/packages/rocketchat-importer-hipchat/package.js +++ b/packages/rocketchat-importer-hipchat/package.js @@ -9,6 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:lib', + 'rocketchat:models', 'rocketchat:importer', 'rocketchat:logger', ]); diff --git a/packages/rocketchat-importer-hipchat/server/importer.js b/packages/rocketchat-importer-hipchat/server/importer.js index 31d5a7d739c8..e22e74366b91 100644 --- a/packages/rocketchat-importer-hipchat/server/importer.js +++ b/packages/rocketchat-importer-hipchat/server/importer.js @@ -8,7 +8,8 @@ import { SelectionUser, } from 'meteor/rocketchat:importer'; import { RocketChatFile } from 'meteor/rocketchat:file'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Rooms } from 'meteor/rocketchat:models'; +import { sendMessage } from 'meteor/rocketchat:lib'; import _ from 'underscore'; import s from 'underscore.string'; import moment from 'moment'; @@ -178,7 +179,7 @@ export class HipChatImporter extends Base { } Meteor.runAsUser(startedByUserId, () => { - const existantUser = RocketChat.models.Users.findOneByEmailAddress(user.email); + const existantUser = Users.findOneByEmailAddress(user.email); if (existantUser) { user.rocketId = existantUser._id; this.userTags.push({ @@ -203,7 +204,7 @@ export class HipChatImporter extends Base { return Meteor.call('userSetUtcOffset', parseInt(moment().tz(user.timezone).format('Z').toString().split(':')[0])); }); if (user.name != null) { - RocketChat.models.Users.setName(userId, user.name); + Users.setName(userId, user.name); } if (user.is_deleted) { Meteor.call('setUserActiveStatus', userId, false); @@ -222,7 +223,7 @@ export class HipChatImporter extends Base { } Meteor.runAsUser(startedByUserId, () => { channel.name = channel.name.replace(/ /g, ''); - const existantRoom = RocketChat.models.Rooms.findOneByName(channel.name); + const existantRoom = Rooms.findOneByName(channel.name); if (existantRoom) { channel.rocketId = existantRoom._id; } else { @@ -240,7 +241,7 @@ export class HipChatImporter extends Base { const returned = Meteor.call('createChannel', channel.name, []); return channel.rocketId = returned.rid; }); - RocketChat.models.Rooms.update({ + Rooms.update({ _id: channel.rocketId, }, { $set: { @@ -262,7 +263,7 @@ export class HipChatImporter extends Base { Meteor.runAsUser(startedByUserId, () => { const hipchatChannel = this.getHipChatChannelFromName(channel); if (hipchatChannel != null ? hipchatChannel.do_import : undefined) { - const room = RocketChat.models.Rooms.findOneById(hipchatChannel.rocketId, { + const room = Rooms.findOneById(hipchatChannel.rocketId, { fields: { usernames: 1, t: 1, @@ -288,7 +289,7 @@ export class HipChatImporter extends Base { username: user.username, }, }; - RocketChat.sendMessage(user, msgObj, room, true); + sendMessage(user, msgObj, room, true); } else if (!nousers[message.from.user_id]) { nousers[message.from.user_id] = message.from; } @@ -330,7 +331,7 @@ export class HipChatImporter extends Base { getRocketUser(hipchatId) { const user = this.users.users.find((user) => user.user_id === hipchatId); - return user ? RocketChat.models.Users.findOneById(user.rocketId, { + return user ? Users.findOneById(user.rocketId, { fields: { username: 1, name: 1, diff --git a/packages/rocketchat-importer-slack-users/package.js b/packages/rocketchat-importer-slack-users/package.js index dfdee437a0fd..dc6b0b7a74f5 100644 --- a/packages/rocketchat-importer-slack-users/package.js +++ b/packages/rocketchat-importer-slack-users/package.js @@ -9,6 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:lib', + 'rocketchat:models', 'rocketchat:importer', 'rocketchat:logger', ]); diff --git a/packages/rocketchat-importer-slack-users/server/importer.js b/packages/rocketchat-importer-slack-users/server/importer.js index cac2b8db9c67..1a65ba194dc9 100644 --- a/packages/rocketchat-importer-slack-users/server/importer.js +++ b/packages/rocketchat-importer-slack-users/server/importer.js @@ -8,7 +8,7 @@ import { SelectionUser, } from 'meteor/rocketchat:importer'; import { RocketChatFile } from 'meteor/rocketchat:file'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; export class SlackUsersImporter extends Base { constructor(info) { @@ -94,17 +94,17 @@ export class SlackUsersImporter extends Base { } Meteor.runAsUser(startedByUserId, () => { - const existantUser = RocketChat.models.Users.findOneByEmailAddress(u.email) || RocketChat.models.Users.findOneByUsername(u.username); + const existantUser = Users.findOneByEmailAddress(u.email) || Users.findOneByUsername(u.username); let userId; if (existantUser) { // since we have an existing user, let's try a few things userId = existantUser._id; u.rocketId = existantUser._id; - RocketChat.models.Users.update({ _id: u.rocketId }, { $addToSet: { importIds: u.id } }); + Users.update({ _id: u.rocketId }, { $addToSet: { importIds: u.id } }); - RocketChat.models.Users.setEmail(existantUser._id, u.email); - RocketChat.models.Users.setEmailVerified(existantUser._id, u.email); + Users.setEmail(existantUser._id, u.email); + Users.setEmailVerified(existantUser._id, u.email); } else { userId = Accounts.createUser({ username: u.username + Random.id(), password: Date.now() + u.name + u.email.toUpperCase() }); @@ -115,10 +115,10 @@ export class SlackUsersImporter extends Base { Meteor.runAsUser(userId, () => { Meteor.call('setUsername', u.username, { joinDefaultChannelsSilenced: true }); - RocketChat.models.Users.setName(userId, u.name); - RocketChat.models.Users.update({ _id: userId }, { $addToSet: { importIds: u.id } }); - RocketChat.models.Users.setEmail(userId, u.email); - RocketChat.models.Users.setEmailVerified(userId, u.email); + Users.setName(userId, u.name); + Users.update({ _id: userId }, { $addToSet: { importIds: u.id } }); + Users.setEmail(userId, u.email); + Users.setEmailVerified(userId, u.email); u.rocketId = userId; }); } diff --git a/packages/rocketchat-importer-slack/package.js b/packages/rocketchat-importer-slack/package.js index d86ec806a9dc..b391684bd921 100644 --- a/packages/rocketchat-importer-slack/package.js +++ b/packages/rocketchat-importer-slack/package.js @@ -9,6 +9,7 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:lib', + 'rocketchat:models', 'rocketchat:importer', 'rocketchat:logger', ]); diff --git a/packages/rocketchat-importer-slack/server/importer.js b/packages/rocketchat-importer-slack/server/importer.js index bc4e3f406032..32bca264daae 100644 --- a/packages/rocketchat-importer-slack/server/importer.js +++ b/packages/rocketchat-importer-slack/server/importer.js @@ -8,8 +8,9 @@ import { SelectionUser, } from 'meteor/rocketchat:importer'; import { RocketChatFile } from 'meteor/rocketchat:file'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { getAvatarUrlFromUsername } from 'meteor/rocketchat:ui'; +import { Users, Rooms, Messages } from 'meteor/rocketchat:models'; +import { sendMessage } from 'meteor/rocketchat:lib'; import _ from 'underscore'; @@ -162,10 +163,10 @@ export class SlackImporter extends Base { } Meteor.runAsUser(startedByUserId, () => { - const existantUser = RocketChat.models.Users.findOneByEmailAddress(user.profile.email) || RocketChat.models.Users.findOneByUsername(user.name); + const existantUser = Users.findOneByEmailAddress(user.profile.email) || Users.findOneByUsername(user.name); if (existantUser) { user.rocketId = existantUser._id; - RocketChat.models.Users.update({ _id: user.rocketId }, { $addToSet: { importIds: user.id } }); + Users.update({ _id: user.rocketId }, { $addToSet: { importIds: user.id } }); this.userTags.push({ slack: `<@${ user.id }>`, slackLong: `<@${ user.id }|${ user.name }>`, @@ -190,10 +191,10 @@ export class SlackImporter extends Base { } }); - RocketChat.models.Users.update({ _id: userId }, { $addToSet: { importIds: user.id } }); + Users.update({ _id: userId }, { $addToSet: { importIds: user.id } }); if (user.profile.real_name) { - RocketChat.models.Users.setName(userId, user.profile.real_name); + Users.setName(userId, user.profile.real_name); } // Deleted users are 'inactive' users in Rocket.Chat @@ -221,14 +222,14 @@ export class SlackImporter extends Base { } Meteor.runAsUser (startedByUserId, () => { - const existantRoom = RocketChat.models.Rooms.findOneByName(channel.name); + const existantRoom = Rooms.findOneByName(channel.name); if (existantRoom || channel.is_general) { if (channel.is_general && existantRoom && channel.name !== existantRoom.name) { Meteor.call('saveRoomSettings', 'GENERAL', 'roomName', channel.name); } channel.rocketId = channel.is_general ? 'GENERAL' : existantRoom._id; - RocketChat.models.Rooms.update({ _id: channel.rocketId }, { $addToSet: { importIds: channel.id } }); + Rooms.update({ _id: channel.rocketId }, { $addToSet: { importIds: channel.id } }); } else { const users = channel.members .reduce((ret, member) => { @@ -261,7 +262,7 @@ export class SlackImporter extends Base { if (!_.isEmpty(channel.purpose && channel.purpose.value)) { roomUpdate.description = channel.purpose.value; } - RocketChat.models.Rooms.update({ _id: channel.rocketId }, { $set: roomUpdate, $addToSet: { importIds: channel.id } }); + Rooms.update({ _id: channel.rocketId }, { $set: roomUpdate, $addToSet: { importIds: channel.id } }); } this.addCountCompleted(1); }); @@ -277,7 +278,7 @@ export class SlackImporter extends Base { Meteor.runAsUser(startedByUserId, () => { const slackChannel = this.getSlackChannelFromName(channel); if (!slackChannel || !slackChannel.do_import) { return; } - const room = RocketChat.models.Rooms.findOneById(slackChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } }); + const room = Rooms.findOneById(slackChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } }); Object.keys(messagesObj).forEach((date) => { const msgs = messagesObj[date]; msgs.messages.forEach((message) => { @@ -314,25 +315,25 @@ export class SlackImporter extends Base { ...msgDataDefaults, msg: this.convertSlackMessageToRocketChat(message.files[0].url_private_download), }; - RocketChat.sendMessage(this.getRocketUser(message.user), msgObj, room, true); + sendMessage(this.getRocketUser(message.user), msgObj, room, true); } if (message.subtype) { if (message.subtype === 'channel_join') { if (this.getRocketUser(message.user)) { - RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(room._id, this.getRocketUser(message.user), msgDataDefaults); + Messages.createUserJoinWithRoomIdAndUser(room._id, this.getRocketUser(message.user), msgDataDefaults); } } else if (message.subtype === 'channel_leave') { if (this.getRocketUser(message.user)) { - RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser(room._id, this.getRocketUser(message.user), msgDataDefaults); + Messages.createUserLeaveWithRoomIdAndUser(room._id, this.getRocketUser(message.user), msgDataDefaults); } } else if (message.subtype === 'me_message') { const msgObj = { ...msgDataDefaults, msg: `_${ this.convertSlackMessageToRocketChat(message.text) }_`, }; - RocketChat.sendMessage(this.getRocketUser(message.user), msgObj, room, true); + sendMessage(this.getRocketUser(message.user), msgObj, room, true); } else if (message.subtype === 'bot_message' || message.subtype === 'slackbot_response') { - const botUser = RocketChat.models.Users.findOneById('rocket.cat', { fields: { username: 1 } }); + const botUser = Users.findOneById('rocket.cat', { fields: { username: 1 } }); const botUsername = this.bots[message.bot_id] ? this.bots[message.bot_id].name : message.username; const msgObj = { ...msgDataDefaults, @@ -357,18 +358,18 @@ export class SlackImporter extends Base { if (message.icons) { msgObj.emoji = message.icons.emoji; } - RocketChat.sendMessage(botUser, msgObj, room, true); + sendMessage(botUser, msgObj, room, true); } else if (message.subtype === 'channel_purpose') { if (this.getRocketUser(message.user)) { - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_description', room._id, message.purpose, this.getRocketUser(message.user), msgDataDefaults); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_description', room._id, message.purpose, this.getRocketUser(message.user), msgDataDefaults); } } else if (message.subtype === 'channel_topic') { if (this.getRocketUser(message.user)) { - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', room._id, message.topic, this.getRocketUser(message.user), msgDataDefaults); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', room._id, message.topic, this.getRocketUser(message.user), msgDataDefaults); } } else if (message.subtype === 'channel_name') { if (this.getRocketUser(message.user)) { - RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser(room._id, message.name, this.getRocketUser(message.user), msgDataDefaults); + Messages.createRoomRenamedWithRoomIdRoomNameAndUser(room._id, message.name, this.getRocketUser(message.user), msgDataDefaults); } } else if (message.subtype === 'pinned_item') { if (message.attachments) { @@ -380,7 +381,7 @@ export class SlackImporter extends Base { author_icon : getAvatarUrlFromUsername(message.attachments[0].author_subname), }], }; - RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser('message_pinned', room._id, '', this.getRocketUser(message.user), msgObj); + Messages.createWithTypeRoomIdMessageAndUser('message_pinned', room._id, '', this.getRocketUser(message.user), msgObj); } else { // TODO: make this better this.logger.debug('Pinned item with no attachment, needs work.'); @@ -425,7 +426,7 @@ export class SlackImporter extends Base { } try { - RocketChat.sendMessage(this.getRocketUser(message.user), msgObj, room, true); + sendMessage(this.getRocketUser(message.user), msgObj, room, true); } catch (e) { this.logger.warn(`Failed to import the message: ${ msgDataDefaults._id }`); } @@ -472,7 +473,7 @@ export class SlackImporter extends Base { const user = this.users.users.find((user) => user.id === slackId); if (user) { - return RocketChat.models.Users.findOneById(user.rocketId, { fields: { username: 1, name: 1 } }); + return Users.findOneById(user.rocketId, { fields: { username: 1, name: 1 } }); } } From 767f35d2d9e270eca5edb5577d46b9ecca6c870b Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 16:40:59 -0200 Subject: [PATCH 26/33] Remove dependency of RC namespace in rc-api/helpers and api.js (#13273) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js --- packages/rocketchat-api/client/index.js | 1 + .../client/lib/RestApiClient.js | 112 ++++++++++++++++++ packages/rocketchat-api/package.js | 5 + 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 +- .../client/lib/RestApiClient.js | 112 +----------------- 17 files changed, 214 insertions(+), 187 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..969cca9a542c 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -12,9 +12,14 @@ Package.onUse(function(api) { 'rate-limit', 'rocketchat:lib', 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:utils', + 'rocketchat:metrics', + 'rocketchat:authorization', 'rocketchat:integrations', 'rocketchat:file-upload', ]); + api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); 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 6b4c06e7a83a..f1ce328769cb 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 }); 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 5228d2f3a6170da171514f4f3fc5521da4f0bb62 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 17:09:40 -0200 Subject: [PATCH 27/33] Remove dependency of RC namespace on half of api files (#13275) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * 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 10ebcb64bb27..43bf3a6a84eb 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 = {}; @@ -53,7 +54,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 = {}; @@ -82,7 +83,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.')); } @@ -106,15 +107,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 b084dcbaa9ad..eb011021d119 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())) { @@ -17,7 +22,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, @@ -25,35 +30,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; @@ -67,7 +72,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; } @@ -91,7 +96,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, @@ -103,7 +108,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) => { @@ -118,23 +123,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); @@ -170,20 +175,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, @@ -192,12 +197,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, @@ -206,7 +211,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); @@ -215,30 +220,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; @@ -246,7 +251,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 }`); } @@ -255,30 +260,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, @@ -288,7 +293,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, @@ -297,10 +302,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(); @@ -308,23 +313,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); @@ -334,14 +339,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); @@ -350,7 +355,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 db160bf8fdce9228c559c8ecf2cc5d5394615def Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 17:57:57 -0200 Subject: [PATCH 28/33] Partial Remove dependency of RC namespace in rc-api (#13277) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * Remove dependency of RC namespace on half of api files * 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 c977598122b81293b682c73eb2fbef5e3f062d2b Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 18:49:20 -0200 Subject: [PATCH 29/33] Remove dependency of RC namespace in rc-api (#13278) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * Remove dependency of RC namespace on half of api files * Partial Remove dependency of RC namespace in rc-api * import API where it was being used by the RC namespace * Move processWebhookMessage function to rc-lib package * Remove API from RC namespace and import missing function that was being used with namespace * Remove namespace in the new livechat endpoint --- .../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 ++++-- .../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 +++--- .../server/processWebhookMessage.js | 87 +----------------- .../client/lib/RestApiClient.js | 3 - .../client/lib/startup/commands.js | 8 +- packages/rocketchat-lib/package.js | 1 - .../rocketchat-lib/server/functions/index.js | 1 + .../server/functions/processWebhookMessage.js | 88 +++++++++++++++++++ .../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 | 35 ++++---- .../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 +- 46 files changed, 369 insertions(+), 332 deletions(-) delete mode 100644 packages/rocketchat-lib/client/lib/RestApiClient.js create mode 100644 packages/rocketchat-lib/server/functions/processWebhookMessage.js diff --git a/packages/rocketchat-api/client/lib/RestApiClient.js b/packages/rocketchat-api/client/lib/RestApiClient.js index 107462f2057d..403ff02f2827 100644 --- a/packages/rocketchat-api/client/lib/RestApiClient.js +++ b/packages/rocketchat-api/client/lib/RestApiClient.js @@ -109,4 +109,3 @@ export const API = { }, }, }; -RocketChat.API = API; diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index a6664d10b8f1..33c14dae9024 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -17,7 +17,6 @@ Package.onUse(function(api) { 'rocketchat:utils', 'rocketchat:metrics', 'rocketchat:authorization', - 'rocketchat:integrations', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-api/server/api.js b/packages/rocketchat-api/server/api.js index a4ee71d3b9a6..d8e1d331ea47 100644 --- a/packages/rocketchat-api/server/api.js +++ b/packages/rocketchat-api/server/api.js @@ -2,7 +2,6 @@ import { Meteor } from 'meteor/meteor'; import { DDPCommon } from 'meteor/ddp-common'; import { DDP } from 'meteor/ddp'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; import { Logger } from 'meteor/rocketchat:logger'; import { settings } from 'meteor/rocketchat:settings'; @@ -448,8 +447,6 @@ API = { ApiClass: APIClass, }; -RocketChat.API = API; - const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { if (this.request.method === 'OPTIONS' && this.request.headers['access-control-request-method']) { if (settings.get('API_Enable_CORS') === true) { diff --git a/packages/rocketchat-api/server/v1/chat.js b/packages/rocketchat-api/server/v1/chat.js index f83b8dc2c804..c3bf42672d00 100644 --- a/packages/rocketchat-api/server/v1/chat.js +++ b/packages/rocketchat-api/server/v1/chat.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { processWebhookMessage } from 'meteor/rocketchat:integrations'; import { Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { processWebhookMessage } from 'meteor/rocketchat:lib'; import { API } from '../api'; API.v1.addRoute('chat.delete', { authRequired: true }, { diff --git a/packages/rocketchat-api/server/v1/im.js b/packages/rocketchat-api/server/v1/im.js index eb011021d119..074cd91ab50b 100644 --- a/packages/rocketchat-api/server/v1/im.js +++ b/packages/rocketchat-api/server/v1/im.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getRoomByNameOrIdWithOptionToJoin } from 'meteor/rocketchat:lib'; import { Subscriptions, Uploads, Users, Messages, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; @@ -11,7 +11,7 @@ function findDirectMessageRoom(params, user) { throw new Meteor.Error('error-room-param-not-provided', 'Body param "roomId" or "username" is required'); } - const room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ + const room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: params.username || params.roomId, type: 'd', diff --git a/packages/rocketchat-api/server/v1/users.js b/packages/rocketchat-api/server/v1/users.js index 178f5d5d108a..6d24bbb53dae 100644 --- a/packages/rocketchat-api/server/v1/users.js +++ b/packages/rocketchat-api/server/v1/users.js @@ -5,6 +5,14 @@ import { Users, Subscriptions } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { getURL } from 'meteor/rocketchat:utils'; +import { + validateCustomFields, + saveUser, + saveCustomFieldsWithoutValidation, + checkUsernameAvailability, + setUserAvatar, + saveCustomFields, +} from 'meteor/rocketchat:lib'; import { API } from '../api'; import _ from 'underscore'; import Busboy from 'busboy'; @@ -31,13 +39,13 @@ API.v1.addRoute('users.create', { authRequired: true }, { } if (this.bodyParams.customFields) { - RocketChat.validateCustomFields(this.bodyParams.customFields); + validateCustomFields(this.bodyParams.customFields); } - const newUserId = RocketChat.saveUser(this.userId, this.bodyParams); + const newUserId = saveUser(this.userId, this.bodyParams); if (this.bodyParams.customFields) { - RocketChat.saveCustomFieldsWithoutValidation(newUserId, this.bodyParams.customFields); + saveCustomFieldsWithoutValidation(newUserId, this.bodyParams.customFields); } @@ -191,7 +199,7 @@ API.v1.addRoute('users.register', { authRequired: false }, { username: String, })); - if (!RocketChat.checkUsernameAvailability(this.bodyParams.username)) { + if (!checkUsernameAvailability(this.bodyParams.username)) { return API.v1.failure('Username is already in use'); } @@ -246,7 +254,7 @@ API.v1.addRoute('users.setAvatar', { authRequired: true }, { Meteor.runAsUser(user._id, () => { if (this.bodyParams.avatarUrl) { - RocketChat.setUserAvatar(user, this.bodyParams.avatarUrl, '', 'url'); + setUserAvatar(user, this.bodyParams.avatarUrl, '', 'url'); } else { const busboy = new Busboy({ headers: this.request.headers }); const fields = {}; @@ -281,7 +289,7 @@ API.v1.addRoute('users.setAvatar', { authRequired: true }, { return callback(new Meteor.Error('error-not-allowed', 'Not allowed')); } } - RocketChat.setUserAvatar(user, Buffer.concat(imageData), mimetype, 'rest'); + setUserAvatar(user, Buffer.concat(imageData), mimetype, 'rest'); callback(); })); })); @@ -318,10 +326,10 @@ API.v1.addRoute('users.update', { authRequired: true }, { const userData = _.extend({ _id: this.bodyParams.userId }, this.bodyParams.data); - Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); + Meteor.runAsUser(this.userId, () => saveUser(this.userId, userData)); if (this.bodyParams.data.customFields) { - RocketChat.saveCustomFields(this.bodyParams.userId, this.bodyParams.data.customFields); + saveCustomFields(this.bodyParams.userId, this.bodyParams.data.customFields); } if (typeof this.bodyParams.data.active !== 'undefined') { @@ -440,7 +448,7 @@ API.v1.addRoute('users.setPreferences', { authRequired: true }, { userData.language = language; } - Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); + Meteor.runAsUser(this.userId, () => saveUser(this.userId, userData)); const user = Users.findOneById(userId, { fields: { 'settings.preferences': 1, diff --git a/packages/rocketchat-apps/client/admin/appInstall.js b/packages/rocketchat-apps/client/admin/appInstall.js index f5e15623ef51..df6ea61b65f7 100644 --- a/packages/rocketchat-apps/client/admin/appInstall.js +++ b/packages/rocketchat-apps/client/admin/appInstall.js @@ -10,6 +10,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; +import { API } from 'meteor/rocketchat:api'; Template.appInstall.helpers({ appFile() { @@ -72,9 +73,9 @@ Template.appInstall.events({ let result; if (isUpdating) { - result = await RocketChat.API.post(`apps/${ t.isUpdatingId.get() }`, { url }); + result = await API.post(`apps/${ t.isUpdatingId.get() }`, { url }); } else { - result = await RocketChat.API.post('apps', { url }); + result = await API.post('apps', { url }); } if (result.compilerErrors.length !== 0 || result.app.status === 'compiler_error') { @@ -115,9 +116,9 @@ Template.appInstall.events({ let result; if (isUpdating) { - result = await RocketChat.API.upload(`apps/${ t.isUpdatingId.get() }`, data); + result = await API.upload(`apps/${ t.isUpdatingId.get() }`, data); } else { - result = await RocketChat.API.upload('apps', data); + result = await API.upload('apps', data); } console.log('install result', result); diff --git a/packages/rocketchat-apps/client/admin/appLogs.js b/packages/rocketchat-apps/client/admin/appLogs.js index 865bf4dcbfab..11f1c419b951 100644 --- a/packages/rocketchat-apps/client/admin/appLogs.js +++ b/packages/rocketchat-apps/client/admin/appLogs.js @@ -2,6 +2,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; +import { API } from 'meteor/rocketchat:api'; import moment from 'moment'; import hljs from 'highlight.js'; @@ -17,8 +18,8 @@ Template.appLogs.onCreated(function() { const id = this.id.get(); Promise.all([ - RocketChat.API.get(`apps/${ id }`), - RocketChat.API.get(`apps/${ id }/logs`), + API.get(`apps/${ id }`), + API.get(`apps/${ id }/logs`), ]).then((results) => { instance.app.set(results[0].app); diff --git a/packages/rocketchat-apps/client/admin/appManage.js b/packages/rocketchat-apps/client/admin/appManage.js index 986cd135d9c8..b0a54ad45c36 100644 --- a/packages/rocketchat-apps/client/admin/appManage.js +++ b/packages/rocketchat-apps/client/admin/appManage.js @@ -5,6 +5,7 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { TAPi18next } from 'meteor/tap:i18n'; import { isEmail } from 'meteor/rocketchat:utils'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -21,7 +22,7 @@ function getApps(instance) { return Promise.all([ fetch(`${ HOST }/v1/apps/${ id }?version=${ RocketChat.Info.marketplaceApiVersion }`).then((data) => data.json()), - RocketChat.API.get('apps/').then((result) => result.apps.filter((app) => app.id === id)), + API.get('apps/').then((result) => result.apps.filter((app) => app.id === id)), ]).then(([remoteApps, [localApp]]) => { remoteApps = remoteApps.sort((a, b) => { if (semver.gt(a.version, b.version)) { @@ -114,7 +115,7 @@ Template.appManage.onCreated(function() { return; } - RocketChat.API.get(`apps/${ id }/settings`).then((result) => { + API.get(`apps/${ id }/settings`).then((result) => { _morphSettings(result.settings); }); }; @@ -263,7 +264,7 @@ async function setActivate(actiavate, e, t) { const status = actiavate ? 'manually_enabled' : 'manually_disabled'; try { - const result = await RocketChat.API.post(`apps/${ t.id.get() }/status`, { status }); + const result = await API.post(`apps/${ t.id.get() }/status`, { status }); const info = t.app.get(); info.status = result.status; t.app.set(info); @@ -301,7 +302,7 @@ Template.appManage.events({ 'click .js-uninstall': async(e, t) => { t.ready.set(false); try { - await RocketChat.API.delete(`apps/${ t.id.get() }`); + await API.delete(`apps/${ t.id.get() }`); FlowRouter.go('/admin/apps'); } catch (err) { console.warn('Error:', err); @@ -321,7 +322,7 @@ Template.appManage.events({ const api = app.newVersion ? `apps/${ t.id.get() }` : 'apps/'; - RocketChat.API.post(api, { url }).then(() => { + API.post(api, { url }).then(() => { getApps(t).then(() => { el.prop('disabled', false); el.removeClass('loading'); @@ -371,7 +372,7 @@ Template.appManage.events({ if (toSave.length === 0) { throw 'Nothing to save..'; } - const result = await RocketChat.API.post(`apps/${ t.id.get() }/settings`, undefined, { settings: toSave }); + const result = await API.post(`apps/${ t.id.get() }/settings`, undefined, { settings: toSave }); console.log('Updating results:', result); result.updated.forEach((setting) => { settings[setting.id].value = settings[setting.id].oldValue = setting.value; diff --git a/packages/rocketchat-apps/client/admin/apps.js b/packages/rocketchat-apps/client/admin/apps.js index a12d2a77db9d..929859561f65 100644 --- a/packages/rocketchat-apps/client/admin/apps.js +++ b/packages/rocketchat-apps/client/admin/apps.js @@ -4,6 +4,7 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { t } from 'meteor/rocketchat:utils'; import { AppEvents } from '../communication'; +import { API } from 'meteor/rocketchat:api'; const ENABLED_STATUS = ['auto_enabled', 'manually_enabled']; const HOST = 'https://marketplace.rocket.chat'; @@ -48,7 +49,7 @@ const getApps = (instance) => { const getInstalledApps = (instance) => { - RocketChat.API.get('apps').then((data) => { + API.get('apps').then((data) => { const apps = data.apps.map((app) => ({ latest: app })); instance.installedApps.set(apps); @@ -253,7 +254,7 @@ Template.apps.events({ const url = `${ HOST }/v1/apps/${ this.latest.id }/download/${ this.latest.version }`; - RocketChat.API.post('apps/', { url }).then(() => { + API.post('apps/', { url }).then(() => { getInstalledApps(template); }).catch((e) => { toastr.error((e.xhr.responseJSON && e.xhr.responseJSON.error) || e.message); diff --git a/packages/rocketchat-apps/client/communication/websockets.js b/packages/rocketchat-apps/client/communication/websockets.js index a43c8312c62a..248331cd0ff8 100644 --- a/packages/rocketchat-apps/client/communication/websockets.js +++ b/packages/rocketchat-apps/client/communication/websockets.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { API } from 'meteor/rocketchat:api'; export const AppEvents = Object.freeze({ APP_ADDED: 'app/added', @@ -49,7 +50,7 @@ export class AppWebsocketReceiver { } onAppAdded(appId) { - RocketChat.API.get(`apps/${ appId }/languages`).then((result) => { + API.get(`apps/${ appId }/languages`).then((result) => { this.orch.parseAndLoadLanguages(result.languages, appId); }); @@ -73,7 +74,7 @@ export class AppWebsocketReceiver { } onCommandAdded(command) { - RocketChat.API.v1.get('commands.get', { command }).then((result) => { + API.v1.get('commands.get', { command }).then((result) => { RocketChat.slashCommands.commands[command] = result.command; }); } @@ -83,7 +84,7 @@ export class AppWebsocketReceiver { } onCommandUpdated(command) { - RocketChat.API.v1.get('commands.get', { command }).then((result) => { + API.v1.get('commands.get', { command }).then((result) => { RocketChat.slashCommands.commands[command] = result.command; }); } diff --git a/packages/rocketchat-apps/client/orchestrator.js b/packages/rocketchat-apps/client/orchestrator.js index fb85e8da85a6..ebe4067a8540 100644 --- a/packages/rocketchat-apps/client/orchestrator.js +++ b/packages/rocketchat-apps/client/orchestrator.js @@ -4,6 +4,7 @@ import { Utilities } from '../lib/misc/Utilities'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { TAPi18next } from 'meteor/tap:i18n'; +import { API } from 'meteor/rocketchat:api'; class AppClientOrchestrator { constructor() { @@ -71,7 +72,7 @@ class AppClientOrchestrator { } _loadLanguages() { - return RocketChat.API.get('apps/languages').then((info) => { + return API.get('apps/languages').then((info) => { info.apps.forEach((rlInfo) => this.parseAndLoadLanguages(rlInfo.languages, rlInfo.id)); }); } @@ -92,7 +93,7 @@ class AppClientOrchestrator { } async getAppApis(appId) { - const result = await RocketChat.API.get(`apps/${ appId }/apis`); + const result = await API.get(`apps/${ appId }/apis`); return result.apis; } } diff --git a/packages/rocketchat-apps/server/communication/rest.js b/packages/rocketchat-apps/server/communication/rest.js index 68d30c1bf470..431956037a1f 100644 --- a/packages/rocketchat-apps/server/communication/rest.js +++ b/packages/rocketchat-apps/server/communication/rest.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; +import { API } from 'meteor/rocketchat:api'; import Busboy from 'busboy'; export class AppsRestApi { constructor(orch, manager) { this._orch = orch; this._manager = manager; - this.api = new RocketChat.API.ApiClass({ + this.api = new API.ApiClass({ version: 'apps', useDefaultAuth: true, prettyJson: false, enableCors: false, - auth: RocketChat.API.getUserAuth(), + auth: API.getUserAuth(), }); this.addManagementRoutes(); @@ -53,7 +54,7 @@ export class AppsRestApi { return info; }); - return RocketChat.API.v1.success({ apps }); + return API.v1.success({ apps }); }, post() { let buff; @@ -62,7 +63,7 @@ export class AppsRestApi { const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: 'base64' } }); if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') { - return RocketChat.API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); + return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); } buff = Buffer.from(result.content, 'base64'); @@ -71,7 +72,7 @@ export class AppsRestApi { } if (!buff) { - return RocketChat.API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); + return API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); } const aff = Promise.await(manager.add(buff.toString('base64'), false)); @@ -84,7 +85,7 @@ export class AppsRestApi { info.status = 'compiler_error'; } - return RocketChat.API.v1.success({ + return API.v1.success({ app: info, implemented: aff.getImplementedInferfaces(), compilerErrors: aff.getCompilerErrors(), @@ -99,7 +100,7 @@ export class AppsRestApi { languages: prl.getStorageItem().languageContent, })); - return RocketChat.API.v1.success({ apps }); + return API.v1.success({ apps }); }, }); @@ -112,9 +113,9 @@ export class AppsRestApi { const info = prl.getInfo(); info.status = prl.getStatus(); - return RocketChat.API.v1.success({ app: info }); + return API.v1.success({ app: info }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { @@ -127,7 +128,7 @@ export class AppsRestApi { const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: 'base64' } }); if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') { - return RocketChat.API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); + return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); } buff = Buffer.from(result.content, 'base64'); @@ -136,7 +137,7 @@ export class AppsRestApi { } if (!buff) { - return RocketChat.API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); + return API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); } const aff = Promise.await(manager.update(buff.toString('base64'))); @@ -149,7 +150,7 @@ export class AppsRestApi { info.status = 'compiler_error'; } - return RocketChat.API.v1.success({ + return API.v1.success({ app: info, implemented: aff.getImplementedInferfaces(), compilerErrors: aff.getCompilerErrors(), @@ -165,9 +166,9 @@ export class AppsRestApi { const info = prl.getInfo(); info.status = prl.getStatus(); - return RocketChat.API.v1.success({ app: info }); + return API.v1.success({ app: info }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -180,9 +181,9 @@ export class AppsRestApi { if (prl) { const info = prl.getInfo(); - return RocketChat.API.v1.success({ iconFileContent: info.iconFileContent }); + return API.v1.success({ iconFileContent: info.iconFileContent }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -195,9 +196,9 @@ export class AppsRestApi { if (prl) { const languages = prl.getStorageItem().languageContent || {}; - return RocketChat.API.v1.success({ languages }); + return API.v1.success({ languages }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -221,9 +222,9 @@ export class AppsRestApi { const logs = Promise.await(orchestrator.getLogStorage().find(ourQuery, options)); - return RocketChat.API.v1.success({ logs }); + return API.v1.success({ logs }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -242,21 +243,21 @@ export class AppsRestApi { } }); - return RocketChat.API.v1.success({ settings }); + return API.v1.success({ settings }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { console.log(`Updating ${ this.urlParams.id }'s settings..`); if (!this.bodyParams || !this.bodyParams.settings) { - return RocketChat.API.v1.failure('The settings to update must be present.'); + return API.v1.failure('The settings to update must be present.'); } const prl = manager.getOneById(this.urlParams.id); if (!prl) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } const { settings } = prl.getStorageItem(); @@ -270,7 +271,7 @@ export class AppsRestApi { } }); - return RocketChat.API.v1.success({ updated }); + return API.v1.success({ updated }); }, }); @@ -281,14 +282,14 @@ export class AppsRestApi { try { const setting = manager.getSettingsManager().getAppSetting(this.urlParams.id, this.urlParams.settingId); - RocketChat.API.v1.success({ setting }); + API.v1.success({ setting }); } catch (e) { if (e.message.includes('No setting found')) { - return RocketChat.API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); + return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); } else if (e.message.includes('No App found')) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } else { - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } } }, @@ -296,20 +297,20 @@ export class AppsRestApi { console.log(`Updating the App ${ this.urlParams.id }'s setting ${ this.urlParams.settingId }`); if (!this.bodyParams.setting) { - return RocketChat.API.v1.failure('Setting to update to must be present on the posted body.'); + return API.v1.failure('Setting to update to must be present on the posted body.'); } try { Promise.await(manager.getSettingsManager().updateAppSetting(this.urlParams.id, this.bodyParams.setting)); - return RocketChat.API.v1.success(); + return API.v1.success(); } catch (e) { if (e.message.includes('No setting found')) { - return RocketChat.API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); + return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); } else if (e.message.includes('No App found')) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } else { - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } } }, @@ -321,11 +322,11 @@ export class AppsRestApi { const prl = manager.getOneById(this.urlParams.id); if (prl) { - return RocketChat.API.v1.success({ + return API.v1.success({ apis: manager.apiManager.listApis(this.urlParams.id), }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -336,14 +337,14 @@ export class AppsRestApi { const prl = manager.getOneById(this.urlParams.id); if (prl) { - return RocketChat.API.v1.success({ status: prl.getStatus() }); + return API.v1.success({ status: prl.getStatus() }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { if (!this.bodyParams.status || typeof this.bodyParams.status !== 'string') { - return RocketChat.API.v1.failure('Invalid status provided, it must be "status" field and a string.'); + return API.v1.failure('Invalid status provided, it must be "status" field and a string.'); } console.log(`Updating ${ this.urlParams.id }'s status...`, this.bodyParams.status); @@ -352,9 +353,9 @@ export class AppsRestApi { if (prl) { const result = Promise.await(manager.changeStatus(prl.getID(), this.bodyParams.status)); - return RocketChat.API.v1.success({ status: result.getStatus() }); + return API.v1.success({ status: result.getStatus() }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); diff --git a/packages/rocketchat-graphql/package.js b/packages/rocketchat-graphql/package.js index 87b0c860d278..33c25e41e4ce 100644 --- a/packages/rocketchat-graphql/package.js +++ b/packages/rocketchat-graphql/package.js @@ -13,6 +13,7 @@ Package.onUse(function(api) { 'rocketchat:lib', 'rocketchat:api', 'rocketchat:accounts', + 'rocketchat:integrations', 'swydo:graphql', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js index 5d4c8a154df4..c74398268e84 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js @@ -1,5 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { API } from 'meteor/rocketchat:api'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/createChannel.graphqls'; @@ -7,7 +6,7 @@ const resolver = { Mutation: { createChannel: authenticated((root, args, { user }) => { try { - RocketChat.API.channels.create.validate({ + API.channels.create.validate({ user: { value: user._id, }, @@ -24,7 +23,7 @@ const resolver = { throw e; } - const { channel } = RocketChat.API.channels.create.execute(user._id, { + const { channel } = API.channels.create.execute(user._id, { name: args.name, members: args.membersId, }); diff --git a/packages/rocketchat-importer/client/admin/adminImportHistory.js b/packages/rocketchat-importer/client/admin/adminImportHistory.js index 5b2ee4d5dcfe..76f81a877753 100644 --- a/packages/rocketchat-importer/client/admin/adminImportHistory.js +++ b/packages/rocketchat-importer/client/admin/adminImportHistory.js @@ -7,6 +7,7 @@ import toastr from 'toastr'; import { ReactiveVar } from 'meteor/reactive-var'; import { ProgressStep } from '../../lib/ImporterProgressStep'; import { FlowRouter } from 'meteor/kadira:flow-router'; +import { API } from 'meteor/rocketchat:api'; Template.adminImportHistory.helpers({ isAdmin() { @@ -183,7 +184,7 @@ Template.adminImportHistory.onCreated(function() { this.preparing = new ReactiveVar(true); this.history = new ReactiveVar([]); - RocketChat.API.get('v1/getLatestImportOperations').then((data) => { + API.get('v1/getLatestImportOperations').then((data) => { instance.history.set(data); instance.preparing.set(false); }).catch((error) => { diff --git a/packages/rocketchat-importer/client/admin/adminImportPrepare.js b/packages/rocketchat-importer/client/admin/adminImportPrepare.js index 216301adcb5d..b58c95f61697 100644 --- a/packages/rocketchat-importer/client/admin/adminImportPrepare.js +++ b/packages/rocketchat-importer/client/admin/adminImportPrepare.js @@ -6,6 +6,7 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat, handleError } from 'meteor/rocketchat:lib'; import { t } from 'meteor/rocketchat:utils'; +import { API } from 'meteor/rocketchat:api'; import toastr from 'toastr'; Template.adminImportPrepare.helpers({ @@ -95,7 +96,7 @@ function showException(error, defaultErrorString) { } function getImportFileData(importer, template) { - RocketChat.API.get(`v1/getImportFileData?importerKey=${ importer.key }`).then((data) => { + API.get(`v1/getImportFileData?importerKey=${ importer.key }`).then((data) => { if (!data) { console.warn(`The importer ${ importer.key } is not set up correctly, as it did not return any data.`); toastr.error(t('Importer_not_setup')); @@ -148,7 +149,7 @@ Template.adminImportPrepare.events({ reader.readAsBinaryString(file); reader.onloadend = () => { - RocketChat.API.post('v1/uploadImportFile', { + API.post('v1/uploadImportFile', { binaryContent: reader.result, contentType: file.type, fileName: file.name, @@ -174,7 +175,7 @@ Template.adminImportPrepare.events({ template.preparing.set(true); - RocketChat.API.post('v1/downloadPublicImportFile', { + API.post('v1/downloadPublicImportFile', { fileUrl, importerKey: importer.key, }).then(() => { diff --git a/packages/rocketchat-importer/package.js b/packages/rocketchat-importer/package.js index 136826523918..71fe8869d538 100644 --- a/packages/rocketchat-importer/package.js +++ b/packages/rocketchat-importer/package.js @@ -12,6 +12,7 @@ Package.onUse(function(api) { 'check', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:logger', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-integrations/package.js b/packages/rocketchat-integrations/package.js index 43f897cb8e47..577a0ee92f32 100644 --- a/packages/rocketchat-integrations/package.js +++ b/packages/rocketchat-integrations/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'ecmascript', 'mongo', 'babel-compiler', + 'rocketchat:api', 'rocketchat:lib', 'rocketchat:authorization', 'rocketchat:theme', diff --git a/packages/rocketchat-integrations/server/api/api.js b/packages/rocketchat-integrations/server/api/api.js index d92b52664ea7..5b8b6b4a05c5 100644 --- a/packages/rocketchat-integrations/server/api/api.js +++ b/packages/rocketchat-integrations/server/api/api.js @@ -3,6 +3,7 @@ import { HTTP } from 'meteor/http'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; +import { API } from 'meteor/rocketchat:api'; import { logger } from '../logger'; import { processWebhookMessage } from '../processWebhookMessage'; import Fiber from 'fibers'; @@ -129,12 +130,12 @@ function getIntegrationScript(integration) { logger.incoming.error(script.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); - throw RocketChat.API.v1.failure('error-evaluating-script'); + throw API.v1.failure('error-evaluating-script'); } if (!sandbox.Script) { logger.incoming.error('[Class "Script" not in Trigger', integration.name, ']'); - throw RocketChat.API.v1.failure('class-script-not-found'); + throw API.v1.failure('class-script-not-found'); } } @@ -172,7 +173,7 @@ function createIntegration(options, user) { } }); - return RocketChat.API.v1.success(); + return API.v1.success(); } function removeIntegration(options, user) { @@ -185,7 +186,7 @@ function removeIntegration(options, user) { Meteor.runAsUser(user._id, () => Meteor.call('deleteOutgoingIntegration', integrationToRemove._id)); - return RocketChat.API.v1.success(); + return API.v1.success(); } function executeIntegrationRest() { @@ -213,7 +214,7 @@ function executeIntegrationRest() { script = getIntegrationScript(this.integration); } catch (e) { logger.incoming.warn(e); - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } this.request.setEncoding('utf8'); @@ -262,9 +263,9 @@ function executeIntegrationRest() { if (!result) { logger.incoming.debug('[Process Incoming Request result of Trigger', this.integration.name, ':] No data'); - return RocketChat.API.v1.success(); + return API.v1.success(); } else if (result && result.error) { - return RocketChat.API.v1.failure(result.error); + return API.v1.failure(result.error); } this.bodyParams = result && result.content; @@ -280,7 +281,7 @@ function executeIntegrationRest() { logger.incoming.error(this.integration.scriptCompiled.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); - return RocketChat.API.v1.failure('error-running-script'); + return API.v1.failure('error-running-script'); } } @@ -288,7 +289,7 @@ function executeIntegrationRest() { // TODO: Temporary fix for https://github.com/RocketChat/Rocket.Chat/issues/7770 until the above is implemented if (!this.bodyParams || (_.isEmpty(this.bodyParams) && !this.integration.scriptEnabled)) { // return RocketChat.API.v1.failure('body-empty'); - return RocketChat.API.v1.success(); + return API.v1.success(); } this.bodyParams.bot = { i: this.integration._id }; @@ -296,16 +297,16 @@ function executeIntegrationRest() { try { const message = processWebhookMessage(this.bodyParams, this.user, defaultValues); if (_.isEmpty(message)) { - return RocketChat.API.v1.failure('unknown-error'); + return API.v1.failure('unknown-error'); } if (this.scriptResponse) { logger.incoming.debug('response', this.scriptResponse); } - return RocketChat.API.v1.success(this.scriptResponse); + return API.v1.success(this.scriptResponse); } catch ({ error, message }) { - return RocketChat.API.v1.failure(error || message); + return API.v1.failure(error || message); } } diff --git a/packages/rocketchat-integrations/server/processWebhookMessage.js b/packages/rocketchat-integrations/server/processWebhookMessage.js index d72a96fb36ed..a0c36c660726 100644 --- a/packages/rocketchat-integrations/server/processWebhookMessage.js +++ b/packages/rocketchat-integrations/server/processWebhookMessage.js @@ -1,86 +1 @@ -import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import _ from 'underscore'; -import s from 'underscore.string'; - -export const processWebhookMessage = function(messageObj, user, defaultValues = { channel: '', alias: '', avatar: '', emoji: '' }, mustBeJoined = false) { - const sentData = []; - const channels = [].concat(messageObj.channel || messageObj.roomId || defaultValues.channel); - - for (const channel of channels) { - const channelType = channel[0]; - - let channelValue = channel.substr(1); - let room; - - switch (channelType) { - case '#': - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true }); - break; - case '@': - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd' }); - break; - default: - channelValue = channelType + channelValue; - - // Try to find the room by id or name if they didn't include the prefix. - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true, errorOnEmpty: false }); - if (room) { - break; - } - - // We didn't get a room, let's try finding direct messages - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd', tryDirectByUserIdOnly: true }); - if (room) { - break; - } - - // No room, so throw an error - throw new Meteor.Error('invalid-channel'); - } - - if (mustBeJoined && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { - // throw new Meteor.Error('invalid-room', 'Invalid room provided to send a message to, must be joined.'); - throw new Meteor.Error('invalid-channel'); // Throwing the generic one so people can't "brute force" find rooms - } - - if (messageObj.attachments && !_.isArray(messageObj.attachments)) { - console.log('Attachments should be Array, ignoring value'.red, messageObj.attachments); - messageObj.attachments = undefined; - } - - const message = { - alias: messageObj.username || messageObj.alias || defaultValues.alias, - msg: s.trim(messageObj.text || messageObj.msg || ''), - attachments: messageObj.attachments || [], - parseUrls: messageObj.parseUrls !== undefined ? messageObj.parseUrls : !messageObj.attachments, - bot: messageObj.bot, - groupable: (messageObj.groupable !== undefined) ? messageObj.groupable : false, - }; - - if (!_.isEmpty(messageObj.icon_url) || !_.isEmpty(messageObj.avatar)) { - message.avatar = messageObj.icon_url || messageObj.avatar; - } else if (!_.isEmpty(messageObj.icon_emoji) || !_.isEmpty(messageObj.emoji)) { - message.emoji = messageObj.icon_emoji || messageObj.emoji; - } else if (!_.isEmpty(defaultValues.avatar)) { - message.avatar = defaultValues.avatar; - } else if (!_.isEmpty(defaultValues.emoji)) { - message.emoji = defaultValues.emoji; - } - - if (_.isArray(message.attachments)) { - for (let i = 0; i < message.attachments.length; i++) { - const attachment = message.attachments[i]; - if (attachment.msg) { - attachment.text = s.trim(attachment.msg); - delete attachment.msg; - } - } - } - - const messageReturn = RocketChat.sendMessage(user, message, room); - sentData.push({ channel, message: messageReturn }); - } - - return sentData; -}; +export { processWebhookMessage } from 'meteor/rocketchat:lib'; diff --git a/packages/rocketchat-lib/client/lib/RestApiClient.js b/packages/rocketchat-lib/client/lib/RestApiClient.js deleted file mode 100644 index 9c2d7a9b86e9..000000000000 --- a/packages/rocketchat-lib/client/lib/RestApiClient.js +++ /dev/null @@ -1,3 +0,0 @@ -// import { API } from 'meteor/rocketchat:api'; - -// RocketChat.API = API; diff --git a/packages/rocketchat-lib/client/lib/startup/commands.js b/packages/rocketchat-lib/client/lib/startup/commands.js index 35cc4960da43..d07c7e670ce6 100644 --- a/packages/rocketchat-lib/client/lib/startup/commands.js +++ b/packages/rocketchat-lib/client/lib/startup/commands.js @@ -9,9 +9,11 @@ import { slashCommands } from 'meteor/rocketchat:utils'; Tracker.autorun(() => { const newUserId = Meteor.userId(); if (oldUserId === null && newUserId) { - RocketChat.API.v1.get('commands.list').then(function _loadedCommands(result) { - result.commands.forEach((command) => { - slashCommands.commands[command.command] = command; + import('meteor/rocketchat:api').then(({ API }) => { + API.v1.get('commands.list').then(function _loadedCommands(result) { + result.commands.forEach((command) => { + slashCommands.commands[command.command] = command; + }); }); }); } diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9947ebcd7751..c29baddb4e19 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -237,7 +237,6 @@ Package.onUse(function(api) { api.addFiles('client/Notifications.js', 'client'); api.addFiles('client/OAuthProxy.js', 'client'); api.addFiles('client/UserDeleted.js', 'client'); - api.addFiles('client/lib/RestApiClient.js', 'client'); api.addFiles('client/lib/TabBar.js', 'client'); api.addFiles('client/lib/RocketChatTabBar.js', 'client'); api.addFiles('client/lib/RocketChatAnnouncement.js', 'client'); diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js index c60ee0e9849d..5ff75d6934f9 100644 --- a/packages/rocketchat-lib/server/functions/index.js +++ b/packages/rocketchat-lib/server/functions/index.js @@ -24,3 +24,4 @@ export { unarchiveRoom } from './unarchiveRoom'; export { updateMessage } from './updateMessage'; export { validateCustomFields } from './validateCustomFields'; export { generateUsernameSuggestion } from './getUsernameSuggestion'; +export { processWebhookMessage } from './processWebhookMessage'; diff --git a/packages/rocketchat-lib/server/functions/processWebhookMessage.js b/packages/rocketchat-lib/server/functions/processWebhookMessage.js new file mode 100644 index 000000000000..ed87ef60468f --- /dev/null +++ b/packages/rocketchat-lib/server/functions/processWebhookMessage.js @@ -0,0 +1,88 @@ +import { Meteor } from 'meteor/meteor'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { getRoomByNameOrIdWithOptionToJoin } from './getRoomByNameOrIdWithOptionToJoin'; +import { sendMessage } from './sendMessage'; +import _ from 'underscore'; +import s from 'underscore.string'; + +export const processWebhookMessage = function(messageObj, user, defaultValues = { channel: '', alias: '', avatar: '', emoji: '' }, mustBeJoined = false) { + const sentData = []; + const channels = [].concat(messageObj.channel || messageObj.roomId || defaultValues.channel); + + for (const channel of channels) { + const channelType = channel[0]; + + let channelValue = channel.substr(1); + let room; + + switch (channelType) { + case '#': + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true }); + break; + case '@': + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd' }); + break; + default: + channelValue = channelType + channelValue; + + // Try to find the room by id or name if they didn't include the prefix. + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true, errorOnEmpty: false }); + if (room) { + break; + } + + // We didn't get a room, let's try finding direct messages + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd', tryDirectByUserIdOnly: true }); + if (room) { + break; + } + + // No room, so throw an error + throw new Meteor.Error('invalid-channel'); + } + + if (mustBeJoined && !Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { + // throw new Meteor.Error('invalid-room', 'Invalid room provided to send a message to, must be joined.'); + throw new Meteor.Error('invalid-channel'); // Throwing the generic one so people can't "brute force" find rooms + } + + if (messageObj.attachments && !_.isArray(messageObj.attachments)) { + console.log('Attachments should be Array, ignoring value'.red, messageObj.attachments); + messageObj.attachments = undefined; + } + + const message = { + alias: messageObj.username || messageObj.alias || defaultValues.alias, + msg: s.trim(messageObj.text || messageObj.msg || ''), + attachments: messageObj.attachments || [], + parseUrls: messageObj.parseUrls !== undefined ? messageObj.parseUrls : !messageObj.attachments, + bot: messageObj.bot, + groupable: (messageObj.groupable !== undefined) ? messageObj.groupable : false, + }; + + if (!_.isEmpty(messageObj.icon_url) || !_.isEmpty(messageObj.avatar)) { + message.avatar = messageObj.icon_url || messageObj.avatar; + } else if (!_.isEmpty(messageObj.icon_emoji) || !_.isEmpty(messageObj.emoji)) { + message.emoji = messageObj.icon_emoji || messageObj.emoji; + } else if (!_.isEmpty(defaultValues.avatar)) { + message.avatar = defaultValues.avatar; + } else if (!_.isEmpty(defaultValues.emoji)) { + message.emoji = defaultValues.emoji; + } + + if (_.isArray(message.attachments)) { + for (let i = 0; i < message.attachments.length; i++) { + const attachment = message.attachments[i]; + if (attachment.msg) { + attachment.text = s.trim(attachment.msg); + delete attachment.msg; + } + } + } + + const messageReturn = sendMessage(user, message, room); + sentData.push({ channel, message: messageReturn }); + } + + return sentData; +}; diff --git a/packages/rocketchat-livechat/imports/server/rest/departments.js b/packages/rocketchat-livechat/imports/server/rest/departments.js index 296cf37707b7..422d0f492102 100644 --- a/packages/rocketchat-livechat/imports/server/rest/departments.js +++ b/packages/rocketchat-livechat/imports/server/rest/departments.js @@ -1,19 +1,20 @@ import { check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/department', { authRequired: true }, { +API.v1.addRoute('livechat/department', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success({ + return API.v1.success({ departments: RocketChat.models.LivechatDepartment.find().fetch(), }); }, post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -25,23 +26,23 @@ RocketChat.API.v1.addRoute('livechat/department', { authRequired: true }, { const department = RocketChat.Livechat.saveDepartment(null, this.bodyParams.department, this.bodyParams.agents); if (department) { - return RocketChat.API.v1.success({ + return API.v1.success({ department, agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: department._id }).fetch(), }); } - RocketChat.API.v1.failure(); + API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { +API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -49,17 +50,17 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { _id: String, }); - return RocketChat.API.v1.success({ + return API.v1.success({ department: RocketChat.models.LivechatDepartment.findOneById(this.urlParams._id), agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: this.urlParams._id }).fetch(), }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, put() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -73,20 +74,20 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { }); if (RocketChat.Livechat.saveDepartment(this.urlParams._id, this.bodyParams.department, this.bodyParams.agents)) { - return RocketChat.API.v1.success({ + return API.v1.success({ department: RocketChat.models.LivechatDepartment.findOneById(this.urlParams._id), agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: this.urlParams._id }).fetch(), }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -95,12 +96,12 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { }); if (RocketChat.Livechat.removeDepartment(this.urlParams._id)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); diff --git a/packages/rocketchat-livechat/imports/server/rest/facebook.js b/packages/rocketchat-livechat/imports/server/rest/facebook.js index a083c649716f..0e05e98d2161 100644 --- a/packages/rocketchat-livechat/imports/server/rest/facebook.js +++ b/packages/rocketchat-livechat/imports/server/rest/facebook.js @@ -1,6 +1,7 @@ import crypto from 'crypto'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; @@ -17,7 +18,7 @@ import LivechatVisitors from '../../../server/models/LivechatVisitors'; * @apiParam {String} [text] Facebook message text * @apiParam {String} [attachments] Facebook message attachments */ -RocketChat.API.v1.addRoute('livechat/facebook', { +API.v1.addRoute('livechat/facebook', { post() { if (!this.bodyParams.text && !this.bodyParams.attachments) { return { diff --git a/packages/rocketchat-livechat/imports/server/rest/sms.js b/packages/rocketchat-livechat/imports/server/rest/sms.js index 4924d9b5cdfb..ce107e278848 100644 --- a/packages/rocketchat-livechat/imports/server/rest/sms.js +++ b/packages/rocketchat-livechat/imports/server/rest/sms.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; -RocketChat.API.v1.addRoute('livechat/sms-incoming/:service', { +API.v1.addRoute('livechat/sms-incoming/:service', { post() { const SMSService = RocketChat.SMS.getService(this.urlParams.service); diff --git a/packages/rocketchat-livechat/imports/server/rest/upload.js b/packages/rocketchat-livechat/imports/server/rest/upload.js index 88310a6e96db..61dd1438bb5f 100644 --- a/packages/rocketchat-livechat/imports/server/rest/upload.js +++ b/packages/rocketchat-livechat/imports/server/rest/upload.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { API } from 'meteor/rocketchat:api'; import Busboy from 'busboy'; import filesize from 'filesize'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; @@ -14,22 +15,22 @@ RocketChat.settings.get('FileUpload_MaxFileSize', function(key, value) { } }); -RocketChat.API.v1.addRoute('livechat/upload/:rid', { +API.v1.addRoute('livechat/upload/:rid', { post() { if (!this.request.headers['x-visitor-token']) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const visitorToken = this.request.headers['x-visitor-token']; const visitor = LivechatVisitors.getVisitorByToken(visitorToken); if (!visitor) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const room = RocketChat.models.Rooms.findOneOpenByRoomIdAndVisitorToken(this.urlParams.rid, visitorToken); if (!room) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const busboy = new Busboy({ headers: this.request.headers }); @@ -58,24 +59,24 @@ RocketChat.API.v1.addRoute('livechat/upload/:rid', { })(); if (files.length === 0) { - return RocketChat.API.v1.failure('File required'); + return API.v1.failure('File required'); } if (files.length > 1) { - return RocketChat.API.v1.failure('Just 1 file is allowed'); + return API.v1.failure('Just 1 file is allowed'); } const file = files[0]; if (!RocketChat.fileUploadIsValidContentType(file.mimetype)) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ reason: 'error-type-not-allowed', }); } // -1 maxFileSize means there is no limit if (maxFileSize > -1 && file.fileBuffer.length > maxFileSize) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ reason: 'error-size-not-allowed', sizeAllowed: filesize(maxFileSize), }); @@ -96,6 +97,6 @@ RocketChat.API.v1.addRoute('livechat/upload/:rid', { uploadedFile.description = fields.description; delete fields.description; - RocketChat.API.v1.success(Meteor.call('sendFileLivechatMessage', this.urlParams.rid, visitorToken, uploadedFile, fields)); + API.v1.success(Meteor.call('sendFileLivechatMessage', this.urlParams.rid, visitorToken, uploadedFile, fields)); }, }); diff --git a/packages/rocketchat-livechat/imports/server/rest/users.js b/packages/rocketchat-livechat/imports/server/rest/users.js index 3245793857e6..3892da0bbb53 100644 --- a/packages/rocketchat-livechat/imports/server/rest/users.js +++ b/packages/rocketchat-livechat/imports/server/rest/users.js @@ -1,11 +1,12 @@ import { check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; -RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { +API.v1.addRoute('livechat/users/:type', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -24,16 +25,16 @@ RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { const users = RocketChat.authz.getUsersInRole(role); - return RocketChat.API.v1.success({ + return API.v1.success({ users: users.fetch().map((user) => _.pick(user, '_id', 'username', 'name', 'status', 'statusLivechat')), }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { check(this.urlParams, { @@ -47,28 +48,28 @@ RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { if (this.urlParams.type === 'agent') { const user = RocketChat.Livechat.addAgent(this.bodyParams.username); if (user) { - return RocketChat.API.v1.success({ user }); + return API.v1.success({ user }); } } else if (this.urlParams.type === 'manager') { const user = RocketChat.Livechat.addManager(this.bodyParams.username); if (user) { - return RocketChat.API.v1.success({ user }); + return API.v1.success({ user }); } } else { throw 'Invalid type'; } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, { +API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -80,7 +81,7 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, const user = RocketChat.models.Users.findOneById(this.urlParams._id); if (!user) { - return RocketChat.API.v1.failure('User not found'); + return API.v1.failure('User not found'); } let role; @@ -94,21 +95,21 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, } if (user.roles.indexOf(role) !== -1) { - return RocketChat.API.v1.success({ + return API.v1.success({ user: _.pick(user, '_id', 'username'), }); } - return RocketChat.API.v1.success({ + return API.v1.success({ user: null, }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -120,24 +121,24 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, const user = RocketChat.models.Users.findOneById(this.urlParams._id); if (!user) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } if (this.urlParams.type === 'agent') { if (RocketChat.Livechat.removeAgent(user.username)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } } else if (this.urlParams.type === 'manager') { if (RocketChat.Livechat.removeManager(user.username)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } } else { throw 'Invalid type'; } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/agent.js b/packages/rocketchat-livechat/server/api/v1/agent.js index 655e8bb7db36..d9a50d533e70 100644 --- a/packages/rocketchat-livechat/server/api/v1/agent.js +++ b/packages/rocketchat-livechat/server/api/v1/agent.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findRoom, findGuest, findAgent, findOpenRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/agent.info/:rid/:token', { +API.v1.addRoute('livechat/agent.info/:rid/:token', { get() { try { check(this.urlParams, { @@ -26,14 +27,14 @@ RocketChat.API.v1.addRoute('livechat/agent.info/:rid/:token', { throw new Meteor.Error('invalid-agent'); } - return RocketChat.API.v1.success({ agent }); + return API.v1.success({ agent }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/agent.next/:token', { +API.v1.addRoute('livechat/agent.next/:token', { get() { try { check(this.urlParams, { @@ -68,9 +69,9 @@ RocketChat.API.v1.addRoute('livechat/agent.next/:token', { throw new Meteor.Error('invalid-agent'); } - return RocketChat.API.v1.success({ agent }); + return API.v1.success({ agent }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/config.js b/packages/rocketchat-livechat/server/api/v1/config.js index b59c679bf934..03e86c76128d 100644 --- a/packages/rocketchat-livechat/server/api/v1/config.js +++ b/packages/rocketchat-livechat/server/api/v1/config.js @@ -1,8 +1,9 @@ import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, settings, online, findOpenRoom } from '../lib/livechat'; import { Match, check } from 'meteor/check'; -RocketChat.API.v1.addRoute('livechat/config', { +API.v1.addRoute('livechat/config', { get() { try { check(this.queryParams, { @@ -11,7 +12,7 @@ RocketChat.API.v1.addRoute('livechat/config', { const config = settings(); if (!config.enabled) { - return RocketChat.API.v1.success({ config: { enabled: false } }); + return API.v1.success({ config: { enabled: false } }); } const status = online(); @@ -30,9 +31,9 @@ RocketChat.API.v1.addRoute('livechat/config', { Object.assign(config, { online: status, guest, room, agent }); - return RocketChat.API.v1.success({ config }); + return API.v1.success({ config }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/customField.js b/packages/rocketchat-livechat/server/api/v1/customField.js index bcb738428ba4..e2818fa2f466 100644 --- a/packages/rocketchat-livechat/server/api/v1/customField.js +++ b/packages/rocketchat-livechat/server/api/v1/customField.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/custom.field', { +API.v1.addRoute('livechat/custom.field', { post() { try { check(this.bodyParams, { @@ -21,17 +22,17 @@ RocketChat.API.v1.addRoute('livechat/custom.field', { } if (!RocketChat.Livechat.setCustomFields({ token, key, value, overwrite })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ field: { key, value, overwrite } }); + return API.v1.success({ field: { key, value, overwrite } }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/custom.fields', { +API.v1.addRoute('livechat/custom.fields', { post() { check(this.bodyParams, { token: String, @@ -53,13 +54,13 @@ RocketChat.API.v1.addRoute('livechat/custom.fields', { const fields = this.bodyParams.customFields.map((customField) => { const data = Object.assign({ token }, customField); if (!RocketChat.Livechat.setCustomFields(data)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } return { Key: customField.key, value: customField.value, overwrite: customField.overwrite }; }); - return RocketChat.API.v1.success({ fields }); + return API.v1.success({ fields }); }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/message.js b/packages/rocketchat-livechat/server/api/v1/message.js index 8acc1dd9da6d..8abdaa6b761c 100644 --- a/packages/rocketchat-livechat/server/api/v1/message.js +++ b/packages/rocketchat-livechat/server/api/v1/message.js @@ -2,10 +2,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; import { findGuest, findRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/message', { +API.v1.addRoute('livechat/message', { post() { try { check(this.bodyParams, { @@ -47,17 +48,17 @@ RocketChat.API.v1.addRoute('livechat/message', { const result = RocketChat.Livechat.sendMessage(sendMessage); if (result) { const message = { _id: result._id, rid: result.rid, msg: result.msg, u: result.u, ts: result.ts }; - return RocketChat.API.v1.success({ message }); + return API.v1.success({ message }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/message/:_id', { +API.v1.addRoute('livechat/message/:_id', { put() { try { check(this.urlParams, { @@ -93,14 +94,14 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { const result = RocketChat.Livechat.updateMessage({ guest, message }); if (result) { const data = RocketChat.models.Messages.findOneById(_id); - return RocketChat.API.v1.success({ + return API.v1.success({ message: { _id: data._id, rid: data.rid, msg: data.msg, u: data.u, ts: data.ts }, }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { @@ -134,7 +135,7 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { const result = RocketChat.Livechat.deleteMessage({ guest, message }); if (result) { - return RocketChat.API.v1.success({ + return API.v1.success({ message: { _id, ts: new Date().toISOString(), @@ -142,14 +143,14 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/messages.history/:rid', { +API.v1.addRoute('livechat/messages.history/:rid', { get() { try { check(this.urlParams, { @@ -189,33 +190,33 @@ RocketChat.API.v1.addRoute('livechat/messages.history/:rid', { } const messages = RocketChat.loadMessageHistory({ userId: guest._id, rid, end, limit, ls }); - return RocketChat.API.v1.success(messages); + return API.v1.success(messages); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/messages', { authRequired: true }, { +API.v1.addRoute('livechat/messages', { authRequired: true }, { post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } if (!this.bodyParams.visitor) { - return RocketChat.API.v1.failure('Body param "visitor" is required'); + return API.v1.failure('Body param "visitor" is required'); } if (!this.bodyParams.visitor.token) { - return RocketChat.API.v1.failure('Body param "visitor.token" is required'); + return API.v1.failure('Body param "visitor.token" is required'); } if (!this.bodyParams.messages) { - return RocketChat.API.v1.failure('Body param "messages" is required'); + return API.v1.failure('Body param "messages" is required'); } if (!(this.bodyParams.messages instanceof Array)) { - return RocketChat.API.v1.failure('Body param "messages" is not an array'); + return API.v1.failure('Body param "messages" is not an array'); } if (this.bodyParams.messages.length === 0) { - return RocketChat.API.v1.failure('Body param "messages" is empty'); + return API.v1.failure('Body param "messages" is empty'); } const visitorToken = this.bodyParams.visitor.token; @@ -253,7 +254,7 @@ RocketChat.API.v1.addRoute('livechat/messages', { authRequired: true }, { }; }); - return RocketChat.API.v1.success({ + return API.v1.success({ messages: sentMessages, }); }, diff --git a/packages/rocketchat-livechat/server/api/v1/offlineMessage.js b/packages/rocketchat-livechat/server/api/v1/offlineMessage.js index 6409ea0f5667..338573084ebe 100644 --- a/packages/rocketchat-livechat/server/api/v1/offlineMessage.js +++ b/packages/rocketchat-livechat/server/api/v1/offlineMessage.js @@ -1,8 +1,9 @@ import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/offline.message', { +API.v1.addRoute('livechat/offline.message', { post() { try { check(this.bodyParams, { @@ -13,12 +14,12 @@ RocketChat.API.v1.addRoute('livechat/offline.message', { const { name, email, message } = this.bodyParams; if (!RocketChat.Livechat.sendOfflineMessage({ name, email, message })) { - return RocketChat.API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_offline_message') }); + return API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_offline_message') }); } - return RocketChat.API.v1.success({ message: TAPi18n.__('Livechat_offline_message_sent') }); + return API.v1.success({ message: TAPi18n.__('Livechat_offline_message_sent') }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/pageVisited.js b/packages/rocketchat-livechat/server/api/v1/pageVisited.js index 906f3f783529..1a0fc1098b6e 100644 --- a/packages/rocketchat-livechat/server/api/v1/pageVisited.js +++ b/packages/rocketchat-livechat/server/api/v1/pageVisited.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; import { findGuest, findRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/page.visited', { +API.v1.addRoute('livechat/page.visited', { post() { try { check(this.bodyParams, { @@ -34,12 +35,12 @@ RocketChat.API.v1.addRoute('livechat/page.visited', { const obj = RocketChat.Livechat.savePageHistory(token, rid, pageInfo); if (obj) { const page = _.pick(obj, 'msg', 'navigation'); - return RocketChat.API.v1.success({ page }); + return API.v1.success({ page }); } - return RocketChat.API.v1.success(); + return API.v1.success(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/room.js b/packages/rocketchat-livechat/server/api/v1/room.js index 246f9451af11..d21bbc13f6bb 100644 --- a/packages/rocketchat-livechat/server/api/v1/room.js +++ b/packages/rocketchat-livechat/server/api/v1/room.js @@ -3,9 +3,10 @@ import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, findRoom, getRoom, settings } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/room', { +API.v1.addRoute('livechat/room', { get() { try { check(this.queryParams, { @@ -22,14 +23,14 @@ RocketChat.API.v1.addRoute('livechat/room', { const rid = this.queryParams.rid || Random.id(); const room = getRoom(guest, rid); - return RocketChat.API.v1.success(room); + return API.v1.success(room); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.close', { +API.v1.addRoute('livechat/room.close', { post() { try { check(this.bodyParams, { @@ -57,17 +58,17 @@ RocketChat.API.v1.addRoute('livechat/room.close', { const comment = TAPi18n.__('Closed_by_visitor', { lng: language }); if (!RocketChat.Livechat.closeRoom({ visitor, room, comment })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ rid, comment }); + return API.v1.success({ rid, comment }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.transfer', { +API.v1.addRoute('livechat/room.transfer', { post() { try { check(this.bodyParams, { @@ -92,18 +93,18 @@ RocketChat.API.v1.addRoute('livechat/room.transfer', { RocketChat.models.Messages.keepHistoryForToken(token); if (!RocketChat.Livechat.transfer(room, guest, { roomId: rid, departmentId: department })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } room = findRoom(token, rid); - return RocketChat.API.v1.success({ room }); + return API.v1.success({ room }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.survey', { +API.v1.addRoute('livechat/room.survey', { post() { try { check(this.bodyParams, { @@ -144,18 +145,18 @@ RocketChat.API.v1.addRoute('livechat/room.survey', { } if (!RocketChat.models.Rooms.updateSurveyFeedbackById(room._id, updateData)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ rid, data: updateData }); + return API.v1.success({ rid, data: updateData }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.forward', { authRequired: true }, { +API.v1.addRoute('livechat/room.forward', { authRequired: true }, { post() { - RocketChat.API.v1.success(Meteor.runAsUser(this.userId, () => Meteor.call('livechat:transfer', this.bodyParams))); + API.v1.success(Meteor.runAsUser(this.userId, () => Meteor.call('livechat:transfer', this.bodyParams))); }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/transcript.js b/packages/rocketchat-livechat/server/api/v1/transcript.js index 1dcb988c916b..efcf64e48bb0 100644 --- a/packages/rocketchat-livechat/server/api/v1/transcript.js +++ b/packages/rocketchat-livechat/server/api/v1/transcript.js @@ -1,8 +1,9 @@ import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/transcript', { +API.v1.addRoute('livechat/transcript', { post() { try { check(this.bodyParams, { @@ -13,12 +14,12 @@ RocketChat.API.v1.addRoute('livechat/transcript', { const { token, rid, email } = this.bodyParams; if (!RocketChat.Livechat.sendTranscript({ token, rid, email })) { - return RocketChat.API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_transcript') }); + return API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_transcript') }); } - return RocketChat.API.v1.success({ message: TAPi18n.__('Livechat_transcript_sent') }); + return API.v1.success({ message: TAPi18n.__('Livechat_transcript_sent') }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/videoCall.js b/packages/rocketchat-livechat/server/api/v1/videoCall.js index 01d7ce628412..aaa7e0521d3f 100644 --- a/packages/rocketchat-livechat/server/api/v1/videoCall.js +++ b/packages/rocketchat-livechat/server/api/v1/videoCall.js @@ -2,9 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, getRoom, settings } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/video.call/:token', { +API.v1.addRoute('livechat/video.call/:token', { get() { try { check(this.urlParams, { @@ -41,9 +42,9 @@ RocketChat.API.v1.addRoute('livechat/video.call/:token', { timeout: new Date(Date.now() + 3600 * 1000), }; - return RocketChat.API.v1.success({ videoCall }); + return API.v1.success({ videoCall }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/visitor.js b/packages/rocketchat-livechat/server/api/v1/visitor.js index 75dbc02997e3..f5c8a6b2e777 100644 --- a/packages/rocketchat-livechat/server/api/v1/visitor.js +++ b/packages/rocketchat-livechat/server/api/v1/visitor.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; import { findGuest } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/visitor', { +API.v1.addRoute('livechat/visitor', { post() { try { check(this.bodyParams, { @@ -49,20 +50,20 @@ RocketChat.API.v1.addRoute('livechat/visitor', { } const { key, value, overwrite } = field; if (customField.scope === 'visitor' && !LivechatVisitors.updateLivechatDataByToken(token, key, value, overwrite)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } }); } visitor = LivechatVisitors.findOneById(visitorId); - return RocketChat.API.v1.success({ visitor }); + return API.v1.success({ visitor }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/visitor/:token', { +API.v1.addRoute('livechat/visitor/:token', { get() { try { check(this.urlParams, { @@ -70,9 +71,9 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { }); const visitor = LivechatVisitors.getVisitorByToken(this.urlParams.token); - return RocketChat.API.v1.success({ visitor }); + return API.v1.success({ visitor }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { @@ -89,7 +90,7 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { const { _id } = visitor; const result = RocketChat.Livechat.removeGuest(_id); if (result) { - return RocketChat.API.v1.success({ + return API.v1.success({ visitor: { _id, ts: new Date().toISOString(), @@ -97,17 +98,17 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true }, { +API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const rooms = RocketChat.models.Rooms.findOpenByVisitorToken(this.urlParams.token, { @@ -120,11 +121,11 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true servedBy: 1, }, }).fetch(); - return RocketChat.API.v1.success({ rooms }); + return API.v1.success({ rooms }); }, }); -RocketChat.API.v1.addRoute('livechat/visitor.status', { +API.v1.addRoute('livechat/visitor.status', { post() { try { check(this.bodyParams, { @@ -141,9 +142,9 @@ RocketChat.API.v1.addRoute('livechat/visitor.status', { RocketChat.Livechat.notifyGuestStatusChanged(token, status); - return RocketChat.API.v1.success({ token, status }); + return API.v1.success({ token, status }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livestream/package.js b/packages/rocketchat-livestream/package.js index 2b22c85b851b..e99f39beae74 100644 --- a/packages/rocketchat-livestream/package.js +++ b/packages/rocketchat-livestream/package.js @@ -10,6 +10,7 @@ Package.onUse(function(api) { 'ecmascript', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:ui', 'templating', ]); diff --git a/packages/rocketchat-livestream/server/routes.js b/packages/rocketchat-livestream/server/routes.js index 5806dc03174a..92673e2bd370 100644 --- a/packages/rocketchat-livestream/server/routes.js +++ b/packages/rocketchat-livestream/server/routes.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import google from 'googleapis'; const { OAuth2 } = google.auth; -RocketChat.API.v1.addRoute('livestream/oauth', { +API.v1.addRoute('livestream/oauth', { get: function functionName() { const clientAuth = new OAuth2(RocketChat.settings.get('Broadcasting_client_id'), RocketChat.settings.get('Broadcasting_client_secret'), `${ RocketChat.settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api')); const { userId } = this.queryParams; @@ -24,7 +25,7 @@ RocketChat.API.v1.addRoute('livestream/oauth', { }, }); -RocketChat.API.v1.addRoute('livestream/oauth/callback', { +API.v1.addRoute('livestream/oauth/callback', { get: function functionName() { const { code, state } = this.queryParams; diff --git a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js index ec1da72899c6..b8b79807b1cd 100644 --- a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js +++ b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; import { RocketChat } from 'meteor/rocketchat:lib'; import { OAuth2Server } from 'meteor/rocketchat:oauth2-server'; +import { API } from 'meteor/rocketchat:api'; const oauth2server = new OAuth2Server({ accessTokensCollectionName: 'rocketchat_oauth_access_tokens', @@ -55,7 +56,7 @@ Meteor.publish('oauthClient', function(clientId) { }); }); -RocketChat.API.v1.addAuthMethod(function() { +API.v1.addAuthMethod(function() { let headerToken = this.request.headers.authorization; const getToken = this.request.query.access_token; if (headerToken != null) { diff --git a/packages/rocketchat-videobridge/package.js b/packages/rocketchat-videobridge/package.js index a455f5f047ab..7ac995888486 100644 --- a/packages/rocketchat-videobridge/package.js +++ b/packages/rocketchat-videobridge/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'less', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:bigbluebutton', 'templating', ]); diff --git a/packages/rocketchat-videobridge/server/methods/bbb.js b/packages/rocketchat-videobridge/server/methods/bbb.js index a0019961bb93..db8dc32351f6 100644 --- a/packages/rocketchat-videobridge/server/methods/bbb.js +++ b/packages/rocketchat-videobridge/server/methods/bbb.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import BigBlueButtonApi from 'meteor/rocketchat:bigbluebutton'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { HTTP } from 'meteor/http'; import xml2js from 'xml2js'; @@ -121,7 +122,7 @@ Meteor.methods({ }, }); -RocketChat.API.v1.addRoute('videoconference.bbb.update/:id', { authRequired: false }, { +API.v1.addRoute('videoconference.bbb.update/:id', { authRequired: false }, { post() { // TODO check checksum const event = JSON.parse(this.bodyParams.event)[0]; From 599f6f37aa5ca01a37a343b158eea8e00e37bb17 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 18:49:51 -0200 Subject: [PATCH 30/33] Remove dependency of RC namespace in rc-graphql (#13279) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * Remove dependency of RC namespace on half of api files * Partial Remove dependency of RC namespace in rc-api * import API where it was being used by the RC namespace * Move processWebhookMessage function to rc-lib package * Remove API from RC namespace and import missing function that was being used with namespace * Remove dependency of RC namespace in rc-graphql * Fix import from wrong package * Remove namespace in the new livechat endpoint --- 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..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 { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; 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 05bb4a65d21f6955abad0a0b8c11d651d9adbfac Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 19:14:54 -0200 Subject: [PATCH 31/33] Remove dependency of RC namespace in rc-importer (#13280) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * Remove dependency of RC namespace on half of api files * Partial Remove dependency of RC namespace in rc-api * import API where it was being used by the RC namespace * Move processWebhookMessage function to rc-lib package * Remove API from RC namespace and import missing function that was being used with namespace * Remove dependency of RC namespace in rc-graphql * Fix import from wrong package * Remove dependency of RC namespace in rc-importer * Remove namespace in the new livechat endpoint --- .../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 242954bf62d9..21d9f7809ba8 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 dc75e7d56cf8f1ef7c838c97176e92d0a2a14820 Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 19:15:20 -0200 Subject: [PATCH 32/33] Remove dependency of RC namespace in rc-ldap, katex and issue-links (#13281) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * Remove dependency of RC namespace on half of api files * Partial Remove dependency of RC namespace in rc-api * import API where it was being used by the RC namespace * Move processWebhookMessage function to rc-lib package * Remove API from RC namespace and import missing function that was being used with namespace * Remove dependency of RC namespace in rc-graphql * Fix import from wrong package * Remove dependency of RC namespace in rc-importer * Remove dependency of RC namespace in rc-issue-links * Remove dependency of RC namespace in rc-katex * Move templateVarHandler fn to rc-utils * Remove dependency of RC namespace in rc-ldap * Fix templateVarHandler that was in wrong folder * Remove namespace in the new livechat endpoint --- .../rocketchat-issuelinks/client/client.js | 9 +-- packages/rocketchat-issuelinks/package.js | 3 +- .../rocketchat-issuelinks/server/settings.js | 6 +- packages/rocketchat-katex/client/index.js | 2 +- packages/rocketchat-katex/lib/katex.js | 19 +++--- packages/rocketchat-katex/package.js | 3 +- packages/rocketchat-katex/server/index.js | 2 +- packages/rocketchat-katex/server/settings.js | 8 +-- packages/rocketchat-ldap/package.js | 6 ++ packages/rocketchat-ldap/server/ldap.js | 58 ++++++++--------- .../rocketchat-ldap/server/loginHandler.js | 21 +++--- packages/rocketchat-ldap/server/settings.js | 4 +- packages/rocketchat-ldap/server/sync.js | 64 ++++++++++--------- packages/rocketchat-ldap/server/syncUsers.js | 7 +- .../rocketchat-ldap/server/testConnection.js | 7 +- .../rocketchat-lib/lib/templateVarHandler.js | 41 +----------- .../client/messageBox.js | 9 +-- packages/rocketchat-ui-message/package.js | 1 + packages/rocketchat-utils/client/index.js | 1 + .../lib/templateVarHandler.js | 42 ++++++++++++ packages/rocketchat-utils/server/index.js | 1 + 21 files changed, 170 insertions(+), 144 deletions(-) create mode 100644 packages/rocketchat-utils/lib/templateVarHandler.js diff --git a/packages/rocketchat-issuelinks/client/client.js b/packages/rocketchat-issuelinks/client/client.js index d7c236440232..b8573888d465 100644 --- a/packages/rocketchat-issuelinks/client/client.js +++ b/packages/rocketchat-issuelinks/client/client.js @@ -1,4 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import s from 'underscore.string'; // @@ -7,13 +8,13 @@ import s from 'underscore.string'; // function IssueLink(message) { - if (s.trim(message.html) && RocketChat.settings.get('IssueLinks_Enabled')) { + if (s.trim(message.html) && settings.get('IssueLinks_Enabled')) { message.html = message.html.replace(/(?:^|\s|\n)(#[0-9]+)\b/g, function(match, issueNumber) { - const url = RocketChat.settings.get('IssueLinks_Template').replace('%s', issueNumber.substring(1)); + const url = settings.get('IssueLinks_Template').replace('%s', issueNumber.substring(1)); return match.replace(issueNumber, `${ issueNumber }`); }); } return message; } -RocketChat.callbacks.add('renderMessage', IssueLink, RocketChat.callbacks.priority.MEDIUM, 'issuelink'); +callbacks.add('renderMessage', IssueLink, callbacks.priority.MEDIUM, 'issuelink'); diff --git a/packages/rocketchat-issuelinks/package.js b/packages/rocketchat-issuelinks/package.js index 4f32a343778f..5e515d24e0f5 100644 --- a/packages/rocketchat-issuelinks/package.js +++ b/packages/rocketchat-issuelinks/package.js @@ -8,7 +8,8 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-issuelinks/server/settings.js b/packages/rocketchat-issuelinks/server/settings.js index b4a96d4e7d86..4bdb185016c1 100644 --- a/packages/rocketchat-issuelinks/server/settings.js +++ b/packages/rocketchat-issuelinks/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.add('IssueLinks_Enabled', false, { +settings.add('IssueLinks_Enabled', false, { type: 'boolean', i18nLabel: 'Enabled', i18nDescription: 'IssueLinks_Incompatible', @@ -9,7 +9,7 @@ RocketChat.settings.add('IssueLinks_Enabled', false, { public: true, }); -RocketChat.settings.add('IssueLinks_Template', '', { +settings.add('IssueLinks_Template', '', { type: 'string', i18nLabel: 'IssueLinks_LinkTemplate', i18nDescription: 'IssueLinks_LinkTemplate_Description', diff --git a/packages/rocketchat-katex/client/index.js b/packages/rocketchat-katex/client/index.js index b52d47a76610..23608aca27cc 100644 --- a/packages/rocketchat-katex/client/index.js +++ b/packages/rocketchat-katex/client/index.js @@ -1 +1 @@ -import '../lib/katex'; +export { Katex } from '../lib/katex'; diff --git a/packages/rocketchat-katex/lib/katex.js b/packages/rocketchat-katex/lib/katex.js index 2de92c13f2a1..368d7173857a 100644 --- a/packages/rocketchat-katex/lib/katex.js +++ b/packages/rocketchat-katex/lib/katex.js @@ -5,7 +5,8 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { Blaze } from 'meteor/blaze'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; import s from 'underscore.string'; @@ -24,7 +25,7 @@ class Boundary { } -class Katex { +class KatexClass { constructor() { this.delimiters_map = [ { @@ -226,27 +227,27 @@ class Katex { } katex_enabled() { - return RocketChat.settings.get('Katex_Enabled'); + return settings.get('Katex_Enabled'); } dollar_syntax_enabled() { - return RocketChat.settings.get('Katex_Dollar_Syntax'); + return settings.get('Katex_Dollar_Syntax'); } parenthesis_syntax_enabled() { - return RocketChat.settings.get('Katex_Parenthesis_Syntax'); + return settings.get('Katex_Parenthesis_Syntax'); } } -RocketChat.katex = new Katex; +export const Katex = new KatexClass; -const cb = RocketChat.katex.render_message.bind(RocketChat.katex); +const cb = Katex.render_message.bind(Katex); -RocketChat.callbacks.add('renderMessage', cb, RocketChat.callbacks.priority.HIGH - 1, 'katex'); +callbacks.add('renderMessage', cb, callbacks.priority.HIGH - 1, 'katex'); if (Meteor.isClient) { Blaze.registerHelper('RocketChatKatex', function(text) { - return RocketChat.katex.render_message(text); + return Katex.render_message(text); }); } diff --git a/packages/rocketchat-katex/package.js b/packages/rocketchat-katex/package.js index 1d9d359d0ef0..ca96c453c84d 100644 --- a/packages/rocketchat-katex/package.js +++ b/packages/rocketchat-katex/package.js @@ -9,7 +9,8 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', ]); api.addFiles('client/style.css', 'client'); const katexPath = 'node_modules/katex/dist/'; diff --git a/packages/rocketchat-katex/server/index.js b/packages/rocketchat-katex/server/index.js index 7acf7409da24..ee368f15c035 100644 --- a/packages/rocketchat-katex/server/index.js +++ b/packages/rocketchat-katex/server/index.js @@ -1,2 +1,2 @@ import './settings'; -import '../lib/katex'; +export { Katex } from '../lib/katex'; diff --git a/packages/rocketchat-katex/server/settings.js b/packages/rocketchat-katex/server/settings.js index 6684450ea952..ead386bb2748 100644 --- a/packages/rocketchat-katex/server/settings.js +++ b/packages/rocketchat-katex/server/settings.js @@ -1,19 +1,19 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { const enableQuery = { _id: 'Katex_Enabled', value: true, }; - RocketChat.settings.add('Katex_Enabled', true, { + settings.add('Katex_Enabled', true, { type: 'boolean', group: 'Message', section: 'Katex', public: true, i18n: 'Katex_Enabled_Description', }); - RocketChat.settings.add('Katex_Parenthesis_Syntax', true, { + settings.add('Katex_Parenthesis_Syntax', true, { type: 'boolean', group: 'Message', section: 'Katex', @@ -21,7 +21,7 @@ Meteor.startup(function() { enableQuery, i18nDescription: 'Katex_Parenthesis_Syntax_Description', }); - return RocketChat.settings.add('Katex_Dollar_Syntax', false, { + return settings.add('Katex_Dollar_Syntax', false, { type: 'boolean', group: 'Message', section: 'Katex', diff --git a/packages/rocketchat-ldap/package.js b/packages/rocketchat-ldap/package.js index b6ec9d1840af..91ceb5613976 100644 --- a/packages/rocketchat-ldap/package.js +++ b/packages/rocketchat-ldap/package.js @@ -11,7 +11,13 @@ Package.onUse(function(api) { 'underscore', 'sha', 'rocketchat:logger', + 'rocketchat:settings', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:notifications', + 'rocketchat:authorization', + 'rocketchat:utils', + 'rocketchat:callbacks', 'yasaricli:slugify', 'templating', 'accounts-base', diff --git a/packages/rocketchat-ldap/server/ldap.js b/packages/rocketchat-ldap/server/ldap.js index 6ce7e895f294..e373bcbfdd48 100644 --- a/packages/rocketchat-ldap/server/ldap.js +++ b/packages/rocketchat-ldap/server/ldap.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { Logger } from 'meteor/rocketchat:logger'; import ldapjs from 'ldapjs'; import Bunyan from 'bunyan'; @@ -20,32 +20,32 @@ export default class LDAP { this.connected = false; this.options = { - host: RocketChat.settings.get('LDAP_Host'), - port: RocketChat.settings.get('LDAP_Port'), - Reconnect: RocketChat.settings.get('LDAP_Reconnect'), - Internal_Log_Level: RocketChat.settings.get('LDAP_Internal_Log_Level'), - timeout: RocketChat.settings.get('LDAP_Timeout'), - connect_timeout: RocketChat.settings.get('LDAP_Connect_Timeout'), - idle_timeout: RocketChat.settings.get('LDAP_Idle_Timeout'), - encryption: RocketChat.settings.get('LDAP_Encryption'), - ca_cert: RocketChat.settings.get('LDAP_CA_Cert'), - reject_unauthorized: RocketChat.settings.get('LDAP_Reject_Unauthorized') || false, - Authentication: RocketChat.settings.get('LDAP_Authentication'), - Authentication_UserDN: RocketChat.settings.get('LDAP_Authentication_UserDN'), - Authentication_Password: RocketChat.settings.get('LDAP_Authentication_Password'), - BaseDN: RocketChat.settings.get('LDAP_BaseDN'), - User_Search_Filter: RocketChat.settings.get('LDAP_User_Search_Filter'), - User_Search_Scope: RocketChat.settings.get('LDAP_User_Search_Scope'), - User_Search_Field: RocketChat.settings.get('LDAP_User_Search_Field'), - Search_Page_Size: RocketChat.settings.get('LDAP_Search_Page_Size'), - Search_Size_Limit: RocketChat.settings.get('LDAP_Search_Size_Limit'), - group_filter_enabled: RocketChat.settings.get('LDAP_Group_Filter_Enable'), - group_filter_object_class: RocketChat.settings.get('LDAP_Group_Filter_ObjectClass'), - group_filter_group_id_attribute: RocketChat.settings.get('LDAP_Group_Filter_Group_Id_Attribute'), - group_filter_group_member_attribute: RocketChat.settings.get('LDAP_Group_Filter_Group_Member_Attribute'), - group_filter_group_member_format: RocketChat.settings.get('LDAP_Group_Filter_Group_Member_Format'), - group_filter_group_name: RocketChat.settings.get('LDAP_Group_Filter_Group_Name'), - find_user_after_login: RocketChat.settings.get('LDAP_Find_User_After_Login'), + host: settings.get('LDAP_Host'), + port: settings.get('LDAP_Port'), + Reconnect: settings.get('LDAP_Reconnect'), + Internal_Log_Level: settings.get('LDAP_Internal_Log_Level'), + timeout: settings.get('LDAP_Timeout'), + connect_timeout: settings.get('LDAP_Connect_Timeout'), + idle_timeout: settings.get('LDAP_Idle_Timeout'), + encryption: settings.get('LDAP_Encryption'), + ca_cert: settings.get('LDAP_CA_Cert'), + reject_unauthorized: settings.get('LDAP_Reject_Unauthorized') || false, + Authentication: settings.get('LDAP_Authentication'), + Authentication_UserDN: settings.get('LDAP_Authentication_UserDN'), + Authentication_Password: settings.get('LDAP_Authentication_Password'), + BaseDN: settings.get('LDAP_BaseDN'), + User_Search_Filter: settings.get('LDAP_User_Search_Filter'), + User_Search_Scope: settings.get('LDAP_User_Search_Scope'), + User_Search_Field: settings.get('LDAP_User_Search_Field'), + Search_Page_Size: settings.get('LDAP_Search_Page_Size'), + Search_Size_Limit: settings.get('LDAP_Search_Size_Limit'), + group_filter_enabled: settings.get('LDAP_Group_Filter_Enable'), + group_filter_object_class: settings.get('LDAP_Group_Filter_ObjectClass'), + group_filter_group_id_attribute: settings.get('LDAP_Group_Filter_Group_Id_Attribute'), + group_filter_group_member_attribute: settings.get('LDAP_Group_Filter_Group_Member_Attribute'), + group_filter_group_member_format: settings.get('LDAP_Group_Filter_Group_Member_Format'), + group_filter_group_name: settings.get('LDAP_Group_Filter_Group_Name'), + find_user_after_login: settings.get('LDAP_Find_User_After_Login'), }; } @@ -91,7 +91,7 @@ export default class LDAP { if (this.options.ca_cert && this.options.ca_cert !== '') { // Split CA cert into array of strings - const chainLines = RocketChat.settings.get('LDAP_CA_Cert').split('\n'); + const chainLines = settings.get('LDAP_CA_Cert').split('\n'); let cert = []; const ca = []; chainLines.forEach((line) => { @@ -249,7 +249,7 @@ export default class LDAP { getUserByIdSync(id, attribute) { this.bindIfNecessary(); - const Unique_Identifier_Field = RocketChat.settings.get('LDAP_Unique_Identifier_Field').split(','); + const Unique_Identifier_Field = settings.get('LDAP_Unique_Identifier_Field').split(','); let filter; diff --git a/packages/rocketchat-ldap/server/loginHandler.js b/packages/rocketchat-ldap/server/loginHandler.js index 345dd26765e4..84226913f341 100644 --- a/packages/rocketchat-ldap/server/loginHandler.js +++ b/packages/rocketchat-ldap/server/loginHandler.js @@ -1,7 +1,8 @@ import { SHA256 } from 'meteor/sha'; import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { Logger } from 'meteor/rocketchat:logger'; import { slug, getLdapUsername, getLdapUserUniqueID, syncUserData, addLdapUser } from './sync'; import LDAP from './ldap'; @@ -37,7 +38,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { logger.info('Init LDAP login', loginRequest.username); - if (RocketChat.settings.get('LDAP_Enable') !== true) { + if (settings.get('LDAP_Enable') !== true) { return fallbackDefaultAccountSystem(this, loginRequest.username, loginRequest.ldapPass); } @@ -68,7 +69,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { } if (ldapUser === undefined) { - if (RocketChat.settings.get('LDAP_Login_Fallback') === true) { + if (settings.get('LDAP_Login_Fallback') === true) { return fallbackDefaultAccountSystem(self, loginRequest.username, loginRequest.ldapPass); } @@ -94,7 +95,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { let username; - if (RocketChat.settings.get('LDAP_Username_Field') !== '') { + if (settings.get('LDAP_Username_Field') !== '') { username = slug(getLdapUsername(ldapUser)); } else { username = slug(loginRequest.username); @@ -112,7 +113,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { // Login user if they exist if (user) { - if (user.ldap !== true && RocketChat.settings.get('LDAP_Merge_Existing_Users') !== true) { + if (user.ldap !== true && settings.get('LDAP_Merge_Existing_Users') !== true) { logger.info('User exists without "ldap: true"'); throw new Meteor.Error('LDAP-login-error', `LDAP Authentication succeded, but there's already an existing user with provided username [${ username }] in Mongo.`); } @@ -121,10 +122,10 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { syncUserData(user, ldapUser); - if (RocketChat.settings.get('LDAP_Login_Fallback') === true && typeof loginRequest.ldapPass === 'string' && loginRequest.ldapPass.trim() !== '') { + if (settings.get('LDAP_Login_Fallback') === true && typeof loginRequest.ldapPass === 'string' && loginRequest.ldapPass.trim() !== '') { Accounts.setPassword(user._id, loginRequest.ldapPass, { logout: false }); } - RocketChat.callbacks.run('afterLDAPLogin', { user, ldapUser, ldap }); + callbacks.run('afterLDAPLogin', { user, ldapUser, ldap }); return { userId: user._id, }; @@ -132,11 +133,11 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { logger.info('User does not exist, creating', username); - if (RocketChat.settings.get('LDAP_Username_Field') === '') { + if (settings.get('LDAP_Username_Field') === '') { username = undefined; } - if (RocketChat.settings.get('LDAP_Login_Fallback') !== true) { + if (settings.get('LDAP_Login_Fallback') !== true) { loginRequest.ldapPass = undefined; } @@ -146,7 +147,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) { if (result instanceof Error) { throw result; } - RocketChat.callbacks.run('afterLDAPLogin', { user: result, ldapUser, ldap }); + callbacks.run('afterLDAPLogin', { user: result, ldapUser, ldap }); return result; }); diff --git a/packages/rocketchat-ldap/server/settings.js b/packages/rocketchat-ldap/server/settings.js index 4706105831ef..e6d711e94d15 100644 --- a/packages/rocketchat-ldap/server/settings.js +++ b/packages/rocketchat-ldap/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('LDAP', function() { +settings.addGroup('LDAP', function() { const enableQuery = { _id: 'LDAP_Enable', value: true }; const enableAuthentication = [ enableQuery, diff --git a/packages/rocketchat-ldap/server/sync.js b/packages/rocketchat-ldap/server/sync.js index d465eee8d685..190ba9943357 100644 --- a/packages/rocketchat-ldap/server/sync.js +++ b/packages/rocketchat-ldap/server/sync.js @@ -1,8 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { RocketChatFile } from 'meteor/rocketchat:file'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users } from 'meteor/rocketchat:models'; import { Logger } from 'meteor/rocketchat:logger'; +import { _setRealName, _setUsername } from 'meteor/rocketchat:lib'; +import { templateVarHandler } from 'meteor/rocketchat:utils'; import { SyncedCron } from 'meteor/littledata:synced-cron'; import { FileUpload } from 'meteor/rocketchat:file-upload'; import { slugify } from 'meteor/yasaricli:slugify'; @@ -12,7 +16,7 @@ import LDAP from './ldap'; const logger = new Logger('LDAPSync', {}); export function slug(text) { - if (RocketChat.settings.get('UTF8_Names_Slugify') !== true) { + if (settings.get('UTF8_Names_Slugify') !== true) { return text; } text = slugify(text, '.'); @@ -30,7 +34,7 @@ export function getPropertyValue(obj, key) { export function getLdapUsername(ldapUser) { - const usernameField = RocketChat.settings.get('LDAP_Username_Field'); + const usernameField = settings.get('LDAP_Username_Field'); if (usernameField.indexOf('#{') > -1) { return usernameField.replace(/#{(.+?)}/g, function(match, field) { @@ -43,7 +47,7 @@ export function getLdapUsername(ldapUser) { export function getLdapUserUniqueID(ldapUser) { - let Unique_Identifier_Field = RocketChat.settings.get('LDAP_Unique_Identifier_Field'); + let Unique_Identifier_Field = settings.get('LDAP_Unique_Identifier_Field'); if (Unique_Identifier_Field !== '') { Unique_Identifier_Field = Unique_Identifier_Field.replace(/\s/g, '').split(','); @@ -51,7 +55,7 @@ export function getLdapUserUniqueID(ldapUser) { Unique_Identifier_Field = []; } - let User_Search_Field = RocketChat.settings.get('LDAP_User_Search_Field'); + let User_Search_Field = settings.get('LDAP_User_Search_Field'); if (User_Search_Field !== '') { User_Search_Field = User_Search_Field.replace(/\s/g, '').split(','); @@ -74,8 +78,8 @@ export function getLdapUserUniqueID(ldapUser) { } export function getDataToSyncUserData(ldapUser, user) { - const syncUserData = RocketChat.settings.get('LDAP_Sync_User_Data'); - const syncUserDataFieldMap = RocketChat.settings.get('LDAP_Sync_User_Data_FieldMap').trim(); + const syncUserData = settings.get('LDAP_Sync_User_Data'); + const syncUserDataFieldMap = settings.get('LDAP_Sync_User_Data_FieldMap').trim(); const userData = {}; @@ -112,7 +116,7 @@ export function getDataToSyncUserData(ldapUser, user) { let customFieldsMeta; try { - customFieldsMeta = JSON.parse(RocketChat.settings.get('Accounts_CustomFields')); + customFieldsMeta = JSON.parse(settings.get('Accounts_CustomFields')); } catch (e) { logger.debug('Invalid JSON for Custom Fields'); return; @@ -125,7 +129,7 @@ export function getDataToSyncUserData(ldapUser, user) { } const tmpUserField = getPropertyValue(user, userField); - const tmpLdapField = RocketChat.templateVarHandler(ldapField, ldapUser); + const tmpLdapField = templateVarHandler(ldapField, ldapUser); if (tmpLdapField && tmpUserField !== tmpLdapField) { // creates the object structure instead of just assigning 'tmpLdapField' to @@ -178,22 +182,22 @@ export function syncUserData(user, ldapUser) { if (user && user._id && userData) { logger.debug('setting', JSON.stringify(userData, null, 2)); if (userData.name) { - RocketChat._setRealName(user._id, userData.name); + _setRealName(user._id, userData.name); delete userData.name; } Meteor.users.update(user._id, { $set: userData }); user = Meteor.users.findOne({ _id: user._id }); } - if (RocketChat.settings.get('LDAP_Username_Field') !== '') { + if (settings.get('LDAP_Username_Field') !== '') { const username = slug(getLdapUsername(ldapUser)); if (user && user._id && username !== user.username) { logger.info('Syncing user username', user.username, '->', username); - RocketChat._setUsername(user._id, username); + _setUsername(user._id, username); } } - if (user && user._id && RocketChat.settings.get('LDAP_Sync_User_Avatar') === true) { + if (user && user._id && settings.get('LDAP_Sync_User_Avatar') === true) { const avatar = ldapUser._raw.thumbnailPhoto || ldapUser._raw.jpegPhoto; if (avatar) { logger.info('Syncing user avatar'); @@ -210,8 +214,8 @@ export function syncUserData(user, ldapUser) { Meteor.runAsUser(user._id, () => { fileStore.insert(file, rs, () => { Meteor.setTimeout(function() { - RocketChat.models.Users.setAvatarOrigin(user._id, 'ldap'); - RocketChat.Notifications.notifyLogged('updateAvatar', { username: user.username }); + Users.setAvatarOrigin(user._id, 'ldap'); + Notifications.notifyLogged('updateAvatar', { username: user.username }); }, 500); }); }); @@ -238,8 +242,8 @@ export function addLdapUser(ldapUser, username, password) { } } else if (ldapUser.mail && ldapUser.mail.indexOf('@') > -1) { userObject.email = ldapUser.mail; - } else if (RocketChat.settings.get('LDAP_Default_Domain') !== '') { - userObject.email = `${ username || uniqueId.value }@${ RocketChat.settings.get('LDAP_Default_Domain') }`; + } else if (settings.get('LDAP_Default_Domain') !== '') { + userObject.email = `${ username || uniqueId.value }@${ settings.get('LDAP_Default_Domain') }`; } else { const error = new Meteor.Error('LDAP-login-error', 'LDAP Authentication succeded, there is no email to create an account. Have you tried setting your Default Domain in LDAP Settings?'); logger.error(error); @@ -267,7 +271,7 @@ export function addLdapUser(ldapUser, username, password) { } export function importNewUsers(ldap) { - if (RocketChat.settings.get('LDAP_Enable') !== true) { + if (settings.get('LDAP_Enable') !== true) { logger.error('Can\'t run LDAP Import, LDAP is disabled'); return; } @@ -295,14 +299,14 @@ export function importNewUsers(ldap) { logger.debug('userQuery', userQuery); let username; - if (RocketChat.settings.get('LDAP_Username_Field') !== '') { + if (settings.get('LDAP_Username_Field') !== '') { username = slug(getLdapUsername(ldapUser)); } // Add user if it was not added before let user = Meteor.users.findOne(userQuery); - if (!user && username && RocketChat.settings.get('LDAP_Merge_Existing_Users') === true) { + if (!user && username && settings.get('LDAP_Merge_Existing_Users') === true) { const userQuery = { username, }; @@ -333,7 +337,7 @@ export function importNewUsers(ldap) { } function sync() { - if (RocketChat.settings.get('LDAP_Enable') !== true) { + if (settings.get('LDAP_Enable') !== true) { return; } @@ -343,15 +347,15 @@ function sync() { ldap.connectSync(); let users; - if (RocketChat.settings.get('LDAP_Background_Sync_Keep_Existant_Users_Updated') === true) { - users = RocketChat.models.Users.findLDAPUsers(); + if (settings.get('LDAP_Background_Sync_Keep_Existant_Users_Updated') === true) { + users = Users.findLDAPUsers(); } - if (RocketChat.settings.get('LDAP_Background_Sync_Import_New_Users') === true) { + if (settings.get('LDAP_Background_Sync_Import_New_Users') === true) { importNewUsers(ldap); } - if (RocketChat.settings.get('LDAP_Background_Sync_Keep_Existant_Users_Updated') === true) { + if (settings.get('LDAP_Background_Sync_Keep_Existant_Users_Updated') === true) { users.forEach(function(user) { let ldapUser; @@ -378,7 +382,7 @@ function sync() { const jobName = 'LDAP_Sync'; const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounced() { - if (RocketChat.settings.get('LDAP_Background_Sync') !== true) { + if (settings.get('LDAP_Background_Sync') !== true) { logger.info('Disabling LDAP Background Sync'); if (SyncedCron.nextScheduledAtDate(jobName)) { SyncedCron.remove(jobName); @@ -386,11 +390,11 @@ const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounce return; } - if (RocketChat.settings.get('LDAP_Background_Sync_Interval')) { + if (settings.get('LDAP_Background_Sync_Interval')) { logger.info('Enabling LDAP Background Sync'); SyncedCron.add({ name: jobName, - schedule: (parser) => parser.text(RocketChat.settings.get('LDAP_Background_Sync_Interval')), + schedule: (parser) => parser.text(settings.get('LDAP_Background_Sync_Interval')), job() { sync(); }, @@ -401,7 +405,7 @@ const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounce Meteor.startup(() => { Meteor.defer(() => { - RocketChat.settings.get('LDAP_Background_Sync', addCronJob); - RocketChat.settings.get('LDAP_Background_Sync_Interval', addCronJob); + settings.get('LDAP_Background_Sync', addCronJob); + settings.get('LDAP_Background_Sync_Interval', addCronJob); }); }); diff --git a/packages/rocketchat-ldap/server/syncUsers.js b/packages/rocketchat-ldap/server/syncUsers.js index 98d0bfcbb475..b590b4d20b57 100644 --- a/packages/rocketchat-ldap/server/syncUsers.js +++ b/packages/rocketchat-ldap/server/syncUsers.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; import { importNewUsers } from './sync'; Meteor.methods({ @@ -9,11 +10,11 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'ldap_sync_users' }); } - if (!RocketChat.authz.hasRole(user._id, 'admin')) { + if (!hasRole(user._id, 'admin')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'ldap_sync_users' }); } - if (RocketChat.settings.get('LDAP_Enable') !== true) { + if (settings.get('LDAP_Enable') !== true) { throw new Meteor.Error('LDAP_disabled'); } diff --git a/packages/rocketchat-ldap/server/testConnection.js b/packages/rocketchat-ldap/server/testConnection.js index 5e0ab7be0042..d1a4aa6d340d 100644 --- a/packages/rocketchat-ldap/server/testConnection.js +++ b/packages/rocketchat-ldap/server/testConnection.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; import LDAP from './ldap'; Meteor.methods({ @@ -9,11 +10,11 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'ldap_test_connection' }); } - if (!RocketChat.authz.hasRole(user._id, 'admin')) { + if (!hasRole(user._id, 'admin')) { throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'ldap_test_connection' }); } - if (RocketChat.settings.get('LDAP_Enable') !== true) { + if (settings.get('LDAP_Enable') !== true) { throw new Meteor.Error('LDAP_disabled'); } diff --git a/packages/rocketchat-lib/lib/templateVarHandler.js b/packages/rocketchat-lib/lib/templateVarHandler.js index d823e4841f36..9359d1dd242b 100644 --- a/packages/rocketchat-lib/lib/templateVarHandler.js +++ b/packages/rocketchat-lib/lib/templateVarHandler.js @@ -1,40 +1,3 @@ -import { Meteor } from 'meteor/meteor'; -import { Logger } from 'meteor/rocketchat:logger'; +import { templateVarHandler } from 'meteor/rocketchat:utils'; -let logger; - -if (Meteor.isServer) { - logger = new Logger('TemplateVarHandler', {}); -} - -RocketChat.templateVarHandler = function(variable, object) { - - const templateRegex = /#{([\w\-]+)}/gi; - let match = templateRegex.exec(variable); - let tmpVariable = variable; - - if (match == null) { - if (!object.hasOwnProperty(variable)) { - logger && logger.debug(`user does not have attribute: ${ variable }`); - return; - } - return object[variable]; - } else { - logger && logger.debug('template found. replacing values'); - while (match != null) { - const tmplVar = match[0]; - const tmplAttrName = match[1]; - - if (!object.hasOwnProperty(tmplAttrName)) { - logger && logger.debug(`user does not have attribute: ${ tmplAttrName }`); - return; - } - - const attrVal = object[tmplAttrName]; - logger && logger.debug(`replacing template var: ${ tmplVar } with value: ${ attrVal }`); - tmpVariable = tmpVariable.replace(tmplVar, attrVal); - match = templateRegex.exec(variable); - } - return tmpVariable; - } -}; +RocketChat.templateVarHandler = templateVarHandler; diff --git a/packages/rocketchat-ui-message/client/messageBox.js b/packages/rocketchat-ui-message/client/messageBox.js index a8d80f1b01fc..ed71ed5613ff 100644 --- a/packages/rocketchat-ui-message/client/messageBox.js +++ b/packages/rocketchat-ui-message/client/messageBox.js @@ -8,6 +8,7 @@ import { RocketChat } from 'meteor/rocketchat:lib'; import { fileUploadHandler } from 'meteor/rocketchat:file-upload'; import { ChatSubscription, RoomHistoryManager, RoomManager, KonchatNotification, popover, ChatMessages, fileUpload, AudioRecorder, chatMessages, MsgTyping } from 'meteor/rocketchat:ui'; import { t } from 'meteor/rocketchat:utils'; +import { Katex } from 'meteor/rocketchat:katex'; import toastr from 'toastr'; import moment from 'moment'; import _ from 'underscore'; @@ -15,11 +16,11 @@ import _ from 'underscore'; let audioMessageIntervalId; function katexSyntax() { - if (RocketChat.katex.katex_enabled()) { - if (RocketChat.katex.dollar_syntax_enabled()) { + if (Katex.katex_enabled()) { + if (Katex.dollar_syntax_enabled()) { return '$$KaTeX$$'; } - if (RocketChat.katex.parenthesis_syntax_enabled()) { + if (Katex.parenthesis_syntax_enabled()) { return '\\[KaTeX\\]'; } } @@ -134,7 +135,7 @@ const markdownButtons = [ { label: katexSyntax, link: 'https://khan.github.io/KaTeX/function-support.html', - condition: () => RocketChat.katex.katex_enabled(), + condition: () => Katex.katex_enabled(), }, ]; diff --git a/packages/rocketchat-ui-message/package.js b/packages/rocketchat-ui-message/package.js index 2ed826cf9223..550a41dc6d9d 100644 --- a/packages/rocketchat-ui-message/package.js +++ b/packages/rocketchat-ui-message/package.js @@ -20,6 +20,7 @@ Package.onUse(function(api) { 'rocketchat:ui', 'rocketchat:ui-utils', 'rocketchat:emoji', + 'rocketchat:katex', 'rocketchat:lib', 'rocketchat:ui', 'rocketchat:ui-account', diff --git a/packages/rocketchat-utils/client/index.js b/packages/rocketchat-utils/client/index.js index 3fc66523a403..958894c3f10e 100644 --- a/packages/rocketchat-utils/client/index.js +++ b/packages/rocketchat-utils/client/index.js @@ -17,3 +17,4 @@ export { getAvatarColor } from '../lib/getAvatarColor'; export { getURL } from '../lib/getURL'; export { getValidRoomName } from '../lib/getValidRoomName'; export { placeholders } from '../lib/placeholders'; +export { templateVarHandler } from '../lib/templateVarHandler'; diff --git a/packages/rocketchat-utils/lib/templateVarHandler.js b/packages/rocketchat-utils/lib/templateVarHandler.js new file mode 100644 index 000000000000..3d31f8d9a43a --- /dev/null +++ b/packages/rocketchat-utils/lib/templateVarHandler.js @@ -0,0 +1,42 @@ +import { Meteor } from 'meteor/meteor'; + +let logger; + +if (Meteor.isServer) { + Meteor.startup(async() => { + const { Logger } = await import('meteor/rocketchat:logger'); + logger = new Logger('TemplateVarHandler', {}); + }); +} + +export const templateVarHandler = function(variable, object) { + + const templateRegex = /#{([\w\-]+)}/gi; + let match = templateRegex.exec(variable); + let tmpVariable = variable; + + if (match == null) { + if (!object.hasOwnProperty(variable)) { + logger && logger.debug(`user does not have attribute: ${ variable }`); + return; + } + return object[variable]; + } else { + logger && logger.debug('template found. replacing values'); + while (match != null) { + const tmplVar = match[0]; + const tmplAttrName = match[1]; + + if (!object.hasOwnProperty(tmplAttrName)) { + logger && logger.debug(`user does not have attribute: ${ tmplAttrName }`); + return; + } + + const attrVal = object[tmplAttrName]; + logger && logger.debug(`replacing template var: ${ tmplVar } with value: ${ attrVal }`); + tmpVariable = tmpVariable.replace(tmplVar, attrVal); + match = templateRegex.exec(variable); + } + return tmpVariable; + } +}; diff --git a/packages/rocketchat-utils/server/index.js b/packages/rocketchat-utils/server/index.js index c40c7e4517dc..e9be652340da 100644 --- a/packages/rocketchat-utils/server/index.js +++ b/packages/rocketchat-utils/server/index.js @@ -15,3 +15,4 @@ export { getURL } from '../lib/getURL'; export { getValidRoomName } from '../lib/getValidRoomName'; export { placeholders } from '../lib/placeholders'; export { composeMessageObjectWithUser } from './lib/composeMessageObjectWithUser'; +export { templateVarHandler } from '../lib/templateVarHandler'; From 412eb06b6cc6d52e5f6c1f01c1569b4225d5face Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 19:46:24 -0200 Subject: [PATCH 33/33] Remove dependency of RC namespace in rc-livestream and rc-mail-messages (#13320) * Move RestAPI client to rc-api package * Remove dependency of RC namespace in rc-api/helpers and api.js * Remove dependency of RC namespace on half of api files * Partial Remove dependency of RC namespace in rc-api * import API where it was being used by the RC namespace * Move processWebhookMessage function to rc-lib package * Remove API from RC namespace and import missing function that was being used with namespace * Remove dependency of RC namespace in rc-graphql * Fix import from wrong package * Remove dependency of RC namespace in rc-importer * Remove dependency of RC namespace in rc-issue-links * Remove dependency of RC namespace in rc-katex * Move templateVarHandler fn to rc-utils * Remove dependency of RC namespace in rc-ldap * Remove dependency of RC namespace in rc-livestream * Remove dependency of RC namespace in rc-mail-messages * Fix templateVarHandler that was in wrong folder * Remove namespace in the new livechat endpoint --- .../rocketchat-livestream/client/oauth.js | 4 +-- .../rocketchat-livestream/client/tabBar.js | 14 ++++++----- .../client/views/broadcastView.js | 5 ++-- .../client/views/liveStreamTab.js | 20 +++++++++------ packages/rocketchat-livestream/package.js | 6 ++++- .../rocketchat-livestream/server/methods.js | 25 ++++++++++--------- .../rocketchat-livestream/server/routes.js | 9 ++++--- .../rocketchat-livestream/server/settings.js | 4 +-- .../client/startup.js | 7 +++--- .../client/views/mailer.js | 5 ++-- packages/rocketchat-mail-messages/package.js | 3 +++ .../server/functions/sendMail.js | 6 ++--- .../server/functions/unsubscribe.js | 4 +-- .../rocketchat-mail-messages/server/index.js | 1 - .../server/methods/sendMail.js | 4 +-- .../server/models/Users.js | 16 ------------ .../server/startup.js | 4 +-- .../rocketchat-models/server/models/Users.js | 15 +++++++++++ 18 files changed, 84 insertions(+), 68 deletions(-) delete mode 100644 packages/rocketchat-mail-messages/server/models/Users.js diff --git a/packages/rocketchat-livestream/client/oauth.js b/packages/rocketchat-livestream/client/oauth.js index eb9b5358be4d..79e45036c768 100644 --- a/packages/rocketchat-livestream/client/oauth.js +++ b/packages/rocketchat-livestream/client/oauth.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; export const close = (popup) => new Promise(function(resolve) { const checkInterval = setInterval(() => { @@ -11,6 +11,6 @@ export const close = (popup) => new Promise(function(resolve) { }); export const auth = async() => { - const oauthWindow = window.open(`${ RocketChat.settings.get('Site_Url') }/api/v1/livestream/oauth?userId=${ Meteor.userId() }`, 'youtube-integration-oauth', 'width=400,height=600'); + const oauthWindow = window.open(`${ settings.get('Site_Url') }/api/v1/livestream/oauth?userId=${ Meteor.userId() }`, 'youtube-integration-oauth', 'width=400,height=600'); return await close(oauthWindow); }; diff --git a/packages/rocketchat-livestream/client/tabBar.js b/packages/rocketchat-livestream/client/tabBar.js index 7741f96a3e36..a608dfa4b32d 100644 --- a/packages/rocketchat-livestream/client/tabBar.js +++ b/packages/rocketchat-livestream/client/tabBar.js @@ -1,15 +1,17 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { Session } from 'meteor/session'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; +import { Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { Tracker.autorun(function() { - RocketChat.TabBar.removeButton('livestream'); - if (RocketChat.settings.get('Livestream_enabled')) { - const live = RocketChat.models.Rooms.findOne({ _id: Session.get('openedRoom'), 'streamingOptions.type': 'livestream', 'streamingOptions.id': { $exists :1 } }, { fields: { streamingOptions: 1 } }); - RocketChat.TabBar.size = live ? 5 : 4; - return RocketChat.TabBar.addButton({ + TabBar.removeButton('livestream'); + if (settings.get('Livestream_enabled')) { + const live = Rooms.findOne({ _id: Session.get('openedRoom'), 'streamingOptions.type': 'livestream', 'streamingOptions.id': { $exists :1 } }, { fields: { streamingOptions: 1 } }); + TabBar.size = live ? 5 : 4; + return TabBar.addButton({ groups: ['channel', 'group'], id: 'livestream', i18nTitle: 'Livestream', diff --git a/packages/rocketchat-livestream/client/views/broadcastView.js b/packages/rocketchat-livestream/client/views/broadcastView.js index e2feea2e05f8..1e6a23d590a6 100644 --- a/packages/rocketchat-livestream/client/views/broadcastView.js +++ b/packages/rocketchat-livestream/client/views/broadcastView.js @@ -2,7 +2,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; +import { handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; const getMedia = () => navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; const createAndConnect = (url) => { @@ -66,7 +67,7 @@ Template.broadcastView.helpers({ }); Template.broadcastView.onCreated(async function() { - const connection = createAndConnect(`${ RocketChat.settings.get('Broadcasting_media_server_url') }/${ this.data.id }`); + const connection = createAndConnect(`${ settings.get('Broadcasting_media_server_url') }/${ this.data.id }`); this.mediaStream = new ReactiveVar(null); this.mediaRecorder = new ReactiveVar(null); this.connection = new ReactiveVar(connection); diff --git a/packages/rocketchat-livestream/client/views/liveStreamTab.js b/packages/rocketchat-livestream/client/views/liveStreamTab.js index 647d80c877b8..3b92e0b3323f 100644 --- a/packages/rocketchat-livestream/client/views/liveStreamTab.js +++ b/packages/rocketchat-livestream/client/views/liveStreamTab.js @@ -6,9 +6,13 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import toastr from 'toastr'; import { auth } from '../oauth.js'; -import { RocketChatAnnouncement, RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { popout } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { RocketChatAnnouncement } from 'meteor/rocketchat:lib'; +import { popout } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { Users, Rooms } from 'meteor/rocketchat:models'; export const call = (...args) => new Promise(function(resolve, reject) { Meteor.call(...args, function(err, result) { @@ -46,7 +50,7 @@ function optionsFromUrl(url) { Template.liveStreamTab.helpers({ broadcastEnabled() { - return !!RocketChat.settings.get('Broadcasting_enabled'); + return !!settings.get('Broadcasting_enabled'); }, streamingSource() { return Template.instance().streamingOptions.get() ? Template.instance().streamingOptions.get().url : ''; @@ -64,7 +68,7 @@ Template.liveStreamTab.helpers({ return !!Template.instance().streamingOptions.get() && !!Template.instance().streamingOptions.get().url && Template.instance().streamingOptions.get().url !== ''; }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', this.rid); + return hasAllPermission('edit-room', this.rid); }, editing() { return Template.instance().editing.get() || Template.instance().streamingOptions.get() == null || (Template.instance().streamingOptions.get() != null && (Template.instance().streamingOptions.get().url == null || Template.instance().streamingOptions.get().url === '')); @@ -100,7 +104,7 @@ Template.liveStreamTab.onCreated(function() { this.popoutOpen = new ReactiveVar(popout.context != null); this.autorun(() => { - const room = RocketChat.models.Rooms.findOne(this.data.rid, { fields: { streamingOptions : 1 } }); + const room = Rooms.findOne(this.data.rid, { fields: { streamingOptions : 1 } }); this.streamingOptions.set(room.streamingOptions); }); }); @@ -246,7 +250,7 @@ Template.liveStreamTab.events({ e.preventDefault(); e.currentTarget.classList.add('loading'); try { - const user = RocketChat.models.Users.findOne({ _id: Meteor.userId() }, { fields: { 'settings.livestream': 1 } }); + const user = Users.findOne({ _id: Meteor.userId() }, { fields: { 'settings.livestream': 1 } }); if (!user.settings || !user.settings.livestream) { await auth(); } @@ -269,7 +273,7 @@ Template.liveStreamTab.events({ }, }); -RocketChat.callbacks.add('openBroadcast', (rid) => { +callbacks.add('openBroadcast', (rid) => { const roomData = Session.get(`roomData${ rid }`); if (!roomData) { return; } popout.open({ diff --git a/packages/rocketchat-livestream/package.js b/packages/rocketchat-livestream/package.js index e99f39beae74..5bdeb36baa98 100644 --- a/packages/rocketchat-livestream/package.js +++ b/packages/rocketchat-livestream/package.js @@ -9,9 +9,13 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:utils', + 'rocketchat:ui-utils', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:authorization', 'rocketchat:lib', 'rocketchat:api', - 'rocketchat:ui', 'templating', ]); api.addFiles('client/styles/liveStreamTab.css', 'client'); diff --git a/packages/rocketchat-livestream/server/methods.js b/packages/rocketchat-livestream/server/methods.js index 3625c74ceb56..5e1f4471280b 100644 --- a/packages/rocketchat-livestream/server/methods.js +++ b/packages/rocketchat-livestream/server/methods.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Rooms } from 'meteor/rocketchat:models'; import { createLiveStream, statusLiveStream, statusStreamLiveStream, getBroadcastStatus, setBroadcastStatus } from './functions/livestream'; const selectLivestreamSettings = (user) => user && user.settings && user.settings.livestream; @@ -27,8 +28,8 @@ Meteor.methods({ id: streamId, access_token, refresh_token, - clientId: RocketChat.settings.get('Broadcasting_client_id'), - clientSecret: RocketChat.settings.get('Broadcasting_client_secret'), + clientId: settings.get('Broadcasting_client_id'), + clientSecret: settings.get('Broadcasting_client_secret'), }); }, @@ -54,8 +55,8 @@ Meteor.methods({ access_token, refresh_token, status, - clientId: RocketChat.settings.get('Broadcasting_client_id'), - clientSecret: RocketChat.settings.get('Broadcasting_client_secret'), + clientId: settings.get('Broadcasting_client_id'), + clientSecret: settings.get('Broadcasting_client_secret'), }); }, @@ -68,7 +69,7 @@ Meteor.methods({ }); } - const room = RocketChat.models.Rooms.findOne({ _id: rid }); + const room = Rooms.findOne({ _id: rid }); if (!room) { // TODO: change error @@ -82,8 +83,8 @@ Meteor.methods({ room, access_token, refresh_token, - clientId: RocketChat.settings.get('Broadcasting_client_id'), - clientSecret: RocketChat.settings.get('Broadcasting_client_secret'), + clientId: settings.get('Broadcasting_client_id'), + clientSecret: settings.get('Broadcasting_client_secret'), }); }, @@ -108,8 +109,8 @@ Meteor.methods({ id: broadcastId, access_token, refresh_token, - clientId: RocketChat.settings.get('Broadcasting_client_id'), - clientSecret: RocketChat.settings.get('Broadcasting_client_secret'), + clientId: settings.get('Broadcasting_client_id'), + clientSecret: settings.get('Broadcasting_client_secret'), }); }, async setBroadcastStatus({ broadcastId, status }) { @@ -134,8 +135,8 @@ Meteor.methods({ access_token, refresh_token, status, - clientId: RocketChat.settings.get('Broadcasting_client_id'), - clientSecret: RocketChat.settings.get('Broadcasting_client_secret'), + clientId: settings.get('Broadcasting_client_id'), + clientSecret: settings.get('Broadcasting_client_secret'), }); }, diff --git a/packages/rocketchat-livestream/server/routes.js b/packages/rocketchat-livestream/server/routes.js index 92673e2bd370..437d1075efc9 100644 --- a/packages/rocketchat-livestream/server/routes.js +++ b/packages/rocketchat-livestream/server/routes.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; import { API } from 'meteor/rocketchat:api'; import google from 'googleapis'; const { OAuth2 } = google.auth; 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 clientAuth = new OAuth2(settings.get('Broadcasting_client_id'), settings.get('Broadcasting_client_secret'), `${ settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api')); const { userId } = this.queryParams; const url = clientAuth.generateAuthUrl({ access_type: 'offline', @@ -31,11 +32,11 @@ API.v1.addRoute('livestream/oauth/callback', { const { userId } = JSON.parse(state); - 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 clientAuth = new OAuth2(settings.get('Broadcasting_client_id'), settings.get('Broadcasting_client_secret'), `${ settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api')); const ret = Meteor.wrapAsync(clientAuth.getToken.bind(clientAuth))(code); - RocketChat.models.Users.update({ _id: userId }, { $set: { + Users.update({ _id: userId }, { $set: { 'settings.livestream' : ret, } }); diff --git a/packages/rocketchat-livestream/server/settings.js b/packages/rocketchat-livestream/server/settings.js index f5ba52b6343e..8a4d5223b94e 100644 --- a/packages/rocketchat-livestream/server/settings.js +++ b/packages/rocketchat-livestream/server/settings.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Meteor.startup(function() { - RocketChat.settings.addGroup('LiveStream & Broadcasting', function() { + settings.addGroup('LiveStream & Broadcasting', function() { this.add('Livestream_enabled', false, { type: 'boolean', diff --git a/packages/rocketchat-mail-messages/client/startup.js b/packages/rocketchat-mail-messages/client/startup.js index 285fc2297ca1..6681e32a56d6 100644 --- a/packages/rocketchat-mail-messages/client/startup.js +++ b/packages/rocketchat-mail-messages/client/startup.js @@ -1,10 +1,11 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { AdminBox } from 'meteor/rocketchat:ui-utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; -RocketChat.AdminBox.addOption({ +AdminBox.addOption({ href: 'mailer', i18nLabel: 'Mailer', icon: 'mail', permissionGranted() { - return RocketChat.authz.hasAllPermission('access-mailer'); + return hasAllPermission('access-mailer'); }, }); diff --git a/packages/rocketchat-mail-messages/client/views/mailer.js b/packages/rocketchat-mail-messages/client/views/mailer.js index a59ef3f18f84..1549301fdcdd 100644 --- a/packages/rocketchat-mail-messages/client/views/mailer.js +++ b/packages/rocketchat-mail-messages/client/views/mailer.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { handleError } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; Template.mailer.helpers({ fromEmail() { - return RocketChat.settings.get('From_Email'); + return settings.get('From_Email'); }, }); diff --git a/packages/rocketchat-mail-messages/package.js b/packages/rocketchat-mail-messages/package.js index d47bba2236a1..98b75ff3c855 100644 --- a/packages/rocketchat-mail-messages/package.js +++ b/packages/rocketchat-mail-messages/package.js @@ -11,6 +11,9 @@ Package.onUse(function(api) { 'kadira:flow-router', 'kadira:blaze-layout', 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:settings', + 'rocketchat:models', 'rocketchat:authorization', 'templating', ]); diff --git a/packages/rocketchat-mail-messages/server/functions/sendMail.js b/packages/rocketchat-mail-messages/server/functions/sendMail.js index 262105588683..5cfc4e201d6b 100644 --- a/packages/rocketchat-mail-messages/server/functions/sendMail.js +++ b/packages/rocketchat-mail-messages/server/functions/sendMail.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { EJSON } from 'meteor/ejson'; import { FlowRouter } from 'meteor/kadira:flow-router'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { placeholders } from 'meteor/rocketchat:utils'; import s from 'underscore.string'; import * as Mailer from 'meteor/rocketchat:mailer'; @@ -23,7 +23,7 @@ export const sendMail = function(from, subject, body, dryrun, query) { 'emails.address': from, }).forEach((user) => { const email = `${ user.name } <${ user.emails[0].address }>`; - const html = RocketChat.placeholders.replace(body, { + const html = placeholders.replace(body, { unsubscribe: Meteor.absoluteUrl(FlowRouter.path('mailer/unsubscribe/:_id/:createdAt', { _id: user._id, createdAt: user.createdAt.getTime(), @@ -45,7 +45,7 @@ export const sendMail = function(from, subject, body, dryrun, query) { return Meteor.users.find(userQuery).forEach(function(user) { const email = `${ user.name } <${ user.emails[0].address }>`; - const html = RocketChat.placeholders.replace(body, { + const html = placeholders.replace(body, { unsubscribe: Meteor.absoluteUrl(FlowRouter.path('mailer/unsubscribe/:_id/:createdAt', { _id: user._id, createdAt: user.createdAt.getTime(), diff --git a/packages/rocketchat-mail-messages/server/functions/unsubscribe.js b/packages/rocketchat-mail-messages/server/functions/unsubscribe.js index 721ff5eee0bb..d87b3e7c4645 100644 --- a/packages/rocketchat-mail-messages/server/functions/unsubscribe.js +++ b/packages/rocketchat-mail-messages/server/functions/unsubscribe.js @@ -1,8 +1,8 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; export const unsubscribe = function(_id, createdAt) { if (_id && createdAt) { - return RocketChat.models.Users.rocketMailUnsubscribe(_id, createdAt) === 1; + return Users.rocketMailUnsubscribe(_id, createdAt) === 1; } return false; }; diff --git a/packages/rocketchat-mail-messages/server/index.js b/packages/rocketchat-mail-messages/server/index.js index e547390cb72b..a05bc57cc61e 100644 --- a/packages/rocketchat-mail-messages/server/index.js +++ b/packages/rocketchat-mail-messages/server/index.js @@ -1,5 +1,4 @@ import './startup'; -import './models/Users'; import './methods/sendMail'; import './methods/unsubscribe'; import { Mailer } from './lib/Mailer'; diff --git a/packages/rocketchat-mail-messages/server/methods/sendMail.js b/packages/rocketchat-mail-messages/server/methods/sendMail.js index 8b6bdaa75d8a..4471acf37cc2 100644 --- a/packages/rocketchat-mail-messages/server/methods/sendMail.js +++ b/packages/rocketchat-mail-messages/server/methods/sendMail.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Mailer } from '../lib/Mailer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ 'Mailer.sendMail'(from, subject, body, dryrun, query) { @@ -10,7 +10,7 @@ Meteor.methods({ method: 'Mailer.sendMail', }); } - if (RocketChat.authz.hasRole(userId, 'admin') !== true) { + if (hasRole(userId, 'admin') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'Mailer.sendMail', }); diff --git a/packages/rocketchat-mail-messages/server/models/Users.js b/packages/rocketchat-mail-messages/server/models/Users.js deleted file mode 100644 index b9e4eca24bf1..000000000000 --- a/packages/rocketchat-mail-messages/server/models/Users.js +++ /dev/null @@ -1,16 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Users.rocketMailUnsubscribe = function(_id, createdAt) { - const query = { - _id, - createdAt: new Date(parseInt(createdAt)), - }; - const update = { - $set: { - 'mailer.unsubscribed': true, - }, - }; - const affectedRows = this.update(query, update); - console.log('[Mailer:Unsubscribe]', _id, createdAt, new Date(parseInt(createdAt)), affectedRows); - return affectedRows; -}; diff --git a/packages/rocketchat-mail-messages/server/startup.js b/packages/rocketchat-mail-messages/server/startup.js index f8c063d8d7b9..2f19be1aef23 100644 --- a/packages/rocketchat-mail-messages/server/startup.js +++ b/packages/rocketchat-mail-messages/server/startup.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Permissions } from 'meteor/rocketchat:models'; Meteor.startup(function() { - return RocketChat.models.Permissions.upsert('access-mailer', { + return Permissions.upsert('access-mailer', { $setOnInsert: { _id: 'access-mailer', roles: ['admin'], diff --git a/packages/rocketchat-models/server/models/Users.js b/packages/rocketchat-models/server/models/Users.js index 770c4a8ad9f5..ded5341e8b16 100644 --- a/packages/rocketchat-models/server/models/Users.js +++ b/packages/rocketchat-models/server/models/Users.js @@ -39,6 +39,21 @@ export class Users extends Base { }); } + rocketMailUnsubscribe(_id, createdAt) { + const query = { + _id, + createdAt: new Date(parseInt(createdAt)), + }; + const update = { + $set: { + 'mailer.unsubscribed': true, + }, + }; + const affectedRows = this.update(query, update); + console.log('[Mailer:Unsubscribe]', _id, createdAt, new Date(parseInt(createdAt)), affectedRows); + return affectedRows; + } + fetchKeysByUserId(userId) { const user = this.findOne({ _id: userId }, { fields: { e2e: 1 } });