From 171754ec0f941089facfac02a827a4a29b46240c Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Mon, 21 Jan 2019 17:01:40 -0200 Subject: [PATCH 001/101] 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 002/101] 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 003/101] 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 004/101] 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 005/101] 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 006/101] 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 007/101] 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 008/101] 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 009/101] 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 010/101] 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 011/101] 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 012/101] 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 013/101] 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 014/101] 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 015/101] 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 016/101] 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 017/101] 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 018/101] 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 019/101] 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 020/101] 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 021/101] 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 022/101] 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 023/101] 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 024/101] 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 025/101] 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 801ed018ffbce17f4f7f49dd5b997f4dfcc137e4 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 10:39:43 -0200 Subject: [PATCH 026/101] Move RestAPI client to rc-api package --- packages/rocketchat-api/client/index.js | 1 + .../client/lib/RestApiClient.js | 112 ++++++++++++++++++ packages/rocketchat-api/package.js | 1 + .../client/lib/RestApiClient.js | 112 +----------------- 4 files changed, 116 insertions(+), 110 deletions(-) create mode 100644 packages/rocketchat-api/client/index.js create mode 100644 packages/rocketchat-api/client/lib/RestApiClient.js diff --git a/packages/rocketchat-api/client/index.js b/packages/rocketchat-api/client/index.js new file mode 100644 index 000000000000..7e1df916437f --- /dev/null +++ b/packages/rocketchat-api/client/index.js @@ -0,0 +1 @@ +export { API } from './lib/RestApiClient'; diff --git a/packages/rocketchat-api/client/lib/RestApiClient.js b/packages/rocketchat-api/client/lib/RestApiClient.js new file mode 100644 index 000000000000..107462f2057d --- /dev/null +++ b/packages/rocketchat-api/client/lib/RestApiClient.js @@ -0,0 +1,112 @@ +export const API = { + delete(endpoint, params) { + return API._jqueryCall('DELETE', endpoint, params); + }, + + get(endpoint, params) { + return API._jqueryCall('GET', endpoint, params); + }, + + post(endpoint, params, body) { + if (!body) { + body = params; + params = {}; + } + + return API._jqueryCall('POST', endpoint, params, body); + }, + + upload(endpoint, params, formData) { + if (!formData) { + formData = params; + params = {}; + } + + return API._jqueryFormDataCall(endpoint, params, formData); + }, + + _generateQueryFromParams(params) { + let query = ''; + if (params && typeof params === 'object') { + Object.keys(params).forEach((key) => { + query += query === '' ? '?' : '&'; + + query += `${ key }=${ params[key] }`; + }); + } + + return query; + }, + + _jqueryCall(method, endpoint, params, body) { + const query = API._generateQueryFromParams(params); + + return new Promise(function _rlRestApiGet(resolve, reject) { + jQuery.ajax({ + method, + url: `${ document.baseURI }api/${ endpoint }${ query }`, + headers: { + 'Content-Type': 'application/json', + 'X-User-Id': localStorage['Meteor.userId'], + 'X-Auth-Token': localStorage['Meteor.loginToken'], + }, + data: JSON.stringify(body), + success: function _rlGetSuccess(result) { + resolve(result); + }, + error: function _rlGetFailure(xhr, status, errorThrown) { + const error = new Error(errorThrown); + error.xhr = xhr; + reject(error); + }, + }); + }); + }, + + _jqueryFormDataCall(endpoint, params, formData) { + const query = API._generateQueryFromParams(params); + + if (!(formData instanceof FormData)) { + throw new Error('The formData parameter MUST be an instance of the FormData class.'); + } + + return new Promise(function _jqueryFormDataPromise(resolve, reject) { + jQuery.ajax({ + url: `${ document.baseURI }api/${ endpoint }${ query }`, + headers: { + 'X-User-Id': localStorage['Meteor.userId'], + 'X-Auth-Token': localStorage['Meteor.loginToken'], + }, + data: formData, + processData: false, + contentType: false, + type: 'POST', + success: function _jqueryFormDataSuccess(result) { + resolve(result); + }, + error: function _jqueryFormDataError(xhr, status, errorThrown) { + reject(new Error(errorThrown)); + }, + }); + }); + }, + + v1: { + delete(endpoint, params) { + return API.delete(`v1/${ endpoint }`, params); + }, + + get(endpoint, params) { + return API.get(`v1/${ endpoint }`, params); + }, + + post(endpoint, params, body) { + return API.post(`v1/${ endpoint }`, params, body); + }, + + upload(endpoint, params, formData) { + return API.upload(`v1/${ endpoint }`, params, formData); + }, + }, +}; +RocketChat.API = API; diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index 1384ef6670d6..3844ff0909bb 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -16,5 +16,6 @@ Package.onUse(function(api) { 'rocketchat:file-upload', ]); + api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-lib/client/lib/RestApiClient.js b/packages/rocketchat-lib/client/lib/RestApiClient.js index 7226be0360d1..9c2d7a9b86e9 100644 --- a/packages/rocketchat-lib/client/lib/RestApiClient.js +++ b/packages/rocketchat-lib/client/lib/RestApiClient.js @@ -1,111 +1,3 @@ -RocketChat.API = { - delete(endpoint, params) { - return RocketChat.API._jqueryCall('DELETE', endpoint, params); - }, +// import { API } from 'meteor/rocketchat:api'; - get(endpoint, params) { - return RocketChat.API._jqueryCall('GET', endpoint, params); - }, - - post(endpoint, params, body) { - if (!body) { - body = params; - params = {}; - } - - return RocketChat.API._jqueryCall('POST', endpoint, params, body); - }, - - upload(endpoint, params, formData) { - if (!formData) { - formData = params; - params = {}; - } - - return RocketChat.API._jqueryFormDataCall(endpoint, params, formData); - }, - - _generateQueryFromParams(params) { - let query = ''; - if (params && typeof params === 'object') { - Object.keys(params).forEach((key) => { - query += query === '' ? '?' : '&'; - - query += `${ key }=${ params[key] }`; - }); - } - - return query; - }, - - _jqueryCall(method, endpoint, params, body) { - const query = RocketChat.API._generateQueryFromParams(params); - - return new Promise(function _rlRestApiGet(resolve, reject) { - jQuery.ajax({ - method, - url: `${ document.baseURI }api/${ endpoint }${ query }`, - headers: { - 'Content-Type': 'application/json', - 'X-User-Id': localStorage['Meteor.userId'], - 'X-Auth-Token': localStorage['Meteor.loginToken'], - }, - data: JSON.stringify(body), - success: function _rlGetSuccess(result) { - resolve(result); - }, - error: function _rlGetFailure(xhr, status, errorThrown) { - const error = new Error(errorThrown); - error.xhr = xhr; - reject(error); - }, - }); - }); - }, - - _jqueryFormDataCall(endpoint, params, formData) { - const query = RocketChat.API._generateQueryFromParams(params); - - if (!(formData instanceof FormData)) { - throw new Error('The formData parameter MUST be an instance of the FormData class.'); - } - - return new Promise(function _jqueryFormDataPromise(resolve, reject) { - jQuery.ajax({ - url: `${ document.baseURI }api/${ endpoint }${ query }`, - headers: { - 'X-User-Id': localStorage['Meteor.userId'], - 'X-Auth-Token': localStorage['Meteor.loginToken'], - }, - data: formData, - processData: false, - contentType: false, - type: 'POST', - success: function _jqueryFormDataSuccess(result) { - resolve(result); - }, - error: function _jqueryFormDataError(xhr, status, errorThrown) { - reject(new Error(errorThrown)); - }, - }); - }); - }, - - v1: { - delete(endpoint, params) { - return RocketChat.API.delete(`v1/${ endpoint }`, params); - }, - - get(endpoint, params) { - return RocketChat.API.get(`v1/${ endpoint }`, params); - }, - - post(endpoint, params, body) { - return RocketChat.API.post(`v1/${ endpoint }`, params, body); - }, - - upload(endpoint, params, formData) { - return RocketChat.API.upload(`v1/${ endpoint }`, params, formData); - }, - }, -}; +// RocketChat.API = API; From 1238c2c8835195cb8675871c47ffa390c7799519 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 10:40:31 -0200 Subject: [PATCH 027/101] Remove dependency of RC namespace in rc-api/helpers and api.js --- packages/rocketchat-api/package.js | 4 ++ packages/rocketchat-api/server/api.js | 57 +++++++++++-------- .../rocketchat-api/server/default/info.js | 16 +++--- .../helpers/composeRoomWithLastMessage.js | 7 ++- .../server/helpers/deprecationWarning.js | 4 +- .../server/helpers/getLoggedInUser.js | 7 ++- .../server/helpers/getPaginationItems.js | 11 ++-- .../server/helpers/getUserFromParams.js | 11 ++-- .../server/helpers/getUserInfo.js | 10 ++-- .../server/helpers/insertUserObject.js | 7 ++- .../server/helpers/isUserFromParams.js | 4 +- .../server/helpers/parseJsonQuery.js | 29 +++++----- .../server/helpers/requestParams.js | 4 +- packages/rocketchat-api/server/settings.js | 4 +- 14 files changed, 98 insertions(+), 77 deletions(-) diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index 3844ff0909bb..969cca9a542c 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -12,6 +12,10 @@ Package.onUse(function(api) { 'rate-limit', 'rocketchat:lib', 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:utils', + 'rocketchat:metrics', + 'rocketchat:authorization', 'rocketchat:integrations', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-api/server/api.js b/packages/rocketchat-api/server/api.js index e32407d689c3..a4ee71d3b9a6 100644 --- a/packages/rocketchat-api/server/api.js +++ b/packages/rocketchat-api/server/api.js @@ -5,17 +5,22 @@ import { Accounts } from 'meteor/accounts-base'; import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; import { Logger } from 'meteor/rocketchat:logger'; +import { settings } from 'meteor/rocketchat:settings'; +import { metrics } from 'meteor/rocketchat:metrics'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import { RateLimiter } from 'meteor/rate-limit'; import _ from 'underscore'; const logger = new Logger('API', {}); const rateLimiterDictionary = {}; const defaultRateLimiterOptions = { - numRequestsAllowed: RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default'), - intervalTimeInMS: RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'), + numRequestsAllowed: settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default'), + intervalTimeInMS: settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'), }; -class API extends Restivus { +export let API = {}; + +class APIClass extends Restivus { constructor(properties) { super(properties); this.authMethods = []; @@ -48,15 +53,15 @@ class API extends Restivus { } hasHelperMethods() { - return RocketChat.API.helperMethods.size !== 0; + return API.helperMethods.size !== 0; } getHelperMethods() { - return RocketChat.API.helperMethods; + return API.helperMethods; } getHelperMethod(name) { - return RocketChat.API.helperMethods.get(name); + return API.helperMethods.get(name); } addAuthMethod(method) { @@ -182,7 +187,7 @@ class API extends Restivus { // Add a try/catch for each endpoint const originalAction = endpoints[method].action; endpoints[method].action = function _internalRouteActionHandler() { - const rocketchatRestApiEnd = RocketChat.metrics.rocketchatRestApi.startTimer({ + const rocketchatRestApiEnd = metrics.rocketchatRestApi.startTimer({ method, version, user_agent: this.request.headers['user-agent'], @@ -198,8 +203,8 @@ class API extends Restivus { let result; try { const shouldVerifyRateLimit = rateLimiterDictionary.hasOwnProperty(objectForRateLimitMatch.route) - && (!this.userId || !RocketChat.authz.hasPermission(this.userId, 'api-bypass-rate-limit')) - && ((process.env.NODE_ENV === 'development' && RocketChat.settings.get('API_Enable_Rate_Limiter_Dev') === true) || process.env.NODE_ENV !== 'development'); + && (!this.userId || !hasPermission(this.userId, 'api-bypass-rate-limit')) + && ((process.env.NODE_ENV === 'development' && settings.get('API_Enable_Rate_Limiter_Dev') === true) || process.env.NODE_ENV !== 'development'); if (shouldVerifyRateLimit) { rateLimiterDictionary[objectForRateLimitMatch.route].rateLimiter.increment(objectForRateLimitMatch); const attemptResult = rateLimiterDictionary[objectForRateLimitMatch.route].rateLimiter.check(objectForRateLimitMatch); @@ -217,9 +222,9 @@ class API extends Restivus { result = originalAction.apply(this); } catch (e) { logger.debug(`${ method } ${ route } threw an error:`, e.stack); - result = RocketChat.API.v1.failure(e.message, e.error); + result = API.v1.failure(e.message, e.error); } - result = result || RocketChat.API.v1.success(); + result = result || API.v1.success(); rocketchatRestApiEnd({ status: result.statusCode, @@ -413,8 +418,8 @@ const getUserAuth = function _getUserAuth(...args) { this.bodyParams = JSON.parse(this.bodyParams.payload); } - for (let i = 0; i < RocketChat.API.v1.authMethods.length; i++) { - const method = RocketChat.API.v1.authMethods[i]; + for (let i = 0; i < API.v1.authMethods.length; i++) { + const method = API.v1.authMethods[i]; if (typeof method === 'function') { const result = method.apply(this, args); @@ -437,17 +442,19 @@ const getUserAuth = function _getUserAuth(...args) { }; }; -RocketChat.API = { +API = { helperMethods: new Map(), getUserAuth, - ApiClass: API, + ApiClass: APIClass, }; +RocketChat.API = API; + const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { if (this.request.method === 'OPTIONS' && this.request.headers['access-control-request-method']) { - if (RocketChat.settings.get('API_Enable_CORS') === true) { + if (settings.get('API_Enable_CORS') === true) { this.response.writeHead(200, { - 'Access-Control-Allow-Origin': RocketChat.settings.get('API_CORS_Origin'), + 'Access-Control-Allow-Origin': settings.get('API_CORS_Origin'), 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, HEAD, PATCH', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-User-Id, X-Auth-Token, x-visitor-token', }); @@ -462,8 +469,8 @@ const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { }; const createApi = function _createApi(enableCors) { - if (!RocketChat.API.v1 || RocketChat.API.v1._config.enableCors !== enableCors) { - RocketChat.API.v1 = new API({ + if (!API.v1 || API.v1._config.enableCors !== enableCors) { + API.v1 = new APIClass({ version: 'v1', useDefaultAuth: true, prettyJson: process.env.NODE_ENV === 'development', @@ -473,8 +480,8 @@ const createApi = function _createApi(enableCors) { }); } - if (!RocketChat.API.default || RocketChat.API.default._config.enableCors !== enableCors) { - RocketChat.API.default = new API({ + if (!API.default || API.default._config.enableCors !== enableCors) { + API.default = new APIClass({ useDefaultAuth: true, prettyJson: process.env.NODE_ENV === 'development', enableCors, @@ -485,19 +492,19 @@ const createApi = function _createApi(enableCors) { }; // register the API to be re-created once the CORS-setting changes. -RocketChat.settings.get('API_Enable_CORS', (key, value) => { +settings.get('API_Enable_CORS', (key, value) => { createApi(value); }); -RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Time_Default', (key, value) => { +settings.get('API_Enable_Rate_Limiter_Limit_Time_Default', (key, value) => { defaultRateLimiterOptions.intervalTimeInMS = value; createApi(value); }); -RocketChat.settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default', (key, value) => { +settings.get('API_Enable_Rate_Limiter_Limit_Calls_Default', (key, value) => { defaultRateLimiterOptions.numRequestsAllowed = value; createApi(value); }); // also create the API immediately -createApi(!!RocketChat.settings.get('API_Enable_CORS')); +createApi(!!settings.get('API_Enable_CORS')); diff --git a/packages/rocketchat-api/server/default/info.js b/packages/rocketchat-api/server/default/info.js index 97b372dd42ad..f4bbcad21ec8 100644 --- a/packages/rocketchat-api/server/default/info.js +++ b/packages/rocketchat-api/server/default/info.js @@ -1,17 +1,19 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { Info } from 'meteor/rocketchat:utils'; +import { API } from '../api'; -RocketChat.API.default.addRoute('info', { authRequired: false }, { +API.default.addRoute('info', { authRequired: false }, { get() { const user = this.getLoggedInUser(); - if (user && RocketChat.authz.hasRole(user._id, 'admin')) { - return RocketChat.API.v1.success({ - info: RocketChat.Info, + if (user && hasRole(user._id, 'admin')) { + return API.v1.success({ + info: Info, }); } - return RocketChat.API.v1.success({ - version: RocketChat.Info.version, + return API.v1.success({ + version: Info.version, }); }, }); diff --git a/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js b/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js index f9a8e3a702c8..4c833d898709 100644 --- a/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js +++ b/packages/rocketchat-api/server/helpers/composeRoomWithLastMessage.js @@ -1,8 +1,9 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('composeRoomWithLastMessage', function _composeRoomWithLastMessage(room, userId) { +API.helperMethods.set('composeRoomWithLastMessage', function _composeRoomWithLastMessage(room, userId) { if (room.lastMessage) { - room.lastMessage = RocketChat.composeMessageObjectWithUser(room.lastMessage, userId); + room.lastMessage = composeMessageObjectWithUser(room.lastMessage, userId); } return room; }); diff --git a/packages/rocketchat-api/server/helpers/deprecationWarning.js b/packages/rocketchat-api/server/helpers/deprecationWarning.js index ad2cb11a5131..06dc47c3f096 100644 --- a/packages/rocketchat-api/server/helpers/deprecationWarning.js +++ b/packages/rocketchat-api/server/helpers/deprecationWarning.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { +API.helperMethods.set('deprecationWarning', function _deprecationWarning({ endpoint, versionWillBeRemove, response }) { const warningMessage = `The endpoint "${ endpoint }" is deprecated and will be removed after version ${ versionWillBeRemove }`; console.warn(warningMessage); if (process.env.NODE_ENV === 'development') { diff --git a/packages/rocketchat-api/server/helpers/getLoggedInUser.js b/packages/rocketchat-api/server/helpers/getLoggedInUser.js index 1ff50826b928..9406ff576f1f 100644 --- a/packages/rocketchat-api/server/helpers/getLoggedInUser.js +++ b/packages/rocketchat-api/server/helpers/getLoggedInUser.js @@ -1,11 +1,12 @@ import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('getLoggedInUser', function _getLoggedInUser() { +API.helperMethods.set('getLoggedInUser', function _getLoggedInUser() { let user; if (this.request.headers['x-auth-token'] && this.request.headers['x-user-id']) { - user = RocketChat.models.Users.findOne({ + user = Users.findOne({ _id: this.request.headers['x-user-id'], 'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(this.request.headers['x-auth-token']), }); diff --git a/packages/rocketchat-api/server/helpers/getPaginationItems.js b/packages/rocketchat-api/server/helpers/getPaginationItems.js index f7d3cff75d1e..0060155d0f0c 100644 --- a/packages/rocketchat-api/server/helpers/getPaginationItems.js +++ b/packages/rocketchat-api/server/helpers/getPaginationItems.js @@ -1,11 +1,12 @@ // If the count query param is higher than the "API_Upper_Count_Limit" setting, then we limit that // If the count query param isn't defined, then we set it to the "API_Default_Count" setting // If the count is zero, then that means unlimited and is only allowed if the setting "API_Allow_Infinite_Count" is true -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('getPaginationItems', function _getPaginationItems() { - const hardUpperLimit = RocketChat.settings.get('API_Upper_Count_Limit') <= 0 ? 100 : RocketChat.settings.get('API_Upper_Count_Limit'); - const defaultCount = RocketChat.settings.get('API_Default_Count') <= 0 ? 50 : RocketChat.settings.get('API_Default_Count'); +API.helperMethods.set('getPaginationItems', function _getPaginationItems() { + const hardUpperLimit = settings.get('API_Upper_Count_Limit') <= 0 ? 100 : settings.get('API_Upper_Count_Limit'); + const defaultCount = settings.get('API_Default_Count') <= 0 ? 50 : settings.get('API_Default_Count'); const offset = this.queryParams.offset ? parseInt(this.queryParams.offset) : 0; let count = defaultCount; @@ -20,7 +21,7 @@ RocketChat.API.helperMethods.set('getPaginationItems', function _getPaginationIt count = hardUpperLimit; } - if (count === 0 && !RocketChat.settings.get('API_Allow_Infinite_Count')) { + if (count === 0 && !settings.get('API_Allow_Infinite_Count')) { count = defaultCount; } diff --git a/packages/rocketchat-api/server/helpers/getUserFromParams.js b/packages/rocketchat-api/server/helpers/getUserFromParams.js index 54b884de6059..e9f49ca7cc61 100644 --- a/packages/rocketchat-api/server/helpers/getUserFromParams.js +++ b/packages/rocketchat-api/server/helpers/getUserFromParams.js @@ -1,18 +1,19 @@ // Convenience method, almost need to turn it into a middleware of sorts import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('getUserFromParams', function _getUserFromParams() { +API.helperMethods.set('getUserFromParams', function _getUserFromParams() { const doesntExist = { _doesntExist: true }; let user; const params = this.requestParams(); if (params.userId && params.userId.trim()) { - user = RocketChat.models.Users.findOneById(params.userId) || doesntExist; + user = Users.findOneById(params.userId) || doesntExist; } else if (params.username && params.username.trim()) { - user = RocketChat.models.Users.findOneByUsername(params.username) || doesntExist; + user = Users.findOneByUsername(params.username) || doesntExist; } else if (params.user && params.user.trim()) { - user = RocketChat.models.Users.findOneByUsername(params.user) || doesntExist; + user = Users.findOneByUsername(params.user) || doesntExist; } else { throw new Meteor.Error('error-user-param-not-provided', 'The required "userId" or "username" param was not provided'); } diff --git a/packages/rocketchat-api/server/helpers/getUserInfo.js b/packages/rocketchat-api/server/helpers/getUserInfo.js index c573a336ddd1..f7a76b35c14e 100644 --- a/packages/rocketchat-api/server/helpers/getUserInfo.js +++ b/packages/rocketchat-api/server/helpers/getUserInfo.js @@ -1,4 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { API } from '../api'; const getInfoFromUserObject = (user) => { const { @@ -32,7 +34,7 @@ const getInfoFromUserObject = (user) => { }; -RocketChat.API.helperMethods.set('getUserInfo', function _getUserInfo(user) { +API.helperMethods.set('getUserInfo', function _getUserInfo(user) { const me = getInfoFromUserObject(user); const isVerifiedEmail = () => { if (me && me.emails && Array.isArray(me.emails)) { @@ -42,11 +44,11 @@ RocketChat.API.helperMethods.set('getUserInfo', function _getUserInfo(user) { }; const getUserPreferences = () => { const defaultUserSettingPrefix = 'Accounts_Default_User_Preferences_'; - const allDefaultUserSettings = RocketChat.settings.get(new RegExp(`^${ defaultUserSettingPrefix }.*$`)); + const allDefaultUserSettings = settings.get(new RegExp(`^${ defaultUserSettingPrefix }.*$`)); return allDefaultUserSettings.reduce((accumulator, setting) => { const settingWithoutPrefix = setting.key.replace(defaultUserSettingPrefix, ' ').trim(); - accumulator[settingWithoutPrefix] = RocketChat.getUserPreference(user, settingWithoutPrefix); + accumulator[settingWithoutPrefix] = getUserPreference(user, settingWithoutPrefix); return accumulator; }, {}); }; diff --git a/packages/rocketchat-api/server/helpers/insertUserObject.js b/packages/rocketchat-api/server/helpers/insertUserObject.js index dfa6322099b9..9883f8f830fa 100644 --- a/packages/rocketchat-api/server/helpers/insertUserObject.js +++ b/packages/rocketchat-api/server/helpers/insertUserObject.js @@ -1,7 +1,8 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('insertUserObject', function _addUserToObject({ object, userId }) { - const user = RocketChat.models.Users.findOneById(userId); +API.helperMethods.set('insertUserObject', function _addUserToObject({ object, userId }) { + const user = Users.findOneById(userId); object.user = { }; if (user) { object.user = { diff --git a/packages/rocketchat-api/server/helpers/isUserFromParams.js b/packages/rocketchat-api/server/helpers/isUserFromParams.js index 79f3b90f3aef..a96779c2eedc 100644 --- a/packages/rocketchat-api/server/helpers/isUserFromParams.js +++ b/packages/rocketchat-api/server/helpers/isUserFromParams.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('isUserFromParams', function _isUserFromParams() { +API.helperMethods.set('isUserFromParams', function _isUserFromParams() { const params = this.requestParams(); return (!params.userId && !params.username && !params.user) || diff --git a/packages/rocketchat-api/server/helpers/parseJsonQuery.js b/packages/rocketchat-api/server/helpers/parseJsonQuery.js index 6b9caf541987..60bf964c3e22 100644 --- a/packages/rocketchat-api/server/helpers/parseJsonQuery.js +++ b/packages/rocketchat-api/server/helpers/parseJsonQuery.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; import { EJSON } from 'meteor/ejson'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { +API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { let sort; if (this.queryParams.sort) { try { @@ -25,26 +26,26 @@ RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { // Verify the user's selected fields only contains ones which their role allows if (typeof fields === 'object') { - let nonSelectableFields = Object.keys(RocketChat.API.v1.defaultFieldsToExclude); + let nonSelectableFields = Object.keys(API.v1.defaultFieldsToExclude); if (this.request.route.includes('/v1/users.')) { - const getFields = () => Object.keys(RocketChat.authz.hasPermission(this.userId, 'view-full-other-user-info') ? RocketChat.API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser : RocketChat.API.v1.limitedUserFieldsToExclude); + const getFields = () => Object.keys(hasPermission(this.userId, 'view-full-other-user-info') ? API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser : API.v1.limitedUserFieldsToExclude); nonSelectableFields = nonSelectableFields.concat(getFields()); } Object.keys(fields).forEach((k) => { - if (nonSelectableFields.includes(k) || nonSelectableFields.includes(k.split(RocketChat.API.v1.fieldSeparator)[0])) { + if (nonSelectableFields.includes(k) || nonSelectableFields.includes(k.split(API.v1.fieldSeparator)[0])) { delete fields[k]; } }); } // Limit the fields by default - fields = Object.assign({}, fields, RocketChat.API.v1.defaultFieldsToExclude); + fields = Object.assign({}, fields, API.v1.defaultFieldsToExclude); if (this.request.route.includes('/v1/users.')) { - if (RocketChat.authz.hasPermission(this.userId, 'view-full-other-user-info')) { - fields = Object.assign(fields, RocketChat.API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser); + if (hasPermission(this.userId, 'view-full-other-user-info')) { + fields = Object.assign(fields, API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser); } else { - fields = Object.assign(fields, RocketChat.API.v1.limitedUserFieldsToExclude); + fields = Object.assign(fields, API.v1.limitedUserFieldsToExclude); } } @@ -60,17 +61,17 @@ RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() { // Verify the user has permission to query the fields they are if (typeof query === 'object') { - let nonQueryableFields = Object.keys(RocketChat.API.v1.defaultFieldsToExclude); + let nonQueryableFields = Object.keys(API.v1.defaultFieldsToExclude); if (this.request.route.includes('/v1/users.')) { - if (RocketChat.authz.hasPermission(this.userId, 'view-full-other-user-info')) { - nonQueryableFields = nonQueryableFields.concat(Object.keys(RocketChat.API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser)); + if (hasPermission(this.userId, 'view-full-other-user-info')) { + nonQueryableFields = nonQueryableFields.concat(Object.keys(API.v1.limitedUserFieldsToExcludeIfIsPrivilegedUser)); } else { - nonQueryableFields = nonQueryableFields.concat(Object.keys(RocketChat.API.v1.limitedUserFieldsToExclude)); + nonQueryableFields = nonQueryableFields.concat(Object.keys(API.v1.limitedUserFieldsToExclude)); } } Object.keys(query).forEach((k) => { - if (nonQueryableFields.includes(k) || nonQueryableFields.includes(k.split(RocketChat.API.v1.fieldSeparator)[0])) { + if (nonQueryableFields.includes(k) || nonQueryableFields.includes(k.split(API.v1.fieldSeparator)[0])) { delete query[k]; } }); diff --git a/packages/rocketchat-api/server/helpers/requestParams.js b/packages/rocketchat-api/server/helpers/requestParams.js index fe70278dd463..2883c94a727e 100644 --- a/packages/rocketchat-api/server/helpers/requestParams.js +++ b/packages/rocketchat-api/server/helpers/requestParams.js @@ -1,5 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.helperMethods.set('requestParams', function _requestParams() { +API.helperMethods.set('requestParams', function _requestParams() { return ['POST', 'PUT'].includes(this.request.method) ? this.bodyParams : this.queryParams; }); diff --git a/packages/rocketchat-api/server/settings.js b/packages/rocketchat-api/server/settings.js index 6e17f1c91e05..5b2d3badb9e0 100644 --- a/packages/rocketchat-api/server/settings.js +++ b/packages/rocketchat-api/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.section('REST API', function() { this.add('API_Upper_Count_Limit', 100, { type: 'int', public: false }); this.add('API_Default_Count', 50, { type: 'int', public: false }); From dc8f61511f43311ae3ca90cccb387fc3ac084cb8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 12:58:51 -0200 Subject: [PATCH 028/101] Remove dependency of RC namespace on half of api files --- packages/rocketchat-api/package.js | 1 + packages/rocketchat-api/server/v1/assets.js | 15 +- packages/rocketchat-api/server/v1/channels.js | 293 +++++++++--------- packages/rocketchat-api/server/v1/chat.js | 129 ++++---- packages/rocketchat-api/server/v1/commands.js | 68 ++-- packages/rocketchat-api/server/v1/e2e.js | 28 +- .../rocketchat-api/server/v1/emoji-custom.js | 19 +- packages/rocketchat-api/server/v1/groups.js | 267 ++++++++-------- packages/rocketchat-api/server/v1/im.js | 103 +++--- packages/rocketchat-api/server/v1/import.js | 22 +- .../rocketchat-api/server/v1/integrations.js | 56 ++-- 11 files changed, 511 insertions(+), 490 deletions(-) diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index 969cca9a542c..a6664d10b8f1 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -13,6 +13,7 @@ Package.onUse(function(api) { 'rocketchat:lib', 'rocketchat:models', 'rocketchat:settings', + 'rocketchat:assets', 'rocketchat:utils', 'rocketchat:metrics', 'rocketchat:authorization', diff --git a/packages/rocketchat-api/server/v1/assets.js b/packages/rocketchat-api/server/v1/assets.js index 774ee3c8d58f..c69b619b27fe 100644 --- a/packages/rocketchat-api/server/v1/assets.js +++ b/packages/rocketchat-api/server/v1/assets.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; +import { RocketChatAssets } from 'meteor/rocketchat:assets'; import Busboy from 'busboy'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('assets.setAsset', { authRequired: true }, { +API.v1.addRoute('assets.setAsset', { authRequired: true }, { post() { const busboy = new Busboy({ headers: this.request.headers }); const fields = {}; @@ -11,7 +12,7 @@ RocketChat.API.v1.addRoute('assets.setAsset', { authRequired: true }, { Meteor.wrapAsync((callback) => { busboy.on('field', (fieldname, value) => fields[fieldname] = value); busboy.on('file', Meteor.bindEnvironment((fieldname, file, filename, encoding, mimetype) => { - const isValidAsset = Object.keys(RocketChat.Assets.assets).includes(fieldname); + const isValidAsset = Object.keys(RocketChatAssets.assets).includes(fieldname); if (!isValidAsset) { callback(new Meteor.Error('error-invalid-asset', 'Invalid asset')); } @@ -35,14 +36,14 @@ RocketChat.API.v1.addRoute('assets.setAsset', { authRequired: true }, { if (fields.refreshAllClients) { Meteor.runAsUser(this.userId, () => Meteor.call('refreshClients')); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('assets.unsetAsset', { authRequired: true }, { +API.v1.addRoute('assets.unsetAsset', { authRequired: true }, { post() { const { assetName, refreshAllClients } = this.bodyParams; - const isValidAsset = Object.keys(RocketChat.Assets.assets).includes(assetName); + const isValidAsset = Object.keys(RocketChatAssets.assets).includes(assetName); if (!isValidAsset) { throw new Meteor.Error('error-invalid-asset', 'Invalid asset'); } @@ -50,6 +51,6 @@ RocketChat.API.v1.addRoute('assets.unsetAsset', { authRequired: true }, { if (refreshAllClients) { Meteor.runAsUser(this.userId, () => Meteor.call('refreshClients')); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/channels.js b/packages/rocketchat-api/server/v1/channels.js index 6332e0ef840e..4fc61f4c6780 100644 --- a/packages/rocketchat-api/server/v1/channels.js +++ b/packages/rocketchat-api/server/v1/channels.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions, Messages, Uploads, Integrations, Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; import _ from 'underscore'; // Returns the channel IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property @@ -8,13 +11,13 @@ function findChannelByIdOrName({ params, checkedArchived = true, userId }) { throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" or "roomName" is required'); } - const fields = { ...RocketChat.API.v1.defaultFieldsToExclude }; + const fields = { ...API.v1.defaultFieldsToExclude }; let room; if (params.roomId) { - room = RocketChat.models.Rooms.findOneById(params.roomId, { fields }); + room = Rooms.findOneById(params.roomId, { fields }); } else if (params.roomName) { - room = RocketChat.models.Rooms.findOneByName(params.roomName, { fields }); + room = Rooms.findOneByName(params.roomName, { fields }); } if (!room || room.t !== 'c') { @@ -25,13 +28,13 @@ function findChannelByIdOrName({ params, checkedArchived = true, userId }) { throw new Meteor.Error('error-room-archived', `The channel, ${ room.name }, is archived`); } if (userId && room.lastMessage) { - room.lastMessage = RocketChat.composeMessageObjectWithUser(room.lastMessage, userId); + room.lastMessage = composeMessageObjectWithUser(room.lastMessage, userId); } return room; } -RocketChat.API.v1.addRoute('channels.addAll', { authRequired: true }, { +API.v1.addRoute('channels.addAll', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -39,13 +42,13 @@ RocketChat.API.v1.addRoute('channels.addAll', { authRequired: true }, { Meteor.call('addAllUserToRoom', findResult._id, this.bodyParams.activeUsersOnly); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.addModerator', { authRequired: true }, { +API.v1.addRoute('channels.addModerator', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -55,11 +58,11 @@ RocketChat.API.v1.addRoute('channels.addModerator', { authRequired: true }, { Meteor.call('addRoomModerator', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.addOwner', { authRequired: true }, { +API.v1.addRoute('channels.addOwner', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -69,11 +72,11 @@ RocketChat.API.v1.addRoute('channels.addOwner', { authRequired: true }, { Meteor.call('addRoomOwner', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.archive', { authRequired: true }, { +API.v1.addRoute('channels.archive', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -81,35 +84,35 @@ RocketChat.API.v1.addRoute('channels.archive', { authRequired: true }, { Meteor.call('archiveRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.close', { authRequired: true }, { +API.v1.addRoute('channels.close', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); + const sub = Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); if (!sub) { - return RocketChat.API.v1.failure(`The user/callee is not in the channel "${ findResult.name }.`); + return API.v1.failure(`The user/callee is not in the channel "${ findResult.name }.`); } if (!sub.open) { - return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is already closed to the sender`); + return API.v1.failure(`The channel, ${ findResult.name }, is already closed to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('hideRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { +API.v1.addRoute('channels.counters', { authRequired: true }, { get() { - const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration'); + const access = hasPermission(this.userId, 'view-room-administration'); const { userId } = this.requestParams(); let user = this.userId; let unreads = null; @@ -122,7 +125,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { if (userId) { if (!access) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } user = userId; } @@ -130,11 +133,11 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { params: this.requestParams(), returnUsernames: true, }); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user); const lm = room.lm ? room.lm : room._updatedAt; if (typeof subscription !== 'undefined' && subscription.open) { - unreads = RocketChat.models.Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, subscription.ls, lm); + unreads = Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, subscription.ls, lm); unreadsFrom = subscription.ls || subscription.ts; userMentions = subscription.userMentions; joined = true; @@ -146,7 +149,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { members = room.usersCount; } - return RocketChat.API.v1.success({ + return API.v1.success({ joined, members, unreads, @@ -161,7 +164,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, { // Channel -> create function createChannelValidator(params) { - if (!RocketChat.authz.hasPermission(params.user.value, 'create-c')) { + if (!hasPermission(params.user.value, 'create-c')) { throw new Error('unauthorized'); } @@ -187,20 +190,20 @@ function createChannel(userId, params) { }; } -RocketChat.API.channels = {}; -RocketChat.API.channels.create = { +API.channels = {}; +API.channels.create = { validate: createChannelValidator, execute: createChannel, }; -RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, { +API.v1.addRoute('channels.create', { authRequired: true }, { post() { const { userId, bodyParams } = this; let error; try { - RocketChat.API.channels.create.validate({ + API.channels.create.validate({ user: { value: userId, }, @@ -215,9 +218,9 @@ RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, { }); } catch (e) { if (e.message === 'unauthorized') { - error = RocketChat.API.v1.unauthorized(); + error = API.v1.unauthorized(); } else { - error = RocketChat.API.v1.failure(e.message); + error = API.v1.failure(e.message); } } @@ -225,11 +228,11 @@ RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, { return error; } - return RocketChat.API.v1.success(RocketChat.API.channels.create.execute(userId, bodyParams)); + return API.v1.success(API.channels.create.execute(userId, bodyParams)); }, }); -RocketChat.API.v1.addRoute('channels.delete', { authRequired: true }, { +API.v1.addRoute('channels.delete', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); @@ -237,11 +240,11 @@ RocketChat.API.v1.addRoute('channels.delete', { authRequired: true }, { Meteor.call('eraseRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, { +API.v1.addRoute('channels.files', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); const addUserObjectToEveryObject = (file) => { @@ -260,27 +263,27 @@ RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult._id }); - const files = RocketChat.models.Uploads.find(ourQuery, { + const files = Uploads.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ files: files.map(addUserObjectToEveryObject), count: files.length, offset, - total: RocketChat.models.Uploads.find(ourQuery).count(), + total: Uploads.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, { +API.v1.addRoute('channels.getIntegrations', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); @@ -305,23 +308,23 @@ RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, { ourQuery = Object.assign({}, query, ourQuery); - const integrations = RocketChat.models.Integrations.find(ourQuery, { + const integrations = Integrations.find(ourQuery, { sort: sort ? sort : { _createdAt: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ integrations, count: integrations.length, offset, - total: RocketChat.models.Integrations.find(ourQuery).count(), + total: Integrations.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, { +API.v1.addRoute('channels.history', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); @@ -357,16 +360,16 @@ RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, { }); if (!result) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('channels.info', { authRequired: true }, { +API.v1.addRoute('channels.info', { authRequired: true }, { get() { - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false, @@ -376,7 +379,7 @@ RocketChat.API.v1.addRoute('channels.info', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.invite', { authRequired: true }, { +API.v1.addRoute('channels.invite', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -386,13 +389,13 @@ RocketChat.API.v1.addRoute('channels.invite', { authRequired: true }, { Meteor.call('addUserToRoom', { rid: findResult._id, username: user.username }); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.join', { authRequired: true }, { +API.v1.addRoute('channels.join', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -400,13 +403,13 @@ RocketChat.API.v1.addRoute('channels.join', { authRequired: true }, { Meteor.call('joinRoom', findResult._id, this.bodyParams.joinCode); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.kick', { authRequired: true }, { +API.v1.addRoute('channels.kick', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -416,13 +419,13 @@ RocketChat.API.v1.addRoute('channels.kick', { authRequired: true }, { Meteor.call('removeUserFromRoom', { rid: findResult._id, username: user.username }); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.leave', { authRequired: true }, { +API.v1.addRoute('channels.leave', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -430,31 +433,31 @@ RocketChat.API.v1.addRoute('channels.leave', { authRequired: true }, { Meteor.call('leaveRoom', findResult._id); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, { +API.v1.addRoute('channels.list', { authRequired: true }, { get: { // This is defined as such only to provide an example of how the routes can be defined :X action() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - const hasPermissionToSeeAllPublicChannels = RocketChat.authz.hasPermission(this.userId, 'view-c-room'); + const hasPermissionToSeeAllPublicChannels = hasPermission(this.userId, 'view-c-room'); const ourQuery = { ...query, t: 'c' }; if (!hasPermissionToSeeAllPublicChannels) { - if (!RocketChat.authz.hasPermission(this.userId, 'view-joined-room')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-joined-room')) { + return API.v1.unauthorized(); } - const roomIds = RocketChat.models.Subscriptions.findByUserIdAndType(this.userId, 'c', { fields: { rid: 1 } }).fetch().map((s) => s.rid); + const roomIds = Subscriptions.findByUserIdAndType(this.userId, 'c', { fields: { rid: 1 } }).fetch().map((s) => s.rid); ourQuery._id = { $in: roomIds }; } - const cursor = RocketChat.models.Rooms.find(ourQuery, { + const cursor = Rooms.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, @@ -465,7 +468,7 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, { const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ channels: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), count: rooms.length, offset, @@ -475,13 +478,13 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, { +API.v1.addRoute('channels.list.joined', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields } = this.parseJsonQuery(); // TODO: CACHE: Add Breacking notice since we removed the query param - const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('c', this.userId, { + const cursor = Rooms.findBySubscriptionTypeAndUserId('c', this.userId, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, @@ -491,7 +494,7 @@ RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, { const totalCount = cursor.count(); const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ channels: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -500,21 +503,21 @@ RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, { +API.v1.addRoute('channels.members', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false, }); - if (findResult.broadcast && !RocketChat.authz.hasPermission(this.userId, 'view-broadcast-member-list')) { - return RocketChat.API.v1.unauthorized(); + if (findResult.broadcast && !hasPermission(this.userId, 'view-broadcast-member-list')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort = {} } = this.parseJsonQuery(); - const subscriptions = RocketChat.models.Subscriptions.findByRoomId(findResult._id, { + const subscriptions = Subscriptions.findByRoomId(findResult._id, { fields: { 'u._id': 1 }, sort: { 'u.username': sort.username != null ? sort.username : 1 }, skip: offset, @@ -525,12 +528,12 @@ RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, { const members = subscriptions.fetch().map((s) => s.u && s.u._id); - const users = RocketChat.models.Users.find({ _id: { $in: members } }, { + const users = Users.find({ _id: { $in: members } }, { fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 }, sort: { username: sort.username != null ? sort.username : 1 }, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ members: users, count: users.length, offset, @@ -539,7 +542,7 @@ RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { +API.v1.addRoute('channels.messages', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams(), @@ -551,14 +554,14 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult._id }); // Special check for the permissions - if (RocketChat.authz.hasPermission(this.userId, 'view-joined-room') && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId, { fields: { _id: 1 } })) { - return RocketChat.API.v1.unauthorized(); + if (hasPermission(this.userId, 'view-joined-room') && !Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId, { fields: { _id: 1 } })) { + return API.v1.unauthorized(); } - if (!RocketChat.authz.hasPermission(this.userId, 'view-c-room')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-c-room')) { + return API.v1.unauthorized(); } - const cursor = RocketChat.models.Messages.find(ourQuery, { + const cursor = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, @@ -568,8 +571,8 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { const total = cursor.count(); const messages = cursor.fetch(); - return RocketChat.API.v1.success({ - messages: messages.map((record) => RocketChat.composeMessageObjectWithUser(record, this.userId)), + return API.v1.success({ + messages: messages.map((record) => composeMessageObjectWithUser(record, this.userId)), count: messages.length, offset, total, @@ -605,24 +608,24 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, { // } // }); -RocketChat.API.v1.addRoute('channels.online', { authRequired: true }, { +API.v1.addRoute('channels.online', { authRequired: true }, { get() { const { query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { t: 'c' }); - const room = RocketChat.models.Rooms.findOne(ourQuery); + const room = Rooms.findOne(ourQuery); if (room == null) { - return RocketChat.API.v1.failure('Channel does not exists'); + return API.v1.failure('Channel does not exists'); } - const online = RocketChat.models.Users.findUsersNotOffline({ + const online = Users.findUsersNotOffline({ fields: { username: 1 }, }).fetch(); const onlineInRoom = []; online.forEach((user) => { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); if (subscription) { onlineInRoom.push({ _id: user._id, @@ -631,35 +634,35 @@ RocketChat.API.v1.addRoute('channels.online', { authRequired: true }, { } }); - return RocketChat.API.v1.success({ + return API.v1.success({ online: onlineInRoom, }); }, }); -RocketChat.API.v1.addRoute('channels.open', { authRequired: true }, { +API.v1.addRoute('channels.open', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); + const sub = Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId); if (!sub) { - return RocketChat.API.v1.failure(`The user/callee is not in the channel "${ findResult.name }".`); + return API.v1.failure(`The user/callee is not in the channel "${ findResult.name }".`); } if (sub.open) { - return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is already open to the sender`); + return API.v1.failure(`The channel, ${ findResult.name }, is already open to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('openRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.removeModerator', { authRequired: true }, { +API.v1.addRoute('channels.removeModerator', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -669,11 +672,11 @@ RocketChat.API.v1.addRoute('channels.removeModerator', { authRequired: true }, { Meteor.call('removeRoomModerator', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.removeOwner', { authRequired: true }, { +API.v1.addRoute('channels.removeOwner', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -683,36 +686,36 @@ RocketChat.API.v1.addRoute('channels.removeOwner', { authRequired: true }, { Meteor.call('removeRoomOwner', findResult._id, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.rename', { authRequired: true }, { +API.v1.addRoute('channels.rename', { authRequired: true }, { post() { if (!this.bodyParams.name || !this.bodyParams.name.trim()) { - return RocketChat.API.v1.failure('The bodyParam "name" is required'); + return API.v1.failure('The bodyParam "name" is required'); } const findResult = findChannelByIdOrName({ params: { roomId: this.bodyParams.roomId } }); if (findResult.name === this.bodyParams.name) { - return RocketChat.API.v1.failure('The channel name is the same as what it would be renamed to.'); + return API.v1.failure('The channel name is the same as what it would be renamed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomName', this.bodyParams.name); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: { roomId: this.bodyParams.roomId }, userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setCustomFields', { authRequired: true }, { +API.v1.addRoute('channels.setCustomFields', { authRequired: true }, { post() { if (!this.bodyParams.customFields || !(typeof this.bodyParams.customFields === 'object')) { - return RocketChat.API.v1.failure('The bodyParam "customFields" is required with a type like object.'); + return API.v1.failure('The bodyParam "customFields" is required with a type like object.'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -721,60 +724,60 @@ RocketChat.API.v1.addRoute('channels.setCustomFields', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult._id, 'roomCustomFields', this.bodyParams.customFields); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setDefault', { authRequired: true }, { +API.v1.addRoute('channels.setDefault', { authRequired: true }, { post() { if (typeof this.bodyParams.default === 'undefined') { - return RocketChat.API.v1.failure('The bodyParam "default" is required', 'error-channels-setdefault-is-same'); + return API.v1.failure('The bodyParam "default" is required', 'error-channels-setdefault-is-same'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.default === this.bodyParams.default) { - return RocketChat.API.v1.failure('The channel default setting is the same as what it would be changed to.', 'error-channels-setdefault-missing-default-param'); + return API.v1.failure('The channel default setting is the same as what it would be changed to.', 'error-channels-setdefault-missing-default-param'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'default', this.bodyParams.default.toString()); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setDescription', { authRequired: true }, { +API.v1.addRoute('channels.setDescription', { authRequired: true }, { post() { if (!this.bodyParams.description || !this.bodyParams.description.trim()) { - return RocketChat.API.v1.failure('The bodyParam "description" is required'); + return API.v1.failure('The bodyParam "description" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.description === this.bodyParams.description) { - return RocketChat.API.v1.failure('The channel description is the same as what it would be changed to.'); + return API.v1.failure('The channel description is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomDescription', this.bodyParams.description); }); - return RocketChat.API.v1.success({ + return API.v1.success({ description: this.bodyParams.description, }); }, }); -RocketChat.API.v1.addRoute('channels.setJoinCode', { authRequired: true }, { +API.v1.addRoute('channels.setJoinCode', { authRequired: true }, { post() { if (!this.bodyParams.joinCode || !this.bodyParams.joinCode.trim()) { - return RocketChat.API.v1.failure('The bodyParam "joinCode" is required'); + return API.v1.failure('The bodyParam "joinCode" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -783,82 +786,82 @@ RocketChat.API.v1.addRoute('channels.setJoinCode', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult._id, 'joinCode', this.bodyParams.joinCode); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setPurpose', { authRequired: true }, { +API.v1.addRoute('channels.setPurpose', { authRequired: true }, { post() { if (!this.bodyParams.purpose || !this.bodyParams.purpose.trim()) { - return RocketChat.API.v1.failure('The bodyParam "purpose" is required'); + return API.v1.failure('The bodyParam "purpose" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.description === this.bodyParams.purpose) { - return RocketChat.API.v1.failure('The channel purpose (description) is the same as what it would be changed to.'); + return API.v1.failure('The channel purpose (description) is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomDescription', this.bodyParams.purpose); }); - return RocketChat.API.v1.success({ + return API.v1.success({ purpose: this.bodyParams.purpose, }); }, }); -RocketChat.API.v1.addRoute('channels.setReadOnly', { authRequired: true }, { +API.v1.addRoute('channels.setReadOnly', { authRequired: true }, { post() { if (typeof this.bodyParams.readOnly === 'undefined') { - return RocketChat.API.v1.failure('The bodyParam "readOnly" is required'); + return API.v1.failure('The bodyParam "readOnly" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.ro === this.bodyParams.readOnly) { - return RocketChat.API.v1.failure('The channel read only setting is the same as what it would be changed to.'); + return API.v1.failure('The channel read only setting is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'readOnly', this.bodyParams.readOnly); }); - return RocketChat.API.v1.success({ + return API.v1.success({ channel: findChannelByIdOrName({ params: this.requestParams(), userId: this.userId }), }); }, }); -RocketChat.API.v1.addRoute('channels.setTopic', { authRequired: true }, { +API.v1.addRoute('channels.setTopic', { authRequired: true }, { post() { if (!this.bodyParams.topic || !this.bodyParams.topic.trim()) { - return RocketChat.API.v1.failure('The bodyParam "topic" is required'); + return API.v1.failure('The bodyParam "topic" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.topic === this.bodyParams.topic) { - return RocketChat.API.v1.failure('The channel topic is the same as what it would be changed to.'); + return API.v1.failure('The channel topic is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomTopic', this.bodyParams.topic); }); - return RocketChat.API.v1.success({ + return API.v1.success({ topic: this.bodyParams.topic, }); }, }); -RocketChat.API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, { +API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, { post() { if (!this.bodyParams.announcement || !this.bodyParams.announcement.trim()) { - return RocketChat.API.v1.failure('The bodyParam "announcement" is required'); + return API.v1.failure('The bodyParam "announcement" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); @@ -867,58 +870,58 @@ RocketChat.API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult._id, 'roomAnnouncement', this.bodyParams.announcement); }); - return RocketChat.API.v1.success({ + return API.v1.success({ announcement: this.bodyParams.announcement, }); }, }); -RocketChat.API.v1.addRoute('channels.setType', { authRequired: true }, { +API.v1.addRoute('channels.setType', { authRequired: true }, { post() { if (!this.bodyParams.type || !this.bodyParams.type.trim()) { - return RocketChat.API.v1.failure('The bodyParam "type" is required'); + return API.v1.failure('The bodyParam "type" is required'); } const findResult = findChannelByIdOrName({ params: this.requestParams() }); if (findResult.t === this.bodyParams.type) { - return RocketChat.API.v1.failure('The channel type is the same as what it would be changed to.'); + return API.v1.failure('The channel type is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult._id, 'roomType', this.bodyParams.type); }); - return RocketChat.API.v1.success({ - channel: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + channel: this.composeRoomWithLastMessage(Rooms.findOneById(findResult._id, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('channels.unarchive', { authRequired: true }, { +API.v1.addRoute('channels.unarchive', { authRequired: true }, { post() { const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false }); if (!findResult.archived) { - return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is not archived`); + return API.v1.failure(`The channel, ${ findResult.name }, is not archived`); } Meteor.runAsUser(this.userId, () => { Meteor.call('unarchiveRoom', findResult._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequired: true }, { +API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequired: true }, { get() { const { roomId } = this.requestParams(); const { offset, count } = this.getPaginationItems(); const { sort } = this.parseJsonQuery(); if (!roomId) { - return RocketChat.API.v1.failure('The request param "roomId" is required'); + return API.v1.failure('The request param "roomId" is required'); } const mentions = Meteor.runAsUser(this.userId, () => Meteor.call('getUserMentionsByChannel', { @@ -935,7 +938,7 @@ RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequire options: {}, })); - return RocketChat.API.v1.success({ + return API.v1.success({ mentions, count: mentions.length, offset, @@ -944,25 +947,25 @@ RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequire }, }); -RocketChat.API.v1.addRoute('channels.roles', { authRequired: true }, { +API.v1.addRoute('channels.roles', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); const roles = Meteor.runAsUser(this.userId, () => Meteor.call('getRoomRoles', findResult._id)); - return RocketChat.API.v1.success({ + return API.v1.success({ roles, }); }, }); -RocketChat.API.v1.addRoute('channels.moderators', { authRequired: true }, { +API.v1.addRoute('channels.moderators', { authRequired: true }, { get() { const findResult = findChannelByIdOrName({ params: this.requestParams() }); - const moderators = RocketChat.models.Subscriptions.findByRoomIdAndRoles(findResult._id, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); + const moderators = Subscriptions.findByRoomIdAndRoles(findResult._id, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); - return RocketChat.API.v1.success({ + return API.v1.success({ moderators, }); }, diff --git a/packages/rocketchat-api/server/v1/chat.js b/packages/rocketchat-api/server/v1/chat.js index f6f92ae02444..f83b8dc2c804 100644 --- a/packages/rocketchat-api/server/v1/chat.js +++ b/packages/rocketchat-api/server/v1/chat.js @@ -1,9 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Match, check } from 'meteor/check'; import { processWebhookMessage } from 'meteor/rocketchat:integrations'; +import { Messages } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { +API.v1.addRoute('chat.delete', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ msgId: String, @@ -11,25 +14,25 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { asUser: Match.Maybe(Boolean), })); - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 } }); + const msg = Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 } }); if (!msg) { - return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); + return API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); } if (this.bodyParams.roomId !== msg.rid) { - return RocketChat.API.v1.failure('The room id provided does not match where the message is from.'); + return API.v1.failure('The room id provided does not match where the message is from.'); } - if (this.bodyParams.asUser && msg.u._id !== this.userId && !RocketChat.authz.hasPermission(this.userId, 'force-delete-message', msg.rid)) { - return RocketChat.API.v1.failure('Unauthorized. You must have the permission "force-delete-message" to delete other\'s message as them.'); + if (this.bodyParams.asUser && msg.u._id !== this.userId && !hasPermission(this.userId, 'force-delete-message', msg.rid)) { + return API.v1.failure('Unauthorized. You must have the permission "force-delete-message" to delete other\'s message as them.'); } Meteor.runAsUser(this.bodyParams.asUser ? msg.u._id : this.userId, () => { Meteor.call('deleteMessage', { _id: msg._id }); }); - return RocketChat.API.v1.success({ + return API.v1.success({ _id: msg._id, ts: Date.now(), message: msg, @@ -37,7 +40,7 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('chat.syncMessages', { authRequired: true }, { +API.v1.addRoute('chat.syncMessages', { authRequired: true }, { get() { const { roomId, lastUpdate } = this.queryParams; @@ -57,22 +60,22 @@ RocketChat.API.v1.addRoute('chat.syncMessages', { authRequired: true }, { }); if (!result) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ + return API.v1.success({ result: { - updated: result.updated.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), - deleted: result.deleted.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + updated: result.updated.map((message) => composeMessageObjectWithUser(message, this.userId)), + deleted: result.deleted.map((message) => composeMessageObjectWithUser(message, this.userId)), }, }); }, }); -RocketChat.API.v1.addRoute('chat.getMessage', { authRequired: true }, { +API.v1.addRoute('chat.getMessage', { authRequired: true }, { get() { if (!this.queryParams.msgId) { - return RocketChat.API.v1.failure('The "msgId" query parameter must be provided.'); + return API.v1.failure('The "msgId" query parameter must be provided.'); } let msg; @@ -81,22 +84,22 @@ RocketChat.API.v1.addRoute('chat.getMessage', { authRequired: true }, { }); if (!msg) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(msg, this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(msg, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.pinMessage', { authRequired: true }, { +API.v1.addRoute('chat.pinMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is missing.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -105,29 +108,29 @@ RocketChat.API.v1.addRoute('chat.pinMessage', { authRequired: true }, { let pinnedMessage; Meteor.runAsUser(this.userId, () => pinnedMessage = Meteor.call('pinMessage', msg)); - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(pinnedMessage, this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(pinnedMessage, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.postMessage', { authRequired: true }, { +API.v1.addRoute('chat.postMessage', { authRequired: true }, { post() { const messageReturn = processWebhookMessage(this.bodyParams, this.user, undefined, true)[0]; if (!messageReturn) { - return RocketChat.API.v1.failure('unknown-error'); + return API.v1.failure('unknown-error'); } - return RocketChat.API.v1.success({ + return API.v1.success({ ts: Date.now(), channel: messageReturn.channel, - message: RocketChat.composeMessageObjectWithUser(messageReturn.message, this.userId), + message: composeMessageObjectWithUser(messageReturn.message, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, { +API.v1.addRoute('chat.search', { authRequired: true }, { get() { const { roomId, searchText } = this.queryParams; const { count } = this.getPaginationItems(); @@ -143,8 +146,8 @@ RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, { let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('messageSearch', searchText, roomId, count).message.docs); - return RocketChat.API.v1.success({ - messages: result.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: result.map((message) => composeMessageObjectWithUser(message, this.userId)), }); }, }); @@ -152,7 +155,7 @@ RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, { // The difference between `chat.postMessage` and `chat.sendMessage` is that `chat.sendMessage` allows // for passing a value for `_id` and the other one doesn't. Also, `chat.sendMessage` only sends it to // one channel whereas the other one allows for sending to more than one channel at a time. -RocketChat.API.v1.addRoute('chat.sendMessage', { authRequired: true }, { +API.v1.addRoute('chat.sendMessage', { authRequired: true }, { post() { if (!this.bodyParams.message) { throw new Meteor.Error('error-invalid-params', 'The "message" parameter must be provided.'); @@ -161,19 +164,19 @@ RocketChat.API.v1.addRoute('chat.sendMessage', { authRequired: true }, { let message; Meteor.runAsUser(this.userId, () => message = Meteor.call('sendMessage', this.bodyParams.message)); - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(message, this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(message, this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.starMessage', { authRequired: true }, { +API.v1.addRoute('chat.starMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is required.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -185,17 +188,17 @@ RocketChat.API.v1.addRoute('chat.starMessage', { authRequired: true }, { starred: true, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.unPinMessage', { authRequired: true }, { +API.v1.addRoute('chat.unPinMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is required.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -203,17 +206,17 @@ RocketChat.API.v1.addRoute('chat.unPinMessage', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('unpinMessage', msg)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.unStarMessage', { authRequired: true }, { +API.v1.addRoute('chat.unStarMessage', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is required.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -225,11 +228,11 @@ RocketChat.API.v1.addRoute('chat.unStarMessage', { authRequired: true }, { starred: false, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, { +API.v1.addRoute('chat.update', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ roomId: String, @@ -237,15 +240,15 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, { text: String, // Using text to be consistant with chat.postMessage })); - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId); + const msg = Messages.findOneById(this.bodyParams.msgId); // Ensure the message exists if (!msg) { - return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); + return API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`); } if (this.bodyParams.roomId !== msg.rid) { - return RocketChat.API.v1.failure('The room id provided does not match where the message is from.'); + return API.v1.failure('The room id provided does not match where the message is from.'); } // Permission checks are already done in the updateMessage method, so no need to duplicate them @@ -253,19 +256,19 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, { Meteor.call('updateMessage', { _id: msg._id, msg: this.bodyParams.text, rid: msg.rid }); }); - return RocketChat.API.v1.success({ - message: RocketChat.composeMessageObjectWithUser(RocketChat.models.Messages.findOneById(msg._id), this.userId), + return API.v1.success({ + message: composeMessageObjectWithUser(Messages.findOneById(msg._id), this.userId), }); }, }); -RocketChat.API.v1.addRoute('chat.react', { authRequired: true }, { +API.v1.addRoute('chat.react', { authRequired: true }, { post() { if (!this.bodyParams.messageId || !this.bodyParams.messageId.trim()) { throw new Meteor.Error('error-messageid-param-not-provided', 'The required "messageId" param is missing.'); } - const msg = RocketChat.models.Messages.findOneById(this.bodyParams.messageId); + const msg = Messages.findOneById(this.bodyParams.messageId); if (!msg) { throw new Meteor.Error('error-message-not-found', 'The provided "messageId" does not match any existing message.'); @@ -279,50 +282,50 @@ RocketChat.API.v1.addRoute('chat.react', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('setReaction', emoji, msg._id, this.bodyParams.shouldReact)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.getMessageReadReceipts', { authRequired: true }, { +API.v1.addRoute('chat.getMessageReadReceipts', { authRequired: true }, { get() { const { messageId } = this.queryParams; if (!messageId) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ error: 'The required \'messageId\' param is missing.', }); } try { const messageReadReceipts = Meteor.runAsUser(this.userId, () => Meteor.call('getReadReceipts', { messageId })); - return RocketChat.API.v1.success({ + return API.v1.success({ receipts: messageReadReceipts, }); } catch (error) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ error: error.message, }); } }, }); -RocketChat.API.v1.addRoute('chat.reportMessage', { authRequired: true }, { +API.v1.addRoute('chat.reportMessage', { authRequired: true }, { post() { const { messageId, description } = this.bodyParams; if (!messageId) { - return RocketChat.API.v1.failure('The required "messageId" param is missing.'); + return API.v1.failure('The required "messageId" param is missing.'); } if (!description) { - return RocketChat.API.v1.failure('The required "description" param is missing.'); + return API.v1.failure('The required "description" param is missing.'); } Meteor.runAsUser(this.userId, () => Meteor.call('reportMessage', messageId, description)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.ignoreUser', { authRequired: true }, { +API.v1.addRoute('chat.ignoreUser', { authRequired: true }, { get() { const { rid, userId } = this.queryParams; let { ignore = true } = this.queryParams; @@ -339,11 +342,11 @@ RocketChat.API.v1.addRoute('chat.ignoreUser', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('ignoreUser', { rid, userId, ignore })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { +API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { get() { const { roomId, since } = this.queryParams; const { offset, count } = this.getPaginationItems(); @@ -357,7 +360,7 @@ RocketChat.API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { } else if (isNaN(Date.parse(since))) { throw new Meteor.Error('The "since" query parameter must be a valid date.'); } - const cursor = RocketChat.models.Messages.trashFindDeletedAfter(new Date(since), { rid: roomId }, { + const cursor = Messages.trashFindDeletedAfter(new Date(since), { rid: roomId }, { skip: offset, limit: count, fields: { _id: 1 }, @@ -367,7 +370,7 @@ RocketChat.API.v1.addRoute('chat.getDeletedMessages', { authRequired: true }, { const messages = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ messages, count: messages.length, offset, diff --git a/packages/rocketchat-api/server/v1/commands.js b/packages/rocketchat-api/server/v1/commands.js index bfac0b17d5aa..3fdd8f042c47 100644 --- a/packages/rocketchat-api/server/v1/commands.js +++ b/packages/rocketchat-api/server/v1/commands.js @@ -1,45 +1,47 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Rooms } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('commands.get', { authRequired: true }, { +API.v1.addRoute('commands.get', { authRequired: true }, { get() { const params = this.queryParams; if (typeof params.command !== 'string') { - return RocketChat.API.v1.failure('The query param "command" must be provided.'); + return API.v1.failure('The query param "command" must be provided.'); } - const cmd = RocketChat.slashCommands.commands[params.command.toLowerCase()]; + const cmd = slashCommands.commands[params.command.toLowerCase()]; if (!cmd) { - return RocketChat.API.v1.failure(`There is no command in the system by the name of: ${ params.command }`); + return API.v1.failure(`There is no command in the system by the name of: ${ params.command }`); } - return RocketChat.API.v1.success({ command: cmd }); + return API.v1.success({ command: cmd }); }, }); -RocketChat.API.v1.addRoute('commands.list', { authRequired: true }, { +API.v1.addRoute('commands.list', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - let commands = Object.values(RocketChat.slashCommands.commands); + let commands = Object.values(slashCommands.commands); if (query && query.command) { commands = commands.filter((command) => command.command === query.command); } const totalCount = commands.length; - commands = RocketChat.models.Rooms.processQueryOptionsOnResult(commands, { + commands = Rooms.processQueryOptionsOnResult(commands, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }); - return RocketChat.API.v1.success({ + return API.v1.success({ commands, offset, count: commands.length, @@ -49,26 +51,26 @@ RocketChat.API.v1.addRoute('commands.list', { authRequired: true }, { }); // Expects a body of: { command: 'gimme', params: 'any string value', roomId: 'value' } -RocketChat.API.v1.addRoute('commands.run', { authRequired: true }, { +API.v1.addRoute('commands.run', { authRequired: true }, { post() { const body = this.bodyParams; const user = this.getLoggedInUser(); if (typeof body.command !== 'string') { - return RocketChat.API.v1.failure('You must provide a command to run.'); + return API.v1.failure('You must provide a command to run.'); } if (body.params && typeof body.params !== 'string') { - return RocketChat.API.v1.failure('The parameters for the command must be a single string.'); + return API.v1.failure('The parameters for the command must be a single string.'); } if (typeof body.roomId !== 'string') { - return RocketChat.API.v1.failure('The room\'s id where to execute this command must be provided and be a string.'); + return API.v1.failure('The room\'s id where to execute this command must be provided and be a string.'); } const cmd = body.command.toLowerCase(); - if (!RocketChat.slashCommands.commands[body.command.toLowerCase()]) { - return RocketChat.API.v1.failure('The command provided does not exist (or is disabled).'); + if (!slashCommands.commands[body.command.toLowerCase()]) { + return API.v1.failure('The command provided does not exist (or is disabled).'); } // This will throw an error if they can't or the room is invalid @@ -78,38 +80,38 @@ RocketChat.API.v1.addRoute('commands.run', { authRequired: true }, { let result; Meteor.runAsUser(user._id, () => { - result = RocketChat.slashCommands.run(cmd, params, { + result = slashCommands.run(cmd, params, { _id: Random.id(), rid: body.roomId, msg: `/${ cmd } ${ params }`, }); }); - return RocketChat.API.v1.success({ result }); + return API.v1.success({ result }); }, }); -RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { +API.v1.addRoute('commands.preview', { authRequired: true }, { // Expects these query params: command: 'giphy', params: 'mine', roomId: 'value' get() { const query = this.queryParams; const user = this.getLoggedInUser(); if (typeof query.command !== 'string') { - return RocketChat.API.v1.failure('You must provide a command to get the previews from.'); + return API.v1.failure('You must provide a command to get the previews from.'); } if (query.params && typeof query.params !== 'string') { - return RocketChat.API.v1.failure('The parameters for the command must be a single string.'); + return API.v1.failure('The parameters for the command must be a single string.'); } if (typeof query.roomId !== 'string') { - return RocketChat.API.v1.failure('The room\'s id where the previews are being displayed must be provided and be a string.'); + return API.v1.failure('The room\'s id where the previews are being displayed must be provided and be a string.'); } const cmd = query.command.toLowerCase(); - if (!RocketChat.slashCommands.commands[cmd]) { - return RocketChat.API.v1.failure('The command provided does not exist (or is disabled).'); + if (!slashCommands.commands[cmd]) { + return API.v1.failure('The command provided does not exist (or is disabled).'); } // This will throw an error if they can't or the room is invalid @@ -122,7 +124,7 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { preview = Meteor.call('getSlashCommandPreviews', { cmd, params, msg: { rid: query.roomId } }); }); - return RocketChat.API.v1.success({ preview }); + return API.v1.success({ preview }); }, // Expects a body format of: { command: 'giphy', params: 'mine', roomId: 'value', previewItem: { id: 'sadf8' type: 'image', value: 'https://dev.null/gif } } post() { @@ -130,28 +132,28 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { const user = this.getLoggedInUser(); if (typeof body.command !== 'string') { - return RocketChat.API.v1.failure('You must provide a command to run the preview item on.'); + return API.v1.failure('You must provide a command to run the preview item on.'); } if (body.params && typeof body.params !== 'string') { - return RocketChat.API.v1.failure('The parameters for the command must be a single string.'); + return API.v1.failure('The parameters for the command must be a single string.'); } if (typeof body.roomId !== 'string') { - return RocketChat.API.v1.failure('The room\'s id where the preview is being executed in must be provided and be a string.'); + return API.v1.failure('The room\'s id where the preview is being executed in must be provided and be a string.'); } if (typeof body.previewItem === 'undefined') { - return RocketChat.API.v1.failure('The preview item being executed must be provided.'); + return API.v1.failure('The preview item being executed must be provided.'); } if (!body.previewItem.id || !body.previewItem.type || typeof body.previewItem.value === 'undefined') { - return RocketChat.API.v1.failure('The preview item being executed is in the wrong format.'); + return API.v1.failure('The preview item being executed is in the wrong format.'); } const cmd = body.command.toLowerCase(); - if (!RocketChat.slashCommands.commands[cmd]) { - return RocketChat.API.v1.failure('The command provided does not exist (or is disabled).'); + if (!slashCommands.commands[cmd]) { + return API.v1.failure('The command provided does not exist (or is disabled).'); } // This will throw an error if they can't or the room is invalid @@ -163,6 +165,6 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, { Meteor.call('executeSlashCommandPreview', { cmd, params, msg: { rid: body.roomId } }, body.previewItem); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/e2e.js b/packages/rocketchat-api/server/v1/e2e.js index f21f55e6e294..c4974add4774 100644 --- a/packages/rocketchat-api/server/v1/e2e.js +++ b/packages/rocketchat-api/server/v1/e2e.js @@ -1,61 +1,61 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('e2e.fetchMyKeys', { authRequired: true }, { +API.v1.addRoute('e2e.fetchMyKeys', { authRequired: true }, { get() { let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('e2e.fetchMyKeys')); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('e2e.getUsersOfRoomWithoutKey', { authRequired: true }, { +API.v1.addRoute('e2e.getUsersOfRoomWithoutKey', { authRequired: true }, { get() { const { rid } = this.queryParams; let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('e2e.getUsersOfRoomWithoutKey', rid)); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('e2e.setRoomKeyID', { authRequired: true }, { +API.v1.addRoute('e2e.setRoomKeyID', { authRequired: true }, { post() { const { rid, keyID } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('e2e.setRoomKeyID', rid, keyID)); + API.v1.success(Meteor.call('e2e.setRoomKeyID', rid, keyID)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('e2e.setUserPublicAndPivateKeys', { authRequired: true }, { +API.v1.addRoute('e2e.setUserPublicAndPivateKeys', { authRequired: true }, { post() { const { public_key, private_key } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('e2e.setUserPublicAndPivateKeys', { + API.v1.success(Meteor.call('e2e.setUserPublicAndPivateKeys', { public_key, private_key, })); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('e2e.updateGroupKey', { authRequired: true }, { +API.v1.addRoute('e2e.updateGroupKey', { authRequired: true }, { post() { const { uid, rid, key } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('e2e.updateGroupKey', rid, uid, key)); + API.v1.success(Meteor.call('e2e.updateGroupKey', rid, uid, key)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/emoji-custom.js b/packages/rocketchat-api/server/v1/emoji-custom.js index 94f427511ba5..09c931370d86 100644 --- a/packages/rocketchat-api/server/v1/emoji-custom.js +++ b/packages/rocketchat-api/server/v1/emoji-custom.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { EmojiCustom } from 'meteor/rocketchat:models'; +import { API } from '../api'; import Busboy from 'busboy'; -RocketChat.API.v1.addRoute('emoji-custom', { authRequired: true }, { +API.v1.addRoute('emoji-custom', { authRequired: true }, { get() { const { query } = this.parseJsonQuery(); const emojis = Meteor.call('listEmojiCustom', query); - return RocketChat.API.v1.success({ emojis }); + return API.v1.success({ emojis }); }, }); -RocketChat.API.v1.addRoute('emoji-custom.create', { authRequired: true }, { +API.v1.addRoute('emoji-custom.create', { authRequired: true }, { post() { Meteor.runAsUser(this.userId, () => { const fields = {}; @@ -49,7 +50,7 @@ RocketChat.API.v1.addRoute('emoji-custom.create', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('emoji-custom.update', { authRequired: true }, { +API.v1.addRoute('emoji-custom.update', { authRequired: true }, { post() { Meteor.runAsUser(this.userId, () => { const fields = {}; @@ -78,7 +79,7 @@ RocketChat.API.v1.addRoute('emoji-custom.update', { authRequired: true }, { if (!fields._id) { return callback(new Meteor.Error('The required "_id" query param is missing.')); } - const emojiToUpdate = RocketChat.models.EmojiCustom.findOneByID(fields._id); + const emojiToUpdate = EmojiCustom.findOneByID(fields._id); if (!emojiToUpdate) { return callback(new Meteor.Error('Emoji not found.')); } @@ -102,15 +103,15 @@ RocketChat.API.v1.addRoute('emoji-custom.update', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('emoji-custom.delete', { authRequired: true }, { +API.v1.addRoute('emoji-custom.delete', { authRequired: true }, { post() { const { emojiId } = this.bodyParams; if (!emojiId) { - return RocketChat.API.v1.failure('The "emojiId" params is required!'); + return API.v1.failure('The "emojiId" params is required!'); } Meteor.runAsUser(this.userId, () => Meteor.call('deleteEmojiCustom', emojiId)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/groups.js b/packages/rocketchat-api/server/v1/groups.js index fc5430c1f6ce..96c23e42e726 100644 --- a/packages/rocketchat-api/server/v1/groups.js +++ b/packages/rocketchat-api/server/v1/groups.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Rooms, Messages, Uploads, Integrations, Users } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { API } from '../api'; import _ from 'underscore'; // Returns the private group subscription IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property @@ -10,9 +13,9 @@ function findPrivateGroupByIdOrName({ params, userId, checkedArchived = true }) let roomSub; if (params.roomId) { - roomSub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(params.roomId, userId); + roomSub = Subscriptions.findOneByRoomIdAndUserId(params.roomId, userId); } else if (params.roomName) { - roomSub = RocketChat.models.Subscriptions.findOneByRoomNameAndUserId(params.roomName, userId); + roomSub = Subscriptions.findOneByRoomNameAndUserId(params.roomName, userId); } if (!roomSub || roomSub.t !== 'p') { @@ -26,7 +29,7 @@ function findPrivateGroupByIdOrName({ params, userId, checkedArchived = true }) return roomSub; } -RocketChat.API.v1.addRoute('groups.addAll', { authRequired: true }, { +API.v1.addRoute('groups.addAll', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -34,13 +37,13 @@ RocketChat.API.v1.addRoute('groups.addAll', { authRequired: true }, { Meteor.call('addAllUserToRoom', findResult.rid, this.bodyParams.activeUsersOnly); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.addModerator', { authRequired: true }, { +API.v1.addRoute('groups.addModerator', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -50,11 +53,11 @@ RocketChat.API.v1.addRoute('groups.addModerator', { authRequired: true }, { Meteor.call('addRoomModerator', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.addOwner', { authRequired: true }, { +API.v1.addRoute('groups.addOwner', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -64,11 +67,11 @@ RocketChat.API.v1.addRoute('groups.addOwner', { authRequired: true }, { Meteor.call('addRoomOwner', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.addLeader', { authRequired: true }, { +API.v1.addRoute('groups.addLeader', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); const user = this.getUserFromParams(); @@ -76,12 +79,12 @@ RocketChat.API.v1.addRoute('groups.addLeader', { authRequired: true }, { Meteor.call('addRoomLeader', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); // Archives a private group only if it wasn't -RocketChat.API.v1.addRoute('groups.archive', { authRequired: true }, { +API.v1.addRoute('groups.archive', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -89,29 +92,29 @@ RocketChat.API.v1.addRoute('groups.archive', { authRequired: true }, { Meteor.call('archiveRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.close', { authRequired: true }, { +API.v1.addRoute('groups.close', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); if (!findResult.open) { - return RocketChat.API.v1.failure(`The private group, ${ findResult.name }, is already closed to the sender`); + return API.v1.failure(`The private group, ${ findResult.name }, is already closed to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('hideRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { +API.v1.addRoute('groups.counters', { authRequired: true }, { get() { - const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration'); + const access = hasPermission(this.userId, 'view-room-administration'); const params = this.requestParams(); let user = this.userId; let room; @@ -128,9 +131,9 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { } if (params.roomId) { - room = RocketChat.models.Rooms.findOneById(params.roomId); + room = Rooms.findOneById(params.roomId); } else if (params.roomName) { - room = RocketChat.models.Rooms.findOneByName(params.roomName); + room = Rooms.findOneByName(params.roomName); } if (!room || room.t !== 'p') { @@ -143,15 +146,15 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { if (params.userId) { if (!access) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } user = params.userId; } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user); const lm = room.lm ? room.lm : room._updatedAt; if (typeof subscription !== 'undefined' && subscription.open) { - unreads = RocketChat.models.Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, (subscription.ls || subscription.ts), lm); + unreads = Messages.countVisibleByRoomIdBetweenTimestampsInclusive(subscription.rid, (subscription.ls || subscription.ts), lm); unreadsFrom = subscription.ls || subscription.ts; userMentions = subscription.userMentions; joined = true; @@ -163,7 +166,7 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { members = room.usersCount; } - return RocketChat.API.v1.success({ + return API.v1.success({ joined, members, unreads, @@ -176,22 +179,22 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, { }); // Create Private Group -RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, { +API.v1.addRoute('groups.create', { authRequired: true }, { post() { - if (!RocketChat.authz.hasPermission(this.userId, 'create-p')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'create-p')) { + return API.v1.unauthorized(); } if (!this.bodyParams.name) { - return RocketChat.API.v1.failure('Body param "name" is required'); + return API.v1.failure('Body param "name" is required'); } if (this.bodyParams.members && !_.isArray(this.bodyParams.members)) { - return RocketChat.API.v1.failure('Body param "members" must be an array if provided'); + return API.v1.failure('Body param "members" must be an array if provided'); } if (this.bodyParams.customFields && !(typeof this.bodyParams.customFields === 'object')) { - return RocketChat.API.v1.failure('Body param "customFields" must be an object if provided'); + return API.v1.failure('Body param "customFields" must be an object if provided'); } const readOnly = typeof this.bodyParams.readOnly !== 'undefined' ? this.bodyParams.readOnly : false; @@ -201,13 +204,13 @@ RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, { id = Meteor.call('createPrivateGroup', this.bodyParams.name, this.bodyParams.members ? this.bodyParams.members : [], readOnly, this.bodyParams.customFields); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(id.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(id.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.delete', { authRequired: true }, { +API.v1.addRoute('groups.delete', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -215,11 +218,11 @@ RocketChat.API.v1.addRoute('groups.delete', { authRequired: true }, { Meteor.call('eraseRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.files', { authRequired: true }, { +API.v1.addRoute('groups.files', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); const addUserObjectToEveryObject = (file) => { @@ -234,26 +237,26 @@ RocketChat.API.v1.addRoute('groups.files', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult.rid }); - const files = RocketChat.models.Uploads.find(ourQuery, { + const files = Uploads.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ files: files.map(addUserObjectToEveryObject), count: files.length, offset, - total: RocketChat.models.Uploads.find(ourQuery).count(), + total: Uploads.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, { +API.v1.addRoute('groups.getIntegrations', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -272,23 +275,23 @@ RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, { const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { channel: { $in: channelsToSearch } }); - const integrations = RocketChat.models.Integrations.find(ourQuery, { + const integrations = Integrations.find(ourQuery, { sort: sort ? sort : { _createdAt: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ integrations, count: integrations.length, offset, - total: RocketChat.models.Integrations.find(ourQuery).count(), + total: Integrations.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, { +API.v1.addRoute('groups.history', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -317,24 +320,24 @@ RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, { }); if (!result) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('groups.info', { authRequired: true }, { +API.v1.addRoute('groups.info', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, { +API.v1.addRoute('groups.invite', { authRequired: true }, { post() { const { roomId = '', roomName = '' } = this.requestParams(); const idOrName = roomId || roomName; @@ -342,7 +345,7 @@ RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, { throw new Meteor.Error('error-room-param-not-provided', 'The parameter "roomId" or "roomName" is required'); } - const { _id: rid, t: type } = RocketChat.models.Rooms.findOneByIdOrName(idOrName) || {}; + const { _id: rid, t: type } = Rooms.findOneByIdOrName(idOrName) || {}; if (!rid || type !== 'p') { throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "roomName" param provided does not match any group'); @@ -352,13 +355,13 @@ RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('addUserToRoom', { rid, username })); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.kick', { authRequired: true }, { +API.v1.addRoute('groups.kick', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -368,11 +371,11 @@ RocketChat.API.v1.addRoute('groups.kick', { authRequired: true }, { Meteor.call('removeUserFromRoom', { rid: findResult.rid, username: user.username }); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.leave', { authRequired: true }, { +API.v1.addRoute('groups.leave', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -380,18 +383,18 @@ RocketChat.API.v1.addRoute('groups.leave', { authRequired: true }, { Meteor.call('leaveRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); // List Private Groups a user has access to -RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, { +API.v1.addRoute('groups.list', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields } = this.parseJsonQuery(); // TODO: CACHE: Add Breacking notice since we removed the query param - const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('p', this.userId, { + const cursor = Rooms.findBySubscriptionTypeAndUserId('p', this.userId, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, @@ -402,7 +405,7 @@ RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, { const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ groups: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -412,26 +415,26 @@ RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, { }); -RocketChat.API.v1.addRoute('groups.listAll', { authRequired: true }, { +API.v1.addRoute('groups.listAll', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-room-administration')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-room-administration')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { t: 'p' }); - let rooms = RocketChat.models.Rooms.find(ourQuery).fetch(); + let rooms = Rooms.find(ourQuery).fetch(); const totalCount = rooms.length; - rooms = RocketChat.models.Rooms.processQueryOptionsOnResult(rooms, { + rooms = Rooms.processQueryOptionsOnResult(rooms, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }); - return RocketChat.API.v1.success({ + return API.v1.success({ groups: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -440,19 +443,19 @@ RocketChat.API.v1.addRoute('groups.listAll', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, { +API.v1.addRoute('groups.members', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); - const room = RocketChat.models.Rooms.findOneById(findResult.rid, { fields: { broadcast: 1 } }); + const room = Rooms.findOneById(findResult.rid, { fields: { broadcast: 1 } }); - if (room.broadcast && !RocketChat.authz.hasPermission(this.userId, 'view-broadcast-member-list')) { - return RocketChat.API.v1.unauthorized(); + if (room.broadcast && !hasPermission(this.userId, 'view-broadcast-member-list')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort = {} } = this.parseJsonQuery(); - const subscriptions = RocketChat.models.Subscriptions.findByRoomId(findResult.rid, { + const subscriptions = Subscriptions.findByRoomId(findResult.rid, { fields: { 'u._id': 1 }, sort: { 'u.username': sort.username != null ? sort.username : 1 }, skip: offset, @@ -463,12 +466,12 @@ RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, { const members = subscriptions.fetch().map((s) => s.u && s.u._id); - const users = RocketChat.models.Users.find({ _id: { $in: members } }, { + const users = Users.find({ _id: { $in: members } }, { fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 }, sort: { username: sort.username != null ? sort.username : 1 }, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ members: users, count: users.length, offset, @@ -477,7 +480,7 @@ RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('groups.messages', { authRequired: true }, { +API.v1.addRoute('groups.messages', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); const { offset, count } = this.getPaginationItems(); @@ -485,34 +488,34 @@ RocketChat.API.v1.addRoute('groups.messages', { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult.rid }); - const messages = RocketChat.models.Messages.find(ourQuery, { + const messages = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ - messages: messages.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: messages.map((message) => composeMessageObjectWithUser(message, this.userId)), count: messages.length, offset, - total: RocketChat.models.Messages.find(ourQuery).count(), + total: Messages.find(ourQuery).count(), }); }, }); // TODO: CACHE: same as channels.online -RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, { +API.v1.addRoute('groups.online', { authRequired: true }, { get() { const { query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { t: 'p' }); - const room = RocketChat.models.Rooms.findOne(ourQuery); + const room = Rooms.findOne(ourQuery); if (room == null) { - return RocketChat.API.v1.failure('Group does not exists'); + return API.v1.failure('Group does not exists'); } - const online = RocketChat.models.Users.findUsersNotOffline({ + const online = Users.findUsersNotOffline({ fields: { username: 1, }, @@ -520,7 +523,7 @@ RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, { const onlineInRoom = []; online.forEach((user) => { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } }); if (subscription) { onlineInRoom.push({ _id: user._id, @@ -529,29 +532,29 @@ RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, { } }); - return RocketChat.API.v1.success({ + return API.v1.success({ online: onlineInRoom, }); }, }); -RocketChat.API.v1.addRoute('groups.open', { authRequired: true }, { +API.v1.addRoute('groups.open', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); if (findResult.open) { - return RocketChat.API.v1.failure(`The private group, ${ findResult.name }, is already open for the sender`); + return API.v1.failure(`The private group, ${ findResult.name }, is already open for the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('openRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.removeModerator', { authRequired: true }, { +API.v1.addRoute('groups.removeModerator', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -561,11 +564,11 @@ RocketChat.API.v1.addRoute('groups.removeModerator', { authRequired: true }, { Meteor.call('removeRoomModerator', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.removeOwner', { authRequired: true }, { +API.v1.addRoute('groups.removeOwner', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -575,11 +578,11 @@ RocketChat.API.v1.addRoute('groups.removeOwner', { authRequired: true }, { Meteor.call('removeRoomOwner', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.removeLeader', { authRequired: true }, { +API.v1.addRoute('groups.removeLeader', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -589,14 +592,14 @@ RocketChat.API.v1.addRoute('groups.removeLeader', { authRequired: true }, { Meteor.call('removeRoomLeader', findResult.rid, user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.rename', { authRequired: true }, { +API.v1.addRoute('groups.rename', { authRequired: true }, { post() { if (!this.bodyParams.name || !this.bodyParams.name.trim()) { - return RocketChat.API.v1.failure('The bodyParam "name" is required'); + return API.v1.failure('The bodyParam "name" is required'); } const findResult = findPrivateGroupByIdOrName({ params: { roomId: this.bodyParams.roomId }, userId: this.userId }); @@ -605,16 +608,16 @@ RocketChat.API.v1.addRoute('groups.rename', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomName', this.bodyParams.name); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setCustomFields', { authRequired: true }, { +API.v1.addRoute('groups.setCustomFields', { authRequired: true }, { post() { if (!this.bodyParams.customFields || !(typeof this.bodyParams.customFields === 'object')) { - return RocketChat.API.v1.failure('The bodyParam "customFields" is required with a type like object.'); + return API.v1.failure('The bodyParam "customFields" is required with a type like object.'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -623,16 +626,16 @@ RocketChat.API.v1.addRoute('groups.setCustomFields', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomCustomFields', this.bodyParams.customFields); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setDescription', { authRequired: true }, { +API.v1.addRoute('groups.setDescription', { authRequired: true }, { post() { if (!this.bodyParams.description || !this.bodyParams.description.trim()) { - return RocketChat.API.v1.failure('The bodyParam "description" is required'); + return API.v1.failure('The bodyParam "description" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -641,16 +644,16 @@ RocketChat.API.v1.addRoute('groups.setDescription', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomDescription', this.bodyParams.description); }); - return RocketChat.API.v1.success({ + return API.v1.success({ description: this.bodyParams.description, }); }, }); -RocketChat.API.v1.addRoute('groups.setPurpose', { authRequired: true }, { +API.v1.addRoute('groups.setPurpose', { authRequired: true }, { post() { if (!this.bodyParams.purpose || !this.bodyParams.purpose.trim()) { - return RocketChat.API.v1.failure('The bodyParam "purpose" is required'); + return API.v1.failure('The bodyParam "purpose" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -659,38 +662,38 @@ RocketChat.API.v1.addRoute('groups.setPurpose', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomDescription', this.bodyParams.purpose); }); - return RocketChat.API.v1.success({ + return API.v1.success({ purpose: this.bodyParams.purpose, }); }, }); -RocketChat.API.v1.addRoute('groups.setReadOnly', { authRequired: true }, { +API.v1.addRoute('groups.setReadOnly', { authRequired: true }, { post() { if (typeof this.bodyParams.readOnly === 'undefined') { - return RocketChat.API.v1.failure('The bodyParam "readOnly" is required'); + return API.v1.failure('The bodyParam "readOnly" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); if (findResult.ro === this.bodyParams.readOnly) { - return RocketChat.API.v1.failure('The private group read only setting is the same as what it would be changed to.'); + return API.v1.failure('The private group read only setting is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult.rid, 'readOnly', this.bodyParams.readOnly); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setTopic', { authRequired: true }, { +API.v1.addRoute('groups.setTopic', { authRequired: true }, { post() { if (!this.bodyParams.topic || !this.bodyParams.topic.trim()) { - return RocketChat.API.v1.failure('The bodyParam "topic" is required'); + return API.v1.failure('The bodyParam "topic" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -699,38 +702,38 @@ RocketChat.API.v1.addRoute('groups.setTopic', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomTopic', this.bodyParams.topic); }); - return RocketChat.API.v1.success({ + return API.v1.success({ topic: this.bodyParams.topic, }); }, }); -RocketChat.API.v1.addRoute('groups.setType', { authRequired: true }, { +API.v1.addRoute('groups.setType', { authRequired: true }, { post() { if (!this.bodyParams.type || !this.bodyParams.type.trim()) { - return RocketChat.API.v1.failure('The bodyParam "type" is required'); + return API.v1.failure('The bodyParam "type" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); if (findResult.t === this.bodyParams.type) { - return RocketChat.API.v1.failure('The private group type is the same as what it would be changed to.'); + return API.v1.failure('The private group type is the same as what it would be changed to.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('saveRoomSettings', findResult.rid, 'roomType', this.bodyParams.type); }); - return RocketChat.API.v1.success({ - group: this.composeRoomWithLastMessage(RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }), this.userId), + return API.v1.success({ + group: this.composeRoomWithLastMessage(Rooms.findOneById(findResult.rid, { fields: API.v1.defaultFieldsToExclude }), this.userId), }); }, }); -RocketChat.API.v1.addRoute('groups.setAnnouncement', { authRequired: true }, { +API.v1.addRoute('groups.setAnnouncement', { authRequired: true }, { post() { if (!this.bodyParams.announcement || !this.bodyParams.announcement.trim()) { - return RocketChat.API.v1.failure('The bodyParam "announcement" is required'); + return API.v1.failure('The bodyParam "announcement" is required'); } const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); @@ -739,13 +742,13 @@ RocketChat.API.v1.addRoute('groups.setAnnouncement', { authRequired: true }, { Meteor.call('saveRoomSettings', findResult.rid, 'roomAnnouncement', this.bodyParams.announcement); }); - return RocketChat.API.v1.success({ + return API.v1.success({ announcement: this.bodyParams.announcement, }); }, }); -RocketChat.API.v1.addRoute('groups.unarchive', { authRequired: true }, { +API.v1.addRoute('groups.unarchive', { authRequired: true }, { post() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false }); @@ -753,29 +756,29 @@ RocketChat.API.v1.addRoute('groups.unarchive', { authRequired: true }, { Meteor.call('unarchiveRoom', findResult.rid); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('groups.roles', { authRequired: true }, { +API.v1.addRoute('groups.roles', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); const roles = Meteor.runAsUser(this.userId, () => Meteor.call('getRoomRoles', findResult.rid)); - return RocketChat.API.v1.success({ + return API.v1.success({ roles, }); }, }); -RocketChat.API.v1.addRoute('groups.moderators', { authRequired: true }, { +API.v1.addRoute('groups.moderators', { authRequired: true }, { get() { const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId }); - const moderators = RocketChat.models.Subscriptions.findByRoomIdAndRoles(findResult.rid, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); + const moderators = Subscriptions.findByRoomIdAndRoles(findResult.rid, ['moderator'], { fields: { u: 1 } }).fetch().map((sub) => sub.u); - return RocketChat.API.v1.success({ + return API.v1.success({ moderators, }); }, diff --git a/packages/rocketchat-api/server/v1/im.js b/packages/rocketchat-api/server/v1/im.js index f560bed0449e..763dc8def581 100644 --- a/packages/rocketchat-api/server/v1/im.js +++ b/packages/rocketchat-api/server/v1/im.js @@ -1,5 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Uploads, Users, Messages, Rooms } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { API } from '../api'; function findDirectMessageRoom(params, user) { if ((!params.roomId || !params.roomId.trim()) && (!params.username || !params.username.trim())) { @@ -16,7 +21,7 @@ function findDirectMessageRoom(params, user) { throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "username" param provided does not match any dirct message'); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id); + const subscription = Subscriptions.findOneByRoomIdAndUserId(room._id, user._id); return { room, @@ -24,35 +29,35 @@ function findDirectMessageRoom(params, user) { }; } -RocketChat.API.v1.addRoute(['dm.create', 'im.create'], { authRequired: true }, { +API.v1.addRoute(['dm.create', 'im.create'], { authRequired: true }, { post() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); - return RocketChat.API.v1.success({ + return API.v1.success({ room: findResult.room, }); }, }); -RocketChat.API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, { +API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, { post() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); if (!findResult.subscription.open) { - return RocketChat.API.v1.failure(`The direct message room, ${ this.bodyParams.name }, is already closed to the sender`); + return API.v1.failure(`The direct message room, ${ this.bodyParams.name }, is already closed to the sender`); } Meteor.runAsUser(this.userId, () => { Meteor.call('hideRoom', findResult.room._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, { +API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, { get() { - const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration'); + const access = hasPermission(this.userId, 'view-room-administration'); const ruserId = this.requestParams().userId; let user = this.userId; let unreads = null; @@ -66,7 +71,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true if (ruserId) { if (!access) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } user = ruserId; } @@ -90,7 +95,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true members = room.usersCount; } - return RocketChat.API.v1.success({ + return API.v1.success({ joined, members, unreads, @@ -102,7 +107,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, }); -RocketChat.API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, { +API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); const addUserObjectToEveryObject = (file) => { @@ -117,23 +122,23 @@ RocketChat.API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, { const ourQuery = Object.assign({}, query, { rid: findResult.room._id }); - const files = RocketChat.models.Uploads.find(ourQuery, { + const files = Uploads.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ files: files.map(addUserObjectToEveryObject), count: files.length, offset, - total: RocketChat.models.Uploads.find(ourQuery).count(), + total: Uploads.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, { +API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -169,20 +174,20 @@ RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, }); if (!result) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, { +API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); const { offset, count } = this.getPaginationItems(); const { sort } = this.parseJsonQuery(); - const cursor = RocketChat.models.Subscriptions.findByRoomId(findResult.room._id, { + const cursor = Subscriptions.findByRoomId(findResult.room._id, { sort: { 'u.username': sort && sort.username ? sort.username : 1 }, skip: offset, limit: count, @@ -191,12 +196,12 @@ RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, const total = cursor.count(); const members = cursor.fetch().map((s) => s.u && s.u.username); - const users = RocketChat.models.Users.find({ username: { $in: members } }, { + const users = Users.find({ username: { $in: members } }, { fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 }, sort: { username: sort && sort.username ? sort.username : 1 }, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ members: users, count: members.length, offset, @@ -205,7 +210,7 @@ RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, }, }); -RocketChat.API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true }, { +API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true }, { get() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -214,30 +219,30 @@ RocketChat.API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true const ourQuery = Object.assign({}, query, { rid: findResult.room._id }); - const messages = RocketChat.models.Messages.find(ourQuery, { + const messages = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ - messages: messages.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: messages.map((message) => composeMessageObjectWithUser(message, this.userId)), count: messages.length, offset, - total: RocketChat.models.Messages.find(ourQuery).count(), + total: Messages.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authRequired: true }, { +API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authRequired: true }, { get() { - if (RocketChat.settings.get('API_Enable_Direct_Message_History_EndPoint') !== true) { + if (settings.get('API_Enable_Direct_Message_History_EndPoint') !== true) { throw new Meteor.Error('error-endpoint-disabled', 'This endpoint is disabled', { route: '/api/v1/im.messages.others' }); } - if (!RocketChat.authz.hasPermission(this.userId, 'view-room-administration')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-room-administration')) { + return API.v1.unauthorized(); } const { roomId } = this.queryParams; @@ -245,7 +250,7 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" is required'); } - const room = RocketChat.models.Rooms.findOneById(roomId); + const room = Rooms.findOneById(roomId); if (!room || room.t !== 'd') { throw new Meteor.Error('error-room-not-found', `No direct message room found by the id of: ${ roomId }`); } @@ -254,30 +259,30 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { rid: room._id }); - const msgs = RocketChat.models.Messages.find(ourQuery, { + const msgs = Messages.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ - messages: msgs.map((message) => RocketChat.composeMessageObjectWithUser(message, this.userId)), + return API.v1.success({ + messages: msgs.map((message) => composeMessageObjectWithUser(message, this.userId)), offset, count: msgs.length, - total: RocketChat.models.Messages.find(ourQuery).count(), + total: Messages.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { +API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort = { name: 1 }, fields } = this.parseJsonQuery(); // TODO: CACHE: Add Breacking notice since we removed the query param - const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('d', this.userId, { + const cursor = Rooms.findBySubscriptionTypeAndUserId('d', this.userId, { sort, skip: offset, limit: count, @@ -287,7 +292,7 @@ RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { const total = cursor.count(); const rooms = cursor.fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ ims: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, @@ -296,10 +301,10 @@ RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequired: true }, { +API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-room-administration')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-room-administration')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); @@ -307,23 +312,23 @@ RocketChat.API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequi const ourQuery = Object.assign({}, query, { t: 'd' }); - const rooms = RocketChat.models.Rooms.find(ourQuery, { + const rooms = Rooms.find(ourQuery, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ ims: rooms.map((room) => this.composeRoomWithLastMessage(room, this.userId)), offset, count: rooms.length, - total: RocketChat.models.Rooms.find(ourQuery).count(), + total: Rooms.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, { +API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, { post() { const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -333,14 +338,14 @@ RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, { }); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true }, { +API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true }, { post() { if (!this.bodyParams.topic || !this.bodyParams.topic.trim()) { - return RocketChat.API.v1.failure('The bodyParam "topic" is required'); + return API.v1.failure('The bodyParam "topic" is required'); } const findResult = findDirectMessageRoom(this.requestParams(), this.user); @@ -349,7 +354,7 @@ RocketChat.API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true Meteor.call('saveRoomSettings', findResult.room._id, 'roomTopic', this.bodyParams.topic); }); - return RocketChat.API.v1.success({ + return API.v1.success({ topic: this.bodyParams.topic, }); }, diff --git a/packages/rocketchat-api/server/v1/import.js b/packages/rocketchat-api/server/v1/import.js index acd596e47e83..a68788a40a55 100644 --- a/packages/rocketchat-api/server/v1/import.js +++ b/packages/rocketchat-api/server/v1/import.js @@ -1,33 +1,33 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('uploadImportFile', { authRequired: true }, { +API.v1.addRoute('uploadImportFile', { authRequired: true }, { post() { const { binaryContent, contentType, fileName, importerKey } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('uploadImportFile', binaryContent, contentType, fileName, importerKey)); + API.v1.success(Meteor.call('uploadImportFile', binaryContent, contentType, fileName, importerKey)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('downloadPublicImportFile', { authRequired: true }, { +API.v1.addRoute('downloadPublicImportFile', { authRequired: true }, { post() { const { fileUrl, importerKey } = this.bodyParams; Meteor.runAsUser(this.userId, () => { - RocketChat.API.v1.success(Meteor.call('downloadPublicImportFile', fileUrl, importerKey)); + API.v1.success(Meteor.call('downloadPublicImportFile', fileUrl, importerKey)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('getImportFileData', { authRequired: true }, { +API.v1.addRoute('getImportFileData', { authRequired: true }, { get() { const { importerKey } = this.requestParams(); let result; @@ -35,16 +35,16 @@ RocketChat.API.v1.addRoute('getImportFileData', { authRequired: true }, { result = Meteor.call('getImportFileData', importerKey); }); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('getLatestImportOperations', { authRequired: true }, { +API.v1.addRoute('getLatestImportOperations', { authRequired: true }, { get() { let result; Meteor.runAsUser(this.userId, () => result = Meteor.call('getLatestImportOperations')); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); diff --git a/packages/rocketchat-api/server/v1/integrations.js b/packages/rocketchat-api/server/v1/integrations.js index 8b47074daa6a..49e6e0a2c974 100644 --- a/packages/rocketchat-api/server/v1/integrations.js +++ b/packages/rocketchat-api/server/v1/integrations.js @@ -1,8 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { IntegrationHistory, Integrations } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('integrations.create', { authRequired: true }, { +API.v1.addRoute('integrations.create', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ type: String, @@ -36,21 +38,21 @@ RocketChat.API.v1.addRoute('integrations.create', { authRequired: true }, { }); break; default: - return RocketChat.API.v1.failure('Invalid integration type.'); + return API.v1.failure('Invalid integration type.'); } - return RocketChat.API.v1.success({ integration }); + return API.v1.success({ integration }); }, }); -RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, { +API.v1.addRoute('integrations.history', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } if (!this.queryParams.id || this.queryParams.id.trim() === '') { - return RocketChat.API.v1.failure('Invalid integration id.'); + return API.v1.failure('Invalid integration id.'); } const { id } = this.queryParams; @@ -58,49 +60,49 @@ RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, { const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query, { 'integration._id': id }); - const history = RocketChat.models.IntegrationHistory.find(ourQuery, { + const history = IntegrationHistory.find(ourQuery, { sort: sort ? sort : { _updatedAt: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ history, offset, items: history.length, - total: RocketChat.models.IntegrationHistory.find(ourQuery).count(), + total: IntegrationHistory.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('integrations.list', { authRequired: true }, { +API.v1.addRoute('integrations.list', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-integrations')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'manage-integrations')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); const ourQuery = Object.assign({}, query); - const integrations = RocketChat.models.Integrations.find(ourQuery, { + const integrations = Integrations.find(ourQuery, { sort: sort ? sort : { ts: -1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ integrations, offset, items: integrations.length, - total: RocketChat.models.Integrations.find(ourQuery).count(), + total: Integrations.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, { +API.v1.addRoute('integrations.remove', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ type: String, @@ -109,45 +111,45 @@ RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, { })); if (!this.bodyParams.target_url && !this.bodyParams.integrationId) { - return RocketChat.API.v1.failure('An integrationId or target_url needs to be provided.'); + return API.v1.failure('An integrationId or target_url needs to be provided.'); } let integration; switch (this.bodyParams.type) { case 'webhook-outgoing': if (this.bodyParams.target_url) { - integration = RocketChat.models.Integrations.findOne({ urls: this.bodyParams.target_url }); + integration = Integrations.findOne({ urls: this.bodyParams.target_url }); } else if (this.bodyParams.integrationId) { - integration = RocketChat.models.Integrations.findOne({ _id: this.bodyParams.integrationId }); + integration = Integrations.findOne({ _id: this.bodyParams.integrationId }); } if (!integration) { - return RocketChat.API.v1.failure('No integration found.'); + return API.v1.failure('No integration found.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('deleteOutgoingIntegration', integration._id); }); - return RocketChat.API.v1.success({ + return API.v1.success({ integration, }); case 'webhook-incoming': - integration = RocketChat.models.Integrations.findOne({ _id: this.bodyParams.integrationId }); + integration = Integrations.findOne({ _id: this.bodyParams.integrationId }); if (!integration) { - return RocketChat.API.v1.failure('No integration found.'); + return API.v1.failure('No integration found.'); } Meteor.runAsUser(this.userId, () => { Meteor.call('deleteIncomingIntegration', integration._id); }); - return RocketChat.API.v1.success({ + return API.v1.success({ integration, }); default: - return RocketChat.API.v1.failure('Invalid integration type.'); + return API.v1.failure('Invalid integration type.'); } }, }); From c6db2d5766a19c57bb8fe5aa5f926228ec975b8b Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 13:41:14 -0200 Subject: [PATCH 029/101] Partial Remove dependency of RC namespace in rc-api --- packages/rocketchat-api/server/index.js | 2 +- packages/rocketchat-api/server/v1/misc.js | 48 +++--- .../rocketchat-api/server/v1/permissions.js | 34 ++-- packages/rocketchat-api/server/v1/push.js | 10 +- packages/rocketchat-api/server/v1/roles.js | 21 +-- packages/rocketchat-api/server/v1/rooms.js | 57 +++---- packages/rocketchat-api/server/v1/settings.js | 58 +++---- packages/rocketchat-api/server/v1/stats.js | 20 ++- .../rocketchat-api/server/v1/subscriptions.js | 25 +-- packages/rocketchat-api/server/v1/users.js | 156 +++++++++--------- .../server/v1/video-conference.js | 10 +- 11 files changed, 229 insertions(+), 212 deletions(-) diff --git a/packages/rocketchat-api/server/index.js b/packages/rocketchat-api/server/index.js index 1c6c5b0277c0..483de4253475 100644 --- a/packages/rocketchat-api/server/index.js +++ b/packages/rocketchat-api/server/index.js @@ -1,5 +1,5 @@ import './settings'; -import './api'; +export { API } from './api'; import './helpers/composeRoomWithLastMessage'; import './helpers/deprecationWarning'; import './helpers/getLoggedInUser'; diff --git a/packages/rocketchat-api/server/v1/misc.js b/packages/rocketchat-api/server/v1/misc.js index 97efb021f569..7528fe4f0bb9 100644 --- a/packages/rocketchat-api/server/v1/misc.js +++ b/packages/rocketchat-api/server/v1/misc.js @@ -1,50 +1,54 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { Info } from 'meteor/rocketchat:utils'; +import { Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('info', { authRequired: false }, { +API.v1.addRoute('info', { authRequired: false }, { get() { const user = this.getLoggedInUser(); - if (user && RocketChat.authz.hasRole(user._id, 'admin')) { - return RocketChat.API.v1.success({ - info: RocketChat.Info, + if (user && hasRole(user._id, 'admin')) { + return API.v1.success({ + info: Info, }); } - return RocketChat.API.v1.success({ + return API.v1.success({ info: { - version: RocketChat.Info.version, + version: Info.version, }, }); }, }); -RocketChat.API.v1.addRoute('me', { authRequired: true }, { +API.v1.addRoute('me', { authRequired: true }, { get() { - return RocketChat.API.v1.success(this.getUserInfo(RocketChat.models.Users.findOneById(this.userId))); + return API.v1.success(this.getUserInfo(Users.findOneById(this.userId))); }, }); let onlineCache = 0; let onlineCacheDate = 0; const cacheInvalid = 60000; // 1 minute -RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { +API.v1.addRoute('shield.svg', { authRequired: false }, { get() { const { type, channel, name, icon } = this.queryParams; - if (!RocketChat.settings.get('API_Enable_Shields')) { + if (!settings.get('API_Enable_Shields')) { throw new Meteor.Error('error-endpoint-disabled', 'This endpoint is disabled', { route: '/api/v1/shield.svg' }); } - const types = RocketChat.settings.get('API_Shield_Types'); + const types = settings.get('API_Shield_Types'); if (type && (types !== '*' && !types.split(',').map((t) => t.trim()).includes(type))) { throw new Meteor.Error('error-shield-disabled', 'This shield type is disabled', { route: '/api/v1/shield.svg' }); } const hideIcon = icon === 'false'; if (hideIcon && (!name || !name.trim())) { - return RocketChat.API.v1.failure('Name cannot be empty when icon is hidden'); + return API.v1.failure('Name cannot be empty when icon is hidden'); } let text; @@ -52,7 +56,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { switch (type) { case 'online': if (Date.now() - onlineCacheDate > cacheInvalid) { - onlineCache = RocketChat.models.Users.findUsersNotOffline().count(); + onlineCache = Users.findUsersNotOffline().count(); onlineCacheDate = Date.now(); } @@ -60,7 +64,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { break; case 'channel': if (!channel) { - return RocketChat.API.v1.failure('Shield channel is required for type "channel"'); + return API.v1.failure('Shield channel is required for type "channel"'); } text = `#${ channel }`; @@ -69,7 +73,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { const user = this.getUserFromParams(); // Respect the server's choice for using their real names or not - if (user.name && RocketChat.settings.get('UI_Use_Real_Name')) { + if (user.name && settings.get('UI_Use_Real_Name')) { text = `${ user.name }`; } else { text = `@${ user.username }`; @@ -127,7 +131,7 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, { }, }); -RocketChat.API.v1.addRoute('spotlight', { authRequired: true }, { +API.v1.addRoute('spotlight', { authRequired: true }, { get() { check(this.queryParams, { query: String, @@ -139,18 +143,18 @@ RocketChat.API.v1.addRoute('spotlight', { authRequired: true }, { Meteor.call('spotlight', query) ); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('directory', { authRequired: true }, { +API.v1.addRoute('directory', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, query } = this.parseJsonQuery(); const { text, type } = query; if (sort && Object.keys(sort).length > 1) { - return RocketChat.API.v1.failure('This method support only one "sort" parameter'); + return API.v1.failure('This method support only one "sort" parameter'); } const sortBy = sort ? Object.keys(sort)[0] : undefined; const sortDirection = sort && Object.values(sort)[0] === 1 ? 'asc' : 'desc'; @@ -165,9 +169,9 @@ RocketChat.API.v1.addRoute('directory', { authRequired: true }, { })); if (!result) { - return RocketChat.API.v1.failure('Please verify the parameters'); + return API.v1.failure('Please verify the parameters'); } - return RocketChat.API.v1.success({ + return API.v1.success({ result: result.results, count: result.results.length, offset, diff --git a/packages/rocketchat-api/server/v1/permissions.js b/packages/rocketchat-api/server/v1/permissions.js index 4bbe0707336b..369c72a73909 100644 --- a/packages/rocketchat-api/server/v1/permissions.js +++ b/packages/rocketchat-api/server/v1/permissions.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Permissions, Roles } from 'meteor/rocketchat:models'; +import { API } from '../api'; /** This API returns all permissions that exists @@ -9,24 +11,24 @@ import { RocketChat } from 'meteor/rocketchat:lib'; Method: GET Route: api/v1/permissions */ -RocketChat.API.v1.addRoute('permissions', { authRequired: true }, { +API.v1.addRoute('permissions', { authRequired: true }, { get() { const warningMessage = 'The endpoint "permissions" is deprecated and will be removed after version v0.69'; console.warn(warningMessage); const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get')); - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); // DEPRECATED // TODO: Remove this after three versions have been released. That means at 0.85 this should be gone. -RocketChat.API.v1.addRoute('permissions.list', { authRequired: true }, { +API.v1.addRoute('permissions.list', { authRequired: true }, { get() { const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get')); - return RocketChat.API.v1.success(this.deprecationWarning({ + return API.v1.success(this.deprecationWarning({ endpoint: 'permissions.list', versionWillBeRemove: '0.85', response: { @@ -36,7 +38,7 @@ RocketChat.API.v1.addRoute('permissions.list', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('permissions.listAll', { authRequired: true }, { +API.v1.addRoute('permissions.listAll', { authRequired: true }, { get() { const { updatedSince } = this.queryParams; @@ -59,14 +61,14 @@ RocketChat.API.v1.addRoute('permissions.listAll', { authRequired: true }, { }; } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, { +API.v1.addRoute('permissions.update', { authRequired: true }, { post() { - if (!RocketChat.authz.hasPermission(this.userId, 'access-permissions')) { - return RocketChat.API.v1.failure('Editing permissions is not allowed', 'error-edit-permissions-not-allowed'); + if (!hasPermission(this.userId, 'access-permissions')) { + return API.v1.failure('Editing permissions is not allowed', 'error-edit-permissions-not-allowed'); } check(this.bodyParams, { @@ -83,34 +85,34 @@ RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, { Object.keys(this.bodyParams.permissions).forEach((key) => { const element = this.bodyParams.permissions[key]; - if (!RocketChat.models.Permissions.findOneById(element._id)) { + if (!Permissions.findOneById(element._id)) { permissionNotFound = true; } Object.keys(element.roles).forEach((key) => { const subelement = element.roles[key]; - if (!RocketChat.models.Roles.findOneById(subelement)) { + if (!Roles.findOneById(subelement)) { roleNotFound = true; } }); }); if (permissionNotFound) { - return RocketChat.API.v1.failure('Invalid permission', 'error-invalid-permission'); + return API.v1.failure('Invalid permission', 'error-invalid-permission'); } else if (roleNotFound) { - return RocketChat.API.v1.failure('Invalid role', 'error-invalid-role'); + return API.v1.failure('Invalid role', 'error-invalid-role'); } Object.keys(this.bodyParams.permissions).forEach((key) => { const element = this.bodyParams.permissions[key]; - RocketChat.models.Permissions.createOrUpdate(element._id, element.roles); + Permissions.createOrUpdate(element._id, element.roles); }); const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get')); - return RocketChat.API.v1.success({ + return API.v1.success({ permissions: result, }); }, diff --git a/packages/rocketchat-api/server/v1/push.js b/packages/rocketchat-api/server/v1/push.js index 50b46f79e62a..fa5b2a70f652 100644 --- a/packages/rocketchat-api/server/v1/push.js +++ b/packages/rocketchat-api/server/v1/push.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Push } from 'meteor/rocketchat:push'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('push.token', { authRequired: true }, { +API.v1.addRoute('push.token', { authRequired: true }, { post() { const { type, value, appName } = this.bodyParams; let { id } = this.bodyParams; @@ -35,7 +35,7 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, { userId: this.userId, })); - return RocketChat.API.v1.success({ result }); + return API.v1.success({ result }); }, delete() { const { token } = this.bodyParams; @@ -54,9 +54,9 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, { }); if (affectedRecords === 0) { - return RocketChat.API.v1.notFound(); + return API.v1.notFound(); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/roles.js b/packages/rocketchat-api/server/v1/roles.js index 08addfb62d80..e7fba691e97b 100644 --- a/packages/rocketchat-api/server/v1/roles.js +++ b/packages/rocketchat-api/server/v1/roles.js @@ -1,16 +1,17 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Roles } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('roles.list', { authRequired: true }, { +API.v1.addRoute('roles.list', { authRequired: true }, { get() { - const roles = RocketChat.models.Roles.find({}, { fields: { _updatedAt: 0 } }).fetch(); + const roles = Roles.find({}, { fields: { _updatedAt: 0 } }).fetch(); - return RocketChat.API.v1.success({ roles }); + return API.v1.success({ roles }); }, }); -RocketChat.API.v1.addRoute('roles.create', { authRequired: true }, { +API.v1.addRoute('roles.create', { authRequired: true }, { post() { check(this.bodyParams, { name: String, @@ -28,13 +29,13 @@ RocketChat.API.v1.addRoute('roles.create', { authRequired: true }, { Meteor.call('authorization:saveRole', roleData); }); - return RocketChat.API.v1.success({ - role: RocketChat.models.Roles.findOneByIdOrName(roleData.name, { fields: RocketChat.API.v1.defaultFieldsToExclude }), + return API.v1.success({ + role: Roles.findOneByIdOrName(roleData.name, { fields: API.v1.defaultFieldsToExclude }), }); }, }); -RocketChat.API.v1.addRoute('roles.addUserToRole', { authRequired: true }, { +API.v1.addRoute('roles.addUserToRole', { authRequired: true }, { post() { check(this.bodyParams, { roleName: String, @@ -48,8 +49,8 @@ RocketChat.API.v1.addRoute('roles.addUserToRole', { authRequired: true }, { Meteor.call('authorization:addUserToRole', this.bodyParams.roleName, user.username, this.bodyParams.roomId); }); - return RocketChat.API.v1.success({ - role: RocketChat.models.Roles.findOneByIdOrName(this.bodyParams.roleName, { fields: RocketChat.API.v1.defaultFieldsToExclude }), + return API.v1.success({ + role: Roles.findOneByIdOrName(this.bodyParams.roleName, { fields: API.v1.defaultFieldsToExclude }), }); }, }); diff --git a/packages/rocketchat-api/server/v1/rooms.js b/packages/rocketchat-api/server/v1/rooms.js index b913fe18ea0e..9a0b99984f2d 100644 --- a/packages/rocketchat-api/server/v1/rooms.js +++ b/packages/rocketchat-api/server/v1/rooms.js @@ -1,20 +1,21 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { Rooms } from 'meteor/rocketchat:models'; import Busboy from 'busboy'; +import { API } from '../api'; function findRoomByIdOrName({ params, checkedArchived = true }) { if ((!params.roomId || !params.roomId.trim()) && (!params.roomName || !params.roomName.trim())) { throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" or "roomName" is required'); } - const fields = { ...RocketChat.API.v1.defaultFieldsToExclude }; + const fields = { ...API.v1.defaultFieldsToExclude }; let room; if (params.roomId) { - room = RocketChat.models.Rooms.findOneById(params.roomId, { fields }); + room = Rooms.findOneById(params.roomId, { fields }); } else if (params.roomName) { - room = RocketChat.models.Rooms.findOneByName(params.roomName, { fields }); + room = Rooms.findOneByName(params.roomName, { fields }); } if (!room) { throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "roomName" param provided does not match any channel'); @@ -26,7 +27,7 @@ function findRoomByIdOrName({ params, checkedArchived = true }) { return room; } -RocketChat.API.v1.addRoute('rooms.get', { authRequired: true }, { +API.v1.addRoute('rooms.get', { authRequired: true }, { get() { const { updatedSince } = this.queryParams; @@ -49,19 +50,19 @@ RocketChat.API.v1.addRoute('rooms.get', { authRequired: true }, { }; } - return RocketChat.API.v1.success({ + return API.v1.success({ update: result.update.map((room) => this.composeRoomWithLastMessage(room, this.userId)), remove: result.remove.map((room) => this.composeRoomWithLastMessage(room, this.userId)), }); }, }); -RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { +API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { post() { const room = Meteor.call('canAccessRoom', this.urlParams.rid, this.userId); if (!room) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const busboy = new Busboy({ headers: this.request.headers }); @@ -90,11 +91,11 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { })(); if (files.length === 0) { - return RocketChat.API.v1.failure('File required'); + return API.v1.failure('File required'); } if (files.length > 1) { - return RocketChat.API.v1.failure('Just 1 file is allowed'); + return API.v1.failure('Just 1 file is allowed'); } const file = files[0]; @@ -116,14 +117,14 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, { delete fields.description; - RocketChat.API.v1.success(Meteor.call('sendFileMessage', this.urlParams.rid, null, uploadedFile, fields)); + API.v1.success(Meteor.call('sendFileMessage', this.urlParams.rid, null, uploadedFile, fields)); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, { +API.v1.addRoute('rooms.saveNotification', { authRequired: true }, { post() { const saveNotifications = (notifications, roomId) => { Object.keys(notifications).forEach((notificationKey) => @@ -135,45 +136,45 @@ RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, { const { roomId, notifications } = this.bodyParams; if (!roomId) { - return RocketChat.API.v1.failure('The \'roomId\' param is required'); + return API.v1.failure('The \'roomId\' param is required'); } if (!notifications || Object.keys(notifications).length === 0) { - return RocketChat.API.v1.failure('The \'notifications\' param is required'); + return API.v1.failure('The \'notifications\' param is required'); } saveNotifications(notifications, roomId); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.favorite', { authRequired: true }, { +API.v1.addRoute('rooms.favorite', { authRequired: true }, { post() { const { favorite } = this.bodyParams; if (!this.bodyParams.hasOwnProperty('favorite')) { - return RocketChat.API.v1.failure('The \'favorite\' param is required'); + return API.v1.failure('The \'favorite\' param is required'); } const room = findRoomByIdOrName({ params: this.bodyParams }); Meteor.runAsUser(this.userId, () => Meteor.call('toggleFavorite', room._id, favorite)); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, { +API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, { post() { const findResult = findRoomByIdOrName({ params: this.bodyParams }); if (!this.bodyParams.latest) { - return RocketChat.API.v1.failure('Body parameter "latest" is required.'); + return API.v1.failure('Body parameter "latest" is required.'); } if (!this.bodyParams.oldest) { - return RocketChat.API.v1.failure('Body parameter "oldest" is required.'); + return API.v1.failure('Body parameter "oldest" is required.'); } const latest = new Date(this.bodyParams.latest); @@ -192,28 +193,28 @@ RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, { fromUsers: this.bodyParams.users, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('rooms.info', { authRequired: true }, { +API.v1.addRoute('rooms.info', { authRequired: true }, { get() { const room = findRoomByIdOrName({ params: this.requestParams() }); const { fields } = this.parseJsonQuery(); if (!Meteor.call('canAccessRoom', room._id, this.userId, {})) { - return RocketChat.API.v1.failure('not-allowed', 'Not Allowed'); + return API.v1.failure('not-allowed', 'Not Allowed'); } - return RocketChat.API.v1.success({ room: RocketChat.models.Rooms.findOneByIdOrName(room._id, { fields }) }); + return API.v1.success({ room: Rooms.findOneByIdOrName(room._id, { fields }) }); }, }); -RocketChat.API.v1.addRoute('rooms.leave', { authRequired: true }, { +API.v1.addRoute('rooms.leave', { authRequired: true }, { post() { const room = findRoomByIdOrName({ params: this.bodyParams }); Meteor.runAsUser(this.userId, () => { Meteor.call('leaveRoom', room._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/settings.js b/packages/rocketchat-api/server/v1/settings.js index 3ed2a54e11e8..5069a2278dd2 100644 --- a/packages/rocketchat-api/server/v1/settings.js +++ b/packages/rocketchat-api/server/v1/settings.js @@ -1,11 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { ServiceConfiguration } from 'meteor/service-configuration'; +import { Settings } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { API } from '../api'; import _ from 'underscore'; // settings endpoints -RocketChat.API.v1.addRoute('settings.public', { authRequired: false }, { +API.v1.addRoute('settings.public', { authRequired: false }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); @@ -17,23 +19,23 @@ RocketChat.API.v1.addRoute('settings.public', { authRequired: false }, { ourQuery = Object.assign({}, query, ourQuery); - const settings = RocketChat.models.Settings.find(ourQuery, { + const settings = Settings.find(ourQuery, { sort: sort ? sort : { _id: 1 }, skip: offset, limit: count, fields: Object.assign({ _id: 1, value: 1 }, fields), }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ settings, count: settings.length, offset, - total: RocketChat.models.Settings.find(ourQuery).count(), + total: Settings.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('settings.oauth', { authRequired: false }, { +API.v1.addRoute('settings.oauth', { authRequired: false }, { get() { const mountOAuthServices = () => { const oAuthServicesEnabled = ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch(); @@ -55,13 +57,13 @@ RocketChat.API.v1.addRoute('settings.oauth', { authRequired: false }, { }); }; - return RocketChat.API.v1.success({ + return API.v1.success({ services: mountOAuthServices(), }); }, }); -RocketChat.API.v1.addRoute('settings', { authRequired: true }, { +API.v1.addRoute('settings', { authRequired: true }, { get() { const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); @@ -70,71 +72,71 @@ RocketChat.API.v1.addRoute('settings', { authRequired: true }, { hidden: { $ne: true }, }; - if (!RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting')) { + if (!hasPermission(this.userId, 'view-privileged-setting')) { ourQuery.public = true; } ourQuery = Object.assign({}, query, ourQuery); - const settings = RocketChat.models.Settings.find(ourQuery, { + const settings = Settings.find(ourQuery, { sort: sort ? sort : { _id: 1 }, skip: offset, limit: count, fields: Object.assign({ _id: 1, value: 1 }, fields), }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ settings, count: settings.length, offset, - total: RocketChat.models.Settings.find(ourQuery).count(), + total: Settings.find(ourQuery).count(), }); }, }); -RocketChat.API.v1.addRoute('settings/:_id', { authRequired: true }, { +API.v1.addRoute('settings/:_id', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-privileged-setting')) { + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(_.pick(RocketChat.models.Settings.findOneNotHiddenById(this.urlParams._id), '_id', 'value')); + return API.v1.success(_.pick(Settings.findOneNotHiddenById(this.urlParams._id), '_id', 'value')); }, post() { - if (!RocketChat.authz.hasPermission(this.userId, 'edit-privileged-setting')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'edit-privileged-setting')) { + return API.v1.unauthorized(); } // allow special handling of particular setting types - const setting = RocketChat.models.Settings.findOneNotHiddenById(this.urlParams._id); + const setting = Settings.findOneNotHiddenById(this.urlParams._id); if (setting.type === 'action' && this.bodyParams && this.bodyParams.execute) { // execute the configured method Meteor.call(setting.value); - return RocketChat.API.v1.success(); + return API.v1.success(); } if (setting.type === 'color' && this.bodyParams && this.bodyParams.editor && this.bodyParams.value) { - RocketChat.models.Settings.updateOptionsById(this.urlParams._id, { editor: this.bodyParams.editor }); - RocketChat.models.Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value); - return RocketChat.API.v1.success(); + Settings.updateOptionsById(this.urlParams._id, { editor: this.bodyParams.editor }); + Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value); + return API.v1.success(); } check(this.bodyParams, { value: Match.Any, }); - if (RocketChat.models.Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value)) { - return RocketChat.API.v1.success(); + if (Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value)) { + return API.v1.success(); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); }, }); -RocketChat.API.v1.addRoute('service.configurations', { authRequired: false }, { +API.v1.addRoute('service.configurations', { authRequired: false }, { get() { const { ServiceConfiguration } = Package['service-configuration']; - return RocketChat.API.v1.success({ + return API.v1.success({ configurations: ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch(), }); }, diff --git a/packages/rocketchat-api/server/v1/stats.js b/packages/rocketchat-api/server/v1/stats.js index d21a1a66174c..05c10167eb9b 100644 --- a/packages/rocketchat-api/server/v1/stats.js +++ b/packages/rocketchat-api/server/v1/stats.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Statistics } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('statistics', { authRequired: true }, { +API.v1.addRoute('statistics', { authRequired: true }, { get() { let refresh = false; if (typeof this.queryParams.refresh !== 'undefined' && this.queryParams.refresh === 'true') { @@ -13,33 +15,33 @@ RocketChat.API.v1.addRoute('statistics', { authRequired: true }, { stats = Meteor.call('getStatistics', refresh); }); - return RocketChat.API.v1.success({ + return API.v1.success({ statistics: stats, }); }, }); -RocketChat.API.v1.addRoute('statistics.list', { authRequired: true }, { +API.v1.addRoute('statistics.list', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-statistics')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-statistics')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - const statistics = RocketChat.models.Statistics.find(query, { + const statistics = Statistics.find(query, { sort: sort ? sort : { name: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ statistics, count: statistics.length, offset, - total: RocketChat.models.Statistics.find(query).count(), + total: Statistics.find(query).count(), }); }, }); diff --git a/packages/rocketchat-api/server/v1/subscriptions.js b/packages/rocketchat-api/server/v1/subscriptions.js index 9f82c57cf90f..37568d1413ad 100644 --- a/packages/rocketchat-api/server/v1/subscriptions.js +++ b/packages/rocketchat-api/server/v1/subscriptions.js @@ -1,8 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('subscriptions.get', { authRequired: true }, { +API.v1.addRoute('subscriptions.get', { authRequired: true }, { get() { const { updatedSince } = this.queryParams; @@ -25,21 +26,21 @@ RocketChat.API.v1.addRoute('subscriptions.get', { authRequired: true }, { }; } - return RocketChat.API.v1.success(result); + return API.v1.success(result); }, }); -RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, { +API.v1.addRoute('subscriptions.getOne', { authRequired: true }, { get() { const { roomId } = this.requestParams(); if (!roomId) { - return RocketChat.API.v1.failure('The \'roomId\' param is required'); + return API.v1.failure('The \'roomId\' param is required'); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId); + const subscription = Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId); - return RocketChat.API.v1.success({ + return API.v1.success({ subscription, }); }, @@ -53,7 +54,7 @@ RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, { Params: - rid: The rid of the room to be marked as read. */ -RocketChat.API.v1.addRoute('subscriptions.read', { authRequired: true }, { +API.v1.addRoute('subscriptions.read', { authRequired: true }, { post() { check(this.bodyParams, { rid: String, @@ -63,22 +64,22 @@ RocketChat.API.v1.addRoute('subscriptions.read', { authRequired: true }, { Meteor.call('readMessages', this.bodyParams.rid) ); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('subscriptions.unread', { authRequired: true }, { +API.v1.addRoute('subscriptions.unread', { authRequired: true }, { post() { const { roomId, firstUnreadMessage } = this.bodyParams; if (!roomId && (firstUnreadMessage && !firstUnreadMessage._id)) { - return RocketChat.API.v1.failure('At least one of "roomId" or "firstUnreadMessage._id" params is required'); + return API.v1.failure('At least one of "roomId" or "firstUnreadMessage._id" params is required'); } Meteor.runAsUser(this.userId, () => Meteor.call('unreadMessages', firstUnreadMessage, roomId) ); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/users.js b/packages/rocketchat-api/server/v1/users.js index 6969d74d7663..178f5d5d108a 100644 --- a/packages/rocketchat-api/server/v1/users.js +++ b/packages/rocketchat-api/server/v1/users.js @@ -1,11 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { getURL } from 'meteor/rocketchat:utils'; +import { API } from '../api'; import _ from 'underscore'; import Busboy from 'busboy'; -RocketChat.API.v1.addRoute('users.create', { authRequired: true }, { +API.v1.addRoute('users.create', { authRequired: true }, { post() { check(this.bodyParams, { email: String, @@ -43,14 +47,14 @@ RocketChat.API.v1.addRoute('users.create', { authRequired: true }, { }); } - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(newUserId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(newUserId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.delete', { authRequired: true }, { +API.v1.addRoute('users.delete', { authRequired: true }, { post() { - if (!RocketChat.authz.hasPermission(this.userId, 'delete-user')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'delete-user')) { + return API.v1.unauthorized(); } const user = this.getUserFromParams(); @@ -59,17 +63,17 @@ RocketChat.API.v1.addRoute('users.delete', { authRequired: true }, { Meteor.call('deleteUser', user._id); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, { +API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, { post() { const { password } = this.bodyParams; if (!password) { - return RocketChat.API.v1.failure('Body parameter "password" is required.'); + return API.v1.failure('Body parameter "password" is required.'); } - if (!RocketChat.settings.get('Accounts_AllowDeleteOwnAccount')) { + if (!settings.get('Accounts_AllowDeleteOwnAccount')) { throw new Meteor.Error('error-not-allowed', 'Not allowed'); } @@ -77,15 +81,15 @@ RocketChat.API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, { Meteor.call('deleteUserOwnAccount', password); }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, { +API.v1.addRoute('users.getAvatar', { authRequired: false }, { get() { const user = this.getUserFromParams(); - const url = RocketChat.getURL(`/avatar/${ user.username }`, { cdn: false, full: true }); + const url = getURL(`/avatar/${ user.username }`, { cdn: false, full: true }); this.response.setHeader('Location', url); return { @@ -95,11 +99,11 @@ RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, { }, }); -RocketChat.API.v1.addRoute('users.getPresence', { authRequired: true }, { +API.v1.addRoute('users.getPresence', { authRequired: true }, { get() { if (this.isUserFromParams()) { - const user = RocketChat.models.Users.findOneById(this.userId); - return RocketChat.API.v1.success({ + const user = Users.findOneById(this.userId); + return API.v1.success({ presence: user.status, connectionStatus: user.statusConnection, lastLogin: user.lastLogin, @@ -108,13 +112,13 @@ RocketChat.API.v1.addRoute('users.getPresence', { authRequired: true }, { const user = this.getUserFromParams(); - return RocketChat.API.v1.success({ + return API.v1.success({ presence: user.status, }); }, }); -RocketChat.API.v1.addRoute('users.info', { authRequired: true }, { +API.v1.addRoute('users.info', { authRequired: true }, { get() { const { username } = this.getUserFromParams(); const { fields } = this.parseJsonQuery(); @@ -125,12 +129,12 @@ RocketChat.API.v1.addRoute('users.info', { authRequired: true }, { }); if (!result || result.length !== 1) { - return RocketChat.API.v1.failure(`Failed to get the user data for the userId of "${ username }".`); + return API.v1.failure(`Failed to get the user data for the userId of "${ username }".`); } user = result[0]; - if (fields.userRooms === 1 && RocketChat.authz.hasPermission(this.userId, 'view-other-user-channels')) { - user.rooms = RocketChat.models.Subscriptions.findByUserId(user._id, { + if (fields.userRooms === 1 && hasPermission(this.userId, 'view-other-user-channels')) { + user.rooms = Subscriptions.findByUserId(user._id, { fields: { rid: 1, name: 1, @@ -144,41 +148,41 @@ RocketChat.API.v1.addRoute('users.info', { authRequired: true }, { }).fetch(); } - return RocketChat.API.v1.success({ + return API.v1.success({ user, }); }, }); -RocketChat.API.v1.addRoute('users.list', { authRequired: true }, { +API.v1.addRoute('users.list', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'view-d-room')) { - return RocketChat.API.v1.unauthorized(); + if (!hasPermission(this.userId, 'view-d-room')) { + return API.v1.unauthorized(); } const { offset, count } = this.getPaginationItems(); const { sort, fields, query } = this.parseJsonQuery(); - const users = RocketChat.models.Users.find(query, { + const users = Users.find(query, { sort: sort ? sort : { username: 1 }, skip: offset, limit: count, fields, }).fetch(); - return RocketChat.API.v1.success({ + return API.v1.success({ users, count: users.length, offset, - total: RocketChat.models.Users.find(query).count(), + total: Users.find(query).count(), }); }, }); -RocketChat.API.v1.addRoute('users.register', { authRequired: false }, { +API.v1.addRoute('users.register', { authRequired: false }, { post() { if (this.userId) { - return RocketChat.API.v1.failure('Logged in users can not register again.'); + return API.v1.failure('Logged in users can not register again.'); } // We set their username here, so require it @@ -188,7 +192,7 @@ RocketChat.API.v1.addRoute('users.register', { authRequired: false }, { })); if (!RocketChat.checkUsernameAvailability(this.bodyParams.username)) { - return RocketChat.API.v1.failure('Username is already in use'); + return API.v1.failure('Username is already in use'); } // Register the user @@ -197,27 +201,27 @@ RocketChat.API.v1.addRoute('users.register', { authRequired: false }, { // Now set their username Meteor.runAsUser(userId, () => Meteor.call('setUsername', this.bodyParams.username)); - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(userId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.resetAvatar', { authRequired: true }, { +API.v1.addRoute('users.resetAvatar', { authRequired: true }, { post() { const user = this.getUserFromParams(); if (user._id === this.userId) { Meteor.runAsUser(this.userId, () => Meteor.call('resetAvatar')); - } else if (RocketChat.authz.hasPermission(this.userId, 'edit-other-user-info')) { + } else if (hasPermission(this.userId, 'edit-other-user-info')) { Meteor.runAsUser(user._id, () => Meteor.call('resetAvatar')); } else { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { +API.v1.addRoute('users.setAvatar', { authRequired: true }, { post() { check(this.bodyParams, Match.ObjectIncluding({ avatarUrl: Match.Maybe(String), @@ -225,7 +229,7 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { username: Match.Maybe(String), })); - if (!RocketChat.settings.get('Accounts_AllowUserAvatarChange')) { + if (!settings.get('Accounts_AllowUserAvatarChange')) { throw new Meteor.Error('error-not-allowed', 'Change avatar is not allowed', { method: 'users.setAvatar', }); @@ -234,10 +238,10 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { let user; if (this.isUserFromParams()) { user = Meteor.users.findOne(this.userId); - } else if (RocketChat.authz.hasPermission(this.userId, 'edit-other-user-info')) { + } else if (hasPermission(this.userId, 'edit-other-user-info')) { user = this.getUserFromParams(); } else { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } Meteor.runAsUser(user._id, () => { @@ -248,10 +252,10 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { const fields = {}; const getUserFromFormData = (fields) => { if (fields.userId) { - return RocketChat.models.Users.findOneById(fields.userId, { _id: 1 }); + return Users.findOneById(fields.userId, { _id: 1 }); } if (fields.username) { - return RocketChat.models.Users.findOneByUsername(fields.username, { _id: 1 }); + return Users.findOneByUsername(fields.username, { _id: 1 }); } }; @@ -273,7 +277,7 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { return callback(new Meteor.Error('error-invalid-user', 'The optional "userId" or "username" param provided does not match any users')); } const isAnotherUser = this.userId !== user._id; - if (isAnotherUser && !RocketChat.authz.hasPermission(this.userId, 'edit-other-user-info')) { + if (isAnotherUser && !hasPermission(this.userId, 'edit-other-user-info')) { return callback(new Meteor.Error('error-not-allowed', 'Not allowed')); } } @@ -289,11 +293,11 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, { } }); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); -RocketChat.API.v1.addRoute('users.update', { authRequired: true }, { +API.v1.addRoute('users.update', { authRequired: true }, { post() { check(this.bodyParams, { userId: String, @@ -326,11 +330,11 @@ RocketChat.API.v1.addRoute('users.update', { authRequired: true }, { }); } - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(this.bodyParams.userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(this.bodyParams.userId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, { +API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, { post() { check(this.bodyParams, { data: Match.ObjectIncluding({ @@ -353,38 +357,38 @@ RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, { Meteor.runAsUser(this.userId, () => Meteor.call('saveUserProfile', userData, this.bodyParams.customFields)); - return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(this.userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) }); + return API.v1.success({ user: Users.findOneById(this.userId, { fields: API.v1.defaultFieldsToExclude }) }); }, }); -RocketChat.API.v1.addRoute('users.createToken', { authRequired: true }, { +API.v1.addRoute('users.createToken', { authRequired: true }, { post() { const user = this.getUserFromParams(); let data; Meteor.runAsUser(this.userId, () => { data = Meteor.call('createToken', user._id); }); - return data ? RocketChat.API.v1.success({ data }) : RocketChat.API.v1.unauthorized(); + return data ? API.v1.success({ data }) : API.v1.unauthorized(); }, }); -RocketChat.API.v1.addRoute('users.getPreferences', { authRequired: true }, { +API.v1.addRoute('users.getPreferences', { authRequired: true }, { get() { - const user = RocketChat.models.Users.findOneById(this.userId); + const user = Users.findOneById(this.userId); if (user.settings) { const { preferences } = user.settings; preferences.language = user.language; - return RocketChat.API.v1.success({ + return API.v1.success({ preferences, }); } else { - return RocketChat.API.v1.failure(TAPi18n.__('Accounts_Default_User_Preferences_not_available').toUpperCase()); + return API.v1.failure(TAPi18n.__('Accounts_Default_User_Preferences_not_available').toUpperCase()); } }, }); -RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, { +API.v1.addRoute('users.setPreferences', { authRequired: true }, { post() { check(this.bodyParams, { userId: Match.Maybe(String), @@ -437,14 +441,14 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, { } Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); - const user = RocketChat.models.Users.findOneById(userId, { + const user = Users.findOneById(userId, { fields: { 'settings.preferences': 1, language: 1, }, }); - return RocketChat.API.v1.success({ + return API.v1.success({ user: { _id: user._id, settings: { @@ -458,59 +462,59 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, { }, }); -RocketChat.API.v1.addRoute('users.forgotPassword', { authRequired: false }, { +API.v1.addRoute('users.forgotPassword', { authRequired: false }, { post() { const { email } = this.bodyParams; if (!email) { - return RocketChat.API.v1.failure('The \'email\' param is required'); + return API.v1.failure('The \'email\' param is required'); } const emailSent = Meteor.call('sendForgotPasswordEmail', email); if (emailSent) { - return RocketChat.API.v1.success(); + return API.v1.success(); } - return RocketChat.API.v1.failure('User not found'); + return API.v1.failure('User not found'); }, }); -RocketChat.API.v1.addRoute('users.getUsernameSuggestion', { authRequired: true }, { +API.v1.addRoute('users.getUsernameSuggestion', { authRequired: true }, { get() { const result = Meteor.runAsUser(this.userId, () => Meteor.call('getUsernameSuggestion')); - return RocketChat.API.v1.success({ result }); + return API.v1.success({ result }); }, }); -RocketChat.API.v1.addRoute('users.generatePersonalAccessToken', { authRequired: true }, { +API.v1.addRoute('users.generatePersonalAccessToken', { authRequired: true }, { post() { const { tokenName } = this.bodyParams; if (!tokenName) { - return RocketChat.API.v1.failure('The \'tokenName\' param is required'); + return API.v1.failure('The \'tokenName\' param is required'); } const token = Meteor.runAsUser(this.userId, () => Meteor.call('personalAccessTokens:generateToken', { tokenName })); - return RocketChat.API.v1.success({ token }); + return API.v1.success({ token }); }, }); -RocketChat.API.v1.addRoute('users.regeneratePersonalAccessToken', { authRequired: true }, { +API.v1.addRoute('users.regeneratePersonalAccessToken', { authRequired: true }, { post() { const { tokenName } = this.bodyParams; if (!tokenName) { - return RocketChat.API.v1.failure('The \'tokenName\' param is required'); + return API.v1.failure('The \'tokenName\' param is required'); } const token = Meteor.runAsUser(this.userId, () => Meteor.call('personalAccessTokens:regenerateToken', { tokenName })); - return RocketChat.API.v1.success({ token }); + return API.v1.success({ token }); }, }); -RocketChat.API.v1.addRoute('users.getPersonalAccessTokens', { authRequired: true }, { +API.v1.addRoute('users.getPersonalAccessTokens', { authRequired: true }, { get() { - if (!RocketChat.authz.hasPermission(this.userId, 'create-personal-access-tokens')) { + if (!hasPermission(this.userId, 'create-personal-access-tokens')) { throw new Meteor.Error('not-authorized', 'Not Authorized'); } - const loginTokens = RocketChat.models.Users.getLoginTokensByUserId(this.userId).fetch()[0]; + const loginTokens = Users.getLoginTokensByUserId(this.userId).fetch()[0]; const getPersonalAccessTokens = () => loginTokens.services.resume.loginTokens .filter((loginToken) => loginToken.type && loginToken.type === 'personalAccessToken') .map((loginToken) => ({ @@ -519,22 +523,22 @@ RocketChat.API.v1.addRoute('users.getPersonalAccessTokens', { authRequired: true lastTokenPart: loginToken.lastTokenPart, })); - return RocketChat.API.v1.success({ + return API.v1.success({ tokens: loginTokens ? getPersonalAccessTokens() : [], }); }, }); -RocketChat.API.v1.addRoute('users.removePersonalAccessToken', { authRequired: true }, { +API.v1.addRoute('users.removePersonalAccessToken', { authRequired: true }, { post() { const { tokenName } = this.bodyParams; if (!tokenName) { - return RocketChat.API.v1.failure('The \'tokenName\' param is required'); + return API.v1.failure('The \'tokenName\' param is required'); } Meteor.runAsUser(this.userId, () => Meteor.call('personalAccessTokens:removeToken', { tokenName, })); - return RocketChat.API.v1.success(); + return API.v1.success(); }, }); diff --git a/packages/rocketchat-api/server/v1/video-conference.js b/packages/rocketchat-api/server/v1/video-conference.js index 1bcf0ce52581..020f38aac336 100644 --- a/packages/rocketchat-api/server/v1/video-conference.js +++ b/packages/rocketchat-api/server/v1/video-conference.js @@ -1,21 +1,21 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Rooms } from 'meteor/rocketchat:models'; +import { API } from '../api'; -RocketChat.API.v1.addRoute('video-conference/jitsi.update-timeout', { authRequired: true }, { +API.v1.addRoute('video-conference/jitsi.update-timeout', { authRequired: true }, { post() { const { roomId } = this.bodyParams; if (!roomId) { - return RocketChat.API.v1.failure('The "roomId" parameter is required!'); + return API.v1.failure('The "roomId" parameter is required!'); } const room = Rooms.findOneById(roomId); if (!room) { - return RocketChat.API.v1.failure('Room does not exist!'); + return API.v1.failure('Room does not exist!'); } Meteor.runAsUser(this.userId, () => Meteor.call('jitsi:updateTimeout', roomId)); - return RocketChat.API.v1.success({ jitsiTimeout: Rooms.findOneById(roomId).jitsiTimeout }); + return API.v1.success({ jitsiTimeout: Rooms.findOneById(roomId).jitsiTimeout }); }, }); From 06f62e6d17672401c0b7c170f67c5c18805d2db1 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 14:40:45 -0200 Subject: [PATCH 030/101] import API where it was being used by the RC namespace --- .../client/admin/appInstall.js | 9 +- .../rocketchat-apps/client/admin/appLogs.js | 5 +- .../rocketchat-apps/client/admin/appManage.js | 13 +-- packages/rocketchat-apps/client/admin/apps.js | 5 +- .../client/communication/websockets.js | 7 +- .../rocketchat-apps/client/orchestrator.js | 5 +- .../server/communication/rest.js | 83 ++++++++++--------- packages/rocketchat-graphql/package.js | 1 + .../resolvers/channels/createChannel.js | 7 +- .../client/admin/adminImportHistory.js | 3 +- .../client/admin/adminImportPrepare.js | 7 +- packages/rocketchat-importer/package.js | 1 + packages/rocketchat-integrations/package.js | 1 + .../rocketchat-integrations/server/api/api.js | 25 +++--- .../client/lib/RestApiClient.js | 3 - .../client/lib/startup/commands.js | 8 +- packages/rocketchat-lib/package.js | 1 - .../imports/server/rest/departments.js | 39 ++++----- .../imports/server/rest/facebook.js | 3 +- .../imports/server/rest/sms.js | 3 +- .../imports/server/rest/upload.js | 19 +++-- .../imports/server/rest/users.js | 43 +++++----- .../server/api/v1/agent.js | 13 +-- .../server/api/v1/config.js | 9 +- .../server/api/v1/customField.js | 15 ++-- .../server/api/v1/message.js | 45 +++++----- .../server/api/v1/offlineMessage.js | 9 +- .../server/api/v1/pageVisited.js | 9 +- .../rocketchat-livechat/server/api/v1/room.js | 31 +++---- .../server/api/v1/transcript.js | 9 +- .../server/api/v1/videoCall.js | 7 +- .../server/api/v1/visitor.js | 33 ++++---- packages/rocketchat-livestream/package.js | 1 + .../rocketchat-livestream/server/routes.js | 5 +- .../server/oauth/oauth2-server.js | 3 +- packages/rocketchat-videobridge/package.js | 1 + .../server/methods/bbb.js | 3 +- 37 files changed, 257 insertions(+), 227 deletions(-) delete mode 100644 packages/rocketchat-lib/client/lib/RestApiClient.js diff --git a/packages/rocketchat-apps/client/admin/appInstall.js b/packages/rocketchat-apps/client/admin/appInstall.js index f5e15623ef51..df6ea61b65f7 100644 --- a/packages/rocketchat-apps/client/admin/appInstall.js +++ b/packages/rocketchat-apps/client/admin/appInstall.js @@ -10,6 +10,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; +import { API } from 'meteor/rocketchat:api'; Template.appInstall.helpers({ appFile() { @@ -72,9 +73,9 @@ Template.appInstall.events({ let result; if (isUpdating) { - result = await RocketChat.API.post(`apps/${ t.isUpdatingId.get() }`, { url }); + result = await API.post(`apps/${ t.isUpdatingId.get() }`, { url }); } else { - result = await RocketChat.API.post('apps', { url }); + result = await API.post('apps', { url }); } if (result.compilerErrors.length !== 0 || result.app.status === 'compiler_error') { @@ -115,9 +116,9 @@ Template.appInstall.events({ let result; if (isUpdating) { - result = await RocketChat.API.upload(`apps/${ t.isUpdatingId.get() }`, data); + result = await API.upload(`apps/${ t.isUpdatingId.get() }`, data); } else { - result = await RocketChat.API.upload('apps', data); + result = await API.upload('apps', data); } console.log('install result', result); diff --git a/packages/rocketchat-apps/client/admin/appLogs.js b/packages/rocketchat-apps/client/admin/appLogs.js index 865bf4dcbfab..11f1c419b951 100644 --- a/packages/rocketchat-apps/client/admin/appLogs.js +++ b/packages/rocketchat-apps/client/admin/appLogs.js @@ -2,6 +2,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; +import { API } from 'meteor/rocketchat:api'; import moment from 'moment'; import hljs from 'highlight.js'; @@ -17,8 +18,8 @@ Template.appLogs.onCreated(function() { const id = this.id.get(); Promise.all([ - RocketChat.API.get(`apps/${ id }`), - RocketChat.API.get(`apps/${ id }/logs`), + API.get(`apps/${ id }`), + API.get(`apps/${ id }/logs`), ]).then((results) => { instance.app.set(results[0].app); diff --git a/packages/rocketchat-apps/client/admin/appManage.js b/packages/rocketchat-apps/client/admin/appManage.js index 986cd135d9c8..b0a54ad45c36 100644 --- a/packages/rocketchat-apps/client/admin/appManage.js +++ b/packages/rocketchat-apps/client/admin/appManage.js @@ -5,6 +5,7 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { TAPi18next } from 'meteor/tap:i18n'; import { isEmail } from 'meteor/rocketchat:utils'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -21,7 +22,7 @@ function getApps(instance) { return Promise.all([ fetch(`${ HOST }/v1/apps/${ id }?version=${ RocketChat.Info.marketplaceApiVersion }`).then((data) => data.json()), - RocketChat.API.get('apps/').then((result) => result.apps.filter((app) => app.id === id)), + API.get('apps/').then((result) => result.apps.filter((app) => app.id === id)), ]).then(([remoteApps, [localApp]]) => { remoteApps = remoteApps.sort((a, b) => { if (semver.gt(a.version, b.version)) { @@ -114,7 +115,7 @@ Template.appManage.onCreated(function() { return; } - RocketChat.API.get(`apps/${ id }/settings`).then((result) => { + API.get(`apps/${ id }/settings`).then((result) => { _morphSettings(result.settings); }); }; @@ -263,7 +264,7 @@ async function setActivate(actiavate, e, t) { const status = actiavate ? 'manually_enabled' : 'manually_disabled'; try { - const result = await RocketChat.API.post(`apps/${ t.id.get() }/status`, { status }); + const result = await API.post(`apps/${ t.id.get() }/status`, { status }); const info = t.app.get(); info.status = result.status; t.app.set(info); @@ -301,7 +302,7 @@ Template.appManage.events({ 'click .js-uninstall': async(e, t) => { t.ready.set(false); try { - await RocketChat.API.delete(`apps/${ t.id.get() }`); + await API.delete(`apps/${ t.id.get() }`); FlowRouter.go('/admin/apps'); } catch (err) { console.warn('Error:', err); @@ -321,7 +322,7 @@ Template.appManage.events({ const api = app.newVersion ? `apps/${ t.id.get() }` : 'apps/'; - RocketChat.API.post(api, { url }).then(() => { + API.post(api, { url }).then(() => { getApps(t).then(() => { el.prop('disabled', false); el.removeClass('loading'); @@ -371,7 +372,7 @@ Template.appManage.events({ if (toSave.length === 0) { throw 'Nothing to save..'; } - const result = await RocketChat.API.post(`apps/${ t.id.get() }/settings`, undefined, { settings: toSave }); + const result = await API.post(`apps/${ t.id.get() }/settings`, undefined, { settings: toSave }); console.log('Updating results:', result); result.updated.forEach((setting) => { settings[setting.id].value = settings[setting.id].oldValue = setting.value; diff --git a/packages/rocketchat-apps/client/admin/apps.js b/packages/rocketchat-apps/client/admin/apps.js index a12d2a77db9d..929859561f65 100644 --- a/packages/rocketchat-apps/client/admin/apps.js +++ b/packages/rocketchat-apps/client/admin/apps.js @@ -4,6 +4,7 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { t } from 'meteor/rocketchat:utils'; import { AppEvents } from '../communication'; +import { API } from 'meteor/rocketchat:api'; const ENABLED_STATUS = ['auto_enabled', 'manually_enabled']; const HOST = 'https://marketplace.rocket.chat'; @@ -48,7 +49,7 @@ const getApps = (instance) => { const getInstalledApps = (instance) => { - RocketChat.API.get('apps').then((data) => { + API.get('apps').then((data) => { const apps = data.apps.map((app) => ({ latest: app })); instance.installedApps.set(apps); @@ -253,7 +254,7 @@ Template.apps.events({ const url = `${ HOST }/v1/apps/${ this.latest.id }/download/${ this.latest.version }`; - RocketChat.API.post('apps/', { url }).then(() => { + API.post('apps/', { url }).then(() => { getInstalledApps(template); }).catch((e) => { toastr.error((e.xhr.responseJSON && e.xhr.responseJSON.error) || e.message); diff --git a/packages/rocketchat-apps/client/communication/websockets.js b/packages/rocketchat-apps/client/communication/websockets.js index a43c8312c62a..248331cd0ff8 100644 --- a/packages/rocketchat-apps/client/communication/websockets.js +++ b/packages/rocketchat-apps/client/communication/websockets.js @@ -1,4 +1,5 @@ import { Meteor } from 'meteor/meteor'; +import { API } from 'meteor/rocketchat:api'; export const AppEvents = Object.freeze({ APP_ADDED: 'app/added', @@ -49,7 +50,7 @@ export class AppWebsocketReceiver { } onAppAdded(appId) { - RocketChat.API.get(`apps/${ appId }/languages`).then((result) => { + API.get(`apps/${ appId }/languages`).then((result) => { this.orch.parseAndLoadLanguages(result.languages, appId); }); @@ -73,7 +74,7 @@ export class AppWebsocketReceiver { } onCommandAdded(command) { - RocketChat.API.v1.get('commands.get', { command }).then((result) => { + API.v1.get('commands.get', { command }).then((result) => { RocketChat.slashCommands.commands[command] = result.command; }); } @@ -83,7 +84,7 @@ export class AppWebsocketReceiver { } onCommandUpdated(command) { - RocketChat.API.v1.get('commands.get', { command }).then((result) => { + API.v1.get('commands.get', { command }).then((result) => { RocketChat.slashCommands.commands[command] = result.command; }); } diff --git a/packages/rocketchat-apps/client/orchestrator.js b/packages/rocketchat-apps/client/orchestrator.js index fb85e8da85a6..ebe4067a8540 100644 --- a/packages/rocketchat-apps/client/orchestrator.js +++ b/packages/rocketchat-apps/client/orchestrator.js @@ -4,6 +4,7 @@ import { Utilities } from '../lib/misc/Utilities'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; import { TAPi18next } from 'meteor/tap:i18n'; +import { API } from 'meteor/rocketchat:api'; class AppClientOrchestrator { constructor() { @@ -71,7 +72,7 @@ class AppClientOrchestrator { } _loadLanguages() { - return RocketChat.API.get('apps/languages').then((info) => { + return API.get('apps/languages').then((info) => { info.apps.forEach((rlInfo) => this.parseAndLoadLanguages(rlInfo.languages, rlInfo.id)); }); } @@ -92,7 +93,7 @@ class AppClientOrchestrator { } async getAppApis(appId) { - const result = await RocketChat.API.get(`apps/${ appId }/apis`); + const result = await API.get(`apps/${ appId }/apis`); return result.apis; } } diff --git a/packages/rocketchat-apps/server/communication/rest.js b/packages/rocketchat-apps/server/communication/rest.js index 68d30c1bf470..431956037a1f 100644 --- a/packages/rocketchat-apps/server/communication/rest.js +++ b/packages/rocketchat-apps/server/communication/rest.js @@ -1,17 +1,18 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; +import { API } from 'meteor/rocketchat:api'; import Busboy from 'busboy'; export class AppsRestApi { constructor(orch, manager) { this._orch = orch; this._manager = manager; - this.api = new RocketChat.API.ApiClass({ + this.api = new API.ApiClass({ version: 'apps', useDefaultAuth: true, prettyJson: false, enableCors: false, - auth: RocketChat.API.getUserAuth(), + auth: API.getUserAuth(), }); this.addManagementRoutes(); @@ -53,7 +54,7 @@ export class AppsRestApi { return info; }); - return RocketChat.API.v1.success({ apps }); + return API.v1.success({ apps }); }, post() { let buff; @@ -62,7 +63,7 @@ export class AppsRestApi { const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: 'base64' } }); if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') { - return RocketChat.API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); + return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); } buff = Buffer.from(result.content, 'base64'); @@ -71,7 +72,7 @@ export class AppsRestApi { } if (!buff) { - return RocketChat.API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); + return API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); } const aff = Promise.await(manager.add(buff.toString('base64'), false)); @@ -84,7 +85,7 @@ export class AppsRestApi { info.status = 'compiler_error'; } - return RocketChat.API.v1.success({ + return API.v1.success({ app: info, implemented: aff.getImplementedInferfaces(), compilerErrors: aff.getCompilerErrors(), @@ -99,7 +100,7 @@ export class AppsRestApi { languages: prl.getStorageItem().languageContent, })); - return RocketChat.API.v1.success({ apps }); + return API.v1.success({ apps }); }, }); @@ -112,9 +113,9 @@ export class AppsRestApi { const info = prl.getInfo(); info.status = prl.getStatus(); - return RocketChat.API.v1.success({ app: info }); + return API.v1.success({ app: info }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { @@ -127,7 +128,7 @@ export class AppsRestApi { const result = HTTP.call('GET', this.bodyParams.url, { npmRequestOptions: { encoding: 'base64' } }); if (result.statusCode !== 200 || !result.headers['content-type'] || result.headers['content-type'] !== 'application/zip') { - return RocketChat.API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); + return API.v1.failure({ error: 'Invalid url. It doesn\'t exist or is not "application/zip".' }); } buff = Buffer.from(result.content, 'base64'); @@ -136,7 +137,7 @@ export class AppsRestApi { } if (!buff) { - return RocketChat.API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); + return API.v1.failure({ error: 'Failed to get a file to install for the App. ' }); } const aff = Promise.await(manager.update(buff.toString('base64'))); @@ -149,7 +150,7 @@ export class AppsRestApi { info.status = 'compiler_error'; } - return RocketChat.API.v1.success({ + return API.v1.success({ app: info, implemented: aff.getImplementedInferfaces(), compilerErrors: aff.getCompilerErrors(), @@ -165,9 +166,9 @@ export class AppsRestApi { const info = prl.getInfo(); info.status = prl.getStatus(); - return RocketChat.API.v1.success({ app: info }); + return API.v1.success({ app: info }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -180,9 +181,9 @@ export class AppsRestApi { if (prl) { const info = prl.getInfo(); - return RocketChat.API.v1.success({ iconFileContent: info.iconFileContent }); + return API.v1.success({ iconFileContent: info.iconFileContent }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -195,9 +196,9 @@ export class AppsRestApi { if (prl) { const languages = prl.getStorageItem().languageContent || {}; - return RocketChat.API.v1.success({ languages }); + return API.v1.success({ languages }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -221,9 +222,9 @@ export class AppsRestApi { const logs = Promise.await(orchestrator.getLogStorage().find(ourQuery, options)); - return RocketChat.API.v1.success({ logs }); + return API.v1.success({ logs }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -242,21 +243,21 @@ export class AppsRestApi { } }); - return RocketChat.API.v1.success({ settings }); + return API.v1.success({ settings }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { console.log(`Updating ${ this.urlParams.id }'s settings..`); if (!this.bodyParams || !this.bodyParams.settings) { - return RocketChat.API.v1.failure('The settings to update must be present.'); + return API.v1.failure('The settings to update must be present.'); } const prl = manager.getOneById(this.urlParams.id); if (!prl) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } const { settings } = prl.getStorageItem(); @@ -270,7 +271,7 @@ export class AppsRestApi { } }); - return RocketChat.API.v1.success({ updated }); + return API.v1.success({ updated }); }, }); @@ -281,14 +282,14 @@ export class AppsRestApi { try { const setting = manager.getSettingsManager().getAppSetting(this.urlParams.id, this.urlParams.settingId); - RocketChat.API.v1.success({ setting }); + API.v1.success({ setting }); } catch (e) { if (e.message.includes('No setting found')) { - return RocketChat.API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); + return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); } else if (e.message.includes('No App found')) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } else { - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } } }, @@ -296,20 +297,20 @@ export class AppsRestApi { console.log(`Updating the App ${ this.urlParams.id }'s setting ${ this.urlParams.settingId }`); if (!this.bodyParams.setting) { - return RocketChat.API.v1.failure('Setting to update to must be present on the posted body.'); + return API.v1.failure('Setting to update to must be present on the posted body.'); } try { Promise.await(manager.getSettingsManager().updateAppSetting(this.urlParams.id, this.bodyParams.setting)); - return RocketChat.API.v1.success(); + return API.v1.success(); } catch (e) { if (e.message.includes('No setting found')) { - return RocketChat.API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); + return API.v1.notFound(`No Setting found on the App by the id of: "${ this.urlParams.settingId }"`); } else if (e.message.includes('No App found')) { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } else { - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } } }, @@ -321,11 +322,11 @@ export class AppsRestApi { const prl = manager.getOneById(this.urlParams.id); if (prl) { - return RocketChat.API.v1.success({ + return API.v1.success({ apis: manager.apiManager.listApis(this.urlParams.id), }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); @@ -336,14 +337,14 @@ export class AppsRestApi { const prl = manager.getOneById(this.urlParams.id); if (prl) { - return RocketChat.API.v1.success({ status: prl.getStatus() }); + return API.v1.success({ status: prl.getStatus() }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, post() { if (!this.bodyParams.status || typeof this.bodyParams.status !== 'string') { - return RocketChat.API.v1.failure('Invalid status provided, it must be "status" field and a string.'); + return API.v1.failure('Invalid status provided, it must be "status" field and a string.'); } console.log(`Updating ${ this.urlParams.id }'s status...`, this.bodyParams.status); @@ -352,9 +353,9 @@ export class AppsRestApi { if (prl) { const result = Promise.await(manager.changeStatus(prl.getID(), this.bodyParams.status)); - return RocketChat.API.v1.success({ status: result.getStatus() }); + return API.v1.success({ status: result.getStatus() }); } else { - return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); + return API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`); } }, }); diff --git a/packages/rocketchat-graphql/package.js b/packages/rocketchat-graphql/package.js index 87b0c860d278..33c25e41e4ce 100644 --- a/packages/rocketchat-graphql/package.js +++ b/packages/rocketchat-graphql/package.js @@ -13,6 +13,7 @@ Package.onUse(function(api) { 'rocketchat:lib', 'rocketchat:api', 'rocketchat:accounts', + 'rocketchat:integrations', 'swydo:graphql', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js index 5d4c8a154df4..c74398268e84 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/createChannel.js @@ -1,5 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - +import { API } from 'meteor/rocketchat:api'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/createChannel.graphqls'; @@ -7,7 +6,7 @@ const resolver = { Mutation: { createChannel: authenticated((root, args, { user }) => { try { - RocketChat.API.channels.create.validate({ + API.channels.create.validate({ user: { value: user._id, }, @@ -24,7 +23,7 @@ const resolver = { throw e; } - const { channel } = RocketChat.API.channels.create.execute(user._id, { + const { channel } = API.channels.create.execute(user._id, { name: args.name, members: args.membersId, }); diff --git a/packages/rocketchat-importer/client/admin/adminImportHistory.js b/packages/rocketchat-importer/client/admin/adminImportHistory.js index 5b2ee4d5dcfe..76f81a877753 100644 --- a/packages/rocketchat-importer/client/admin/adminImportHistory.js +++ b/packages/rocketchat-importer/client/admin/adminImportHistory.js @@ -7,6 +7,7 @@ import toastr from 'toastr'; import { ReactiveVar } from 'meteor/reactive-var'; import { ProgressStep } from '../../lib/ImporterProgressStep'; import { FlowRouter } from 'meteor/kadira:flow-router'; +import { API } from 'meteor/rocketchat:api'; Template.adminImportHistory.helpers({ isAdmin() { @@ -183,7 +184,7 @@ Template.adminImportHistory.onCreated(function() { this.preparing = new ReactiveVar(true); this.history = new ReactiveVar([]); - RocketChat.API.get('v1/getLatestImportOperations').then((data) => { + API.get('v1/getLatestImportOperations').then((data) => { instance.history.set(data); instance.preparing.set(false); }).catch((error) => { diff --git a/packages/rocketchat-importer/client/admin/adminImportPrepare.js b/packages/rocketchat-importer/client/admin/adminImportPrepare.js index 216301adcb5d..b58c95f61697 100644 --- a/packages/rocketchat-importer/client/admin/adminImportPrepare.js +++ b/packages/rocketchat-importer/client/admin/adminImportPrepare.js @@ -6,6 +6,7 @@ import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat, handleError } from 'meteor/rocketchat:lib'; import { t } from 'meteor/rocketchat:utils'; +import { API } from 'meteor/rocketchat:api'; import toastr from 'toastr'; Template.adminImportPrepare.helpers({ @@ -95,7 +96,7 @@ function showException(error, defaultErrorString) { } function getImportFileData(importer, template) { - RocketChat.API.get(`v1/getImportFileData?importerKey=${ importer.key }`).then((data) => { + API.get(`v1/getImportFileData?importerKey=${ importer.key }`).then((data) => { if (!data) { console.warn(`The importer ${ importer.key } is not set up correctly, as it did not return any data.`); toastr.error(t('Importer_not_setup')); @@ -148,7 +149,7 @@ Template.adminImportPrepare.events({ reader.readAsBinaryString(file); reader.onloadend = () => { - RocketChat.API.post('v1/uploadImportFile', { + API.post('v1/uploadImportFile', { binaryContent: reader.result, contentType: file.type, fileName: file.name, @@ -174,7 +175,7 @@ Template.adminImportPrepare.events({ template.preparing.set(true); - RocketChat.API.post('v1/downloadPublicImportFile', { + API.post('v1/downloadPublicImportFile', { fileUrl, importerKey: importer.key, }).then(() => { diff --git a/packages/rocketchat-importer/package.js b/packages/rocketchat-importer/package.js index 136826523918..71fe8869d538 100644 --- a/packages/rocketchat-importer/package.js +++ b/packages/rocketchat-importer/package.js @@ -12,6 +12,7 @@ Package.onUse(function(api) { 'check', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:logger', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-integrations/package.js b/packages/rocketchat-integrations/package.js index 43f897cb8e47..577a0ee92f32 100644 --- a/packages/rocketchat-integrations/package.js +++ b/packages/rocketchat-integrations/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'ecmascript', 'mongo', 'babel-compiler', + 'rocketchat:api', 'rocketchat:lib', 'rocketchat:authorization', 'rocketchat:theme', diff --git a/packages/rocketchat-integrations/server/api/api.js b/packages/rocketchat-integrations/server/api/api.js index d92b52664ea7..5b8b6b4a05c5 100644 --- a/packages/rocketchat-integrations/server/api/api.js +++ b/packages/rocketchat-integrations/server/api/api.js @@ -3,6 +3,7 @@ import { HTTP } from 'meteor/http'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; +import { API } from 'meteor/rocketchat:api'; import { logger } from '../logger'; import { processWebhookMessage } from '../processWebhookMessage'; import Fiber from 'fibers'; @@ -129,12 +130,12 @@ function getIntegrationScript(integration) { logger.incoming.error(script.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); - throw RocketChat.API.v1.failure('error-evaluating-script'); + throw API.v1.failure('error-evaluating-script'); } if (!sandbox.Script) { logger.incoming.error('[Class "Script" not in Trigger', integration.name, ']'); - throw RocketChat.API.v1.failure('class-script-not-found'); + throw API.v1.failure('class-script-not-found'); } } @@ -172,7 +173,7 @@ function createIntegration(options, user) { } }); - return RocketChat.API.v1.success(); + return API.v1.success(); } function removeIntegration(options, user) { @@ -185,7 +186,7 @@ function removeIntegration(options, user) { Meteor.runAsUser(user._id, () => Meteor.call('deleteOutgoingIntegration', integrationToRemove._id)); - return RocketChat.API.v1.success(); + return API.v1.success(); } function executeIntegrationRest() { @@ -213,7 +214,7 @@ function executeIntegrationRest() { script = getIntegrationScript(this.integration); } catch (e) { logger.incoming.warn(e); - return RocketChat.API.v1.failure(e.message); + return API.v1.failure(e.message); } this.request.setEncoding('utf8'); @@ -262,9 +263,9 @@ function executeIntegrationRest() { if (!result) { logger.incoming.debug('[Process Incoming Request result of Trigger', this.integration.name, ':] No data'); - return RocketChat.API.v1.success(); + return API.v1.success(); } else if (result && result.error) { - return RocketChat.API.v1.failure(result.error); + return API.v1.failure(result.error); } this.bodyParams = result && result.content; @@ -280,7 +281,7 @@ function executeIntegrationRest() { logger.incoming.error(this.integration.scriptCompiled.replace(/^/gm, ' ')); logger.incoming.error('[Stack:]'); logger.incoming.error(stack.replace(/^/gm, ' ')); - return RocketChat.API.v1.failure('error-running-script'); + return API.v1.failure('error-running-script'); } } @@ -288,7 +289,7 @@ function executeIntegrationRest() { // TODO: Temporary fix for https://github.com/RocketChat/Rocket.Chat/issues/7770 until the above is implemented if (!this.bodyParams || (_.isEmpty(this.bodyParams) && !this.integration.scriptEnabled)) { // return RocketChat.API.v1.failure('body-empty'); - return RocketChat.API.v1.success(); + return API.v1.success(); } this.bodyParams.bot = { i: this.integration._id }; @@ -296,16 +297,16 @@ function executeIntegrationRest() { try { const message = processWebhookMessage(this.bodyParams, this.user, defaultValues); if (_.isEmpty(message)) { - return RocketChat.API.v1.failure('unknown-error'); + return API.v1.failure('unknown-error'); } if (this.scriptResponse) { logger.incoming.debug('response', this.scriptResponse); } - return RocketChat.API.v1.success(this.scriptResponse); + return API.v1.success(this.scriptResponse); } catch ({ error, message }) { - return RocketChat.API.v1.failure(error || message); + return API.v1.failure(error || message); } } diff --git a/packages/rocketchat-lib/client/lib/RestApiClient.js b/packages/rocketchat-lib/client/lib/RestApiClient.js deleted file mode 100644 index 9c2d7a9b86e9..000000000000 --- a/packages/rocketchat-lib/client/lib/RestApiClient.js +++ /dev/null @@ -1,3 +0,0 @@ -// import { API } from 'meteor/rocketchat:api'; - -// RocketChat.API = API; diff --git a/packages/rocketchat-lib/client/lib/startup/commands.js b/packages/rocketchat-lib/client/lib/startup/commands.js index 35cc4960da43..d07c7e670ce6 100644 --- a/packages/rocketchat-lib/client/lib/startup/commands.js +++ b/packages/rocketchat-lib/client/lib/startup/commands.js @@ -9,9 +9,11 @@ import { slashCommands } from 'meteor/rocketchat:utils'; Tracker.autorun(() => { const newUserId = Meteor.userId(); if (oldUserId === null && newUserId) { - RocketChat.API.v1.get('commands.list').then(function _loadedCommands(result) { - result.commands.forEach((command) => { - slashCommands.commands[command.command] = command; + import('meteor/rocketchat:api').then(({ API }) => { + API.v1.get('commands.list').then(function _loadedCommands(result) { + result.commands.forEach((command) => { + slashCommands.commands[command.command] = command; + }); }); }); } diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index c8f66f40ee41..4e66b5c7f70a 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -236,7 +236,6 @@ Package.onUse(function(api) { api.addFiles('client/Notifications.js', 'client'); api.addFiles('client/OAuthProxy.js', 'client'); api.addFiles('client/UserDeleted.js', 'client'); - api.addFiles('client/lib/RestApiClient.js', 'client'); api.addFiles('client/lib/TabBar.js', 'client'); api.addFiles('client/lib/RocketChatTabBar.js', 'client'); api.addFiles('client/lib/RocketChatAnnouncement.js', 'client'); diff --git a/packages/rocketchat-livechat/imports/server/rest/departments.js b/packages/rocketchat-livechat/imports/server/rest/departments.js index 296cf37707b7..422d0f492102 100644 --- a/packages/rocketchat-livechat/imports/server/rest/departments.js +++ b/packages/rocketchat-livechat/imports/server/rest/departments.js @@ -1,19 +1,20 @@ import { check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/department', { authRequired: true }, { +API.v1.addRoute('livechat/department', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } - return RocketChat.API.v1.success({ + return API.v1.success({ departments: RocketChat.models.LivechatDepartment.find().fetch(), }); }, post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -25,23 +26,23 @@ RocketChat.API.v1.addRoute('livechat/department', { authRequired: true }, { const department = RocketChat.Livechat.saveDepartment(null, this.bodyParams.department, this.bodyParams.agents); if (department) { - return RocketChat.API.v1.success({ + return API.v1.success({ department, agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: department._id }).fetch(), }); } - RocketChat.API.v1.failure(); + API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { +API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -49,17 +50,17 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { _id: String, }); - return RocketChat.API.v1.success({ + return API.v1.success({ department: RocketChat.models.LivechatDepartment.findOneById(this.urlParams._id), agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: this.urlParams._id }).fetch(), }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, put() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -73,20 +74,20 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { }); if (RocketChat.Livechat.saveDepartment(this.urlParams._id, this.bodyParams.department, this.bodyParams.agents)) { - return RocketChat.API.v1.success({ + return API.v1.success({ department: RocketChat.models.LivechatDepartment.findOneById(this.urlParams._id), agents: RocketChat.models.LivechatDepartmentAgents.find({ departmentId: this.urlParams._id }).fetch(), }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -95,12 +96,12 @@ RocketChat.API.v1.addRoute('livechat/department/:_id', { authRequired: true }, { }); if (RocketChat.Livechat.removeDepartment(this.urlParams._id)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); diff --git a/packages/rocketchat-livechat/imports/server/rest/facebook.js b/packages/rocketchat-livechat/imports/server/rest/facebook.js index a083c649716f..0e05e98d2161 100644 --- a/packages/rocketchat-livechat/imports/server/rest/facebook.js +++ b/packages/rocketchat-livechat/imports/server/rest/facebook.js @@ -1,6 +1,7 @@ import crypto from 'crypto'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; @@ -17,7 +18,7 @@ import LivechatVisitors from '../../../server/models/LivechatVisitors'; * @apiParam {String} [text] Facebook message text * @apiParam {String} [attachments] Facebook message attachments */ -RocketChat.API.v1.addRoute('livechat/facebook', { +API.v1.addRoute('livechat/facebook', { post() { if (!this.bodyParams.text && !this.bodyParams.attachments) { return { diff --git a/packages/rocketchat-livechat/imports/server/rest/sms.js b/packages/rocketchat-livechat/imports/server/rest/sms.js index 4924d9b5cdfb..ce107e278848 100644 --- a/packages/rocketchat-livechat/imports/server/rest/sms.js +++ b/packages/rocketchat-livechat/imports/server/rest/sms.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; -RocketChat.API.v1.addRoute('livechat/sms-incoming/:service', { +API.v1.addRoute('livechat/sms-incoming/:service', { post() { const SMSService = RocketChat.SMS.getService(this.urlParams.service); diff --git a/packages/rocketchat-livechat/imports/server/rest/upload.js b/packages/rocketchat-livechat/imports/server/rest/upload.js index 88310a6e96db..61dd1438bb5f 100644 --- a/packages/rocketchat-livechat/imports/server/rest/upload.js +++ b/packages/rocketchat-livechat/imports/server/rest/upload.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { API } from 'meteor/rocketchat:api'; import Busboy from 'busboy'; import filesize from 'filesize'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; @@ -14,22 +15,22 @@ RocketChat.settings.get('FileUpload_MaxFileSize', function(key, value) { } }); -RocketChat.API.v1.addRoute('livechat/upload/:rid', { +API.v1.addRoute('livechat/upload/:rid', { post() { if (!this.request.headers['x-visitor-token']) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const visitorToken = this.request.headers['x-visitor-token']; const visitor = LivechatVisitors.getVisitorByToken(visitorToken); if (!visitor) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const room = RocketChat.models.Rooms.findOneOpenByRoomIdAndVisitorToken(this.urlParams.rid, visitorToken); if (!room) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const busboy = new Busboy({ headers: this.request.headers }); @@ -58,24 +59,24 @@ RocketChat.API.v1.addRoute('livechat/upload/:rid', { })(); if (files.length === 0) { - return RocketChat.API.v1.failure('File required'); + return API.v1.failure('File required'); } if (files.length > 1) { - return RocketChat.API.v1.failure('Just 1 file is allowed'); + return API.v1.failure('Just 1 file is allowed'); } const file = files[0]; if (!RocketChat.fileUploadIsValidContentType(file.mimetype)) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ reason: 'error-type-not-allowed', }); } // -1 maxFileSize means there is no limit if (maxFileSize > -1 && file.fileBuffer.length > maxFileSize) { - return RocketChat.API.v1.failure({ + return API.v1.failure({ reason: 'error-size-not-allowed', sizeAllowed: filesize(maxFileSize), }); @@ -96,6 +97,6 @@ RocketChat.API.v1.addRoute('livechat/upload/:rid', { uploadedFile.description = fields.description; delete fields.description; - RocketChat.API.v1.success(Meteor.call('sendFileLivechatMessage', this.urlParams.rid, visitorToken, uploadedFile, fields)); + API.v1.success(Meteor.call('sendFileLivechatMessage', this.urlParams.rid, visitorToken, uploadedFile, fields)); }, }); diff --git a/packages/rocketchat-livechat/imports/server/rest/users.js b/packages/rocketchat-livechat/imports/server/rest/users.js index 3245793857e6..3892da0bbb53 100644 --- a/packages/rocketchat-livechat/imports/server/rest/users.js +++ b/packages/rocketchat-livechat/imports/server/rest/users.js @@ -1,11 +1,12 @@ import { check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; -RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { +API.v1.addRoute('livechat/users/:type', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -24,16 +25,16 @@ RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { const users = RocketChat.authz.getUsersInRole(role); - return RocketChat.API.v1.success({ + return API.v1.success({ users: users.fetch().map((user) => _.pick(user, '_id', 'username', 'name', 'status', 'statusLivechat')), }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { check(this.urlParams, { @@ -47,28 +48,28 @@ RocketChat.API.v1.addRoute('livechat/users/:type', { authRequired: true }, { if (this.urlParams.type === 'agent') { const user = RocketChat.Livechat.addAgent(this.bodyParams.username); if (user) { - return RocketChat.API.v1.success({ user }); + return API.v1.success({ user }); } } else if (this.urlParams.type === 'manager') { const user = RocketChat.Livechat.addManager(this.bodyParams.username); if (user) { - return RocketChat.API.v1.success({ user }); + return API.v1.success({ user }); } } else { throw 'Invalid type'; } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, { +API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -80,7 +81,7 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, const user = RocketChat.models.Users.findOneById(this.urlParams._id); if (!user) { - return RocketChat.API.v1.failure('User not found'); + return API.v1.failure('User not found'); } let role; @@ -94,21 +95,21 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, } if (user.roles.indexOf(role) !== -1) { - return RocketChat.API.v1.success({ + return API.v1.success({ user: _.pick(user, '_id', 'username'), }); } - return RocketChat.API.v1.success({ + return API.v1.success({ user: null, }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } try { @@ -120,24 +121,24 @@ RocketChat.API.v1.addRoute('livechat/users/:type/:_id', { authRequired: true }, const user = RocketChat.models.Users.findOneById(this.urlParams._id); if (!user) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } if (this.urlParams.type === 'agent') { if (RocketChat.Livechat.removeAgent(user.username)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } } else if (this.urlParams.type === 'manager') { if (RocketChat.Livechat.removeManager(user.username)) { - return RocketChat.API.v1.success(); + return API.v1.success(); } } else { throw 'Invalid type'; } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/agent.js b/packages/rocketchat-livechat/server/api/v1/agent.js index 655e8bb7db36..d9a50d533e70 100644 --- a/packages/rocketchat-livechat/server/api/v1/agent.js +++ b/packages/rocketchat-livechat/server/api/v1/agent.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findRoom, findGuest, findAgent, findOpenRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/agent.info/:rid/:token', { +API.v1.addRoute('livechat/agent.info/:rid/:token', { get() { try { check(this.urlParams, { @@ -26,14 +27,14 @@ RocketChat.API.v1.addRoute('livechat/agent.info/:rid/:token', { throw new Meteor.Error('invalid-agent'); } - return RocketChat.API.v1.success({ agent }); + return API.v1.success({ agent }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/agent.next/:token', { +API.v1.addRoute('livechat/agent.next/:token', { get() { try { check(this.urlParams, { @@ -68,9 +69,9 @@ RocketChat.API.v1.addRoute('livechat/agent.next/:token', { throw new Meteor.Error('invalid-agent'); } - return RocketChat.API.v1.success({ agent }); + return API.v1.success({ agent }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/config.js b/packages/rocketchat-livechat/server/api/v1/config.js index b59c679bf934..03e86c76128d 100644 --- a/packages/rocketchat-livechat/server/api/v1/config.js +++ b/packages/rocketchat-livechat/server/api/v1/config.js @@ -1,8 +1,9 @@ import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, settings, online, findOpenRoom } from '../lib/livechat'; import { Match, check } from 'meteor/check'; -RocketChat.API.v1.addRoute('livechat/config', { +API.v1.addRoute('livechat/config', { get() { try { check(this.queryParams, { @@ -11,7 +12,7 @@ RocketChat.API.v1.addRoute('livechat/config', { const config = settings(); if (!config.enabled) { - return RocketChat.API.v1.success({ config: { enabled: false } }); + return API.v1.success({ config: { enabled: false } }); } const status = online(); @@ -30,9 +31,9 @@ RocketChat.API.v1.addRoute('livechat/config', { Object.assign(config, { online: status, guest, room, agent }); - return RocketChat.API.v1.success({ config }); + return API.v1.success({ config }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/customField.js b/packages/rocketchat-livechat/server/api/v1/customField.js index bcb738428ba4..e2818fa2f466 100644 --- a/packages/rocketchat-livechat/server/api/v1/customField.js +++ b/packages/rocketchat-livechat/server/api/v1/customField.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/custom.field', { +API.v1.addRoute('livechat/custom.field', { post() { try { check(this.bodyParams, { @@ -21,17 +22,17 @@ RocketChat.API.v1.addRoute('livechat/custom.field', { } if (!RocketChat.Livechat.setCustomFields({ token, key, value, overwrite })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ field: { key, value, overwrite } }); + return API.v1.success({ field: { key, value, overwrite } }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/custom.fields', { +API.v1.addRoute('livechat/custom.fields', { post() { check(this.bodyParams, { token: String, @@ -53,13 +54,13 @@ RocketChat.API.v1.addRoute('livechat/custom.fields', { const fields = this.bodyParams.customFields.map((customField) => { const data = Object.assign({ token }, customField); if (!RocketChat.Livechat.setCustomFields(data)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } return { Key: customField.key, value: customField.value, overwrite: customField.overwrite }; }); - return RocketChat.API.v1.success({ fields }); + return API.v1.success({ fields }); }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/message.js b/packages/rocketchat-livechat/server/api/v1/message.js index 8acc1dd9da6d..8abdaa6b761c 100644 --- a/packages/rocketchat-livechat/server/api/v1/message.js +++ b/packages/rocketchat-livechat/server/api/v1/message.js @@ -2,10 +2,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; import { findGuest, findRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/message', { +API.v1.addRoute('livechat/message', { post() { try { check(this.bodyParams, { @@ -47,17 +48,17 @@ RocketChat.API.v1.addRoute('livechat/message', { const result = RocketChat.Livechat.sendMessage(sendMessage); if (result) { const message = { _id: result._id, rid: result.rid, msg: result.msg, u: result.u, ts: result.ts }; - return RocketChat.API.v1.success({ message }); + return API.v1.success({ message }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/message/:_id', { +API.v1.addRoute('livechat/message/:_id', { put() { try { check(this.urlParams, { @@ -93,14 +94,14 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { const result = RocketChat.Livechat.updateMessage({ guest, message }); if (result) { const data = RocketChat.models.Messages.findOneById(_id); - return RocketChat.API.v1.success({ + return API.v1.success({ message: { _id: data._id, rid: data.rid, msg: data.msg, u: data.u, ts: data.ts }, }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { @@ -134,7 +135,7 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { const result = RocketChat.Livechat.deleteMessage({ guest, message }); if (result) { - return RocketChat.API.v1.success({ + return API.v1.success({ message: { _id, ts: new Date().toISOString(), @@ -142,14 +143,14 @@ RocketChat.API.v1.addRoute('livechat/message/:_id', { }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/messages.history/:rid', { +API.v1.addRoute('livechat/messages.history/:rid', { get() { try { check(this.urlParams, { @@ -189,33 +190,33 @@ RocketChat.API.v1.addRoute('livechat/messages.history/:rid', { } const messages = RocketChat.loadMessageHistory({ userId: guest._id, rid, end, limit, ls }); - return RocketChat.API.v1.success(messages); + return API.v1.success(messages); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/messages', { authRequired: true }, { +API.v1.addRoute('livechat/messages', { authRequired: true }, { post() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } if (!this.bodyParams.visitor) { - return RocketChat.API.v1.failure('Body param "visitor" is required'); + return API.v1.failure('Body param "visitor" is required'); } if (!this.bodyParams.visitor.token) { - return RocketChat.API.v1.failure('Body param "visitor.token" is required'); + return API.v1.failure('Body param "visitor.token" is required'); } if (!this.bodyParams.messages) { - return RocketChat.API.v1.failure('Body param "messages" is required'); + return API.v1.failure('Body param "messages" is required'); } if (!(this.bodyParams.messages instanceof Array)) { - return RocketChat.API.v1.failure('Body param "messages" is not an array'); + return API.v1.failure('Body param "messages" is not an array'); } if (this.bodyParams.messages.length === 0) { - return RocketChat.API.v1.failure('Body param "messages" is empty'); + return API.v1.failure('Body param "messages" is empty'); } const visitorToken = this.bodyParams.visitor.token; @@ -253,7 +254,7 @@ RocketChat.API.v1.addRoute('livechat/messages', { authRequired: true }, { }; }); - return RocketChat.API.v1.success({ + return API.v1.success({ messages: sentMessages, }); }, diff --git a/packages/rocketchat-livechat/server/api/v1/offlineMessage.js b/packages/rocketchat-livechat/server/api/v1/offlineMessage.js index 6409ea0f5667..338573084ebe 100644 --- a/packages/rocketchat-livechat/server/api/v1/offlineMessage.js +++ b/packages/rocketchat-livechat/server/api/v1/offlineMessage.js @@ -1,8 +1,9 @@ import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/offline.message', { +API.v1.addRoute('livechat/offline.message', { post() { try { check(this.bodyParams, { @@ -13,12 +14,12 @@ RocketChat.API.v1.addRoute('livechat/offline.message', { const { name, email, message } = this.bodyParams; if (!RocketChat.Livechat.sendOfflineMessage({ name, email, message })) { - return RocketChat.API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_offline_message') }); + return API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_offline_message') }); } - return RocketChat.API.v1.success({ message: TAPi18n.__('Livechat_offline_message_sent') }); + return API.v1.success({ message: TAPi18n.__('Livechat_offline_message_sent') }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/pageVisited.js b/packages/rocketchat-livechat/server/api/v1/pageVisited.js index 906f3f783529..1a0fc1098b6e 100644 --- a/packages/rocketchat-livechat/server/api/v1/pageVisited.js +++ b/packages/rocketchat-livechat/server/api/v1/pageVisited.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import _ from 'underscore'; import { findGuest, findRoom } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/page.visited', { +API.v1.addRoute('livechat/page.visited', { post() { try { check(this.bodyParams, { @@ -34,12 +35,12 @@ RocketChat.API.v1.addRoute('livechat/page.visited', { const obj = RocketChat.Livechat.savePageHistory(token, rid, pageInfo); if (obj) { const page = _.pick(obj, 'msg', 'navigation'); - return RocketChat.API.v1.success({ page }); + return API.v1.success({ page }); } - return RocketChat.API.v1.success(); + return API.v1.success(); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/room.js b/packages/rocketchat-livechat/server/api/v1/room.js index e2e544cfec18..6e9f3d6e98fa 100644 --- a/packages/rocketchat-livechat/server/api/v1/room.js +++ b/packages/rocketchat-livechat/server/api/v1/room.js @@ -3,9 +3,10 @@ import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, findRoom, getRoom, settings } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/room', { +API.v1.addRoute('livechat/room', { get() { try { check(this.queryParams, { @@ -22,14 +23,14 @@ RocketChat.API.v1.addRoute('livechat/room', { const rid = this.queryParams.rid || Random.id(); const room = getRoom(guest, rid); - return RocketChat.API.v1.success(room); + return API.v1.success(room); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.close', { +API.v1.addRoute('livechat/room.close', { post() { try { check(this.bodyParams, { @@ -57,17 +58,17 @@ RocketChat.API.v1.addRoute('livechat/room.close', { const comment = TAPi18n.__('Closed_by_visitor', { lng: language }); if (!RocketChat.Livechat.closeRoom({ visitor, room, comment })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ rid, comment }); + return API.v1.success({ rid, comment }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.transfer', { +API.v1.addRoute('livechat/room.transfer', { post() { try { check(this.bodyParams, { @@ -92,18 +93,18 @@ RocketChat.API.v1.addRoute('livechat/room.transfer', { RocketChat.models.Messages.keepHistoryForToken(token); if (!RocketChat.Livechat.transfer(room, guest, { roomId: rid, departmentId: department })) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } room = findRoom(token, rid); - return RocketChat.API.v1.success({ room }); + return API.v1.success({ room }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/room.survey', { +API.v1.addRoute('livechat/room.survey', { post() { try { check(this.bodyParams, { @@ -144,12 +145,12 @@ RocketChat.API.v1.addRoute('livechat/room.survey', { } if (!RocketChat.models.Rooms.updateSurveyFeedbackById(room._id, updateData)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } - return RocketChat.API.v1.success({ rid, data: updateData }); + return API.v1.success({ rid, data: updateData }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/transcript.js b/packages/rocketchat-livechat/server/api/v1/transcript.js index 1dcb988c916b..efcf64e48bb0 100644 --- a/packages/rocketchat-livechat/server/api/v1/transcript.js +++ b/packages/rocketchat-livechat/server/api/v1/transcript.js @@ -1,8 +1,9 @@ import { check } from 'meteor/check'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; -RocketChat.API.v1.addRoute('livechat/transcript', { +API.v1.addRoute('livechat/transcript', { post() { try { check(this.bodyParams, { @@ -13,12 +14,12 @@ RocketChat.API.v1.addRoute('livechat/transcript', { const { token, rid, email } = this.bodyParams; if (!RocketChat.Livechat.sendTranscript({ token, rid, email })) { - return RocketChat.API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_transcript') }); + return API.v1.failure({ message: TAPi18n.__('Error_sending_livechat_transcript') }); } - return RocketChat.API.v1.success({ message: TAPi18n.__('Livechat_transcript_sent') }); + return API.v1.success({ message: TAPi18n.__('Livechat_transcript_sent') }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/videoCall.js b/packages/rocketchat-livechat/server/api/v1/videoCall.js index 01d7ce628412..aaa7e0521d3f 100644 --- a/packages/rocketchat-livechat/server/api/v1/videoCall.js +++ b/packages/rocketchat-livechat/server/api/v1/videoCall.js @@ -2,9 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { findGuest, getRoom, settings } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/video.call/:token', { +API.v1.addRoute('livechat/video.call/:token', { get() { try { check(this.urlParams, { @@ -41,9 +42,9 @@ RocketChat.API.v1.addRoute('livechat/video.call/:token', { timeout: new Date(Date.now() + 3600 * 1000), }; - return RocketChat.API.v1.success({ videoCall }); + return API.v1.success({ videoCall }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livechat/server/api/v1/visitor.js b/packages/rocketchat-livechat/server/api/v1/visitor.js index 75dbc02997e3..f5c8a6b2e777 100644 --- a/packages/rocketchat-livechat/server/api/v1/visitor.js +++ b/packages/rocketchat-livechat/server/api/v1/visitor.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; import { findGuest } from '../lib/livechat'; -RocketChat.API.v1.addRoute('livechat/visitor', { +API.v1.addRoute('livechat/visitor', { post() { try { check(this.bodyParams, { @@ -49,20 +50,20 @@ RocketChat.API.v1.addRoute('livechat/visitor', { } const { key, value, overwrite } = field; if (customField.scope === 'visitor' && !LivechatVisitors.updateLivechatDataByToken(token, key, value, overwrite)) { - return RocketChat.API.v1.failure(); + return API.v1.failure(); } }); } visitor = LivechatVisitors.findOneById(visitorId); - return RocketChat.API.v1.success({ visitor }); + return API.v1.success({ visitor }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); -RocketChat.API.v1.addRoute('livechat/visitor/:token', { +API.v1.addRoute('livechat/visitor/:token', { get() { try { check(this.urlParams, { @@ -70,9 +71,9 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { }); const visitor = LivechatVisitors.getVisitorByToken(this.urlParams.token); - return RocketChat.API.v1.success({ visitor }); + return API.v1.success({ visitor }); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, delete() { @@ -89,7 +90,7 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { const { _id } = visitor; const result = RocketChat.Livechat.removeGuest(_id); if (result) { - return RocketChat.API.v1.success({ + return API.v1.success({ visitor: { _id, ts: new Date().toISOString(), @@ -97,17 +98,17 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token', { }); } - return RocketChat.API.v1.failure(); + return API.v1.failure(); } catch (e) { - return RocketChat.API.v1.failure(e.error); + return API.v1.failure(e.error); } }, }); -RocketChat.API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true }, { +API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true }, { get() { if (!RocketChat.authz.hasPermission(this.userId, 'view-livechat-manager')) { - return RocketChat.API.v1.unauthorized(); + return API.v1.unauthorized(); } const rooms = RocketChat.models.Rooms.findOpenByVisitorToken(this.urlParams.token, { @@ -120,11 +121,11 @@ RocketChat.API.v1.addRoute('livechat/visitor/:token/room', { authRequired: true servedBy: 1, }, }).fetch(); - return RocketChat.API.v1.success({ rooms }); + return API.v1.success({ rooms }); }, }); -RocketChat.API.v1.addRoute('livechat/visitor.status', { +API.v1.addRoute('livechat/visitor.status', { post() { try { check(this.bodyParams, { @@ -141,9 +142,9 @@ RocketChat.API.v1.addRoute('livechat/visitor.status', { RocketChat.Livechat.notifyGuestStatusChanged(token, status); - return RocketChat.API.v1.success({ token, status }); + return API.v1.success({ token, status }); } catch (e) { - return RocketChat.API.v1.failure(e); + return API.v1.failure(e); } }, }); diff --git a/packages/rocketchat-livestream/package.js b/packages/rocketchat-livestream/package.js index 2b22c85b851b..e99f39beae74 100644 --- a/packages/rocketchat-livestream/package.js +++ b/packages/rocketchat-livestream/package.js @@ -10,6 +10,7 @@ Package.onUse(function(api) { 'ecmascript', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:ui', 'templating', ]); diff --git a/packages/rocketchat-livestream/server/routes.js b/packages/rocketchat-livestream/server/routes.js index 5806dc03174a..92673e2bd370 100644 --- a/packages/rocketchat-livestream/server/routes.js +++ b/packages/rocketchat-livestream/server/routes.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import google from 'googleapis'; const { OAuth2 } = google.auth; -RocketChat.API.v1.addRoute('livestream/oauth', { +API.v1.addRoute('livestream/oauth', { get: function functionName() { const clientAuth = new OAuth2(RocketChat.settings.get('Broadcasting_client_id'), RocketChat.settings.get('Broadcasting_client_secret'), `${ RocketChat.settings.get('Site_Url') }/api/v1/livestream/oauth/callback`.replace(/\/{2}api/g, '/api')); const { userId } = this.queryParams; @@ -24,7 +25,7 @@ RocketChat.API.v1.addRoute('livestream/oauth', { }, }); -RocketChat.API.v1.addRoute('livestream/oauth/callback', { +API.v1.addRoute('livestream/oauth/callback', { get: function functionName() { const { code, state } = this.queryParams; diff --git a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js index ec1da72899c6..b8b79807b1cd 100644 --- a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js +++ b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; import { RocketChat } from 'meteor/rocketchat:lib'; import { OAuth2Server } from 'meteor/rocketchat:oauth2-server'; +import { API } from 'meteor/rocketchat:api'; const oauth2server = new OAuth2Server({ accessTokensCollectionName: 'rocketchat_oauth_access_tokens', @@ -55,7 +56,7 @@ Meteor.publish('oauthClient', function(clientId) { }); }); -RocketChat.API.v1.addAuthMethod(function() { +API.v1.addAuthMethod(function() { let headerToken = this.request.headers.authorization; const getToken = this.request.query.access_token; if (headerToken != null) { diff --git a/packages/rocketchat-videobridge/package.js b/packages/rocketchat-videobridge/package.js index a455f5f047ab..7ac995888486 100644 --- a/packages/rocketchat-videobridge/package.js +++ b/packages/rocketchat-videobridge/package.js @@ -11,6 +11,7 @@ Package.onUse(function(api) { 'less', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:api', 'rocketchat:bigbluebutton', 'templating', ]); diff --git a/packages/rocketchat-videobridge/server/methods/bbb.js b/packages/rocketchat-videobridge/server/methods/bbb.js index a0019961bb93..db8dc32351f6 100644 --- a/packages/rocketchat-videobridge/server/methods/bbb.js +++ b/packages/rocketchat-videobridge/server/methods/bbb.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import BigBlueButtonApi from 'meteor/rocketchat:bigbluebutton'; import { RocketChat } from 'meteor/rocketchat:lib'; +import { API } from 'meteor/rocketchat:api'; import { HTTP } from 'meteor/http'; import xml2js from 'xml2js'; @@ -121,7 +122,7 @@ Meteor.methods({ }, }); -RocketChat.API.v1.addRoute('videoconference.bbb.update/:id', { authRequired: false }, { +API.v1.addRoute('videoconference.bbb.update/:id', { authRequired: false }, { post() { // TODO check checksum const event = JSON.parse(this.bodyParams.event)[0]; From cd1930c68c95bde892c8a454c94fc62ee7b1d643 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 14:43:33 -0200 Subject: [PATCH 031/101] Move processWebhookMessage function to rc-lib package --- .../server/processWebhookMessage.js | 87 +----------------- .../rocketchat-lib/server/functions/index.js | 1 + .../server/functions/processWebhookMessage.js | 88 +++++++++++++++++++ 3 files changed, 90 insertions(+), 86 deletions(-) create mode 100644 packages/rocketchat-lib/server/functions/processWebhookMessage.js diff --git a/packages/rocketchat-integrations/server/processWebhookMessage.js b/packages/rocketchat-integrations/server/processWebhookMessage.js index d72a96fb36ed..a0c36c660726 100644 --- a/packages/rocketchat-integrations/server/processWebhookMessage.js +++ b/packages/rocketchat-integrations/server/processWebhookMessage.js @@ -1,86 +1 @@ -import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import _ from 'underscore'; -import s from 'underscore.string'; - -export const processWebhookMessage = function(messageObj, user, defaultValues = { channel: '', alias: '', avatar: '', emoji: '' }, mustBeJoined = false) { - const sentData = []; - const channels = [].concat(messageObj.channel || messageObj.roomId || defaultValues.channel); - - for (const channel of channels) { - const channelType = channel[0]; - - let channelValue = channel.substr(1); - let room; - - switch (channelType) { - case '#': - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true }); - break; - case '@': - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd' }); - break; - default: - channelValue = channelType + channelValue; - - // Try to find the room by id or name if they didn't include the prefix. - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true, errorOnEmpty: false }); - if (room) { - break; - } - - // We didn't get a room, let's try finding direct messages - room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd', tryDirectByUserIdOnly: true }); - if (room) { - break; - } - - // No room, so throw an error - throw new Meteor.Error('invalid-channel'); - } - - if (mustBeJoined && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { - // throw new Meteor.Error('invalid-room', 'Invalid room provided to send a message to, must be joined.'); - throw new Meteor.Error('invalid-channel'); // Throwing the generic one so people can't "brute force" find rooms - } - - if (messageObj.attachments && !_.isArray(messageObj.attachments)) { - console.log('Attachments should be Array, ignoring value'.red, messageObj.attachments); - messageObj.attachments = undefined; - } - - const message = { - alias: messageObj.username || messageObj.alias || defaultValues.alias, - msg: s.trim(messageObj.text || messageObj.msg || ''), - attachments: messageObj.attachments || [], - parseUrls: messageObj.parseUrls !== undefined ? messageObj.parseUrls : !messageObj.attachments, - bot: messageObj.bot, - groupable: (messageObj.groupable !== undefined) ? messageObj.groupable : false, - }; - - if (!_.isEmpty(messageObj.icon_url) || !_.isEmpty(messageObj.avatar)) { - message.avatar = messageObj.icon_url || messageObj.avatar; - } else if (!_.isEmpty(messageObj.icon_emoji) || !_.isEmpty(messageObj.emoji)) { - message.emoji = messageObj.icon_emoji || messageObj.emoji; - } else if (!_.isEmpty(defaultValues.avatar)) { - message.avatar = defaultValues.avatar; - } else if (!_.isEmpty(defaultValues.emoji)) { - message.emoji = defaultValues.emoji; - } - - if (_.isArray(message.attachments)) { - for (let i = 0; i < message.attachments.length; i++) { - const attachment = message.attachments[i]; - if (attachment.msg) { - attachment.text = s.trim(attachment.msg); - delete attachment.msg; - } - } - } - - const messageReturn = RocketChat.sendMessage(user, message, room); - sentData.push({ channel, message: messageReturn }); - } - - return sentData; -}; +export { processWebhookMessage } from 'meteor/rocketchat:lib'; diff --git a/packages/rocketchat-lib/server/functions/index.js b/packages/rocketchat-lib/server/functions/index.js index c60ee0e9849d..5ff75d6934f9 100644 --- a/packages/rocketchat-lib/server/functions/index.js +++ b/packages/rocketchat-lib/server/functions/index.js @@ -24,3 +24,4 @@ export { unarchiveRoom } from './unarchiveRoom'; export { updateMessage } from './updateMessage'; export { validateCustomFields } from './validateCustomFields'; export { generateUsernameSuggestion } from './getUsernameSuggestion'; +export { processWebhookMessage } from './processWebhookMessage'; diff --git a/packages/rocketchat-lib/server/functions/processWebhookMessage.js b/packages/rocketchat-lib/server/functions/processWebhookMessage.js new file mode 100644 index 000000000000..ed87ef60468f --- /dev/null +++ b/packages/rocketchat-lib/server/functions/processWebhookMessage.js @@ -0,0 +1,88 @@ +import { Meteor } from 'meteor/meteor'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { getRoomByNameOrIdWithOptionToJoin } from './getRoomByNameOrIdWithOptionToJoin'; +import { sendMessage } from './sendMessage'; +import _ from 'underscore'; +import s from 'underscore.string'; + +export const processWebhookMessage = function(messageObj, user, defaultValues = { channel: '', alias: '', avatar: '', emoji: '' }, mustBeJoined = false) { + const sentData = []; + const channels = [].concat(messageObj.channel || messageObj.roomId || defaultValues.channel); + + for (const channel of channels) { + const channelType = channel[0]; + + let channelValue = channel.substr(1); + let room; + + switch (channelType) { + case '#': + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true }); + break; + case '@': + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd' }); + break; + default: + channelValue = channelType + channelValue; + + // Try to find the room by id or name if they didn't include the prefix. + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, joinChannel: true, errorOnEmpty: false }); + if (room) { + break; + } + + // We didn't get a room, let's try finding direct messages + room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: channelValue, type: 'd', tryDirectByUserIdOnly: true }); + if (room) { + break; + } + + // No room, so throw an error + throw new Meteor.Error('invalid-channel'); + } + + if (mustBeJoined && !Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { + // throw new Meteor.Error('invalid-room', 'Invalid room provided to send a message to, must be joined.'); + throw new Meteor.Error('invalid-channel'); // Throwing the generic one so people can't "brute force" find rooms + } + + if (messageObj.attachments && !_.isArray(messageObj.attachments)) { + console.log('Attachments should be Array, ignoring value'.red, messageObj.attachments); + messageObj.attachments = undefined; + } + + const message = { + alias: messageObj.username || messageObj.alias || defaultValues.alias, + msg: s.trim(messageObj.text || messageObj.msg || ''), + attachments: messageObj.attachments || [], + parseUrls: messageObj.parseUrls !== undefined ? messageObj.parseUrls : !messageObj.attachments, + bot: messageObj.bot, + groupable: (messageObj.groupable !== undefined) ? messageObj.groupable : false, + }; + + if (!_.isEmpty(messageObj.icon_url) || !_.isEmpty(messageObj.avatar)) { + message.avatar = messageObj.icon_url || messageObj.avatar; + } else if (!_.isEmpty(messageObj.icon_emoji) || !_.isEmpty(messageObj.emoji)) { + message.emoji = messageObj.icon_emoji || messageObj.emoji; + } else if (!_.isEmpty(defaultValues.avatar)) { + message.avatar = defaultValues.avatar; + } else if (!_.isEmpty(defaultValues.emoji)) { + message.emoji = defaultValues.emoji; + } + + if (_.isArray(message.attachments)) { + for (let i = 0; i < message.attachments.length; i++) { + const attachment = message.attachments[i]; + if (attachment.msg) { + attachment.text = s.trim(attachment.msg); + delete attachment.msg; + } + } + } + + const messageReturn = sendMessage(user, message, room); + sentData.push({ channel, message: messageReturn }); + } + + return sentData; +}; From d7eab39d477982d9a1835a6a7750f3994c2e2e29 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 14:45:01 -0200 Subject: [PATCH 032/101] Remove API from RC namespace and import missing function that was being used with namespace --- .../client/lib/RestApiClient.js | 1 - packages/rocketchat-api/package.js | 1 - packages/rocketchat-api/server/api.js | 3 --- packages/rocketchat-api/server/v1/chat.js | 2 +- packages/rocketchat-api/server/v1/im.js | 4 +-- packages/rocketchat-api/server/v1/users.js | 26 ++++++++++++------- 6 files changed, 20 insertions(+), 17 deletions(-) diff --git a/packages/rocketchat-api/client/lib/RestApiClient.js b/packages/rocketchat-api/client/lib/RestApiClient.js index 107462f2057d..403ff02f2827 100644 --- a/packages/rocketchat-api/client/lib/RestApiClient.js +++ b/packages/rocketchat-api/client/lib/RestApiClient.js @@ -109,4 +109,3 @@ export const API = { }, }, }; -RocketChat.API = API; diff --git a/packages/rocketchat-api/package.js b/packages/rocketchat-api/package.js index a6664d10b8f1..33c14dae9024 100644 --- a/packages/rocketchat-api/package.js +++ b/packages/rocketchat-api/package.js @@ -17,7 +17,6 @@ Package.onUse(function(api) { 'rocketchat:utils', 'rocketchat:metrics', 'rocketchat:authorization', - 'rocketchat:integrations', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-api/server/api.js b/packages/rocketchat-api/server/api.js index a4ee71d3b9a6..d8e1d331ea47 100644 --- a/packages/rocketchat-api/server/api.js +++ b/packages/rocketchat-api/server/api.js @@ -2,7 +2,6 @@ import { Meteor } from 'meteor/meteor'; import { DDPCommon } from 'meteor/ddp-common'; import { DDP } from 'meteor/ddp'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { Restivus } from 'meteor/nimble:restivus'; import { Logger } from 'meteor/rocketchat:logger'; import { settings } from 'meteor/rocketchat:settings'; @@ -448,8 +447,6 @@ API = { ApiClass: APIClass, }; -RocketChat.API = API; - const defaultOptionsEndpoint = function _defaultOptionsEndpoint() { if (this.request.method === 'OPTIONS' && this.request.headers['access-control-request-method']) { if (settings.get('API_Enable_CORS') === true) { diff --git a/packages/rocketchat-api/server/v1/chat.js b/packages/rocketchat-api/server/v1/chat.js index f83b8dc2c804..c3bf42672d00 100644 --- a/packages/rocketchat-api/server/v1/chat.js +++ b/packages/rocketchat-api/server/v1/chat.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; -import { processWebhookMessage } from 'meteor/rocketchat:integrations'; import { Messages } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; +import { processWebhookMessage } from 'meteor/rocketchat:lib'; import { API } from '../api'; API.v1.addRoute('chat.delete', { authRequired: true }, { diff --git a/packages/rocketchat-api/server/v1/im.js b/packages/rocketchat-api/server/v1/im.js index 763dc8def581..655b06ca8764 100644 --- a/packages/rocketchat-api/server/v1/im.js +++ b/packages/rocketchat-api/server/v1/im.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getRoomByNameOrIdWithOptionToJoin } from 'meteor/rocketchat:lib'; import { Subscriptions, Uploads, Users, Messages, Rooms } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { composeMessageObjectWithUser } from 'meteor/rocketchat:utils'; @@ -11,7 +11,7 @@ function findDirectMessageRoom(params, user) { throw new Meteor.Error('error-room-param-not-provided', 'Body param "roomId" or "username" is required'); } - const room = RocketChat.getRoomByNameOrIdWithOptionToJoin({ + const room = getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: params.username || params.roomId, type: 'd', diff --git a/packages/rocketchat-api/server/v1/users.js b/packages/rocketchat-api/server/v1/users.js index 178f5d5d108a..6d24bbb53dae 100644 --- a/packages/rocketchat-api/server/v1/users.js +++ b/packages/rocketchat-api/server/v1/users.js @@ -5,6 +5,14 @@ import { Users, Subscriptions } from 'meteor/rocketchat:models'; import { hasPermission } from 'meteor/rocketchat:authorization'; import { settings } from 'meteor/rocketchat:settings'; import { getURL } from 'meteor/rocketchat:utils'; +import { + validateCustomFields, + saveUser, + saveCustomFieldsWithoutValidation, + checkUsernameAvailability, + setUserAvatar, + saveCustomFields, +} from 'meteor/rocketchat:lib'; import { API } from '../api'; import _ from 'underscore'; import Busboy from 'busboy'; @@ -31,13 +39,13 @@ API.v1.addRoute('users.create', { authRequired: true }, { } if (this.bodyParams.customFields) { - RocketChat.validateCustomFields(this.bodyParams.customFields); + validateCustomFields(this.bodyParams.customFields); } - const newUserId = RocketChat.saveUser(this.userId, this.bodyParams); + const newUserId = saveUser(this.userId, this.bodyParams); if (this.bodyParams.customFields) { - RocketChat.saveCustomFieldsWithoutValidation(newUserId, this.bodyParams.customFields); + saveCustomFieldsWithoutValidation(newUserId, this.bodyParams.customFields); } @@ -191,7 +199,7 @@ API.v1.addRoute('users.register', { authRequired: false }, { username: String, })); - if (!RocketChat.checkUsernameAvailability(this.bodyParams.username)) { + if (!checkUsernameAvailability(this.bodyParams.username)) { return API.v1.failure('Username is already in use'); } @@ -246,7 +254,7 @@ API.v1.addRoute('users.setAvatar', { authRequired: true }, { Meteor.runAsUser(user._id, () => { if (this.bodyParams.avatarUrl) { - RocketChat.setUserAvatar(user, this.bodyParams.avatarUrl, '', 'url'); + setUserAvatar(user, this.bodyParams.avatarUrl, '', 'url'); } else { const busboy = new Busboy({ headers: this.request.headers }); const fields = {}; @@ -281,7 +289,7 @@ API.v1.addRoute('users.setAvatar', { authRequired: true }, { return callback(new Meteor.Error('error-not-allowed', 'Not allowed')); } } - RocketChat.setUserAvatar(user, Buffer.concat(imageData), mimetype, 'rest'); + setUserAvatar(user, Buffer.concat(imageData), mimetype, 'rest'); callback(); })); })); @@ -318,10 +326,10 @@ API.v1.addRoute('users.update', { authRequired: true }, { const userData = _.extend({ _id: this.bodyParams.userId }, this.bodyParams.data); - Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); + Meteor.runAsUser(this.userId, () => saveUser(this.userId, userData)); if (this.bodyParams.data.customFields) { - RocketChat.saveCustomFields(this.bodyParams.userId, this.bodyParams.data.customFields); + saveCustomFields(this.bodyParams.userId, this.bodyParams.data.customFields); } if (typeof this.bodyParams.data.active !== 'undefined') { @@ -440,7 +448,7 @@ API.v1.addRoute('users.setPreferences', { authRequired: true }, { userData.language = language; } - Meteor.runAsUser(this.userId, () => RocketChat.saveUser(this.userId, userData)); + Meteor.runAsUser(this.userId, () => saveUser(this.userId, userData)); const user = Users.findOneById(userId, { fields: { 'settings.preferences': 1, From 59bbccc10a34d8caeae0c3ba5d0974d1e919bc44 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 15:58:07 -0200 Subject: [PATCH 033/101] Remove dependency of RC namespace in rc-graphql --- packages/rocketchat-graphql/package.js | 3 +++ packages/rocketchat-graphql/server/api.js | 10 +++++----- .../server/resolvers/channels/Channel-type.js | 14 +++++++------- .../server/resolvers/channels/channelByName.js | 4 ++-- .../server/resolvers/channels/channels.js | 4 ++-- .../server/resolvers/channels/channelsByUser.js | 8 ++++---- .../server/resolvers/channels/deleteChannel.js | 6 +++--- .../server/resolvers/channels/directChannel.js | 4 ++-- .../server/resolvers/channels/hideChannel.js | 6 +++--- .../server/resolvers/channels/leaveChannel.js | 4 ++-- .../server/resolvers/messages/Message-type.js | 10 +++++----- .../resolvers/messages/addReactionToMessage.js | 4 ++-- .../server/resolvers/messages/chatMessageAdded.js | 7 ++++--- .../server/resolvers/messages/deleteMessage.js | 4 ++-- .../server/resolvers/messages/editMessage.js | 6 +++--- .../server/resolvers/messages/messages.js | 10 +++++----- .../server/resolvers/messages/sendMessage.js | 2 +- .../server/resolvers/users/User-type.js | 8 ++++---- .../server/resolvers/users/setStatus.js | 6 +++--- packages/rocketchat-graphql/server/settings.js | 4 ++-- 20 files changed, 64 insertions(+), 60 deletions(-) diff --git a/packages/rocketchat-graphql/package.js b/packages/rocketchat-graphql/package.js index 33c25e41e4ce..8ed9547bc74e 100644 --- a/packages/rocketchat-graphql/package.js +++ b/packages/rocketchat-graphql/package.js @@ -11,6 +11,9 @@ Package.onUse(function(api) { 'ecmascript', 'http', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:settings', 'rocketchat:api', 'rocketchat:accounts', 'rocketchat:integrations', diff --git a/packages/rocketchat-graphql/server/api.js b/packages/rocketchat-graphql/server/api.js index f0079592d348..734e524a90e0 100644 --- a/packages/rocketchat-graphql/server/api.js +++ b/packages/rocketchat-graphql/server/api.js @@ -4,24 +4,24 @@ import { SubscriptionServer } from 'subscriptions-transport-ws'; import { execute, subscribe } from 'graphql'; import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import bodyParser from 'body-parser'; import express from 'express'; import cors from 'cors'; import { executableSchema } from './schema'; -const subscriptionPort = RocketChat.settings.get('Graphql_Subscription_Port') || 3100; +const subscriptionPort = settings.get('Graphql_Subscription_Port') || 3100; // the Meteor GraphQL server is an Express server const graphQLServer = express(); -if (RocketChat.settings.get('Graphql_CORS')) { +if (settings.get('Graphql_CORS')) { graphQLServer.use(cors()); } graphQLServer.use('/api/graphql', (req, res, next) => { - if (RocketChat.settings.get('Graphql_Enabled')) { + if (settings.get('Graphql_Enabled')) { next(); } else { res.status(400).send('Graphql is not enabled in this server'); @@ -52,7 +52,7 @@ graphQLServer.use( ); const startSubscriptionServer = () => { - if (RocketChat.settings.get('Graphql_Enabled')) { + if (settings.get('Graphql_Enabled')) { SubscriptionServer.create({ schema: executableSchema, execute, diff --git a/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js b/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js index 098a08f5a13d..39945c10923e 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/Channel-type.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Users } from 'meteor/rocketchat:models'; import property from 'lodash.property'; import schema from '../../schemas/channels/Channel-type.graphqls'; @@ -14,10 +14,10 @@ const resolver = { return root.name; }, members: (root) => { - const ids = RocketChat.models.Subscriptions.findByRoomIdWhenUserIdExists(root._id, { fields: { 'u._id': 1 } }) + const ids = Subscriptions.findByRoomIdWhenUserIdExists(root._id, { fields: { 'u._id': 1 } }) .fetch() .map((sub) => sub.u._id); - return RocketChat.models.Users.findByIds(ids).fetch(); + return Users.findByIds(ids).fetch(); }, owners: (root) => { // there might be no owner @@ -25,20 +25,20 @@ const resolver = { return; } - return [RocketChat.models.Users.findOneByUsername(root.u.username)]; + return [Users.findOneByUsername(root.u.username)]; }, - numberOfMembers: (root) => RocketChat.models.Subscriptions.findByRoomId(root._id).count(), + numberOfMembers: (root) => Subscriptions.findByRoomId(root._id).count(), numberOfMessages: property('msgs'), readOnly: (root) => root.ro === true, direct: (root) => root.t === 'd', privateChannel: (root) => root.t === 'p', favourite: (root, args, { user }) => { - const room = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); + const room = Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); return room && room.f === true; }, unseenMessages: (root, args, { user }) => { - const room = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); + const room = Subscriptions.findOneByRoomIdAndUserId(root._id, user._id); return (room || {}).unread; }, diff --git a/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js b/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js index 8bf960126130..972cc609c543 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/channelByName.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -12,7 +12,7 @@ const resolver = { t: 'c', }; - return RocketChat.models.Rooms.findOne(query, { + return Rooms.findOne(query, { fields: roomPublicFields, }); }), diff --git a/packages/rocketchat-graphql/server/resolvers/channels/channels.js b/packages/rocketchat-graphql/server/resolvers/channels/channels.js index f9341e88b700..d5ac90da4e56 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/channels.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/channels.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -44,7 +44,7 @@ const resolver = { } } - return RocketChat.models.Rooms.find(query, options).fetch(); + return Rooms.find(query, options).fetch(); }), }, }; diff --git a/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js b/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js index 4b42e4339072..1c94c3e93eb4 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/channelsByUser.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -7,14 +7,14 @@ import schema from '../../schemas/channels/channelsByUser.graphqls'; const resolver = { Query: { channelsByUser: authenticated((root, { userId }) => { - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); if (!user) { throw new Error('No user'); } - const roomIds = RocketChat.models.Subscriptions.findByUserId(userId, { fields: { rid: 1 } }).fetch().map((s) => s.rid); - const rooms = RocketChat.models.Rooms.findByIds(roomIds, { + const roomIds = Subscriptions.findByUserId(userId, { fields: { rid: 1 } }).fetch().map((s) => s.rid); + const rooms = Rooms.findByIds(roomIds, { sort: { name: 1, }, diff --git a/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js index 88dca7097998..b53bdd9ea072 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/deleteChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/deleteChannel.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/channels/deleteChannel.graphqls'; const resolver = { Mutation: { deleteChannel: authenticated((root, { channelId }, { user }) => { - const channel = RocketChat.models.Rooms.findOne({ + const channel = Rooms.findOne({ _id: channelId, t: 'c', }); @@ -16,7 +16,7 @@ const resolver = { throw new Error('error-room-not-found', 'The required "channelId" param provided does not match any channel'); } - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); + const sub = Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); if (!sub) { throw new Error(`The user/callee is not in the channel "${ channel.name }.`); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js index bbecd45dbb33..bb3f1b4bb680 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/directChannel.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import { roomPublicFields } from './settings'; @@ -24,7 +24,7 @@ const resolver = { throw new Error('Use one of those fields: username, channelId'); } - return RocketChat.models.Rooms.findOne(query, { + return Rooms.findOne(query, { fields: roomPublicFields, }); }), diff --git a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js index 19088eaf9140..4c5ebc4a2bef 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:lib'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/hideChannel.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/channels/hideChannel.graphqls'; const resolver = { Mutation: { hideChannel: authenticated((root, args, { user }) => { - const channel = RocketChat.models.Rooms.findOne({ + const channel = Rooms.findOne({ _id: args.channelId, t: 'c', }); @@ -16,7 +16,7 @@ const resolver = { throw new Error('error-room-not-found', 'The required "channelId" param provided does not match any channel'); } - const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); + const sub = Subscriptions.findOneByRoomIdAndUserId(channel._id, user._id); if (!sub) { throw new Error(`The user/callee is not in the channel "${ channel.name }.`); diff --git a/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js index 863ace8354f2..98b1bfe9eb57 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/leaveChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/leaveChannel.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/channels/leaveChannel.graphqls'; const resolver = { Mutation: { leaveChannel: authenticated((root, args, { user }) => { - const channel = RocketChat.models.Rooms.findOne({ + const channel = Rooms.findOne({ _id: args.channelId, t: 'c', }); diff --git a/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js b/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js index 036ad99d0b5a..0a81f1881b3f 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/Message-type.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Users } from 'meteor/rocketchat:models'; import property from 'lodash.property'; import { dateToFloat } from '../../helpers/dateToFloat'; @@ -10,11 +10,11 @@ const resolver = { content: property('msg'), creationTime: (root) => dateToFloat(root.ts), author: (root) => { - const user = RocketChat.models.Users.findOne(root.u._id); + const user = Users.findOne(root.u._id); return user || root.u; }, - channel: (root) => RocketChat.models.Rooms.findOne(root.rid), + channel: (root) => Rooms.findOne(root.rid), fromServer: (root) => typeof root.t !== 'undefined', // on a message sent by user `true` otherwise `false` type: property('t'), channelRef: (root) => { @@ -22,7 +22,7 @@ const resolver = { return; } - return RocketChat.models.Rooms.find({ + return Rooms.find({ _id: { $in: root.channels.map((c) => c._id), }, @@ -37,7 +37,7 @@ const resolver = { return; } - return RocketChat.models.Users.find({ + return Users.find({ _id: { $in: root.mentions.map((c) => c._id), }, diff --git a/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js index 39022bacc104..3d9b035b7854 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/addReactionToMessage.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/addReactionToMessage.graphqls'; @@ -9,7 +9,7 @@ const resolver = { addReactionToMessage: authenticated((root, { id, icon, shouldReact }, { user }) => new Promise((resolve) => { Meteor.runAsUser(user._id, () => { Meteor.call('setReaction', icon, id.messageId, shouldReact, () => { - resolve(RocketChat.models.Messages.findOne(id.messageId)); + resolve(Messages.findOne(id.messageId)); }); }); })), diff --git a/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js b/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js index 3e2aa1f067d5..9574e2a5c121 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/chatMessageAdded.js @@ -1,5 +1,6 @@ import { withFilter } from 'graphql-subscriptions'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { pubsub } from '../../subscriptions'; import { authenticated } from '../../helpers/authenticated'; @@ -15,7 +16,7 @@ function shouldPublish(message, { id, directTo }, username) { if (id) { return message.rid === id; } else if (directTo) { - const room = RocketChat.models.Rooms.findOne({ + const room = Rooms.findOne({ usernames: { $all: [directTo, username] }, t: 'd', }); @@ -41,7 +42,7 @@ const resolver = { }, }; -RocketChat.callbacks.add('afterSaveMessage', (message) => { +callbacks.add('afterSaveMessage', (message) => { publishMessage(message); }, null, 'chatMessageAddedSubscription'); diff --git a/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js index 779836a8b6b8..4ff8d1041b8a 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/deleteMessage.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/deleteMessage.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/messages/deleteMessage.graphqls'; const resolver = { Mutation: { deleteMessage: authenticated((root, { id }, { user }) => { - const msg = RocketChat.models.Messages.findOneById(id.messageId, { fields: { u: 1, rid: 1 } }); + const msg = Messages.findOneById(id.messageId, { fields: { u: 1, rid: 1 } }); if (!msg) { throw new Error(`No message found with the id of "${ id.messageId }".`); diff --git a/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js index 45a8fedd33a4..7d22829d3275 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/editMessage.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/editMessage.graphqls'; @@ -7,7 +7,7 @@ import schema from '../../schemas/messages/editMessage.graphqls'; const resolver = { Mutation: { editMessage: authenticated((root, { id, content }, { user }) => { - const msg = RocketChat.models.Messages.findOneById(id.messageId); + const msg = Messages.findOneById(id.messageId); // Ensure the message exists if (!msg) { @@ -23,7 +23,7 @@ const resolver = { Meteor.call('updateMessage', { _id: msg._id, msg: content, rid: msg.rid }); }); - return RocketChat.models.Messages.findOneById(msg._id); + return Messages.findOneById(msg._id); }), }, }; diff --git a/packages/rocketchat-graphql/server/resolvers/messages/messages.js b/packages/rocketchat-graphql/server/resolvers/messages/messages.js index 71a51cbb4eec..c331024a75d6 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/messages.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/messages.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/messages.graphqls'; @@ -30,14 +30,14 @@ const resolver = { return null; } - const channel = RocketChat.models.Rooms.findOne(channelQuery); + const channel = Rooms.findOne(channelQuery); let messagesArray = []; if (channel) { // cursor if (isPagination && args.cursor) { - const cursorMsg = RocketChat.models.Messages.findOne(args.cursor, { fields: { ts: 1 } }); + const cursorMsg = Messages.findOne(args.cursor, { fields: { ts: 1 } }); messagesQuery.ts = { $lt: cursorMsg.ts }; } @@ -61,7 +61,7 @@ const resolver = { // look for messages that belongs to specific channel messagesQuery.rid = channel._id; - const messages = RocketChat.models.Messages.find(messagesQuery, messagesOptions); + const messages = Messages.find(messagesQuery, messagesOptions); messagesArray = messages.fetch(); @@ -69,7 +69,7 @@ const resolver = { // oldest first (because of findOne) messagesOptions.sort.ts = 1; - const firstMessage = RocketChat.models.Messages.findOne(messagesQuery, messagesOptions); + const firstMessage = Messages.findOne(messagesQuery, messagesOptions); const lastId = (messagesArray[messagesArray.length - 1] || {})._id; cursor = !lastId || lastId === firstMessage._id ? null : lastId; diff --git a/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js b/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js index 13cfe4a82f29..5759e67ad310 100644 --- a/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js +++ b/packages/rocketchat-graphql/server/resolvers/messages/sendMessage.js @@ -1,4 +1,4 @@ -import { processWebhookMessage } from 'meteor/rocketchat:integrations'; +import { processWebhookMessage } from 'meteor/rocketchat:lib'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/messages/sendMessage.graphqls'; diff --git a/packages/rocketchat-graphql/server/resolvers/users/User-type.js b/packages/rocketchat-graphql/server/resolvers/users/User-type.js index ed35be4b3b31..243c8b1128ab 100644 --- a/packages/rocketchat-graphql/server/resolvers/users/User-type.js +++ b/packages/rocketchat-graphql/server/resolvers/users/User-type.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Avatars, Rooms } from 'meteor/rocketchat:models'; import property from 'lodash.property'; import schema from '../../schemas/users/User-type.graphqls'; @@ -10,7 +10,7 @@ const resolver = { status: ({ status }) => status.toUpperCase(), avatar: async({ _id }) => { // XXX js-accounts/graphql#16 - const avatar = await RocketChat.models.Avatars.model.rawCollection().findOne({ + const avatar = await Avatars.model.rawCollection().findOne({ userId: _id, }, { fields: { url: 1 } }); @@ -18,8 +18,8 @@ const resolver = { return avatar.url; } }, - channels: Meteor.bindEnvironment(async({ _id }) => await RocketChat.models.Rooms.findBySubscriptionUserId(_id).fetch()), - directMessages: ({ username }) => RocketChat.models.Rooms.findDirectRoomContainingUsername(username).fetch(), + channels: Meteor.bindEnvironment(async({ _id }) => await Rooms.findBySubscriptionUserId(_id).fetch()), + directMessages: ({ username }) => Rooms.findDirectRoomContainingUsername(username).fetch(), }, }; diff --git a/packages/rocketchat-graphql/server/resolvers/users/setStatus.js b/packages/rocketchat-graphql/server/resolvers/users/setStatus.js index 1649929c7ce3..862b8abdbed3 100644 --- a/packages/rocketchat-graphql/server/resolvers/users/setStatus.js +++ b/packages/rocketchat-graphql/server/resolvers/users/setStatus.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/users/setStatus.graphqls'; @@ -6,13 +6,13 @@ import schema from '../../schemas/users/setStatus.graphqls'; const resolver = { Mutation: { setStatus: authenticated((root, { status }, { user }) => { - RocketChat.models.Users.update(user._id, { + Users.update(user._id, { $set: { status: status.toLowerCase(), }, }); - return RocketChat.models.Users.findOne(user._id); + return Users.findOne(user._id); }), }, }; diff --git a/packages/rocketchat-graphql/server/settings.js b/packages/rocketchat-graphql/server/settings.js index de2735d15995..56f285ed0023 100644 --- a/packages/rocketchat-graphql/server/settings.js +++ b/packages/rocketchat-graphql/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.section('GraphQL API', function() { this.add('Graphql_Enabled', false, { type: 'boolean', public: false }); this.add('Graphql_CORS', true, { type: 'boolean', public: false, enableQuery: { _id: 'Graphql_Enabled', value: true } }); From e90ab248f2df5f7b94c02b92c81237ef9d4a6a63 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 16:03:49 -0200 Subject: [PATCH 034/101] Fix import from wrong package --- .../rocketchat-graphql/server/resolvers/channels/hideChannel.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js index 4c5ebc4a2bef..221ae7377fd1 100644 --- a/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js +++ b/packages/rocketchat-graphql/server/resolvers/channels/hideChannel.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { Rooms, Subscriptions } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; import { authenticated } from '../../helpers/authenticated'; import schema from '../../schemas/channels/hideChannel.graphqls'; From fd4f74c5f43254de559801c02fba2634c08e8a5a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 16:19:49 -0200 Subject: [PATCH 035/101] Remove dependency of RC namespace in rc-importer --- .../client/ImporterWebsocketReceiver.js | 4 +-- .../client/admin/adminImport.js | 6 ++-- .../client/admin/adminImportHistory.js | 4 +-- .../client/admin/adminImportPrepare.js | 9 +++--- .../client/admin/adminImportProgress.js | 3 +- packages/rocketchat-importer/package.js | 4 +++ .../server/classes/ImporterBase.js | 29 ++++++++++--------- .../methods/downloadPublicImportFile.js | 3 +- .../server/methods/getImportFileData.js | 3 +- .../server/methods/getImportProgress.js | 4 +-- .../methods/getLatestImportOperations.js | 3 +- .../server/methods/getSelectionData.js | 4 +-- .../server/methods/prepareImport.js | 4 +-- .../server/methods/restartImport.js | 4 +-- .../server/methods/setupImporter.js | 4 +-- .../server/methods/startImport.js | 4 +-- .../server/methods/uploadImportFile.js | 3 +- .../server/models/Imports.js | 4 +-- .../server/models/RawImports.js | 4 +-- .../server/startup/store.js | 7 +++-- 20 files changed, 60 insertions(+), 50 deletions(-) diff --git a/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js b/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js index 7c0d52e781be..6751dff6689f 100644 --- a/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js +++ b/packages/rocketchat-importer/client/ImporterWebsocketReceiver.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { CachedCollectionManager } from 'meteor/rocketchat:ui-cached-collection'; class ImporterWebsocketReceiverDef { constructor() { this.streamer = new Meteor.Streamer('importers'); this.callbacks = []; - RocketChat.CachedCollectionManager.onLogin(() => { + CachedCollectionManager.onLogin(() => { this.streamer.on('progress', this.progressUpdated.bind(this)); }); } diff --git a/packages/rocketchat-importer/client/admin/adminImport.js b/packages/rocketchat-importer/client/admin/adminImport.js index 71ecda141480..0dbc3a5d63c6 100644 --- a/packages/rocketchat-importer/client/admin/adminImport.js +++ b/packages/rocketchat-importer/client/admin/adminImport.js @@ -3,12 +3,12 @@ import { Importers } from 'meteor/rocketchat:importer'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { t, handleError } from 'meteor/rocketchat:utils'; Template.adminImport.helpers({ isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, getDescription(importer) { return TAPi18n.__('Importer_From_Description', { from: importer.name }); diff --git a/packages/rocketchat-importer/client/admin/adminImportHistory.js b/packages/rocketchat-importer/client/admin/adminImportHistory.js index 76f81a877753..9a33fd86ec99 100644 --- a/packages/rocketchat-importer/client/admin/adminImportHistory.js +++ b/packages/rocketchat-importer/client/admin/adminImportHistory.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; import { ReactiveVar } from 'meteor/reactive-var'; @@ -11,7 +11,7 @@ import { API } from 'meteor/rocketchat:api'; Template.adminImportHistory.helpers({ isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, importers() { return Importers.getAll(); diff --git a/packages/rocketchat-importer/client/admin/adminImportPrepare.js b/packages/rocketchat-importer/client/admin/adminImportPrepare.js index b58c95f61697..ff98bd19bc35 100644 --- a/packages/rocketchat-importer/client/admin/adminImportPrepare.js +++ b/packages/rocketchat-importer/client/admin/adminImportPrepare.js @@ -4,14 +4,15 @@ import { Importers } from 'meteor/rocketchat:importer'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { settings } from 'meteor/rocketchat:settings'; +import { t, handleError } from 'meteor/rocketchat:utils'; import { API } from 'meteor/rocketchat:api'; import toastr from 'toastr'; Template.adminImportPrepare.helpers({ isAdmin() { - return RocketChat.authz.hasRole(Meteor.userId(), 'admin'); + return hasRole(Meteor.userId(), 'admin'); }, importer() { const importerKey = FlowRouter.getParam('importer'); @@ -34,7 +35,7 @@ Template.adminImportPrepare.helpers({ return Template.instance().message_count.get(); }, fileSizeLimitMessage() { - const maxFileSize = RocketChat.settings.get('FileUpload_MaxFileSize'); + const maxFileSize = settings.get('FileUpload_MaxFileSize'); let message; if (maxFileSize > 0) { diff --git a/packages/rocketchat-importer/client/admin/adminImportProgress.js b/packages/rocketchat-importer/client/admin/adminImportProgress.js index 4c18ca511268..e3571a946a3d 100644 --- a/packages/rocketchat-importer/client/admin/adminImportProgress.js +++ b/packages/rocketchat-importer/client/admin/adminImportProgress.js @@ -3,8 +3,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Importers, ImporterWebsocketReceiver, ProgressStep } from 'meteor/rocketchat:importer'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { t } from 'meteor/rocketchat:utils'; -import { handleError } from 'meteor/rocketchat:lib'; +import { t, handleError } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; Template.adminImportProgress.helpers({ diff --git a/packages/rocketchat-importer/package.js b/packages/rocketchat-importer/package.js index 71fe8869d538..a936d939ea15 100644 --- a/packages/rocketchat-importer/package.js +++ b/packages/rocketchat-importer/package.js @@ -12,6 +12,10 @@ Package.onUse(function(api) { 'check', 'rocketchat:utils', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:authorization', + 'rocketchat:ui-cached-collection', + 'rocketchat:settings', 'rocketchat:api', 'rocketchat:logger', 'rocketchat:file-upload', diff --git a/packages/rocketchat-importer/server/classes/ImporterBase.js b/packages/rocketchat-importer/server/classes/ImporterBase.js index 036161e3ffd6..a7853c1cc73b 100644 --- a/packages/rocketchat-importer/server/classes/ImporterBase.js +++ b/packages/rocketchat-importer/server/classes/ImporterBase.js @@ -6,9 +6,10 @@ import { Imports } from '../models/Imports'; import { ImporterInfo } from '../../lib/ImporterInfo'; import { RawImports } from '../models/RawImports'; import { ImporterWebsocket } from './ImporterWebsocket'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Settings } from 'meteor/rocketchat:models'; import { Logger } from 'meteor/rocketchat:logger'; import { FileUpload } from 'meteor/rocketchat:file-upload'; +import { sendMessage } from 'meteor/rocketchat:lib'; import http from 'http'; import fs from 'fs'; import https from 'https'; @@ -230,24 +231,24 @@ export class Base { switch (step) { case ProgressStep.IMPORTING_STARTED: - this.oldSettings.Accounts_AllowedDomainsList = RocketChat.models.Settings.findOneById('Accounts_AllowedDomainsList').value; - RocketChat.models.Settings.updateValueById('Accounts_AllowedDomainsList', ''); + this.oldSettings.Accounts_AllowedDomainsList = Settings.findOneById('Accounts_AllowedDomainsList').value; + Settings.updateValueById('Accounts_AllowedDomainsList', ''); - this.oldSettings.Accounts_AllowUsernameChange = RocketChat.models.Settings.findOneById('Accounts_AllowUsernameChange').value; - RocketChat.models.Settings.updateValueById('Accounts_AllowUsernameChange', true); + this.oldSettings.Accounts_AllowUsernameChange = Settings.findOneById('Accounts_AllowUsernameChange').value; + Settings.updateValueById('Accounts_AllowUsernameChange', true); - this.oldSettings.FileUpload_MaxFileSize = RocketChat.models.Settings.findOneById('FileUpload_MaxFileSize').value; - RocketChat.models.Settings.updateValueById('FileUpload_MaxFileSize', -1); + this.oldSettings.FileUpload_MaxFileSize = Settings.findOneById('FileUpload_MaxFileSize').value; + Settings.updateValueById('FileUpload_MaxFileSize', -1); - this.oldSettings.FileUpload_MediaTypeWhiteList = RocketChat.models.Settings.findOneById('FileUpload_MediaTypeWhiteList').value; - RocketChat.models.Settings.updateValueById('FileUpload_MediaTypeWhiteList', '*'); + this.oldSettings.FileUpload_MediaTypeWhiteList = Settings.findOneById('FileUpload_MediaTypeWhiteList').value; + Settings.updateValueById('FileUpload_MediaTypeWhiteList', '*'); break; case ProgressStep.DONE: case ProgressStep.ERROR: - RocketChat.models.Settings.updateValueById('Accounts_AllowedDomainsList', this.oldSettings.Accounts_AllowedDomainsList); - RocketChat.models.Settings.updateValueById('Accounts_AllowUsernameChange', this.oldSettings.Accounts_AllowUsernameChange); - RocketChat.models.Settings.updateValueById('FileUpload_MaxFileSize', this.oldSettings.FileUpload_MaxFileSize); - RocketChat.models.Settings.updateValueById('FileUpload_MediaTypeWhiteList', this.oldSettings.FileUpload_MediaTypeWhiteList); + Settings.updateValueById('Accounts_AllowedDomainsList', this.oldSettings.Accounts_AllowedDomainsList); + Settings.updateValueById('Accounts_AllowUsernameChange', this.oldSettings.Accounts_AllowUsernameChange); + Settings.updateValueById('FileUpload_MaxFileSize', this.oldSettings.FileUpload_MaxFileSize); + Settings.updateValueById('FileUpload_MediaTypeWhiteList', this.oldSettings.FileUpload_MediaTypeWhiteList); break; } @@ -421,7 +422,7 @@ export class Base { msg._id = details.message_id; } - return RocketChat.sendMessage(user, msg, room, true); + return sendMessage(user, msg, room, true); } }); })); diff --git a/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js b/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js index 1f44d7a99d80..d45d3c7f2caa 100644 --- a/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js +++ b/packages/rocketchat-importer/server/methods/downloadPublicImportFile.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; import { RocketChatImportFileInstance } from '../startup/store'; import { ProgressStep } from '../../lib/ImporterProgressStep'; +import { hasRole } from 'meteor/rocketchat:authorization'; import http from 'http'; import fs from 'fs'; @@ -24,7 +25,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'downloadPublicImportFile' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'downloadPublicImportFile' }); } diff --git a/packages/rocketchat-importer/server/methods/getImportFileData.js b/packages/rocketchat-importer/server/methods/getImportFileData.js index 6e143aca2f8d..a58ffaec2235 100644 --- a/packages/rocketchat-importer/server/methods/getImportFileData.js +++ b/packages/rocketchat-importer/server/methods/getImportFileData.js @@ -1,6 +1,7 @@ import { RocketChatImportFileInstance } from '../startup/store'; import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; +import { hasRole } from 'meteor/rocketchat:authorization'; import { ProgressStep } from '../../lib/ImporterProgressStep'; import path from 'path'; @@ -12,7 +13,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getImportFileData' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'getImportFileData' }); } diff --git a/packages/rocketchat-importer/server/methods/getImportProgress.js b/packages/rocketchat-importer/server/methods/getImportProgress.js index 145003b24278..db5b8a9439a8 100644 --- a/packages/rocketchat-importer/server/methods/getImportProgress.js +++ b/packages/rocketchat-importer/server/methods/getImportProgress.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ getImportProgress(key) { @@ -8,7 +8,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getImportProgress' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/getLatestImportOperations.js b/packages/rocketchat-importer/server/methods/getLatestImportOperations.js index c6977dbc2727..78e83721c845 100644 --- a/packages/rocketchat-importer/server/methods/getLatestImportOperations.js +++ b/packages/rocketchat-importer/server/methods/getLatestImportOperations.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Imports } from '../models/Imports'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ getLatestImportOperations() { @@ -9,7 +10,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getLatestImportOperations' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'getLatestImportOperations' }); } diff --git a/packages/rocketchat-importer/server/methods/getSelectionData.js b/packages/rocketchat-importer/server/methods/getSelectionData.js index c8ff1f625949..e24a6d3819ac 100644 --- a/packages/rocketchat-importer/server/methods/getSelectionData.js +++ b/packages/rocketchat-importer/server/methods/getSelectionData.js @@ -3,7 +3,7 @@ import { Importers, ProgressStep, } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ getSelectionData(key) { @@ -11,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getSelectionData' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/prepareImport.js b/packages/rocketchat-importer/server/methods/prepareImport.js index 8f9c7e06036b..7a3677a4ac07 100644 --- a/packages/rocketchat-importer/server/methods/prepareImport.js +++ b/packages/rocketchat-importer/server/methods/prepareImport.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Importers } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ prepareImport(key, dataURI, contentType, fileName) { @@ -9,7 +9,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'prepareImport' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/restartImport.js b/packages/rocketchat-importer/server/methods/restartImport.js index 508fdaa352b0..e2c6733bf144 100644 --- a/packages/rocketchat-importer/server/methods/restartImport.js +++ b/packages/rocketchat-importer/server/methods/restartImport.js @@ -3,7 +3,7 @@ import { Importers, ProgressStep, } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ restartImport(key) { @@ -11,7 +11,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'restartImport' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/setupImporter.js b/packages/rocketchat-importer/server/methods/setupImporter.js index 2498b8d950c1..5aac8afdbffe 100644 --- a/packages/rocketchat-importer/server/methods/setupImporter.js +++ b/packages/rocketchat-importer/server/methods/setupImporter.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ setupImporter(key) { @@ -8,7 +8,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setupImporter' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'setupImporter' }); } diff --git a/packages/rocketchat-importer/server/methods/startImport.js b/packages/rocketchat-importer/server/methods/startImport.js index 38a7911178ef..49ecfdfa7e9b 100644 --- a/packages/rocketchat-importer/server/methods/startImport.js +++ b/packages/rocketchat-importer/server/methods/startImport.js @@ -5,7 +5,7 @@ import { SelectionChannel, SelectionUser, } from 'meteor/rocketchat:importer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; Meteor.methods({ startImport(key, input) { @@ -14,7 +14,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'startImport' }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'run-import')) { + if (!hasPermission(Meteor.userId(), 'run-import')) { throw new Meteor.Error('error-action-not-allowed', 'Importing is not allowed', { method: 'startImport' }); } diff --git a/packages/rocketchat-importer/server/methods/uploadImportFile.js b/packages/rocketchat-importer/server/methods/uploadImportFile.js index ded0e5c3ab83..c2166e8ae736 100644 --- a/packages/rocketchat-importer/server/methods/uploadImportFile.js +++ b/packages/rocketchat-importer/server/methods/uploadImportFile.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Importers } from 'meteor/rocketchat:importer'; import { RocketChatFile } from 'meteor/rocketchat:file'; import { RocketChatImportFileInstance } from '../startup/store'; +import { hasRole } from 'meteor/rocketchat:authorization'; Meteor.methods({ uploadImportFile(binaryContent, contentType, fileName, importerKey) { @@ -11,7 +12,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'uploadImportFile' }); } - if (!RocketChat.authz.hasRole(userId, 'admin')) { + if (!hasRole(userId, 'admin')) { throw new Meteor.Error('not_authorized', 'User not authorized', { method: 'uploadImportFile' }); } diff --git a/packages/rocketchat-importer/server/models/Imports.js b/packages/rocketchat-importer/server/models/Imports.js index 06e06a5bab08..a50b27ddf963 100644 --- a/packages/rocketchat-importer/server/models/Imports.js +++ b/packages/rocketchat-importer/server/models/Imports.js @@ -1,7 +1,7 @@ import { ProgressStep } from '../../lib/ImporterProgressStep'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from 'meteor/rocketchat:models'; -class ImportsModel extends RocketChat.models._Base { +class ImportsModel extends Base { constructor() { super('import'); } diff --git a/packages/rocketchat-importer/server/models/RawImports.js b/packages/rocketchat-importer/server/models/RawImports.js index 3b850d80c6a9..3a761eb15dc4 100644 --- a/packages/rocketchat-importer/server/models/RawImports.js +++ b/packages/rocketchat-importer/server/models/RawImports.js @@ -1,6 +1,6 @@ -import { Base as _Base } from 'meteor/rocketchat:models'; +import { Base } from 'meteor/rocketchat:models'; -class RawImportsModel extends _Base { +class RawImportsModel extends Base { constructor() { super('raw_imports'); } diff --git a/packages/rocketchat-importer/server/startup/store.js b/packages/rocketchat-importer/server/startup/store.js index d996b1e9af2e..afe6b66139c5 100644 --- a/packages/rocketchat-importer/server/startup/store.js +++ b/packages/rocketchat-importer/server/startup/store.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { RocketChatFile } from 'meteor/rocketchat:file'; +import { settings } from 'meteor/rocketchat:settings'; export let RocketChatImportFileInstance; @@ -7,9 +8,9 @@ Meteor.startup(function() { const RocketChatStore = RocketChatFile.FileSystem; let path = '/tmp/rocketchat-importer'; - if (RocketChat.settings.get('ImportFile_FileSystemPath') != null) { - if (RocketChat.settings.get('ImportFile_FileSystemPath').trim() !== '') { - path = RocketChat.settings.get('ImportFile_FileSystemPath'); + if (settings.get('ImportFile_FileSystemPath') != null) { + if (settings.get('ImportFile_FileSystemPath').trim() !== '') { + path = settings.get('ImportFile_FileSystemPath'); } } From 58ad493a14afa2b97b24ccca8c973e2379e8be15 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 17:10:46 -0200 Subject: [PATCH 036/101] Remove dependency of RC namespace in rc-issue-links --- packages/rocketchat-issuelinks/client/client.js | 9 +++++---- packages/rocketchat-issuelinks/package.js | 3 ++- packages/rocketchat-issuelinks/server/settings.js | 6 +++--- 3 files changed, 10 insertions(+), 8 deletions(-) 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', From 57837864e5b35203b0b87fcc962bda2b4f8dc8fd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 17:11:23 -0200 Subject: [PATCH 037/101] Remove dependency of RC namespace in rc-katex --- 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 ++++---- .../client/messageBox.js | 9 +++++---- packages/rocketchat-ui-message/package.js | 1 + 7 files changed, 24 insertions(+), 20 deletions(-) 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-ui-message/client/messageBox.js b/packages/rocketchat-ui-message/client/messageBox.js index a1912e680d09..9ee1867c6e29 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', From e9be3a43cb138081d6f2226f9f29b25fcaa0c3dc Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 17:11:48 -0200 Subject: [PATCH 038/101] Move templateVarHandler fn to rc-utils --- .../rocketchat-lib/lib/templateVarHandler.js | 3 ++ packages/rocketchat-utils/client/index.js | 1 + .../client/lib/templateVarHandler.js | 42 +++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 packages/rocketchat-utils/client/lib/templateVarHandler.js diff --git a/packages/rocketchat-lib/lib/templateVarHandler.js b/packages/rocketchat-lib/lib/templateVarHandler.js index d823e4841f36..ed0fbf1d2b73 100644 --- a/packages/rocketchat-lib/lib/templateVarHandler.js +++ b/packages/rocketchat-lib/lib/templateVarHandler.js @@ -38,3 +38,6 @@ RocketChat.templateVarHandler = function(variable, object) { return tmpVariable; } }; +import { templateVarHandler } from 'meteor/rocketchat:utils'; + +RocketChat.templateVarHandler = templateVarHandler; diff --git a/packages/rocketchat-utils/client/index.js b/packages/rocketchat-utils/client/index.js index 3fc66523a403..6937c1c0336d 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/client/lib/templateVarHandler.js b/packages/rocketchat-utils/client/lib/templateVarHandler.js new file mode 100644 index 000000000000..3d31f8d9a43a --- /dev/null +++ b/packages/rocketchat-utils/client/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; + } +}; From 406e0374dd07d36021268ae01cd80b0b9f67ac75 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 28 Jan 2019 17:12:09 -0200 Subject: [PATCH 039/101] Remove dependency of RC namespace in rc-ldap --- 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 +- 7 files changed, 90 insertions(+), 77 deletions(-) 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'); } From 0206d2817d9c4a0b09442e20b869ed13d7613ed8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 14:30:20 -0200 Subject: [PATCH 040/101] Remove dependency of RC namespace in rc-livestream --- .../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 +-- 8 files changed, 50 insertions(+), 37 deletions(-) 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', From b6b980b96a83c205a0d4df8e77b50e8037be1761 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 14:33:03 -0200 Subject: [PATCH 041/101] Remove dependency of RC namespace in rc-mail-messages --- .../rocketchat-mail-messages/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 ---------------- .../rocketchat-mail-messages/server/startup.js | 4 ++-- .../rocketchat-models/server/models/Users.js | 15 +++++++++++++++ 10 files changed, 34 insertions(+), 31 deletions(-) delete mode 100644 packages/rocketchat-mail-messages/server/models/Users.js 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 } }); From 7c7b063cae6a0141763686f89974cb679b04c801 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 15:00:28 -0200 Subject: [PATCH 042/101] Remove dependency of RC namespace in rc-mapview --- packages/rocketchat-mapview/client/mapview.js | 7 ++++--- packages/rocketchat-mapview/package.js | 3 ++- packages/rocketchat-mapview/server/settings.js | 6 +++--- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/rocketchat-mapview/client/mapview.js b/packages/rocketchat-mapview/client/mapview.js index bd6efc7962bf..1689f77f445e 100644 --- a/packages/rocketchat-mapview/client/mapview.js +++ b/packages/rocketchat-mapview/client/mapview.js @@ -1,5 +1,6 @@ import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; /* * MapView is a named function that will replace geolocation in messages with a Google Static Map * @param {Object} message - The message object @@ -8,7 +9,7 @@ import { RocketChat } from 'meteor/rocketchat:lib'; function MapView(message) { // get MapView settings - const mv_googlekey = RocketChat.settings.get('MapView_GMapsAPIKey'); + const mv_googlekey = settings.get('MapView_GMapsAPIKey'); if (message.location) { @@ -26,4 +27,4 @@ function MapView(message) { return message; } -RocketChat.callbacks.add('renderMessage', MapView, RocketChat.callbacks.priority.HIGH, 'mapview'); +callbacks.add('renderMessage', MapView, callbacks.priority.HIGH, 'mapview'); diff --git a/packages/rocketchat-mapview/package.js b/packages/rocketchat-mapview/package.js index a1f7f3b204ac..167cf84cd90c 100644 --- a/packages/rocketchat-mapview/package.js +++ b/packages/rocketchat-mapview/package.js @@ -7,7 +7,8 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', 'tap:i18n', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-mapview/server/settings.js b/packages/rocketchat-mapview/server/settings.js index 56dd471591df..1e592d8892a1 100644 --- a/packages/rocketchat-mapview/server/settings.js +++ b/packages/rocketchat-mapview/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('MapView_Enabled', false, { type: 'boolean', group: 'Message', section: 'Google Maps', public: true, i18nLabel: 'MapView_Enabled', i18nDescription: 'MapView_Enabled_Description' }); - return RocketChat.settings.add('MapView_GMapsAPIKey', '', { type: 'string', group: 'Message', section: 'Google Maps', public: true, i18nLabel: 'MapView_GMapsAPIKey', i18nDescription: 'MapView_GMapsAPIKey_Description' }); + settings.add('MapView_Enabled', false, { type: 'boolean', group: 'Message', section: 'Google Maps', public: true, i18nLabel: 'MapView_Enabled', i18nDescription: 'MapView_Enabled_Description' }); + return settings.add('MapView_GMapsAPIKey', '', { type: 'string', group: 'Message', section: 'Google Maps', public: true, i18nLabel: 'MapView_GMapsAPIKey', i18nDescription: 'MapView_GMapsAPIKey_Description' }); }); From e08ad7e81d5861048666b4119cfac2d5735bc262 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 15:00:56 -0200 Subject: [PATCH 043/101] Remove dependency of RC namespace in rc-mentions --- packages/rocketchat-mentions/client/client.js | 11 ++++++----- packages/rocketchat-mentions/package.js | 5 ++++- .../methods/getUserMentionsByChannel.js | 8 ++++---- packages/rocketchat-mentions/server/server.js | 19 +++++++++++-------- 4 files changed, 25 insertions(+), 18 deletions(-) diff --git a/packages/rocketchat-mentions/client/client.js b/packages/rocketchat-mentions/client/client.js index 2f06f367447f..efec44bd9310 100644 --- a/packages/rocketchat-mentions/client/client.js +++ b/packages/rocketchat-mentions/client/client.js @@ -1,13 +1,14 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { settings } from 'meteor/rocketchat:settings'; import Mentions from '../lib/Mentions'; const MentionsClient = new Mentions({ pattern() { - return RocketChat.settings.get('UTF8_Names_Validation'); + return settings.get('UTF8_Names_Validation'); }, useRealName() { - return RocketChat.settings.get('UI_Use_Real_Name'); + return settings.get('UI_Use_Real_Name'); }, me() { const me = Meteor.user(); @@ -15,5 +16,5 @@ const MentionsClient = new Mentions({ }, }); -RocketChat.callbacks.add('renderMessage', (message) => MentionsClient.parse(message), RocketChat.callbacks.priority.MEDIUM, 'mentions-message'); -RocketChat.callbacks.add('renderMentions', (message) => MentionsClient.parse(message), RocketChat.callbacks.priority.MEDIUM, 'mentions-mentions'); +callbacks.add('renderMessage', (message) => MentionsClient.parse(message), callbacks.priority.MEDIUM, 'mentions-message'); +callbacks.add('renderMentions', (message) => MentionsClient.parse(message), callbacks.priority.MEDIUM, 'mentions-mentions'); diff --git a/packages/rocketchat-mentions/package.js b/packages/rocketchat-mentions/package.js index 96cf55b02a1b..34a31e101339 100644 --- a/packages/rocketchat-mentions/package.js +++ b/packages/rocketchat-mentions/package.js @@ -8,7 +8,10 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:notifications', + 'rocketchat:models', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-mentions/server/methods/getUserMentionsByChannel.js b/packages/rocketchat-mentions/server/methods/getUserMentionsByChannel.js index ac1b002ba0d4..01d28687ce0d 100644 --- a/packages/rocketchat-mentions/server/methods/getUserMentionsByChannel.js +++ b/packages/rocketchat-mentions/server/methods/getUserMentionsByChannel.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Users, Messages } from 'meteor/rocketchat:models'; Meteor.methods({ getUserMentionsByChannel({ roomId, options }) { @@ -10,14 +10,14 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getUserMentionsByChannel' }); } - const room = RocketChat.models.Rooms.findOneById(roomId); + const room = Rooms.findOneById(roomId); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'getUserMentionsByChannel' }); } - const user = RocketChat.models.Users.findOneById(Meteor.userId()); + const user = Users.findOneById(Meteor.userId()); - return RocketChat.models.Messages.findVisibleByMentionAndRoomId(user.username, roomId, options).fetch(); + return Messages.findVisibleByMentionAndRoomId(user.username, roomId, options).fetch(); }, }); diff --git a/packages/rocketchat-mentions/server/server.js b/packages/rocketchat-mentions/server/server.js index 0babdb13cc46..4fdf6556ef8b 100644 --- a/packages/rocketchat-mentions/server/server.js +++ b/packages/rocketchat-mentions/server/server.js @@ -1,23 +1,26 @@ 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 { Users, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import _ from 'underscore'; import MentionsServer from './Mentions'; const mention = new MentionsServer({ - pattern: () => RocketChat.settings.get('UTF8_Names_Validation'), - messageMaxAll: () => RocketChat.settings.get('Message_MaxAll'), + pattern: () => settings.get('UTF8_Names_Validation'), + messageMaxAll: () => settings.get('Message_MaxAll'), getUsers: (usernames) => Meteor.users.find({ username: { $in: _.unique(usernames) } }, { fields: { _id: true, username: true, name: 1 } }).fetch(), - getUser: (userId) => RocketChat.models.Users.findOneById(userId), - getTotalChannelMembers: (rid) => RocketChat.models.Subscriptions.findByRoomId(rid).count(), - getChannels: (channels) => RocketChat.models.Rooms.find({ name: { $in: _.unique(channels) }, t: 'c' }, { fields: { _id: 1, name: 1 } }).fetch(), + getUser: (userId) => Users.findOneById(userId), + getTotalChannelMembers: (rid) => Subscriptions.findByRoomId(rid).count(), + getChannels: (channels) => Rooms.find({ name: { $in: _.unique(channels) }, t: 'c' }, { fields: { _id: 1, name: 1 } }).fetch(), onMaxRoomMembersExceeded({ sender, rid }) { // Get the language of the user for the error notification. const { language } = this.getUser(sender._id); const msg = TAPi18n.__('Group_mentions_disabled_x_members', { total: this.messageMaxAll }, language); - RocketChat.Notifications.notifyUser(sender._id, 'message', { + Notifications.notifyUser(sender._id, 'message', { _id: Random.id(), rid, ts: new Date, @@ -32,4 +35,4 @@ const mention = new MentionsServer({ }); }, }); -RocketChat.callbacks.add('beforeSaveMessage', (message) => mention.execute(message), RocketChat.callbacks.priority.HIGH, 'mentions'); +callbacks.add('beforeSaveMessage', (message) => mention.execute(message), callbacks.priority.HIGH, 'mentions'); From 8bb2a9628a521d8547d3214ac1ec7eff5702a67e Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 15:16:42 -0200 Subject: [PATCH 044/101] Remove dependency of RC namespace in rc-mentions-flextab --- packages/rocketchat-mentions-flextab/client/actionButton.js | 5 ++--- packages/rocketchat-mentions-flextab/client/tabBar.js | 4 ++-- packages/rocketchat-mentions-flextab/package.js | 3 ++- .../server/publications/mentionedMessages.js | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/rocketchat-mentions-flextab/client/actionButton.js b/packages/rocketchat-mentions-flextab/client/actionButton.js index 58fd25e89e16..f47380e6d644 100644 --- a/packages/rocketchat-mentions-flextab/client/actionButton.js +++ b/packages/rocketchat-mentions-flextab/client/actionButton.js @@ -1,10 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { RoomHistoryManager } from 'meteor/rocketchat:ui'; +import { MessageAction, RoomHistoryManager } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'jump-to-message', icon: 'jump', label: 'Jump_to_message', diff --git a/packages/rocketchat-mentions-flextab/client/tabBar.js b/packages/rocketchat-mentions-flextab/client/tabBar.js index e1b25e8c59ba..768da54e5998 100644 --- a/packages/rocketchat-mentions-flextab/client/tabBar.js +++ b/packages/rocketchat-mentions-flextab/client/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(function() { - return RocketChat.TabBar.addButton({ + return TabBar.addButton({ groups: ['channel', 'group'], id: 'mentions', i18nTitle: 'Mentions', diff --git a/packages/rocketchat-mentions-flextab/package.js b/packages/rocketchat-mentions-flextab/package.js index 726ce88376b1..898b19936329 100644 --- a/packages/rocketchat-mentions-flextab/package.js +++ b/packages/rocketchat-mentions-flextab/package.js @@ -10,7 +10,8 @@ Package.onUse(function(api) { 'mongo', 'ecmascript', 'less', - 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:ui-utils', 'templating', ]); api.addFiles('client/views/stylesheets/mentionsFlexTab.less', 'client'); diff --git a/packages/rocketchat-mentions-flextab/server/publications/mentionedMessages.js b/packages/rocketchat-mentions-flextab/server/publications/mentionedMessages.js index c26d68c4b598..0ebf128160b5 100644 --- a/packages/rocketchat-mentions-flextab/server/publications/mentionedMessages.js +++ b/packages/rocketchat-mentions-flextab/server/publications/mentionedMessages.js @@ -1,19 +1,19 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Messages } from 'meteor/rocketchat:models'; Meteor.publish('mentionedMessages', function(rid, limit = 50) { if (!this.userId) { return this.ready(); } const publication = this; - const user = RocketChat.models.Users.findOneById(this.userId); + const user = Users.findOneById(this.userId); if (!user) { return this.ready(); } if (!Meteor.call('canAccessRoom', rid, this.userId)) { return this.ready(); } - const cursorHandle = RocketChat.models.Messages.findVisibleByMentionAndRoomId(user.username, rid, { + const cursorHandle = Messages.findVisibleByMentionAndRoomId(user.username, rid, { sort: { ts: -1, }, From ea2b69931958076dcc48c4d37f88ecf8b9ebc2ec Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 15:18:10 -0200 Subject: [PATCH 045/101] Remove depedency of RC namespace in rc-message-attachements --- packages/rocketchat-message-action/package.js | 1 - .../client/messageAttachment.js | 11 ++++++----- packages/rocketchat-message-attachments/package.js | 2 ++ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/rocketchat-message-action/package.js b/packages/rocketchat-message-action/package.js index 2ff31877235e..5dff219226d8 100644 --- a/packages/rocketchat-message-action/package.js +++ b/packages/rocketchat-message-action/package.js @@ -9,7 +9,6 @@ Package.onUse(function(api) { api.use([ 'templating', 'ecmascript', - 'rocketchat:lib', ]); api.addFiles('client/stylesheets/messageAction.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-message-attachments/client/messageAttachment.js b/packages/rocketchat-message-attachments/client/messageAttachment.js index 93b70ba62bf3..1e6b32fc2a3c 100644 --- a/packages/rocketchat-message-attachments/client/messageAttachment.js +++ b/packages/rocketchat-message-attachments/client/messageAttachment.js @@ -2,7 +2,8 @@ import { Meteor } from 'meteor/meteor'; import { DateFormat } from 'meteor/rocketchat:lib'; import { fixCordova } from 'meteor/rocketchat:lazy-load'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; +import { Users } from 'meteor/rocketchat:models'; import { renderMessageBody } from 'meteor/rocketchat:ui-utils'; const colors = { @@ -28,11 +29,11 @@ Template.messageAttachment.helpers({ }, loadImage() { if (this.downloadImages !== true) { - const user = RocketChat.models.Users.findOne({ _id: Meteor.userId() }, { fields: { 'settings.autoImageLoad' : 1 } }); - if (RocketChat.getUserPreference(user, 'autoImageLoad') === false) { + const user = Users.findOne({ _id: Meteor.userId() }, { fields: { 'settings.autoImageLoad' : 1 } }); + if (getUserPreference(user, 'autoImageLoad') === false) { return false; } - if (Meteor.Device.isPhone() && RocketChat.getUserPreference(user, 'saveMobileBandwidth') !== true) { + if (Meteor.Device.isPhone() && getUserPreference(user, 'saveMobileBandwidth') !== true) { return false; } } @@ -54,7 +55,7 @@ Template.messageAttachment.helpers({ if (this.collapsed != null) { return this.collapsed; } else { - return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; + return getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; } }, time() { diff --git a/packages/rocketchat-message-attachments/package.js b/packages/rocketchat-message-attachments/package.js index 956c10513ea2..2c8e22737fbd 100644 --- a/packages/rocketchat-message-attachments/package.js +++ b/packages/rocketchat-message-attachments/package.js @@ -14,6 +14,8 @@ Package.onUse(function(api) { 'rocketchat:e2e', 'rocketchat:ui-message', 'rocketchat:ui-utils', + 'rocketchat:utils', + 'rocketchat:models', ]); api.addFiles('client/stylesheets/messageAttachments.css', 'client'); api.mainModule('client/index.js', 'client'); From 4da85d9fd907d8b30b2721e150c0b7ea4c34ab5a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 15:27:17 -0200 Subject: [PATCH 046/101] Remove dependdency of RC namespace in rc-message-mark-as-unread --- .../client/actionButton.js | 7 ++++--- .../rocketchat-message-mark-as-unread/package.js | 5 +++-- .../server/unreadMessages.js | 12 ++++++------ 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/rocketchat-message-mark-as-unread/client/actionButton.js b/packages/rocketchat-message-mark-as-unread/client/actionButton.js index 4e7a4966715c..57e1e410d692 100644 --- a/packages/rocketchat-message-mark-as-unread/client/actionButton.js +++ b/packages/rocketchat-message-mark-as-unread/client/actionButton.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { FlowRouter } from 'meteor/kadira:flow-router'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { RoomManager, ChatSubscription } from 'meteor/rocketchat:ui'; +import { RoomManager, MessageAction } from 'meteor/rocketchat:ui-utils'; +import { handleError } from 'meteor/rocketchat:utils'; +import { ChatSubscription } from 'meteor/rocketchat:models'; Meteor.startup(() => { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'mark-message-as-unread', icon: 'flag', label: 'Mark_as_unread', diff --git a/packages/rocketchat-message-mark-as-unread/package.js b/packages/rocketchat-message-mark-as-unread/package.js index 40f1a1c1b8d9..45c82b3a4938 100644 --- a/packages/rocketchat-message-mark-as-unread/package.js +++ b/packages/rocketchat-message-mark-as-unread/package.js @@ -7,9 +7,10 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', 'rocketchat:logger', - 'rocketchat:ui', + 'rocketchat:models', + 'rocketchat:ui-utils', + 'rocketchat:utils', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js b/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js index 11ed3a839d97..a649537b4563 100644 --- a/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js +++ b/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, Subscriptions } from 'meteor/rocketchat:models'; import logger from './logger'; Meteor.methods({ @@ -12,7 +12,7 @@ Meteor.methods({ } if (room) { - const lastMessage = RocketChat.models.Messages.findVisibleByRoomId(room, { limit: 1, sort: { ts: -1 } }).fetch()[0]; + const lastMessage = Messages.findVisibleByRoomId(room, { limit: 1, sort: { ts: -1 } }).fetch()[0]; if (lastMessage == null) { throw new Meteor.Error('error-action-not-allowed', 'Not allowed', { @@ -21,10 +21,10 @@ Meteor.methods({ }); } - return RocketChat.models.Subscriptions.setAsUnreadByRoomIdAndUserId(lastMessage.rid, userId, lastMessage.ts); + return Subscriptions.setAsUnreadByRoomIdAndUserId(lastMessage.rid, userId, lastMessage.ts); } - const originalMessage = RocketChat.models.Messages.findOneById(firstUnreadMessage._id, { + const originalMessage = Messages.findOneById(firstUnreadMessage._id, { fields: { u: 1, rid: 1, @@ -38,11 +38,11 @@ Meteor.methods({ action: 'Unread_messages', }); } - const lastSeen = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(originalMessage.rid, userId).ls; + const lastSeen = Subscriptions.findOneByRoomIdAndUserId(originalMessage.rid, userId).ls; if (firstUnreadMessage.ts >= lastSeen) { return logger.connection.debug('Provided message is already marked as unread'); } logger.connection.debug(`Updating unread message of ${ originalMessage.ts } as the first unread`); - return RocketChat.models.Subscriptions.setAsUnreadByRoomIdAndUserId(originalMessage.rid, userId, originalMessage.ts); + return Subscriptions.setAsUnreadByRoomIdAndUserId(originalMessage.rid, userId, originalMessage.ts); }, }); From 1717135f858cbbcbf9fae76c8e0f1826eda710fc Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 15:57:35 -0200 Subject: [PATCH 047/101] Remove dependency of RC namespace in rc-message-pin --- .../client/actionButton.js | 29 +++++----- .../client/messageType.js | 4 +- .../client/pinMessage.js | 12 ++--- .../rocketchat-message-pin/client/tabBar.js | 9 ++-- packages/rocketchat-message-pin/package.js | 7 ++- .../rocketchat-message-pin/server/index.js | 1 - .../server/models/Rooms.js | 15 ------ .../server/pinMessage.js | 54 ++++++++++--------- .../server/publications/pinnedMessages.js | 6 +-- .../rocketchat-message-pin/server/settings.js | 7 +-- .../server/startup/indexes.js | 4 +- .../rocketchat-models/server/models/Rooms.js | 14 +++++ 12 files changed, 87 insertions(+), 75 deletions(-) delete mode 100644 packages/rocketchat-message-pin/server/models/Rooms.js diff --git a/packages/rocketchat-message-pin/client/actionButton.js b/packages/rocketchat-message-pin/client/actionButton.js index ee4a6526e432..5798a03de39f 100644 --- a/packages/rocketchat-message-pin/client/actionButton.js +++ b/packages/rocketchat-message-pin/client/actionButton.js @@ -1,12 +1,15 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { RoomHistoryManager } from 'meteor/rocketchat:ui'; +import { RoomHistoryManager, MessageAction } from 'meteor/rocketchat:ui-utils'; +import { handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; import toastr from 'toastr'; Meteor.startup(function() { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'pin-message', icon: 'pin', label: 'Pin_Message', @@ -21,17 +24,17 @@ Meteor.startup(function() { }); }, condition(message) { - if (!RocketChat.settings.get('Message_AllowPinning') || message.pinned || !RocketChat.models.Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { + if (!settings.get('Message_AllowPinning') || message.pinned || !Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { return false; } - return RocketChat.authz.hasAtLeastOnePermission('pin-message', message.rid); + return hasAtLeastOnePermission('pin-message', message.rid); }, order: 20, group: 'menu', }); - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'unpin-message', icon: 'pin', label: 'Unpin_Message', @@ -46,17 +49,17 @@ Meteor.startup(function() { }); }, condition(message) { - if (!RocketChat.settings.get('Message_AllowPinning') || !message.pinned || !RocketChat.models.Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { + if (!settings.get('Message_AllowPinning') || !message.pinned || !Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { return false; } - return RocketChat.authz.hasAtLeastOnePermission('pin-message', message.rid); + return hasAtLeastOnePermission('pin-message', message.rid); }, order: 21, group: 'menu', }); - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'jump-to-pin-message', icon: 'jump', label: 'Jump_to_message', @@ -69,7 +72,7 @@ Meteor.startup(function() { return RoomHistoryManager.getSurroundingMessages(message, 50); }, condition(message) { - if (!RocketChat.models.Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { + if (!Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { return false; } return true; @@ -78,7 +81,7 @@ Meteor.startup(function() { group: 'menu', }); - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'permalink-pinned', icon: 'permalink', label: 'Permalink', @@ -86,11 +89,11 @@ Meteor.startup(function() { context: ['pinned'], async action(event) { const message = this._arguments[1]; - $(event.currentTarget).attr('data-clipboard-text', await RocketChat.MessageAction.getPermaLink(message._id)); + $(event.currentTarget).attr('data-clipboard-text', await MessageAction.getPermaLink(message._id)); toastr.success(TAPi18n.__('Copied')); }, condition(message) { - if (!RocketChat.models.Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { + if (!Subscriptions.findOne({ rid: message.rid }, { fields: { _id: 1 } })) { return false; } return true; diff --git a/packages/rocketchat-message-pin/client/messageType.js b/packages/rocketchat-message-pin/client/messageType.js index 5a045ca29909..a0d01b0be306 100644 --- a/packages/rocketchat-message-pin/client/messageType.js +++ b/packages/rocketchat-message-pin/client/messageType.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { MessageTypes } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'message_pinned', system: true, message: 'Pinned_a_message', diff --git a/packages/rocketchat-message-pin/client/pinMessage.js b/packages/rocketchat-message-pin/client/pinMessage.js index 0b4a1a8459fe..9fffe740b97c 100644 --- a/packages/rocketchat-message-pin/client/pinMessage.js +++ b/packages/rocketchat-message-pin/client/pinMessage.js @@ -1,16 +1,16 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatMessage } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { ChatMessage, Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ pinMessage(message) { if (!Meteor.userId()) { return false; } - if (!RocketChat.settings.get('Message_AllowPinning')) { + if (!settings.get('Message_AllowPinning')) { return false; } - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null) { + if (Subscriptions.findOne({ rid: message.rid }) == null) { return false; } return ChatMessage.update({ @@ -25,10 +25,10 @@ Meteor.methods({ if (!Meteor.userId()) { return false; } - if (!RocketChat.settings.get('Message_AllowPinning')) { + if (!settings.get('Message_AllowPinning')) { return false; } - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null) { + if (Subscriptions.findOne({ rid: message.rid }) == null) { return false; } return ChatMessage.update({ diff --git a/packages/rocketchat-message-pin/client/tabBar.js b/packages/rocketchat-message-pin/client/tabBar.js index 478f7a1e2c46..a4bc83e2414f 100644 --- a/packages/rocketchat-message-pin/client/tabBar.js +++ b/packages/rocketchat-message-pin/client/tabBar.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { return Tracker.autorun(function() { - if (RocketChat.settings.get('Message_AllowPinning')) { - RocketChat.TabBar.addButton({ + if (settings.get('Message_AllowPinning')) { + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'pinned-messages', i18nTitle: 'Pinned_Messages', @@ -14,7 +15,7 @@ Meteor.startup(function() { order: 10, }); } else { - RocketChat.TabBar.removeButton('pinned-messages'); + TabBar.removeButton('pinned-messages'); } }); }); diff --git a/packages/rocketchat-message-pin/package.js b/packages/rocketchat-message-pin/package.js index 9f04d6f2d87b..822d480da378 100644 --- a/packages/rocketchat-message-pin/package.js +++ b/packages/rocketchat-message-pin/package.js @@ -8,8 +8,13 @@ Package.onUse(function(api) { api.use([ 'mongo', 'ecmascript', - 'rocketchat:lib', + 'rocketchat:ui-utils', 'rocketchat:utils', + 'rocketchat:settings', + 'rocketchat:authorization', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:lib', 'templating', ]); api.addFiles('client/views/stylesheets/messagepin.css', 'client'); diff --git a/packages/rocketchat-message-pin/server/index.js b/packages/rocketchat-message-pin/server/index.js index bfa1e3f15e1e..e4160692c732 100644 --- a/packages/rocketchat-message-pin/server/index.js +++ b/packages/rocketchat-message-pin/server/index.js @@ -1,4 +1,3 @@ -import './models/Rooms'; import './settings'; import './pinMessage'; import './publications/pinnedMessages'; diff --git a/packages/rocketchat-message-pin/server/models/Rooms.js b/packages/rocketchat-message-pin/server/models/Rooms.js deleted file mode 100644 index 23282cdcfd4d..000000000000 --- a/packages/rocketchat-message-pin/server/models/Rooms.js +++ /dev/null @@ -1,15 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.setLastMessagePinned = function(roomId, pinnedBy, pinned, pinnedAt) { - const query = { _id: roomId }; - - const update = { - $set: { - 'lastMessage.pinned': pinned, - 'lastMessage.pinnedAt': pinnedAt || new Date, - 'lastMessage.pinnedBy': pinnedBy, - }, - }; - - return this.update(query, update); -}; diff --git a/packages/rocketchat-message-pin/server/pinMessage.js b/packages/rocketchat-message-pin/server/pinMessage.js index 2458ed2b5377..bb68a967cf78 100644 --- a/packages/rocketchat-message-pin/server/pinMessage.js +++ b/packages/rocketchat-message-pin/server/pinMessage.js @@ -1,13 +1,17 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { isTheLastMessage } from 'meteor/rocketchat:lib'; import { getAvatarUrlFromUsername } from 'meteor/rocketchat:utils'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Subscriptions, Messages, Users, Rooms } from 'meteor/rocketchat:models'; const recursiveRemove = (msg, deep = 1) => { if (!msg) { return; } - if (deep > RocketChat.settings.get('Message_QuoteChainLimit')) { + if (deep > settings.get('Message_QuoteChainLimit')) { delete msg.attachments; return msg; } @@ -30,23 +34,23 @@ Meteor.methods({ }); } - if (!RocketChat.settings.get('Message_AllowPinning')) { + if (!settings.get('Message_AllowPinning')) { throw new Meteor.Error('error-action-not-allowed', 'Message pinning not allowed', { method: 'pinMessage', action: 'Message_pinning', }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'pin-message')) { + if (!hasPermission(Meteor.userId(), 'pin-message')) { throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'pinMessage' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); if (!subscription) { return false; } - let originalMessage = RocketChat.models.Messages.findOneById(message._id); + let originalMessage = Messages.findOneById(message._id); if (originalMessage == null || originalMessage._id == null) { throw new Meteor.Error('error-invalid-message', 'Message you are pinning was not found', { method: 'pinMessage', @@ -55,11 +59,11 @@ Meteor.methods({ } // 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); } const room = Meteor.call('canAccessRoom', message.rid, Meteor.userId()); - const me = RocketChat.models.Users.findOneById(userId); + const me = Users.findOneById(userId); originalMessage.pinned = true; originalMessage.pinnedAt = pinnedAt || Date.now; @@ -68,11 +72,11 @@ Meteor.methods({ username: me.username, }; - originalMessage = RocketChat.callbacks.run('beforeSaveMessage', originalMessage); + originalMessage = callbacks.run('beforeSaveMessage', originalMessage); - RocketChat.models.Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned); - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned); + Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned); + if (isTheLastMessage(room, message)) { + Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned); } const attachments = []; @@ -85,7 +89,7 @@ Meteor.methods({ }); } - return RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser( + return Messages.createWithTypeRoomIdMessageAndUser( 'message_pinned', originalMessage.rid, '', @@ -112,23 +116,23 @@ Meteor.methods({ }); } - if (!RocketChat.settings.get('Message_AllowPinning')) { + if (!settings.get('Message_AllowPinning')) { throw new Meteor.Error('error-action-not-allowed', 'Message pinning not allowed', { method: 'unpinMessage', action: 'Message_pinning', }); } - if (!RocketChat.authz.hasPermission(Meteor.userId(), 'pin-message')) { + if (!hasPermission(Meteor.userId(), 'pin-message')) { throw new Meteor.Error('not-authorized', 'Not Authorized', { method: 'pinMessage' }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); if (!subscription) { return false; } - let originalMessage = RocketChat.models.Messages.findOneById(message._id); + let originalMessage = Messages.findOneById(message._id); if (originalMessage == null || originalMessage._id == null) { throw new Meteor.Error('error-invalid-message', 'Message you are unpinning was not found', { @@ -138,22 +142,22 @@ Meteor.methods({ } // If we keep history of edits, insert a new message to store history information - if (RocketChat.settings.get('Message_KeepHistory')) { - RocketChat.models.Messages.cloneAndSaveAsHistoryById(originalMessage._id); + if (settings.get('Message_KeepHistory')) { + Messages.cloneAndSaveAsHistoryById(originalMessage._id); } - const me = RocketChat.models.Users.findOneById(Meteor.userId()); + const me = Users.findOneById(Meteor.userId()); originalMessage.pinned = false; originalMessage.pinnedBy = { _id: Meteor.userId(), username: me.username, }; - originalMessage = RocketChat.callbacks.run('beforeSaveMessage', originalMessage); + originalMessage = callbacks.run('beforeSaveMessage', originalMessage); const room = Meteor.call('canAccessRoom', message.rid, Meteor.userId()); - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned); + if (isTheLastMessage(room, message)) { + Rooms.setLastMessagePinned(room._id, originalMessage.pinnedBy, originalMessage.pinned); } - return RocketChat.models.Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned); + return Messages.setPinnedByIdAndUserId(originalMessage._id, originalMessage.pinnedBy, originalMessage.pinned); }, }); diff --git a/packages/rocketchat-message-pin/server/publications/pinnedMessages.js b/packages/rocketchat-message-pin/server/publications/pinnedMessages.js index eb4813cd5464..11417bb73b01 100644 --- a/packages/rocketchat-message-pin/server/publications/pinnedMessages.js +++ b/packages/rocketchat-message-pin/server/publications/pinnedMessages.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Messages } from 'meteor/rocketchat:models'; Meteor.publish('pinnedMessages', function(rid, limit = 50) { if (!this.userId) { @@ -7,14 +7,14 @@ Meteor.publish('pinnedMessages', function(rid, limit = 50) { } const publication = this; - const user = RocketChat.models.Users.findOneById(this.userId); + const user = Users.findOneById(this.userId); if (!user) { return this.ready(); } if (!Meteor.call('canAccessRoom', rid, this.userId)) { return this.ready(); } - const cursorHandle = RocketChat.models.Messages.findPinnedByRoom(rid, { sort: { ts: -1 }, limit }).observeChanges({ + const cursorHandle = Messages.findPinnedByRoom(rid, { sort: { ts: -1 }, limit }).observeChanges({ added(_id, record) { return publication.added('rocketchat_pinned_message', _id, record); }, diff --git a/packages/rocketchat-message-pin/server/settings.js b/packages/rocketchat-message-pin/server/settings.js index 58197aeeb65a..ad6b27b3c219 100644 --- a/packages/rocketchat-message-pin/server/settings.js +++ b/packages/rocketchat-message-pin/server/settings.js @@ -1,13 +1,14 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Permissions } from 'meteor/rocketchat:models'; Meteor.startup(function() { - RocketChat.settings.add('Message_AllowPinning', true, { + settings.add('Message_AllowPinning', true, { type: 'boolean', group: 'Message', public: true, }); - return RocketChat.models.Permissions.upsert('pin-message', { + return Permissions.upsert('pin-message', { $setOnInsert: { roles: ['owner', 'moderator', 'admin'], }, diff --git a/packages/rocketchat-message-pin/server/startup/indexes.js b/packages/rocketchat-message-pin/server/startup/indexes.js index 293f4a8a44a2..6d54a9e747c0 100644 --- a/packages/rocketchat-message-pin/server/startup/indexes.js +++ b/packages/rocketchat-message-pin/server/startup/indexes.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; Meteor.startup(function() { return Meteor.defer(function() { - return RocketChat.models.Messages.tryEnsureIndex({ + return Messages.tryEnsureIndex({ 'pinnedBy._id': 1, }, { sparse: 1, diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index 1e8600f944a6..7e8974fcc166 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,20 @@ export class Rooms extends Base { return this.findOne(query, options); } + setLastMessagePinned(roomId, pinnedBy, pinned, pinnedAt) { + const query = { _id: roomId }; + + const update = { + $set: { + 'lastMessage.pinned': pinned, + 'lastMessage.pinnedAt': pinnedAt || new Date, + 'lastMessage.pinnedBy': pinnedBy, + }, + }; + + return this.update(query, update); + } + setSentiment(roomId, sentiment) { return this.update({ _id: roomId }, { $set: { sentiment } }); } From 67331120a1305047283b72d9697a62ca8c15efe5 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 1 Feb 2019 17:10:28 -0200 Subject: [PATCH 048/101] Fix templateVarHandler that was in wrong folder --- .../rocketchat-lib/lib/templateVarHandler.js | 40 ------------------- packages/rocketchat-utils/client/index.js | 2 +- .../{client => }/lib/templateVarHandler.js | 0 packages/rocketchat-utils/server/index.js | 1 + 4 files changed, 2 insertions(+), 41 deletions(-) rename packages/rocketchat-utils/{client => }/lib/templateVarHandler.js (100%) diff --git a/packages/rocketchat-lib/lib/templateVarHandler.js b/packages/rocketchat-lib/lib/templateVarHandler.js index ed0fbf1d2b73..9359d1dd242b 100644 --- a/packages/rocketchat-lib/lib/templateVarHandler.js +++ b/packages/rocketchat-lib/lib/templateVarHandler.js @@ -1,43 +1,3 @@ -import { Meteor } from 'meteor/meteor'; -import { Logger } from 'meteor/rocketchat:logger'; - -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; - } -}; import { templateVarHandler } from 'meteor/rocketchat:utils'; RocketChat.templateVarHandler = templateVarHandler; diff --git a/packages/rocketchat-utils/client/index.js b/packages/rocketchat-utils/client/index.js index 6937c1c0336d..958894c3f10e 100644 --- a/packages/rocketchat-utils/client/index.js +++ b/packages/rocketchat-utils/client/index.js @@ -17,4 +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'; +export { templateVarHandler } from '../lib/templateVarHandler'; diff --git a/packages/rocketchat-utils/client/lib/templateVarHandler.js b/packages/rocketchat-utils/lib/templateVarHandler.js similarity index 100% rename from packages/rocketchat-utils/client/lib/templateVarHandler.js rename to packages/rocketchat-utils/lib/templateVarHandler.js 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 d39b6cd993d891f8f5b9733fd1db2b5821bf531d Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 13:50:01 -0200 Subject: [PATCH 049/101] Remove namespace in the new livechat endpoint --- packages/rocketchat-livechat/server/api/v1/room.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/rocketchat-livechat/server/api/v1/room.js b/packages/rocketchat-livechat/server/api/v1/room.js index 5f80d84aa59b..d21bbc13f6bb 100644 --- a/packages/rocketchat-livechat/server/api/v1/room.js +++ b/packages/rocketchat-livechat/server/api/v1/room.js @@ -155,8 +155,8 @@ API.v1.addRoute('livechat/room.survey', { }, }); -RocketChat.API.v1.addRoute('livechat/room.forward', { authRequired: true }, { +API.v1.addRoute('livechat/room.forward', { authRequired: true }, { post() { - RocketChat.API.v1.success(Meteor.runAsUser(this.userId, () => Meteor.call('livechat:transfer', this.bodyParams))); + API.v1.success(Meteor.runAsUser(this.userId, () => Meteor.call('livechat:transfer', this.bodyParams))); }, }); From 1ae8bfd3baa06382788ec3c54f5de50165eb2714 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 15:42:19 -0200 Subject: [PATCH 050/101] Remove dependency of RC namespace in rc-message-snippet --- .../client/actionButton.js | 20 ++++++++------- .../client/messageType.js | 4 +-- .../client/page/snippetPage.js | 7 +++--- .../client/router.js | 6 ++--- .../client/snippetMessage.js | 12 ++++----- .../client/tabBar/tabBar.js | 9 ++++--- .../rocketchat-message-snippet/package.js | 5 ++++ .../server/index.js | 1 - .../server/methods/snippetMessage.js | 25 +++++++++++-------- .../server/models/Rooms.js | 19 -------------- .../server/publications/snippetedMessage.js | 10 ++++---- .../publications/snippetedMessagesByRoom.js | 6 ++--- .../server/requests.js | 8 +++--- .../server/startup/settings.js | 7 +++--- .../rocketchat-models/server/models/Rooms.js | 18 +++++++++++++ 15 files changed, 84 insertions(+), 73 deletions(-) delete mode 100644 packages/rocketchat-message-snippet/server/models/Rooms.js diff --git a/packages/rocketchat-message-snippet/client/actionButton.js b/packages/rocketchat-message-snippet/client/actionButton.js index 14a59daf8f71..520d48e48f52 100644 --- a/packages/rocketchat-message-snippet/client/actionButton.js +++ b/packages/rocketchat-message-snippet/client/actionButton.js @@ -1,10 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { MessageAction, modal } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; Meteor.startup(function() { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'snippeted-message', icon: 'code', label: 'Snippet', @@ -49,17 +51,17 @@ Meteor.startup(function() { }, condition(message) { - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid, 'u._id': Meteor.userId() }) === undefined) { + if (Subscriptions.findOne({ rid: message.rid, 'u._id': Meteor.userId() }) === undefined) { return false; } - if (message.snippeted || ((RocketChat.settings.get('Message_AllowSnippeting') === undefined) || - (RocketChat.settings.get('Message_AllowSnippeting') === null) || - (RocketChat.settings.get('Message_AllowSnippeting')) === false)) { + if (message.snippeted || ((settings.get('Message_AllowSnippeting') === undefined) || + (settings.get('Message_AllowSnippeting') === null) || + (settings.get('Message_AllowSnippeting')) === false)) { return false; } - return RocketChat.authz.hasAtLeastOnePermission('snippet-message', message.rid); + return hasAtLeastOnePermission('snippet-message', message.rid); }, }); }); diff --git a/packages/rocketchat-message-snippet/client/messageType.js b/packages/rocketchat-message-snippet/client/messageType.js index 00b826badb7a..f4ccc4581bc6 100644 --- a/packages/rocketchat-message-snippet/client/messageType.js +++ b/packages/rocketchat-message-snippet/client/messageType.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { MessageTypes } from 'meteor/rocketchat:ui-utils'; import s from 'underscore.string'; Meteor.startup(function() { - RocketChat.MessageTypes.registerType({ + MessageTypes.registerType({ id: 'message_snippeted', system: true, message: 'Snippeted_a_message', diff --git a/packages/rocketchat-message-snippet/client/page/snippetPage.js b/packages/rocketchat-message-snippet/client/page/snippetPage.js index a985b453be8f..7fe33bb0d6c9 100644 --- a/packages/rocketchat-message-snippet/client/page/snippetPage.js +++ b/packages/rocketchat-message-snippet/client/page/snippetPage.js @@ -2,7 +2,8 @@ import { Meteor } from 'meteor/meteor'; import { DateFormat } from 'meteor/rocketchat:lib'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Markdown } from 'meteor/rocketchat:markdown'; import { SnippetedMessages } from '../lib/collections'; import moment from 'moment'; @@ -16,13 +17,13 @@ Template.snippetPage.helpers({ return null; } message.html = message.msg; - const markdown = RocketChat.Markdown.parse(message); + const markdown = Markdown.parse(message); return markdown.tokens[0].text; }, date() { const snippet = SnippetedMessages.findOne({ _id: FlowRouter.getParam('snippetId') }); if (snippet !== undefined) { - return moment(snippet.ts).format(RocketChat.settings.get('Message_DateFormat')); + return moment(snippet.ts).format(settings.get('Message_DateFormat')); } }, time() { diff --git a/packages/rocketchat-message-snippet/client/router.js b/packages/rocketchat-message-snippet/client/router.js index 4df5e3778b79..2e8076fa622b 100644 --- a/packages/rocketchat-message-snippet/client/router.js +++ b/packages/rocketchat-message-snippet/client/router.js @@ -1,6 +1,6 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { BlazeLayout } from 'meteor/kadira:blaze-layout'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; FlowRouter.route('/snippet/:snippetId/:snippetName', { name: 'snippetView', @@ -8,11 +8,11 @@ FlowRouter.route('/snippet/:snippetId/:snippetName', { BlazeLayout.render('main', { center: 'snippetPage', flexTabBar: null }); }, triggersEnter: [function() { - RocketChat.TabBar.hide(); + TabBar.hide(); }], triggersExit: [ function() { - RocketChat.TabBar.show(); + TabBar.show(); }, ], }); diff --git a/packages/rocketchat-message-snippet/client/snippetMessage.js b/packages/rocketchat-message-snippet/client/snippetMessage.js index a45af6d0a487..7929fa1ca9c1 100644 --- a/packages/rocketchat-message-snippet/client/snippetMessage.js +++ b/packages/rocketchat-message-snippet/client/snippetMessage.js @@ -1,19 +1,19 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatMessage } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { ChatMessage, Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ snippetMessage(message) { if (typeof Meteor.userId() === 'undefined' || Meteor.userId() === null) { return false; } - if ((typeof RocketChat.settings.get('Message_AllowSnippeting') === 'undefined') || - (RocketChat.settings.get('Message_AllowSnippeting') === null) || - (RocketChat.settings.get('Message_AllowSnippeting') === false)) { + if ((typeof settings.get('Message_AllowSnippeting') === 'undefined') || + (settings.get('Message_AllowSnippeting') === null) || + (settings.get('Message_AllowSnippeting') === false)) { return false; } - const subscription = RocketChat.models.Subscriptions.findOne({ rid: message.rid, 'u._id': Meteor.userId() }); + const subscription = Subscriptions.findOne({ rid: message.rid, 'u._id': Meteor.userId() }); if (subscription === undefined) { return false; diff --git a/packages/rocketchat-message-snippet/client/tabBar/tabBar.js b/packages/rocketchat-message-snippet/client/tabBar/tabBar.js index 74b53c1707a3..015f27b15fcf 100644 --- a/packages/rocketchat-message-snippet/client/tabBar/tabBar.js +++ b/packages/rocketchat-message-snippet/client/tabBar/tabBar.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('Message_AllowSnippeting')) { - RocketChat.TabBar.addButton({ + if (settings.get('Message_AllowSnippeting')) { + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'snippeted-messages', i18nTitle: 'snippet-message', @@ -14,7 +15,7 @@ Meteor.startup(function() { order: 20, }); } else { - RocketChat.TabBar.removeButton('snippeted-messages'); + TabBar.removeButton('snippeted-messages'); } }); }); diff --git a/packages/rocketchat-message-snippet/package.js b/packages/rocketchat-message-snippet/package.js index 2762df5c1a5b..e80e61379d71 100644 --- a/packages/rocketchat-message-snippet/package.js +++ b/packages/rocketchat-message-snippet/package.js @@ -13,7 +13,12 @@ Package.onUse(function(api) { 'rocketchat:lib', 'rocketchat:file', 'rocketchat:markdown', + 'rocketchat:settings', + 'rocketchat:ui-utils', 'rocketchat:theme', + 'rocketchat:models', + 'rocketchat:authorization', + 'rocketchat:callbacks', 'random', 'tracker', 'webapp', diff --git a/packages/rocketchat-message-snippet/server/index.js b/packages/rocketchat-message-snippet/server/index.js index 2445b9485f4e..4e46076a914f 100644 --- a/packages/rocketchat-message-snippet/server/index.js +++ b/packages/rocketchat-message-snippet/server/index.js @@ -1,5 +1,4 @@ import './startup/settings'; -import './models/Rooms'; import './methods/snippetMessage'; import './requests'; import './publications/snippetedMessagesByRoom'; diff --git a/packages/rocketchat-message-snippet/server/methods/snippetMessage.js b/packages/rocketchat-message-snippet/server/methods/snippetMessage.js index f9ef3b77f052..f88198f22629 100644 --- a/packages/rocketchat-message-snippet/server/methods/snippetMessage.js +++ b/packages/rocketchat-message-snippet/server/methods/snippetMessage.js @@ -1,5 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Messages, Users, Rooms } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { isTheLastMessage } from 'meteor/rocketchat:lib'; Meteor.methods({ snippetMessage(message, filename) { @@ -9,23 +12,23 @@ Meteor.methods({ { method: 'snippetMessage' }); } - const room = RocketChat.models.Rooms.findOne({ _id: message.rid }); + const room = Rooms.findOne({ _id: message.rid }); if ((typeof room === 'undefined') || (room === null)) { return false; } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); if (!subscription) { return false; } // 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); } - const me = RocketChat.models.Users.findOneById(Meteor.userId()); + const me = Users.findOneById(Meteor.userId()); message.snippeted = true; message.snippetedAt = Date.now; @@ -34,17 +37,17 @@ Meteor.methods({ username: me.username, }; - message = RocketChat.callbacks.run('beforeSaveMessage', message); + message = callbacks.run('beforeSaveMessage', message); // Create the SnippetMessage - RocketChat.models.Messages.setSnippetedByIdAndUserId(message, filename, message.snippetedBy, + Messages.setSnippetedByIdAndUserId(message, filename, message.snippetedBy, message.snippeted, Date.now, filename); - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.setLastMessageSnippeted(room._id, message, filename, message.snippetedBy, + if (isTheLastMessage(room, message)) { + Rooms.setLastMessageSnippeted(room._id, message, filename, message.snippetedBy, message.snippeted, Date.now, filename); } - RocketChat.models.Messages.createWithTypeRoomIdMessageAndUser( + Messages.createWithTypeRoomIdMessageAndUser( 'message_snippeted', message.rid, '', me, { snippetId: message._id, snippetName: filename }); }, }); diff --git a/packages/rocketchat-message-snippet/server/models/Rooms.js b/packages/rocketchat-message-snippet/server/models/Rooms.js deleted file mode 100644 index 165c7a155c67..000000000000 --- a/packages/rocketchat-message-snippet/server/models/Rooms.js +++ /dev/null @@ -1,19 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.setLastMessageSnippeted = function(roomId, message, snippetName, snippetedBy, snippeted, snippetedAt) { - const query = { _id: roomId }; - - const msg = `\`\`\`${ message.msg }\`\`\``; - - const update = { - $set: { - 'lastMessage.msg': msg, - 'lastMessage.snippeted': snippeted, - 'lastMessage.snippetedAt': snippetedAt || new Date, - 'lastMessage.snippetedBy': snippetedBy, - 'lastMessage.snippetName': snippetName, - }, - }; - - return this.update(query, update); -}; diff --git a/packages/rocketchat-message-snippet/server/publications/snippetedMessage.js b/packages/rocketchat-message-snippet/server/publications/snippetedMessage.js index 4f30beaa3d62..6318606d0402 100644 --- a/packages/rocketchat-message-snippet/server/publications/snippetedMessage.js +++ b/packages/rocketchat-message-snippet/server/publications/snippetedMessage.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, Users, Rooms } from 'meteor/rocketchat:models'; Meteor.publish('snippetedMessage', function(_id) { if (typeof this.userId === 'undefined' || this.userId === null) { return this.ready(); } - const snippet = RocketChat.models.Messages.findOne({ _id, snippeted: true }); - const user = RocketChat.models.Users.findOneById(this.userId); + const snippet = Messages.findOne({ _id, snippeted: true }); + const user = Users.findOneById(this.userId); const roomSnippetQuery = { _id: snippet.rid, usernames: { @@ -21,7 +21,7 @@ Meteor.publish('snippetedMessage', function(_id) { return this.ready(); } - if (RocketChat.models.Rooms.findOne(roomSnippetQuery) === undefined) { + if (Rooms.findOne(roomSnippetQuery) === undefined) { return this.ready(); } @@ -32,7 +32,7 @@ Meteor.publish('snippetedMessage', function(_id) { return this.ready(); } - const cursor = RocketChat.models.Messages.find( + const cursor = Messages.find( { _id } ).observeChanges({ added(_id, record) { diff --git a/packages/rocketchat-message-snippet/server/publications/snippetedMessagesByRoom.js b/packages/rocketchat-message-snippet/server/publications/snippetedMessagesByRoom.js index b7b6c5a769d3..2a05ae02a6ae 100644 --- a/packages/rocketchat-message-snippet/server/publications/snippetedMessagesByRoom.js +++ b/packages/rocketchat-message-snippet/server/publications/snippetedMessagesByRoom.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Messages } from 'meteor/rocketchat:models'; Meteor.publish('snippetedMessages', function(rid, limit = 50) { if (typeof this.userId === 'undefined' || this.userId === null) { @@ -8,7 +8,7 @@ Meteor.publish('snippetedMessages', function(rid, limit = 50) { const publication = this; - const user = RocketChat.models.Users.findOneById(this.userId); + const user = Users.findOneById(this.userId); if (typeof user === 'undefined' || user === null) { return this.ready(); @@ -18,7 +18,7 @@ Meteor.publish('snippetedMessages', function(rid, limit = 50) { return this.ready(); } - const cursorHandle = RocketChat.models.Messages.findSnippetedByRoom( + const cursorHandle = Messages.findSnippetedByRoom( rid, { sort: { ts: -1 }, diff --git a/packages/rocketchat-message-snippet/server/requests.js b/packages/rocketchat-message-snippet/server/requests.js index 6a526a5a3435..7886186fe891 100644 --- a/packages/rocketchat-message-snippet/server/requests.js +++ b/packages/rocketchat-message-snippet/server/requests.js @@ -1,6 +1,6 @@ import { WebApp } from 'meteor/webapp'; import { Cookies } from 'meteor/ostrio:cookies'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Rooms, Messages } from 'meteor/rocketchat:models'; WebApp.connectHandlers.use('/snippet/download', function(req, res) { let rawCookies; @@ -25,7 +25,7 @@ WebApp.connectHandlers.use('/snippet/download', function(req, res) { token = req.query.rc_token; } - const user = RocketChat.models.Users.findOneByIdAndLoginToken(uid, token); + const user = Users.findOneByIdAndLoginToken(uid, token); if (!(uid && token && user)) { res.writeHead(403); @@ -35,13 +35,13 @@ WebApp.connectHandlers.use('/snippet/download', function(req, res) { const match = /^\/([^\/]+)\/(.*)/.exec(req.url); if (match[1]) { - const snippet = RocketChat.models.Messages.findOne( + const snippet = Messages.findOne( { _id: match[1], snippeted: true, } ); - const room = RocketChat.models.Rooms.findOne({ _id: snippet.rid, usernames: { $in: [user.username] } }); + const room = Rooms.findOne({ _id: snippet.rid, usernames: { $in: [user.username] } }); if (room === undefined) { res.writeHead(403); res.end(); diff --git a/packages/rocketchat-message-snippet/server/startup/settings.js b/packages/rocketchat-message-snippet/server/startup/settings.js index 7f5e7c2816f6..ddab0ef7a336 100644 --- a/packages/rocketchat-message-snippet/server/startup/settings.js +++ b/packages/rocketchat-message-snippet/server/startup/settings.js @@ -1,13 +1,14 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Permissions } from 'meteor/rocketchat:models'; Meteor.startup(function() { - RocketChat.settings.add('Message_AllowSnippeting', false, { + settings.add('Message_AllowSnippeting', false, { type: 'boolean', public: true, group: 'Message', }); - RocketChat.models.Permissions.upsert('snippet-message', { + Permissions.upsert('snippet-message', { $setOnInsert: { roles: ['owner', 'moderator', 'admin'], }, diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index 7e8974fcc166..ba64a1084f29 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,24 @@ export class Rooms extends Base { return this.findOne(query, options); } + setLastMessageSnippeted(roomId, message, snippetName, snippetedBy, snippeted, snippetedAt) { + const query = { _id: roomId }; + + const msg = `\`\`\`${ message.msg }\`\`\``; + + const update = { + $set: { + 'lastMessage.msg': msg, + 'lastMessage.snippeted': snippeted, + 'lastMessage.snippetedAt': snippetedAt || new Date, + 'lastMessage.snippetedBy': snippetedBy, + 'lastMessage.snippetName': snippetName, + }, + }; + + return this.update(query, update); + } + setLastMessagePinned(roomId, pinnedBy, pinned, pinnedAt) { const query = { _id: roomId }; From 3bd702f1bf54eef3e824c7ffedc1b1433717e399 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 16:04:43 -0200 Subject: [PATCH 051/101] Remove dependency of RC namespace in rc-message-star --- .../client/actionButton.js | 24 ++++++++++--------- .../client/starMessage.js | 8 +++---- .../rocketchat-message-star/client/tabBar.js | 4 ++-- packages/rocketchat-message-star/package.js | 4 ++++ .../rocketchat-message-star/server/index.js | 1 - .../server/models/Rooms.js | 23 ------------------ .../server/publications/starredMessages.js | 6 ++--- .../server/settings.js | 4 ++-- .../server/starMessage.js | 14 ++++++----- .../server/startup/indexes.js | 4 ++-- .../rocketchat-models/server/models/Rooms.js | 21 ++++++++++++++++ 11 files changed, 59 insertions(+), 54 deletions(-) delete mode 100644 packages/rocketchat-message-star/server/models/Rooms.js diff --git a/packages/rocketchat-message-star/client/actionButton.js b/packages/rocketchat-message-star/client/actionButton.js index 097f4a26d410..c5ce3c2751cf 100644 --- a/packages/rocketchat-message-star/client/actionButton.js +++ b/packages/rocketchat-message-star/client/actionButton.js @@ -1,12 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { RoomHistoryManager } from 'meteor/rocketchat:ui'; +import { handleError } from 'meteor/rocketchat:utils'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { RoomHistoryManager, MessageAction } from 'meteor/rocketchat:ui-utils'; import toastr from 'toastr'; Meteor.startup(function() { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'star-message', icon: 'star', label: 'Star_Message', @@ -21,7 +23,7 @@ Meteor.startup(function() { }); }, condition(message) { - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null && RocketChat.settings.get('Message_AllowStarring')) { + if (Subscriptions.findOne({ rid: message.rid }) == null && settings.get('Message_AllowStarring')) { return false; } @@ -31,7 +33,7 @@ Meteor.startup(function() { group: 'menu', }); - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'unstar-message', icon: 'star', label: 'Unstar_Message', @@ -46,7 +48,7 @@ Meteor.startup(function() { }); }, condition(message) { - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null && RocketChat.settings.get('Message_AllowStarring')) { + if (Subscriptions.findOne({ rid: message.rid }) == null && settings.get('Message_AllowStarring')) { return false; } @@ -56,7 +58,7 @@ Meteor.startup(function() { group: 'menu', }); - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'jump-to-star-message', icon: 'jump', label: 'Jump_to_message', @@ -69,7 +71,7 @@ Meteor.startup(function() { RoomHistoryManager.getSurroundingMessages(message, 50); }, condition(message) { - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null) { + if (Subscriptions.findOne({ rid: message.rid }) == null) { return false; } return true; @@ -78,7 +80,7 @@ Meteor.startup(function() { group: 'menu', }); - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'permalink-star', icon: 'permalink', label: 'Permalink', @@ -86,11 +88,11 @@ Meteor.startup(function() { context: ['starred'], async action(event) { const message = this._arguments[1]; - $(event.currentTarget).attr('data-clipboard-text', await RocketChat.MessageAction.getPermaLink(message._id)); + $(event.currentTarget).attr('data-clipboard-text', await MessageAction.getPermaLink(message._id)); toastr.success(TAPi18n.__('Copied')); }, condition(message) { - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null) { + if (Subscriptions.findOne({ rid: message.rid }) == null) { return false; } return true; diff --git a/packages/rocketchat-message-star/client/starMessage.js b/packages/rocketchat-message-star/client/starMessage.js index 349470f09986..cd9066bca7ca 100644 --- a/packages/rocketchat-message-star/client/starMessage.js +++ b/packages/rocketchat-message-star/client/starMessage.js @@ -1,16 +1,16 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatMessage } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { ChatMessage, Subscriptions } from 'meteor/rocketchat:models'; Meteor.methods({ starMessage(message) { if (!Meteor.userId()) { return false; } - if (RocketChat.models.Subscriptions.findOne({ rid: message.rid }) == null) { + if (Subscriptions.findOne({ rid: message.rid }) == null) { return false; } - if (!RocketChat.settings.get('Message_AllowStarring')) { + if (!settings.get('Message_AllowStarring')) { return false; } return ChatMessage.update({ diff --git a/packages/rocketchat-message-star/client/tabBar.js b/packages/rocketchat-message-star/client/tabBar.js index f93f2701654e..87cfbb61f2a8 100644 --- a/packages/rocketchat-message-star/client/tabBar.js +++ b/packages/rocketchat-message-star/client/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(function() { - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'starred-messages', i18nTitle: 'Starred_Messages', diff --git a/packages/rocketchat-message-star/package.js b/packages/rocketchat-message-star/package.js index cf7bb6d3c53d..03dfd647fe1b 100644 --- a/packages/rocketchat-message-star/package.js +++ b/packages/rocketchat-message-star/package.js @@ -10,6 +10,10 @@ Package.onUse(function(api) { 'mongo', 'ecmascript', 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:ui-utils', 'templating', ]); api.addFiles('client/views/stylesheets/messagestar.css', 'client'); diff --git a/packages/rocketchat-message-star/server/index.js b/packages/rocketchat-message-star/server/index.js index 9b347ac8584a..ceeedf7d8669 100644 --- a/packages/rocketchat-message-star/server/index.js +++ b/packages/rocketchat-message-star/server/index.js @@ -1,4 +1,3 @@ -import './models/Rooms'; import './settings'; import './starMessage'; import './publications/starredMessages'; diff --git a/packages/rocketchat-message-star/server/models/Rooms.js b/packages/rocketchat-message-star/server/models/Rooms.js deleted file mode 100644 index f011f8968925..000000000000 --- a/packages/rocketchat-message-star/server/models/Rooms.js +++ /dev/null @@ -1,23 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.updateLastMessageStar = function(roomId, userId, starred) { - let update; - const query = { _id: roomId }; - - if (starred) { - update = { - $addToSet: { - 'lastMessage.starred': { _id: userId }, - }, - }; - } else { - update = { - $pull: { - 'lastMessage.starred': { _id: userId }, - }, - }; - } - - return this.update(query, update); -}; - diff --git a/packages/rocketchat-message-star/server/publications/starredMessages.js b/packages/rocketchat-message-star/server/publications/starredMessages.js index 20795c449227..1a9dfe00e1b9 100644 --- a/packages/rocketchat-message-star/server/publications/starredMessages.js +++ b/packages/rocketchat-message-star/server/publications/starredMessages.js @@ -1,19 +1,19 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users, Messages } from 'meteor/rocketchat:models'; Meteor.publish('starredMessages', function(rid, limit = 50) { if (!this.userId) { return this.ready(); } const publication = this; - const user = RocketChat.models.Users.findOneById(this.userId); + const user = Users.findOneById(this.userId); if (!user) { return this.ready(); } if (!Meteor.call('canAccessRoom', rid, this.userId)) { return this.ready(); } - const cursorHandle = RocketChat.models.Messages.findStarredByUserAtRoom(this.userId, rid, { + const cursorHandle = Messages.findStarredByUserAtRoom(this.userId, rid, { sort: { ts: -1, }, diff --git a/packages/rocketchat-message-star/server/settings.js b/packages/rocketchat-message-star/server/settings.js index f83b9f82d435..f4a18790d3ae 100644 --- a/packages/rocketchat-message-star/server/settings.js +++ b/packages/rocketchat-message-star/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() { - return RocketChat.settings.add('Message_AllowStarring', true, { + return settings.add('Message_AllowStarring', true, { type: 'boolean', group: 'Message', public: true, diff --git a/packages/rocketchat-message-star/server/starMessage.js b/packages/rocketchat-message-star/server/starMessage.js index 7cad3581642a..b174ed83ff1e 100644 --- a/packages/rocketchat-message-star/server/starMessage.js +++ b/packages/rocketchat-message-star/server/starMessage.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { isTheLastMessage } from 'meteor/rocketchat:lib'; +import { Subscriptions, Rooms, Messages } from 'meteor/rocketchat:models'; Meteor.methods({ starMessage(message) { @@ -9,22 +11,22 @@ Meteor.methods({ }); } - if (!RocketChat.settings.get('Message_AllowStarring')) { + if (!settings.get('Message_AllowStarring')) { throw new Meteor.Error('error-action-not-allowed', 'Message starring not allowed', { method: 'pinMessage', action: 'Message_starring', }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, Meteor.userId(), { fields: { _id: 1 } }); if (!subscription) { return false; } const room = Meteor.call('canAccessRoom', message.rid, Meteor.userId()); - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.updateLastMessageStar(room._id, Meteor.userId(), message.starred); + if (isTheLastMessage(room, message)) { + Rooms.updateLastMessageStar(room._id, Meteor.userId(), message.starred); } - return RocketChat.models.Messages.updateUserStarById(message._id, Meteor.userId(), message.starred); + return Messages.updateUserStarById(message._id, Meteor.userId(), message.starred); }, }); diff --git a/packages/rocketchat-message-star/server/startup/indexes.js b/packages/rocketchat-message-star/server/startup/indexes.js index 6b45c173eac7..bfebc7dc00b5 100644 --- a/packages/rocketchat-message-star/server/startup/indexes.js +++ b/packages/rocketchat-message-star/server/startup/indexes.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; Meteor.startup(function() { return Meteor.defer(function() { - return RocketChat.models.Messages.tryEnsureIndex({ + return Messages.tryEnsureIndex({ 'starred._id': 1, }, { sparse: 1, diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index ba64a1084f29..5e36690db5b8 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,27 @@ export class Rooms extends Base { return this.findOne(query, options); } + updateLastMessageStar(roomId, userId, starred) { + let update; + const query = { _id: roomId }; + + if (starred) { + update = { + $addToSet: { + 'lastMessage.starred': { _id: userId }, + }, + }; + } else { + update = { + $pull: { + 'lastMessage.starred': { _id: userId }, + }, + }; + } + + return this.update(query, update); + } + setLastMessageSnippeted(roomId, message, snippetName, snippetedBy, snippeted, snippetedAt) { const query = { _id: roomId }; From 0dbc8ed423c3d2e43804dd8ea657c65d84cc5bb4 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 16:35:21 -0200 Subject: [PATCH 052/101] Remove dependency of RC namespace in rc-oauth2 --- packages/rocketchat-models/server/index.js | 2 ++ .../server/models/OAuthApps.js | 9 +++++++++ .../client/admin/startup.js | 7 ++++--- .../client/admin/views/oauthApp.js | 8 ++++---- .../client/admin/views/oauthApps.js | 4 ++-- .../rocketchat-oauth2-server-config/package.js | 4 +++- .../server/admin/methods/addOAuthApp.js | 9 +++++---- .../server/admin/methods/deleteOAuthApp.js | 9 +++++---- .../server/admin/methods/updateOAuthApp.js | 13 +++++++------ .../server/admin/publications/oauthApps.js | 7 ++++--- .../server/index.js | 1 - .../server/models/OAuthApps.js | 17 ----------------- .../server/oauth/default-services.js | 6 +++--- .../server/oauth/oauth2-server.js | 10 +++++----- 14 files changed, 53 insertions(+), 53 deletions(-) create mode 100644 packages/rocketchat-models/server/models/OAuthApps.js delete mode 100644 packages/rocketchat-oauth2-server-config/server/models/OAuthApps.js diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index 55f01c48ba30..2abc6e8718cd 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -19,6 +19,7 @@ import Integrations from './models/Integrations'; import IntegrationHistory from './models/IntegrationHistory'; import CredentialTokens from './models/CredentialTokens'; import EmojiCustom from './models/EmojiCustom'; +import OAuthApps from './models/OAuthApps'; export { Base, @@ -42,4 +43,5 @@ export { IntegrationHistory, CredentialTokens, EmojiCustom, + OAuthApps, }; diff --git a/packages/rocketchat-models/server/models/OAuthApps.js b/packages/rocketchat-models/server/models/OAuthApps.js new file mode 100644 index 000000000000..6aedffb63ae0 --- /dev/null +++ b/packages/rocketchat-models/server/models/OAuthApps.js @@ -0,0 +1,9 @@ +import { Base } from './_Base'; + +export class OAuthApps extends Base { + constructor() { + super('oauth_apps'); + } +} + +export default new OAuthApps(); diff --git a/packages/rocketchat-oauth2-server-config/client/admin/startup.js b/packages/rocketchat-oauth2-server-config/client/admin/startup.js index 1d3eb2cbdff5..7643e8231c9f 100644 --- a/packages/rocketchat-oauth2-server-config/client/admin/startup.js +++ b/packages/rocketchat-oauth2-server-config/client/admin/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: 'admin-oauth-apps', i18nLabel: 'OAuth Apps', icon: 'discover', permissionGranted() { - return RocketChat.authz.hasAllPermission('manage-oauth-apps'); + return hasAllPermission('manage-oauth-apps'); }, }); diff --git a/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApp.js b/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApp.js index 706f6d73a50e..5dace4435db1 100644 --- a/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApp.js +++ b/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApp.js @@ -3,9 +3,9 @@ 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 { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { modal } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; import { ChatOAuthApps } from '../collection'; import toastr from 'toastr'; @@ -18,7 +18,7 @@ Template.oauthApp.onCreated(function() { Template.oauthApp.helpers({ hasPermission() { - return RocketChat.authz.hasAllPermission('manage-oauth-apps'); + return hasAllPermission('manage-oauth-apps'); }, data() { const instance = Template.instance(); diff --git a/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApps.js b/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApps.js index c779e6b08d7a..cabdf6e76eef 100644 --- a/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApps.js +++ b/packages/rocketchat-oauth2-server-config/client/admin/views/oauthApps.js @@ -1,5 +1,5 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; import { ChatOAuthApps } from '../collection'; import moment from 'moment'; @@ -9,7 +9,7 @@ Template.oauthApps.onCreated(function() { Template.oauthApps.helpers({ hasPermission() { - return RocketChat.authz.hasAllPermission('manage-oauth-apps'); + return hasAllPermission('manage-oauth-apps'); }, applications() { return ChatOAuthApps.find(); diff --git a/packages/rocketchat-oauth2-server-config/package.js b/packages/rocketchat-oauth2-server-config/package.js index 6533759629a4..efa8a1cffb4d 100644 --- a/packages/rocketchat-oauth2-server-config/package.js +++ b/packages/rocketchat-oauth2-server-config/package.js @@ -10,7 +10,9 @@ Package.onUse(function(api) { 'webapp', 'mongo', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:ui-utils', + 'rocketchat:authorization', 'rocketchat:api', 'rocketchat:theme', 'rocketchat:oauth2-server', diff --git a/packages/rocketchat-oauth2-server-config/server/admin/methods/addOAuthApp.js b/packages/rocketchat-oauth2-server-config/server/admin/methods/addOAuthApp.js index 75c08982cacf..c847bc51a950 100644 --- a/packages/rocketchat-oauth2-server-config/server/admin/methods/addOAuthApp.js +++ b/packages/rocketchat-oauth2-server-config/server/admin/methods/addOAuthApp.js @@ -1,11 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Users, OAuthApps } from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ addOAuthApp(application) { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-oauth-apps')) { + if (!hasPermission(this.userId, 'manage-oauth-apps')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'addOAuthApp' }); } if (!_.isString(application.name) || application.name.trim() === '') { @@ -20,8 +21,8 @@ Meteor.methods({ application.clientId = Random.id(); application.clientSecret = Random.secret(); application._createdAt = new Date; - application._createdBy = RocketChat.models.Users.findOne(this.userId, { fields: { username: 1 } }); - application._id = RocketChat.models.OAuthApps.insert(application); + application._createdBy = Users.findOne(this.userId, { fields: { username: 1 } }); + application._id = OAuthApps.insert(application); return application; }, }); diff --git a/packages/rocketchat-oauth2-server-config/server/admin/methods/deleteOAuthApp.js b/packages/rocketchat-oauth2-server-config/server/admin/methods/deleteOAuthApp.js index d1fabde3b8c3..1a1a2b88badb 100644 --- a/packages/rocketchat-oauth2-server-config/server/admin/methods/deleteOAuthApp.js +++ b/packages/rocketchat-oauth2-server-config/server/admin/methods/deleteOAuthApp.js @@ -1,16 +1,17 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { OAuthApps } from 'meteor/rocketchat:models'; Meteor.methods({ deleteOAuthApp(applicationId) { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-oauth-apps')) { + if (!hasPermission(this.userId, 'manage-oauth-apps')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'deleteOAuthApp' }); } - const application = RocketChat.models.OAuthApps.findOne(applicationId); + const application = OAuthApps.findOne(applicationId); if (application == null) { throw new Meteor.Error('error-application-not-found', 'Application not found', { method: 'deleteOAuthApp' }); } - RocketChat.models.OAuthApps.remove({ _id: applicationId }); + OAuthApps.remove({ _id: applicationId }); return true; }, }); diff --git a/packages/rocketchat-oauth2-server-config/server/admin/methods/updateOAuthApp.js b/packages/rocketchat-oauth2-server-config/server/admin/methods/updateOAuthApp.js index 788fbebd2ccd..c5e85cdcc27c 100644 --- a/packages/rocketchat-oauth2-server-config/server/admin/methods/updateOAuthApp.js +++ b/packages/rocketchat-oauth2-server-config/server/admin/methods/updateOAuthApp.js @@ -1,10 +1,11 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { OAuthApps, Users } from 'meteor/rocketchat:models'; import _ from 'underscore'; Meteor.methods({ updateOAuthApp(applicationId, application) { - if (!RocketChat.authz.hasPermission(this.userId, 'manage-oauth-apps')) { + if (!hasPermission(this.userId, 'manage-oauth-apps')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'updateOAuthApp' }); } if (!_.isString(application.name) || application.name.trim() === '') { @@ -16,23 +17,23 @@ Meteor.methods({ if (!_.isBoolean(application.active)) { throw new Meteor.Error('error-invalid-arguments', 'Invalid arguments', { method: 'updateOAuthApp' }); } - const currentApplication = RocketChat.models.OAuthApps.findOne(applicationId); + const currentApplication = OAuthApps.findOne(applicationId); if (currentApplication == null) { throw new Meteor.Error('error-application-not-found', 'Application not found', { method: 'updateOAuthApp' }); } - RocketChat.models.OAuthApps.update(applicationId, { + OAuthApps.update(applicationId, { $set: { name: application.name, active: application.active, redirectUri: application.redirectUri, _updatedAt: new Date, - _updatedBy: RocketChat.models.Users.findOne(this.userId, { + _updatedBy: Users.findOne(this.userId, { fields: { username: 1, }, }), }, }); - return RocketChat.models.OAuthApps.findOne(applicationId); + return OAuthApps.findOne(applicationId); }, }); diff --git a/packages/rocketchat-oauth2-server-config/server/admin/publications/oauthApps.js b/packages/rocketchat-oauth2-server-config/server/admin/publications/oauthApps.js index c6f872421f33..1125675026cf 100644 --- a/packages/rocketchat-oauth2-server-config/server/admin/publications/oauthApps.js +++ b/packages/rocketchat-oauth2-server-config/server/admin/publications/oauthApps.js @@ -1,12 +1,13 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { OAuthApps } from 'meteor/rocketchat:models'; Meteor.publish('oauthApps', function() { if (!this.userId) { return this.ready(); } - if (!RocketChat.authz.hasPermission(this.userId, 'manage-oauth-apps')) { + if (!hasPermission(this.userId, 'manage-oauth-apps')) { this.error(Meteor.Error('error-not-allowed', 'Not allowed', { publish: 'oauthApps' })); } - return RocketChat.models.OAuthApps.find(); + return OAuthApps.find(); }); diff --git a/packages/rocketchat-oauth2-server-config/server/index.js b/packages/rocketchat-oauth2-server-config/server/index.js index 0ca7e49a6905..4fe04df84ed2 100644 --- a/packages/rocketchat-oauth2-server-config/server/index.js +++ b/packages/rocketchat-oauth2-server-config/server/index.js @@ -1,4 +1,3 @@ -import './models/OAuthApps'; import './oauth/oauth2-server'; import './oauth/default-services'; import './admin/publications/oauthApps'; diff --git a/packages/rocketchat-oauth2-server-config/server/models/OAuthApps.js b/packages/rocketchat-oauth2-server-config/server/models/OAuthApps.js deleted file mode 100644 index 4d889bbd974a..000000000000 --- a/packages/rocketchat-oauth2-server-config/server/models/OAuthApps.js +++ /dev/null @@ -1,17 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.OAuthApps = new class extends RocketChat.models._Base { - constructor() { - super('oauth_apps'); - } -}; - - -// FIND -// findByRole: (role, options) -> -// query = -// roles: role - -// return @find query, options - -// CREATE diff --git a/packages/rocketchat-oauth2-server-config/server/oauth/default-services.js b/packages/rocketchat-oauth2-server-config/server/oauth/default-services.js index 156d79920211..380d3711d362 100644 --- a/packages/rocketchat-oauth2-server-config/server/oauth/default-services.js +++ b/packages/rocketchat-oauth2-server-config/server/oauth/default-services.js @@ -1,7 +1,7 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { OAuthApps } from 'meteor/rocketchat:models'; -if (!RocketChat.models.OAuthApps.findOne('zapier')) { - RocketChat.models.OAuthApps.insert({ +if (!OAuthApps.findOne('zapier')) { + OAuthApps.insert({ _id: 'zapier', name: 'Zapier', active: true, 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 b8b79807b1cd..ed6f8be4348a 100644 --- a/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js +++ b/packages/rocketchat-oauth2-server-config/server/oauth/oauth2-server.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { WebApp } from 'meteor/webapp'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { OAuthApps, Users } from 'meteor/rocketchat:models'; import { OAuth2Server } from 'meteor/rocketchat:oauth2-server'; import { API } from 'meteor/rocketchat:api'; @@ -8,7 +8,7 @@ const oauth2server = new OAuth2Server({ accessTokensCollectionName: 'rocketchat_oauth_access_tokens', refreshTokensCollectionName: 'rocketchat_oauth_refresh_tokens', authCodesCollectionName: 'rocketchat_oauth_auth_codes', - clientsCollection: RocketChat.models.OAuthApps.model, + clientsCollection: OAuthApps.model, debug: true, }); @@ -25,7 +25,7 @@ oauth2server.routes.get('/oauth/userinfo', function(req, res) { if (token == null) { return res.sendStatus(401).send('Invalid Token'); } - const user = RocketChat.models.Users.findOneById(token.userId); + const user = Users.findOneById(token.userId); if (user == null) { return res.sendStatus(401).send('Invalid Token'); } @@ -46,7 +46,7 @@ Meteor.publish('oauthClient', function(clientId) { if (!this.userId) { return this.ready(); } - return RocketChat.models.OAuthApps.find({ + return OAuthApps.find({ clientId, active: true, }, { @@ -79,7 +79,7 @@ API.v1.addAuthMethod(function() { if ((accessToken.expires != null) && accessToken.expires !== 0 && accessToken.expires < new Date()) { return; } - const user = RocketChat.models.Users.findOne(accessToken.userId); + const user = Users.findOne(accessToken.userId); if (user == null) { return; } From 584d08788c29def6157310107e1b409c09dcdca5 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 17:02:38 -0200 Subject: [PATCH 053/101] Remove dependency of RC namespace in rc-oembed --- packages/rocketchat-models/server/index.js | 2 ++ .../server/models/OEmbedCache.js | 8 ++--- .../client/oembedAudioWidget.js | 4 +-- .../client/oembedFrameWidget.js | 4 +-- .../client/oembedImageWidget.js | 8 ++--- .../client/oembedUrlWidget.js | 4 +-- .../client/oembedVideoWidget.js | 4 +-- .../client/oembedYoutubeWidget.js | 4 +-- packages/rocketchat-oembed/package.js | 4 ++- packages/rocketchat-oembed/server/index.js | 1 - .../rocketchat-oembed/server/jumpToMessage.js | 12 ++++---- .../rocketchat-oembed/server/providers.js | 14 ++++----- packages/rocketchat-oembed/server/server.js | 30 ++++++++++--------- 13 files changed, 53 insertions(+), 46 deletions(-) rename packages/{rocketchat-oembed => rocketchat-models}/server/models/OEmbedCache.js (79%) diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index 2abc6e8718cd..e2cf6662bba1 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -20,6 +20,7 @@ import IntegrationHistory from './models/IntegrationHistory'; import CredentialTokens from './models/CredentialTokens'; import EmojiCustom from './models/EmojiCustom'; import OAuthApps from './models/OAuthApps'; +import OEmbedCache from './models/OEmbedCache'; export { Base, @@ -44,4 +45,5 @@ export { CredentialTokens, EmojiCustom, OAuthApps, + OEmbedCache, }; diff --git a/packages/rocketchat-oembed/server/models/OEmbedCache.js b/packages/rocketchat-models/server/models/OEmbedCache.js similarity index 79% rename from packages/rocketchat-oembed/server/models/OEmbedCache.js rename to packages/rocketchat-models/server/models/OEmbedCache.js index 7f83342b51b2..444d30b1c63f 100644 --- a/packages/rocketchat-oembed/server/models/OEmbedCache.js +++ b/packages/rocketchat-models/server/models/OEmbedCache.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Base } from './_Base'; -RocketChat.models.OEmbedCache = new class extends RocketChat.models._Base { +export class OEmbedCache extends Base { constructor() { super('oembed_cache'); this.tryEnsureIndex({ updatedAt: 1 }); @@ -34,6 +34,6 @@ RocketChat.models.OEmbedCache = new class extends RocketChat.models._Base { }; return this.remove(query); } -}; - +} +export default new OEmbedCache(); diff --git a/packages/rocketchat-oembed/client/oembedAudioWidget.js b/packages/rocketchat-oembed/client/oembedAudioWidget.js index 85a5c7ceb947..0be8e05bdfa7 100644 --- a/packages/rocketchat-oembed/client/oembedAudioWidget.js +++ b/packages/rocketchat-oembed/client/oembedAudioWidget.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; Template.oembedAudioWidget.helpers({ collapsed() { if (this.collapsed) { return this.collapsed; } else { - return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; + return getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; } }, }); diff --git a/packages/rocketchat-oembed/client/oembedFrameWidget.js b/packages/rocketchat-oembed/client/oembedFrameWidget.js index 9a8d529fcf24..3538aab4e0f3 100644 --- a/packages/rocketchat-oembed/client/oembedFrameWidget.js +++ b/packages/rocketchat-oembed/client/oembedFrameWidget.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; Template.oembedFrameWidget.helpers({ collapsed() { if (this.collapsed) { return this.collapsed; } else { - return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; + return getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; } }, }); diff --git a/packages/rocketchat-oembed/client/oembedImageWidget.js b/packages/rocketchat-oembed/client/oembedImageWidget.js index 5b321caa97ce..99e75b0a723b 100644 --- a/packages/rocketchat-oembed/client/oembedImageWidget.js +++ b/packages/rocketchat-oembed/client/oembedImageWidget.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; Template.oembedImageWidget.helpers({ loadImage() { - if (RocketChat.getUserPreference(Meteor.userId(), 'autoImageLoad') === false && this.downloadImages == null) { + if (getUserPreference(Meteor.userId(), 'autoImageLoad') === false && this.downloadImages == null) { return false; } - if (Meteor.Device.isPhone() && RocketChat.getUserPreference(Meteor.userId(), 'saveMobileBandwidth') && this.downloadImages == null) { + if (Meteor.Device.isPhone() && getUserPreference(Meteor.userId(), 'saveMobileBandwidth') && this.downloadImages == null) { return false; } return true; @@ -16,7 +16,7 @@ Template.oembedImageWidget.helpers({ if (this.collapsed != null) { return this.collapsed; } else { - return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; + return getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; } }, }); diff --git a/packages/rocketchat-oembed/client/oembedUrlWidget.js b/packages/rocketchat-oembed/client/oembedUrlWidget.js index d231f6a35e80..9b6d93772b19 100644 --- a/packages/rocketchat-oembed/client/oembedUrlWidget.js +++ b/packages/rocketchat-oembed/client/oembedUrlWidget.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Blaze } from 'meteor/blaze'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; import _ from 'underscore'; const getTitle = function(self) { @@ -66,7 +66,7 @@ Template.oembedUrlWidget.helpers({ if (this.collapsed != null) { return this.collapsed; } else { - return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; + return getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; } }, }); diff --git a/packages/rocketchat-oembed/client/oembedVideoWidget.js b/packages/rocketchat-oembed/client/oembedVideoWidget.js index 0c0d21d40d89..8b9ac363718a 100644 --- a/packages/rocketchat-oembed/client/oembedVideoWidget.js +++ b/packages/rocketchat-oembed/client/oembedVideoWidget.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; const getTitle = function(self) { if (self.meta == null) { @@ -31,7 +31,7 @@ Template.oembedVideoWidget.helpers({ if (this.collapsed) { return this.collapsed; } else { - return RocketChat.getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; + return getUserPreference(Meteor.userId(), 'collapseMediaByDefault') === true; } }, diff --git a/packages/rocketchat-oembed/client/oembedYoutubeWidget.js b/packages/rocketchat-oembed/client/oembedYoutubeWidget.js index 848e89e2f219..3cece36b63cd 100644 --- a/packages/rocketchat-oembed/client/oembedYoutubeWidget.js +++ b/packages/rocketchat-oembed/client/oembedYoutubeWidget.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { getUserPreference } from 'meteor/rocketchat:utils'; Template.oembedYoutubeWidget.helpers({ collapsed() { @@ -8,7 +8,7 @@ Template.oembedYoutubeWidget.helpers({ return this.collapsed; } else { const user = Meteor.user(); - return RocketChat.getUserPreference(user, 'collapseMediaByDefault') === true; + return getUserPreference(user, 'collapseMediaByDefault') === true; } }, }); diff --git a/packages/rocketchat-oembed/package.js b/packages/rocketchat-oembed/package.js index 9d8196c7610d..956933eb2505 100644 --- a/packages/rocketchat-oembed/package.js +++ b/packages/rocketchat-oembed/package.js @@ -11,7 +11,9 @@ Package.onUse(function(api) { 'templating', 'ecmascript', 'konecty:change-case', - 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:callbacks', 'rocketchat:utils', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-oembed/server/index.js b/packages/rocketchat-oembed/server/index.js index a16eab3a866a..86617752ce43 100644 --- a/packages/rocketchat-oembed/server/index.js +++ b/packages/rocketchat-oembed/server/index.js @@ -1,4 +1,3 @@ -import './models/OEmbedCache'; import './jumpToMessage'; import './providers'; import { OEmbed } from './server'; diff --git a/packages/rocketchat-oembed/server/jumpToMessage.js b/packages/rocketchat-oembed/server/jumpToMessage.js index ca84b1026a0d..d8d082f89e24 100644 --- a/packages/rocketchat-oembed/server/jumpToMessage.js +++ b/packages/rocketchat-oembed/server/jumpToMessage.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { getAvatarUrlFromUsername } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import URL from 'url'; @@ -7,7 +9,7 @@ import QueryString from 'querystring'; const recursiveRemove = (message, deep = 1) => { if (message) { - if ('attachments' in message && message.attachments !== null && deep < RocketChat.settings.get('Message_QuoteChainLimit')) { + if ('attachments' in message && message.attachments !== null && deep < settings.get('Message_QuoteChainLimit')) { message.attachments.map((msg) => recursiveRemove(msg, deep + 1)); } else { delete(message.attachments); @@ -16,7 +18,7 @@ const recursiveRemove = (message, deep = 1) => { return message; }; -RocketChat.callbacks.add('beforeSaveMessage', (msg) => { +callbacks.add('beforeSaveMessage', (msg) => { if (msg && msg.urls) { msg.urls.forEach((item) => { if (item.url.indexOf(Meteor.absoluteUrl()) === 0) { @@ -24,7 +26,7 @@ RocketChat.callbacks.add('beforeSaveMessage', (msg) => { if (urlObj.query) { const queryString = QueryString.parse(urlObj.query); if (_.isString(queryString.msg)) { // Jump-to query param - const jumpToMessage = recursiveRemove(RocketChat.models.Messages.findOneById(queryString.msg)); + const jumpToMessage = recursiveRemove(Messages.findOneById(queryString.msg)); if (jumpToMessage) { msg.attachments = msg.attachments || []; @@ -50,4 +52,4 @@ RocketChat.callbacks.add('beforeSaveMessage', (msg) => { }); } return msg; -}, RocketChat.callbacks.priority.LOW, 'jumpToMessage'); +}, callbacks.priority.LOW, 'jumpToMessage'); diff --git a/packages/rocketchat-oembed/server/providers.js b/packages/rocketchat-oembed/server/providers.js index 60e18cc8144b..c0f6b0d5bb56 100644 --- a/packages/rocketchat-oembed/server/providers.js +++ b/packages/rocketchat-oembed/server/providers.js @@ -1,5 +1,5 @@ import { changeCase } from 'meteor/konecty:change-case'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; import URL from 'url'; import QueryString from 'querystring'; @@ -66,11 +66,11 @@ providers.registerProvider({ endPoint: 'https://www.dailymotion.com/services/oembed?maxheight=200', }); -RocketChat.oembed = {}; +export const oembed = {}; -RocketChat.oembed.providers = providers; +oembed.providers = providers; -RocketChat.callbacks.add('oembed:beforeGetUrlContent', function(data) { +callbacks.add('oembed:beforeGetUrlContent', function(data) { if (data.parsedUrl != null) { const url = URL.format(data.parsedUrl); const provider = providers.getProviderForUrl(url); @@ -87,9 +87,9 @@ RocketChat.callbacks.add('oembed:beforeGetUrlContent', function(data) { } } return data; -}, RocketChat.callbacks.priority.MEDIUM, 'oembed-providers-before'); +}, callbacks.priority.MEDIUM, 'oembed-providers-before'); -RocketChat.callbacks.add('oembed:afterParseContent', function(data) { +callbacks.add('oembed:afterParseContent', function(data) { if (data.parsedUrl && data.parsedUrl.query) { let queryString = data.parsedUrl.query; if (_.isString(data.parsedUrl.query)) { @@ -116,4 +116,4 @@ RocketChat.callbacks.add('oembed:afterParseContent', function(data) { } } return data; -}, RocketChat.callbacks.priority.MEDIUM, 'oembed-providers-after'); +}, callbacks.priority.MEDIUM, 'oembed-providers-after'); diff --git a/packages/rocketchat-oembed/server/server.js b/packages/rocketchat-oembed/server/server.js index d323649e6e1e..b43930743abc 100644 --- a/packages/rocketchat-oembed/server/server.js +++ b/packages/rocketchat-oembed/server/server.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { HTTPInternals } from 'meteor/http'; import { changeCase } from 'meteor/konecty:change-case'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { OEmbedCache, Messages } from 'meteor/rocketchat:models'; import _ from 'underscore'; import URL from 'url'; import querystring from 'querystring'; @@ -62,17 +64,17 @@ const getUrlContent = function(urlObj, redirectCount = 5, callback) { } const parsedUrl = _.pick(urlObj, ['host', 'hash', 'pathname', 'protocol', 'port', 'query', 'search', 'hostname']); - const ignoredHosts = RocketChat.settings.get('API_EmbedIgnoredHosts').replace(/\s/g, '').split(',') || []; + const ignoredHosts = settings.get('API_EmbedIgnoredHosts').replace(/\s/g, '').split(',') || []; if (ignoredHosts.includes(parsedUrl.hostname) || ipRangeCheck(parsedUrl.hostname, ignoredHosts)) { return callback(); } - const safePorts = RocketChat.settings.get('API_EmbedSafePorts').replace(/\s/g, '').split(',') || []; + const safePorts = settings.get('API_EmbedSafePorts').replace(/\s/g, '').split(',') || []; if (parsedUrl.port && safePorts.length > 0 && (!safePorts.includes(parsedUrl.port))) { return callback(); } - const data = RocketChat.callbacks.run('oembed:beforeGetUrlContent', { + const data = callbacks.run('oembed:beforeGetUrlContent', { urlObj, parsedUrl, }); @@ -82,11 +84,11 @@ const getUrlContent = function(urlObj, redirectCount = 5, callback) { const url = URL.format(data.urlObj); const opts = { url, - strictSSL: !RocketChat.settings.get('Allow_Invalid_SelfSigned_Certs'), + strictSSL: !settings.get('Allow_Invalid_SelfSigned_Certs'), gzip: true, maxRedirects: redirectCount, headers: { - 'User-Agent': RocketChat.settings.get('API_Embed_UserAgent'), + 'User-Agent': settings.get('API_Embed_UserAgent'), }, }; let headers = null; @@ -189,7 +191,7 @@ OEmbed.getUrlMeta = function(url, withFragment) { if (content && content.statusCode !== 200) { return data; } - data = RocketChat.callbacks.run('oembed:afterParseContent', { + data = callbacks.run('oembed:afterParseContent', { meta: metas, headers, parsedUrl: content.parsedUrl, @@ -199,14 +201,14 @@ OEmbed.getUrlMeta = function(url, withFragment) { }; OEmbed.getUrlMetaWithCache = function(url, withFragment) { - const cache = RocketChat.models.OEmbedCache.findOneById(url); + const cache = OEmbedCache.findOneById(url); if (cache != null) { return cache.data; } const data = OEmbed.getUrlMeta(url, withFragment); if (data != null) { try { - RocketChat.models.OEmbedCache.createWithIdAndData(url, data); + OEmbedCache.createWithIdAndData(url, data); } catch (_error) { console.error('OEmbed duplicated record', url); } @@ -280,20 +282,20 @@ OEmbed.rocketUrlParser = function(message) { } }); if (attachments.length) { - RocketChat.models.Messages.setMessageAttachments(message._id, attachments); + Messages.setMessageAttachments(message._id, attachments); } if (changed === true) { - RocketChat.models.Messages.setUrlsById(message._id, message.urls); + Messages.setUrlsById(message._id, message.urls); } } return message; }; -RocketChat.settings.get('API_Embed', function(key, value) { +settings.get('API_Embed', function(key, value) { if (value) { - return RocketChat.callbacks.add('afterSaveMessage', OEmbed.rocketUrlParser, RocketChat.callbacks.priority.LOW, 'API_Embed'); + return callbacks.add('afterSaveMessage', OEmbed.rocketUrlParser, callbacks.priority.LOW, 'API_Embed'); } else { - return RocketChat.callbacks.remove('afterSaveMessage', 'API_Embed'); + return callbacks.remove('afterSaveMessage', 'API_Embed'); } }); From c06f9e1c763f959c7fd48053a16f892c76c4cc5f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 17:24:05 -0200 Subject: [PATCH 054/101] Remove dependency of RC namespace in rc-otr --- .../server/models/Messages.js | 11 +++++++ packages/rocketchat-otr/client/index.js | 2 +- .../rocketchat-otr/client/rocketchat.otr.js | 32 ++++++++++--------- .../client/rocketchat.otr.room.js | 31 +++++++++--------- packages/rocketchat-otr/client/tabBar.js | 16 ++++++---- .../rocketchat-otr/client/views/otrFlexTab.js | 16 +++++----- packages/rocketchat-otr/package.js | 6 +++- packages/rocketchat-otr/server/index.js | 1 - .../server/methods/deleteOldOTRMessages.js | 6 ++-- .../server/methods/updateOTRAck.js | 4 +-- .../rocketchat-otr/server/models/Messages.js | 12 ------- packages/rocketchat-otr/server/settings.js | 4 +-- 12 files changed, 74 insertions(+), 67 deletions(-) delete mode 100644 packages/rocketchat-otr/server/models/Messages.js diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index 2ccc8d21c8ba..dd333283114c 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 { }); } + deleteOldOTRMessages(roomId, ts) { + const query = { rid: roomId, t: 'otr', ts: { $lte: ts } }; + return this.remove(query); + } + + updateOTRAck(_id, otrAck) { + const query = { _id }; + const update = { $set: { otrAck } }; + return this.update(query, update); + } + setGoogleVisionData(messageId, visionData) { const updateObj = {}; for (const index in visionData) { diff --git a/packages/rocketchat-otr/client/index.js b/packages/rocketchat-otr/client/index.js index fb0bd1078d0c..5a2ca16a74a7 100644 --- a/packages/rocketchat-otr/client/index.js +++ b/packages/rocketchat-otr/client/index.js @@ -1,5 +1,5 @@ -import './rocketchat.otr'; import './rocketchat.otr.room'; +import './rocketchat.otr'; import './views/otrFlexTab.html'; import './views/otrFlexTab'; import './tabBar'; diff --git a/packages/rocketchat-otr/client/rocketchat.otr.js b/packages/rocketchat-otr/client/rocketchat.otr.js index 977bf8072b7f..4f9d49645e5e 100644 --- a/packages/rocketchat-otr/client/rocketchat.otr.js +++ b/packages/rocketchat-otr/client/rocketchat.otr.js @@ -1,10 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions } from 'meteor/rocketchat:models'; +import { promises } from 'meteor/rocketchat:promises'; +import { Notifications } from 'meteor/rocketchat:notifications'; import { t } from 'meteor/rocketchat:utils'; -class OTR { +class OTRClass { constructor() { this.enabled = new ReactiveVar(false); this.instancesByRoomId = {}; @@ -23,7 +25,7 @@ class OTR { return this.instancesByRoomId[roomId]; } - const subscription = RocketChat.models.Subscriptions.findOne({ + const subscription = Subscriptions.findOne({ rid: roomId, }); @@ -31,29 +33,29 @@ class OTR { return; } - this.instancesByRoomId[roomId] = new RocketChat.OTR.Room(Meteor.userId(), roomId); + this.instancesByRoomId[roomId] = new OTR.Room(Meteor.userId(), roomId); // eslint-disable-line no-use-before-define return this.instancesByRoomId[roomId]; } } -RocketChat.OTR = new OTR(); +export const OTR = new OTRClass(); Meteor.startup(function() { Tracker.autorun(function() { if (Meteor.userId()) { - RocketChat.Notifications.onUser('otr', (type, data) => { + Notifications.onUser('otr', (type, data) => { if (!data.roomId || !data.userId || data.userId === Meteor.userId()) { return; } else { - RocketChat.OTR.getInstanceByRoomId(data.roomId).onUserStream(type, data); + OTR.getInstanceByRoomId(data.roomId).onUserStream(type, data); } }); } }); - RocketChat.promises.add('onClientBeforeSendMessage', function(message) { - if (message.rid && RocketChat.OTR.getInstanceByRoomId(message.rid) && RocketChat.OTR.getInstanceByRoomId(message.rid).established.get()) { - return RocketChat.OTR.getInstanceByRoomId(message.rid).encrypt(message) + promises.add('onClientBeforeSendMessage', function(message) { + if (message.rid && OTR.getInstanceByRoomId(message.rid) && OTR.getInstanceByRoomId(message.rid).established.get()) { + return OTR.getInstanceByRoomId(message.rid).encrypt(message) .then((msg) => { message.msg = msg; message.t = 'otr'; @@ -62,15 +64,15 @@ Meteor.startup(function() { } else { return Promise.resolve(message); } - }, RocketChat.promises.priority.HIGH); + }, promises.priority.HIGH); - RocketChat.promises.add('onClientMessageReceived', function(message) { - if (message.rid && RocketChat.OTR.getInstanceByRoomId(message.rid) && RocketChat.OTR.getInstanceByRoomId(message.rid).established.get()) { + promises.add('onClientMessageReceived', function(message) { + if (message.rid && OTR.getInstanceByRoomId(message.rid) && OTR.getInstanceByRoomId(message.rid).established.get()) { if (message.notification) { message.msg = t('Encrypted_message'); return Promise.resolve(message); } else { - const otrRoom = RocketChat.OTR.getInstanceByRoomId(message.rid); + const otrRoom = OTR.getInstanceByRoomId(message.rid); return otrRoom.decrypt(message.msg) .then((data) => { const { _id, text, ack } = data; @@ -106,5 +108,5 @@ Meteor.startup(function() { } return Promise.resolve(message); } - }, RocketChat.promises.priority.HIGH); + }, promises.priority.HIGH); }); diff --git a/packages/rocketchat-otr/client/rocketchat.otr.room.js b/packages/rocketchat-otr/client/rocketchat.otr.room.js index a70e7b893ebb..d40524713c8d 100644 --- a/packages/rocketchat-otr/client/rocketchat.otr.room.js +++ b/packages/rocketchat-otr/client/rocketchat.otr.room.js @@ -6,12 +6,13 @@ import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { TAPi18n } from 'meteor/tap:i18n'; import { TimeSync } from 'meteor/mizzao:timesync'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { modal } from 'meteor/rocketchat:ui-utils'; +import { OTR } from './rocketchat.otr'; import _ from 'underscore'; import toastr from 'toastr'; -RocketChat.OTR.Room = class { +OTR.Room = class { constructor(userId, roomId) { this.userId = userId; this.roomId = roomId; @@ -30,22 +31,22 @@ RocketChat.OTR.Room = class { this.establishing.set(true); this.firstPeer = true; this.generateKeyPair().then(() => { - RocketChat.Notifications.notifyUser(this.peerId, 'otr', 'handshake', { roomId: this.roomId, userId: this.userId, publicKey: EJSON.stringify(this.exportedPublicKey), refresh }); + Notifications.notifyUser(this.peerId, 'otr', 'handshake', { roomId: this.roomId, userId: this.userId, publicKey: EJSON.stringify(this.exportedPublicKey), refresh }); }); } acknowledge() { - RocketChat.Notifications.notifyUser(this.peerId, 'otr', 'acknowledge', { roomId: this.roomId, userId: this.userId, publicKey: EJSON.stringify(this.exportedPublicKey) }); + Notifications.notifyUser(this.peerId, 'otr', 'acknowledge', { roomId: this.roomId, userId: this.userId, publicKey: EJSON.stringify(this.exportedPublicKey) }); } deny() { this.reset(); - RocketChat.Notifications.notifyUser(this.peerId, 'otr', 'deny', { roomId: this.roomId, userId: this.userId }); + Notifications.notifyUser(this.peerId, 'otr', 'deny', { roomId: this.roomId, userId: this.userId }); } end() { this.reset(); - RocketChat.Notifications.notifyUser(this.peerId, 'otr', 'end', { roomId: this.roomId, userId: this.userId }); + Notifications.notifyUser(this.peerId, 'otr', 'end', { roomId: this.roomId, userId: this.userId }); } reset() { @@ -79,13 +80,13 @@ RocketChat.OTR.Room = class { }); // Generate an ephemeral key pair. - return RocketChat.OTR.crypto.generateKey({ + return OTR.crypto.generateKey({ name: 'ECDH', namedCurve: 'P-256', }, false, ['deriveKey', 'deriveBits']) .then((keyPair) => { this.keyPair = keyPair; - return RocketChat.OTR.crypto.exportKey('jwk', keyPair.publicKey); + return OTR.crypto.exportKey('jwk', keyPair.publicKey); }) .then((exportedPublicKey) => { this.exportedPublicKey = exportedPublicKey; @@ -99,19 +100,19 @@ RocketChat.OTR.Room = class { } importPublicKey(publicKey) { - return RocketChat.OTR.crypto.importKey('jwk', EJSON.parse(publicKey), { + return OTR.crypto.importKey('jwk', EJSON.parse(publicKey), { name: 'ECDH', namedCurve: 'P-256', - }, false, []).then((peerPublicKey) => RocketChat.OTR.crypto.deriveBits({ + }, false, []).then((peerPublicKey) => OTR.crypto.deriveBits({ name: 'ECDH', namedCurve: 'P-256', public: peerPublicKey, - }, this.keyPair.privateKey, 256)).then((bits) => RocketChat.OTR.crypto.digest({ + }, this.keyPair.privateKey, 256)).then((bits) => OTR.crypto.digest({ name: 'SHA-256', }, bits)).then((hashedBits) => { // We truncate the hash to 128 bits. const sessionKeyData = new Uint8Array(hashedBits).slice(0, 16); - return RocketChat.OTR.crypto.importKey('raw', sessionKeyData, { + return OTR.crypto.importKey('raw', sessionKeyData, { name: 'AES-GCM', }, false, ['encrypt', 'decrypt']); }).then((sessionKey) => { @@ -126,7 +127,7 @@ RocketChat.OTR.Room = class { } const iv = crypto.getRandomValues(new Uint8Array(12)); - return RocketChat.OTR.crypto.encrypt({ + return OTR.crypto.encrypt({ name: 'AES-GCM', iv, }, this.sessionKey, data).then((cipherText) => { @@ -164,7 +165,7 @@ RocketChat.OTR.Room = class { const iv = cipherText.slice(0, 12); cipherText = cipherText.slice(12); - return RocketChat.OTR.crypto.decrypt({ + return OTR.crypto.decrypt({ name: 'AES-GCM', iv, }, this.sessionKey, cipherText) diff --git a/packages/rocketchat-otr/client/tabBar.js b/packages/rocketchat-otr/client/tabBar.js index 156cf9167c10..7c321d302562 100644 --- a/packages/rocketchat-otr/client/tabBar.js +++ b/packages/rocketchat-otr/client/tabBar.js @@ -1,13 +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 { TabBar } from 'meteor/rocketchat:ui-utils'; +import { OTR } from './rocketchat.otr'; Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('OTR_Enable') && window.crypto) { - RocketChat.OTR.crypto = window.crypto.subtle || window.crypto.webkitSubtle; - RocketChat.OTR.enabled.set(true); - RocketChat.TabBar.addButton({ + if (settings.get('OTR_Enable') && window.crypto) { + OTR.crypto = window.crypto.subtle || window.crypto.webkitSubtle; + OTR.enabled.set(true); + TabBar.addButton({ groups: ['direct'], id: 'otr', i18nTitle: 'OTR', @@ -16,8 +18,8 @@ Meteor.startup(function() { order: 11, }); } else { - RocketChat.OTR.enabled.set(false); - RocketChat.TabBar.removeButton('otr'); + OTR.enabled.set(false); + TabBar.removeButton('otr'); } }); }); diff --git a/packages/rocketchat-otr/client/views/otrFlexTab.js b/packages/rocketchat-otr/client/views/otrFlexTab.js index ebfbecff3b9f..6116dec4d71f 100644 --- a/packages/rocketchat-otr/client/views/otrFlexTab.js +++ b/packages/rocketchat-otr/client/views/otrFlexTab.js @@ -1,11 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { OTR } from '../rocketchat.otr'; import { modal } from 'meteor/rocketchat:ui'; Template.otrFlexTab.helpers({ otrAvailable() { - return RocketChat.OTR && RocketChat.OTR.isEnabled(); + return OTR && OTR.isEnabled(); }, userIsOnline() { // I have to appear online for the other user @@ -23,11 +23,11 @@ Template.otrFlexTab.helpers({ } }, established() { - const otr = RocketChat.OTR.getInstanceByRoomId(this.rid); + const otr = OTR.getInstanceByRoomId(this.rid); return otr && otr.established.get(); }, establishing() { - const otr = RocketChat.OTR.getInstanceByRoomId(this.rid); + const otr = OTR.getInstanceByRoomId(this.rid); return otr && otr.establishing.get(); }, }); @@ -35,7 +35,7 @@ Template.otrFlexTab.helpers({ Template.otrFlexTab.events({ 'click button.start'(e, t) { e.preventDefault(); - const otr = RocketChat.OTR.getInstanceByRoomId(this.rid); + const otr = OTR.getInstanceByRoomId(this.rid); if (otr) { otr.handshake(); t.timeout = Meteor.setTimeout(() => { @@ -50,7 +50,7 @@ Template.otrFlexTab.events({ }, 'click button.refresh'(e, t) { e.preventDefault(); - const otr = RocketChat.OTR.getInstanceByRoomId(this.rid); + const otr = OTR.getInstanceByRoomId(this.rid); if (otr) { otr.reset(); otr.handshake(true); @@ -66,7 +66,7 @@ Template.otrFlexTab.events({ }, 'click button.end'(e/* , t*/) { e.preventDefault(); - const otr = RocketChat.OTR.getInstanceByRoomId(this.rid); + const otr = OTR.getInstanceByRoomId(this.rid); if (otr) { otr.end(); } @@ -76,7 +76,7 @@ Template.otrFlexTab.events({ Template.otrFlexTab.onCreated(function() { this.timeout = null; this.autorun(() => { - const otr = RocketChat.OTR.getInstanceByRoomId(this.data.rid); + const otr = OTR.getInstanceByRoomId(this.data.rid); if (otr && otr.established.get()) { Meteor.clearTimeout(this.timeout); } diff --git a/packages/rocketchat-otr/package.js b/packages/rocketchat-otr/package.js index 124bb4e2f249..c7be4707c1cf 100644 --- a/packages/rocketchat-otr/package.js +++ b/packages/rocketchat-otr/package.js @@ -9,7 +9,11 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:promises', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:notifications', + 'rocketchat:ui-utils', 'tracker', 'reactive-var', 'templating', diff --git a/packages/rocketchat-otr/server/index.js b/packages/rocketchat-otr/server/index.js index 3d2d30e4b1ed..1df0c14f3b15 100644 --- a/packages/rocketchat-otr/server/index.js +++ b/packages/rocketchat-otr/server/index.js @@ -1,4 +1,3 @@ import './settings'; -import './models/Messages'; import './methods/deleteOldOTRMessages'; import './methods/updateOTRAck'; diff --git a/packages/rocketchat-otr/server/methods/deleteOldOTRMessages.js b/packages/rocketchat-otr/server/methods/deleteOldOTRMessages.js index 9763067b0bd6..bc8d910cdcd3 100644 --- a/packages/rocketchat-otr/server/methods/deleteOldOTRMessages.js +++ b/packages/rocketchat-otr/server/methods/deleteOldOTRMessages.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions, Messages } from 'meteor/rocketchat:models'; Meteor.methods({ deleteOldOTRMessages(roomId) { @@ -8,9 +8,9 @@ Meteor.methods({ } const now = new Date(); - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, Meteor.userId()); + const subscription = Subscriptions.findOneByRoomIdAndUserId(roomId, Meteor.userId()); if (subscription && subscription.t === 'd') { - RocketChat.models.Messages.deleteOldOTRMessages(roomId, now); + Messages.deleteOldOTRMessages(roomId, now); } else { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'deleteOldOTRMessages' }); } diff --git a/packages/rocketchat-otr/server/methods/updateOTRAck.js b/packages/rocketchat-otr/server/methods/updateOTRAck.js index 0e5a7c85059e..2c77dea587d0 100644 --- a/packages/rocketchat-otr/server/methods/updateOTRAck.js +++ b/packages/rocketchat-otr/server/methods/updateOTRAck.js @@ -1,11 +1,11 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages } from 'meteor/rocketchat:models'; Meteor.methods({ updateOTRAck(_id, ack) { if (!Meteor.userId()) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'updateOTRAck' }); } - RocketChat.models.Messages.updateOTRAck(_id, ack); + Messages.updateOTRAck(_id, ack); }, }); diff --git a/packages/rocketchat-otr/server/models/Messages.js b/packages/rocketchat-otr/server/models/Messages.js deleted file mode 100644 index a8af1f83eaac..000000000000 --- a/packages/rocketchat-otr/server/models/Messages.js +++ /dev/null @@ -1,12 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.deleteOldOTRMessages = function(roomId, ts) { - const query = { rid: roomId, t: 'otr', ts: { $lte: ts } }; - return this.remove(query); -}; - -RocketChat.models.Messages.updateOTRAck = function(_id, otrAck) { - const query = { _id }; - const update = { $set: { otrAck } }; - return this.update(query, update); -}; diff --git a/packages/rocketchat-otr/server/settings.js b/packages/rocketchat-otr/server/settings.js index 22310dfa5267..82c72d2c2b91 100644 --- a/packages/rocketchat-otr/server/settings.js +++ b/packages/rocketchat-otr/server/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('OTR', function() { +settings.addGroup('OTR', function() { this.add('OTR_Enable', true, { type: 'boolean', i18nLabel: 'Enabled', From b807e99b1568c315faade57d957ddf349ef84e31 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 18:06:57 -0200 Subject: [PATCH 055/101] Remove dependency of RC namespace in rc-reactions --- .../client/models/ChatMessage.js | 8 ++++ .../client/models/ChatRoom.js | 8 ++++ .../server/models/Messages.js | 8 ++++ .../rocketchat-models/server/models/Rooms.js | 8 ++++ packages/rocketchat-reactions/client/index.js | 2 - packages/rocketchat-reactions/client/init.js | 23 ++++++----- .../client/methods/setReaction.js | 24 ++++++------ .../lib/models/Messages.js | 9 ----- .../rocketchat-reactions/lib/models/Rooms.js | 9 ----- packages/rocketchat-reactions/package.js | 8 +++- packages/rocketchat-reactions/server/index.js | 2 - .../server/setReaction.js | 38 ++++++++++--------- 12 files changed, 85 insertions(+), 62 deletions(-) delete mode 100644 packages/rocketchat-reactions/lib/models/Messages.js delete mode 100644 packages/rocketchat-reactions/lib/models/Rooms.js diff --git a/packages/rocketchat-models/client/models/ChatMessage.js b/packages/rocketchat-models/client/models/ChatMessage.js index 7a7947b1a566..9109ffabfc2b 100644 --- a/packages/rocketchat-models/client/models/ChatMessage.js +++ b/packages/rocketchat-models/client/models/ChatMessage.js @@ -1,3 +1,11 @@ import { Mongo } from 'meteor/mongo'; export const ChatMessage = new Mongo.Collection(null); + +ChatMessage.setReactions = function(messageId, reactions) { + return this.update({ _id: messageId }, { $set: { reactions } }); +}; + +ChatMessage.unsetReactions = function(messageId) { + return this.update({ _id: messageId }, { $unset: { reactions: 1 } }); +}; diff --git a/packages/rocketchat-models/client/models/ChatRoom.js b/packages/rocketchat-models/client/models/ChatRoom.js index c7867ba834a2..e55c3e94f930 100644 --- a/packages/rocketchat-models/client/models/ChatRoom.js +++ b/packages/rocketchat-models/client/models/ChatRoom.js @@ -1,3 +1,11 @@ import { CachedChatRoom } from './CachedChatRoom'; export const ChatRoom = CachedChatRoom.collection; + +ChatRoom.setReactionsInLastMessage = function(roomId, lastMessage) { + return this.update({ _id: roomId }, { $set: { lastMessage } }); +}; + +ChatRoom.unsetReactionsInLastMessage = function(roomId) { + return this.update({ _id: roomId }, { $unset: { lastMessage: { reactions: 1 } } }); +}; diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index dd333283114c..f284564aa685 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 { }); } + setReactions(messageId, reactions) { + return this.update({ _id: messageId }, { $set: { reactions } }); + } + + unsetReactions(messageId) { + return this.update({ _id: messageId }, { $unset: { reactions: 1 } }); + } + deleteOldOTRMessages(roomId, ts) { const query = { rid: roomId, t: 'otr', ts: { $lte: ts } }; return this.remove(query); diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index 5e36690db5b8..ce1b209292ce 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,14 @@ export class Rooms extends Base { return this.findOne(query, options); } + setReactionsInLastMessage(roomId, lastMessage) { + return this.update({ _id: roomId }, { $set: { lastMessage } }); + } + + unsetReactionsInLastMessage(roomId) { + return this.update({ _id: roomId }, { $unset: { lastMessage: { reactions: 1 } } }); + } + updateLastMessageStar(roomId, userId, starred) { let update; const query = { _id: roomId }; diff --git a/packages/rocketchat-reactions/client/index.js b/packages/rocketchat-reactions/client/index.js index 84f0f9d06ac3..8d85a264dd7d 100644 --- a/packages/rocketchat-reactions/client/index.js +++ b/packages/rocketchat-reactions/client/index.js @@ -1,4 +1,2 @@ -import '../lib/models/Rooms'; -import '../lib/models/Messages'; import './init'; import './methods/setReaction'; diff --git a/packages/rocketchat-reactions/client/init.js b/packages/rocketchat-reactions/client/init.js index c759dacab87d..dfc4d43805fa 100644 --- a/packages/rocketchat-reactions/client/init.js +++ b/packages/rocketchat-reactions/client/init.js @@ -1,7 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Blaze } from 'meteor/blaze'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { MessageAction } from 'meteor/rocketchat:ui-utils'; +import { EmojiPicker } from 'meteor/rocketchat:emoji'; +import { tooltip } from 'meteor/rocketchat:tooltip'; Template.room.events({ 'click .add-reaction, click [data-message-action="reaction-message"]'(event) { @@ -10,13 +13,13 @@ Template.room.events({ const data = Blaze.getData(event.currentTarget); const user = Meteor.user(); - const room = RocketChat.models.Rooms.findOne({ _id: data._arguments[1].rid }); + const room = Rooms.findOne({ _id: data._arguments[1].rid }); if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1 && !room.reactWhenReadOnly) { return false; } - RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => { + EmojiPicker.open(event.currentTarget, (emoji) => { Meteor.call('setReaction', `:${ emoji }:`, data._arguments[1]._id); }); }, @@ -25,23 +28,23 @@ Template.room.events({ event.preventDefault(); const data = Blaze.getData(event.currentTarget); Meteor.call('setReaction', $(event.currentTarget).data('emoji'), data._arguments[1]._id, () => { - RocketChat.tooltip.hide(); + tooltip.hide(); }); }, 'mouseenter .reactions > li:not(.add-reaction)'(event) { event.stopPropagation(); - RocketChat.tooltip.showElement($(event.currentTarget).find('.people').get(0), event.currentTarget); + tooltip.showElement($(event.currentTarget).find('.people').get(0), event.currentTarget); }, 'mouseleave .reactions > li:not(.add-reaction)'(event) { event.stopPropagation(); - RocketChat.tooltip.hide(); + tooltip.hide(); }, }); Meteor.startup(function() { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'reaction-message', icon: 'add-reaction', label: 'Reactions', @@ -51,17 +54,17 @@ Meteor.startup(function() { ], action(event) { event.stopPropagation(); - RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => Meteor.call('setReaction', `:${ emoji }:`, this._arguments[1]._id)); + EmojiPicker.open(event.currentTarget, (emoji) => Meteor.call('setReaction', `:${ emoji }:`, this._arguments[1]._id)); }, condition(message) { - const room = RocketChat.models.Rooms.findOne({ _id: message.rid }); + const room = Rooms.findOne({ _id: message.rid }); const user = Meteor.user(); if (!room) { return false; } else if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1 && !room.reactWhenReadOnly) { return false; - } else if (!RocketChat.models.Subscriptions.findOne({ rid: message.rid })) { + } else if (!Subscriptions.findOne({ rid: message.rid })) { return false; } else if (message.private) { return false; diff --git a/packages/rocketchat-reactions/client/methods/setReaction.js b/packages/rocketchat-reactions/client/methods/setReaction.js index c3a5f570d30e..b12b9fc65579 100644 --- a/packages/rocketchat-reactions/client/methods/setReaction.js +++ b/packages/rocketchat-reactions/client/methods/setReaction.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, Rooms, Subscriptions, EmojiCustom } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { emoji } from 'meteor/rocketchat:emoji'; import _ from 'underscore'; Meteor.methods({ @@ -10,16 +12,16 @@ Meteor.methods({ const user = Meteor.user(); - const message = RocketChat.models.Messages.findOne({ _id: messageId }); - const room = RocketChat.models.Rooms.findOne({ _id: message.rid }); + const message = Messages.findOne({ _id: messageId }); + const room = Rooms.findOne({ _id: message.rid }); if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1 && !room.reactWhenReadOnly) { return false; - } else if (!RocketChat.models.Subscriptions.findOne({ rid: message.rid })) { + } else if (!Subscriptions.findOne({ rid: message.rid })) { return false; } else if (message.private) { return false; - } else if (!RocketChat.emoji.list[reaction] && RocketChat.models.EmojiCustom.findByNameOrAlias(reaction).count() === 0) { + } else if (!emoji.list[reaction] && EmojiCustom.findByNameOrAlias(reaction).count() === 0) { return false; } @@ -32,11 +34,11 @@ Meteor.methods({ if (_.isEmpty(message.reactions)) { delete message.reactions; - RocketChat.models.Messages.unsetReactions(messageId); - RocketChat.callbacks.run('unsetReaction', messageId, reaction); + Messages.unsetReactions(messageId); + callbacks.run('unsetReaction', messageId, reaction); } else { - RocketChat.models.Messages.setReactions(messageId, message.reactions); - RocketChat.callbacks.run('setReaction', messageId, reaction); + Messages.setReactions(messageId, message.reactions); + callbacks.run('setReaction', messageId, reaction); } } else { if (!message.reactions) { @@ -49,8 +51,8 @@ Meteor.methods({ } message.reactions[reaction].usernames.push(user.username); - RocketChat.models.Messages.setReactions(messageId, message.reactions); - RocketChat.callbacks.run('setReaction', messageId, reaction); + Messages.setReactions(messageId, message.reactions); + callbacks.run('setReaction', messageId, reaction); } return; diff --git a/packages/rocketchat-reactions/lib/models/Messages.js b/packages/rocketchat-reactions/lib/models/Messages.js deleted file mode 100644 index 36eb034771fb..000000000000 --- a/packages/rocketchat-reactions/lib/models/Messages.js +++ /dev/null @@ -1,9 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.setReactions = function(messageId, reactions) { - return this.update({ _id: messageId }, { $set: { reactions } }); -}; - -RocketChat.models.Messages.unsetReactions = function(messageId) { - return this.update({ _id: messageId }, { $unset: { reactions: 1 } }); -}; diff --git a/packages/rocketchat-reactions/lib/models/Rooms.js b/packages/rocketchat-reactions/lib/models/Rooms.js deleted file mode 100644 index ea0a580fd393..000000000000 --- a/packages/rocketchat-reactions/lib/models/Rooms.js +++ /dev/null @@ -1,9 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.setReactionsInLastMessage = function(roomId, lastMessage) { - return this.update({ _id: roomId }, { $set: { lastMessage } }); -}; - -RocketChat.models.Rooms.unsetReactionsInLastMessage = function(roomId) { - return this.update({ _id: roomId }, { $unset: { lastMessage: { reactions: 1 } } }); -}; diff --git a/packages/rocketchat-reactions/package.js b/packages/rocketchat-reactions/package.js index 4979b59fc61a..4e1f4817de61 100644 --- a/packages/rocketchat-reactions/package.js +++ b/packages/rocketchat-reactions/package.js @@ -10,9 +10,13 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:emoji', + 'rocketchat:models', + 'rocketchat:callbacks', 'rocketchat:theme', - 'rocketchat:ui', + 'rocketchat:tooltip', + 'rocketchat:ui-utils', + 'rocketchat:lib', ]); api.addFiles('client/stylesheets/reaction.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-reactions/server/index.js b/packages/rocketchat-reactions/server/index.js index 27b9951a9101..8c5644023dbc 100644 --- a/packages/rocketchat-reactions/server/index.js +++ b/packages/rocketchat-reactions/server/index.js @@ -1,3 +1 @@ -import '../lib/models/Messages'; -import '../lib/models/Rooms'; import './setReaction'; diff --git a/packages/rocketchat-reactions/server/setReaction.js b/packages/rocketchat-reactions/server/setReaction.js index b090cd559b21..d9321b7dfd2e 100644 --- a/packages/rocketchat-reactions/server/setReaction.js +++ b/packages/rocketchat-reactions/server/setReaction.js @@ -1,7 +1,11 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, EmojiCustom, Subscriptions, Rooms } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { emoji } from 'meteor/rocketchat:emoji'; +import { isTheLastMessage } from 'meteor/rocketchat:lib'; import _ from 'underscore'; const removeUserReaction = (message, reaction, username) => { @@ -18,7 +22,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setReaction' }); } - const message = RocketChat.models.Messages.findOneById(messageId); + const message = Messages.findOneById(messageId); if (!message) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setReaction' }); @@ -32,21 +36,21 @@ Meteor.methods({ reaction = `:${ reaction.replace(/:/g, '') }:`; - if (!RocketChat.emoji.list[reaction] && RocketChat.models.EmojiCustom.findByNameOrAlias(reaction).count() === 0) { + if (!emoji.list[reaction] && EmojiCustom.findByNameOrAlias(reaction).count() === 0) { throw new Meteor.Error('error-not-allowed', 'Invalid emoji provided.', { method: 'setReaction' }); } const user = Meteor.user(); if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1 && !room.reactWhenReadOnly) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: room._id, ts: new Date(), msg: TAPi18n.__('You_have_been_muted', {}, user.language), }); return false; - } else if (!RocketChat.models.Subscriptions.findOne({ rid: message.rid })) { + } else if (!Subscriptions.findOne({ rid: message.rid })) { return false; } @@ -64,17 +68,17 @@ Meteor.methods({ if (_.isEmpty(message.reactions)) { delete message.reactions; - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.unsetReactionsInLastMessage(room._id); + if (isTheLastMessage(room, message)) { + Rooms.unsetReactionsInLastMessage(room._id); } - RocketChat.models.Messages.unsetReactions(messageId); - RocketChat.callbacks.run('unsetReaction', messageId, reaction); + Messages.unsetReactions(messageId); + callbacks.run('unsetReaction', messageId, reaction); } else { - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.setReactionsInLastMessage(room._id, message); + if (isTheLastMessage(room, message)) { + Rooms.setReactionsInLastMessage(room._id, message); } - RocketChat.models.Messages.setReactions(messageId, message.reactions); - RocketChat.callbacks.run('setReaction', messageId, reaction); + Messages.setReactions(messageId, message.reactions); + callbacks.run('setReaction', messageId, reaction); } } else { if (!message.reactions) { @@ -86,11 +90,11 @@ Meteor.methods({ }; } message.reactions[reaction].usernames.push(user.username); - if (RocketChat.isTheLastMessage(room, message)) { - RocketChat.models.Rooms.setReactionsInLastMessage(room._id, message); + if (isTheLastMessage(room, message)) { + Rooms.setReactionsInLastMessage(room._id, message); } - RocketChat.models.Messages.setReactions(messageId, message.reactions); - RocketChat.callbacks.run('setReaction', messageId, reaction); + Messages.setReactions(messageId, message.reactions); + callbacks.run('setReaction', messageId, reaction); } msgStream.emit(message.rid, message); From 87a39cfdc1d4a00bde524fe9272ff71675989a86 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 18:11:45 -0200 Subject: [PATCH 056/101] Remove dependency of RC namespace in rc-retention-policy --- .../rocketchat-retention-policy/package.js | 3 ++ .../server/cronPruneMessages.js | 34 ++++++++++--------- .../server/startup/settings.js | 4 +-- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/packages/rocketchat-retention-policy/package.js b/packages/rocketchat-retention-policy/package.js index 252f57cb66c3..e375bcb354bc 100644 --- a/packages/rocketchat-retention-policy/package.js +++ b/packages/rocketchat-retention-policy/package.js @@ -15,7 +15,10 @@ Package.onUse(function(api) { 'mongo', 'ecmascript', 'templating', + 'littledata:synced-cron', 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:settings', ]); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-retention-policy/server/cronPruneMessages.js b/packages/rocketchat-retention-policy/server/cronPruneMessages.js index e570806e7b8d..214f9ea78032 100644 --- a/packages/rocketchat-retention-policy/server/cronPruneMessages.js +++ b/packages/rocketchat-retention-policy/server/cronPruneMessages.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Rooms, Settings } from 'meteor/rocketchat:models'; +import { cleanRoomHistory } from 'meteor/rocketchat:lib'; import { SyncedCron } from 'meteor/littledata:synced-cron'; let types = []; @@ -17,25 +19,25 @@ const toDays = 1000 * 60 * 60 * 24; const gracePeriod = 5000; function job() { const now = new Date(); - const filesOnly = RocketChat.settings.get('RetentionPolicy_FilesOnly'); - const excludePinned = RocketChat.settings.get('RetentionPolicy_ExcludePinned'); + const filesOnly = settings.get('RetentionPolicy_FilesOnly'); + const excludePinned = settings.get('RetentionPolicy_ExcludePinned'); // get all rooms with default values types.forEach((type) => { const maxAge = maxTimes[type] || 0; const latest = new Date(now.getTime() - maxAge * toDays); - RocketChat.models.Rooms.find({ + Rooms.find({ t: type, _updatedAt: { $gte: lastPrune }, $or: [{ 'retention.enabled': { $eq: true } }, { 'retention.enabled': { $exists: false } }], 'retention.overrideGlobal': { $ne: true }, }).forEach(({ _id: rid }) => { - RocketChat.cleanRoomHistory({ rid, latest, oldest, filesOnly, excludePinned }); + cleanRoomHistory({ rid, latest, oldest, filesOnly, excludePinned }); }); }); - RocketChat.models.Rooms.find({ + Rooms.find({ 'retention.enabled': { $eq: true }, 'retention.overrideGlobal': { $eq: true }, 'retention.maxAge': { $gte: 0 }, @@ -43,7 +45,7 @@ function job() { }).forEach((room) => { const { maxAge = 30, filesOnly, excludePinned } = room.retention; const latest = new Date(now.getTime() - maxAge * toDays); - RocketChat.cleanRoomHistory({ rid: room._id, latest, oldest, filesOnly, excludePinned }); + cleanRoomHistory({ rid: room._id, latest, oldest, filesOnly, excludePinned }); }); lastPrune = new Date(now.getTime() - gracePeriod); } @@ -77,31 +79,31 @@ function deployCron(precision) { function reloadPolicy() { types = []; - if (RocketChat.settings.get('RetentionPolicy_Enabled')) { - if (RocketChat.settings.get('RetentionPolicy_AppliesToChannels')) { + if (settings.get('RetentionPolicy_Enabled')) { + if (settings.get('RetentionPolicy_AppliesToChannels')) { types.push('c'); } - if (RocketChat.settings.get('RetentionPolicy_AppliesToGroups')) { + if (settings.get('RetentionPolicy_AppliesToGroups')) { types.push('p'); } - if (RocketChat.settings.get('RetentionPolicy_AppliesToDMs')) { + if (settings.get('RetentionPolicy_AppliesToDMs')) { types.push('d'); } - maxTimes.c = RocketChat.settings.get('RetentionPolicy_MaxAge_Channels'); - maxTimes.p = RocketChat.settings.get('RetentionPolicy_MaxAge_Groups'); - maxTimes.d = RocketChat.settings.get('RetentionPolicy_MaxAge_DMs'); + maxTimes.c = settings.get('RetentionPolicy_MaxAge_Channels'); + maxTimes.p = settings.get('RetentionPolicy_MaxAge_Groups'); + maxTimes.d = settings.get('RetentionPolicy_MaxAge_DMs'); - return deployCron(RocketChat.settings.get('RetentionPolicy_Precision')); + return deployCron(settings.get('RetentionPolicy_Precision')); } return SyncedCron.remove(pruneCronName); } Meteor.startup(function() { Meteor.defer(function() { - RocketChat.models.Settings.find({ + Settings.find({ _id: { $in: [ 'RetentionPolicy_Enabled', diff --git a/packages/rocketchat-retention-policy/server/startup/settings.js b/packages/rocketchat-retention-policy/server/startup/settings.js index de3155527adc..b750c2e9624d 100644 --- a/packages/rocketchat-retention-policy/server/startup/settings.js +++ b/packages/rocketchat-retention-policy/server/startup/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('RetentionPolicy', function() { +settings.addGroup('RetentionPolicy', function() { this.add('RetentionPolicy_Enabled', false, { type: 'boolean', From 923b584d9891f03c6c3aa988c786475b7b6f3182 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 18:20:50 -0200 Subject: [PATCH 057/101] Remove dependency of RC namespace in rc-earch --- .../rocketchat-search/client/provider/result.js | 5 ++--- packages/rocketchat-search/package.js | 5 ++++- .../rocketchat-search/server/events/events.js | 15 ++++++++------- .../rocketchat-search/server/model/provider.js | 4 ++-- .../server/service/providerService.js | 8 ++++---- .../server/service/validationService.js | 4 ++-- 6 files changed, 22 insertions(+), 19 deletions(-) diff --git a/packages/rocketchat-search/client/provider/result.js b/packages/rocketchat-search/client/provider/result.js index cfbbe8a146a8..f62e1e49eedc 100644 --- a/packages/rocketchat-search/client/provider/result.js +++ b/packages/rocketchat-search/client/provider/result.js @@ -3,12 +3,11 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { RoomHistoryManager } from 'meteor/rocketchat:ui'; +import { MessageAction, RoomHistoryManager } from 'meteor/rocketchat:ui-utils'; import _ from 'underscore'; Meteor.startup(function() { - RocketChat.MessageAction.addButton({ + MessageAction.addButton({ id: 'jump-to-search-message', icon: 'jump', label: 'Jump_to_message', diff --git a/packages/rocketchat-search/package.js b/packages/rocketchat-search/package.js index d5004dfd2607..30a09b9ab8a7 100644 --- a/packages/rocketchat-search/package.js +++ b/packages/rocketchat-search/package.js @@ -9,7 +9,10 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'templating', - 'rocketchat:lib', + 'rocketchat:ui-utils', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:settings', 'rocketchat:logger', 'kadira:flow-router', ]); diff --git a/packages/rocketchat-search/server/events/events.js b/packages/rocketchat-search/server/events/events.js index e5b7b0d68865..a4b6ce1034d9 100644 --- a/packages/rocketchat-search/server/events/events.js +++ b/packages/rocketchat-search/server/events/events.js @@ -1,4 +1,5 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Users, Rooms } from 'meteor/rocketchat:models'; import { searchProviderService } from '../service/providerService'; import SearchLogger from '../logger/logger'; @@ -22,11 +23,11 @@ const eventService = new EventService(); /** * Listen to message changes via Hooks */ -RocketChat.callbacks.add('afterSaveMessage', function(m) { +callbacks.add('afterSaveMessage', function(m) { eventService.promoteEvent('message.save', m._id, m); }); -RocketChat.callbacks.add('afterDeleteMessage', function(m) { +callbacks.add('afterDeleteMessage', function(m) { eventService.promoteEvent('message.delete', m._id); }); @@ -35,11 +36,11 @@ RocketChat.callbacks.add('afterDeleteMessage', function(m) { */ -RocketChat.models.Users.on('change', ({ clientAction, id, data }) => { +Users.on('change', ({ clientAction, id, data }) => { switch (clientAction) { case 'updated': case 'inserted': - const user = data || RocketChat.models.Users.findOneById(id); + const user = data || Users.findOneById(id); eventService.promoteEvent('user.save', id, user); break; @@ -49,11 +50,11 @@ RocketChat.models.Users.on('change', ({ clientAction, id, data }) => { } }); -RocketChat.models.Rooms.on('change', ({ clientAction, id, data }) => { +Rooms.on('change', ({ clientAction, id, data }) => { switch (clientAction) { case 'updated': case 'inserted': - const room = data || RocketChat.models.Rooms.findOneById(id); + const room = data || Rooms.findOneById(id); eventService.promoteEvent('room.save', id, room); break; diff --git a/packages/rocketchat-search/server/model/provider.js b/packages/rocketchat-search/server/model/provider.js index 2e7768ac58ce..21112d1f495d 100644 --- a/packages/rocketchat-search/server/model/provider.js +++ b/packages/rocketchat-search/server/model/provider.js @@ -1,6 +1,6 @@ /* eslint no-unused-vars: [2, { "args": "none" }]*/ import SearchLogger from '../logger/logger'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; /** * Setting Object in order to manage settings loading for providers and admin ui display @@ -28,7 +28,7 @@ class Setting { } load() { - this._value = RocketChat.settings.get(this.id); + this._value = settings.get(this.id); if (this._value === undefined) { this._value = this.defaultValue; } } diff --git a/packages/rocketchat-search/server/service/providerService.js b/packages/rocketchat-search/server/service/providerService.js index 64590845ac15..50e6c3cb0c5c 100644 --- a/packages/rocketchat-search/server/service/providerService.js +++ b/packages/rocketchat-search/server/service/providerService.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import _ from 'underscore'; import { validationService } from '../service/validationService'; import SearchLogger from '../logger/logger'; @@ -78,7 +78,7 @@ class SearchProviderService { const { providers } = this; // add settings for admininistration - RocketChat.settings.addGroup('Search', function() { + settings.addGroup('Search', function() { const self = this; @@ -115,7 +115,7 @@ class SearchProviderService { // add listener to react on setting changes const configProvider = _.debounce(Meteor.bindEnvironment(() => { - const providerId = RocketChat.settings.get('Search.Provider'); + const providerId = settings.get('Search.Provider'); if (providerId) { this.use(providerId);// TODO do something with success and errors @@ -123,7 +123,7 @@ class SearchProviderService { }), 1000); - RocketChat.settings.get(/^Search\./, configProvider); + settings.get(/^Search\./, configProvider); } } diff --git a/packages/rocketchat-search/server/service/validationService.js b/packages/rocketchat-search/server/service/validationService.js index bd9b2ba4fa6f..77a04e8fc99f 100644 --- a/packages/rocketchat-search/server/service/validationService.js +++ b/packages/rocketchat-search/server/service/validationService.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import SearchLogger from '../logger/logger'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; class ValidationService { constructor() {} @@ -22,7 +22,7 @@ class ValidationService { const getUsername = (uid) => { if (!userCache.hasOwnProperty(uid)) { try { - userCache[uid] = RocketChat.models.Users.findById(uid).fetch()[0].username; + userCache[uid] = Users.findById(uid).fetch()[0].username; } catch (e) { userCache[uid] = undefined; } From b2db16910842a5d38cfcabf4159e95c11e24225e Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 18:36:03 -0200 Subject: [PATCH 058/101] Remove dependency of RC namespace in rc-setup-wizard --- .../rocketchat-setup-wizard/client/final.js | 14 ++++++----- .../client/setupWizard.js | 25 +++++++++++-------- packages/rocketchat-setup-wizard/package.js | 4 +++ .../server/getSetupWizardParameters.js | 7 +++--- 4 files changed, 30 insertions(+), 20 deletions(-) diff --git a/packages/rocketchat-setup-wizard/client/final.js b/packages/rocketchat-setup-wizard/client/final.js index 05b0b3d791a6..ac52acd4e1c4 100644 --- a/packages/rocketchat-setup-wizard/client/final.js +++ b/packages/rocketchat-setup-wizard/client/final.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Users } from 'meteor/rocketchat:models'; +import { hasRole } from 'meteor/rocketchat:authorization'; Template.setupWizardFinal.onCreated(function() { const isSetupWizardDone = localStorage.getItem('wizardFinal'); @@ -10,14 +12,14 @@ Template.setupWizardFinal.onCreated(function() { } this.autorun((c) => { - const showSetupWizard = RocketChat.settings.get('Show_Setup_Wizard'); + const showSetupWizard = settings.get('Show_Setup_Wizard'); if (!showSetupWizard) { // Setup Wizard state is not defined yet return; } const userId = Meteor.userId(); - const user = userId && RocketChat.models.Users.findOne(userId, { fields: { status: true } }); + const user = userId && Users.findOne(userId, { fields: { status: true } }); if (userId && (!user || !user.status)) { // User and its status are not defined yet return; @@ -27,7 +29,7 @@ Template.setupWizardFinal.onCreated(function() { const isComplete = showSetupWizard === 'completed'; const noUserLoggedInAndIsNotPending = !userId && showSetupWizard !== 'pending'; - const userIsLoggedButIsNotAdmin = userId && !RocketChat.authz.hasRole(userId, 'admin'); + const userIsLoggedButIsNotAdmin = userId && !hasRole(userId, 'admin'); if (isComplete || noUserLoggedInAndIsNotPending || userIsLoggedButIsNotAdmin) { FlowRouter.go('home'); return; @@ -41,7 +43,7 @@ Template.setupWizardFinal.onRendered(function() { Template.setupWizardFinal.events({ 'click .js-finish'() { - RocketChat.settings.set('Show_Setup_Wizard', 'completed', function() { + settings.set('Show_Setup_Wizard', 'completed', function() { localStorage.removeItem('wizard'); localStorage.removeItem('wizardFinal'); FlowRouter.go('home'); @@ -51,6 +53,6 @@ Template.setupWizardFinal.events({ Template.setupWizardFinal.helpers({ siteUrl() { - return RocketChat.settings.get('Site_Url'); + return settings.get('Site_Url'); }, }); diff --git a/packages/rocketchat-setup-wizard/client/setupWizard.js b/packages/rocketchat-setup-wizard/client/setupWizard.js index d79dd8288f50..bf1092de7218 100644 --- a/packages/rocketchat-setup-wizard/client/setupWizard.js +++ b/packages/rocketchat-setup-wizard/client/setupWizard.js @@ -5,19 +5,22 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; 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 { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { Users } from 'meteor/rocketchat:models'; +import { t, handleError } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; const cannotSetup = () => { - const showSetupWizard = RocketChat.settings.get('Show_Setup_Wizard'); + const showSetupWizard = settings.get('Show_Setup_Wizard'); if (!showSetupWizard) { // Setup Wizard state is not defined yet return; } const userId = Meteor.userId(); - const user = userId && RocketChat.models.Users.findOne(userId, { fields: { status: true } }); + const user = userId && Users.findOne(userId, { fields: { status: true } }); if (userId && (!user || !user.status)) { // User and its status are not defined yet return; @@ -25,7 +28,7 @@ const cannotSetup = () => { const isComplete = showSetupWizard === 'completed'; const noUserLoggedInAndIsNotPending = !userId && showSetupWizard !== 'pending'; - const userIsLoggedButIsNotAdmin = userId && !RocketChat.authz.hasRole(userId, 'admin'); + const userIsLoggedButIsNotAdmin = userId && !hasRole(userId, 'admin'); return isComplete || noUserLoggedInAndIsNotPending || userIsLoggedButIsNotAdmin; }; @@ -41,7 +44,7 @@ const registerAdminUser = (state, callback) => { return handleError(error); } - RocketChat.callbacks.run('userRegistered'); + callbacks.run('userRegistered'); Meteor.loginWithPassword(registrationData.email, registrationData.pass, (error) => { if (error) { if (error.error === 'error-invalid-email') { @@ -58,7 +61,7 @@ const registerAdminUser = (state, callback) => { return handleError(error); } - RocketChat.callbacks.run('usernameSet'); + callbacks.run('usernameSet'); callback && callback(); }); }); @@ -66,7 +69,7 @@ const registerAdminUser = (state, callback) => { }; const persistSettings = (state, callback) => { - const settings = Object.entries(state) + const setupSettings = Object.entries(state) .filter(([key]) => !/registration-|registerServer|optIn|currentStep|invalidUsername|invalidEmail/.test(key)) .map(([_id, value]) => ({ _id, value })) .concat([ @@ -88,7 +91,7 @@ const persistSettings = (state, callback) => { }, ]); - RocketChat.settings.batchSet(settings, (error) => { + settings.batchSet(setupSettings, (error) => { if (error) { return handleError(error); } @@ -164,7 +167,7 @@ Template.setupWizard.events({ switch (t.state.get('currentStep')) { case 1: { const usernameValue = t.state.get('registration-username'); - const usernameRegex = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const usernameRegex = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); t.state.set('invalidUsername', !usernameRegex.test(usernameValue)); const emailValue = t.state.get('registration-email'); @@ -256,7 +259,7 @@ Template.setupWizard.helpers({ formLoadStateClass() { switch (Template.instance().state.get('currentStep')) { case 1: - return RocketChat.settings.get('Show_Setup_Wizard') === 'pending' && 'setup-wizard-forms__box--loaded'; + return settings.get('Show_Setup_Wizard') === 'pending' && 'setup-wizard-forms__box--loaded'; case 2: case 3: return Template.instance().wizardSettings.get().length > 0 && 'setup-wizard-forms__box--loaded'; diff --git a/packages/rocketchat-setup-wizard/package.js b/packages/rocketchat-setup-wizard/package.js index 69472c57b0ee..fc91ee48a236 100644 --- a/packages/rocketchat-setup-wizard/package.js +++ b/packages/rocketchat-setup-wizard/package.js @@ -11,6 +11,10 @@ Package.onUse(function(api) { 'templating', 'rocketchat:utils', 'rocketchat:theme', + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:models', + 'rocketchat:authorization', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-setup-wizard/server/getSetupWizardParameters.js b/packages/rocketchat-setup-wizard/server/getSetupWizardParameters.js index 78a66c00c433..deb38d39b227 100644 --- a/packages/rocketchat-setup-wizard/server/getSetupWizardParameters.js +++ b/packages/rocketchat-setup-wizard/server/getSetupWizardParameters.js @@ -1,16 +1,17 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasRole } from 'meteor/rocketchat:authorization'; +import { Settings } from 'meteor/rocketchat:models'; Meteor.methods({ getSetupWizardParameters() { const userId = Meteor.userId(); - const userHasAdminRole = userId && RocketChat.authz.hasRole(userId, 'admin'); + const userHasAdminRole = userId && hasRole(userId, 'admin'); if (!userHasAdminRole) { throw new Meteor.Error('error-not-allowed'); } - const settings = RocketChat.models.Settings.findSetupWizardSettings().fetch(); + const settings = Settings.findSetupWizardSettings().fetch(); const allowStandaloneServer = process.env.DEPLOY_PLATFORM !== 'rocket-cloud'; return { From b7174f80213a733df8919817197e5d36457398cf Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 18:55:25 -0200 Subject: [PATCH 059/101] Remove dependency of RC namespace in rc-slackbridge --- .../client/slackbridge_import.client.js | 9 +- packages/rocketchat-slackbridge/package.js | 6 +- .../server/RocketAdapter.js | 69 ++++++++------- .../server/SlackAdapter.js | 85 +++++++++++-------- .../rocketchat-slackbridge/server/settings.js | 4 +- .../server/slackbridge.js | 18 ++-- .../server/slackbridge_import.server.js | 10 ++- 7 files changed, 111 insertions(+), 90 deletions(-) diff --git a/packages/rocketchat-slackbridge/client/slackbridge_import.client.js b/packages/rocketchat-slackbridge/client/slackbridge_import.client.js index 8655bfb83d57..6cdcc0967f3a 100644 --- a/packages/rocketchat-slackbridge/client/slackbridge_import.client.js +++ b/packages/rocketchat-slackbridge/client/slackbridge_import.client.js @@ -1,11 +1,12 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.settings.onload('SlackBridge_Enabled', (key, value) => { +settings.onload('SlackBridge_Enabled', (key, value) => { if (value) { - RocketChat.slashCommands.add('slackbridge-import', null, { + slashCommands.add('slackbridge-import', null, { description: 'Import_old_messages_from_slackbridge', }); } else { - delete RocketChat.slashCommands.commands['slackbridge-import']; + delete slashCommands.commands['slackbridge-import']; } }); diff --git a/packages/rocketchat-slackbridge/package.js b/packages/rocketchat-slackbridge/package.js index 027bd3ff65b0..95a42f6f7d55 100644 --- a/packages/rocketchat-slackbridge/package.js +++ b/packages/rocketchat-slackbridge/package.js @@ -9,8 +9,12 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', 'rocketchat:utils', + 'rocketchat:lib', + 'rocketchat:callbacks', + 'rocketchat:channel-settings', + 'rocketchat:models', 'rocketchat:logger', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-slackbridge/server/RocketAdapter.js b/packages/rocketchat-slackbridge/server/RocketAdapter.js index f75886b9f8eb..ac3f3d0c1144 100644 --- a/packages/rocketchat-slackbridge/server/RocketAdapter.js +++ b/packages/rocketchat-slackbridge/server/RocketAdapter.js @@ -2,7 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { settings } from 'meteor/rocketchat:settings'; +import { Messages, Rooms, Users } from 'meteor/rocketchat:models'; +import { createRoom, sendMessage, setUserAvatar } from 'meteor/rocketchat:lib'; import { logger } from './logger'; import _ from 'underscore'; @@ -30,18 +33,18 @@ export default class RocketAdapter { registerForEvents() { logger.rocket.debug('Register for events'); - RocketChat.callbacks.add('afterSaveMessage', this.onMessage.bind(this), RocketChat.callbacks.priority.LOW, 'SlackBridge_Out'); - RocketChat.callbacks.add('afterDeleteMessage', this.onMessageDelete.bind(this), RocketChat.callbacks.priority.LOW, 'SlackBridge_Delete'); - RocketChat.callbacks.add('setReaction', this.onSetReaction.bind(this), RocketChat.callbacks.priority.LOW, 'SlackBridge_SetReaction'); - RocketChat.callbacks.add('unsetReaction', this.onUnSetReaction.bind(this), RocketChat.callbacks.priority.LOW, 'SlackBridge_UnSetReaction'); + callbacks.add('afterSaveMessage', this.onMessage.bind(this), callbacks.priority.LOW, 'SlackBridge_Out'); + callbacks.add('afterDeleteMessage', this.onMessageDelete.bind(this), callbacks.priority.LOW, 'SlackBridge_Delete'); + callbacks.add('setReaction', this.onSetReaction.bind(this), callbacks.priority.LOW, 'SlackBridge_SetReaction'); + callbacks.add('unsetReaction', this.onUnSetReaction.bind(this), callbacks.priority.LOW, 'SlackBridge_UnSetReaction'); } unregisterForEvents() { logger.rocket.debug('Unregister for events'); - RocketChat.callbacks.remove('afterSaveMessage', 'SlackBridge_Out'); - RocketChat.callbacks.remove('afterDeleteMessage', 'SlackBridge_Delete'); - RocketChat.callbacks.remove('setReaction', 'SlackBridge_SetReaction'); - RocketChat.callbacks.remove('unsetReaction', 'SlackBridge_UnSetReaction'); + callbacks.remove('afterSaveMessage', 'SlackBridge_Out'); + callbacks.remove('afterDeleteMessage', 'SlackBridge_Delete'); + callbacks.remove('setReaction', 'SlackBridge_SetReaction'); + callbacks.remove('unsetReaction', 'SlackBridge_UnSetReaction'); } onMessageDelete(rocketMessageDeleted) { @@ -70,7 +73,7 @@ export default class RocketAdapter { // This was a Slack reaction, we don't need to tell Slack about it return; } - const rocketMsg = RocketChat.models.Messages.findOneById(rocketMsgID); + const rocketMsg = Messages.findOneById(rocketMsgID); if (rocketMsg) { const slackChannel = this.slack.getSlackChannel(rocketMsg.rid); if (null != slackChannel) { @@ -97,7 +100,7 @@ export default class RocketAdapter { return; } - const rocketMsg = RocketChat.models.Messages.findOneById(rocketMsgID); + const rocketMsg = Messages.findOneById(rocketMsgID); if (rocketMsg) { const slackChannel = this.slack.getSlackChannel(rocketMsg.rid); if (null != slackChannel) { @@ -145,11 +148,11 @@ export default class RocketAdapter { processSendMessage(rocketMessage) { // Since we got this message, SlackBridge_Out_Enabled is true - if (RocketChat.settings.get('SlackBridge_Out_All') === true) { + if (settings.get('SlackBridge_Out_All') === true) { this.slack.postMessage(this.slack.getSlackChannel(rocketMessage.rid), rocketMessage); } else { // They want to limit to certain groups - const outSlackChannels = _.pluck(RocketChat.settings.get('SlackBridge_Out_Channels'), '_id') || []; + const outSlackChannels = _.pluck(settings.get('SlackBridge_Out_Channels'), '_id') || []; // logger.rocket.debug('Out SlackChannels: ', outSlackChannels); if (outSlackChannels.indexOf(rocketMessage.rid) !== -1) { this.slack.postMessage(this.slack.getSlackChannel(rocketMessage.rid), rocketMessage); @@ -179,7 +182,7 @@ export default class RocketAdapter { } processFileShare(rocketMessage) { - if (! RocketChat.settings.get('SlackBridge_FileUpload_Enabled')) { + if (! settings.get('SlackBridge_FileUpload_Enabled')) { return; } @@ -229,7 +232,7 @@ export default class RocketAdapter { } findChannel(slackChannelId) { - return RocketChat.models.Rooms.findOneByImportId(slackChannelId); + return Rooms.findOneByImportId(slackChannelId); } addChannel(slackChannelID, hasRetried = false) { @@ -244,12 +247,12 @@ export default class RocketAdapter { } if (slackResults && slackResults.data && slackResults.data.ok === true) { const rocketChannelData = isGroup ? slackResults.data.group : slackResults.data.channel; - const existingRocketRoom = RocketChat.models.Rooms.findOneByName(rocketChannelData.name); + const existingRocketRoom = Rooms.findOneByName(rocketChannelData.name); // If the room exists, make sure we have its id in importIds if (existingRocketRoom || rocketChannelData.is_general) { rocketChannelData.rocketId = rocketChannelData.is_general ? 'GENERAL' : existingRocketRoom._id; - RocketChat.models.Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); + Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); } else { const rocketUsers = []; for (const member of rocketChannelData.members) { @@ -267,7 +270,7 @@ export default class RocketAdapter { } try { - const rocketChannel = RocketChat.createRoom(isGroup ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); + const rocketChannel = createRoom(isGroup ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); rocketChannelData.rocketId = rocketChannel.rid; } catch (e) { if (!hasRetried) { @@ -291,17 +294,17 @@ export default class RocketAdapter { if (!_.isEmpty(rocketChannelData.purpose && rocketChannelData.purpose.value) && rocketChannelData.purpose.last_set > lastSetTopic) { roomUpdate.topic = rocketChannelData.purpose.value; } - RocketChat.models.Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); + Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); } - return RocketChat.models.Rooms.findOneById(rocketChannelData.rocketId); + return Rooms.findOneById(rocketChannelData.rocketId); } logger.rocket.debug('Channel not added'); return; } findUser(slackUserID) { - const rocketUser = RocketChat.models.Users.findOneByImportId(slackUserID); + const rocketUser = Users.findOneByImportId(slackUserID); if (rocketUser && !this.userTags[slackUserID]) { this.userTags[slackUserID] = { slack: `<@${ slackUserID }>`, rocket: `@${ rocketUser.username }` }; } @@ -317,9 +320,9 @@ export default class RocketAdapter { const email = (rocketUserData.profile && rocketUserData.profile.email) || ''; let existingRocketUser; if (!isBot) { - existingRocketUser = RocketChat.models.Users.findOneByEmailAddress(email) || RocketChat.models.Users.findOneByUsername(rocketUserData.name); + existingRocketUser = Users.findOneByEmailAddress(email) || Users.findOneByUsername(rocketUserData.name); } else { - existingRocketUser = RocketChat.models.Users.findOneByUsername(rocketUserData.name); + existingRocketUser = Users.findOneByUsername(rocketUserData.name); } if (existingRocketUser) { @@ -354,9 +357,9 @@ export default class RocketAdapter { userUpdate['services.resume.loginTokens'] = []; } - RocketChat.models.Users.update({ _id: rocketUserData.rocketId }, { $set: userUpdate }); + Users.update({ _id: rocketUserData.rocketId }, { $set: userUpdate }); - const user = RocketChat.models.Users.findOneById(rocketUserData.rocketId); + const user = Users.findOneById(rocketUserData.rocketId); let url = null; if (rocketUserData.profile) { @@ -368,7 +371,7 @@ export default class RocketAdapter { } if (url) { try { - RocketChat.setUserAvatar(user, url, null, 'url'); + setUserAvatar(user, url, null, 'url'); } catch (error) { logger.rocket.debug('Error setting user avatar', error.message); } @@ -379,18 +382,18 @@ export default class RocketAdapter { if (isBot && rocketUserData.profile && rocketUserData.profile.bot_id) { importIds.push(rocketUserData.profile.bot_id); } - RocketChat.models.Users.addImportIds(rocketUserData.rocketId, importIds); + Users.addImportIds(rocketUserData.rocketId, importIds); if (!this.userTags[slackUserID]) { this.userTags[slackUserID] = { slack: `<@${ slackUserID }>`, rocket: `@${ rocketUserData.name }` }; } - return RocketChat.models.Users.findOneById(rocketUserData.rocketId); + return Users.findOneById(rocketUserData.rocketId); } logger.rocket.debug('User not added'); return; } addAliasToMsg(rocketUserName, rocketMsgObj) { - const aliasFormat = RocketChat.settings.get('SlackBridge_AliasFormat'); + const aliasFormat = settings.get('SlackBridge_AliasFormat'); if (aliasFormat) { const alias = this.util.format(aliasFormat, rocketUserName); @@ -427,7 +430,7 @@ export default class RocketAdapter { rocketMsgObj.editedAt = new Date(parseInt(slackMessage.edited.ts.split('.')[0]) * 1000); } if (slackMessage.subtype === 'bot_message') { - rocketUser = RocketChat.models.Users.findOneById('rocket.cat', { fields: { username: 1 } }); + rocketUser = Users.findOneById('rocket.cat', { fields: { username: 1 } }); } if (slackMessage.pinned_to && slackMessage.pinned_to.indexOf(slackMessage.channel) !== -1) { @@ -437,13 +440,13 @@ export default class RocketAdapter { } if (slackMessage.subtype === 'bot_message') { Meteor.setTimeout(() => { - if (slackMessage.bot_id && slackMessage.ts && !RocketChat.models.Messages.findOneBySlackBotIdAndSlackTs(slackMessage.bot_id, slackMessage.ts)) { - RocketChat.sendMessage(rocketUser, rocketMsgObj, rocketChannel, true); + if (slackMessage.bot_id && slackMessage.ts && !Messages.findOneBySlackBotIdAndSlackTs(slackMessage.bot_id, slackMessage.ts)) { + sendMessage(rocketUser, rocketMsgObj, rocketChannel, true); } }, 500); } else { logger.rocket.debug('Send message to Rocket.Chat'); - RocketChat.sendMessage(rocketUser, rocketMsgObj, rocketChannel, true); + sendMessage(rocketUser, rocketMsgObj, rocketChannel, true); } } } diff --git a/packages/rocketchat-slackbridge/server/SlackAdapter.js b/packages/rocketchat-slackbridge/server/SlackAdapter.js index 7889b8277926..dd20dc7178dd 100644 --- a/packages/rocketchat-slackbridge/server/SlackAdapter.js +++ b/packages/rocketchat-slackbridge/server/SlackAdapter.js @@ -1,7 +1,18 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { getAvatarUrlFromUsername } from 'meteor/rocketchat:utils'; +import { Messages, Rooms, Users } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { + deleteMessage, + updateMessage, + addUserToRoom, + removeUserFromRoom, + archiveRoom, + unarchiveRoom, + sendMessage, +} from 'meteor/rocketchat:lib'; +import { saveRoomName, saveRoomTopic } from 'meteor/rocketchat:channel-settings'; import { FileUpload } from 'meteor/rocketchat:file-upload'; import { logger } from './logger'; import _ from 'underscore'; @@ -326,12 +337,12 @@ export default class SlackAdapter { } const rocketUser = this.rocket.getUser(slackReactionMsg.user); // Lets find our Rocket originated message - let rocketMsg = RocketChat.models.Messages.findOneBySlackTs(slackReactionMsg.item.ts); + let rocketMsg = Messages.findOneBySlackTs(slackReactionMsg.item.ts); if (!rocketMsg) { // Must have originated from Slack const rocketID = this.rocket.createRocketID(slackReactionMsg.item.channel, slackReactionMsg.item.ts); - rocketMsg = RocketChat.models.Messages.findOneById(rocketID); + rocketMsg = Messages.findOneById(rocketID); } if (rocketMsg && rocketUser) { @@ -375,12 +386,12 @@ export default class SlackAdapter { } // Lets find our Rocket originated message - let rocketMsg = RocketChat.models.Messages.findOneBySlackTs(slackReactionMsg.item.ts); + let rocketMsg = Messages.findOneBySlackTs(slackReactionMsg.item.ts); if (!rocketMsg) { // Must have originated from Slack const rocketID = this.rocket.createRocketID(slackReactionMsg.item.channel, slackReactionMsg.item.ts); - rocketMsg = RocketChat.models.Messages.findOneById(rocketID); + rocketMsg = Messages.findOneById(rocketID); } if (rocketMsg && rocketUser) { @@ -524,7 +535,7 @@ export default class SlackAdapter { const response = HTTP.get('https://slack.com/api/channels.list', { params: { token: this.apiToken } }); if (response && response.data && _.isArray(response.data.channels) && response.data.channels.length > 0) { for (const slackChannel of response.data.channels) { - const rocketchat_room = RocketChat.models.Rooms.findOneByName(slackChannel.name, { fields: { _id: 1 } }); + const rocketchat_room = Rooms.findOneByName(slackChannel.name, { fields: { _id: 1 } }); if (rocketchat_room) { if (slackChannel.is_member) { this.addSlackChannel(rocketchat_room._id, slackChannel.id); @@ -538,7 +549,7 @@ export default class SlackAdapter { const response = HTTP.get('https://slack.com/api/groups.list', { params: { token: this.apiToken } }); if (response && response.data && _.isArray(response.data.groups) && response.data.groups.length > 0) { for (const slackGroup of response.data.groups) { - const rocketchat_room = RocketChat.models.Rooms.findOneByName(slackGroup.name, { fields: { _id: 1 } }); + const rocketchat_room = Rooms.findOneByName(slackGroup.name, { fields: { _id: 1 } }); if (rocketchat_room) { if (slackGroup.is_member) { this.addSlackChannel(rocketchat_room._id, slackGroup.id); @@ -632,7 +643,7 @@ export default class SlackAdapter { logger.slack.debug('Post Message To Slack', data); const postResult = HTTP.post('https://slack.com/api/chat.postMessage', { params: data }); if (postResult.statusCode === 200 && postResult.data && postResult.data.message && postResult.data.message.bot_id && postResult.data.message.ts) { - RocketChat.models.Messages.setSlackBotIdAndSlackTs(rocketMessage._id, postResult.data.message.bot_id, postResult.data.message.ts); + Messages.setSlackBotIdAndSlackTs(rocketMessage._id, postResult.data.message.bot_id, postResult.data.message.ts); logger.slack.debug(`RocketMsgID=${ rocketMessage._id } SlackMsgID=${ postResult.data.message.ts } SlackBotID=${ postResult.data.message.bot_id }`); } } @@ -667,7 +678,7 @@ export default class SlackAdapter { } processFileShare(slackMessage) { - if (! RocketChat.settings.get('SlackBridge_FileUpload_Enabled')) { + if (! settings.get('SlackBridge_FileUpload_Enabled')) { return; } @@ -702,21 +713,21 @@ export default class SlackAdapter { processMessageDeleted(slackMessage) { if (slackMessage.previous_message) { const rocketChannel = this.rocket.getChannel(slackMessage); - const rocketUser = RocketChat.models.Users.findOneById('rocket.cat', { fields: { username: 1 } }); + const rocketUser = Users.findOneById('rocket.cat', { fields: { username: 1 } }); if (rocketChannel && rocketUser) { // Find the Rocket message to delete - let rocketMsgObj = RocketChat.models.Messages + let rocketMsgObj = Messages .findOneBySlackBotIdAndSlackTs(slackMessage.previous_message.bot_id, slackMessage.previous_message.ts); if (!rocketMsgObj) { // Must have been a Slack originated msg const _id = this.rocket.createRocketID(slackMessage.channel, slackMessage.previous_message.ts); - rocketMsgObj = RocketChat.models.Messages.findOneById(_id); + rocketMsgObj = Messages.findOneById(_id); } if (rocketMsgObj) { - RocketChat.deleteMessage(rocketMsgObj, rocketUser); + deleteMessage(rocketMsgObj, rocketUser); logger.slack.debug('Rocket message deleted by Slack'); } } @@ -728,7 +739,7 @@ export default class SlackAdapter { */ processMessageChanged(slackMessage) { if (slackMessage.previous_message) { - const currentMsg = RocketChat.models.Messages.findOneById(this.rocket.createRocketID(slackMessage.channel, slackMessage.message.ts)); + const currentMsg = Messages.findOneById(this.rocket.createRocketID(slackMessage.channel, slackMessage.message.ts)); // Only process this change, if its an actual update (not just Slack repeating back our Rocket original change) if (currentMsg && (slackMessage.message.text !== currentMsg.msg)) { @@ -743,7 +754,7 @@ export default class SlackAdapter { updatedBySlack: true, // We don't want to notify slack about this change since Slack initiated it }; - RocketChat.updateMessage(rocketMsgObj, rocketUser); + updateMessage(rocketMsgObj, rocketUser); logger.slack.debug('Rocket message updated by Slack'); } } @@ -756,7 +767,7 @@ export default class SlackAdapter { const rocketChannel = this.rocket.getChannel(slackMessage); let rocketUser = null; if (slackMessage.subtype === 'bot_message') { - rocketUser = RocketChat.models.Users.findOneById('rocket.cat', { fields: { username: 1 } }); + rocketUser = Users.findOneById('rocket.cat', { fields: { username: 1 } }); } else { rocketUser = slackMessage.user ? this.rocket.findUser(slackMessage.user) || this.rocket.addUser(slackMessage.user) : null; } @@ -783,7 +794,7 @@ export default class SlackAdapter { } processBotMessage(rocketChannel, slackMessage) { - const excludeBotNames = RocketChat.settings.get('SlackBridge_ExcludeBotnames'); + const excludeBotNames = settings.get('SlackBridge_ExcludeBotnames'); if (slackMessage.username !== undefined && excludeBotNames && slackMessage.username.match(excludeBotNames)) { return; } @@ -810,9 +821,9 @@ export default class SlackAdapter { processChannelJoinMessage(rocketChannel, rocketUser, slackMessage, isImporting) { if (isImporting) { - RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rocketChannel._id, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); + Messages.createUserJoinWithRoomIdAndUser(rocketChannel._id, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); } else { - RocketChat.addUserToRoom(rocketChannel._id, rocketUser); + addUserToRoom(rocketChannel._id, rocketUser); } } @@ -820,7 +831,7 @@ export default class SlackAdapter { if (slackMessage.inviter) { const inviter = slackMessage.inviter ? this.rocket.findUser(slackMessage.inviter) || this.rocket.addUser(slackMessage.inviter) : null; if (isImporting) { - RocketChat.models.Messages.createUserAddedWithRoomIdAndUser(rocketChannel._id, rocketUser, { + Messages.createUserAddedWithRoomIdAndUser(rocketChannel._id, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), u: { _id: inviter._id, @@ -829,43 +840,43 @@ export default class SlackAdapter { imported: 'slackbridge', }); } else { - RocketChat.addUserToRoom(rocketChannel._id, rocketUser, inviter); + addUserToRoom(rocketChannel._id, rocketUser, inviter); } } } processLeaveMessage(rocketChannel, rocketUser, slackMessage, isImporting) { if (isImporting) { - RocketChat.models.Messages.createUserLeaveWithRoomIdAndUser(rocketChannel._id, rocketUser, { + Messages.createUserLeaveWithRoomIdAndUser(rocketChannel._id, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge', }); } else { - RocketChat.removeUserFromRoom(rocketChannel._id, rocketUser); + removeUserFromRoom(rocketChannel._id, rocketUser); } } processTopicMessage(rocketChannel, rocketUser, slackMessage, isImporting) { if (isImporting) { - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', rocketChannel._id, slackMessage.topic, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', rocketChannel._id, slackMessage.topic, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); } else { - RocketChat.saveRoomTopic(rocketChannel._id, slackMessage.topic, rocketUser, false); + saveRoomTopic(rocketChannel._id, slackMessage.topic, rocketUser, false); } } processPurposeMessage(rocketChannel, rocketUser, slackMessage, isImporting) { if (isImporting) { - RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', rocketChannel._id, slackMessage.purpose, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); + Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_topic', rocketChannel._id, slackMessage.purpose, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); } else { - RocketChat.saveRoomTopic(rocketChannel._id, slackMessage.purpose, rocketUser, false); + saveRoomTopic(rocketChannel._id, slackMessage.purpose, rocketUser, false); } } processNameMessage(rocketChannel, rocketUser, slackMessage, isImporting) { if (isImporting) { - RocketChat.models.Messages.createRoomRenamedWithRoomIdRoomNameAndUser(rocketChannel._id, slackMessage.name, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); + Messages.createRoomRenamedWithRoomIdRoomNameAndUser(rocketChannel._id, slackMessage.name, rocketUser, { ts: new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000), imported: 'slackbridge' }); } else { - RocketChat.saveRoomName(rocketChannel._id, slackMessage.name, rocketUser, false); + saveRoomName(rocketChannel._id, slackMessage.name, rocketUser, false); } } @@ -901,7 +912,7 @@ export default class SlackAdapter { }; if (!isImporting) { - RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${ slackMessage.attachments[0].channel_id }-${ slackMessage.attachments[0].ts.replace(/\./g, '-') }`, rocketMsgObj.u, true, new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000)); + Messages.setPinnedByIdAndUserId(`slack-${ slackMessage.attachments[0].channel_id }-${ slackMessage.attachments[0].ts.replace(/\./g, '-') }`, rocketMsgObj.u, true, new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000)); } return rocketMsgObj; @@ -935,13 +946,13 @@ export default class SlackAdapter { case 'channel_archive': case 'group_archive': if (!isImporting) { - RocketChat.archiveRoom(rocketChannel); + archiveRoom(rocketChannel); } return; case 'channel_unarchive': case 'group_unarchive': if (!isImporting) { - RocketChat.unarchiveRoom(rocketChannel); + unarchiveRoom(rocketChannel); } return; case 'file_share': @@ -1022,7 +1033,7 @@ export default class SlackAdapter { msg._id = details.message_id; } - return RocketChat.sendMessage(rocketUser, msg, rocketChannel, true); + return sendMessage(rocketUser, msg, rocketChannel, true); } }); })); @@ -1055,7 +1066,7 @@ export default class SlackAdapter { const user = this.rocket.findUser(member) || this.rocket.addUser(member); if (user) { logger.slack.debug('Adding user to room', user.username, rid); - RocketChat.addUserToRoom(rid, user, null, true); + addUserToRoom(rid, user, null, true); } } } @@ -1084,7 +1095,7 @@ export default class SlackAdapter { if (topic) { const creator = this.rocket.findUser(topic_creator) || this.rocket.addUser(topic_creator); logger.slack.debug('Setting room topic', rid, topic, creator.username); - RocketChat.saveRoomTopic(rid, topic, creator, false); + saveRoomTopic(rid, topic, creator, false); } } } @@ -1111,7 +1122,7 @@ export default class SlackAdapter { }], }; - RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${ pin.channel }-${ pin.message.ts.replace(/\./g, '-') }`, msgObj.u, true, new Date(parseInt(pin.message.ts.split('.')[0]) * 1000)); + Messages.setPinnedByIdAndUserId(`slack-${ pin.channel }-${ pin.message.ts.replace(/\./g, '-') }`, msgObj.u, true, new Date(parseInt(pin.message.ts.split('.')[0]) * 1000)); } } } @@ -1119,7 +1130,7 @@ export default class SlackAdapter { importMessages(rid, callback) { logger.slack.info('importMessages: ', rid); - const rocketchat_room = RocketChat.models.Rooms.findOneById(rid); + const rocketchat_room = Rooms.findOneById(rid); if (rocketchat_room) { if (this.getSlackChannel(rid)) { this.copyChannelInfo(rid, this.getSlackChannel(rid)); diff --git a/packages/rocketchat-slackbridge/server/settings.js b/packages/rocketchat-slackbridge/server/settings.js index a0e0205d032a..f84c1f2515c2 100644 --- a/packages/rocketchat-slackbridge/server/settings.js +++ b/packages/rocketchat-slackbridge/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('SlackBridge', function() { + settings.addGroup('SlackBridge', function() { this.add('SlackBridge_Enabled', false, { type: 'boolean', i18nLabel: 'Enabled', diff --git a/packages/rocketchat-slackbridge/server/slackbridge.js b/packages/rocketchat-slackbridge/server/slackbridge.js index 5e715c0ed4f1..f395a8c6c160 100644 --- a/packages/rocketchat-slackbridge/server/slackbridge.js +++ b/packages/rocketchat-slackbridge/server/slackbridge.js @@ -1,4 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import SlackAdapter from './SlackAdapter.js'; import RocketAdapter from './RocketAdapter.js'; import { logger } from './logger'; @@ -6,7 +6,7 @@ import { logger } from './logger'; /** * SlackBridge interfaces between this Rocket installation and a remote Slack installation. */ -class SlackBridge { +class SlackBridgeClass { constructor() { this.slack = new SlackAdapter(this); @@ -30,7 +30,7 @@ class SlackBridge { if (this.connected === false) { this.slack.connect(this.apiToken); - if (RocketChat.settings.get('SlackBridge_Out_Enabled')) { + if (settings.get('SlackBridge_Out_Enabled')) { this.rocket.connect(); } @@ -50,7 +50,7 @@ class SlackBridge { processSettings() { // Slack installation API token - RocketChat.settings.get('SlackBridge_APIToken', (key, value) => { + settings.get('SlackBridge_APIToken', (key, value) => { if (value !== this.apiToken) { this.apiToken = value; if (this.connected) { @@ -63,25 +63,25 @@ class SlackBridge { }); // Import messages from Slack with an alias; %s is replaced by the username of the user. If empty, no alias will be used. - RocketChat.settings.get('SlackBridge_AliasFormat', (key, value) => { + settings.get('SlackBridge_AliasFormat', (key, value) => { this.aliasFormat = value; logger.class.debug(`Setting: ${ key }`, value); }); // Do not propagate messages from bots whose name matches the regular expression above. If left empty, all messages from bots will be propagated. - RocketChat.settings.get('SlackBridge_ExcludeBotnames', (key, value) => { + settings.get('SlackBridge_ExcludeBotnames', (key, value) => { this.excludeBotnames = value; logger.class.debug(`Setting: ${ key }`, value); }); // Reactions - RocketChat.settings.get('SlackBridge_Reactions_Enabled', (key, value) => { + settings.get('SlackBridge_Reactions_Enabled', (key, value) => { this.isReactionsEnabled = value; logger.class.debug(`Setting: ${ key }`, value); }); // Is this entire SlackBridge enabled - RocketChat.settings.get('SlackBridge_Enabled', (key, value) => { + settings.get('SlackBridge_Enabled', (key, value) => { if (value && this.apiToken) { this.connect(); } else { @@ -92,4 +92,4 @@ class SlackBridge { } } -RocketChat.SlackBridge = new SlackBridge; +export const SlackBridge = new SlackBridgeClass; diff --git a/packages/rocketchat-slackbridge/server/slackbridge_import.server.js b/packages/rocketchat-slackbridge/server/slackbridge_import.server.js index 2b869e0e32da..f11cecab0e9d 100644 --- a/packages/rocketchat-slackbridge/server/slackbridge_import.server.js +++ b/packages/rocketchat-slackbridge/server/slackbridge_import.server.js @@ -2,14 +2,16 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { SlackBridge } from './slackbridge'; function SlackBridgeImport(command, params, item) { if (command !== 'slackbridge-import' || !Match.test(params, String)) { return; } - const room = RocketChat.models.Rooms.findOneById(item.rid); + const room = Rooms.findOneById(item.rid); const channel = room.name; const user = Meteor.users.findOne(Meteor.userId()); @@ -25,7 +27,7 @@ function SlackBridgeImport(command, params, item) { }); try { - RocketChat.SlackBridge.importMessages(item.rid, (error) => { + SlackBridge.importMessages(item.rid, (error) => { if (error) { msgStream.emit(item.rid, { _id: Random.id(), @@ -66,4 +68,4 @@ function SlackBridgeImport(command, params, item) { return SlackBridgeImport; } -RocketChat.slashCommands.add('slackbridge-import', SlackBridgeImport); +slashCommands.add('slackbridge-import', SlackBridgeImport); From 9cbf73865e1d53dfdf97d6621699a0e82bdc112b Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 18:58:18 -0200 Subject: [PATCH 060/101] Remove dependency of Rc namespace in slashcommands-asciiarts --- packages/rocketchat-slashcommand-asciiarts/lib/gimme.js | 4 ++-- packages/rocketchat-slashcommand-asciiarts/lib/lenny.js | 4 ++-- packages/rocketchat-slashcommand-asciiarts/lib/shrug.js | 4 ++-- packages/rocketchat-slashcommand-asciiarts/lib/tableflip.js | 4 ++-- packages/rocketchat-slashcommand-asciiarts/lib/unflip.js | 4 ++-- packages/rocketchat-slashcommand-asciiarts/package.js | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/rocketchat-slashcommand-asciiarts/lib/gimme.js b/packages/rocketchat-slashcommand-asciiarts/lib/gimme.js index 9add71f70cf5..4767bbd193de 100644 --- a/packages/rocketchat-slashcommand-asciiarts/lib/gimme.js +++ b/packages/rocketchat-slashcommand-asciiarts/lib/gimme.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Gimme is a named function that will replace /gimme commands * @param {Object} message - The message object @@ -14,7 +14,7 @@ function Gimme(command, params, item) { } } -RocketChat.slashCommands.add('gimme', Gimme, { +slashCommands.add('gimme', Gimme, { description: 'Slash_Gimme_Description', params: 'your_message_optional', }); diff --git a/packages/rocketchat-slashcommand-asciiarts/lib/lenny.js b/packages/rocketchat-slashcommand-asciiarts/lib/lenny.js index 3fc46b741690..90db7268fc24 100644 --- a/packages/rocketchat-slashcommand-asciiarts/lib/lenny.js +++ b/packages/rocketchat-slashcommand-asciiarts/lib/lenny.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Lenny is a named function that will replace /lenny commands * @param {Object} message - The message object @@ -14,7 +14,7 @@ function LennyFace(command, params, item) { } } -RocketChat.slashCommands.add('lennyface', LennyFace, { +slashCommands.add('lennyface', LennyFace, { description: 'Slash_LennyFace_Description', params: 'your_message_optional', }); diff --git a/packages/rocketchat-slashcommand-asciiarts/lib/shrug.js b/packages/rocketchat-slashcommand-asciiarts/lib/shrug.js index 38aaca78d498..518b62e58e6a 100644 --- a/packages/rocketchat-slashcommand-asciiarts/lib/shrug.js +++ b/packages/rocketchat-slashcommand-asciiarts/lib/shrug.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Shrug is a named function that will replace /shrug commands * @param {Object} message - The message object @@ -14,7 +14,7 @@ function Shrug(command, params, item) { } } -RocketChat.slashCommands.add('shrug', Shrug, { +slashCommands.add('shrug', Shrug, { description: 'Slash_Shrug_Description', params: 'your_message_optional', }); diff --git a/packages/rocketchat-slashcommand-asciiarts/lib/tableflip.js b/packages/rocketchat-slashcommand-asciiarts/lib/tableflip.js index ef6a5940d4f6..e52f091523fb 100644 --- a/packages/rocketchat-slashcommand-asciiarts/lib/tableflip.js +++ b/packages/rocketchat-slashcommand-asciiarts/lib/tableflip.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Tableflip is a named function that will replace /Tableflip commands * @param {Object} message - The message object @@ -14,7 +14,7 @@ function Tableflip(command, params, item) { } } -RocketChat.slashCommands.add('tableflip', Tableflip, { +slashCommands.add('tableflip', Tableflip, { description: 'Slash_Tableflip_Description', params: 'your_message_optional', }); diff --git a/packages/rocketchat-slashcommand-asciiarts/lib/unflip.js b/packages/rocketchat-slashcommand-asciiarts/lib/unflip.js index 0b15cc492939..eeda7d065009 100644 --- a/packages/rocketchat-slashcommand-asciiarts/lib/unflip.js +++ b/packages/rocketchat-slashcommand-asciiarts/lib/unflip.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Unflip is a named function that will replace /unflip commands * @param {Object} message - The message object @@ -14,7 +14,7 @@ function Unflip(command, params, item) { } } -RocketChat.slashCommands.add('unflip', Unflip, { +slashCommands.add('unflip', Unflip, { description: 'Slash_TableUnflip_Description', params: 'your_message_optional', }); diff --git a/packages/rocketchat-slashcommand-asciiarts/package.js b/packages/rocketchat-slashcommand-asciiarts/package.js index 60627aa30d13..66759ab40d80 100644 --- a/packages/rocketchat-slashcommand-asciiarts/package.js +++ b/packages/rocketchat-slashcommand-asciiarts/package.js @@ -8,7 +8,7 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:utils', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); From 3dd76ba3ed8fad492e3169dafe72357bc14cc10c Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 19:04:13 -0200 Subject: [PATCH 061/101] Remove depedency of RC namespace in rc-slash-archiveroom --- .../server/models/Messages.js | 4 ++++ .../client/client.js | 4 ++-- .../package.js | 4 +++- .../server/index.js | 1 - .../server/messages.js | 5 ----- .../server/server.js | 18 ++++++++++-------- 6 files changed, 19 insertions(+), 17 deletions(-) delete mode 100644 packages/rocketchat-slashcommands-archiveroom/server/messages.js diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index f284564aa685..b8956f63d89b 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -37,6 +37,10 @@ export class Messages extends Base { return this.update({ _id: messageId }, { $set: { reactions } }); } + createRoomArchivedByRoomIdAndUser(roomId, user) { + return this.createWithTypeRoomIdMessageAndUser('room-archived', roomId, '', user); + } + unsetReactions(messageId) { return this.update({ _id: messageId }, { $unset: { reactions: 1 } }); } diff --git a/packages/rocketchat-slashcommands-archiveroom/client/client.js b/packages/rocketchat-slashcommands-archiveroom/client/client.js index 17410aa37ff3..e6bcefb8b82f 100644 --- a/packages/rocketchat-slashcommands-archiveroom/client/client.js +++ b/packages/rocketchat-slashcommands-archiveroom/client/client.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('archive', null, { +slashCommands.add('archive', null, { description: 'Archive', params: '#channel', }); diff --git a/packages/rocketchat-slashcommands-archiveroom/package.js b/packages/rocketchat-slashcommands-archiveroom/package.js index 33feaf5e2fe7..fc56e6411b26 100644 --- a/packages/rocketchat-slashcommands-archiveroom/package.js +++ b/packages/rocketchat-slashcommands-archiveroom/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:models', + 'rocketchat:utils', + 'rocketchat:notifications', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-archiveroom/server/index.js b/packages/rocketchat-slashcommands-archiveroom/server/index.js index 509b4bf77af8..1199af15d79f 100644 --- a/packages/rocketchat-slashcommands-archiveroom/server/index.js +++ b/packages/rocketchat-slashcommands-archiveroom/server/index.js @@ -1,2 +1 @@ -import './messages'; import './server'; diff --git a/packages/rocketchat-slashcommands-archiveroom/server/messages.js b/packages/rocketchat-slashcommands-archiveroom/server/messages.js deleted file mode 100644 index a9af71671ce4..000000000000 --- a/packages/rocketchat-slashcommands-archiveroom/server/messages.js +++ /dev/null @@ -1,5 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.createRoomArchivedByRoomIdAndUser = function(roomId, user) { - return this.createWithTypeRoomIdMessageAndUser('room-archived', roomId, '', user); -}; diff --git a/packages/rocketchat-slashcommands-archiveroom/server/server.js b/packages/rocketchat-slashcommands-archiveroom/server/server.js index 25c6cbfad728..6dae39e7f0e1 100644 --- a/packages/rocketchat-slashcommands-archiveroom/server/server.js +++ b/packages/rocketchat-slashcommands-archiveroom/server/server.js @@ -2,7 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Notifications } from 'meteor/rocketchat:notifications'; function Archive(command, params, item) { if (command !== 'archive' || !Match.test(params, String)) { @@ -13,17 +15,17 @@ function Archive(command, params, item) { let room; if (channel === '') { - room = RocketChat.models.Rooms.findOneById(item.rid); + room = Rooms.findOneById(item.rid); channel = room.name; } else { channel = channel.replace('#', ''); - room = RocketChat.models.Rooms.findOneByName(channel); + room = Rooms.findOneByName(channel); } const user = Meteor.users.findOne(Meteor.userId()); if (!room) { - return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + return Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -40,7 +42,7 @@ function Archive(command, params, item) { } if (room.archived) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -53,8 +55,8 @@ function Archive(command, params, item) { } Meteor.call('archiveRoom', room._id); - RocketChat.models.Messages.createRoomArchivedByRoomIdAndUser(room._id, Meteor.user()); - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Messages.createRoomArchivedByRoomIdAndUser(room._id, Meteor.user()); + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -67,7 +69,7 @@ function Archive(command, params, item) { return Archive; } -RocketChat.slashCommands.add('archive', Archive, { +slashCommands.add('archive', Archive, { description: 'Archive', params: '#channel', }); From ca9c0749f6e83101e3a947b2403e719148166873 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 19:07:19 -0200 Subject: [PATCH 062/101] Remove dependency of RC namespace in rc-slash-create --- .../client/client.js | 4 ++-- packages/rocketchat-slashcommands-create/package.js | 5 ++++- .../server/server.js | 13 ++++++++----- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/rocketchat-slashcommands-create/client/client.js b/packages/rocketchat-slashcommands-create/client/client.js index 5678b191bba4..d7ce7dfeaaa6 100644 --- a/packages/rocketchat-slashcommands-create/client/client.js +++ b/packages/rocketchat-slashcommands-create/client/client.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('create', null, { +slashCommands.add('create', null, { description: 'Create_A_New_Channel', params: '#channel', }); diff --git a/packages/rocketchat-slashcommands-create/package.js b/packages/rocketchat-slashcommands-create/package.js index 5335efd45dbe..ce89f5165404 100644 --- a/packages/rocketchat-slashcommands-create/package.js +++ b/packages/rocketchat-slashcommands-create/package.js @@ -9,7 +9,10 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:notifications', + 'rocketchat:settings', + 'rocketchat:models', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-create/server/server.js b/packages/rocketchat-slashcommands-create/server/server.js index b7fe540e6ae8..913fbf17a737 100644 --- a/packages/rocketchat-slashcommands-create/server/server.js +++ b/packages/rocketchat-slashcommands-create/server/server.js @@ -2,7 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Rooms } from 'meteor/rocketchat:models'; +import { slashCommands } from 'meteor/rocketchat:utils'; function Create(command, params, item) { function getParams(str) { @@ -18,7 +21,7 @@ function Create(command, params, item) { return result; } - const regexp = new RegExp(RocketChat.settings.get('UTF8_Names_Validation')); + const regexp = new RegExp(settings.get('UTF8_Names_Validation')); if (command !== 'create' || !Match.test(params, String)) { return; @@ -30,9 +33,9 @@ function Create(command, params, item) { } const user = Meteor.users.findOne(Meteor.userId()); - const room = RocketChat.models.Rooms.findOneByName(channel); + const room = Rooms.findOneByName(channel); if (room != null) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -51,7 +54,7 @@ function Create(command, params, item) { Meteor.call('createChannel', channel, []); } -RocketChat.slashCommands.add('create', Create, { +slashCommands.add('create', Create, { description: 'Create_A_New_Channel', params: '#channel', }); From c4354d09fe5be2423ae6e0247345e076c2a50aea Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 19:10:01 -0200 Subject: [PATCH 063/101] Remove dependency of RC namespace in rc-slash-help --- packages/rocketchat-slashcommands-help/package.js | 3 ++- packages/rocketchat-slashcommands-help/server/server.js | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/rocketchat-slashcommands-help/package.js b/packages/rocketchat-slashcommands-help/package.js index ae2677e09bdb..8aa7ea065ae9 100644 --- a/packages/rocketchat-slashcommands-help/package.js +++ b/packages/rocketchat-slashcommands-help/package.js @@ -9,7 +9,8 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:notifications', 'templating', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-slashcommands-help/server/server.js b/packages/rocketchat-slashcommands-help/server/server.js index 2e9838153031..2e47b0bc7850 100644 --- a/packages/rocketchat-slashcommands-help/server/server.js +++ b/packages/rocketchat-slashcommands-help/server/server.js @@ -1,7 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Notifications } from 'meteor/rocketchat:notifications'; /* * Help is a named function that will replace /join commands @@ -9,7 +10,7 @@ import { RocketChat } from 'meteor/rocketchat:lib'; */ -RocketChat.slashCommands.add('help', function Help(command, params, item) { +slashCommands.add('help', function Help(command, params, item) { const user = Meteor.users.findOne(Meteor.userId()); const keys = [{ Open_channel_user_search: 'Command (or Ctrl) + p OR Command (or Ctrl) + k', @@ -37,7 +38,7 @@ RocketChat.slashCommands.add('help', function Help(command, params, item) { }, ]; keys.forEach((key) => { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, From c0ede559e12a3fbdf3d288c0b394d4abde37c290 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 19:10:17 -0200 Subject: [PATCH 064/101] Remove dependency of RC namespace in rc-slash-hide --- .../rocketchat-slashcommands-hide/client/hide.js | 4 ++-- .../rocketchat-slashcommands-hide/package.js | 4 +++- .../rocketchat-slashcommands-hide/server/hide.js | 16 +++++++++------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/rocketchat-slashcommands-hide/client/hide.js b/packages/rocketchat-slashcommands-hide/client/hide.js index 58a54241b5df..86d7d400f806 100644 --- a/packages/rocketchat-slashcommands-hide/client/hide.js +++ b/packages/rocketchat-slashcommands-hide/client/hide.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('hide', undefined, { +slashCommands.add('hide', undefined, { description: 'Hide_room', params: '#room', }); diff --git a/packages/rocketchat-slashcommands-hide/package.js b/packages/rocketchat-slashcommands-hide/package.js index 2a1931706235..e58915038346 100644 --- a/packages/rocketchat-slashcommands-hide/package.js +++ b/packages/rocketchat-slashcommands-hide/package.js @@ -8,7 +8,9 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:notifications', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-slashcommands-hide/server/hide.js b/packages/rocketchat-slashcommands-hide/server/hide.js index 5e2d0b5b5690..4d578e3f7f5d 100644 --- a/packages/rocketchat-slashcommands-hide/server/hide.js +++ b/packages/rocketchat-slashcommands-hide/server/hide.js @@ -2,7 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Hide is a named function that will replace /hide commands @@ -20,13 +22,13 @@ function Hide(command, param, item) { const [strippedRoom] = room.replace(/#|@/, '').split(' '); const [type] = room; - const roomObject = type === '#' ? RocketChat.models.Rooms.findOneByName(strippedRoom) : RocketChat.models.Rooms.findOne({ + const roomObject = type === '#' ? Rooms.findOneByName(strippedRoom) : Rooms.findOne({ t: 'd', usernames: { $all: [user.username, strippedRoom] }, }); if (!roomObject) { - return RocketChat.Notifications.notifyUser(user._id, 'message', { + return Notifications.notifyUser(user._id, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -37,8 +39,8 @@ function Hide(command, param, item) { }); } - if (!RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { - return RocketChat.Notifications.notifyUser(user._id, 'message', { + if (!Subscriptions.findOneByRoomIdAndUserId(room._id, user._id, { fields: { _id: 1 } })) { + return Notifications.notifyUser(user._id, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -53,7 +55,7 @@ function Hide(command, param, item) { Meteor.call('hideRoom', rid, (error) => { if (error) { - return RocketChat.Notifications.notifyUser(user._id, 'message', { + return Notifications.notifyUser(user._id, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -63,4 +65,4 @@ function Hide(command, param, item) { }); } -RocketChat.slashCommands.add('hide', Hide, { description: 'Hide_room', params: '#room' }); +slashCommands.add('hide', Hide, { description: 'Hide_room', params: '#room' }); From b6fd2d5dff22252f712ffe324bd45d13bc36cec1 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 19:12:39 -0200 Subject: [PATCH 065/101] Remove dependency of RC namespace in rc-slash-invite --- .../client/client.js | 4 ++-- .../rocketchat-slashcommands-invite/package.js | 4 +++- .../server/server.js | 16 +++++++++------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/rocketchat-slashcommands-invite/client/client.js b/packages/rocketchat-slashcommands-invite/client/client.js index 66b6e1d28529..b820e409ebb9 100644 --- a/packages/rocketchat-slashcommands-invite/client/client.js +++ b/packages/rocketchat-slashcommands-invite/client/client.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('invite', undefined, { +slashCommands.add('invite', undefined, { description: 'Invite_user_to_join_channel', params: '@username', }); diff --git a/packages/rocketchat-slashcommands-invite/package.js b/packages/rocketchat-slashcommands-invite/package.js index 192c938c9d28..edb995de8c3e 100644 --- a/packages/rocketchat-slashcommands-invite/package.js +++ b/packages/rocketchat-slashcommands-invite/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:notifications', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-invite/server/server.js b/packages/rocketchat-slashcommands-invite/server/server.js index 82e30bc7cddf..51ace6761752 100644 --- a/packages/rocketchat-slashcommands-invite/server/server.js +++ b/packages/rocketchat-slashcommands-invite/server/server.js @@ -2,7 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Subscriptions } from 'meteor/rocketchat:models'; /* * Invite is a named function that will replace /invite commands @@ -27,7 +29,7 @@ function Invite(command, params, item) { const userId = Meteor.userId(); const currentUser = Meteor.users.findOne(userId); if (users.count() === 0) { - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -39,11 +41,11 @@ function Invite(command, params, item) { return; } users = users.fetch().filter(function(user) { - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(item.rid, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(item.rid, user._id, { fields: { _id: 1 } }); if (subscription == null) { return true; } - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -64,14 +66,14 @@ function Invite(command, params, item) { }); } catch ({ error }) { if (error === 'cant-invite-for-direct-room') { - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, msg: TAPi18n.__('Cannot_invite_users_to_direct_rooms', null, currentUser.language), }); } else { - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -82,7 +84,7 @@ function Invite(command, params, item) { }); } -RocketChat.slashCommands.add('invite', Invite, { +slashCommands.add('invite', Invite, { description: 'Invite_user_to_join_channel', params: '@username', }); From c532fada6bdede0917c42f3a66d1afc3ab276848 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 4 Feb 2019 19:15:56 -0200 Subject: [PATCH 066/101] Remove dependency of RC namespace in rc-slash-inviteall --- .../client/client.js | 6 ++--- .../package.js | 5 +++- .../server/server.js | 25 +++++++++++-------- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/packages/rocketchat-slashcommands-inviteall/client/client.js b/packages/rocketchat-slashcommands-inviteall/client/client.js index 63cd6219912f..34eb7e9ad8e8 100644 --- a/packages/rocketchat-slashcommands-inviteall/client/client.js +++ b/packages/rocketchat-slashcommands-inviteall/client/client.js @@ -1,10 +1,10 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('invite-all-to', undefined, { +slashCommands.add('invite-all-to', undefined, { description: 'Invite_user_to_join_channel_all_to', params: '#room', }); -RocketChat.slashCommands.add('invite-all-from', undefined, { +slashCommands.add('invite-all-from', undefined, { description: 'Invite_user_to_join_channel_all_from', params: '#room', }); diff --git a/packages/rocketchat-slashcommands-inviteall/package.js b/packages/rocketchat-slashcommands-inviteall/package.js index 9c9c13d165f3..b3c1a9488c3f 100644 --- a/packages/rocketchat-slashcommands-inviteall/package.js +++ b/packages/rocketchat-slashcommands-inviteall/package.js @@ -9,7 +9,10 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:notifications', + 'rocketchat:settings', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-inviteall/server/server.js b/packages/rocketchat-slashcommands-inviteall/server/server.js index db5a84e71ea4..0f64b1b713f4 100644 --- a/packages/rocketchat-slashcommands-inviteall/server/server.js +++ b/packages/rocketchat-slashcommands-inviteall/server/server.js @@ -6,7 +6,10 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; function inviteAll(type) { return function inviteAll(command, params, item) { @@ -23,11 +26,11 @@ function inviteAll(type) { } const userId = Meteor.userId(); const currentUser = Meteor.users.findOne(userId); - const baseChannel = type === 'to' ? RocketChat.models.Rooms.findOneById(item.rid) : RocketChat.models.Rooms.findOneByName(channel); - const targetChannel = type === 'from' ? RocketChat.models.Rooms.findOneById(item.rid) : RocketChat.models.Rooms.findOneByName(channel); + const baseChannel = type === 'to' ? Rooms.findOneById(item.rid) : Rooms.findOneByName(channel); + const targetChannel = type === 'from' ? Rooms.findOneById(item.rid) : Rooms.findOneByName(channel); if (!baseChannel) { - return RocketChat.Notifications.notifyUser(userId, 'message', { + return Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -37,10 +40,10 @@ function inviteAll(type) { }, currentUser.language), }); } - const cursor = RocketChat.models.Subscriptions.findByRoomIdWhenUsernameExists(baseChannel._id, { fields: { 'u.username': 1 } }); + const cursor = Subscriptions.findByRoomIdWhenUsernameExists(baseChannel._id, { fields: { 'u.username': 1 } }); try { - if (cursor.count() > RocketChat.settings.get('API_User_Limit')) { + if (cursor.count() > settings.get('API_User_Limit')) { throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', { method: 'addAllToRoom', }); @@ -49,7 +52,7 @@ function inviteAll(type) { if (!targetChannel && ['c', 'p'].indexOf(baseChannel.t) > -1) { Meteor.call(baseChannel.t === 'c' ? 'createChannel' : 'createPrivateGroup', channel, users); - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -64,7 +67,7 @@ function inviteAll(type) { users, }); } - return RocketChat.Notifications.notifyUser(userId, 'message', { + return Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -72,7 +75,7 @@ function inviteAll(type) { }); } catch (e) { const msg = e.error === 'cant-invite-for-direct-room' ? 'Cannot_invite_users_to_direct_rooms' : e.error; - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -82,11 +85,11 @@ function inviteAll(type) { }; } -RocketChat.slashCommands.add('invite-all-to', inviteAll('to'), { +slashCommands.add('invite-all-to', inviteAll('to'), { description: 'Invite_user_to_join_channel_all_to', params: '#room', }); -RocketChat.slashCommands.add('invite-all-from', inviteAll('from'), { +slashCommands.add('invite-all-from', inviteAll('from'), { description: 'Invite_user_to_join_channel_all_from', params: '#room', }); From 40fb5456ddc720cc262b7abd61b8ea152b66bf65 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:17:21 -0200 Subject: [PATCH 067/101] Remove dependency of RC namespace in rc-slash-join --- .../rocketchat-slashcommands-join/client/client.js | 6 +++--- packages/rocketchat-slashcommands-join/package.js | 4 +++- .../rocketchat-slashcommands-join/server/server.js | 12 +++++++----- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/rocketchat-slashcommands-join/client/client.js b/packages/rocketchat-slashcommands-join/client/client.js index eb9e802adba2..4f9377dda40b 100644 --- a/packages/rocketchat-slashcommands-join/client/client.js +++ b/packages/rocketchat-slashcommands-join/client/client.js @@ -1,12 +1,12 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('join', undefined, { +slashCommands.add('join', undefined, { description: 'Join_the_given_channel', params: '#channel', }, function(err, result, params) { if (err.error === 'error-user-already-in-room') { params.cmd = 'open'; params.msg.msg = params.msg.msg.replace('join', 'open'); - return RocketChat.slashCommands.run('open', params.params, params.msg); + return slashCommands.run('open', params.params, params.msg); } }); diff --git a/packages/rocketchat-slashcommands-join/package.js b/packages/rocketchat-slashcommands-join/package.js index 118b5ea5f767..a8a4f407cc53 100644 --- a/packages/rocketchat-slashcommands-join/package.js +++ b/packages/rocketchat-slashcommands-join/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:notifications', + 'rocketchat:models', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-join/server/server.js b/packages/rocketchat-slashcommands-join/server/server.js index 774a09082b72..a2b32900993a 100644 --- a/packages/rocketchat-slashcommands-join/server/server.js +++ b/packages/rocketchat-slashcommands-join/server/server.js @@ -7,9 +7,11 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('join', function Join(command, params, item) { +slashCommands.add('join', function Join(command, params, item) { if (command !== 'join' || !Match.test(params, String)) { return; @@ -20,9 +22,9 @@ RocketChat.slashCommands.add('join', function Join(command, params, item) { } channel = channel.replace('#', ''); const user = Meteor.users.findOne(Meteor.userId()); - const room = RocketChat.models.Rooms.findOneByNameAndType(channel, 'c'); + const room = Rooms.findOneByNameAndType(channel, 'c'); if (!room) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -33,7 +35,7 @@ RocketChat.slashCommands.add('join', function Join(command, params, item) { }); } - 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) { throw new Meteor.Error('error-user-already-in-room', 'You are already in the channel', { method: 'slashCommands', From e24096b851b55275e76e14ae0ccf5554a306a490 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:28:56 -0200 Subject: [PATCH 068/101] Remove dependency of RC namespace in rc-slash-kick --- .../rocketchat-slashcommands-kick/client/client.js | 4 ++-- packages/rocketchat-slashcommands-kick/package.js | 4 +++- .../rocketchat-slashcommands-kick/server/server.js | 14 ++++++++------ 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/rocketchat-slashcommands-kick/client/client.js b/packages/rocketchat-slashcommands-kick/client/client.js index 15868bd81efd..b4ec4b3a17a8 100644 --- a/packages/rocketchat-slashcommands-kick/client/client.js +++ b/packages/rocketchat-slashcommands-kick/client/client.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('kick', function(command, params) { +slashCommands.add('kick', function(command, params) { const username = params.trim(); if (username === '') { return; diff --git a/packages/rocketchat-slashcommands-kick/package.js b/packages/rocketchat-slashcommands-kick/package.js index 69ffed31f8df..48ca20a78c49 100644 --- a/packages/rocketchat-slashcommands-kick/package.js +++ b/packages/rocketchat-slashcommands-kick/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:notifications', + 'rocketchat:models', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-kick/server/server.js b/packages/rocketchat-slashcommands-kick/server/server.js index 71d1b0e79ebd..45b341400886 100644 --- a/packages/rocketchat-slashcommands-kick/server/server.js +++ b/packages/rocketchat-slashcommands-kick/server/server.js @@ -4,7 +4,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; +import { slashCommands } from 'meteor/rocketchat:utils'; const Kick = function(command, params, { rid }) { if (command !== 'kick' || !Match.test(params, String)) { @@ -16,10 +18,10 @@ const Kick = function(command, params, { rid }) { } const userId = Meteor.userId(); const user = Meteor.users.findOne(userId); - const kickedUser = RocketChat.models.Users.findOneByUsername(username); + const kickedUser = Users.findOneByUsername(username); if (kickedUser == null) { - return RocketChat.Notifications.notifyUser(userId, 'message', { + return Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid, ts: new Date, @@ -30,9 +32,9 @@ const Kick = function(command, params, { rid }) { }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(rid, user._id, { fields: { _id: 1 } }); if (!subscription) { - return RocketChat.Notifications.notifyUser(userId, 'message', { + return Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid, ts: new Date, @@ -45,7 +47,7 @@ const Kick = function(command, params, { rid }) { Meteor.call('removeUserFromRoom', { rid, username }); }; -RocketChat.slashCommands.add('kick', Kick, { +slashCommands.add('kick', Kick, { description: 'Remove_someone_from_room', params: '@username', permission: 'remove-user', From 1aa0f73eadc7576c95a8f54bf494c230b2c11b4d Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:29:10 -0200 Subject: [PATCH 069/101] Remove dependency of RC namespace in rc-slash-leave --- packages/rocketchat-slashcommands-leave/package.js | 3 ++- packages/rocketchat-slashcommands-leave/server/leave.js | 9 +++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/rocketchat-slashcommands-leave/package.js b/packages/rocketchat-slashcommands-leave/package.js index f747d1bda029..115f83fab1fc 100644 --- a/packages/rocketchat-slashcommands-leave/package.js +++ b/packages/rocketchat-slashcommands-leave/package.js @@ -8,7 +8,8 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:notifications', ]); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-slashcommands-leave/server/leave.js b/packages/rocketchat-slashcommands-leave/server/leave.js index 3f0d07ac3d42..a3510b410d97 100644 --- a/packages/rocketchat-slashcommands-leave/server/leave.js +++ b/packages/rocketchat-slashcommands-leave/server/leave.js @@ -1,7 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { slashCommands } from 'meteor/rocketchat:utils'; /* * Leave is a named function that will replace /leave commands @@ -15,7 +16,7 @@ function Leave(command, params, item) { try { Meteor.call('leaveRoom', item.rid); } catch ({ error }) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -24,5 +25,5 @@ function Leave(command, params, item) { } } -RocketChat.slashCommands.add('leave', Leave, { description: 'Leave_the_current_channel' }); -RocketChat.slashCommands.add('part', Leave, { description: 'Leave_the_current_channel' }); +slashCommands.add('leave', Leave, { description: 'Leave_the_current_channel' }); +slashCommands.add('part', Leave, { description: 'Leave_the_current_channel' }); From 74fc80c288cdf6246a40ed1ee0dad396e526efab Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:32:12 -0200 Subject: [PATCH 070/101] Remove dependency of RC namespace in rc-slash-me --- packages/rocketchat-slashcommands-me/package.js | 2 +- packages/rocketchat-slashcommands-me/server/me.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/rocketchat-slashcommands-me/package.js b/packages/rocketchat-slashcommands-me/package.js index 92e6c9891642..1920b2678726 100644 --- a/packages/rocketchat-slashcommands-me/package.js +++ b/packages/rocketchat-slashcommands-me/package.js @@ -8,7 +8,7 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:utils', ]); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-slashcommands-me/server/me.js b/packages/rocketchat-slashcommands-me/server/me.js index b02dcd1cdfd0..d3d8242e9b5e 100644 --- a/packages/rocketchat-slashcommands-me/server/me.js +++ b/packages/rocketchat-slashcommands-me/server/me.js @@ -1,12 +1,12 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; import s from 'underscore.string'; /* * Me is a named function that will replace /me commands * @param {Object} message - The message object */ -RocketChat.slashCommands.add('me', function Me(command, params, item) { +slashCommands.add('me', function Me(command, params, item) { if (command !== 'me') { return; } From 5180629b128f96da12cce6f346a0b642753a8233 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:32:26 -0200 Subject: [PATCH 071/101] Remove dependency of RC namespace in rc-slash-msg --- packages/rocketchat-slashcommands-msg/package.js | 4 +++- .../rocketchat-slashcommands-msg/server/server.js | 12 +++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/rocketchat-slashcommands-msg/package.js b/packages/rocketchat-slashcommands-msg/package.js index 77c36632bbbf..6c25c9b1f302 100644 --- a/packages/rocketchat-slashcommands-msg/package.js +++ b/packages/rocketchat-slashcommands-msg/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:notifications', 'templating', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-slashcommands-msg/server/server.js b/packages/rocketchat-slashcommands-msg/server/server.js index 9af2bbb2b30f..caacc12692af 100644 --- a/packages/rocketchat-slashcommands-msg/server/server.js +++ b/packages/rocketchat-slashcommands-msg/server/server.js @@ -2,7 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { Users } from 'meteor/rocketchat:models'; /* * Msg is a named function that will replace /msg commands @@ -16,7 +18,7 @@ function Msg(command, params, item) { const separator = trimmedParams.indexOf(' '); const user = Meteor.users.findOne(Meteor.userId()); if (separator === -1) { - return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + return Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -26,9 +28,9 @@ function Msg(command, params, item) { const message = trimmedParams.slice(separator + 1); const targetUsernameOrig = trimmedParams.slice(0, separator); const targetUsername = targetUsernameOrig.replace('@', ''); - const targetUser = RocketChat.models.Users.findOneByUsername(targetUsername); + const targetUser = Users.findOneByUsername(targetUsername); if (targetUser == null) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -48,7 +50,7 @@ function Msg(command, params, item) { Meteor.call('sendMessage', msgObject); } -RocketChat.slashCommands.add('msg', Msg, { +slashCommands.add('msg', Msg, { description: 'Direct_message_someone', params: '@username ', }); From b3c4be271b7e8e0b212cd13fe9e2d99150790743 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:34:37 -0200 Subject: [PATCH 072/101] Remove dependency of RC namespace in rc-slash-mute --- packages/rocketchat-slashcommands-mute/package.js | 4 +++- .../rocketchat-slashcommands-mute/server/mute.js | 14 ++++++++------ .../rocketchat-slashcommands-mute/server/unmute.js | 14 ++++++++------ 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/packages/rocketchat-slashcommands-mute/package.js b/packages/rocketchat-slashcommands-mute/package.js index 8e2caf22319a..d04f51ea5712 100644 --- a/packages/rocketchat-slashcommands-mute/package.js +++ b/packages/rocketchat-slashcommands-mute/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:notifications', + 'rocketchat:models', ]); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-slashcommands-mute/server/mute.js b/packages/rocketchat-slashcommands-mute/server/mute.js index 31dc84923ce1..b04028482092 100644 --- a/packages/rocketchat-slashcommands-mute/server/mute.js +++ b/packages/rocketchat-slashcommands-mute/server/mute.js @@ -2,13 +2,15 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; /* * Mute is a named function that will replace /mute commands */ -RocketChat.slashCommands.add('mute', function Mute(command, params, item) { +slashCommands.add('mute', function Mute(command, params, item) { if (command !== 'mute' || !Match.test(params, String)) { return; } @@ -18,9 +20,9 @@ RocketChat.slashCommands.add('mute', function Mute(command, params, item) { } const userId = Meteor.userId(); const user = Meteor.users.findOne(userId); - const mutedUser = RocketChat.models.Users.findOneByUsername(username); + const mutedUser = Users.findOneByUsername(username); if (mutedUser == null) { - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -32,9 +34,9 @@ RocketChat.slashCommands.add('mute', function Mute(command, params, item) { return; } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(item.rid, mutedUser._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(item.rid, mutedUser._id, { fields: { _id: 1 } }); if (!subscription) { - RocketChat.Notifications.notifyUser(userId, 'message', { + Notifications.notifyUser(userId, 'message', { _id: Random.id(), rid: item.rid, ts: new Date, diff --git a/packages/rocketchat-slashcommands-mute/server/unmute.js b/packages/rocketchat-slashcommands-mute/server/unmute.js index bb049d7746a0..b2a27df0aa5d 100644 --- a/packages/rocketchat-slashcommands-mute/server/unmute.js +++ b/packages/rocketchat-slashcommands-mute/server/unmute.js @@ -2,13 +2,15 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Users, Subscriptions } from 'meteor/rocketchat:models'; +import { Notifications } from 'meteor/rocketchat:notifications'; /* * Unmute is a named function that will replace /unmute commands */ -RocketChat.slashCommands.add('unmute', function Unmute(command, params, item) { +slashCommands.add('unmute', function Unmute(command, params, item) { if (command !== 'unmute' || !Match.test(params, String)) { return; @@ -18,9 +20,9 @@ RocketChat.slashCommands.add('unmute', function Unmute(command, params, item) { return; } const user = Meteor.users.findOne(Meteor.userId()); - const unmutedUser = RocketChat.models.Users.findOneByUsername(username); + const unmutedUser = Users.findOneByUsername(username); if (unmutedUser == null) { - return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + return Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, @@ -31,9 +33,9 @@ RocketChat.slashCommands.add('unmute', function Unmute(command, params, item) { }); } - const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(item.rid, unmutedUser._id, { fields: { _id: 1 } }); + const subscription = Subscriptions.findOneByRoomIdAndUserId(item.rid, unmutedUser._id, { fields: { _id: 1 } }); if (!subscription) { - return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + return Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date, From baa9aeca3784e7c5330e36ee9947206262ba0aa1 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:36:22 -0200 Subject: [PATCH 073/101] Remove dependency of RC namespace in rc-slash-open --- .../rocketchat-slashcommands-open/client/client.js | 12 ++++++------ packages/rocketchat-slashcommands-open/package.js | 3 ++- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/rocketchat-slashcommands-open/client/client.js b/packages/rocketchat-slashcommands-open/client/client.js index a7d8b05b11a0..c53312a4b181 100644 --- a/packages/rocketchat-slashcommands-open/client/client.js +++ b/packages/rocketchat-slashcommands-open/client/client.js @@ -1,8 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { FlowRouter } from 'meteor/kadira:flow-router'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { ChatSubscription } from 'meteor/rocketchat:ui'; +import { slashCommands, roomTypes } from 'meteor/rocketchat:utils'; +import { ChatSubscription, Subscriptions } from 'meteor/rocketchat:models'; function Open(command, params /* , item*/) { const dict = { @@ -31,7 +31,7 @@ function Open(command, params /* , item*/) { const subscription = ChatSubscription.findOne(query); if (subscription) { - RocketChat.roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams); + roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams); } if (type && type.indexOf('d') === -1) { @@ -41,13 +41,13 @@ function Open(command, params /* , item*/) { if (err) { return; } - const subscription = RocketChat.models.Subscriptions.findOne(query); - RocketChat.roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams); + const subscription = Subscriptions.findOne(query); + roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams); }); } -RocketChat.slashCommands.add('open', Open, { +slashCommands.add('open', Open, { description: 'Opens_a_channel_group_or_direct_message', params: 'room_name', clientOnly: true, diff --git a/packages/rocketchat-slashcommands-open/package.js b/packages/rocketchat-slashcommands-open/package.js index 2aa1b6ed8455..339f1097ba20 100644 --- a/packages/rocketchat-slashcommands-open/package.js +++ b/packages/rocketchat-slashcommands-open/package.js @@ -9,7 +9,8 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', 'kadira:flow-router', 'templating', ]); From d75940e2803173c2d3fb5cf46821a483de52d38c Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:39:19 -0200 Subject: [PATCH 074/101] Remove dependency of RC namespace in rc-slash-topic --- packages/rocketchat-slashcommands-topic/lib/topic.js | 12 +++++++----- packages/rocketchat-slashcommands-topic/package.js | 4 +++- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/rocketchat-slashcommands-topic/lib/topic.js b/packages/rocketchat-slashcommands-topic/lib/topic.js index 8824f3a85cc2..16a06d62aaa1 100644 --- a/packages/rocketchat-slashcommands-topic/lib/topic.js +++ b/packages/rocketchat-slashcommands-topic/lib/topic.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { ChatRoom } from 'meteor/rocketchat:ui'; +import { handleError, slashCommands } from 'meteor/rocketchat:utils'; +import { ChatRoom } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { hasPermission } from 'meteor/rocketchat:authorization'; /* * Join is a named function that will replace /topic commands * @param {Object} message - The message object @@ -8,7 +10,7 @@ import { ChatRoom } from 'meteor/rocketchat:ui'; function Topic(command, params, item) { if (command === 'topic') { - if ((Meteor.isClient && RocketChat.authz.hasPermission('edit-room', item.rid)) || (Meteor.isServer && RocketChat.authz.hasPermission(Meteor.userId(), 'edit-room', item.rid))) { + if ((Meteor.isClient && hasPermission('edit-room', item.rid)) || (Meteor.isServer && hasPermission(Meteor.userId(), 'edit-room', item.rid))) { Meteor.call('saveRoomSettings', item.rid, 'roomTopic', params, (err) => { if (err) { if (Meteor.isClient) { @@ -19,14 +21,14 @@ function Topic(command, params, item) { } if (Meteor.isClient) { - RocketChat.callbacks.run('roomTopicChanged', ChatRoom.findOne(item.rid)); + callbacks.run('roomTopicChanged', ChatRoom.findOne(item.rid)); } }); } } } -RocketChat.slashCommands.add('topic', Topic, { +slashCommands.add('topic', Topic, { description: 'Slash_Topic_Description', params: 'Slash_Topic_Params', }); diff --git a/packages/rocketchat-slashcommands-topic/package.js b/packages/rocketchat-slashcommands-topic/package.js index 209ccf9462b5..30552892422b 100644 --- a/packages/rocketchat-slashcommands-topic/package.js +++ b/packages/rocketchat-slashcommands-topic/package.js @@ -7,7 +7,9 @@ Package.describe({ Package.onUse(function(api) { api.use([ - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:callbacks', 'ecmascript', 'rocketchat:authorization', ]); From 8687f9e8a9e89ec2a59aef1d4c32a7b568609a31 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 10:44:51 -0200 Subject: [PATCH 075/101] Remove dependency of RC namespace in rc-slash-unarchiveroom --- .../server/models/Messages.js | 4 ++++ .../client/client.js | 4 ++-- .../package.js | 4 +++- .../server/index.js | 1 - .../server/messages.js | 5 ----- .../server/server.js | 18 ++++++++++-------- 6 files changed, 19 insertions(+), 17 deletions(-) delete mode 100644 packages/rocketchat-slashcommands-unarchiveroom/server/messages.js diff --git a/packages/rocketchat-models/server/models/Messages.js b/packages/rocketchat-models/server/models/Messages.js index b8956f63d89b..a85e64182430 100644 --- a/packages/rocketchat-models/server/models/Messages.js +++ b/packages/rocketchat-models/server/models/Messages.js @@ -41,6 +41,10 @@ export class Messages extends Base { return this.createWithTypeRoomIdMessageAndUser('room-archived', roomId, '', user); } + createRoomUnarchivedByRoomIdAndUser(roomId, user) { + return this.createWithTypeRoomIdMessageAndUser('room-unarchived', roomId, '', user); + } + unsetReactions(messageId) { return this.update({ _id: messageId }, { $unset: { reactions: 1 } }); } diff --git a/packages/rocketchat-slashcommands-unarchiveroom/client/client.js b/packages/rocketchat-slashcommands-unarchiveroom/client/client.js index 419aab3b5f51..153ccb2f5d93 100644 --- a/packages/rocketchat-slashcommands-unarchiveroom/client/client.js +++ b/packages/rocketchat-slashcommands-unarchiveroom/client/client.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; -RocketChat.slashCommands.add('unarchive', null, { +slashCommands.add('unarchive', null, { description: 'Unarchive', params: '#channel', }); diff --git a/packages/rocketchat-slashcommands-unarchiveroom/package.js b/packages/rocketchat-slashcommands-unarchiveroom/package.js index ec0f7818727b..818c727ab442 100644 --- a/packages/rocketchat-slashcommands-unarchiveroom/package.js +++ b/packages/rocketchat-slashcommands-unarchiveroom/package.js @@ -9,7 +9,9 @@ Package.onUse(function(api) { api.use([ 'ecmascript', 'check', - 'rocketchat:lib', + 'rocketchat:utils', + 'rocketchat:models', + 'rocketchat:notifications', 'templating', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-slashcommands-unarchiveroom/server/index.js b/packages/rocketchat-slashcommands-unarchiveroom/server/index.js index 509b4bf77af8..1199af15d79f 100644 --- a/packages/rocketchat-slashcommands-unarchiveroom/server/index.js +++ b/packages/rocketchat-slashcommands-unarchiveroom/server/index.js @@ -1,2 +1 @@ -import './messages'; import './server'; diff --git a/packages/rocketchat-slashcommands-unarchiveroom/server/messages.js b/packages/rocketchat-slashcommands-unarchiveroom/server/messages.js deleted file mode 100644 index 79538c270a61..000000000000 --- a/packages/rocketchat-slashcommands-unarchiveroom/server/messages.js +++ /dev/null @@ -1,5 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Messages.createRoomUnarchivedByRoomIdAndUser = function(roomId, user) { - return this.createWithTypeRoomIdMessageAndUser('room-unarchived', roomId, '', user); -}; diff --git a/packages/rocketchat-slashcommands-unarchiveroom/server/server.js b/packages/rocketchat-slashcommands-unarchiveroom/server/server.js index 4e6cc8c264c1..406c4d391323 100644 --- a/packages/rocketchat-slashcommands-unarchiveroom/server/server.js +++ b/packages/rocketchat-slashcommands-unarchiveroom/server/server.js @@ -2,7 +2,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Messages } from 'meteor/rocketchat:models'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { Notifications } from 'meteor/rocketchat:notifications'; function Unarchive(command, params, item) { if (command !== 'unarchive' || !Match.test(params, String)) { @@ -13,17 +15,17 @@ function Unarchive(command, params, item) { let room; if (channel === '') { - room = RocketChat.models.Rooms.findOneById(item.rid); + room = Rooms.findOneById(item.rid); channel = room.name; } else { channel = channel.replace('#', ''); - room = RocketChat.models.Rooms.findOneByName(channel); + room = Rooms.findOneByName(channel); } const user = Meteor.users.findOne(Meteor.userId()); if (!room) { - return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + return Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -40,7 +42,7 @@ function Unarchive(command, params, item) { } if (!room.archived) { - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -54,8 +56,8 @@ function Unarchive(command, params, item) { Meteor.call('unarchiveRoom', room._id); - RocketChat.models.Messages.createRoomUnarchivedByRoomIdAndUser(room._id, Meteor.user()); - RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', { + Messages.createRoomUnarchivedByRoomIdAndUser(room._id, Meteor.user()); + Notifications.notifyUser(Meteor.userId(), 'message', { _id: Random.id(), rid: item.rid, ts: new Date(), @@ -68,7 +70,7 @@ function Unarchive(command, params, item) { return Unarchive; } -RocketChat.slashCommands.add('unarchive', Unarchive, { +slashCommands.add('unarchive', Unarchive, { description: 'Unarchive', params: '#channel', }); From 90adc29835d8f53796abbccb3c65d7ab99549851 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 11:02:18 -0200 Subject: [PATCH 076/101] Remove dependency of RC namespace in rc-smarsh-connector --- packages/rocketchat-models/server/index.js | 2 ++ .../server/models/SmarshHistory.js | 9 +++++++ .../client/index.js | 1 - .../lib/rocketchat.js | 3 --- .../rocketchat-smarsh-connector/package.js | 8 ++++-- .../server/functions/generateEml.js | 25 +++++++++++-------- .../server/functions/sendEmail.js | 12 +++++---- .../server/index.js | 2 -- .../server/lib/rocketchat.js | 1 + .../server/models/SmarshHistory.js | 7 ------ .../server/settings.js | 4 +-- .../server/startup.js | 17 +++++++------ 12 files changed, 50 insertions(+), 41 deletions(-) create mode 100644 packages/rocketchat-models/server/models/SmarshHistory.js delete mode 100644 packages/rocketchat-smarsh-connector/client/index.js delete mode 100644 packages/rocketchat-smarsh-connector/lib/rocketchat.js create mode 100644 packages/rocketchat-smarsh-connector/server/lib/rocketchat.js delete mode 100644 packages/rocketchat-smarsh-connector/server/models/SmarshHistory.js diff --git a/packages/rocketchat-models/server/index.js b/packages/rocketchat-models/server/index.js index e2cf6662bba1..16f3e1ff2041 100644 --- a/packages/rocketchat-models/server/index.js +++ b/packages/rocketchat-models/server/index.js @@ -21,6 +21,7 @@ import CredentialTokens from './models/CredentialTokens'; import EmojiCustom from './models/EmojiCustom'; import OAuthApps from './models/OAuthApps'; import OEmbedCache from './models/OEmbedCache'; +import SmarshHistory from './models/SmarshHistory'; export { Base, @@ -46,4 +47,5 @@ export { EmojiCustom, OAuthApps, OEmbedCache, + SmarshHistory, }; diff --git a/packages/rocketchat-models/server/models/SmarshHistory.js b/packages/rocketchat-models/server/models/SmarshHistory.js new file mode 100644 index 000000000000..9b2b7abc5043 --- /dev/null +++ b/packages/rocketchat-models/server/models/SmarshHistory.js @@ -0,0 +1,9 @@ +import { Base } from './_Base'; + +export class SmarshHistory extends Base { + constructor() { + super('smarsh_history'); + } +} + +export default new SmarshHistory(); diff --git a/packages/rocketchat-smarsh-connector/client/index.js b/packages/rocketchat-smarsh-connector/client/index.js deleted file mode 100644 index 8e716d1f414f..000000000000 --- a/packages/rocketchat-smarsh-connector/client/index.js +++ /dev/null @@ -1 +0,0 @@ -import '../lib/rocketchat'; diff --git a/packages/rocketchat-smarsh-connector/lib/rocketchat.js b/packages/rocketchat-smarsh-connector/lib/rocketchat.js deleted file mode 100644 index 4cce0a082f62..000000000000 --- a/packages/rocketchat-smarsh-connector/lib/rocketchat.js +++ /dev/null @@ -1,3 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.smarsh = {}; diff --git a/packages/rocketchat-smarsh-connector/package.js b/packages/rocketchat-smarsh-connector/package.js index a35be1671fc0..6d79ed6ae083 100644 --- a/packages/rocketchat-smarsh-connector/package.js +++ b/packages/rocketchat-smarsh-connector/package.js @@ -8,8 +8,12 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'jalik:ufs', + 'littledata:synced-cron', + 'rocketchat:mailer', + 'rocketchat:ui-utils', + 'rocketchat:models', + 'rocketchat:settings', ]); - api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-smarsh-connector/server/functions/generateEml.js b/packages/rocketchat-smarsh-connector/server/functions/generateEml.js index 561650ca7b58..be9248d74ca6 100644 --- a/packages/rocketchat-smarsh-connector/server/functions/generateEml.js +++ b/packages/rocketchat-smarsh-connector/server/functions/generateEml.js @@ -1,6 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Rooms, Messages, Users, SmarshHistory } from 'meteor/rocketchat:models'; +import { MessageTypes } from 'meteor/rocketchat:ui-utils'; +import { smarsh } from '../lib/rocketchat'; import _ from 'underscore'; import moment from 'moment'; import 'moment-timezone'; @@ -23,13 +26,13 @@ function _getLink(attachment) { } } -RocketChat.smarsh.generateEml = () => { +smarsh.generateEml = () => { Meteor.defer(() => { - const smarshMissingEmail = RocketChat.settings.get('Smarsh_MissingEmail_Email'); - const timeZone = RocketChat.settings.get('Smarsh_Timezone'); + const smarshMissingEmail = settings.get('Smarsh_MissingEmail_Email'); + const timeZone = settings.get('Smarsh_Timezone'); - RocketChat.models.Rooms.find().forEach((room) => { - const smarshHistory = RocketChat.smarsh.History.findOne({ _id: room._id }); + Rooms.find().forEach((room) => { + const smarshHistory = SmarshHistory.findOne({ _id: room._id }); const query = { rid: room._id }; if (smarshHistory) { @@ -46,7 +49,7 @@ RocketChat.smarsh.generateEml = () => { room: room.name ? `#${ room.name }` : `Direct Message Between: ${ room.usernames.join(' & ') }`, }; - RocketChat.models.Messages.find(query).forEach((message) => { + Messages.find(query).forEach((message) => { rows.push(opentr); // The timestamp @@ -56,7 +59,7 @@ RocketChat.smarsh.generateEml = () => { // The sender rows.push(open20td); - const sender = RocketChat.models.Users.findOne({ _id: message.u._id }); + const sender = Users.findOne({ _id: message.u._id }); if (data.users.indexOf(sender._id) === -1) { data.users.push(sender._id); } @@ -73,7 +76,7 @@ RocketChat.smarsh.generateEml = () => { rows.push(open60td); data.msgs++; if (message.t) { - const messageType = RocketChat.MessageTypes.getType(message); + const messageType = MessageTypes.getType(message); if (messageType) { rows.push(TAPi18n.__(messageType.message, messageType.data ? messageType.data(message) : '', 'en')); } else { @@ -106,13 +109,13 @@ RocketChat.smarsh.generateEml = () => { if (rows.length !== 0) { const result = start + rows.join('') + end; - RocketChat.smarsh.History.upsert({ _id: room._id }, { + SmarshHistory.upsert({ _id: room._id }, { _id: room._id, lastRan: date, lastResult: result, }); - RocketChat.smarsh.sendEmail({ + smarsh.sendEmail({ body: result, subject: `Rocket.Chat, ${ data.users.length } Users, ${ data.msgs } Messages, ${ data.files.length } Files, ${ data.time } Minutes, in ${ data.room }`, files: data.files, diff --git a/packages/rocketchat-smarsh-connector/server/functions/sendEmail.js b/packages/rocketchat-smarsh-connector/server/functions/sendEmail.js index cb452103f8b4..b0ddb27bb0f6 100644 --- a/packages/rocketchat-smarsh-connector/server/functions/sendEmail.js +++ b/packages/rocketchat-smarsh-connector/server/functions/sendEmail.js @@ -6,14 +6,16 @@ // } import _ from 'underscore'; import * as Mailer from 'meteor/rocketchat:mailer'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Uploads } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import { UploadFS } from 'meteor/jalik:ufs'; +import { smarsh } from '../lib/rocketchat'; -RocketChat.smarsh.sendEmail = (data) => { +smarsh.sendEmail = (data) => { const attachments = []; _.each(data.files, (fileId) => { - const file = RocketChat.models.Uploads.findOneById(fileId); + const file = Uploads.findOneById(fileId); if (file.store === 'rocketchat_uploads' || file.store === 'fileSystem') { const rs = UploadFS.getStore(file.store).getReadStream(fileId, file); attachments.push({ @@ -25,8 +27,8 @@ RocketChat.smarsh.sendEmail = (data) => { Mailer.sendNoWrap({ - to: RocketChat.settings.get('Smarsh_Email'), - from: RocketChat.settings.get('From_Email'), + to: settings.get('Smarsh_Email'), + from: settings.get('From_Email'), subject: data.subject, html: data.body, attachments, diff --git a/packages/rocketchat-smarsh-connector/server/index.js b/packages/rocketchat-smarsh-connector/server/index.js index 6f5d1370f97a..7c301809bb58 100644 --- a/packages/rocketchat-smarsh-connector/server/index.js +++ b/packages/rocketchat-smarsh-connector/server/index.js @@ -1,6 +1,4 @@ -import '../lib/rocketchat'; import './settings'; -import './models/SmarshHistory'; import './functions/sendEmail'; import './functions/generateEml'; import './startup'; diff --git a/packages/rocketchat-smarsh-connector/server/lib/rocketchat.js b/packages/rocketchat-smarsh-connector/server/lib/rocketchat.js new file mode 100644 index 000000000000..f8f593dbebcc --- /dev/null +++ b/packages/rocketchat-smarsh-connector/server/lib/rocketchat.js @@ -0,0 +1 @@ +export const smarsh = {}; diff --git a/packages/rocketchat-smarsh-connector/server/models/SmarshHistory.js b/packages/rocketchat-smarsh-connector/server/models/SmarshHistory.js deleted file mode 100644 index a53d7b8c3a05..000000000000 --- a/packages/rocketchat-smarsh-connector/server/models/SmarshHistory.js +++ /dev/null @@ -1,7 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.smarsh.History = new class extends RocketChat.models._Base { - constructor() { - super('smarsh_history'); - } -}; diff --git a/packages/rocketchat-smarsh-connector/server/settings.js b/packages/rocketchat-smarsh-connector/server/settings.js index 2a3b2f6fb4e2..b028b56e9917 100644 --- a/packages/rocketchat-smarsh-connector/server/settings.js +++ b/packages/rocketchat-smarsh-connector/server/settings.js @@ -1,8 +1,8 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import moment from 'moment'; import 'moment-timezone'; -RocketChat.settings.addGroup('Smarsh', function addSettings() { +settings.addGroup('Smarsh', function addSettings() { this.add('Smarsh_Enabled', false, { type: 'boolean', i18nLabel: 'Smarsh_Enabled', diff --git a/packages/rocketchat-smarsh-connector/server/startup.js b/packages/rocketchat-smarsh-connector/server/startup.js index 0a596864c44b..74373f3ba53e 100644 --- a/packages/rocketchat-smarsh-connector/server/startup.js +++ b/packages/rocketchat-smarsh-connector/server/startup.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { SyncedCron } from 'meteor/littledata:synced-cron'; +import { smarsh } from './lib/rocketchat'; import _ from 'underscore'; const smarshJobName = 'Smarsh EML Connector'; @@ -10,11 +11,11 @@ const _addSmarshSyncedCronJob = _.debounce(Meteor.bindEnvironment(function __add SyncedCron.remove(smarshJobName); } - if (RocketChat.settings.get('Smarsh_Enabled') && RocketChat.settings.get('Smarsh_Email') !== '' && RocketChat.settings.get('From_Email') !== '') { + if (settings.get('Smarsh_Enabled') && settings.get('Smarsh_Email') !== '' && settings.get('From_Email') !== '') { SyncedCron.add({ name: smarshJobName, - schedule: (parser) => parser.text(RocketChat.settings.get('Smarsh_Interval').replace(/_/g, ' ')), - job: RocketChat.smarsh.generateEml, + schedule: (parser) => parser.text(settings.get('Smarsh_Interval').replace(/_/g, ' ')), + job: smarsh.generateEml, }); } }), 500); @@ -23,9 +24,9 @@ Meteor.startup(() => { Meteor.defer(() => { _addSmarshSyncedCronJob(); - RocketChat.settings.get('Smarsh_Interval', _addSmarshSyncedCronJob); - RocketChat.settings.get('Smarsh_Enabled', _addSmarshSyncedCronJob); - RocketChat.settings.get('Smarsh_Email', _addSmarshSyncedCronJob); - RocketChat.settings.get('From_Email', _addSmarshSyncedCronJob); + settings.get('Smarsh_Interval', _addSmarshSyncedCronJob); + settings.get('Smarsh_Enabled', _addSmarshSyncedCronJob); + settings.get('Smarsh_Email', _addSmarshSyncedCronJob); + settings.get('From_Email', _addSmarshSyncedCronJob); }); }); From 76a7209463d871c806f16b34ccc798a5373c8edc Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 11:14:27 -0200 Subject: [PATCH 077/101] Remove dependency of RC namespace in rc-sms --- packages/rocketchat-livechat/imports/server/rest/sms.js | 3 ++- packages/rocketchat-livechat/server/sendMessageBySMS.js | 5 +++-- packages/rocketchat-sms/package.js | 2 +- packages/rocketchat-sms/server/SMS.js | 8 ++++---- packages/rocketchat-sms/server/index.js | 2 +- packages/rocketchat-sms/server/services/twilio.js | 9 +++++---- packages/rocketchat-sms/server/settings.js | 4 ++-- 7 files changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/rocketchat-livechat/imports/server/rest/sms.js b/packages/rocketchat-livechat/imports/server/rest/sms.js index ce107e278848..43b44b0a5985 100644 --- a/packages/rocketchat-livechat/imports/server/rest/sms.js +++ b/packages/rocketchat-livechat/imports/server/rest/sms.js @@ -2,11 +2,12 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import { RocketChat } from 'meteor/rocketchat:lib'; import { API } from 'meteor/rocketchat:api'; +import { SMS } from 'meteor/rocketchat:sms'; import LivechatVisitors from '../../../server/models/LivechatVisitors'; API.v1.addRoute('livechat/sms-incoming/:service', { post() { - const SMSService = RocketChat.SMS.getService(this.urlParams.service); + const SMSService = SMS.getService(this.urlParams.service); const sms = SMSService.parse(this.bodyParams); diff --git a/packages/rocketchat-livechat/server/sendMessageBySMS.js b/packages/rocketchat-livechat/server/sendMessageBySMS.js index 8cc5a3f0b72e..a1957f85fe8f 100644 --- a/packages/rocketchat-livechat/server/sendMessageBySMS.js +++ b/packages/rocketchat-livechat/server/sendMessageBySMS.js @@ -1,4 +1,5 @@ import { RocketChat } from 'meteor/rocketchat:lib'; +import { SMS } from 'meteor/rocketchat:sms'; import LivechatVisitors from './models/LivechatVisitors'; RocketChat.callbacks.add('afterSaveMessage', function(message, room) { @@ -7,7 +8,7 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) { return message; } - if (!RocketChat.SMS.enabled) { + if (!SMS.enabled) { return message; } @@ -26,7 +27,7 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) { return message; } - const SMSService = RocketChat.SMS.getService(RocketChat.settings.get('SMS_Service')); + const SMSService = SMS.getService(RocketChat.settings.get('SMS_Service')); if (!SMSService) { return message; diff --git a/packages/rocketchat-sms/package.js b/packages/rocketchat-sms/package.js index bbd775c1b9c2..16642149eafa 100644 --- a/packages/rocketchat-sms/package.js +++ b/packages/rocketchat-sms/package.js @@ -9,7 +9,7 @@ Package.describe({ Package.onUse(function(api) { api.use([ 'ecmascript', - 'rocketchat:lib', + 'rocketchat:settings', ]); api.mainModule('server/index.js', 'server'); }); diff --git a/packages/rocketchat-sms/server/SMS.js b/packages/rocketchat-sms/server/SMS.js index 1829756e68ee..d9c1edeb2429 100644 --- a/packages/rocketchat-sms/server/SMS.js +++ b/packages/rocketchat-sms/server/SMS.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.SMS = { +export const SMS = { enabled: false, services: {}, accountSid: null, @@ -20,6 +20,6 @@ RocketChat.SMS = { }, }; -RocketChat.settings.get('SMS_Enabled', function(key, value) { - RocketChat.SMS.enabled = value; +settings.get('SMS_Enabled', function(key, value) { + SMS.enabled = value; }); diff --git a/packages/rocketchat-sms/server/index.js b/packages/rocketchat-sms/server/index.js index e46413334273..73f51cc23d66 100644 --- a/packages/rocketchat-sms/server/index.js +++ b/packages/rocketchat-sms/server/index.js @@ -1,3 +1,3 @@ import './settings'; -import './SMS'; +export { SMS } from './SMS'; import './services/twilio'; diff --git a/packages/rocketchat-sms/server/services/twilio.js b/packages/rocketchat-sms/server/services/twilio.js index 615df3ea13e4..33a07737ee62 100644 --- a/packages/rocketchat-sms/server/services/twilio.js +++ b/packages/rocketchat-sms/server/services/twilio.js @@ -1,10 +1,11 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { SMS } from '../SMS'; import twilio from 'twilio'; class Twilio { constructor() { - this.accountSid = RocketChat.settings.get('SMS_Twilio_Account_SID'); - this.authToken = RocketChat.settings.get('SMS_Twilio_authToken'); + this.accountSid = settings.get('SMS_Twilio_Account_SID'); + this.authToken = settings.get('SMS_Twilio_authToken'); } parse(data) { let numMedia = 0; @@ -85,4 +86,4 @@ class Twilio { } } -RocketChat.SMS.registerService('twilio', Twilio); +SMS.registerService('twilio', Twilio); diff --git a/packages/rocketchat-sms/server/settings.js b/packages/rocketchat-sms/server/settings.js index 040eb21aa9ee..847308c4c2b7 100644 --- a/packages/rocketchat-sms/server/settings.js +++ b/packages/rocketchat-sms/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('SMS', function() { + settings.addGroup('SMS', function() { this.add('SMS_Enabled', false, { type: 'boolean', i18nLabel: 'Enabled', From 73c2704aff34ab08610bf3bd7c823e9167aff4b6 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 11:21:19 -0200 Subject: [PATCH 078/101] Remove dependency of RC namespace in rc-spotify --- packages/rocketchat-spotify/lib/spotify.js | 7 +++---- packages/rocketchat-spotify/package.js | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/packages/rocketchat-spotify/lib/spotify.js b/packages/rocketchat-spotify/lib/spotify.js index 979d54192b8d..57f9e569ca32 100644 --- a/packages/rocketchat-spotify/lib/spotify.js +++ b/packages/rocketchat-spotify/lib/spotify.js @@ -2,7 +2,7 @@ * Spotify a named function that will process Spotify links or syntaxes (ex: spotify:track:1q6IK1l4qpYykOaWaLJkWG) * @param {Object} message - The message object */ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; import s from 'underscore.string'; @@ -73,6 +73,5 @@ class Spotify { } } -RocketChat.callbacks.add('beforeSaveMessage', Spotify.transform, RocketChat.callbacks.priority.LOW, 'spotify-save'); -RocketChat.callbacks.add('renderMessage', Spotify.render, RocketChat.callbacks.priority.MEDIUM, 'spotify-render'); -RocketChat.Spotify = Spotify; +callbacks.add('beforeSaveMessage', Spotify.transform, callbacks.priority.LOW, 'spotify-save'); +callbacks.add('renderMessage', Spotify.render, callbacks.priority.MEDIUM, 'spotify-render'); diff --git a/packages/rocketchat-spotify/package.js b/packages/rocketchat-spotify/package.js index 1497065024c0..fd4af497ad89 100644 --- a/packages/rocketchat-spotify/package.js +++ b/packages/rocketchat-spotify/package.js @@ -10,7 +10,7 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:oembed', - 'rocketchat:lib', + 'rocketchat:callbacks', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); From 56d9d9906ce5bb03ce374448a2e53ddf1276ea78 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 11:44:01 -0200 Subject: [PATCH 079/101] Remove dependency of RC namespace in rc-statistics --- .../rocketchat-statistics/client/index.js | 2 +- .../rocketchat-statistics/lib/rocketchat.js | 4 +- packages/rocketchat-statistics/package.js | 8 ++- .../server/functions/get.js | 69 ++++++++++--------- .../server/functions/save.js | 13 ++-- .../rocketchat-statistics/server/index.js | 3 +- .../server/methods/getStatistics.js | 10 +-- .../server/models/import.js | 4 -- server/startup/cron.js | 7 +- server/startup/migrations/v059.js | 4 +- 10 files changed, 66 insertions(+), 58 deletions(-) delete mode 100644 packages/rocketchat-statistics/server/models/import.js diff --git a/packages/rocketchat-statistics/client/index.js b/packages/rocketchat-statistics/client/index.js index 8e716d1f414f..4d6822b60218 100644 --- a/packages/rocketchat-statistics/client/index.js +++ b/packages/rocketchat-statistics/client/index.js @@ -1 +1 @@ -import '../lib/rocketchat'; +export { statistics } from '../lib/rocketchat'; diff --git a/packages/rocketchat-statistics/lib/rocketchat.js b/packages/rocketchat-statistics/lib/rocketchat.js index 0da35b5c6794..bfd4f992e589 100644 --- a/packages/rocketchat-statistics/lib/rocketchat.js +++ b/packages/rocketchat-statistics/lib/rocketchat.js @@ -1,3 +1 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.statistics = {}; +export const statistics = {}; diff --git a/packages/rocketchat-statistics/package.js b/packages/rocketchat-statistics/package.js index f379ce963648..628a6c88496a 100644 --- a/packages/rocketchat-statistics/package.js +++ b/packages/rocketchat-statistics/package.js @@ -9,8 +9,14 @@ Package.onUse(function(api) { api.use([ 'mongo', 'ecmascript', - 'rocketchat:lib', + 'littledata:synced-cron', + 'accounts-base', + 'rocketchat:migrations', + 'rocketchat:utils', + 'rocketchat:settings', + 'rocketchat:authorization', 'rocketchat:models', + 'rocketchat:logger', 'konecty:multiple-instances-status', ]); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-statistics/server/functions/get.js b/packages/rocketchat-statistics/server/functions/get.js index 5c70902beee4..89137f051816 100644 --- a/packages/rocketchat-statistics/server/functions/get.js +++ b/packages/rocketchat-statistics/server/functions/get.js @@ -3,9 +3,12 @@ import { MongoInternals } from 'meteor/mongo'; import _ from 'underscore'; import os from 'os'; import LivechatVisitors from 'meteor/rocketchat:livechat/server/models/LivechatVisitors'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { InstanceStatus } from 'meteor/konecty:multiple-instances-status'; -import { Sessions } from 'meteor/rocketchat:models'; +import { Sessions, Settings, Users, Rooms, Subscriptions, Uploads, Messages } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; +import { Migrations } from 'meteor/rocketchat:migrations'; +import { statistics } from '../../lib/rocketchat'; const wizardFields = [ 'Organization_Type', @@ -20,37 +23,37 @@ const wizardFields = [ 'Allow_Marketing_Emails', ]; -RocketChat.statistics.get = function _getStatistics() { +statistics.get = function _getStatistics() { const statistics = {}; // Setup Wizard statistics.wizard = {}; wizardFields.forEach((field) => { - const record = RocketChat.models.Settings.findOne(field); + const record = Settings.findOne(field); if (record) { const wizardField = field.replace(/_/g, '').replace(field[0], field[0].toLowerCase()); statistics.wizard[wizardField] = record.value; } }); - const firstUser = RocketChat.models.Users.getOldest({ name: 1, emails: 1 }); + const firstUser = Users.getOldest({ name: 1, emails: 1 }); statistics.wizard.contactName = firstUser && firstUser.name; statistics.wizard.contactEmail = firstUser && firstUser.emails && firstUser.emails[0].address; - if (RocketChat.settings.get('Organization_Email')) { - statistics.wizard.contactEmail = RocketChat.settings.get('Organization_Email'); + if (settings.get('Organization_Email')) { + statistics.wizard.contactEmail = settings.get('Organization_Email'); } // Version - statistics.uniqueId = RocketChat.settings.get('uniqueID'); - if (RocketChat.models.Settings.findOne('uniqueID')) { - statistics.installedAt = RocketChat.models.Settings.findOne('uniqueID').createdAt; + statistics.uniqueId = settings.get('uniqueID'); + if (Settings.findOne('uniqueID')) { + statistics.installedAt = Settings.findOne('uniqueID').createdAt; } - if (RocketChat.Info) { - statistics.version = RocketChat.Info.version; - statistics.tag = RocketChat.Info.tag; - statistics.branch = RocketChat.Info.branch; + if (Info) { + statistics.version = Info.version; + statistics.tag = Info.tag; + statistics.branch = Info.branch; } // User statistics @@ -62,31 +65,31 @@ RocketChat.statistics.get = function _getStatistics() { statistics.offlineUsers = statistics.totalUsers - statistics.onlineUsers - statistics.awayUsers; // Room statistics - statistics.totalRooms = RocketChat.models.Rooms.find().count(); - statistics.totalChannels = RocketChat.models.Rooms.findByType('c').count(); - statistics.totalPrivateGroups = RocketChat.models.Rooms.findByType('p').count(); - statistics.totalDirect = RocketChat.models.Rooms.findByType('d').count(); - statistics.totalLivechat = RocketChat.models.Rooms.findByType('l').count(); + statistics.totalRooms = Rooms.find().count(); + statistics.totalChannels = Rooms.findByType('c').count(); + statistics.totalPrivateGroups = Rooms.findByType('p').count(); + statistics.totalDirect = Rooms.findByType('d').count(); + statistics.totalLivechat = Rooms.findByType('l').count(); // livechat visitors statistics.totalLivechatVisitors = LivechatVisitors.find().count(); // livechat agents - statistics.totalLivechatAgents = RocketChat.models.Users.findAgents().count(); + statistics.totalLivechatAgents = Users.findAgents().count(); // livechat enabled - statistics.livechatEnabled = RocketChat.settings.get('Livechat_enabled'); + statistics.livechatEnabled = settings.get('Livechat_enabled'); // Message statistics - statistics.totalMessages = RocketChat.models.Messages.find().count(); - statistics.totalChannelMessages = _.reduce(RocketChat.models.Rooms.findByType('c', { fields: { msgs: 1 } }).fetch(), function _countChannelMessages(num, room) { return num + room.msgs; }, 0); - statistics.totalPrivateGroupMessages = _.reduce(RocketChat.models.Rooms.findByType('p', { fields: { msgs: 1 } }).fetch(), function _countPrivateGroupMessages(num, room) { return num + room.msgs; }, 0); - statistics.totalDirectMessages = _.reduce(RocketChat.models.Rooms.findByType('d', { fields: { msgs: 1 } }).fetch(), function _countDirectMessages(num, room) { return num + room.msgs; }, 0); - statistics.totalLivechatMessages = _.reduce(RocketChat.models.Rooms.findByType('l', { fields: { msgs: 1 } }).fetch(), function _countLivechatMessages(num, room) { return num + room.msgs; }, 0); + statistics.totalMessages = Messages.find().count(); + statistics.totalChannelMessages = _.reduce(Rooms.findByType('c', { fields: { msgs: 1 } }).fetch(), function _countChannelMessages(num, room) { return num + room.msgs; }, 0); + statistics.totalPrivateGroupMessages = _.reduce(Rooms.findByType('p', { fields: { msgs: 1 } }).fetch(), function _countPrivateGroupMessages(num, room) { return num + room.msgs; }, 0); + statistics.totalDirectMessages = _.reduce(Rooms.findByType('d', { fields: { msgs: 1 } }).fetch(), function _countDirectMessages(num, room) { return num + room.msgs; }, 0); + statistics.totalLivechatMessages = _.reduce(Rooms.findByType('l', { fields: { msgs: 1 } }).fetch(), function _countLivechatMessages(num, room) { return num + room.msgs; }, 0); - statistics.lastLogin = RocketChat.models.Users.getLastLogin(); - statistics.lastMessageSentAt = RocketChat.models.Messages.getLastTimestamp(); - statistics.lastSeenSubscription = RocketChat.models.Subscriptions.getLastSeen(); + statistics.lastLogin = Users.getLastLogin(); + statistics.lastMessageSentAt = Messages.getLastTimestamp(); + statistics.lastSeenSubscription = Subscriptions.getLastSeen(); statistics.os = { type: os.type(), @@ -111,16 +114,16 @@ RocketChat.statistics.get = function _getStatistics() { platform: process.env.DEPLOY_PLATFORM || 'selfinstall', }; - statistics.uploadsTotal = RocketChat.models.Uploads.find().count(); - const [result] = Promise.await(RocketChat.models.Uploads.model.rawCollection().aggregate([{ $group: { _id: 'total', total: { $sum: '$size' } } }]).toArray()); + statistics.uploadsTotal = Uploads.find().count(); + const [result] = Promise.await(Uploads.model.rawCollection().aggregate([{ $group: { _id: 'total', total: { $sum: '$size' } } }]).toArray()); statistics.uploadsTotalSize = result ? result.total : 0; - statistics.migration = RocketChat.Migrations._getControl(); + statistics.migration = Migrations._getControl(); statistics.instanceCount = InstanceStatus.getCollection().find({ _updatedAt: { $gt: new Date(Date.now() - process.uptime() * 1000 - 2000) } }).count(); const { mongo } = MongoInternals.defaultRemoteCollectionDriver(); - if (mongo._oplogHandle && mongo._oplogHandle.onOplogEntry && RocketChat.settings.get('Force_Disable_OpLog_For_Cache') !== true) { + if (mongo._oplogHandle && mongo._oplogHandle.onOplogEntry && settings.get('Force_Disable_OpLog_For_Cache') !== true) { statistics.oplogEnabled = true; } diff --git a/packages/rocketchat-statistics/server/functions/save.js b/packages/rocketchat-statistics/server/functions/save.js index b960a99cca99..3f93e52808e4 100644 --- a/packages/rocketchat-statistics/server/functions/save.js +++ b/packages/rocketchat-statistics/server/functions/save.js @@ -1,8 +1,9 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Statistics } from 'meteor/rocketchat:models'; +import { statistics } from '../../lib/rocketchat'; -RocketChat.statistics.save = function() { - const statistics = RocketChat.statistics.get(); - statistics.createdAt = new Date; - RocketChat.models.Statistics.insert(statistics); - return statistics; +statistics.save = function() { + const rcStatistics = statistics.get(); + rcStatistics.createdAt = new Date; + Statistics.insert(rcStatistics); + return rcStatistics; }; diff --git a/packages/rocketchat-statistics/server/index.js b/packages/rocketchat-statistics/server/index.js index 150f49e1179f..3d85ca7ef891 100644 --- a/packages/rocketchat-statistics/server/index.js +++ b/packages/rocketchat-statistics/server/index.js @@ -1,5 +1,4 @@ -import '../lib/rocketchat'; -import './models/import'; +export { statistics } from '../lib/rocketchat'; import './functions/get'; import './functions/save'; import './methods/getStatistics'; diff --git a/packages/rocketchat-statistics/server/methods/getStatistics.js b/packages/rocketchat-statistics/server/methods/getStatistics.js index b31792e4441a..4c5d172eb715 100644 --- a/packages/rocketchat-statistics/server/methods/getStatistics.js +++ b/packages/rocketchat-statistics/server/methods/getStatistics.js @@ -1,5 +1,7 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Statistics } from 'meteor/rocketchat:models'; +import { statistics } from '../../lib/rocketchat'; Meteor.methods({ getStatistics(refresh) { @@ -7,14 +9,14 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getStatistics' }); } - if (RocketChat.authz.hasPermission(Meteor.userId(), 'view-statistics') !== true) { + if (hasPermission(Meteor.userId(), 'view-statistics') !== true) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'getStatistics' }); } if (refresh) { - return RocketChat.statistics.save(); + return statistics.save(); } else { - return RocketChat.models.Statistics.findLast(); + return Statistics.findLast(); } }, }); diff --git a/packages/rocketchat-statistics/server/models/import.js b/packages/rocketchat-statistics/server/models/import.js deleted file mode 100644 index d628e60380d1..000000000000 --- a/packages/rocketchat-statistics/server/models/import.js +++ /dev/null @@ -1,4 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; -import { Statistics } from 'meteor/rocketchat:models'; - -RocketChat.models.Statistics = Statistics; diff --git a/server/startup/cron.js b/server/startup/cron.js index a5c93b6e1a5a..5c6c14c6fa4a 100644 --- a/server/startup/cron.js +++ b/server/startup/cron.js @@ -3,6 +3,7 @@ import { HTTP } from 'meteor/http'; import { Logger } from 'meteor/rocketchat:logger'; import { getWorkspaceAccessToken } from 'meteor/rocketchat:cloud'; import { SyncedCron } from 'meteor/littledata:synced-cron'; +import { statistics } from 'meteor/rocketchat:statistics'; const logger = new Logger('SyncedCron'); @@ -14,9 +15,9 @@ SyncedCron.config({ }); function generateStatistics() { - const statistics = RocketChat.statistics.save(); + const cronStatistics = statistics.save(); - statistics.host = Meteor.absoluteUrl(); + cronStatistics.host = Meteor.absoluteUrl(); if (RocketChat.settings.get('Statistics_reporting')) { try { @@ -28,7 +29,7 @@ function generateStatistics() { } HTTP.post('https://collector.rocket.chat/', { - data: statistics, + data: cronStatistics, headers, }); } catch (error) { diff --git a/server/startup/migrations/v059.js b/server/startup/migrations/v059.js index c5f0843d440d..9e8a0bdcd458 100644 --- a/server/startup/migrations/v059.js +++ b/server/startup/migrations/v059.js @@ -1,3 +1,5 @@ +import { Statistics } from 'meteor/rocketchat:models'; + RocketChat.Migrations.add({ version: 59, up() { @@ -5,7 +7,7 @@ RocketChat.Migrations.add({ if (users && users.length > 0) { const { createdAt } = users[0]; RocketChat.models.Settings.update({ createdAt: { $exists: 0 } }, { $set: { createdAt } }, { multi: true }); - RocketChat.models.Statistics.update({ installedAt: { $exists: 0 } }, { $set: { installedAt: createdAt } }, { multi: true }); + Statistics.update({ installedAt: { $exists: 0 } }, { $set: { installedAt: createdAt } }, { multi: true }); } }, }); From ad49a78001ee85d04d0e6ab3f3a8acaf8ecf6515 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 12:18:30 -0200 Subject: [PATCH 080/101] Move tokenpass models methods to rc-models --- .../rocketchat-models/server/models/Rooms.js | 33 +++++++++++++++++++ .../server/models/Subscriptions.js | 16 +++++++++ .../rocketchat-models/server/models/Users.js | 24 ++++++++++++++ packages/rocketchat-tokenpass/server/index.js | 4 --- .../server/models/Rooms.js | 33 ------------------- .../server/models/Subscriptions.js | 17 ---------- .../server/models/Users.js | 25 -------------- .../server/models/indexes.js | 6 ---- 8 files changed, 73 insertions(+), 85 deletions(-) delete mode 100644 packages/rocketchat-tokenpass/server/models/Rooms.js delete mode 100644 packages/rocketchat-tokenpass/server/models/Subscriptions.js delete mode 100644 packages/rocketchat-tokenpass/server/models/Users.js delete mode 100644 packages/rocketchat-tokenpass/server/models/indexes.js diff --git a/packages/rocketchat-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index ce1b209292ce..343f3294b881 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -12,6 +12,7 @@ export class Rooms extends Base { this.tryEnsureIndex({ default: 1 }); this.tryEnsureIndex({ t: 1 }); this.tryEnsureIndex({ 'u._id': 1 }); + this.tryEnsureIndex({ 'tokenpass.tokens.token': 1 }); } findOneByIdOrName(_idOrName, options) { @@ -26,6 +27,38 @@ export class Rooms extends Base { return this.findOne(query, options); } + findByTokenpass(tokens) { + const query = { + 'tokenpass.tokens.token': { + $in: tokens, + }, + }; + + return this._db.find(query).fetch(); + } + + setTokensById(_id, tokens) { + const update = { + $set: { + 'tokenpass.tokens.token': tokens, + }, + }; + + return this.update({ _id }, update); + } + + findAllTokenChannels() { + const query = { + tokenpass: { $exists: true }, + }; + const options = { + fields: { + tokenpass: 1, + }, + }; + return this._db.find(query, options); + } + setReactionsInLastMessage(roomId, lastMessage) { return this.update({ _id: roomId }, { $set: { lastMessage } }); } diff --git a/packages/rocketchat-models/server/models/Subscriptions.js b/packages/rocketchat-models/server/models/Subscriptions.js index 0ccfade3d72e..07f96783c241 100644 --- a/packages/rocketchat-models/server/models/Subscriptions.js +++ b/packages/rocketchat-models/server/models/Subscriptions.js @@ -30,6 +30,22 @@ export class Subscriptions extends Base { this.tryEnsureIndex({ 'userHighlights.0': 1 }, { sparse: 1 }); } + findByRoomIds(roomIds) { + const query = { + rid: { + $in: roomIds, + }, + }; + const options = { + fields: { + 'u._id': 1, + rid: 1, + }, + }; + + return this._db.find(query, options); + } + updateAutoTranslateById(_id, autoTranslate) { const query = { _id, diff --git a/packages/rocketchat-models/server/models/Users.js b/packages/rocketchat-models/server/models/Users.js index ded5341e8b16..80ac74653892 100644 --- a/packages/rocketchat-models/server/models/Users.js +++ b/packages/rocketchat-models/server/models/Users.js @@ -26,6 +26,30 @@ export class Users extends Base { }); } + setTokenpassTcaBalances(_id, tcaBalances) { + const update = { + $set: { + 'services.tokenpass.tcaBalances': tcaBalances, + }, + }; + + return this.update(_id, update); + } + + getTokenBalancesByUserId(userId) { + const query = { + _id: userId, + }; + + const options = { + fields: { + 'services.tokenpass.tcaBalances': 1, + }, + }; + + return this.findOne(query, options); + } + roleBaseQuery(userId) { return { _id: userId }; } diff --git a/packages/rocketchat-tokenpass/server/index.js b/packages/rocketchat-tokenpass/server/index.js index f0d554955087..7530be6737d8 100644 --- a/packages/rocketchat-tokenpass/server/index.js +++ b/packages/rocketchat-tokenpass/server/index.js @@ -4,10 +4,6 @@ import './functions/getProtectedTokenpassBalances'; import './functions/getPublicTokenpassBalances'; import './functions/saveRoomTokensMinimumBalance'; import './functions/updateUserTokenpassBalances'; -import './models/indexes'; -import './models/Rooms'; -import './models/Subscriptions'; -import './models/Users'; import './methods/findTokenChannels'; import './methods/getChannelTokenpass'; import './cronRemoveUsers'; diff --git a/packages/rocketchat-tokenpass/server/models/Rooms.js b/packages/rocketchat-tokenpass/server/models/Rooms.js deleted file mode 100644 index bb7838a3965b..000000000000 --- a/packages/rocketchat-tokenpass/server/models/Rooms.js +++ /dev/null @@ -1,33 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Rooms.findByTokenpass = function(tokens) { - const query = { - 'tokenpass.tokens.token': { - $in: tokens, - }, - }; - - return this._db.find(query).fetch(); -}; - -RocketChat.models.Rooms.setTokensById = function(_id, tokens) { - const update = { - $set: { - 'tokenpass.tokens.token': tokens, - }, - }; - - return this.update({ _id }, update); -}; - -RocketChat.models.Rooms.findAllTokenChannels = function() { - const query = { - tokenpass: { $exists: true }, - }; - const options = { - fields: { - tokenpass: 1, - }, - }; - return this._db.find(query, options); -}; diff --git a/packages/rocketchat-tokenpass/server/models/Subscriptions.js b/packages/rocketchat-tokenpass/server/models/Subscriptions.js deleted file mode 100644 index be94296fd8b3..000000000000 --- a/packages/rocketchat-tokenpass/server/models/Subscriptions.js +++ /dev/null @@ -1,17 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Subscriptions.findByRoomIds = function(roomIds) { - const query = { - rid: { - $in: roomIds, - }, - }; - const options = { - fields: { - 'u._id': 1, - rid: 1, - }, - }; - - return this._db.find(query, options); -}; diff --git a/packages/rocketchat-tokenpass/server/models/Users.js b/packages/rocketchat-tokenpass/server/models/Users.js deleted file mode 100644 index 6f762ead3cb6..000000000000 --- a/packages/rocketchat-tokenpass/server/models/Users.js +++ /dev/null @@ -1,25 +0,0 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.models.Users.setTokenpassTcaBalances = function(_id, tcaBalances) { - const update = { - $set: { - 'services.tokenpass.tcaBalances': tcaBalances, - }, - }; - - return this.update(_id, update); -}; - -RocketChat.models.Users.getTokenBalancesByUserId = function(userId) { - const query = { - _id: userId, - }; - - const options = { - fields: { - 'services.tokenpass.tcaBalances': 1, - }, - }; - - return this.findOne(query, options); -}; diff --git a/packages/rocketchat-tokenpass/server/models/indexes.js b/packages/rocketchat-tokenpass/server/models/indexes.js deleted file mode 100644 index b56905ad50d6..000000000000 --- a/packages/rocketchat-tokenpass/server/models/indexes.js +++ /dev/null @@ -1,6 +0,0 @@ -import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; - -Meteor.startup(function() { - RocketChat.models.Rooms.tryEnsureIndex({ 'tokenpass.tokens.token': 1 }); -}); From 8169e2c9cba8b8601e1dcc2dd7534b1c846ba9ed Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 12:20:56 -0200 Subject: [PATCH 081/101] Remove dependency of RC namespace in rc-tokenpass --- .../rocketchat-tokenpass/client/roomType.js | 5 ++-- .../rocketchat-tokenpass/client/startup.js | 7 +++--- .../client/tokenChannelsList.js | 4 ++-- .../client/tokenpassChannelSettings.js | 5 ++-- packages/rocketchat-tokenpass/lib/common.js | 8 +++---- packages/rocketchat-tokenpass/package.js | 5 +++- .../rocketchat-tokenpass/server/Tokenpass.js | 4 +--- .../server/cronRemoveUsers.js | 23 +++++++++++-------- .../getProtectedTokenpassBalances.js | 6 ++--- .../functions/getPublicTokenpassBalances.js | 6 ++--- .../functions/saveRoomTokensMinimumBalance.js | 6 ++--- .../functions/updateUserTokenpassBalances.js | 12 ++++++---- packages/rocketchat-tokenpass/server/index.js | 4 ++-- .../server/methods/findTokenChannels.js | 7 +++--- .../server/methods/getChannelTokenpass.js | 4 ++-- .../rocketchat-tokenpass/server/startup.js | 21 ++++++++++------- 16 files changed, 69 insertions(+), 58 deletions(-) diff --git a/packages/rocketchat-tokenpass/client/roomType.js b/packages/rocketchat-tokenpass/client/roomType.js index 5d635e8b7184..c737c6067ee0 100644 --- a/packages/rocketchat-tokenpass/client/roomType.js +++ b/packages/rocketchat-tokenpass/client/roomType.js @@ -1,6 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RoomTypeConfig } from 'meteor/rocketchat:lib'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { roomTypes, RoomTypeConfig } from 'meteor/rocketchat:utils'; class TokenPassRoomType extends RoomTypeConfig { constructor() { @@ -20,4 +19,4 @@ class TokenPassRoomType extends RoomTypeConfig { } } -RocketChat.roomTypes.add(new TokenPassRoomType()); +roomTypes.add(new TokenPassRoomType()); diff --git a/packages/rocketchat-tokenpass/client/startup.js b/packages/rocketchat-tokenpass/client/startup.js index a622a2262d2a..f63e769fa775 100644 --- a/packages/rocketchat-tokenpass/client/startup.js +++ b/packages/rocketchat-tokenpass/client/startup.js @@ -1,14 +1,15 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { ChannelSettings } from 'meteor/rocketchat:channel-settings'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.startup(function() { - RocketChat.ChannelSettings.addOption({ + ChannelSettings.addOption({ group: ['room'], id: 'tokenpass', template: 'channelSettings__tokenpass', validation(data) { if (data && data.rid) { - const room = RocketChat.models.Rooms.findOne(data.rid, { fields: { tokenpass: 1 } }); + const room = Rooms.findOne(data.rid, { fields: { tokenpass: 1 } }); return room && room.tokenpass; } diff --git a/packages/rocketchat-tokenpass/client/tokenChannelsList.js b/packages/rocketchat-tokenpass/client/tokenChannelsList.js index cc4b8a963523..61511b5237d8 100644 --- a/packages/rocketchat-tokenpass/client/tokenChannelsList.js +++ b/packages/rocketchat-tokenpass/client/tokenChannelsList.js @@ -2,11 +2,11 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Subscriptions } from 'meteor/rocketchat:models'; Template.tokenChannelsList.helpers({ rooms() { - return Template.instance().tokenpassRooms.get().filter((room) => RocketChat.models.Subscriptions.find({ rid: room._id }).count() === 0); + return Template.instance().tokenpassRooms.get().filter((room) => Subscriptions.find({ rid: room._id }).count() === 0); }, }); diff --git a/packages/rocketchat-tokenpass/client/tokenpassChannelSettings.js b/packages/rocketchat-tokenpass/client/tokenpassChannelSettings.js index d8f66006f6f2..6e03c7b0978e 100644 --- a/packages/rocketchat-tokenpass/client/tokenpassChannelSettings.js +++ b/packages/rocketchat-tokenpass/client/tokenpassChannelSettings.js @@ -2,9 +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 { handleError } from 'meteor/rocketchat:lib'; -import { ChatRoom } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { ChatRoom } from 'meteor/rocketchat:ui-utils'; import toastr from 'toastr'; Template.channelSettings__tokenpass.helpers({ diff --git a/packages/rocketchat-tokenpass/lib/common.js b/packages/rocketchat-tokenpass/lib/common.js index d44b7c1e7bd7..5d4c5ad2818d 100644 --- a/packages/rocketchat-tokenpass/lib/common.js +++ b/packages/rocketchat-tokenpass/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 = { @@ -22,7 +22,7 @@ const Tokenpass = new CustomOAuth('tokenpass', config); if (Meteor.isServer) { Meteor.startup(function() { - RocketChat.settings.get('API_Tokenpass_URL', function(key, value) { + settings.get('API_Tokenpass_URL', function(key, value) { config.serverURL = value; Tokenpass.configure(config); }); @@ -30,8 +30,8 @@ if (Meteor.isServer) { } else { Meteor.startup(function() { Tracker.autorun(function() { - if (RocketChat.settings.get('API_Tokenpass_URL')) { - config.serverURL = RocketChat.settings.get('API_Tokenpass_URL'); + if (settings.get('API_Tokenpass_URL')) { + config.serverURL = settings.get('API_Tokenpass_URL'); Tokenpass.configure(config); } }); diff --git a/packages/rocketchat-tokenpass/package.js b/packages/rocketchat-tokenpass/package.js index 971d02779c83..3e5239a57951 100644 --- a/packages/rocketchat-tokenpass/package.js +++ b/packages/rocketchat-tokenpass/package.js @@ -13,7 +13,10 @@ Package.onUse(function(api) { 'templating', 'littledata:synced-cron', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:ui-utils', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:callbacks', 'rocketchat:authorization', 'rocketchat:custom-oauth', 'rocketchat:channel-settings', diff --git a/packages/rocketchat-tokenpass/server/Tokenpass.js b/packages/rocketchat-tokenpass/server/Tokenpass.js index b312b8842782..9a257990ba2f 100644 --- a/packages/rocketchat-tokenpass/server/Tokenpass.js +++ b/packages/rocketchat-tokenpass/server/Tokenpass.js @@ -1,6 +1,4 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.Tokenpass = { +export const Tokenpass = { validateAccess(tokenpass, balances) { const compFunc = tokenpass.require === 'any' ? 'some' : 'every'; return tokenpass.tokens[compFunc]((config) => balances.some((userToken) => config.token === userToken.asset && parseFloat(config.balance) <= parseFloat(userToken.balance))); diff --git a/packages/rocketchat-tokenpass/server/cronRemoveUsers.js b/packages/rocketchat-tokenpass/server/cronRemoveUsers.js index 4adfb2b89450..f80e42428525 100644 --- a/packages/rocketchat-tokenpass/server/cronRemoveUsers.js +++ b/packages/rocketchat-tokenpass/server/cronRemoveUsers.js @@ -1,17 +1,20 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms, Subscriptions, Users } from 'meteor/rocketchat:models'; import { SyncedCron } from 'meteor/littledata:synced-cron'; +import { updateUserTokenpassBalances } from './functions/updateUserTokenpassBalances'; +import { Tokenpass } from './Tokenpass'; -function removeUsersFromTokenChannels() { +async function removeUsersFromTokenChannels() { const rooms = {}; + const { removeUserFromRoom } = await import('meteor/rocketchat:lib'); - RocketChat.models.Rooms.findAllTokenChannels().forEach((room) => { + Rooms.findAllTokenChannels().forEach((room) => { rooms[room._id] = room.tokenpass; }); const users = {}; - RocketChat.models.Subscriptions.findByRoomIds(Object.keys(rooms)).forEach((sub) => { + Subscriptions.findByRoomIds(Object.keys(rooms)).forEach((sub) => { if (!users[sub.u._id]) { users[sub.u._id] = []; } @@ -19,16 +22,16 @@ function removeUsersFromTokenChannels() { }); Object.keys(users).forEach((user) => { - const userInfo = RocketChat.models.Users.findOneById(user); + const userInfo = Users.findOneById(user); if (userInfo && userInfo.services && userInfo.services.tokenpass) { - const balances = RocketChat.updateUserTokenpassBalances(userInfo); + const balances = updateUserTokenpassBalances(userInfo); users[user].forEach((roomId) => { - const valid = RocketChat.Tokenpass.validateAccess(rooms[roomId], balances); + const valid = Tokenpass.validateAccess(rooms[roomId], balances); if (!valid) { - RocketChat.removeUserFromRoom(roomId, userInfo); + removeUserFromRoom(roomId, userInfo); } }); } @@ -36,8 +39,8 @@ function removeUsersFromTokenChannels() { } Meteor.startup(function() { - Meteor.defer(function() { - removeUsersFromTokenChannels(); + Meteor.defer(async function() { + await removeUsersFromTokenChannels(); SyncedCron.add({ name: 'Remove users from Token Channels', diff --git a/packages/rocketchat-tokenpass/server/functions/getProtectedTokenpassBalances.js b/packages/rocketchat-tokenpass/server/functions/getProtectedTokenpassBalances.js index 9cff964a6abb..2d0eb0d571fd 100644 --- a/packages/rocketchat-tokenpass/server/functions/getProtectedTokenpassBalances.js +++ b/packages/rocketchat-tokenpass/server/functions/getProtectedTokenpassBalances.js @@ -1,14 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; let userAgent = 'Meteor'; if (Meteor.release) { userAgent += `/${ Meteor.release }`; } -RocketChat.getProtectedTokenpassBalances = function(accessToken) { +export const getProtectedTokenpassBalances = function(accessToken) { try { return HTTP.get( - `${ RocketChat.settings.get('API_Tokenpass_URL') }/api/v1/tca/protected/balances`, { + `${ settings.get('API_Tokenpass_URL') }/api/v1/tca/protected/balances`, { headers: { Accept: 'application/json', 'User-Agent': userAgent, diff --git a/packages/rocketchat-tokenpass/server/functions/getPublicTokenpassBalances.js b/packages/rocketchat-tokenpass/server/functions/getPublicTokenpassBalances.js index bd721175c7fe..e13a349008c1 100644 --- a/packages/rocketchat-tokenpass/server/functions/getPublicTokenpassBalances.js +++ b/packages/rocketchat-tokenpass/server/functions/getPublicTokenpassBalances.js @@ -1,14 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; let userAgent = 'Meteor'; if (Meteor.release) { userAgent += `/${ Meteor.release }`; } -RocketChat.getPublicTokenpassBalances = function(accessToken) { +export const getPublicTokenpassBalances = function(accessToken) { try { return HTTP.get( - `${ RocketChat.settings.get('API_Tokenpass_URL') }/api/v1/tca/public/balances`, { + `${ settings.get('API_Tokenpass_URL') }/api/v1/tca/public/balances`, { headers: { Accept: 'application/json', 'User-Agent': userAgent, diff --git a/packages/rocketchat-tokenpass/server/functions/saveRoomTokensMinimumBalance.js b/packages/rocketchat-tokenpass/server/functions/saveRoomTokensMinimumBalance.js index 8d10039966d1..ecab7502cf0c 100644 --- a/packages/rocketchat-tokenpass/server/functions/saveRoomTokensMinimumBalance.js +++ b/packages/rocketchat-tokenpass/server/functions/saveRoomTokensMinimumBalance.js @@ -1,9 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { Match } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; import s from 'underscore.string'; -RocketChat.saveRoomTokensMinimumBalance = function(rid, roomTokensMinimumBalance) { +export const saveRoomTokensMinimumBalance = function(rid, roomTokensMinimumBalance) { if (!Match.test(rid, String)) { throw new Meteor.Error('invalid-room', 'Invalid room', { function: 'RocketChat.saveRoomTokensMinimumBalance', @@ -12,5 +12,5 @@ RocketChat.saveRoomTokensMinimumBalance = function(rid, roomTokensMinimumBalance const minimumTokenBalance = parseFloat(s.escapeHTML(roomTokensMinimumBalance)); - return RocketChat.models.Rooms.setMinimumTokenBalanceById(rid, minimumTokenBalance); + return Rooms.setMinimumTokenBalanceById(rid, minimumTokenBalance); }; diff --git a/packages/rocketchat-tokenpass/server/functions/updateUserTokenpassBalances.js b/packages/rocketchat-tokenpass/server/functions/updateUserTokenpassBalances.js index 50698464156d..c72a1beb975a 100644 --- a/packages/rocketchat-tokenpass/server/functions/updateUserTokenpassBalances.js +++ b/packages/rocketchat-tokenpass/server/functions/updateUserTokenpassBalances.js @@ -1,14 +1,16 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; +import { getPublicTokenpassBalances } from './getPublicTokenpassBalances'; +import { getProtectedTokenpassBalances } from './getProtectedTokenpassBalances'; import _ from 'underscore'; -RocketChat.updateUserTokenpassBalances = function(user) { +export const updateUserTokenpassBalances = function(user) { if (user && user.services && user.services.tokenpass) { - const tcaPublicBalances = RocketChat.getPublicTokenpassBalances(user.services.tokenpass.accessToken); - const tcaProtectedBalances = RocketChat.getProtectedTokenpassBalances(user.services.tokenpass.accessToken); + const tcaPublicBalances = getPublicTokenpassBalances(user.services.tokenpass.accessToken); + const tcaProtectedBalances = getProtectedTokenpassBalances(user.services.tokenpass.accessToken); const balances = _.uniq(_.union(tcaPublicBalances, tcaProtectedBalances), false, (item) => item.asset); - RocketChat.models.Users.setTokenpassTcaBalances(user._id, balances); + Users.setTokenpassTcaBalances(user._id, balances); return balances; } diff --git a/packages/rocketchat-tokenpass/server/index.js b/packages/rocketchat-tokenpass/server/index.js index 7530be6737d8..98577e23a026 100644 --- a/packages/rocketchat-tokenpass/server/index.js +++ b/packages/rocketchat-tokenpass/server/index.js @@ -3,8 +3,8 @@ import './startup'; import './functions/getProtectedTokenpassBalances'; import './functions/getPublicTokenpassBalances'; import './functions/saveRoomTokensMinimumBalance'; -import './functions/updateUserTokenpassBalances'; +export { updateUserTokenpassBalances } from './functions/updateUserTokenpassBalances'; import './methods/findTokenChannels'; import './methods/getChannelTokenpass'; import './cronRemoveUsers'; -import './Tokenpass'; +export { Tokenpass } from './Tokenpass'; diff --git a/packages/rocketchat-tokenpass/server/methods/findTokenChannels.js b/packages/rocketchat-tokenpass/server/methods/findTokenChannels.js index 90ae938c7ec3..46f7376fad9c 100644 --- a/packages/rocketchat-tokenpass/server/methods/findTokenChannels.js +++ b/packages/rocketchat-tokenpass/server/methods/findTokenChannels.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; +import { Tokenpass } from '../Tokenpass'; Meteor.methods({ findTokenChannels() { @@ -15,8 +16,8 @@ Meteor.methods({ tokens[token.asset] = 1; }); - return RocketChat.models.Rooms.findByTokenpass(Object.keys(tokens)) - .filter((room) => RocketChat.Tokenpass.validateAccess(room.tokenpass, user.services.tokenpass.tcaBalances)); + return Rooms.findByTokenpass(Object.keys(tokens)) + .filter((room) => Tokenpass.validateAccess(room.tokenpass, user.services.tokenpass.tcaBalances)); } return []; diff --git a/packages/rocketchat-tokenpass/server/methods/getChannelTokenpass.js b/packages/rocketchat-tokenpass/server/methods/getChannelTokenpass.js index 1dad36c89122..80e87c122127 100644 --- a/packages/rocketchat-tokenpass/server/methods/getChannelTokenpass.js +++ b/packages/rocketchat-tokenpass/server/methods/getChannelTokenpass.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Rooms } from 'meteor/rocketchat:models'; Meteor.methods({ getChannelTokenpass(rid) { @@ -10,7 +10,7 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getChannelTokenpass' }); } - const room = RocketChat.models.Rooms.findOneById(rid); + const room = Rooms.findOneById(rid); if (!room) { throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'getChannelTokenpass' }); diff --git a/packages/rocketchat-tokenpass/server/startup.js b/packages/rocketchat-tokenpass/server/startup.js index 24499014cd78..94debabba752 100644 --- a/packages/rocketchat-tokenpass/server/startup.js +++ b/packages/rocketchat-tokenpass/server/startup.js @@ -1,8 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; -import { RocketChat } from 'meteor/rocketchat:lib'; - -RocketChat.settings.addGroup('OAuth', function() { +import { settings } from 'meteor/rocketchat:settings'; +import { addRoomAccessValidator } from 'meteor/rocketchat:authorization'; +import { Users } from 'meteor/rocketchat:models'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { updateUserTokenpassBalances } from './functions/updateUserTokenpassBalances'; +import { Tokenpass } from './Tokenpass'; + +settings.addGroup('OAuth', function() { this.section('Tokenpass', function() { const enableQuery = { _id: 'Accounts_OAuth_Tokenpass', @@ -22,21 +27,21 @@ function validateTokenAccess(userData, roomData) { return false; } - return RocketChat.Tokenpass.validateAccess(roomData.tokenpass, userData.services.tokenpass.tcaBalances); + return Tokenpass.validateAccess(roomData.tokenpass, userData.services.tokenpass.tcaBalances); } Meteor.startup(function() { - RocketChat.authz.addRoomAccessValidator(function(room, user) { + addRoomAccessValidator(function(room, user) { if (!room || !room.tokenpass || !user) { return false; } - const userData = RocketChat.models.Users.getTokenBalancesByUserId(user._id); + const userData = Users.getTokenBalancesByUserId(user._id); return validateTokenAccess(userData, room); }); - RocketChat.callbacks.add('beforeJoinRoom', function(user, room) { + callbacks.add('beforeJoinRoom', function(user, room) { if (room.tokenpass && !validateTokenAccess(user, room)) { throw new Meteor.Error('error-not-allowed', 'Token required', { method: 'joinRoom' }); } @@ -47,6 +52,6 @@ Meteor.startup(function() { Accounts.onLogin(function({ user }) { if (user && user.services && user.services.tokenpass) { - RocketChat.updateUserTokenpassBalances(user); + updateUserTokenpassBalances(user); } }); From dfeab9f5a7c370579bf1075de677a4ae8abf56d4 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 12:21:19 -0200 Subject: [PATCH 082/101] import tokenpass inside rc-lib --- packages/rocketchat-lib/package.js | 1 + packages/rocketchat-lib/server/methods/joinRoom.js | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index c29baddb4e19..7bb4f409febb 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -56,6 +56,7 @@ Package.onUse(function(api) { api.use('rocketchat:assets'); api.use('rocketchat:markdown'); api.use('rocketchat:channel-settings'); + api.use('rocketchat:tokenpass'); api.use('templating', 'client'); api.use('kadira:flow-router'); diff --git a/packages/rocketchat-lib/server/methods/joinRoom.js b/packages/rocketchat-lib/server/methods/joinRoom.js index 56e1fcbb46d5..b6dd4bb37e85 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 { Tokenpass, updateUserTokenpassBalances } from 'meteor/rocketchat:tokenpass'; import { addUserToRoom } from '../functions'; Meteor.methods({ @@ -21,9 +22,9 @@ Meteor.methods({ // TODO we should have a 'beforeJoinRoom' call back so external services can do their own validations const user = Meteor.user(); if (room.tokenpass && user && user.services && user.services.tokenpass) { - const balances = RocketChat.updateUserTokenpassBalances(user); + const balances = updateUserTokenpassBalances(user); - if (!RocketChat.Tokenpass.validateAccess(room.tokenpass, balances)) { + if (!Tokenpass.validateAccess(room.tokenpass, balances)) { throw new Meteor.Error('error-not-allowed', 'Token required', { method: 'joinRoom' }); } } else { From 7e7752cc53eeb8190f0319acbf0055bea791eef9 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 12:40:29 -0200 Subject: [PATCH 083/101] Remove dependency of RC namespace in rc-ui --- packages/rocketchat-ui/client/components/header/header.js | 8 +++++--- packages/rocketchat-ui/package.js | 2 ++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/rocketchat-ui/client/components/header/header.js b/packages/rocketchat-ui/client/components/header/header.js index 6ec8219ef4c0..2eb8566e9220 100644 --- a/packages/rocketchat-ui/client/components/header/header.js +++ b/packages/rocketchat-ui/client/components/header/header.js @@ -4,6 +4,8 @@ import { Template } from 'meteor/templating'; import { t, roomTypes, handleError } from 'meteor/rocketchat:utils'; import { TabBar, fireGlobalEvent } from 'meteor/rocketchat:ui-utils'; import { ChatSubscription, Rooms } from 'meteor/rocketchat:models'; +import { Markdown } from 'meteor/rocketchat:markdown'; +import { emoji } from 'meteor/rocketchat:emoji'; import { settings } from 'meteor/rocketchat:settings'; const isSubscribed = (_id) => ChatSubscription.find({ rid: _id }).count() > 0; @@ -62,13 +64,13 @@ Template.header.helpers({ const roomData = Session.get(`roomData${ this._id }`); if (!roomData || !roomData.topic) { return ''; } - let roomTopic = RocketChat.Markdown.parse(roomData.topic); + let roomTopic = Markdown.parse(roomData.topic); // ' to apostrophe (') for emojis such as :') roomTopic = roomTopic.replace(/'/g, '\''); - Object.keys(RocketChat.emoji.packages).forEach((emojiPackage) => { - roomTopic = RocketChat.emoji.packages[emojiPackage].render(roomTopic); + Object.keys(emoji.packages).forEach((emojiPackage) => { + roomTopic = emoji.packages[emojiPackage].render(roomTopic); }); // apostrophe (') back to ' diff --git a/packages/rocketchat-ui/package.js b/packages/rocketchat-ui/package.js index 7f3ad27a60e2..7af0cd23ce2f 100644 --- a/packages/rocketchat-ui/package.js +++ b/packages/rocketchat-ui/package.js @@ -36,6 +36,8 @@ Package.onUse(function(api) { 'rocketchat:file-upload', 'konecty:user-presence', 'rocketchat:webrtc', + 'rocketchat:markdown', + 'rocketchat:emoji', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); From c9e2c01df9b099fe0a3ffafdc076f8a95405840a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 12:55:52 -0200 Subject: [PATCH 084/101] Move webdavAccounts models to rc-model --- packages/rocketchat-models/client/index.js | 2 ++ packages/rocketchat-models/client/models/WebdavAccounts.js | 3 +++ .../rocketchat-webdav/client/collections/WebdavAccounts.js | 4 ++-- 3 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 packages/rocketchat-models/client/models/WebdavAccounts.js diff --git a/packages/rocketchat-models/client/index.js b/packages/rocketchat-models/client/index.js index 0185653df2e1..a990bd5fc082 100644 --- a/packages/rocketchat-models/client/index.js +++ b/packages/rocketchat-models/client/index.js @@ -17,6 +17,7 @@ import { RoomRoles } from './models/RoomRoles'; import { UserAndRoom } from './models/UserAndRoom'; import { UserRoles } from './models/UserRoles'; import { AuthzCachedCollection, ChatPermissions } from './models/ChatPermissions'; +import { WebdavAccounts } from './models/WebdavAccounts'; import CustomSounds from './models/CustomSounds'; import EmojiCustom from './models/EmojiCustom'; import _ from 'underscore'; @@ -51,4 +52,5 @@ export { Rooms, CustomSounds, EmojiCustom, + WebdavAccounts, }; diff --git a/packages/rocketchat-models/client/models/WebdavAccounts.js b/packages/rocketchat-models/client/models/WebdavAccounts.js new file mode 100644 index 000000000000..fafe9bf792d0 --- /dev/null +++ b/packages/rocketchat-models/client/models/WebdavAccounts.js @@ -0,0 +1,3 @@ +import { Mongo } from 'meteor/mongo'; + +export const WebdavAccounts = new Mongo.Collection('rocketchat_webdav_accounts'); diff --git a/packages/rocketchat-webdav/client/collections/WebdavAccounts.js b/packages/rocketchat-webdav/client/collections/WebdavAccounts.js index 831bfb51a00e..4e35e772f4cc 100644 --- a/packages/rocketchat-webdav/client/collections/WebdavAccounts.js +++ b/packages/rocketchat-webdav/client/collections/WebdavAccounts.js @@ -1,4 +1,4 @@ import { RocketChat } from 'meteor/rocketchat:lib'; -import { Mongo } from 'meteor/mongo'; +import { WebdavAccounts } from 'meteor/rocketchat:models'; -RocketChat.models.WebdavAccounts = new Mongo.Collection('rocketchat_webdav_accounts'); +RocketChat.models.WebdavAccounts = WebdavAccounts; From 62e65420144fbfca7d78cab9b1123e1dca159111 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 12:57:24 -0200 Subject: [PATCH 085/101] Remove dependency of RC namespace in rc-ui-account --- .../rocketchat-ui-account/client/account.js | 2 +- .../client/accountFlex.js | 15 +++--- .../client/accountIntegrations.js | 6 +-- .../client/accountPreferences.js | 52 ++++++++++--------- .../client/accountProfile.js | 48 +++++++++-------- .../client/avatar/prompt.js | 19 +++---- packages/rocketchat-ui-account/package.js | 6 +++ 7 files changed, 80 insertions(+), 68 deletions(-) diff --git a/packages/rocketchat-ui-account/client/account.js b/packages/rocketchat-ui-account/client/account.js index 5f95f6e508fd..eb58eb9d528e 100644 --- a/packages/rocketchat-ui-account/client/account.js +++ b/packages/rocketchat-ui-account/client/account.js @@ -1,6 +1,6 @@ import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { SideNav } from 'meteor/rocketchat:ui-utils'; Template.account.onRendered(function() { Tracker.afterFlush(function() { diff --git a/packages/rocketchat-ui-account/client/accountFlex.js b/packages/rocketchat-ui-account/client/accountFlex.js index 31d2794b9f5b..3b0bbf5322b1 100644 --- a/packages/rocketchat-ui-account/client/accountFlex.js +++ b/packages/rocketchat-ui-account/client/accountFlex.js @@ -1,6 +1,7 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { SideNav, Layout } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; Template.accountFlex.events({ @@ -15,16 +16,16 @@ Template.accountFlex.events({ Template.accountFlex.helpers({ allowUserProfileChange() { - return RocketChat.settings.get('Accounts_AllowUserProfileChange'); + return settings.get('Accounts_AllowUserProfileChange'); }, accessTokensEnabled() { - return RocketChat.authz.hasAllPermission(['create-personal-access-tokens']); + return hasAllPermission(['create-personal-access-tokens']); }, encryptionEnabled() { - return RocketChat.settings.get('E2E_Enable'); + return settings.get('E2E_Enable'); }, webdavIntegrationEnabled() { - return RocketChat.settings.get('Webdav_Integration_Enabled'); + return settings.get('Webdav_Integration_Enabled'); }, menuItem(name, icon, section, group) { return { @@ -36,6 +37,6 @@ Template.accountFlex.helpers({ }; }, embeddedVersion() { - return RocketChat.Layout.isEmbedded(); + return Layout.isEmbedded(); }, }); diff --git a/packages/rocketchat-ui-account/client/accountIntegrations.js b/packages/rocketchat-ui-account/client/accountIntegrations.js index 803c84b20d48..f7c4fc5503cc 100644 --- a/packages/rocketchat-ui-account/client/accountIntegrations.js +++ b/packages/rocketchat-ui-account/client/accountIntegrations.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; +import { WebdavAccounts } from 'meteor/rocketchat:models'; +import { modal } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; Template.accountIntegrations.helpers({ webdavAccounts() { - return RocketChat.models.WebdavAccounts.find().fetch(); + return WebdavAccounts.find().fetch(); }, getOptionValue(account) { return account.name || `${ account.username }@${ account.server_url.replace(/^https?\:\/\//i, '') }`; diff --git a/packages/rocketchat-ui-account/client/accountPreferences.js b/packages/rocketchat-ui-account/client/accountPreferences.js index f4488972b5be..4ead30874ad5 100644 --- a/packages/rocketchat-ui-account/client/accountPreferences.js +++ b/packages/rocketchat-ui-account/client/accountPreferences.js @@ -4,9 +4,11 @@ import { Tracker } from 'meteor/tracker'; import { Reload } from 'meteor/reload'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal, SideNav, KonchatNotification } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { t, handleError, getUserPreference } from 'meteor/rocketchat:utils'; +import { modal, SideNav } from 'meteor/rocketchat:ui-utils'; +import { KonchatNotification } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { CustomSounds } from 'meteor/rocketchat:custom-sounds'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -26,21 +28,21 @@ function checkedSelected(property, value, defaultValue = undefined) { if (defaultValue && defaultValue.hash) { defaultValue = undefined; } - return RocketChat.getUserPreference(Meteor.userId(), property, defaultValue) === value; + return getUserPreference(Meteor.userId(), property, defaultValue) === value; } Template.accountPreferences.helpers({ audioAssets() { - return (RocketChat.CustomSounds && RocketChat.CustomSounds.getList && RocketChat.CustomSounds.getList()) || []; + return (CustomSounds && CustomSounds.getList && CustomSounds.getList()) || []; }, newMessageNotification() { - return RocketChat.getUserPreference(Meteor.userId(), 'newMessageNotification'); + return getUserPreference(Meteor.userId(), 'newMessageNotification'); }, newRoomNotification() { - return RocketChat.getUserPreference(Meteor.userId(), 'newRoomNotification'); + return getUserPreference(Meteor.userId(), 'newRoomNotification'); }, muteFocusedConversations() { - return RocketChat.getUserPreference(Meteor.userId(), 'muteFocusedConversations'); + return getUserPreference(Meteor.userId(), 'muteFocusedConversations'); }, languages() { const languages = TAPi18n.getLanguages(); @@ -68,7 +70,7 @@ Template.accountPreferences.helpers({ return checkedSelected(property, value, defaultValue); }, highlights() { - const userHighlights = RocketChat.getUserPreference(Meteor.userId(), 'highlights'); + const userHighlights = getUserPreference(Meteor.userId(), 'highlights'); return userHighlights ? userHighlights.join(',\n') : undefined; }, desktopNotificationEnabled() { @@ -78,38 +80,38 @@ Template.accountPreferences.helpers({ return KonchatNotification.notificationStatus.get() === 'denied' || (window.Notification && Notification.permission === 'denied'); }, desktopNotificationDuration() { - const userPref = RocketChat.getUserPreference(Meteor.userId(), 'desktopNotificationDuration', 'undefined'); + const userPref = getUserPreference(Meteor.userId(), 'desktopNotificationDuration', 'undefined'); return userPref !== 'undefined' ? userPref : undefined; }, defaultDesktopNotificationDuration() { - return RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration'); + return settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration'); }, idleTimeLimit() { - return RocketChat.getUserPreference(Meteor.userId(), 'idleTimeLimit'); + return getUserPreference(Meteor.userId(), 'idleTimeLimit'); }, defaultIdleTimeLimit() { - return RocketChat.settings.get('Accounts_Default_User_Preferences_idleTimeLimit'); + return settings.get('Accounts_Default_User_Preferences_idleTimeLimit'); }, defaultDesktopNotification() { - return notificationLabels[RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotifications')]; + return notificationLabels[settings.get('Accounts_Default_User_Preferences_desktopNotifications')]; }, defaultMobileNotification() { - return notificationLabels[RocketChat.settings.get('Accounts_Default_User_Preferences_mobileNotifications')]; + return notificationLabels[settings.get('Accounts_Default_User_Preferences_mobileNotifications')]; }, defaultEmailNotification() { - return emailLabels[RocketChat.settings.get('Accounts_Default_User_Preferences_emailNotificationMode')]; + return emailLabels[settings.get('Accounts_Default_User_Preferences_emailNotificationMode')]; }, showRoles() { - return RocketChat.settings.get('UI_DisplayRoles'); + return settings.get('UI_DisplayRoles'); }, userDataDownloadEnabled() { - return RocketChat.settings.get('UserData_EnableDownload') !== false; + return settings.get('UserData_EnableDownload') !== false; }, notificationsSoundVolume() { - return RocketChat.getUserPreference(Meteor.userId(), 'notificationsSoundVolume'); + return getUserPreference(Meteor.userId(), 'notificationsSoundVolume'); }, dontAskAgainList() { - return RocketChat.getUserPreference(Meteor.userId(), 'dontAskAgainList'); + return getUserPreference(Meteor.userId(), 'dontAskAgainList'); }, }); @@ -122,7 +124,7 @@ Template.accountPreferences.onCreated(function() { settingsTemplate.child.push(this); - this.useEmojis = new ReactiveVar(RocketChat.getUserPreference(Meteor.userId(), 'useEmojis')); + this.useEmojis = new ReactiveVar(getUserPreference(Meteor.userId(), 'useEmojis')); let instance = this; @@ -161,7 +163,7 @@ Template.accountPreferences.onCreated(function() { data.sendOnEnter = $('#sendOnEnter').find('select').val(); data.autoImageLoad = JSON.parse($('input[name=autoImageLoad]:checked').val()); data.emailNotificationMode = $('select[name=emailNotificationMode]').val(); - data.desktopNotificationDuration = $('input[name=desktopNotificationDuration]').val() === '' ? RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration') : parseInt($('input[name=desktopNotificationDuration]').val()); + data.desktopNotificationDuration = $('input[name=desktopNotificationDuration]').val() === '' ? settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration') : parseInt($('input[name=desktopNotificationDuration]').val()); data.desktopNotifications = $('#desktopNotifications').find('select').val(); data.mobileNotifications = $('#mobileNotifications').find('select').val(); data.unreadAlert = JSON.parse($('#unreadAlert').find('input:checked').val()); @@ -174,12 +176,12 @@ Template.accountPreferences.onCreated(function() { let reload = false; - if (RocketChat.settings.get('UI_DisplayRoles')) { + if (settings.get('UI_DisplayRoles')) { data.hideRoles = JSON.parse($('#hideRoles').find('input:checked').val()); } // if highlights changed we need page reload - const highlights = RocketChat.getUserPreference(Meteor.userId(), 'highlights'); + const highlights = getUserPreference(Meteor.userId(), 'highlights'); if (highlights && highlights.join('\n') !== data.highlights.join('\n')) { reload = true; } @@ -198,7 +200,7 @@ Template.accountPreferences.onCreated(function() { reload = true; } - const idleTimeLimit = $('input[name=idleTimeLimit]').val() === '' ? RocketChat.settings.get('Accounts_Default_User_Preferences_idleTimeLimit') : parseInt($('input[name=idleTimeLimit]').val()); + const idleTimeLimit = $('input[name=idleTimeLimit]').val() === '' ? settings.get('Accounts_Default_User_Preferences_idleTimeLimit') : parseInt($('input[name=idleTimeLimit]').val()); data.idleTimeLimit = idleTimeLimit; if (this.shouldUpdateLocalStorageSetting('idleTimeLimit', idleTimeLimit)) { localStorage.setItem('idleTimeLimit', idleTimeLimit); diff --git a/packages/rocketchat-ui-account/client/accountProfile.js b/packages/rocketchat-ui-account/client/accountProfile.js index ddb1ea964b3c..d189dff7f22f 100644 --- a/packages/rocketchat-ui-account/client/accountProfile.js +++ b/packages/rocketchat-ui-account/client/accountProfile.js @@ -4,16 +4,18 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal, SideNav } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { modal, SideNav } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; const validateEmail = (email) => /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email); const validateUsername = (username) => { - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return reg.test(username); }; const validateName = (name) => name && name.length; @@ -26,7 +28,7 @@ const validatePassword = (password, confirmationPassword) => { }; 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(' ', '')].filter((f) => reg.test(f)).join(''); }; const filterEmail = (old) => old.replace(' ', ''); @@ -83,7 +85,7 @@ Template.accountProfile.helpers({ return Object.keys(suggestions.avatars).map((service) => ({ name: service, // TODO: improve this fix - service: !suggestions.avatars[service.toLowerCase()] ? RocketChat.settings.get(`Accounts_OAuth_${ s.capitalize(service.toLowerCase()) }`) : false, + service: !suggestions.avatars[service.toLowerCase()] ? settings.get(`Accounts_OAuth_${ s.capitalize(service.toLowerCase()) }`) : false, suggestion: suggestions.avatars[service.toLowerCase()], })) .filter(({ service, suggestion }) => service || suggestion); @@ -133,7 +135,7 @@ Template.accountProfile.helpers({ return; }, allowDeleteOwnAccount() { - return RocketChat.settings.get('Accounts_AllowDeleteOwnAccount'); + return settings.get('Accounts_AllowDeleteOwnAccount'); }, realname() { return Meteor.user().name; @@ -150,23 +152,23 @@ Template.accountProfile.helpers({ return isUserEmailVerified(user); }, allowRealNameChange() { - return RocketChat.settings.get('Accounts_AllowRealNameChange'); + return settings.get('Accounts_AllowRealNameChange'); }, allowUsernameChange() { - return RocketChat.settings.get('Accounts_AllowUsernameChange') && RocketChat.settings.get('LDAP_Enable') !== true; + return settings.get('Accounts_AllowUsernameChange') && settings.get('LDAP_Enable') !== true; }, allowEmailChange() { - return RocketChat.settings.get('Accounts_AllowEmailChange'); + return settings.get('Accounts_AllowEmailChange'); }, allowPasswordChange() { - return RocketChat.settings.get('Accounts_AllowPasswordChange'); + return settings.get('Accounts_AllowPasswordChange'); }, canConfirmNewPassword() { const password = Template.instance().password.get(); - return RocketChat.settings.get('Accounts_AllowPasswordChange') && password && password !== ''; + return settings.get('Accounts_AllowPasswordChange') && password && password !== ''; }, allowAvatarChange() { - return RocketChat.settings.get('Accounts_AllowUserAvatarChange'); + return settings.get('Accounts_AllowUserAvatarChange'); }, customFields() { return Meteor.user().customFields; @@ -187,7 +189,7 @@ Template.accountProfile.onCreated(function() { self.url = new ReactiveVar(''); self.usernameAvaliable = new ReactiveVar(true); - RocketChat.Notifications.onLogged('updateAvatar', () => self.avatar.set()); + Notifications.onLogged('updateAvatar', () => self.avatar.set()); self.getSuggestions = function() { self.suggestions.set(undefined); Meteor.call('getAvatarSuggestion', function(error, avatars) { @@ -207,7 +209,7 @@ Template.accountProfile.onCreated(function() { const instance = this; if (!newPassword) { return callback(); - } else if (!RocketChat.settings.get('Accounts_AllowPasswordChange')) { + } else if (!settings.get('Accounts_AllowPasswordChange')) { toastr.remove(); toastr.error(t('Password_Change_Disabled')); instance.clearForm(); @@ -229,7 +231,7 @@ Template.accountProfile.onCreated(function() { })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', avatar.service); + callbacks.run('userAvatarSet', avatar.service); } }); } @@ -239,11 +241,11 @@ Template.accountProfile.onCreated(function() { if (typedPassword) { data.typedPassword = typedPassword; } - if (s.trim(self.password.get()) && RocketChat.settings.get('Accounts_AllowPasswordChange')) { + if (s.trim(self.password.get()) && settings.get('Accounts_AllowPasswordChange')) { data.newPassword = self.password.get(); } if (s.trim(self.realname.get()) !== user.name) { - if (!RocketChat.settings.get('Accounts_AllowRealNameChange')) { + if (!settings.get('Accounts_AllowRealNameChange')) { toastr.remove(); toastr.error(t('RealName_Change_Disabled')); instance.clearForm(); @@ -253,7 +255,7 @@ Template.accountProfile.onCreated(function() { } } if (s.trim(self.username.get()) !== user.username) { - if (!RocketChat.settings.get('Accounts_AllowUsernameChange')) { + if (!settings.get('Accounts_AllowUsernameChange')) { toastr.remove(); toastr.error(t('Username_Change_Disabled')); instance.clearForm(); @@ -263,7 +265,7 @@ Template.accountProfile.onCreated(function() { } } if (s.trim(self.email.get()) !== getUserEmailAddress(user)) { - if (!RocketChat.settings.get('Accounts_AllowEmailChange')) { + if (!settings.get('Accounts_AllowEmailChange')) { toastr.remove(); toastr.error(t('Email_Change_Disabled')); instance.clearForm(); @@ -299,7 +301,7 @@ Template.accountProfile.onCreated(function() { Template.accountProfile.onRendered(function() { Tracker.afterFlush(() => { - if (!RocketChat.settings.get('Accounts_AllowUserProfileChange')) { + if (!settings.get('Accounts_AllowUserProfileChange')) { FlowRouter.go('home'); } this.clearForm(); @@ -326,7 +328,7 @@ Template.accountProfile.events({ })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', 'initials'); + callbacks.run('userAvatarSet', 'initials'); } }); }, @@ -527,7 +529,7 @@ Template.accountProfile.events({ contentType: blob.type, blob: reader.result, }); - RocketChat.callbacks.run('userAvatarSet', 'upload'); + callbacks.run('userAvatarSet', 'upload'); }; }); }, diff --git a/packages/rocketchat-ui-account/client/avatar/prompt.js b/packages/rocketchat-ui-account/client/avatar/prompt.js index db53a5a25a11..3089651357c9 100644 --- a/packages/rocketchat-ui-account/client/avatar/prompt.js +++ b/packages/rocketchat-ui-account/client/avatar/prompt.js @@ -3,8 +3,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { SideNav } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import { fileUploadHandler } from 'meteor/rocketchat:file-upload'; import s from 'underscore.string'; @@ -26,7 +27,7 @@ Template.avatarPrompt.onCreated(function() { Template.avatarPrompt.onRendered(function() { Tracker.afterFlush(function() { - if (!RocketChat.settings.get('Accounts_AllowUserAvatarChange')) { + if (!settings.get('Accounts_AllowUserAvatarChange')) { FlowRouter.go('home'); } SideNav.setFlex('accountFlex'); @@ -40,7 +41,7 @@ Template.avatarPrompt.helpers({ }, suggestAvatar(service) { const suggestions = Template.instance().suggestions.get(); - return RocketChat.settings.get(`Accounts_OAuth_${ s.capitalize(service) }`) && !suggestions.avatars[service]; + return settings.get(`Accounts_OAuth_${ s.capitalize(service) }`) && !suggestions.avatars[service]; }, upload() { return Template.instance().upload.get(); @@ -65,7 +66,7 @@ Template.avatarPrompt.events({ })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', 'initials'); + callbacks.run('userAvatarSet', 'initials'); } }); } else if (this.service === 'url') { @@ -81,7 +82,7 @@ Template.avatarPrompt.events({ } } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', 'url'); + callbacks.run('userAvatarSet', 'url'); } }); } else { @@ -113,7 +114,7 @@ Template.avatarPrompt.events({ upload.start((error, result) => { if (result) { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', this.service); + callbacks.run('userAvatarSet', this.service); } }); } else { @@ -125,7 +126,7 @@ Template.avatarPrompt.events({ })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', tmpService); + callbacks.run('userAvatarSet', tmpService); } }); } @@ -163,7 +164,7 @@ Template.avatarPrompt.events({ contentType: blob.type, blob: reader.result, }); - RocketChat.callbacks.run('userAvatarSet', 'upload'); + callbacks.run('userAvatarSet', 'upload'); }; }); }, diff --git a/packages/rocketchat-ui-account/package.js b/packages/rocketchat-ui-account/package.js index 082dece03b28..822204bc47ea 100644 --- a/packages/rocketchat-ui-account/package.js +++ b/packages/rocketchat-ui-account/package.js @@ -17,6 +17,12 @@ Package.onUse(function(api) { 'rocketchat:lib', 'sha', 'rocketchat:utils', + 'rocketchat:custom-sounds', + 'rocketchat:authorization', + 'rocketchat:settings', + 'rocketchat:notifications', + 'rocketchat:callbacks', + 'rocketchat:ui-utils', 'rocketchat:lazy-load', 'rocketchat:file-upload', ]); From 2432e9a6f9716d74316be7be8ae11430fc85232a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 14:32:31 -0200 Subject: [PATCH 086/101] Remove dependency of RC namespace in rc-ui-admin --- packages/rocketchat-ui-admin/client/admin.js | 69 +++++++++---------- .../rocketchat-ui-admin/client/adminFlex.js | 21 +++--- .../rocketchat-ui-admin/client/adminInfo.js | 11 +-- .../client/rooms/adminRoomInfo.js | 32 +++++---- .../client/rooms/adminRooms.js | 17 ++--- .../client/rooms/channelSettingsDefault.js | 3 +- .../client/users/adminInviteUser.js | 6 +- .../client/users/adminUsers.js | 9 ++- packages/rocketchat-ui-admin/package.js | 8 ++- .../server/publications/adminRooms.js | 11 +-- 10 files changed, 98 insertions(+), 89 deletions(-) diff --git a/packages/rocketchat-ui-admin/client/admin.js b/packages/rocketchat-ui-admin/client/admin.js index c5f17ab6d066..b9210bc0319f 100644 --- a/packages/rocketchat-ui-admin/client/admin.js +++ b/packages/rocketchat-ui-admin/client/admin.js @@ -6,19 +6,18 @@ import { Tracker } from 'meteor/tracker'; 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 { SideNav, modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { SideNav, modal } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { CachedCollection } from 'meteor/rocketchat:ui-cached-collection'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; const TempSettings = new Mongo.Collection(null); -RocketChat.TempSettings = TempSettings; - const getDefaultSetting = function(settingId) { - return RocketChat.settings.collectionPrivate.findOne({ + return settings.collectionPrivate.findOne({ _id: settingId, }); }; @@ -41,7 +40,7 @@ const setFieldValue = function(settingId, value, type, editor) { const selectedRooms = Template.instance().selectedRooms.get(); selectedRooms[settingId] = value; Template.instance().selectedRooms.set(selectedRooms); - TempSettings.update({ _id: settingId }, { $set: { value, changed: JSON.stringify(RocketChat.settings.collectionPrivate.findOne(settingId).value) !== JSON.stringify(value) } }); + TempSettings.update({ _id: settingId }, { $set: { value, changed: JSON.stringify(settings.collectionPrivate.findOne(settingId).value) !== JSON.stringify(value) } }); break; default: input.val(value).change(); @@ -49,17 +48,17 @@ const setFieldValue = function(settingId, value, type, editor) { }; Template.admin.onCreated(function() { - if (RocketChat.settings.cachedCollectionPrivate == null) { - RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ + if (settings.cachedCollectionPrivate == null) { + settings.cachedCollectionPrivate = new CachedCollection({ name: 'private-settings', eventType: 'onLogged', useCache: false, }); - RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection; - RocketChat.settings.cachedCollectionPrivate.init(); + settings.collectionPrivate = settings.cachedCollectionPrivate.collection; + settings.cachedCollectionPrivate.init(); } this.selectedRooms = new ReactiveVar({}); - RocketChat.settings.collectionPrivate.find().observe({ + settings.collectionPrivate.find().observe({ added: (data) => { const selectedRooms = this.selectedRooms.get(); if (data.type === 'roomPick') { @@ -108,23 +107,23 @@ Template.admin.helpers({ return result; }, isAppLanguage(key) { - const languageKey = RocketChat.settings.get('Language'); + const languageKey = settings.get('Language'); return typeof languageKey === 'string' && languageKey.toLowerCase() === key; }, group() { const groupId = FlowRouter.getParam('group'); - const group = RocketChat.settings.collectionPrivate.findOne({ + const group = settings.collectionPrivate.findOne({ _id: groupId, type: 'group', }); if (!group) { return; } - const settings = RocketChat.settings.collectionPrivate.find({ group: groupId }, { sort: { section: 1, sorter: 1, i18nLabel: 1 } }).fetch(); + const rcSettings = settings.collectionPrivate.find({ group: groupId }, { sort: { section: 1, sorter: 1, i18nLabel: 1 } }).fetch(); const sections = {}; - Object.keys(settings).forEach((key) => { - const setting = settings[key]; + Object.keys(rcSettings).forEach((key) => { + const setting = rcSettings[key]; let i18nDefaultQuery; if (setting.i18nDefaultQuery != null) { if (_.isString(setting.i18nDefaultQuery)) { @@ -137,7 +136,7 @@ Template.admin.helpers({ } Object.keys(i18nDefaultQuery).forEach((key) => { const item = i18nDefaultQuery[key]; - if (RocketChat.settings.collectionPrivate.findOne(item) != null) { + if (settings.collectionPrivate.findOne(item) != null) { setting.value = TAPi18n.__(`${ setting._id }_Default`); } }); @@ -273,7 +272,7 @@ Template.admin.helpers({ return Meteor.absoluteUrl(url); }, selectedOption(_id, val) { - const option = RocketChat.settings.collectionPrivate.findOne({ _id }); + const option = settings.collectionPrivate.findOne({ _id }); return option && option.value === val; }, random() { @@ -304,7 +303,7 @@ Template.admin.helpers({ } const onChange = function() { const value = codeMirror.getValue(); - TempSettings.update({ _id }, { $set: { value, changed: RocketChat.settings.collectionPrivate.findOne(_id).value !== value } }); + TempSettings.update({ _id }, { $set: { value, changed: settings.collectionPrivate.findOne(_id).value !== value } }); }; const onChangeDelayed = _.debounce(onChange, 500); codeMirror.on('change', onChangeDelayed); @@ -369,14 +368,14 @@ Template.admin.events({ }, { $set: { value, - changed: RocketChat.settings.collectionPrivate.findOne(this._id).value !== value, + changed: settings.collectionPrivate.findOne(this._id).value !== value, }, }); }, 500), 'change select[name=color-editor]'(e) { const value = s.trim($(e.target).val()); TempSettings.update({ _id: this._id }, { $set: { editor: value } }); - RocketChat.settings.collectionPrivate.update({ _id: this._id }, { $set: { editor: value } }); + settings.collectionPrivate.update({ _id: this._id }, { $set: { editor: value } }); }, 'click .rc-header__section-button .discard'() { const group = FlowRouter.getParam('group'); @@ -384,10 +383,10 @@ Template.admin.events({ group, changed: true, }; - const settings = TempSettings.find(query, { + const rcSettings = TempSettings.find(query, { fields: { _id: 1, value: 1, packageValue: 1 } }).fetch(); - settings.forEach(function(setting) { - const oldSetting = RocketChat.settings.collectionPrivate.findOne({ _id: setting._id }, { fields: { value: 1, type: 1, editor: 1 } }); + rcSettings.forEach(function(setting) { + const oldSetting = settings.collectionPrivate.findOne({ _id: setting._id }, { fields: { value: 1, type: 1, editor: 1 } }); setFieldValue(setting._id, oldSetting.value, oldSetting.type, oldSetting.editor); }); }, @@ -401,22 +400,22 @@ Template.admin.events({ setFieldValue(settingId, defaultValue.packageValue, defaultValue.type, defaultValue.editor); }, 'click .reset-group'(e) { - let settings; + let rcSettings; e.preventDefault(); const group = FlowRouter.getParam('group'); const section = $(e.target).data('section'); if (section === '') { - settings = TempSettings.find({ group, section: { $exists: false } }, { fields: { _id: 1 } }).fetch(); + rcSettings = TempSettings.find({ group, section: { $exists: false } }, { fields: { _id: 1 } }).fetch(); } else { - settings = TempSettings.find({ group, section }, { fields: { _id: 1 } }).fetch(); + rcSettings = TempSettings.find({ group, section }, { fields: { _id: 1 } }).fetch(); } - settings.forEach(function(setting) { + rcSettings.forEach(function(setting) { const defaultValue = getDefaultSetting(setting._id); setFieldValue(setting._id, defaultValue.packageValue, defaultValue.type, defaultValue.editor); TempSettings.update({ _id: setting._id }, { $set: { value: defaultValue.packageValue, - changed: RocketChat.settings.collectionPrivate.findOne(setting._id).value !== defaultValue.packageValue, + changed: settings.collectionPrivate.findOne(setting._id).value !== defaultValue.packageValue, }, }); }); @@ -424,21 +423,21 @@ Template.admin.events({ 'click .rc-header__section-button .save'() { const group = FlowRouter.getParam('group'); const query = { group, changed: true }; - const settings = TempSettings.find(query, { fields: { _id: 1, value: 1, editor: 1 } }).fetch() || []; - if (settings.length === 0) { + const rcSettings = TempSettings.find(query, { fields: { _id: 1, value: 1, editor: 1 } }).fetch() || []; + if (rcSettings.length === 0) { return; } - RocketChat.settings.batchSet(settings, (err) => { + settings.batchSet(rcSettings, (err) => { if (err) { return handleError(err); } TempSettings.update({ changed: true }, { $unset: { changed: 1 } }); - if (settings.some(({ _id }) => _id === 'Language')) { + if (rcSettings.some(({ _id }) => _id === 'Language')) { const lng = Meteor.user().language - || settings.filter(({ _id }) => _id === 'Language').shift().value + || rcSettings.filter(({ _id }) => _id === 'Language').shift().value || 'en'; return TAPi18n._loadLanguage(lng).then(() => toastr.success(TAPi18n.__('Settings_updated', { lng }))); } diff --git a/packages/rocketchat-ui-admin/client/adminFlex.js b/packages/rocketchat-ui-admin/client/adminFlex.js index 06830633eee3..e05a458245f8 100644 --- a/packages/rocketchat-ui-admin/client/adminFlex.js +++ b/packages/rocketchat-ui-admin/client/adminFlex.js @@ -1,22 +1,23 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { CachedCollection } from 'meteor/rocketchat:ui-cached-collection'; +import { SideNav, AdminBox, Layout } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; Template.adminFlex.onCreated(function() { this.settingsFilter = new ReactiveVar(''); - if (RocketChat.settings.cachedCollectionPrivate == null) { - RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ + if (settings.cachedCollectionPrivate == null) { + settings.cachedCollectionPrivate = new CachedCollection({ name: 'private-settings', eventType: 'onLogged', useCache: false, }); - RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection; - RocketChat.settings.cachedCollectionPrivate.init(); + settings.collectionPrivate = settings.cachedCollectionPrivate.collection; + settings.cachedCollectionPrivate.init(); } }); @@ -36,7 +37,7 @@ Template.adminFlex.helpers({ }; if (filter) { const filterRegex = new RegExp(s.escapeRegExp(filter), 'i'); - const records = RocketChat.settings.collectionPrivate.find().fetch(); + const records = settings.collectionPrivate.find().fetch(); let groups = []; records.forEach(function(record) { if (filterRegex.test(TAPi18n.__(record.i18nLabel || record._id))) { @@ -50,7 +51,7 @@ Template.adminFlex.helpers({ }; } } - return RocketChat.settings.collectionPrivate.find(query).fetch().map(function(el) { + return settings.collectionPrivate.find(query).fetch().map(function(el) { el.label = label.apply(el); return el; }).sort(function(a, b) { @@ -63,7 +64,7 @@ Template.adminFlex.helpers({ }, label, adminBoxOptions() { - return RocketChat.AdminBox.getOptions(); + return AdminBox.getOptions(); }, menuItem(name, icon, section, group) { return { @@ -76,7 +77,7 @@ Template.adminFlex.helpers({ }; }, embeddedVersion() { - return RocketChat.Layout.isEmbedded(); + return Layout.isEmbedded(); }, }); diff --git a/packages/rocketchat-ui-admin/client/adminInfo.js b/packages/rocketchat-ui-admin/client/adminInfo.js index 235a461a6077..8791d3197fa9 100644 --- a/packages/rocketchat-ui-admin/client/adminInfo.js +++ b/packages/rocketchat-ui-admin/client/adminInfo.js @@ -3,8 +3,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { handleError, Info } from 'meteor/rocketchat:utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { SideNav } from 'meteor/rocketchat:ui-utils'; import s from 'underscore.string'; import moment from 'moment'; @@ -53,10 +54,10 @@ Template.adminInfo.helpers({ return s.numberFormat(number, 2); }, info() { - return RocketChat.Info; + return Info; }, build() { - return RocketChat.Info && (RocketChat.Info.compile || RocketChat.Info.build); + return Info && (Info.compile || Info.build); }, }); @@ -86,7 +87,7 @@ Template.adminInfo.onCreated(function() { this.statistics = new ReactiveVar({}); this.instances = new ReactiveVar({}); this.ready = new ReactiveVar(false); - if (RocketChat.authz.hasAllPermission('view-statistics')) { + if (hasAllPermission('view-statistics')) { Meteor.call('getStatistics', function(error, statistics) { instance.ready.set(true); if (error) { diff --git a/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js b/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js index ec8d61ca028e..c5a8c1bd0ec9 100644 --- a/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js +++ b/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js @@ -3,10 +3,12 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; -import { call } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { call, modal } from 'meteor/rocketchat:ui-utils'; +import { hasAllPermission, hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { ChannelSettings } from 'meteor/rocketchat:channel-settings'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { AdminChatRoom } from './adminRooms'; import toastr from 'toastr'; @@ -15,7 +17,7 @@ Template.adminRoomInfo.helpers({ return Session.get('adminRoomsSelected'); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', this.rid); + return hasAllPermission('edit-room', this.rid); }, editing(field) { return Template.instance().editing.get() === field; @@ -29,7 +31,7 @@ Template.adminRoomInfo.helpers({ return room && room.t; }, channelSettings() { - return RocketChat.ChannelSettings.getOptions(undefined, 'admin-room'); + return ChannelSettings.getOptions(undefined, 'admin-room'); }, roomTypeDescription() { const room = AdminChatRoom.findOne(this.rid, { fields: { t: 1 } }); @@ -68,7 +70,7 @@ Template.adminRoomInfo.helpers({ canDeleteRoom() { const room = AdminChatRoom.findOne(this.rid, { fields: { t: 1 } }); const roomType = room && room.t; - return (roomType != null) && RocketChat.authz.hasAtLeastOnePermission(`delete-${ roomType }`); + return (roomType != null) && hasAtLeastOnePermission(`delete-${ roomType }`); }, readOnly() { const room = AdminChatRoom.findOne(this.rid, { fields: { ro: 1 } }); @@ -150,13 +152,13 @@ Template.adminRoomInfo.onCreated(function() { this.validateRoomName = (rid) => { const room = AdminChatRoom.findOne(rid); let nameValidation; - if (!RocketChat.authz.hasAllPermission('edit-room', rid) || (room.t !== 'c' && room.t !== 'p')) { + if (!hasAllPermission('edit-room', rid) || (room.t !== 'c' && room.t !== 'p')) { toastr.error(t('error-not-allowed')); return false; } name = $('input[name=roomName]').val(); 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-_.]+$'); } @@ -173,7 +175,7 @@ Template.adminRoomInfo.onCreated(function() { switch (this.editing.get()) { case 'roomName': if (this.validateRoomName(rid)) { - RocketChat.callbacks.run('roomNameChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomNameChanged', AdminChatRoom.findOne(rid)); Meteor.call('saveRoomSettings', rid, 'roomName', this.$('input[name=roomName]').val(), function(err) { if (err) { return handleError(err); @@ -189,7 +191,7 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_topic_changed_successfully')); - RocketChat.callbacks.run('roomTopicChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomTopicChanged', AdminChatRoom.findOne(rid)); }); } break; @@ -200,14 +202,14 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_announcement_changed_successfully')); - RocketChat.callbacks.run('roomAnnouncementChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomAnnouncementChanged', AdminChatRoom.findOne(rid)); }); } break; case 'roomType': const val = this.$('input[name=roomType]:checked').val(); if (this.validateRoomType(rid)) { - RocketChat.callbacks.run('roomTypeChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomTypeChanged', AdminChatRoom.findOne(rid)); const saveRoomSettings = function() { Meteor.call('saveRoomSettings', rid, 'roomType', val, function(err) { if (err) { @@ -243,7 +245,7 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_archived')); - RocketChat.callbacks.run('archiveRoom', AdminChatRoom.findOne(rid)); + callbacks.run('archiveRoom', AdminChatRoom.findOne(rid)); }); } } else if ((room && room.archived) === true) { @@ -252,7 +254,7 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_unarchived')); - RocketChat.callbacks.run('unarchiveRoom', AdminChatRoom.findOne(rid)); + callbacks.run('unarchiveRoom', AdminChatRoom.findOne(rid)); }); } break; diff --git a/packages/rocketchat-ui-admin/client/rooms/adminRooms.js b/packages/rocketchat-ui-admin/client/rooms/adminRooms.js index bba612df0bed..82f7994b0a99 100644 --- a/packages/rocketchat-ui-admin/client/rooms/adminRooms.js +++ b/packages/rocketchat-ui-admin/client/rooms/adminRooms.js @@ -5,9 +5,10 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { SideNav } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; -import { RocketChat, RocketChatTabBar } from 'meteor/rocketchat:lib'; +import { SideNav, RocketChatTabBar, TabBar } from 'meteor/rocketchat:ui-utils'; +import { t, roomTypes } from 'meteor/rocketchat:utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { ChannelSettings } from 'meteor/rocketchat:channel-settings'; import _ from 'underscore'; import s from 'underscore.string'; @@ -38,10 +39,10 @@ Template.adminRooms.helpers({ return rooms && rooms.count(); }, name() { - return RocketChat.roomTypes.roomTypes[this.t].getDisplayName(this); + return roomTypes.roomTypes[this.t].getDisplayName(this); }, type() { - return TAPi18n.__(RocketChat.roomTypes.roomTypes[this.t].label); + return TAPi18n.__(roomTypes.roomTypes[this.t].label); }, 'default'() { if (this.default) { @@ -65,7 +66,7 @@ Template.adminRooms.onCreated(function() { this.ready = new ReactiveVar(true); this.tabBar = new RocketChatTabBar(); this.tabBar.showGroup(FlowRouter.current().route.name); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-rooms'], id: 'admin-room', i18nTitle: 'Room_Info', @@ -73,7 +74,7 @@ Template.adminRooms.onCreated(function() { template: 'adminRoomInfo', order: 1, }); - RocketChat.ChannelSettings.addOption({ + ChannelSettings.addOption({ group: ['admin-room'], id: 'make-default', template: 'channelSettingsDefault', @@ -81,7 +82,7 @@ Template.adminRooms.onCreated(function() { return Session.get('adminRoomsSelected'); }, validation() { - return RocketChat.authz.hasAllPermission('view-room-administration'); + return hasAllPermission('view-room-administration'); }, }); this.autorun(function() { diff --git a/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js b/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js index 6d2546912186..2c984795f9c4 100644 --- a/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js +++ b/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js @@ -2,8 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { t } from 'meteor/rocketchat:utils'; -import { handleError } from 'meteor/rocketchat:lib'; +import { t, handleError } from 'meteor/rocketchat:utils'; import { AdminChatRoom } from './adminRooms'; import toastr from 'toastr'; diff --git a/packages/rocketchat-ui-admin/client/users/adminInviteUser.js b/packages/rocketchat-ui-admin/client/users/adminInviteUser.js index d0462f0f1c4b..e504c72f319a 100644 --- a/packages/rocketchat-ui-admin/client/users/adminInviteUser.js +++ b/packages/rocketchat-ui-admin/client/users/adminInviteUser.js @@ -1,14 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { t, handleError } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import toastr from 'toastr'; Template.adminInviteUser.helpers({ isAllowed() { - return RocketChat.authz.hasAtLeastOnePermission('bulk-register-user'); + return hasAtLeastOnePermission('bulk-register-user'); }, inviteEmails() { return Template.instance().inviteEmails.get(); diff --git a/packages/rocketchat-ui-admin/client/users/adminUsers.js b/packages/rocketchat-ui-admin/client/users/adminUsers.js index 8eae718db764..e55c0bf70387 100644 --- a/packages/rocketchat-ui-admin/client/users/adminUsers.js +++ b/packages/rocketchat-ui-admin/client/users/adminUsers.js @@ -3,8 +3,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { SideNav, TabBar } from 'meteor/rocketchat:ui-utils'; import _ from 'underscore'; import s from 'underscore.string'; @@ -50,7 +49,7 @@ Template.adminUsers.onCreated(function() { this.tabBar = new RocketChatTabBar(); this.tabBar.showGroup(FlowRouter.current().route.name); this.tabBarData = new ReactiveVar; - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-users'], id: 'invite-user', i18nTitle: 'Invite_Users', @@ -58,7 +57,7 @@ Template.adminUsers.onCreated(function() { template: 'adminInviteUser', order: 1, }); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-users'], id: 'add-user', i18nTitle: 'Add_User', @@ -66,7 +65,7 @@ Template.adminUsers.onCreated(function() { template: 'adminUserEdit', order: 2, }); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-users'], id: 'admin-user-info', i18nTitle: 'User_Info', diff --git a/packages/rocketchat-ui-admin/package.js b/packages/rocketchat-ui-admin/package.js index 425121cefb67..cd3191308363 100644 --- a/packages/rocketchat-ui-admin/package.js +++ b/packages/rocketchat-ui-admin/package.js @@ -16,7 +16,13 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:ui-cached-collection', + 'rocketchat:authorization', + 'rocketchat:channel-settings', + 'rocketchat:ui-utils', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-ui-admin/server/publications/adminRooms.js b/packages/rocketchat-ui-admin/server/publications/adminRooms.js index 8d43b1456d02..a45eaa9fb658 100644 --- a/packages/rocketchat-ui-admin/server/publications/adminRooms.js +++ b/packages/rocketchat-ui-admin/server/publications/adminRooms.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; import _ from 'underscore'; import s from 'underscore.string'; @@ -7,7 +8,7 @@ Meteor.publish('adminRooms', function(filter, types, limit) { if (!this.userId) { return this.ready(); } - if (RocketChat.authz.hasPermission(this.userId, 'view-room-administration') !== true) { + if (hasPermission(this.userId, 'view-room-administration') !== true) { return this.ready(); } if (!_.isArray(types)) { @@ -39,12 +40,12 @@ Meteor.publish('adminRooms', function(filter, types, limit) { filter = s.trim(filter); if (filter && types.length) { // CACHE: can we stop using publications here? - return RocketChat.models.Rooms.findByNameContainingAndTypes(filter, types, options); + return Rooms.findByNameContainingAndTypes(filter, types, options); } else if (types.length) { // CACHE: can we stop using publications here? - return RocketChat.models.Rooms.findByTypes(types, options); + return Rooms.findByTypes(types, options); } else { // CACHE: can we stop using publications here? - return RocketChat.models.Rooms.findByNameContaining(filter, options); + return Rooms.findByNameContaining(filter, options); } }); From 3c063a55662e722b6de1c9071301018f625c2135 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 14:40:48 -0200 Subject: [PATCH 087/101] Remove dependency of RC namespace in rc-ui-clean-history --- .../rocketchat-ui-clean-history/client/lib/startup.js | 7 ++++--- .../client/views/cleanHistory.js | 11 ++++++----- packages/rocketchat-ui-clean-history/package.js | 6 +++++- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/rocketchat-ui-clean-history/client/lib/startup.js b/packages/rocketchat-ui-clean-history/client/lib/startup.js index 3c7321c387bd..f4870aec1ad1 100644 --- a/packages/rocketchat-ui-clean-history/client/lib/startup.js +++ b/packages/rocketchat-ui-clean-history/client/lib/startup.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Session } from 'meteor/session'; -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: 'clean-history', anonymous: true, @@ -11,6 +12,6 @@ Meteor.startup(() => { icon: 'trash', template: 'cleanHistory', order: 250, - condition: () => RocketChat.authz.hasAllPermission('clean-channel-history', Session.get('openedRoom')), + condition: () => hasAllPermission('clean-channel-history', Session.get('openedRoom')), }); }); diff --git a/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js b/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js index cb30481ae9cf..c48fbf47ccbd 100644 --- a/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js +++ b/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js @@ -4,9 +4,10 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { AutoComplete } from 'meteor/mizzao:autocomplete'; -import { ChatRoom, modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; -import { RocketChat, call } from 'meteor/rocketchat:lib'; +import { ChatRoom } from 'meteor/rocketchat:models'; +import { t, roomTypes } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { modal, call } from 'meteor/rocketchat:ui-utils'; import moment from 'moment'; const getRoomName = function() { @@ -18,7 +19,7 @@ const getRoomName = function() { return `#${ room.name }`; } - return t('conversation_with_s', RocketChat.roomTypes.getRoomName(room.t, room)); + return t('conversation_with_s', roomTypes.getRoomName(room.t, room)); }; const purgeWorker = function(roomId, oldest, latest, inclusive, limit, excludePinned, filesOnly, fromUsers) { @@ -43,7 +44,7 @@ const getTimeZoneOffset = function() { 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(''); }; diff --git a/packages/rocketchat-ui-clean-history/package.js b/packages/rocketchat-ui-clean-history/package.js index 4b8fce5043e1..73ed2a5848f4 100644 --- a/packages/rocketchat-ui-clean-history/package.js +++ b/packages/rocketchat-ui-clean-history/package.js @@ -15,8 +15,12 @@ Package.onUse(function(api) { 'mongo', 'ecmascript', 'templating', + 'mizzao:autocomplete', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:ui-utils', + 'rocketchat:authorization', ]); api.addFiles('client/views/stylesheets/cleanHistory.css', 'client'); api.mainModule('client/index.js', 'client'); From 18724d638168bfa807e68874deb0515dfca7ee6f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 14:52:16 -0200 Subject: [PATCH 088/101] Remove dependency of RC namespace in rc-ui-flextab --- .../client/flexTabBar.js | 9 +++-- .../client/tabs/inviteUsers.js | 6 +-- .../client/tabs/membersList.js | 27 ++++++------- .../client/tabs/uploadedFilesList.js | 2 +- .../client/tabs/userActions.js | 38 ++++++++++--------- .../client/tabs/userEdit.js | 9 +++-- .../client/tabs/userInfo.js | 17 +++++---- packages/rocketchat-ui-flextab/package.js | 4 ++ 8 files changed, 62 insertions(+), 50 deletions(-) diff --git a/packages/rocketchat-ui-flextab/client/flexTabBar.js b/packages/rocketchat-ui-flextab/client/flexTabBar.js index 0f773e70aeed..329c23b02142 100644 --- a/packages/rocketchat-ui-flextab/client/flexTabBar.js +++ b/packages/rocketchat-ui-flextab/client/flexTabBar.js @@ -4,7 +4,8 @@ import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; -import { popover } from 'meteor/rocketchat:ui'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { popover } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import _ from 'underscore'; @@ -19,13 +20,13 @@ const commonHelpers = { }, }; function canShowAddUsersButton(rid) { - const canAddToChannel = RocketChat.authz.hasAllPermission( + const canAddToChannel = hasAllPermission( 'add-user-to-any-c-room', rid ); - const canAddToGroup = RocketChat.authz.hasAllPermission( + const canAddToGroup = hasAllPermission( 'add-user-to-any-p-room', rid ); - const canAddToJoinedRoom = RocketChat.authz.hasAllPermission( + const canAddToJoinedRoom = hasAllPermission( 'add-user-to-joined-room', rid ); if ( diff --git a/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js b/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js index 06f2ff61209c..cf1a45350362 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js +++ b/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js @@ -4,7 +4,7 @@ import { Blaze } from 'meteor/blaze'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { AutoComplete } from 'meteor/mizzao:autocomplete'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { t } from 'meteor/rocketchat:utils'; import { Deps } from 'meteor/deps'; import toastr from 'toastr'; @@ -35,11 +35,11 @@ const acEvents = { }; const filterNames = (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(''); }; diff --git a/packages/rocketchat-ui-flextab/client/tabs/membersList.js b/packages/rocketchat-ui-flextab/client/tabs/membersList.js index 9988532feca7..fe501127736b 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/membersList.js +++ b/packages/rocketchat-ui-flextab/client/tabs/membersList.js @@ -3,9 +3,10 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { ChatRoom, RoomManager, popover } from 'meteor/rocketchat:ui'; -import { t, isRtl } from 'meteor/rocketchat:utils'; +import { RoomManager, popover } from 'meteor/rocketchat:ui-utils'; +import { ChatRoom, Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { t, isRtl, handleError, roomTypes } from 'meteor/rocketchat:utils'; import { WebRTC } from 'meteor/rocketchat:webrtc'; import _ from 'underscore'; import { getActions } from './userActions'; @@ -13,7 +14,7 @@ import { getActions } from './userActions'; Template.membersList.helpers({ ignored() { const { user } = this; - const sub = RocketChat.models.Subscriptions.findOne({ rid: Session.get('openedRoom') }); + const sub = Subscriptions.findOne({ rid: Session.get('openedRoom') }); return sub && sub.ignored && sub.ignored.indexOf(user._id) > -1 ? `(${ t('Ignored') })` : ''; }, tAddUsers() { @@ -22,7 +23,7 @@ Template.membersList.helpers({ isGroupChat() { const room = ChatRoom.findOne(this.rid, { reactive: false }); - return RocketChat.roomTypes.roomTypes[room.t].isGroupChat(); + return roomTypes.roomTypes[room.t].isGroupChat(); }, isDirectChat() { @@ -82,7 +83,7 @@ Template.membersList.helpers({ }; }); - if (RocketChat.settings.get('UI_Use_Real_Name')) { + if (settings.get('UI_Use_Real_Name')) { users = _.sortBy(users, (u) => u.user.name); } else { users = _.sortBy(users, (u) => u.user.username); @@ -114,7 +115,7 @@ Template.membersList.helpers({ canAddUser() { const roomData = Session.get(`roomData${ this._id }`); if (!roomData) { return ''; } - return (() => RocketChat.roomTypes.roomTypes[roomData.t].canAddUser(roomData))(); + return (() => roomTypes.roomTypes[roomData.t].canAddUser(roomData))(); }, autocompleteSettingsAddUser() { @@ -159,13 +160,13 @@ Template.membersList.helpers({ tabBar: Template.currentData().tabBar, username: Template.instance().userDetail.get(), clear: Template.instance().clearUserDetail, - showAll: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, - hideAdminControls: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, + showAll: roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, + hideAdminControls: roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, video: ['d'].includes(room != null ? room.t : undefined), }; }, displayName() { - if (RocketChat.settings.get('UI_Use_Real_Name') && this.user.name) { + if (settings.get('UI_Use_Real_Name') && this.user.name) { return this.user.name; } @@ -203,8 +204,8 @@ Template.membersList.events({ const room = Session.get(`roomData${ instance.data.rid }`); const _actions = getActions({ user: this.user.user, - hideAdminControls: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, - directActions: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, + hideAdminControls: roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, + directActions: roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, }) .map((action) => (typeof action === 'function' ? action.call(this) : action)) .filter((action) => action && (!action.condition || action.condition.call(this))); @@ -256,7 +257,7 @@ Template.membersList.events({ const roomData = Session.get(`roomData${ template.data.rid }`); - if (RocketChat.roomTypes.roomTypes[roomData.t].canAddUser(roomData)) { + if (roomTypes.roomTypes[roomData.t].canAddUser(roomData)) { return Meteor.call('addUserToRoom', { rid: roomData._id, username: doc.username }, function(error) { if (error) { return handleError(error); diff --git a/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js b/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js index 811c4115612b..94a74c2e89d9 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js +++ b/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js @@ -3,7 +3,7 @@ import { fixCordova } from 'meteor/rocketchat:lazy-load'; import { ReactiveVar } from 'meteor/reactive-var'; import { DateFormat } from 'meteor/rocketchat:lib'; import { t } from 'meteor/rocketchat:utils'; -import { popover } from 'meteor/rocketchat:ui'; +import { popover } from 'meteor/rocketchat:ui-utils'; import { Template } from 'meteor/templating'; import _ from 'underscore'; diff --git a/packages/rocketchat-ui-flextab/client/tabs/userActions.js b/packages/rocketchat-ui-flextab/client/tabs/userActions.js index 81ea34da70d4..1a9b63828f03 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userActions.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userActions.js @@ -2,29 +2,31 @@ import { Meteor } from 'meteor/meteor'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; import { WebRTC } from 'meteor/rocketchat:webrtc'; -import { modal, ChatRoom, ChatSubscription, RoomRoles } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { ChatRoom, ChatSubscription, RoomRoles, Subscriptions } from 'meteor/rocketchat:models'; +import { modal } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAllPermission, hasRole } from 'meteor/rocketchat:authorization'; import _ from 'underscore'; import toastr from 'toastr'; export const getActions = function({ user, directActions, hideAdminControls }) { - const hasPermission = RocketChat.authz.hasAllPermission; + const hasPermission = hasAllPermission; const isIgnored = () => { - const sub = RocketChat.models.Subscriptions.findOne({ rid : Session.get('openedRoom') }); + const sub = Subscriptions.findOne({ rid : Session.get('openedRoom') }); return sub && sub.ignored && sub.ignored.indexOf(user._id) > -1; }; - const canSetLeader = () => RocketChat.authz.hasAllPermission('set-leader', Session.get('openedRoom')); + const canSetLeader = () => hasAllPermission('set-leader', Session.get('openedRoom')); const active = () => user && user.active; const hasAdminRole = () => { if (user && user._id) { - return RocketChat.authz.hasRole(user._id, 'admin'); + return hasRole(user._id, 'admin'); } }; - const canRemoveUser = () => RocketChat.authz.hasAllPermission('remove-user', Session.get('openedRoom')); - const canSetModerator = () => RocketChat.authz.hasAllPermission('set-moderator', Session.get('openedRoom')); + const canRemoveUser = () => hasAllPermission('remove-user', Session.get('openedRoom')); + const canSetModerator = () => hasAllPermission('set-moderator', Session.get('openedRoom')); const isDirect = () => { const room = ChatRoom.findOne(Session.get('openedRoom')); return (room != null ? room.t : undefined) === 'd'; @@ -48,15 +50,15 @@ export const getActions = function({ user, directActions, hideAdminControls }) { return !!RoomRoles.findOne({ rid: Session.get('openedRoom'), 'u._id': user._id, roles: 'moderator' }); } }; - const canSetOwner = () => RocketChat.authz.hasAllPermission('set-owner', Session.get('openedRoom')); + const canSetOwner = () => hasAllPermission('set-owner', Session.get('openedRoom')); const canDirectMessage = (username) => { const rid = Session.get('openedRoom'); - const subscription = RocketChat.models.Subscriptions.findOne({ rid }); - const canOpenDm = RocketChat.authz.hasAllPermission('create-d') || RocketChat.models.Subscriptions.findOne({ name: username }); + const subscription = Subscriptions.findOne({ rid }); + const canOpenDm = hasAllPermission('create-d') || Subscriptions.findOne({ name: username }); const dmIsNotAlreadyOpen = subscription && subscription.name !== username; return canOpenDm && dmIsNotAlreadyOpen; }; - const canMuteUser = () => RocketChat.authz.hasAllPermission('mute-user', Session.get('openedRoom')); + const canMuteUser = () => hasAllPermission('mute-user', Session.get('openedRoom')); const userMuted = () => { const room = ChatRoom.findOne(Session.get('openedRoom')); return _.isArray(room && room.muted) && (room.muted.indexOf(user && user.username) !== -1); @@ -331,7 +333,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { name: t('Unmute_user'), action:prevent(getUser, ({ username }) => { const rid = Session.get('openedRoom'); - if (!RocketChat.authz.hasAllPermission('mute-user', rid)) { + if (!hasAllPermission('mute-user', rid)) { return toastr.error(TAPi18n.__('error-not-allowed')); } Meteor.call('unmuteUserInRoom', { rid, username }, success(() => toastr.success(TAPi18n.__('User_unmuted_in_room')))); @@ -345,7 +347,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { action: prevent(getUser, ({ username }) => { const rid = Session.get('openedRoom'); const room = ChatRoom.findOne(rid); - if (!RocketChat.authz.hasAllPermission('mute-user', rid)) { + if (!hasAllPermission('mute-user', rid)) { return toastr.error(TAPi18n.__('error-not-allowed')); } modal.open({ @@ -379,7 +381,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { action: prevent(getUser, (user) => { const rid = Session.get('openedRoom'); const room = ChatRoom.findOne(rid); - if (!RocketChat.authz.hasAllPermission('remove-user', rid)) { + if (!hasAllPermission('remove-user', rid)) { return toastr.error(TAPi18n.__('error-not-allowed')); } modal.open({ @@ -416,7 +418,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { icon : 'trash', name: 'Delete', action: prevent(getUser, ({ _id }) => { - const erasureType = RocketChat.settings.get('Message_ErasureType'); + const erasureType = settings.get('Message_ErasureType'); const warningKey = `Delete_User_Warning_${ erasureType }`; modal.open({ @@ -487,7 +489,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { if (hideAdminControls || !hasPermission('reset-other-user-e2e-key')) { return; } - if (!RocketChat.settings.get('E2E_Enable')) { + if (!settings.get('E2E_Enable')) { return; } diff --git a/packages/rocketchat-ui-flextab/client/tabs/userEdit.js b/packages/rocketchat-ui-flextab/client/tabs/userEdit.js index f2b6280e59b8..f2089d9c754b 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userEdit.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userEdit.js @@ -3,8 +3,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Random } from 'meteor/random'; 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 { t, handleError } from 'meteor/rocketchat:utils'; +import { Roles } from 'meteor/rocketchat:models'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; import toastr from 'toastr'; import s from 'underscore.string'; @@ -14,7 +15,7 @@ Template.userEdit.helpers({ return cursor.count() === 0 ? 'disabled' : ''; }, canEditOrAdd() { - return (Template.instance().user && RocketChat.authz.hasAtLeastOnePermission('edit-other-user-info')) || (!Template.instance().user && RocketChat.authz.hasAtLeastOnePermission('create-user')); + return (Template.instance().user && hasAtLeastOnePermission('edit-other-user-info')) || (!Template.instance().user && hasAtLeastOnePermission('create-user')); }, user() { @@ -27,7 +28,7 @@ Template.userEdit.helpers({ role() { const roles = Template.instance().roles.get(); - return RocketChat.models.Roles.find({ _id: { $nin:roles }, scope: 'Users' }, { sort: { description: 1, _id: 1 } }); + return Roles.find({ _id: { $nin:roles }, scope: 'Users' }, { sort: { description: 1, _id: 1 } }); }, userRoles() { diff --git a/packages/rocketchat-ui-flextab/client/tabs/userInfo.js b/packages/rocketchat-ui-flextab/client/tabs/userInfo.js index 9a1782f60097..79ca4ac55c04 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userInfo.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userInfo.js @@ -6,8 +6,11 @@ import { TAPi18n } from 'meteor/tap:i18n'; import _ from 'underscore'; import s from 'underscore.string'; import moment from 'moment'; -import { DateFormat, RocketChat } from 'meteor/rocketchat:lib'; -import { RoomRoles, popover, UserRoles } from 'meteor/rocketchat:ui'; +import { DateFormat } from 'meteor/rocketchat:lib'; +import { popover } from 'meteor/rocketchat:ui-utils'; +import { templateVarHandler } from 'meteor/rocketchat:utils'; +import { RoomRoles, UserRoles, Roles } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import { getActions } from './userActions'; const more = function() { @@ -31,7 +34,7 @@ Template.userInfo.helpers({ .slice(0, 2); }, customField() { - const sCustomFieldsToShow = RocketChat.settings.get('Accounts_CustomFieldsToShowInUserInfo').trim(); + const sCustomFieldsToShow = settings.get('Accounts_CustomFieldsToShowInUserInfo').trim(); const customFields = []; if (sCustomFieldsToShow) { @@ -43,13 +46,13 @@ Template.userInfo.helpers({ let content = ''; if (_.isObject(el)) { _.map(el, (key, label) => { - const value = RocketChat.templateVarHandler(key, userCustomFields); + const value = templateVarHandler(key, userCustomFields); if (value) { content = { label, value }; } }); } else { - content = RocketChat.templateVarHandler(el, userCustomFields); + content = templateVarHandler(el, userCustomFields); } if (content) { customFields.push(content); @@ -169,12 +172,12 @@ Template.userInfo.helpers({ const userRoles = UserRoles.findOne(user._id) || {}; const roomRoles = RoomRoles.findOne({ 'u._id': user._id, rid: Session.get('openedRoom') }) || {}; const roles = _.union(userRoles.roles || [], roomRoles.roles || []); - return roles.length && RocketChat.models.Roles.find({ _id: { $in: roles }, description: { $exists: 1 } }, { fields: { description: 1 } }); + return roles.length && Roles.find({ _id: { $in: roles }, description: { $exists: 1 } }, { fields: { description: 1 } }); }, shouldDisplayReason() { const user = Template.instance().user.get(); - return RocketChat.settings.get('Accounts_ManuallyApproveNewUsers') && user.active === false && user.reason; + return settings.get('Accounts_ManuallyApproveNewUsers') && user.active === false && user.reason; }, }); diff --git a/packages/rocketchat-ui-flextab/package.js b/packages/rocketchat-ui-flextab/package.js index 1543254317da..33dbda91b25d 100644 --- a/packages/rocketchat-ui-flextab/package.js +++ b/packages/rocketchat-ui-flextab/package.js @@ -16,7 +16,11 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', + 'rocketchat:models', 'rocketchat:lib', + 'rocketchat:ui-utils', + 'rocketchat:settings', + 'rocketchat:authorization', 'mizzao:autocomplete', 'rocketchat:webrtc', ]); From e8774445fbecc1202ff391b441d69829f4a45a2f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 15:01:51 -0200 Subject: [PATCH 089/101] Remove dependency of RC namespace in rc-ui-login --- .../client/login/footer.js | 4 +- .../rocketchat-ui-login/client/login/form.js | 55 ++++++++++--------- .../client/login/header.js | 4 +- .../client/login/layout.js | 4 +- .../client/reset-password/resetPassword.js | 13 +++-- .../client/username/layout.js | 4 +- .../client/username/username.js | 14 +++-- packages/rocketchat-ui-login/package.js | 3 + 8 files changed, 54 insertions(+), 47 deletions(-) diff --git a/packages/rocketchat-ui-login/client/login/footer.js b/packages/rocketchat-ui-login/client/login/footer.js index e729fdb06b8a..8e06f8db521f 100644 --- a/packages/rocketchat-ui-login/client/login/footer.js +++ b/packages/rocketchat-ui-login/client/login/footer.js @@ -1,7 +1,7 @@ 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'; Template.loginFooter.onCreated(function() { this.suggestedLanguage = new ReactiveVar(); @@ -10,7 +10,7 @@ Template.loginFooter.onCreated(function() { const loadAndSetSuggestedLanguage = (language) => TAPi18n._loadLanguage(language) .then(() => this.suggestedLanguage.set(language)); - const serverLanguage = RocketChat.settings.get('Language'); + const serverLanguage = settings.get('Language'); if (serverLanguage !== language) { loadAndSetSuggestedLanguage(serverLanguage || 'en'); diff --git a/packages/rocketchat-ui-login/client/login/form.js b/packages/rocketchat-ui-login/client/login/form.js index 1e455dd69540..33241f77c3d7 100644 --- a/packages/rocketchat-ui-login/client/login/form.js +++ b/packages/rocketchat-ui-login/client/login/form.js @@ -4,8 +4,9 @@ import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { t, handleError } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -16,14 +17,14 @@ Template.loginForm.helpers({ return user && user.username; }, namePlaceholder() { - if (RocketChat.settings.get('Accounts_RequireNameForSignUp')) { + if (settings.get('Accounts_RequireNameForSignUp')) { return t('Name'); } else { return t('Name_optional'); } }, showFormLogin() { - return RocketChat.settings.get('Accounts_ShowFormLogin'); + return settings.get('Accounts_ShowFormLogin'); }, state(...state) { return state.indexOf(Template.instance().state.get()) > -1; @@ -44,32 +45,32 @@ Template.loginForm.helpers({ } }, loginTerms() { - return RocketChat.settings.get('Layout_Login_Terms'); + return settings.get('Layout_Login_Terms'); }, registrationAllowed() { const validSecretUrl = Template.instance().validSecretURL; - return RocketChat.settings.get('Accounts_RegistrationForm') === 'Public' || (validSecretUrl && validSecretUrl.get()); + return settings.get('Accounts_RegistrationForm') === 'Public' || (validSecretUrl && validSecretUrl.get()); }, linkReplacementText() { - return RocketChat.settings.get('Accounts_RegistrationForm_LinkReplacementText'); + return settings.get('Accounts_RegistrationForm_LinkReplacementText'); }, passwordResetAllowed() { - return RocketChat.settings.get('Accounts_PasswordReset'); + return settings.get('Accounts_PasswordReset'); }, requirePasswordConfirmation() { - return RocketChat.settings.get('Accounts_RequirePasswordConfirmation'); + return settings.get('Accounts_RequirePasswordConfirmation'); }, emailOrUsernamePlaceholder() { - return RocketChat.settings.get('Accounts_EmailOrUsernamePlaceholder') || t('Email_or_username'); + return settings.get('Accounts_EmailOrUsernamePlaceholder') || t('Email_or_username'); }, passwordPlaceholder() { - return RocketChat.settings.get('Accounts_PasswordPlaceholder') || t('Password'); + return settings.get('Accounts_PasswordPlaceholder') || t('Password'); }, confirmPasswordPlaceholder() { - return RocketChat.settings.get('Accounts_ConfirmPasswordPlaceholder') || t('Confirm_password'); + return settings.get('Accounts_ConfirmPasswordPlaceholder') || t('Confirm_password'); }, manuallyApproveNewUsers() { - return RocketChat.settings.get('Accounts_ManuallyApproveNewUsers'); + return settings.get('Accounts_ManuallyApproveNewUsers'); }, }); @@ -84,7 +85,7 @@ Template.loginForm.events({ if (state === 'email-verification') { Meteor.call('sendConfirmationEmail', s.trim(formData.email), () => { instance.loading.set(false); - RocketChat.callbacks.run('userConfirmationEmailRequested'); + callbacks.run('userConfirmationEmailRequested'); toastr.success(t('We_have_sent_registration_email')); return instance.state.set('login'); }); @@ -97,7 +98,7 @@ Template.loginForm.events({ return instance.state.set('login'); } else { instance.loading.set(false); - RocketChat.callbacks.run('userForgotPasswordEmailRequested'); + callbacks.run('userForgotPasswordEmailRequested'); toastr.success(t('If_this_email_is_registered')); return instance.state.set('login'); } @@ -116,7 +117,7 @@ Template.loginForm.events({ } return; } - RocketChat.callbacks.run('userRegistered'); + callbacks.run('userRegistered'); return Meteor.loginWithPassword(s.trim(formData.email), formData.pass, function(error) { if (error && error.error === 'error-invalid-email') { return instance.state.set('wait-email-activation'); @@ -129,10 +130,10 @@ Template.loginForm.events({ }); } else { let loginMethod = 'loginWithPassword'; - if (RocketChat.settings.get('LDAP_Enable')) { + if (settings.get('LDAP_Enable')) { loginMethod = 'loginWithLDAP'; } - if (RocketChat.settings.get('CROWD_Enable')) { + if (settings.get('CROWD_Enable')) { loginMethod = 'loginWithCrowd'; } return Meteor[loginMethod](s.trim(formData.emailOrUsername), formData.pass, function(error) { @@ -154,15 +155,15 @@ Template.loginForm.events({ }, 'click .register'() { Template.instance().state.set('register'); - return RocketChat.callbacks.run('loginPageStateChange', Template.instance().state.get()); + return callbacks.run('loginPageStateChange', Template.instance().state.get()); }, 'click .back-to-login'() { Template.instance().state.set('login'); - return RocketChat.callbacks.run('loginPageStateChange', Template.instance().state.get()); + return callbacks.run('loginPageStateChange', Template.instance().state.get()); }, 'click .forgot-password'() { Template.instance().state.set('forgot-password'); - return RocketChat.callbacks.run('loginPageStateChange', Template.instance().state.get()); + return callbacks.run('loginPageStateChange', Template.instance().state.get()); }, }); @@ -171,10 +172,10 @@ Template.loginForm.onCreated(function() { this.customFields = new ReactiveVar; this.loading = new ReactiveVar(false); 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 { - return this.customFields.set(JSON.parse(RocketChat.settings.get('Accounts_CustomFields'))); + return this.customFields.set(JSON.parse(settings.get('Accounts_CustomFields'))); } catch (error1) { return console.error('Invalid JSON for Accounts_CustomFields'); } @@ -239,13 +240,13 @@ Template.loginForm.onCreated(function() { } } if (state === 'register') { - if (RocketChat.settings.get('Accounts_RequireNameForSignUp') && !formObj.name) { + if (settings.get('Accounts_RequireNameForSignUp') && !formObj.name) { validationObj.name = t('Invalid_name'); } - if (RocketChat.settings.get('Accounts_RequirePasswordConfirmation') && formObj['confirm-pass'] !== formObj.pass) { + if (settings.get('Accounts_RequirePasswordConfirmation') && formObj['confirm-pass'] !== formObj.pass) { validationObj['confirm-pass'] = t('Invalid_confirm_pass'); } - if (RocketChat.settings.get('Accounts_ManuallyApproveNewUsers') && !formObj.reason) { + if (settings.get('Accounts_ManuallyApproveNewUsers') && !formObj.reason) { validationObj.reason = t('Invalid_reason'); } validateCustomFields(formObj, validationObj); @@ -274,7 +275,7 @@ Template.loginForm.onCreated(function() { Template.loginForm.onRendered(function() { Session.set('loginDefaultState'); return Tracker.autorun(() => { - RocketChat.callbacks.run('loginPageStateChange', this.state.get()); + callbacks.run('loginPageStateChange', this.state.get()); switch (this.state.get()) { case 'login': case 'forgot-password': diff --git a/packages/rocketchat-ui-login/client/login/header.js b/packages/rocketchat-ui-login/client/login/header.js index 40ad6b094c01..f1cd0c2595c5 100644 --- a/packages/rocketchat-ui-login/client/login/header.js +++ b/packages/rocketchat-ui-login/client/login/header.js @@ -1,9 +1,9 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.loginHeader.helpers({ logoUrl() { - const asset = RocketChat.settings.get('Assets_logo'); + const asset = settings.get('Assets_logo'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset != null) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; diff --git a/packages/rocketchat-ui-login/client/login/layout.js b/packages/rocketchat-ui-login/client/login/layout.js index 40d321215af1..9c702ab0e086 100644 --- a/packages/rocketchat-ui-login/client/login/layout.js +++ b/packages/rocketchat-ui-login/client/login/layout.js @@ -1,5 +1,5 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.loginLayout.onRendered(function() { $('#initial-page-loading').remove(); @@ -7,7 +7,7 @@ Template.loginLayout.onRendered(function() { Template.loginLayout.helpers({ backgroundUrl() { - const asset = RocketChat.settings.get('Assets_background'); + const asset = settings.get('Assets_background'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset && (asset.url || asset.defaultUrl)) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; diff --git a/packages/rocketchat-ui-login/client/reset-password/resetPassword.js b/packages/rocketchat-ui-login/client/reset-password/resetPassword.js index 90484e88b408..908fa27b95ea 100644 --- a/packages/rocketchat-ui-login/client/reset-password/resetPassword.js +++ b/packages/rocketchat-ui-login/client/reset-password/resetPassword.js @@ -2,9 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { modal } from 'meteor/rocketchat:ui'; +import { modal } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Button } from 'meteor/rocketchat:ui'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import toastr from 'toastr'; Template.resetPassword.helpers({ @@ -35,7 +36,7 @@ Template.resetPassword.events({ event.preventDefault(); const button = instance.$('button.resetpass'); - RocketChat.Button.loading(button); + Button.loading(button); if (Meteor.userId() && !FlowRouter.getParam('token')) { Meteor.call('setUserPassword', instance.find('[name=newPassword]').value, function(error) { @@ -49,12 +50,12 @@ Template.resetPassword.events({ }); } else { Accounts.resetPassword(FlowRouter.getParam('token'), instance.find('[name=newPassword]').value, function(error) { - RocketChat.Button.reset(button); + Button.reset(button); if (error) { console.log(error); if (error.error === 'totp-required') { toastr.success(t('Password_changed_successfully')); - RocketChat.callbacks.run('userPasswordReset'); + callbacks.run('userPasswordReset'); FlowRouter.go('login'); } else { modal.open({ @@ -65,7 +66,7 @@ Template.resetPassword.events({ } else { FlowRouter.go('home'); toastr.success(t('Password_changed_successfully')); - RocketChat.callbacks.run('userPasswordReset'); + callbacks.run('userPasswordReset'); } }); } diff --git a/packages/rocketchat-ui-login/client/username/layout.js b/packages/rocketchat-ui-login/client/username/layout.js index 2f58d4fdb0d3..771d1d40f079 100644 --- a/packages/rocketchat-ui-login/client/username/layout.js +++ b/packages/rocketchat-ui-login/client/username/layout.js @@ -1,9 +1,9 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.usernameLayout.helpers({ backgroundUrl() { - const asset = RocketChat.settings.get('Assets_background'); + const asset = settings.get('Assets_background'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset && (asset.url || asset.defaultUrl)) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; diff --git a/packages/rocketchat-ui-login/client/username/username.js b/packages/rocketchat-ui-login/client/username/username.js index 08f185b01647..20af7ab06f22 100644 --- a/packages/rocketchat-ui-login/client/username/username.js +++ b/packages/rocketchat-ui-login/client/username/username.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Button } from 'meteor/rocketchat:ui'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; Template.username.onCreated(function() { @@ -23,7 +25,7 @@ Template.username.helpers({ }, backgroundUrl() { - const asset = RocketChat.settings.get('Assets_background'); + const asset = settings.get('Assets_background'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset && (asset.url || asset.defaultUrl)) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; @@ -52,13 +54,13 @@ Template.username.events({ instance.username.set(username); const button = $(event.target).find('button.login'); - RocketChat.Button.loading(button); + Button.loading(button); const value = $('#username').val().trim(); if (value === '') { username.empty = true; instance.username.set(username); - RocketChat.Button.reset(button); + Button.reset(button); return; } @@ -74,9 +76,9 @@ Template.username.events({ username.escaped = _.escape(value); } - RocketChat.Button.reset(button); + Button.reset(button); instance.username.set(username); - return RocketChat.callbacks.run('usernameSet'); + return callbacks.run('usernameSet'); }); }, }); diff --git a/packages/rocketchat-ui-login/package.js b/packages/rocketchat-ui-login/package.js index 4a3e59d2849e..2fd43145df10 100644 --- a/packages/rocketchat-ui-login/package.js +++ b/packages/rocketchat-ui-login/package.js @@ -15,9 +15,12 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', + 'rocketchat:ui-utils', 'rocketchat:lib', 'rocketchat:ui', 'rocketchat:assets', + 'rocketchat:settings', + 'rocketchat:callbacks', 'rocketchat:2fa', 'kadira:flow-router', 'kadira:blaze-layout', From 995f51a10381c79b9761ca44a74b6e657088908f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 15:31:37 -0200 Subject: [PATCH 090/101] Remove dependency of RC namespace in rc-ui-master --- packages/rocketchat-ui-master/client/main.js | 2 +- packages/rocketchat-ui-master/package.js | 1 + packages/rocketchat-ui-master/server/dynamic-css.js | 7 ++++++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/rocketchat-ui-master/client/main.js b/packages/rocketchat-ui-master/client/main.js index 80fa33440954..58299aa53e79 100644 --- a/packages/rocketchat-ui-master/client/main.js +++ b/packages/rocketchat-ui-master/client/main.js @@ -15,7 +15,7 @@ import { tooltip } from 'meteor/rocketchat:tooltip'; import Clipboard from 'clipboard'; import s from 'underscore.string'; -settings.collection.find({ _id:/theme-color-rc/i }, { fields:{ value: 1 } }).observe({ changed: () => { DynamicCss.run(true); } }); +settings.collection.find({ _id:/theme-color-rc/i }, { fields:{ value: 1 } }).observe({ changed: () => { DynamicCss.run(true, settings); } }); Template.body.onRendered(function() { new Clipboard('.clipboard'); diff --git a/packages/rocketchat-ui-master/package.js b/packages/rocketchat-ui-master/package.js index b5ca30505859..47cfbfbbbd07 100644 --- a/packages/rocketchat-ui-master/package.js +++ b/packages/rocketchat-ui-master/package.js @@ -18,6 +18,7 @@ Package.onUse(function(api) { 'reactive-var', 'rocketchat:utils', 'rocketchat:tooltip', + 'rocketchat:settings', 'rocketchat:ui-utils', 'rocketchat:ui-sidenav', 'meteorhacks:inject-initial', diff --git a/packages/rocketchat-ui-master/server/dynamic-css.js b/packages/rocketchat-ui-master/server/dynamic-css.js index 95f48091978d..ff871155d635 100644 --- a/packages/rocketchat-ui-master/server/dynamic-css.js +++ b/packages/rocketchat-ui-master/server/dynamic-css.js @@ -144,9 +144,14 @@ DynamicCss.run = debounce(function () { var replace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var settings = arguments.length && arguments[1]; + + if (replace && !settings) { + console.error('You must provide settings to the "run" function in DynamicCss'); + } if (replace) { - var colors = RocketChat.settings.collection.find({ + var colors = settings.collection.find({ _id: /theme-color-rc/i }, { fields: { From 060d85af7849e1c587180c6b6cc79f3b25a2302c Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 16:16:52 -0200 Subject: [PATCH 091/101] Remove dependency of RC namespace in rc-ui-message --- .../rocketchat-ui-message/client/message.js | 71 +++++++------- .../client/messageBox.js | 92 ++++++++++--------- .../client/popup/messagePopupChannel.js | 4 +- .../client/popup/messagePopupConfig.js | 40 ++++---- .../popup/messagePopupSlashCommandPreview.js | 7 +- .../client/startup/messageBoxActions.js | 28 +++--- packages/rocketchat-ui-message/package.js | 6 +- 7 files changed, 134 insertions(+), 114 deletions(-) diff --git a/packages/rocketchat-ui-message/client/message.js b/packages/rocketchat-ui-message/client/message.js index be794edea2e5..06856251b427 100644 --- a/packages/rocketchat-ui-message/client/message.js +++ b/packages/rocketchat-ui-message/client/message.js @@ -7,11 +7,14 @@ import _ from 'underscore'; import moment from 'moment'; import { DateFormat } from 'meteor/rocketchat:lib'; 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 { renderMessageBody, MessageTypes, MessageAction } from 'meteor/rocketchat:ui-utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { RoomRoles, UserRoles, Roles, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { AutoTranslate } from 'meteor/rocketchat:autotranslate'; -import { t } from 'meteor/rocketchat:utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Markdown } from 'meteor/rocketchat:markdown'; +import { t, getUserPreference, roomTypes } from 'meteor/rocketchat:utils'; async function renderPdfToCanvas(canvasId, pdfLink) { const isSafari = /constructor/i.test(window.HTMLElement) || @@ -87,7 +90,7 @@ Template.message.helpers({ } }, roleTags() { - if (!RocketChat.settings.get('UI_DisplayRoles') || RocketChat.getUserPreference(Meteor.userId(), 'hideRoles')) { + if (!settings.get('UI_DisplayRoles') || getUserPreference(Meteor.userId(), 'hideRoles')) { return []; } @@ -100,7 +103,7 @@ Template.message.helpers({ rid: this.rid, }); const roles = [...(userRoles && userRoles.roles) || [], ...(roomRoles && roomRoles.roles) || []]; - return RocketChat.models.Roles.find({ + return Roles.find({ _id: { $in: roles, }, @@ -142,10 +145,10 @@ Template.message.helpers({ if (!this.u) { return ''; } - return (RocketChat.settings.get('UI_Use_Real_Name') && this.u.name) || this.u.username; + return (settings.get('UI_Use_Real_Name') && this.u.name) || this.u.username; }, showUsername() { - return this.alias || (RocketChat.settings.get('UI_Use_Real_Name') && this.u && this.u.name); + return this.alias || (settings.get('UI_Use_Real_Name') && this.u && this.u.name); }, own() { if (this.u && this.u._id === Meteor.userId()) { @@ -156,7 +159,7 @@ Template.message.helpers({ return +this.ts; }, chatops() { - if (this.u && this.u.username === RocketChat.settings.get('Chatops_Username')) { + if (this.u && this.u.username === settings.get('Chatops_Username')) { return 'chatops-message'; } }, @@ -175,7 +178,7 @@ Template.message.helpers({ return Template.instance().body; }, system(returnClass) { - if (RocketChat.MessageTypes.isSystemMessage(this)) { + if (MessageTypes.isSystemMessage(this)) { if (returnClass) { return 'color-info-font-color'; } @@ -183,8 +186,8 @@ Template.message.helpers({ } }, showTranslated() { - if (RocketChat.settings.get('AutoTranslate_Enabled') && this.u && this.u._id !== Meteor.userId() && !RocketChat.MessageTypes.isSystemMessage(this)) { - const subscription = RocketChat.models.Subscriptions.findOne({ + if (settings.get('AutoTranslate_Enabled') && this.u && this.u._id !== Meteor.userId() && !MessageTypes.isSystemMessage(this)) { + const subscription = Subscriptions.findOne({ rid: this.rid, 'u._id': Meteor.userId(), }, { @@ -215,13 +218,13 @@ Template.message.helpers({ return (this.editedBy && this.editedBy.username) || '?'; }, canEdit() { - const hasPermission = RocketChat.authz.hasAtLeastOnePermission('edit-message', this.rid); - const isEditAllowed = RocketChat.settings.get('Message_AllowEditing'); + const hasPermission = hasAtLeastOnePermission('edit-message', this.rid); + const isEditAllowed = settings.get('Message_AllowEditing'); const editOwn = this.u && this.u._id === Meteor.userId(); if (!(hasPermission || (isEditAllowed && editOwn))) { return; } - const blockEditInMinutes = RocketChat.settings.get('Message_AllowEditing_BlockEditInMinutes'); + const blockEditInMinutes = settings.get('Message_AllowEditing_BlockEditInMinutes'); if (blockEditInMinutes) { let msgTs; if (this.ts != null) { @@ -237,13 +240,13 @@ Template.message.helpers({ } }, canDelete() { - const hasPermission = RocketChat.authz.hasAtLeastOnePermission('delete-message', this.rid); - const isDeleteAllowed = RocketChat.settings.get('Message_AllowDeleting'); + const hasPermission = hasAtLeastOnePermission('delete-message', this.rid); + const isDeleteAllowed = settings.get('Message_AllowDeleting'); const deleteOwn = this.u && this.u._id === Meteor.userId(); if (!(hasPermission || (isDeleteAllowed && deleteOwn))) { return; } - const blockDeleteInMinutes = RocketChat.settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); + const blockDeleteInMinutes = settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); if (blockDeleteInMinutes) { let msgTs; if (this.ts != null) { @@ -259,7 +262,7 @@ Template.message.helpers({ } }, showEditedStatus() { - return RocketChat.settings.get('Message_ShowEditedStatus'); + return settings.get('Message_ShowEditedStatus'); }, label() { if (this.i18nLabel) { @@ -270,12 +273,12 @@ Template.message.helpers({ }, hasOembed() { // there is no URLs, there is no template to show the oembed (oembed package removed) or oembed is not enable - if (!(this.urls && this.urls.length > 0) || !Template.oembedBaseWidget || !RocketChat.settings.get('API_Embed')) { + if (!(this.urls && this.urls.length > 0) || !Template.oembedBaseWidget || !settings.get('API_Embed')) { return false; } // check if oembed is disabled for message's sender - if ((RocketChat.settings.get('API_EmbedDisabledFor') || '').split(',').map((username) => username.trim()).includes(this.u && this.u.username)) { + if ((settings.get('API_EmbedDisabledFor') || '').split(',').map((username) => username.trim()).includes(this.u && this.u.username)) { return false; } return true; @@ -337,7 +340,7 @@ Template.message.helpers({ data.index = index; }, hideCog() { - const subscription = RocketChat.models.Subscriptions.findOne({ + const subscription = Subscriptions.findOne({ rid: this.rid, }); if (subscription == null) { @@ -345,7 +348,7 @@ Template.message.helpers({ } }, channelName() { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this.rid }); + const subscription = Subscriptions.findOne({ rid: this.rid }); return subscription && subscription.name; }, roomIcon() { @@ -353,7 +356,7 @@ Template.message.helpers({ if (room && room.t === 'd') { return 'at'; } - return RocketChat.roomTypes.getIcon(room && room.t); + return roomTypes.getIcon(room && room.t); }, fromSearch() { return this.customClass === 'search'; @@ -373,7 +376,7 @@ Template.message.helpers({ context = 'message'; } - return RocketChat.MessageAction.getButtons(Template.currentData(), context, messageGroup); + return MessageAction.getButtons(Template.currentData(), context, messageGroup); }, isSnippet() { return this.actionContext === 'snippeted'; @@ -384,9 +387,9 @@ Template.message.helpers({ Template.message.onCreated(function() { let msg = Template.currentData(); - this.wasEdited = (msg.editedAt != null) && !RocketChat.MessageTypes.isSystemMessage(msg); + this.wasEdited = (msg.editedAt != null) && !MessageTypes.isSystemMessage(msg); - this.room = RocketChat.models.Rooms.findOne({ + this.room = Rooms.findOne({ _id: msg.rid, }, { fields: { @@ -395,8 +398,8 @@ Template.message.onCreated(function() { }); return this.body = (() => { - const isSystemMessage = RocketChat.MessageTypes.isSystemMessage(msg); - const messageType = RocketChat.MessageTypes.getType(msg) || {}; + const isSystemMessage = MessageTypes.isSystemMessage(msg); + const messageType = MessageTypes.getType(msg) || {}; if (messageType.render) { msg = messageType.render(msg); } else if (messageType.template) { @@ -407,16 +410,16 @@ Template.message.onCreated(function() { } else { msg = TAPi18n.__(messageType.message); } - } else if (msg.u && msg.u.username === RocketChat.settings.get('Chatops_Username')) { + } else if (msg.u && msg.u.username === settings.get('Chatops_Username')) { msg.html = msg.msg; - msg = RocketChat.callbacks.run('renderMentions', msg); + msg = callbacks.run('renderMentions', msg); msg = msg.html; } else { msg = renderMessageBody(msg); } if (isSystemMessage) { - msg.html = RocketChat.Markdown.parse(msg.html); + msg.html = Markdown.parse(msg.html); } return msg; })(); @@ -458,7 +461,7 @@ Template.message.onViewRendered = function(context) { } if (previousDataset.groupable === 'false' || currentDataset.groupable === 'false') { $currentNode.removeClass('sequential'); - } else if (previousDataset.username !== currentDataset.username || parseInt(currentDataset.timestamp) - parseInt(previousDataset.timestamp) > RocketChat.settings.get('Message_GroupingPeriod') * 1000) { + } else if (previousDataset.username !== currentDataset.username || parseInt(currentDataset.timestamp) - parseInt(previousDataset.timestamp) > settings.get('Message_GroupingPeriod') * 1000) { $currentNode.removeClass('sequential'); } else if (!$currentNode.hasClass('new-day')) { $currentNode.addClass('sequential'); @@ -472,7 +475,7 @@ Template.message.onViewRendered = function(context) { $nextNode.removeClass('new-day'); } if (nextDataset.groupable !== 'false') { - if (nextDataset.username !== currentDataset.username || parseInt(nextDataset.timestamp) - parseInt(currentDataset.timestamp) > RocketChat.settings.get('Message_GroupingPeriod') * 1000) { + if (nextDataset.username !== currentDataset.username || parseInt(nextDataset.timestamp) - parseInt(currentDataset.timestamp) > settings.get('Message_GroupingPeriod') * 1000) { $nextNode.removeClass('sequential'); } else if (!$nextNode.hasClass('new-day') && !$currentNode.hasClass('temp')) { $nextNode.addClass('sequential'); diff --git a/packages/rocketchat-ui-message/client/messageBox.js b/packages/rocketchat-ui-message/client/messageBox.js index ed71ed5613ff..c490c75940bb 100644 --- a/packages/rocketchat-ui-message/client/messageBox.js +++ b/packages/rocketchat-ui-message/client/messageBox.js @@ -4,10 +4,16 @@ import { Tracker } from 'meteor/tracker'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Markdown } from 'meteor/rocketchat:markdown'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { EmojiPicker } from 'meteor/rocketchat:emoji'; 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 { KonchatNotification, fileUpload, AudioRecorder, chatMessages, MsgTyping, ChatMessages } from 'meteor/rocketchat:ui'; +import { RoomHistoryManager, RoomManager, popover, messageBox, Layout } from 'meteor/rocketchat:ui-utils'; +import { ChatSubscription } from 'meteor/rocketchat:models'; +import { t, roomTypes, getUserPreference } from 'meteor/rocketchat:utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; import { Katex } from 'meteor/rocketchat:katex'; import toastr from 'toastr'; import moment from 'moment'; @@ -92,45 +98,45 @@ const markdownButtons = [ icon: 'bold', pattern: '*{{text}}*', command: 'b', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') === 'original', + condition: () => Markdown && settings.get('Markdown_Parser') === 'original', }, { label: 'bold', icon: 'bold', pattern: '**{{text}}**', command: 'b', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') === 'marked', + condition: () => Markdown && settings.get('Markdown_Parser') === 'marked', }, { label: 'italic', icon: 'italic', pattern: '_{{text}}_', command: 'i', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') !== 'disabled', + condition: () => Markdown && settings.get('Markdown_Parser') !== 'disabled', }, { label: 'strike', icon: 'strike', pattern: '~{{text}}~', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') === 'original', + condition: () => Markdown && settings.get('Markdown_Parser') === 'original', }, { label: 'strike', icon: 'strike', pattern: '~~{{text}}~~', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') === 'marked', + condition: () => Markdown && settings.get('Markdown_Parser') === 'marked', }, { label: 'inline_code', icon: 'code', pattern: '`{{text}}`', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') !== 'disabled', + condition: () => Markdown && settings.get('Markdown_Parser') !== 'disabled', }, { label: 'multi_line', icon: 'multi-line', pattern: '```\n{{text}}\n``` ', - condition: () => RocketChat.Markdown && RocketChat.settings.get('Markdown_Parser') !== 'disabled', + condition: () => Markdown && settings.get('Markdown_Parser') !== 'disabled', }, { label: katexSyntax, @@ -141,7 +147,7 @@ const markdownButtons = [ const methods = { actions() { - const groups = RocketChat.messageBox.actions.get(); + const groups = messageBox.actions.get(); return Object.keys(groups).reduce((ret, el) => ret.concat(groups[el]), []); }, }; @@ -171,23 +177,23 @@ Template.messageBox.helpers({ } }, showFormattingTips() { - return RocketChat.settings.get('Message_ShowFormattingTips'); + return settings.get('Message_ShowFormattingTips'); }, canJoin() { - return Meteor.userId() && RocketChat.roomTypes.verifyShowJoinLink(this._id); + return Meteor.userId() && roomTypes.verifyShowJoinLink(this._id); }, joinCodeRequired() { const code = Session.get(`roomData${ this._id }`); return code && code.joinCodeRequired; }, subscribed() { - return RocketChat.roomTypes.verifyCanSendMessage(this._id); + return roomTypes.verifyCanSendMessage(this._id); }, allowedToSend() { - if (RocketChat.roomTypes.readOnly(this._id, Meteor.user())) { + if (roomTypes.readOnly(this._id, Meteor.user())) { return false; } - if (RocketChat.roomTypes.archived(this._id)) { + if (roomTypes.archived(this._id)) { return false; } const roomData = Session.get(`roomData${ this._id }`); @@ -257,27 +263,27 @@ Template.messageBox.helpers({ }; }, groupAttachHidden() { - if (RocketChat.settings.get('Message_Attachments_GroupAttach')) { + if (settings.get('Message_Attachments_GroupAttach')) { return 'hidden'; } }, notSubscribedTpl() { - return RocketChat.roomTypes.getNotSubscribedTpl(this._id); + return roomTypes.getNotSubscribedTpl(this._id); }, anonymousRead() { - return (Meteor.userId() == null) && RocketChat.settings.get('Accounts_AllowAnonymousRead') === true; + return (Meteor.userId() == null) && settings.get('Accounts_AllowAnonymousRead') === true; }, anonymousWrite() { - return (Meteor.userId() == null) && RocketChat.settings.get('Accounts_AllowAnonymousRead') === true && RocketChat.settings.get('Accounts_AllowAnonymousWrite') === true; + return (Meteor.userId() == null) && settings.get('Accounts_AllowAnonymousRead') === true && settings.get('Accounts_AllowAnonymousWrite') === true; }, disableSendIcon() { return !Template.instance().sendIcon.get() ? 'disabled' : ''; }, embeddedVersion() { - return RocketChat.Layout.isEmbedded(); + return Layout.isEmbedded(); }, isEmojiEnable() { - return RocketChat.getUserPreference(Meteor.userId(), 'useEmojis'); + return getUserPreference(Meteor.userId(), 'useEmojis'); }, dataReply() { return Template.instance().dataReply.get(); @@ -285,10 +291,10 @@ Template.messageBox.helpers({ isAudioMessageAllowed() { return (navigator.mediaDevices || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) && - RocketChat.settings.get('FileUpload_Enabled') && - RocketChat.settings.get('Message_AudioRecorderEnabled') && - (!RocketChat.settings.get('FileUpload_MediaTypeWhiteList') || - RocketChat.settings.get('FileUpload_MediaTypeWhiteList').match(/audio\/mp3|audio\/\*/i)); + settings.get('FileUpload_Enabled') && + settings.get('Message_AudioRecorderEnabled') && + (!settings.get('FileUpload_MediaTypeWhiteList') || + settings.get('FileUpload_MediaTypeWhiteList').match(/audio\/mp3|audio\/\*/i)); }, }); @@ -354,7 +360,7 @@ Template.messageBox.events({ if (err != null) { toastr.error(t(err.reason)); } - if (RocketChat.authz.hasAllPermission('preview-c-room') === false && RoomHistoryManager.getRoom(this._id).loaded === 0) { + if (hasAllPermission('preview-c-room') === false && RoomHistoryManager.getRoom(this._id).loaded === 0) { RoomManager.getOpenedRoomByRid(this._id).streamActive = false; RoomManager.getOpenedRoomByRid(this._id).ready = false; RoomHistoryManager.getRoom(this._id).loaded = null; @@ -419,7 +425,7 @@ Template.messageBox.events({ e.preventDefault(); return { file: item.getAsFile(), - name: `Clipboard - ${ moment().format(RocketChat.settings.get('Message_TimeAndDateFormat')) }`, + name: `Clipboard - ${ moment().format(settings.get('Message_TimeAndDateFormat')) }`, }; }); if (files.length) { @@ -461,7 +467,7 @@ Template.messageBox.events({ applyMd.apply(this, [e, t]); }, 'click .rc-message-box__action-menu'(e) { - const groups = RocketChat.messageBox.actions.get(); + const groups = messageBox.actions.get(); const config = { popoverClass: 'message-box', columns: [ @@ -651,14 +657,14 @@ Template.messageBox.events({ event.stopPropagation(); event.preventDefault(); - if (!RocketChat.getUserPreference(Meteor.userId(), 'useEmojis')) { + if (!getUserPreference(Meteor.userId(), 'useEmojis')) { return false; } - if (RocketChat.EmojiPicker.isOpened()) { - RocketChat.EmojiPicker.close(); + if (EmojiPicker.isOpened()) { + EmojiPicker.close(); } else { - RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => { + EmojiPicker.open(event.currentTarget, (emoji) => { const { input } = chatMessages[RoomManager.openedRoom]; const emojiValue = `:${ emoji }:`; @@ -696,22 +702,24 @@ Template.messageBox.onRendered(function() { }); Template.messageBox.onCreated(function() { - RocketChat.EmojiPicker.init(); + EmojiPicker.init(); this.dataReply = new ReactiveVar(''); // if user is replying to a mssg, this will contain data of the mssg being replied to this.isMessageFieldEmpty = new ReactiveVar(true); this.sendIcon = new ReactiveVar(false); - RocketChat.messageBox.emit('created', this); + messageBox.emit('created', this); }); +export let geolocation; + Meteor.startup(function() { - RocketChat.Geolocation = new ReactiveVar(false); + geolocation = new ReactiveVar(false); Tracker.autorun(function() { - const MapView_GMapsAPIKey = RocketChat.settings.get('MapView_GMapsAPIKey'); - if (RocketChat.settings.get('MapView_Enabled') === true && MapView_GMapsAPIKey && MapView_GMapsAPIKey.length && navigator.geolocation && navigator.geolocation.getCurrentPosition) { - const success = (position) => RocketChat.Geolocation.set(position); + const MapView_GMapsAPIKey = settings.get('MapView_GMapsAPIKey'); + if (settings.get('MapView_Enabled') === true && MapView_GMapsAPIKey && MapView_GMapsAPIKey.length && navigator.geolocation && navigator.geolocation.getCurrentPosition) { + const success = (position) => geolocation.set(position); const error = (error) => { console.log('Error getting your geolocation', error); - return RocketChat.Geolocation.set(false); + return geolocation.set(false); }; const options = { enableHighAccuracy: true, @@ -720,10 +728,10 @@ Meteor.startup(function() { }; return navigator.geolocation.watchPosition(success, error, options); } else { - return RocketChat.Geolocation.set(false); + return geolocation.set(false); } }); - RocketChat.callbacks.add('enter-room', function() { + callbacks.add('enter-room', function() { setTimeout(() => { if (chatMessages[RoomManager.openedRoom].input) { chatMessages[RoomManager.openedRoom].input.focus(); diff --git a/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js b/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js index 51d3937fa0af..b910867792d6 100644 --- a/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js +++ b/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js @@ -1,8 +1,8 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { roomTypes } from 'meteor/rocketchat:utils'; Template.messagePopupChannel.helpers({ channelIcon() { - return RocketChat.roomTypes.getIcon(this.t); + return roomTypes.getIcon(this.t); }, }); diff --git a/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js b/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js index 7b3184eb0a01..218b4ad3a971 100644 --- a/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js +++ b/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js @@ -5,9 +5,11 @@ import { Blaze } from 'meteor/blaze'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, Subscriptions, Users } from 'meteor/rocketchat:models'; +import { hasAllPermission, hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { EmojiPicker, emoji } from 'meteor/rocketchat:emoji'; import { RoomManager } from 'meteor/rocketchat:ui-utils'; -import { t } from 'meteor/rocketchat:utils'; +import { t, getUserPreference, slashCommands } from 'meteor/rocketchat:utils'; import _ from 'underscore'; const usersFromRoomMessages = new Mongo.Collection(null); @@ -18,7 +20,7 @@ const reloadUsersFromRoomMessages = (userId, rid) => { usersFromRoomMessages.remove({}); const uniqueMessageUsersControl = {}; - RocketChat.models.Messages.find({ + Messages.find({ rid, 'u.username': { $ne: user.username }, t: { $exists: false }, @@ -93,7 +95,7 @@ const fetchUsersFromServer = (filterText, records, cb, rid) => { }; const fetchRoomsFromServer = (filterText, records, cb, rid) => { - if (!RocketChat.authz.hasAllPermission('view-outside-room')) { + if (!hasAllPermission('view-outside-room')) { return cb && cb([]); } @@ -128,7 +130,7 @@ const addEmojiToRecents = (emoji) => { const view = Blaze.getView(pickerEl); if (view) { Template._withTemplateInstanceFunc(view.templateInstance, () => { - RocketChat.EmojiPicker.addRecent(emoji.replace(/:/g, '')); + EmojiPicker.addRecent(emoji.replace(/:/g, '')); }); } } @@ -161,16 +163,16 @@ const seeColor = new RegExp('_t(?:o|$)(?:n|$)(?:e|$)(?:[1-5]|$)(?:\:|$)$'); const getEmojis = function(collection, filter) { const key = `:${ filter }`; - if (!RocketChat.getUserPreference(Meteor.userId(), 'useEmojis')) { + if (!getUserPreference(Meteor.userId(), 'useEmojis')) { return []; } - if (!RocketChat.emoji.packages.emojione || RocketChat.emoji.packages.emojione.asciiList[key]) { + if (!emoji.packages.emojione || emoji.packages.emojione.asciiList[key]) { return []; } const regExp = new RegExp(RegExp.escape(filter), 'i'); - const recents = RocketChat.EmojiPicker.getRecent().map((item) => `:${ item }:`); + const recents = EmojiPicker.getRecent().map((item) => `:${ item }:`); return Object.keys(collection).map((_id) => { const data = collection[key]; return { _id, data }; @@ -214,8 +216,8 @@ Template.messagePopupConfig.helpers({ // If needed, add to list the online users if (items.length < 5 && filterText !== '') { const usernamesAlreadyFetched = items.map(({ username }) => username); - if (!RocketChat.authz.hasAllPermission('view-outside-room')) { - const usernamesFromDMs = RocketChat.models.Subscriptions + if (!hasAllPermission('view-outside-room')) { + const usernamesFromDMs = Subscriptions .find( { t: 'd', @@ -236,7 +238,7 @@ Template.messagePopupConfig.helpers({ } ) .map(({ name }) => name); - const newItems = RocketChat.models.Users + const newItems = Users .find( { username: { @@ -344,7 +346,7 @@ Template.messagePopupConfig.helpers({ const self = this; const config = { title: t('Channels'), - collection: RocketChat.models.Subscriptions, + collection: Subscriptions, trigger: '#', suffix: ' ', textFilterDelay: 500, @@ -383,7 +385,7 @@ Template.messagePopupConfig.helpers({ const self = this; const config = { title: t('Commands'), - collection: RocketChat.slashCommands.commands, + collection: slashCommands.commands, trigger: '/', suffix: ' ', triggerAnywhere: false, @@ -409,21 +411,21 @@ Template.messagePopupConfig.helpers({ return true; } - return RocketChat.authz.hasAtLeastOnePermission(command.permission, Session.get('openedRoom')); + return hasAtLeastOnePermission(command.permission, Session.get('openedRoom')); }).sort((a, b) => a._id > b._id).slice(0, 11); }, }; return config; }, emojiEnabled() { - return RocketChat.emoji != null; + return emoji != null; }, popupEmojiConfig() { - if (RocketChat.emoji != null) { + if (emoji != null) { const self = this; return { title: t('Emoji'), - collection: RocketChat.emoji.list, + collection: emoji.list, template: 'messagePopupEmoji', trigger: ':', prefix: '', @@ -438,11 +440,11 @@ Template.messagePopupConfig.helpers({ } }, popupReactionEmojiConfig() { - if (RocketChat.emoji != null) { + if (emoji != null) { const self = this; return { title: t('Emoji'), - collection: RocketChat.emoji.list, + collection: emoji.list, template: 'messagePopupEmoji', trigger: '\\+:', prefix: '+', diff --git a/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js b/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js index 63090414a00a..bcc7717daee4 100644 --- a/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js +++ b/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.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 } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; import { toolbarSearch } from 'meteor/rocketchat:ui-sidenav'; import _ from 'underscore'; @@ -123,12 +124,12 @@ Template.messagePopupSlashCommandPreview.onCreated(function() { const matches = inputValueAtCursor.match(template.selectorRegex); const cmd = matches[1].replace('/', '').trim().toLowerCase(); - const command = RocketChat.slashCommands.commands[cmd]; + const command = slashCommands.commands[cmd]; // Ensure the command they're typing actually exists // And it provides a command preview // And if it provides a permission to check, they have permission to run the command - if (!command || !command.providesPreview || (command.permission && !RocketChat.authz.hasAtLeastOnePermission(command.permission, Session.get('openedRoom')))) { + if (!command || !command.providesPreview || (command.permission && !hasAtLeastOnePermission(command.permission, Session.get('openedRoom')))) { template.open.set(false); return; } diff --git a/packages/rocketchat-ui-message/client/startup/messageBoxActions.js b/packages/rocketchat-ui-message/client/startup/messageBoxActions.js index 7ab590c7d9dd..3f2acbe89568 100644 --- a/packages/rocketchat-ui-message/client/startup/messageBoxActions.js +++ b/packages/rocketchat-ui-message/client/startup/messageBoxActions.js @@ -2,27 +2,29 @@ import { Meteor } from 'meteor/meteor'; import { Random } from 'meteor/random'; import mime from 'mime-type/with-db'; import { VRecDialog } from 'meteor/rocketchat:ui-vrecord'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { modal, fileUpload } from 'meteor/rocketchat:ui'; +import { messageBox, modal } from 'meteor/rocketchat:ui-utils'; +import { fileUpload } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; import { t } from 'meteor/rocketchat:utils'; +import { geolocation } from '../messageBox'; -RocketChat.messageBox.actions.add('Create_new', 'Video_message', { +messageBox.actions.add('Create_new', 'Video_message', { id: 'video-message', icon: 'video', condition: () => (navigator.mediaDevices || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) && window.MediaRecorder && - RocketChat.settings.get('FileUpload_Enabled') && - RocketChat.settings.get('Message_VideoRecorderEnabled') && - (!RocketChat.settings.get('FileUpload_MediaTypeWhiteList') || - RocketChat.settings.get('FileUpload_MediaTypeWhiteList').match(/video\/webm|video\/\*/i)), + settings.get('FileUpload_Enabled') && + settings.get('Message_VideoRecorderEnabled') && + (!settings.get('FileUpload_MediaTypeWhiteList') || + settings.get('FileUpload_MediaTypeWhiteList').match(/video\/webm|video\/\*/i)), action: ({ messageBox }) => (VRecDialog.opened ? VRecDialog.close() : VRecDialog.open(messageBox)), }); -RocketChat.messageBox.actions.add('Add_files_from', 'Computer', { +messageBox.actions.add('Add_files_from', 'Computer', { id: 'file-upload', icon: 'computer', - condition: () => RocketChat.settings.get('FileUpload_Enabled'), + condition: () => settings.get('FileUpload_Enabled'), action({ event }) { event.preventDefault(); const $input = $(document.createElement('input')); @@ -59,14 +61,14 @@ RocketChat.messageBox.actions.add('Add_files_from', 'Computer', { }, }); -RocketChat.messageBox.actions.add('Share', 'My_location', { +messageBox.actions.add('Share', 'My_location', { id: 'share-location', icon: 'map-pin', - condition: () => RocketChat.Geolocation.get() !== false, + condition: () => geolocation.get() !== false, action({ rid }) { - const position = RocketChat.Geolocation.get(); + const position = geolocation.get(); const { latitude, longitude } = position.coords; - const text = `
`; + const text = `
`; modal.open({ title: t('Share_Location_Title'), diff --git a/packages/rocketchat-ui-message/package.js b/packages/rocketchat-ui-message/package.js index 550a41dc6d9d..1cc6fe32bcc3 100644 --- a/packages/rocketchat-ui-message/package.js +++ b/packages/rocketchat-ui-message/package.js @@ -17,7 +17,6 @@ Package.onUse(function(api) { 'templating', 'tracker', 'rocketchat:utils', - 'rocketchat:ui', 'rocketchat:ui-utils', 'rocketchat:emoji', 'rocketchat:katex', @@ -28,6 +27,11 @@ Package.onUse(function(api) { 'rocketchat:ui-sidenav', 'rocketchat:file-upload', 'rocketchat:autotranslate', + 'rocketchat:authorization', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:markdown', ]); api.addAssets('../../node_modules/pdfjs-dist/build/pdf.worker.js', 'client'); api.mainModule('client/index.js', 'client'); From 00b33ca89b3cafe0579ce664db85c459950d4b21 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 16:25:27 -0200 Subject: [PATCH 092/101] REmove dependency of RC namespace in rc-user-data-download --- .../rocketchat-user-data-download/package.js | 3 +- .../server/cronProcessDownloads.js | 43 ++++++++++--------- .../server/startup/settings.js | 4 +- 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/packages/rocketchat-user-data-download/package.js b/packages/rocketchat-user-data-download/package.js index e10af05cc569..6fcd5038490d 100644 --- a/packages/rocketchat-user-data-download/package.js +++ b/packages/rocketchat-user-data-download/package.js @@ -10,7 +10,8 @@ Package.onUse(function(api) { 'ecmascript', 'rocketchat:file', 'rocketchat:file-upload', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', 'webapp', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-user-data-download/server/cronProcessDownloads.js b/packages/rocketchat-user-data-download/server/cronProcessDownloads.js index f3fd2d60191f..260f6fb76c30 100644 --- a/packages/rocketchat-user-data-download/server/cronProcessDownloads.js +++ b/packages/rocketchat-user-data-download/server/cronProcessDownloads.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions, Rooms, Users, Uploads, Messages, UserDataFiles, ExportOperations } from 'meteor/rocketchat:models'; import { FileUpload } from 'meteor/rocketchat:file-upload'; import { SyncedCron } from 'meteor/littledata:synced-cron'; import fs from 'fs'; @@ -9,15 +10,15 @@ import archiver from 'archiver'; import * as Mailer from 'meteor/rocketchat:mailer'; let zipFolder = '/tmp/zipFiles'; -if (RocketChat.settings.get('UserData_FileSystemZipPath') != null) { - if (RocketChat.settings.get('UserData_FileSystemZipPath').trim() !== '') { - zipFolder = RocketChat.settings.get('UserData_FileSystemZipPath'); +if (settings.get('UserData_FileSystemZipPath') != null) { + if (settings.get('UserData_FileSystemZipPath').trim() !== '') { + zipFolder = settings.get('UserData_FileSystemZipPath'); } } let processingFrequency = 15; -if (RocketChat.settings.get('UserData_ProcessingFrequency') > 0) { - processingFrequency = RocketChat.settings.get('UserData_ProcessingFrequency'); +if (settings.get('UserData_ProcessingFrequency') > 0) { + processingFrequency = settings.get('UserData_ProcessingFrequency'); } const startFile = function(fileName, content) { @@ -38,16 +39,16 @@ const loadUserSubscriptions = function(exportOperation) { exportOperation.roomList = []; const exportUserId = exportOperation.userId; - const cursor = RocketChat.models.Subscriptions.findByUserId(exportUserId); + const cursor = Subscriptions.findByUserId(exportUserId); cursor.forEach((subscription) => { const roomId = subscription.rid; - const roomData = RocketChat.models.Rooms.findOneById(roomId); + const roomData = Rooms.findOneById(roomId); let roomName = (roomData && roomData.name) ? roomData.name : roomId; let userId = null; if (subscription.t === 'd') { userId = roomId.replace(exportUserId, ''); - const userData = RocketChat.models.Users.findOneById(userId); + const userData = Users.findOneById(userId); if (userData) { roomName = userData.name; @@ -108,7 +109,7 @@ const getAttachmentData = function(attachment) { const match = /^\/([^\/]+)\/([^\/]+)\/(.*)/.exec(url); if (match && match[2]) { - const file = RocketChat.models.Uploads.findOneById(match[2]); + const file = Uploads.findOneById(match[2]); if (file) { attachmentData.fileId = file._id; @@ -173,7 +174,7 @@ const copyFile = function(exportOperation, attachmentData) { return; } - const file = RocketChat.models.Uploads.findOneById(attachmentData.fileId); + const file = Uploads.findOneById(attachmentData.fileId); if (file) { if (FileUpload.copy(file, attachmentData.targetFile)) { @@ -197,13 +198,13 @@ const continueExportingRoom = function(exportOperation, exportOpRoomData) { } let limit = 100; - if (RocketChat.settings.get('UserData_MessageLimitPerRequest') > 0) { - limit = RocketChat.settings.get('UserData_MessageLimitPerRequest'); + if (settings.get('UserData_MessageLimitPerRequest') > 0) { + limit = settings.get('UserData_MessageLimitPerRequest'); } const skip = exportOpRoomData.exportedCount; - const cursor = RocketChat.models.Messages.findByRoomId(exportOpRoomData.roomId, { limit, skip }); + const cursor = Messages.findByRoomId(exportOpRoomData.roomId, { limit, skip }); const count = cursor.count(); cursor.forEach((msg) => { @@ -288,17 +289,17 @@ const isDownloadFinished = function(exportOperation) { }; const sendEmail = function(userId) { - const lastFile = RocketChat.models.UserDataFiles.findLastFileByUser(userId); + const lastFile = UserDataFiles.findLastFileByUser(userId); if (!lastFile) { return; } - const userData = RocketChat.models.Users.findOneById(userId); + const userData = Users.findOneById(userId); if (!userData || !userData.emails || !userData.emails[0] || !userData.emails[0].address) { return; } const emailAddress = `${ userData.name } <${ userData.emails[0].address }>`; - const fromAddress = RocketChat.settings.get('From_Email'); + const fromAddress = settings.get('From_Email'); const subject = TAPi18n.__('UserDataDownload_EmailSubject'); const download_link = lastFile.url; @@ -355,7 +356,7 @@ const uploadZipFile = function(exportOperation, callback) { const { size } = stat; const { userId } = exportOperation; - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); const userDisplayName = user ? user.name : userId; const utcDate = new Date().toISOString().split('T')[0]; @@ -448,7 +449,7 @@ const continueExportOperation = function(exportOperation) { if (exportOperation.status === 'uploading') { uploadZipFile(exportOperation, () => { exportOperation.status = 'completed'; - RocketChat.models.ExportOperations.updateOperation(exportOperation); + ExportOperations.updateOperation(exportOperation); }); return; } @@ -458,14 +459,14 @@ const continueExportOperation = function(exportOperation) { }; function processDataDownloads() { - const cursor = RocketChat.models.ExportOperations.findAllPending({ limit: 1 }); + const cursor = ExportOperations.findAllPending({ limit: 1 }); cursor.forEach((exportOperation) => { if (exportOperation.status === 'completed') { return; } continueExportOperation(exportOperation); - RocketChat.models.ExportOperations.updateOperation(exportOperation); + ExportOperations.updateOperation(exportOperation); if (exportOperation.status === 'completed') { sendEmail(exportOperation.userId); diff --git a/packages/rocketchat-user-data-download/server/startup/settings.js b/packages/rocketchat-user-data-download/server/startup/settings.js index 6025752d35c1..352033683672 100644 --- a/packages/rocketchat-user-data-download/server/startup/settings.js +++ b/packages/rocketchat-user-data-download/server/startup/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('UserDataDownload', function() { +settings.addGroup('UserDataDownload', function() { this.add('UserData_EnableDownload', true, { type: 'boolean', From ba43cc0a706b193397a6bdf5c0021fcda5f5bac5 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 5 Feb 2019 16:38:16 -0200 Subject: [PATCH 093/101] Remove dependency of RC namespace in rc-version-check --- .../rocketchat-version-check/client/client.js | 2 +- packages/rocketchat-version-check/package.js | 5 ++++- .../server/addSettings.js | 4 ++-- .../server/functions/checkVersionUpdate.js | 20 ++++++++++--------- .../server/functions/getNewUpdates.js | 10 ++++++---- .../server/methods/banner_dismiss.js | 4 ++-- 6 files changed, 26 insertions(+), 19 deletions(-) diff --git a/packages/rocketchat-version-check/client/client.js b/packages/rocketchat-version-check/client/client.js index 6d37b5d73a78..631881e25e55 100644 --- a/packages/rocketchat-version-check/client/client.js +++ b/packages/rocketchat-version-check/client/client.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { TAPi18n } from 'meteor/tap:i18n'; -import { alerts } from 'meteor/rocketchat:ui'; +import { alerts } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { Tracker.autorun(() => { diff --git a/packages/rocketchat-version-check/package.js b/packages/rocketchat-version-check/package.js index 2f76c06b8c3e..970d9830290c 100644 --- a/packages/rocketchat-version-check/package.js +++ b/packages/rocketchat-version-check/package.js @@ -9,8 +9,11 @@ Package.onUse(function(api) { api.use([ 'mongo', 'ecmascript', - 'rocketchat:lib', + 'rocketchat:ui-utils', 'rocketchat:logger', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:utils', 'rocketchat:cloud', 'littledata:synced-cron', ]); diff --git a/packages/rocketchat-version-check/server/addSettings.js b/packages/rocketchat-version-check/server/addSettings.js index 9b41cd65615f..8715baf2154c 100644 --- a/packages/rocketchat-version-check/server/addSettings.js +++ b/packages/rocketchat-version-check/server/addSettings.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('Update', function() { this.add('Update_LatestAvailableVersion', '0.0.0', { type: 'string', diff --git a/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js b/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js index d5457605377b..85c9d079fb1e 100644 --- a/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js +++ b/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; +import { Roles, Users } from 'meteor/rocketchat:models'; import semver from 'semver'; import logger from '../logger'; import getNewUpdates from './getNewUpdates'; @@ -17,13 +19,13 @@ export default () => { security: false, }; - const lastCheckedVersion = RocketChat.settings.get('Update_LatestAvailableVersion'); + const lastCheckedVersion = settings.get('Update_LatestAvailableVersion'); versions.forEach((version) => { if (semver.lte(version.version, lastCheckedVersion)) { return; } - if (semver.lte(version.version, RocketChat.Info.version)) { + if (semver.lte(version.version, Info.version)) { return; } @@ -36,8 +38,8 @@ export default () => { }); if (update.exists) { - RocketChat.settings.updateById('Update_LatestAvailableVersion', update.lastestVersion.version); - RocketChat.models.Roles.findUsersInRole('admin').forEach((adminUser) => { + settings.updateById('Update_LatestAvailableVersion', update.lastestVersion.version); + Roles.findUsersInRole('admin').forEach((adminUser) => { try { Meteor.runAsUser(adminUser._id, () => Meteor.call('createDirectMessage', 'rocket.cat')); @@ -51,7 +53,7 @@ export default () => { console.error(e); } - RocketChat.models.Users.addBannerById(adminUser._id, { + Users.addBannerById(adminUser._id, { id: 'versionUpdate', priority: 10, title: 'Update_your_RocketChat', @@ -63,12 +65,12 @@ export default () => { } if (alerts && alerts.length) { - RocketChat.models.Roles.findUsersInRole('admin').forEach((adminUser) => { + Roles.findUsersInRole('admin').forEach((adminUser) => { try { Meteor.runAsUser(adminUser._id, () => Meteor.call('createDirectMessage', 'rocket.cat')); alerts.forEach((alert) => { - if (RocketChat.models.Users.bannerExistsById(adminUser._id, `alert-${ alert.id }`)) { + if (Users.bannerExistsById(adminUser._id, `alert-${ alert.id }`)) { return; } @@ -84,7 +86,7 @@ export default () => { } alerts.forEach((alert) => { - RocketChat.models.Users.addBannerById(adminUser._id, { + Users.addBannerById(adminUser._id, { id: `alert-${ alert.id }`, priority: 10, title: alert.title, diff --git a/packages/rocketchat-version-check/server/functions/getNewUpdates.js b/packages/rocketchat-version-check/server/functions/getNewUpdates.js index 6480651a2f91..9880cd05b22b 100644 --- a/packages/rocketchat-version-check/server/functions/getNewUpdates.js +++ b/packages/rocketchat-version-check/server/functions/getNewUpdates.js @@ -1,19 +1,21 @@ import os from 'os'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Settings } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; import { getWorkspaceAccessToken } from 'meteor/rocketchat:cloud'; import { MongoInternals } from 'meteor/mongo'; export default () => { try { - const uniqueID = RocketChat.models.Settings.findOne('uniqueID'); + const uniqueID = Settings.findOne('uniqueID'); const { _oplogHandle } = MongoInternals.defaultRemoteCollectionDriver().mongo; - const oplogEnabled = _oplogHandle && _oplogHandle.onOplogEntry && RocketChat.settings.get('Force_Disable_OpLog_For_Cache') !== true; + const oplogEnabled = _oplogHandle && _oplogHandle.onOplogEntry && settings.get('Force_Disable_OpLog_For_Cache') !== true; const data = { uniqueId: uniqueID.value, installedAt: uniqueID.createdAt, - version: RocketChat.Info.version, + version: Info.version, oplogEnabled, osType: os.type(), osPlatform: os.platform(), diff --git a/packages/rocketchat-version-check/server/methods/banner_dismiss.js b/packages/rocketchat-version-check/server/methods/banner_dismiss.js index cdbc2166ab02..eb5cef23fcbc 100644 --- a/packages/rocketchat-version-check/server/methods/banner_dismiss.js +++ b/packages/rocketchat-version-check/server/methods/banner_dismiss.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; Meteor.methods({ 'banner/dismiss'({ id }) { @@ -7,6 +7,6 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'banner/dismiss' }); } - RocketChat.models.Users.setBannerReadById(this.userId, id); + Users.setBannerReadById(this.userId, id); }, }); From 767f35d2d9e270eca5edb5577d46b9ecca6c870b Mon Sep 17 00:00:00 2001 From: Marcos Spessatto Defendi Date: Wed, 6 Feb 2019 16:40:59 -0200 Subject: [PATCH 094/101] 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 095/101] 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 096/101] 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 097/101] 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 098/101] 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 099/101] 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 100/101] 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 101/101] 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 } });