From 6f749bcbab2d3a72782138ff260408e63bb17d4f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 18:58:42 -0200 Subject: [PATCH 01/48] Move integrations models to rc-models --- packages/rocketchat-integrations/server/index.js | 2 -- packages/rocketchat-lib/server/models/index.js | 6 +++++- packages/rocketchat-models/server/index.js | 4 ++++ .../server/models/IntegrationHistory.js | 9 ++++++--- .../server/models/Integrations.js | 8 +++++--- 5 files changed, 20 insertions(+), 9 deletions(-) rename packages/{rocketchat-integrations => rocketchat-models}/server/models/IntegrationHistory.js (85%) rename packages/{rocketchat-integrations => rocketchat-models}/server/models/Integrations.js (73%) 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/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(); From 5dec8ce3e316ff01f4eeac8702d5f6516d4bd7fd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 18:59:34 -0200 Subject: [PATCH 02/48] Move composeMessage function to rc-utils --- packages/rocketchat-lib/package.js | 2 +- .../functions/composeMessageObjectWithUser.js | 20 ---------------- .../composeMessageObjectWithUser_import.js | 3 +++ packages/rocketchat-utils/server/index.js | 1 + .../lib/composeMessageObjectWithUser.js | 23 +++++++++++++++++++ 5 files changed, 28 insertions(+), 21 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-utils/server/lib/composeMessageObjectWithUser.js diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 9784e41bedd6..1226e21e76e0 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -111,7 +111,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'); 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-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 583cb878796f19646f5ce151bd7060b42c4faf37 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 19:00:38 -0200 Subject: [PATCH 03/48] Move PushNotifications class to push-notifications package --- packages/rocketchat-lib/package.js | 5 ++--- .../server/lib/PushNotification_import.js | 3 +++ packages/rocketchat-push-notifications/package.js | 2 ++ packages/rocketchat-push-notifications/server/index.js | 5 +++++ .../server/lib/PushNotification.js | 10 ++++++---- 5 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 packages/rocketchat-lib/server/lib/PushNotification_import.js rename packages/{rocketchat-lib => rocketchat-push-notifications}/server/lib/PushNotification.js (77%) diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index 1226e21e76e0..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'); @@ -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/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-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(); From 039e7cd839fba05d243fc17d2097b879951f8684 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 21 Jan 2019 19:02:00 -0200 Subject: [PATCH 04/48] Import variables to remove dependency of RC namespace --- .../functions/addUserToDefaultChannels.js | 18 +++++--- .../server/functions/addUserToRoom.js | 21 +++++---- .../server/functions/archiveRoom.js | 8 ++-- .../functions/checkUsernameAvailability.js | 4 +- .../server/functions/cleanRoomHistory.js | 12 ++--- .../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 ++- 29 files changed, 278 insertions(+), 198 deletions(-) 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/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'); } From d49540b4589be630fab2b1974cb8ef5f093907a8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 10:13:41 -0200 Subject: [PATCH 05/48] 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 4cede2ea7c2411c2c957e45ef17bf2096516744e Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 11:26:18 -0200 Subject: [PATCH 06/48] 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 5ecc7b84778d30168c61d2142dc06d18ffb048d9 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 15:18:56 -0200 Subject: [PATCH 07/48] 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 f3280a69113e62577ed573266e3df59f48f6afbe Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 16:04:54 -0200 Subject: [PATCH 08/48] 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 f457877396ae7fdf687ac72d71bffa43cc38b742 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 18:09:03 -0200 Subject: [PATCH 09/48] Export function and lib function of rc-lib but keep it inside 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 | 6 +++-- .../server/functions/setUserAvatar.js | 4 ++- .../server/functions/setUsername.js | 6 +++-- .../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/validateEmailDomain.js | 4 ++- 29 files changed, 119 insertions(+), 30 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..d95afdb27501 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,8 @@ 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; 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..2abff008a11c 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,10 @@ 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; 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/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 3b6ffa6e71bffd3aa65700183419ff3f28d97f51 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 18:18:24 -0200 Subject: [PATCH 10/48] 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 +++-- .../rocketchat-lib/server/lib/passwordPolicy.js | 2 +- .../server/lib/processDirectEmail.js | 7 +++++-- .../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 ++- 33 files changed, 93 insertions(+), 55 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 d95afdb27501..6373aaa20609 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 2abff008a11c..9daa3e3ff305 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/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..5c64c67af410 100644 --- a/packages/rocketchat-lib/server/lib/processDirectEmail.js +++ b/packages/rocketchat-lib/server/lib/processDirectEmail.js @@ -3,9 +3,10 @@ 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'; -RocketChat.processDirectEmail = function(email) { +export const processDirectEmail = function(email) { function sendMessage(email) { const message = { ts: new Date(email.headers.date), @@ -95,7 +96,7 @@ RocketChat.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 @@ -120,3 +121,5 @@ RocketChat.processDirectEmail = function(email) { console.log('Invalid Email....If not. Please report it.'); } }; + +RocketChat.processDirectEmail = processDirectEmail; 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 6ab7f284d5737a3e4e0306e219d97cfda84247f6 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Tue, 22 Jan 2019 18:54:21 -0200 Subject: [PATCH 11/48] 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 568ed1f534c9e73cf8bfbdf943cf67b0865a6109 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 23 Jan 2019 14:36:52 -0200 Subject: [PATCH 12/48] 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 5d60447707688a0d97116ba837e63977b276eeec Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:22:28 -0200 Subject: [PATCH 13/48] Move CreadentialTokens model to rc-models --- packages/rocketchat-cas/server/index.js | 1 - packages/rocketchat-models/server/index.js | 2 ++ .../server/models/CredentialTokens.js | 8 +++++--- 3 files changed, 7 insertions(+), 4 deletions(-) rename packages/{rocketchat-cas => rocketchat-models}/server/models/CredentialTokens.js (78%) 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-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 dd9303fd9bd71b11890534d6b40302ceeb40e960 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:26:04 -0200 Subject: [PATCH 14/48] Move getUsernameSuggestion function and method from server/ to rc-lib --- 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 +++++++++++ 5 files changed, 31 insertions(+), 21 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 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); + }, +}); From 842a519c651c6b51d600b45e551f4acdc7bb2472 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:27:36 -0200 Subject: [PATCH 15/48] 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 ++-- 3 files changed, 38 insertions(+), 37 deletions(-) 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) { From ba81c021ceba1c88039d3b4a7e424b746a0ddbfd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 15:48:05 -0200 Subject: [PATCH 16/48] 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 1290be4a2ce95775cad3caef47eb96eac6afffb3 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:08:57 -0200 Subject: [PATCH 17/48] Move 2FA Users model to rc-models --- packages/rocketchat-2fa/server/index.js | 1 - .../rocketchat-2fa/server/models/users.js | 51 ------------------- .../rocketchat-models/server/models/Users.js | 50 ++++++++++++++++++ 3 files changed, 50 insertions(+), 52 deletions(-) delete mode 100644 packages/rocketchat-2fa/server/models/users.js diff --git a/packages/rocketchat-2fa/server/index.js b/packages/rocketchat-2fa/server/index.js index 2f088d337986..ae9766e3a2bb 100644 --- a/packages/rocketchat-2fa/server/index.js +++ b/packages/rocketchat-2fa/server/index.js @@ -1,6 +1,5 @@ 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/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-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 25b121ebf662acc2e8bebe7c2cdb601eaa4cc100 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:09:46 -0200 Subject: [PATCH 18/48] Remove dependency of RC namespace in rc-2fa --- packages/rocketchat-2fa/client/TOTPPassword.js | 2 +- packages/rocketchat-2fa/client/accountSecurity.js | 6 +++--- packages/rocketchat-2fa/package.js | 6 ++++-- packages/rocketchat-2fa/server/index.js | 1 - packages/rocketchat-2fa/server/lib/totp.js | 9 +++++---- packages/rocketchat-2fa/server/loginHandler.js | 10 ++++++---- packages/rocketchat-2fa/server/methods/disable.js | 7 ++++--- packages/rocketchat-2fa/server/methods/enable.js | 9 +++++---- .../rocketchat-2fa/server/methods/regenerateCodes.js | 9 +++++---- .../rocketchat-2fa/server/methods/validateTempToken.js | 9 +++++---- packages/rocketchat-2fa/server/startup/settings.js | 4 ++-- 11 files changed, 40 insertions(+), 32 deletions(-) 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 ae9766e3a2bb..e5d5ab3fc445 100644 --- a/packages/rocketchat-2fa/server/index.js +++ b/packages/rocketchat-2fa/server/index.js @@ -1,5 +1,4 @@ import './startup/settings'; -import './lib/totp'; 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/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', From a7bf7a9c285beb9009ea80805f70971290b9ba96 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:39:42 -0200 Subject: [PATCH 19/48] Remove dependency of RC namespace in rc-action-links --- .../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_theme/package.js | 1 - 8 files changed, 32 insertions(+), 22 deletions(-) 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_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 eff117630eab2c40e9950b3d3d8f3fe9cf853cf3 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:40:32 -0200 Subject: [PATCH 20/48] Add action links in the RC namespace --- packages/rocketchat-lib/lib/actionLinks.js | 3 +++ packages/rocketchat-lib/package.js | 2 ++ 2 files changed, 5 insertions(+) create mode 100644 packages/rocketchat-lib/lib/actionLinks.js 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'); From 2503f08f0faee3b6b35a26dfecce9b5a7ef5cd61 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 16:50:04 -0200 Subject: [PATCH 21/48] Remove dependency of RC namespace in rc-analytics --- .../rocketchat-analytics/client/loadScript.js | 16 +-- .../client/trackEvents.js | 101 +++++++++--------- packages/rocketchat-analytics/package.js | 4 +- .../rocketchat-analytics/server/settings.js | 4 +- 4 files changed, 64 insertions(+), 61 deletions(-) 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, { From 0c95868b945b9d488c18f887897678440dad9116 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 17:07:38 -0200 Subject: [PATCH 22/48] Remove dependency of RC namespace in rc-assets --- packages/rocketchat-assets/package.js | 5 +- packages/rocketchat-assets/server/assets.js | 57 +++++++++++---------- packages/rocketchat-assets/server/index.js | 2 +- 3 files changed, 34 insertions(+), 30 deletions(-) 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..0bead7ef5d09 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 Assets = 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 Assets.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); + Assets.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 Assets.processAsset(record._id, record.value); }, changed(record) { - return RocketChat.Assets.processAsset(record._id, record.value); + return Assets.processAsset(record._id, record.value); }, removed(record) { - return RocketChat.Assets.processAsset(record._id, undefined); + return Assets.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 Assets.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 Assets.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); + Assets.setAsset(binaryContent, contentType, asset); }, }); diff --git a/packages/rocketchat-assets/server/index.js b/packages/rocketchat-assets/server/index.js index 5b8e85c9ffd4..1cd127066f9e 100644 --- a/packages/rocketchat-assets/server/index.js +++ b/packages/rocketchat-assets/server/index.js @@ -1 +1 @@ -import './assets'; +export { Assets } from './assets'; From 2174cee28e08da4f522f8c4c8046c566cb5e6e33 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 17:08:09 -0200 Subject: [PATCH 23/48] Add Assets in RC namespace --- packages/rocketchat-lib/package.js | 2 ++ packages/rocketchat-lib/server/lib/Assets.js | 3 +++ 2 files changed, 5 insertions(+) create mode 100644 packages/rocketchat-lib/server/lib/Assets.js 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..add9894d477b --- /dev/null +++ b/packages/rocketchat-lib/server/lib/Assets.js @@ -0,0 +1,3 @@ +import { Assets } from 'meteor/rocketchat:assets'; + +RocketChat.Assets = Assets; From e0cf4d6d54be47ce23bb0231ef2817ad57375823 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 17:16:44 -0200 Subject: [PATCH 24/48] Remove dependency of RC namespace in rc-autolinker --- .../rocketchat-autolinker/client/client.js | 23 ++++++++++--------- packages/rocketchat-autolinker/package.js | 3 ++- .../rocketchat-autolinker/server/settings.js | 18 +++++++-------- 3 files changed, 23 insertions(+), 21 deletions(-) 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 }); }); From fb28deac245821e9fbd6c9a043f1536987e327f8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 17:41:27 -0200 Subject: [PATCH 25/48] Move autotranslate models to rc-models --- .../rocketchat-autotranslate/server/index.js | 2 - .../server/models/Messages.js | 19 ------- .../server/models/Subscriptions.js | 50 ------------------- .../server/models/Messages.js | 18 +++++++ .../server/models/Subscriptions.js | 49 ++++++++++++++++++ 5 files changed, 67 insertions(+), 71 deletions(-) delete mode 100644 packages/rocketchat-autotranslate/server/models/Messages.js delete mode 100644 packages/rocketchat-autotranslate/server/models/Subscriptions.js 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/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-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..54b400ac931b 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; From 83c3373cca390e01d70fe73ded1558614c642dc8 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 17:42:27 -0200 Subject: [PATCH 26/48] Partial remove dependency of Rc namespace in rc-autotranslate --- .../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 | 7 +++- .../server/autotranslate.js | 24 ++++++------ .../server/methods/getSupportedLanguages.js | 7 ++-- .../server/methods/saveSettings.js | 13 ++++--- .../server/methods/translateMessage.js | 9 +++-- .../server/permissions.js | 8 ++-- .../server/settings.js | 6 +-- 12 files changed, 87 insertions(+), 68 deletions(-) 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..e2302459aff8 100644 --- a/packages/rocketchat-autotranslate/package.js +++ b/packages/rocketchat-autotranslate/package.js @@ -9,7 +9,12 @@ 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', ]); diff --git a/packages/rocketchat-autotranslate/server/autotranslate.js b/packages/rocketchat-autotranslate/server/autotranslate.js index d42da9982d6b..fe7a6c18e2ae 100644 --- a/packages/rocketchat-autotranslate/server/autotranslate.js +++ b/packages/rocketchat-autotranslate/server/autotranslate.js @@ -1,21 +1,23 @@ 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 _ 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 +50,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) { @@ -155,7 +157,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 +189,7 @@ class AutoTranslate { } }); if (!_.isEmpty(translations)) { - RocketChat.models.Messages.addTranslations(message._id, translations); + Messages.addTranslations(message._id, translations); } }); } @@ -212,7 +214,7 @@ class AutoTranslate { } }); if (!_.isEmpty(translations)) { - RocketChat.models.Messages.addAttachmentTranslations(message._id, index, translations); + Messages.addAttachmentTranslations(message._id, index, translations); } } } @@ -257,4 +259,4 @@ class AutoTranslate { } } -RocketChat.AutoTranslate = new AutoTranslate; +export default new AutoTranslate; diff --git a/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js b/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js index b2b79b9c7522..68cef2f8c87d 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..fced378e34a9 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/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 } }); }); From e687a9b10c00c4deb2b4ee8988c9016a3db27b37 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 18:00:31 -0200 Subject: [PATCH 27/48] Remove dependency of RC namespace in rc-markdown --- 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 ++++++++++--------- 10 files changed, 61 insertions(+), 55 deletions(-) create mode 100644 packages/rocketchat-lib/lib/Markdown.js 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, }, }, }); From fe9027787a0200e783d7a14eaf70a71137671764 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 18:01:20 -0200 Subject: [PATCH 28/48] Finish of remotion of RC namespace in rc-autotranslate --- packages/rocketchat-autotranslate/package.js | 1 + packages/rocketchat-autotranslate/server/autotranslate.js | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/rocketchat-autotranslate/package.js b/packages/rocketchat-autotranslate/package.js index e2302459aff8..0dd6ba8c7f4c 100644 --- a/packages/rocketchat-autotranslate/package.js +++ b/packages/rocketchat-autotranslate/package.js @@ -17,6 +17,7 @@ Package.onUse(function(api) { '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 fe7a6c18e2ae..a16da8b2ee49 100644 --- a/packages/rocketchat-autotranslate/server/autotranslate.js +++ b/packages/rocketchat-autotranslate/server/autotranslate.js @@ -3,6 +3,7 @@ import { HTTP } from 'meteor/http'; 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'; @@ -93,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) { From 05e7858be20121b21347d99f8a35b1d269526aa5 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 18:01:48 -0200 Subject: [PATCH 29/48] Import Autotranslate where it has been used --- packages/rocketchat-ui-message/client/message.js | 3 ++- packages/rocketchat-ui-message/package.js | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/rocketchat-ui-message/client/message.js b/packages/rocketchat-ui-message/client/message.js index 38f4c7437c2f..bd4275abc173 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 4ec3a966335c7dbb75677bd74c3695ec0dededd3 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 18:04:18 -0200 Subject: [PATCH 30/48] Fix lint --- packages/rocketchat-models/server/models/Subscriptions.js | 8 ++++---- packages/rocketchat-ui-message/client/message.js | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/rocketchat-models/server/models/Subscriptions.js b/packages/rocketchat-models/server/models/Subscriptions.js index 54b400ac931b..0ccfade3d72e 100644 --- a/packages/rocketchat-models/server/models/Subscriptions.js +++ b/packages/rocketchat-models/server/models/Subscriptions.js @@ -34,7 +34,7 @@ export class Subscriptions extends Base { const query = { _id, }; - + let update; if (autoTranslate) { update = { @@ -49,7 +49,7 @@ export class Subscriptions extends Base { }, }; } - + return this.update(query, update); } @@ -57,13 +57,13 @@ export class Subscriptions extends Base { const query = { _id, }; - + const update = { $set: { autoTranslateLanguage, }, }; - + return this.update(query, update); } diff --git a/packages/rocketchat-ui-message/client/message.js b/packages/rocketchat-ui-message/client/message.js index bd4275abc173..be794edea2e5 100644 --- a/packages/rocketchat-ui-message/client/message.js +++ b/packages/rocketchat-ui-message/client/message.js @@ -10,7 +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 { AutoTranslate } from 'meteor/rocketchat:autotranslate'; import { t } from 'meteor/rocketchat:utils'; async function renderPdfToCanvas(canvasId, pdfLink) { From ac592ae08411e75d1f772605c98bc3c49f04410d Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 23 Jan 2019 18:26:06 -0200 Subject: [PATCH 31/48] Rename Assets variable to avoid conflicts --- packages/rocketchat-assets/server/assets.js | 2 +- packages/rocketchat-assets/server/index.js | 2 +- packages/rocketchat-lib/server/lib/Assets.js | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/rocketchat-assets/server/assets.js b/packages/rocketchat-assets/server/assets.js index 0bead7ef5d09..42b777adfe64 100644 --- a/packages/rocketchat-assets/server/assets.js +++ b/packages/rocketchat-assets/server/assets.js @@ -186,7 +186,7 @@ const assets = { }, }; -export const Assets = new (class { +export const RocketChatAssets = new (class { get mime() { return mime; } diff --git a/packages/rocketchat-assets/server/index.js b/packages/rocketchat-assets/server/index.js index 1cd127066f9e..8e5b30ff6b6f 100644 --- a/packages/rocketchat-assets/server/index.js +++ b/packages/rocketchat-assets/server/index.js @@ -1 +1 @@ -export { Assets } from './assets'; +export { RocketChatAssets } from './assets'; diff --git a/packages/rocketchat-lib/server/lib/Assets.js b/packages/rocketchat-lib/server/lib/Assets.js index add9894d477b..3be7174e0a35 100644 --- a/packages/rocketchat-lib/server/lib/Assets.js +++ b/packages/rocketchat-lib/server/lib/Assets.js @@ -1,3 +1,3 @@ -import { Assets } from 'meteor/rocketchat:assets'; +import { RocketChatAssets } from 'meteor/rocketchat:assets'; -RocketChat.Assets = Assets; +RocketChat.Assets = RocketChatAssets; From 23922e5da55961f1d2c332c714111bfed59d4d7a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 09:45:32 -0200 Subject: [PATCH 32/48] Fix rename Assets --- packages/rocketchat-assets/server/assets.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/rocketchat-assets/server/assets.js b/packages/rocketchat-assets/server/assets.js index 42b777adfe64..46825f7e46d2 100644 --- a/packages/rocketchat-assets/server/assets.js +++ b/packages/rocketchat-assets/server/assets.js @@ -236,7 +236,7 @@ export const RocketChatAssets = new (class { }; settings.updateById(key, value); - return Assets.processAsset(key, value); + return RocketChatAssets.processAsset(key, value); }, 200); })); @@ -257,7 +257,7 @@ export const RocketChatAssets = new (class { }; settings.updateById(key, value); - Assets.processAsset(key, value); + RocketChatAssets.processAsset(key, value); } refreshClients() { @@ -354,15 +354,15 @@ for (const key of Object.keys(assets)) { Settings.find().observe({ added(record) { - return Assets.processAsset(record._id, record.value); + return RocketChatAssets.processAsset(record._id, record.value); }, changed(record) { - return Assets.processAsset(record._id, record.value); + return RocketChatAssets.processAsset(record._id, record.value); }, removed(record) { - return Assets.processAsset(record._id, undefined); + return RocketChatAssets.processAsset(record._id, undefined); }, }); @@ -439,7 +439,7 @@ Meteor.methods({ }); } - return Assets.refreshClients(); + return RocketChatAssets.refreshClients(); }, unsetAsset(asset) { @@ -457,7 +457,7 @@ Meteor.methods({ }); } - return Assets.unsetAsset(asset); + return RocketChatAssets.unsetAsset(asset); }, setAsset(binaryContent, contentType, asset) { @@ -475,7 +475,7 @@ Meteor.methods({ }); } - Assets.setAsset(binaryContent, contentType, asset); + RocketChatAssets.setAsset(binaryContent, contentType, asset); }, }); From 95752275428272c8fd2d0178763beb7b0584cc1c Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 10:42:03 -0200 Subject: [PATCH 33/48] Remove dependency of RC namespace in rc-blockstack --- packages/rocketchat-blockstack/package.js | 10 +++++++--- .../rocketchat-blockstack/server/loginHandler.js | 11 ++++++----- packages/rocketchat-blockstack/server/routes.js | 9 +++++---- packages/rocketchat-blockstack/server/settings.js | 15 +++++++-------- .../rocketchat-blockstack/server/tokenHandler.js | 1 - .../rocketchat-blockstack/server/userHandler.js | 4 ++-- 6 files changed, 27 insertions(+), 23 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 From 85d0c1d8c991e02662cb0a352dd2ef7c78e94412 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 10:42:23 -0200 Subject: [PATCH 34/48] Remove RC dependency in bot-helpers --- packages/rocketchat-bot-helpers/package.js | 4 +++- packages/rocketchat-bot-helpers/server/index.js | 16 +++++++++------- .../rocketchat-bot-helpers/server/settings.js | 4 ++-- 3 files changed, 14 insertions(+), 10 deletions(-) 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', From 4a3ebd69806ffafa16005c2608e7345dbc2ec1d5 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 10:43:07 -0200 Subject: [PATCH 35/48] Remove RC dependency in rc-cas --- 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 +- 6 files changed, 36 insertions(+), 33 deletions(-) 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 13d553ce2b77364849dd8b7c6c945f5e5b322951 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 14:11:15 -0200 Subject: [PATCH 36/48] Move some functions from tokenpass to channel settings and models --- .../server/functions/saveRoomTokens.js | 6 +++--- packages/rocketchat-models/server/models/Rooms.js | 10 ++++++++++ packages/rocketchat-tokenpass/server/index.js | 1 - packages/rocketchat-tokenpass/server/models/Rooms.js | 10 ---------- 4 files changed, 13 insertions(+), 14 deletions(-) rename packages/{rocketchat-tokenpass => rocketchat-channel-settings}/server/functions/saveRoomTokens.js (56%) 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-models/server/models/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index de8e7d452296..c99e3adde860 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,16 @@ export class Rooms extends Base { return this.findOne(query, options); } + setTokenpassById(_id, tokenpass) { + const update = { + $set: { + tokenpass, + }, + }; + + return this.update({ _id }, 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 97060113701db064635e04675146464ad8b8798d Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 14:13:45 -0200 Subject: [PATCH 37/48] Move some function from livestream to channel settings --- .../server/functions/saveStreamingOptions.js | 6 +++--- packages/rocketchat-channel-settings/server/index.js | 2 +- packages/rocketchat-lib/package.js | 2 ++ .../server/functions/saveStreamingOptions.js | 3 +++ packages/rocketchat-livestream/server/index.js | 2 -- packages/rocketchat-livestream/server/models/Rooms.js | 10 ---------- packages/rocketchat-models/server/models/Rooms.js | 9 +++++++++ 7 files changed, 18 insertions(+), 16 deletions(-) rename packages/{rocketchat-livestream => rocketchat-channel-settings}/server/functions/saveStreamingOptions.js (72%) 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-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..adae49053b8f 100644 --- a/packages/rocketchat-channel-settings/server/index.js +++ b/packages/rocketchat-channel-settings/server/index.js @@ -1,6 +1,6 @@ import './startup'; import './models/Messages'; -import './models/Rooms'; +export { saveStreamingOptions } from './functions/saveStreamingOptions'; import './functions/saveReactWhenReadOnly'; import './functions/saveRoomAnnouncement'; import './functions/saveRoomCustomFields'; diff --git a/packages/rocketchat-lib/package.js b/packages/rocketchat-lib/package.js index ec54d31666c1..177ea5982879 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,7 @@ 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'); // SERVER LIB api.addFiles('server/lib/configLogger.js', 'server'); 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/Rooms.js b/packages/rocketchat-models/server/models/Rooms.js index c99e3adde860..dcd834431f8d 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,15 @@ export class Rooms extends Base { return this.findOne(query, options); } + setStreamingOptionsById(_id, streamingOptions) { + const update = { + $set: { + streamingOptions, + }, + }; + return this.update({ _id }, update); + } + setTokenpassById(_id, tokenpass) { const update = { $set: { From b8cc8bce3a1d582b769564b77c0aab7359613bfd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 14:16:25 -0200 Subject: [PATCH 38/48] Remove dependency of RC namespace in rc-channel-settings --- .../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/saveRoomTopic.js | 8 +- .../server/functions/saveRoomType.js | 15 +- .../server/index.js | 11 +- .../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 | 1 + .../server/functions/saveRoomTopic.js | 3 + .../server/models/Messages.js | 8 + .../rocketchat-models/server/models/Rooms.js | 71 ++++++++- 26 files changed, 260 insertions(+), 243 deletions(-) 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/saveRoomTopic.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-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-channel-settings/server/index.js b/packages/rocketchat-channel-settings/server/index.js index adae49053b8f..3cb39fb11f21 100644 --- a/packages/rocketchat-channel-settings/server/index.js +++ b/packages/rocketchat-channel-settings/server/index.js @@ -1,13 +1,4 @@ import './startup'; -import './models/Messages'; +export { saveRoomTopic } from './functions/saveRoomTopic'; export { saveStreamingOptions } from './functions/saveStreamingOptions'; -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'; 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 177ea5982879..49b959999540 100644 --- a/packages/rocketchat-lib/package.js +++ b/packages/rocketchat-lib/package.js @@ -252,6 +252,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/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-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 dcd834431f8d..cd6fb7ff5419 100644 --- a/packages/rocketchat-models/server/models/Rooms.js +++ b/packages/rocketchat-models/server/models/Rooms.js @@ -26,6 +26,18 @@ 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: { @@ -41,10 +53,67 @@ export class Rooms extends Base { 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, From 5d3d0a5f24596ddfd6d3b99a21437ac657aec98f Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 14:18:19 -0200 Subject: [PATCH 39/48] Fix wrong imports --- packages/rocketchat-autotranslate/server/autotranslate.js | 2 +- .../server/methods/getSupportedLanguages.js | 2 +- .../rocketchat-autotranslate/server/methods/translateMessage.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/rocketchat-autotranslate/server/autotranslate.js b/packages/rocketchat-autotranslate/server/autotranslate.js index a16da8b2ee49..914949644ccf 100644 --- a/packages/rocketchat-autotranslate/server/autotranslate.js +++ b/packages/rocketchat-autotranslate/server/autotranslate.js @@ -260,4 +260,4 @@ class AutoTranslate { } } -export default new AutoTranslate; +export default new AutoTranslate(); diff --git a/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js b/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js index 68cef2f8c87d..e860c8d64956 100644 --- a/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js +++ b/packages/rocketchat-autotranslate/server/methods/getSupportedLanguages.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'; import { hasPermission } from 'meteor/rocketchat:authorization'; -import { AutoTranslate } from '../autotranslate'; +import AutoTranslate from '../autotranslate'; Meteor.methods({ 'autoTranslate.getSupportedLanguages'(targetLanguage) { diff --git a/packages/rocketchat-autotranslate/server/methods/translateMessage.js b/packages/rocketchat-autotranslate/server/methods/translateMessage.js index fced378e34a9..78813eb1a135 100644 --- a/packages/rocketchat-autotranslate/server/methods/translateMessage.js +++ b/packages/rocketchat-autotranslate/server/methods/translateMessage.js @@ -1,6 +1,6 @@ import { Meteor } from 'meteor/meteor'; import { Rooms } from 'meteor/rocketchat:models'; -import { AutoTranslate } from '../autotranslate'; +import AutoTranslate from '../autotranslate'; Meteor.methods({ 'autoTranslate.translateMessage'(message, targetLanguage) { From cc5ec5cb8d7d79500987b02763f81940e9eaebe6 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 15:50:30 -0200 Subject: [PATCH 40/48] Remove dependency of RC namespace in rc-channel-mail-messages --- .../client/lib/startup.js | 7 ++++--- .../client/views/mailMessagesInstructions.js | 10 +++++----- .../package.js | 6 ++++-- .../server/lib/startup.js | 4 ++-- .../server/methods/mailMessages.js | 15 +++++++++------ 5 files changed, 24 insertions(+), 18 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, From d912d2ed869c28063bb3fb7a675bea6ce164a505 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 15:51:00 -0200 Subject: [PATCH 41/48] Remove dependency of RC namespace in rc-cloud --- 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 ++++++----- 11 files changed, 78 insertions(+), 49 deletions(-) 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 265bf82a3c5773cfe5ae5c26a26e07ceca01c938 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:09:09 -0200 Subject: [PATCH 42/48] Remove dependency of RC namespace in rc-colors --- packages/rocketchat-colors/client/client.js | 7 ++++--- packages/rocketchat-colors/package.js | 3 ++- packages/rocketchat-colors/server/settings.js | 4 ++-- 3 files changed, 8 insertions(+), 6 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', From 0f9cf3dc0436598860fc3c46fb5932ef21fb4c75 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:09:31 -0200 Subject: [PATCH 43/48] Remove dependency of RC namespace in rc-cors --- packages/rocketchat-cors/lib/common.js | 4 ++-- packages/rocketchat-cors/package.js | 1 + packages/rocketchat-cors/server/cors.js | 22 ++++++++++------------ 3 files changed, 13 insertions(+), 14 deletions(-) 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; From f418bd3adb61b5c45fba2562661b9892d4f5f2fd Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:09:56 -0200 Subject: [PATCH 44/48] Remove dependency of RC namespace in rc-crowd --- packages/rocketchat-crowd/package.js | 3 ++ packages/rocketchat-crowd/server/crowd.js | 43 +++++++++++--------- packages/rocketchat-crowd/server/settings.js | 4 +- 3 files changed, 28 insertions(+), 22 deletions(-) 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 }]; From f2ed727e43097e0af5b6ecf2d3e9472a3041d7b2 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:10:14 -0200 Subject: [PATCH 45/48] Remove dependency of RC namespace in rc-dolphin --- packages/rocketchat-dolphin/lib/common.js | 32 ++++++++++--------- packages/rocketchat-dolphin/package.js | 4 ++- packages/rocketchat-dolphin/server/startup.js | 18 +++++------ 3 files changed, 29 insertions(+), 25 deletions(-) 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 62e775894d8f49da6bf3b5836795e53e9665b2cb Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:17:41 -0200 Subject: [PATCH 46/48] Remove dependency of RC namespace in rc-drupal --- packages/rocketchat-drupal/lib/common.js | 8 ++++---- packages/rocketchat-drupal/package.js | 2 +- packages/rocketchat-drupal/server/startup.js | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) 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', From 96ebaf1a7a457d4eb5eac2a929e2a9791f94730c Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:38:36 -0200 Subject: [PATCH 47/48] Move Emoji custom server and client models to rc-models --- packages/rocketchat-lib/client/models/index.js | 3 ++- packages/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 +++--- 6 files changed, 14 insertions(+), 7 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-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 80e23268eab80f899811ca6ac0ef378b7075f43e Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 24 Jan 2019 17:39:34 -0200 Subject: [PATCH 48/48] Remove dependency of RC namespace in rc-emoji-custom --- .../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 +- 17 files changed, 109 insertions(+), 101 deletions(-) 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: [{