diff --git a/packages/rocketchat-models/client/index.js b/packages/rocketchat-models/client/index.js index 0185653df2e1..a990bd5fc082 100644 --- a/packages/rocketchat-models/client/index.js +++ b/packages/rocketchat-models/client/index.js @@ -17,6 +17,7 @@ import { RoomRoles } from './models/RoomRoles'; import { UserAndRoom } from './models/UserAndRoom'; import { UserRoles } from './models/UserRoles'; import { AuthzCachedCollection, ChatPermissions } from './models/ChatPermissions'; +import { WebdavAccounts } from './models/WebdavAccounts'; import CustomSounds from './models/CustomSounds'; import EmojiCustom from './models/EmojiCustom'; import _ from 'underscore'; @@ -51,4 +52,5 @@ export { Rooms, CustomSounds, EmojiCustom, + WebdavAccounts, }; diff --git a/packages/rocketchat-models/client/models/WebdavAccounts.js b/packages/rocketchat-models/client/models/WebdavAccounts.js new file mode 100644 index 000000000000..fafe9bf792d0 --- /dev/null +++ b/packages/rocketchat-models/client/models/WebdavAccounts.js @@ -0,0 +1,3 @@ +import { Mongo } from 'meteor/mongo'; + +export const WebdavAccounts = new Mongo.Collection('rocketchat_webdav_accounts'); diff --git a/packages/rocketchat-ui-account/client/account.js b/packages/rocketchat-ui-account/client/account.js index 5f95f6e508fd..eb58eb9d528e 100644 --- a/packages/rocketchat-ui-account/client/account.js +++ b/packages/rocketchat-ui-account/client/account.js @@ -1,6 +1,6 @@ import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { SideNav } from 'meteor/rocketchat:ui-utils'; Template.account.onRendered(function() { Tracker.afterFlush(function() { diff --git a/packages/rocketchat-ui-account/client/accountFlex.js b/packages/rocketchat-ui-account/client/accountFlex.js index 31d2794b9f5b..3b0bbf5322b1 100644 --- a/packages/rocketchat-ui-account/client/accountFlex.js +++ b/packages/rocketchat-ui-account/client/accountFlex.js @@ -1,6 +1,7 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { SideNav, Layout } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; Template.accountFlex.events({ @@ -15,16 +16,16 @@ Template.accountFlex.events({ Template.accountFlex.helpers({ allowUserProfileChange() { - return RocketChat.settings.get('Accounts_AllowUserProfileChange'); + return settings.get('Accounts_AllowUserProfileChange'); }, accessTokensEnabled() { - return RocketChat.authz.hasAllPermission(['create-personal-access-tokens']); + return hasAllPermission(['create-personal-access-tokens']); }, encryptionEnabled() { - return RocketChat.settings.get('E2E_Enable'); + return settings.get('E2E_Enable'); }, webdavIntegrationEnabled() { - return RocketChat.settings.get('Webdav_Integration_Enabled'); + return settings.get('Webdav_Integration_Enabled'); }, menuItem(name, icon, section, group) { return { @@ -36,6 +37,6 @@ Template.accountFlex.helpers({ }; }, embeddedVersion() { - return RocketChat.Layout.isEmbedded(); + return Layout.isEmbedded(); }, }); diff --git a/packages/rocketchat-ui-account/client/accountIntegrations.js b/packages/rocketchat-ui-account/client/accountIntegrations.js index 803c84b20d48..f7c4fc5503cc 100644 --- a/packages/rocketchat-ui-account/client/accountIntegrations.js +++ b/packages/rocketchat-ui-account/client/accountIntegrations.js @@ -1,13 +1,13 @@ import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; +import { WebdavAccounts } from 'meteor/rocketchat:models'; +import { modal } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import toastr from 'toastr'; Template.accountIntegrations.helpers({ webdavAccounts() { - return RocketChat.models.WebdavAccounts.find().fetch(); + return WebdavAccounts.find().fetch(); }, getOptionValue(account) { return account.name || `${ account.username }@${ account.server_url.replace(/^https?\:\/\//i, '') }`; diff --git a/packages/rocketchat-ui-account/client/accountPreferences.js b/packages/rocketchat-ui-account/client/accountPreferences.js index 334356280544..12c6d75691ee 100644 --- a/packages/rocketchat-ui-account/client/accountPreferences.js +++ b/packages/rocketchat-ui-account/client/accountPreferences.js @@ -4,9 +4,11 @@ import { Tracker } from 'meteor/tracker'; import { Reload } from 'meteor/reload'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal, SideNav, KonchatNotification } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { t, handleError, getUserPreference } from 'meteor/rocketchat:utils'; +import { modal, SideNav } from 'meteor/rocketchat:ui-utils'; +import { KonchatNotification } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { CustomSounds } from 'meteor/rocketchat:custom-sounds'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -26,21 +28,21 @@ function checkedSelected(property, value, defaultValue = undefined) { if (defaultValue && defaultValue.hash) { defaultValue = undefined; } - return RocketChat.getUserPreference(Meteor.userId(), property, defaultValue) === value; + return getUserPreference(Meteor.userId(), property, defaultValue) === value; } Template.accountPreferences.helpers({ audioAssets() { - return (RocketChat.CustomSounds && RocketChat.CustomSounds.getList && RocketChat.CustomSounds.getList()) || []; + return (CustomSounds && CustomSounds.getList && CustomSounds.getList()) || []; }, newMessageNotification() { - return RocketChat.getUserPreference(Meteor.userId(), 'newMessageNotification'); + return getUserPreference(Meteor.userId(), 'newMessageNotification'); }, newRoomNotification() { - return RocketChat.getUserPreference(Meteor.userId(), 'newRoomNotification'); + return getUserPreference(Meteor.userId(), 'newRoomNotification'); }, muteFocusedConversations() { - return RocketChat.getUserPreference(Meteor.userId(), 'muteFocusedConversations'); + return getUserPreference(Meteor.userId(), 'muteFocusedConversations'); }, languages() { const languages = TAPi18n.getLanguages(); @@ -68,7 +70,7 @@ Template.accountPreferences.helpers({ return checkedSelected(property, value, defaultValue); }, highlights() { - const userHighlights = RocketChat.getUserPreference(Meteor.userId(), 'highlights'); + const userHighlights = getUserPreference(Meteor.userId(), 'highlights'); return userHighlights ? userHighlights.join(',\n') : undefined; }, desktopNotificationEnabled() { @@ -78,38 +80,38 @@ Template.accountPreferences.helpers({ return KonchatNotification.notificationStatus.get() === 'denied' || (window.Notification && Notification.permission === 'denied'); }, desktopNotificationDuration() { - const userPref = RocketChat.getUserPreference(Meteor.userId(), 'desktopNotificationDuration', 'undefined'); + const userPref = getUserPreference(Meteor.userId(), 'desktopNotificationDuration', 'undefined'); return userPref !== 'undefined' ? userPref : undefined; }, defaultDesktopNotificationDuration() { - return RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration'); + return settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration'); }, idleTimeLimit() { - return RocketChat.getUserPreference(Meteor.userId(), 'idleTimeLimit'); + return getUserPreference(Meteor.userId(), 'idleTimeLimit'); }, defaultIdleTimeLimit() { - return RocketChat.settings.get('Accounts_Default_User_Preferences_idleTimeLimit'); + return settings.get('Accounts_Default_User_Preferences_idleTimeLimit'); }, defaultDesktopNotification() { - return notificationLabels[RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotifications')]; + return notificationLabels[settings.get('Accounts_Default_User_Preferences_desktopNotifications')]; }, defaultMobileNotification() { - return notificationLabels[RocketChat.settings.get('Accounts_Default_User_Preferences_mobileNotifications')]; + return notificationLabels[settings.get('Accounts_Default_User_Preferences_mobileNotifications')]; }, defaultEmailNotification() { - return emailLabels[RocketChat.settings.get('Accounts_Default_User_Preferences_emailNotificationMode')]; + return emailLabels[settings.get('Accounts_Default_User_Preferences_emailNotificationMode')]; }, showRoles() { - return RocketChat.settings.get('UI_DisplayRoles'); + return settings.get('UI_DisplayRoles'); }, userDataDownloadEnabled() { - return RocketChat.settings.get('UserData_EnableDownload') !== false; + return settings.get('UserData_EnableDownload') !== false; }, notificationsSoundVolume() { - return RocketChat.getUserPreference(Meteor.userId(), 'notificationsSoundVolume'); + return getUserPreference(Meteor.userId(), 'notificationsSoundVolume'); }, dontAskAgainList() { - return RocketChat.getUserPreference(Meteor.userId(), 'dontAskAgainList'); + return getUserPreference(Meteor.userId(), 'dontAskAgainList'); }, }); @@ -122,7 +124,7 @@ Template.accountPreferences.onCreated(function() { settingsTemplate.child.push(this); - this.useEmojis = new ReactiveVar(RocketChat.getUserPreference(Meteor.userId(), 'useEmojis')); + this.useEmojis = new ReactiveVar(getUserPreference(Meteor.userId(), 'useEmojis')); let instance = this; @@ -161,7 +163,7 @@ Template.accountPreferences.onCreated(function() { data.sendOnEnter = $('#sendOnEnter').find('select').val(); data.autoImageLoad = JSON.parse($('input[name=autoImageLoad]:checked').val()); data.emailNotificationMode = $('select[name=emailNotificationMode]').val(); - data.desktopNotificationDuration = $('input[name=desktopNotificationDuration]').val() === '' ? RocketChat.settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration') : parseInt($('input[name=desktopNotificationDuration]').val()); + data.desktopNotificationDuration = $('input[name=desktopNotificationDuration]').val() === '' ? settings.get('Accounts_Default_User_Preferences_desktopNotificationDuration') : parseInt($('input[name=desktopNotificationDuration]').val()); data.desktopNotifications = $('#desktopNotifications').find('select').val(); data.mobileNotifications = $('#mobileNotifications').find('select').val(); data.unreadAlert = JSON.parse($('#unreadAlert').find('input:checked').val()); @@ -174,12 +176,12 @@ Template.accountPreferences.onCreated(function() { let reload = false; - if (RocketChat.settings.get('UI_DisplayRoles')) { + if (settings.get('UI_DisplayRoles')) { data.hideRoles = JSON.parse($('#hideRoles').find('input:checked').val()); } // if highlights changed we need page reload - const highlights = RocketChat.getUserPreference(Meteor.userId(), 'highlights'); + const highlights = getUserPreference(Meteor.userId(), 'highlights'); if (highlights && highlights.join('\n') !== data.highlights.join('\n')) { reload = true; } @@ -198,7 +200,7 @@ Template.accountPreferences.onCreated(function() { reload = true; } - const idleTimeLimit = $('input[name=idleTimeLimit]').val() === '' ? RocketChat.settings.get('Accounts_Default_User_Preferences_idleTimeLimit') : parseInt($('input[name=idleTimeLimit]').val()); + const idleTimeLimit = $('input[name=idleTimeLimit]').val() === '' ? settings.get('Accounts_Default_User_Preferences_idleTimeLimit') : parseInt($('input[name=idleTimeLimit]').val()); data.idleTimeLimit = idleTimeLimit; if (this.shouldUpdateLocalStorageSetting('idleTimeLimit', idleTimeLimit)) { localStorage.setItem('idleTimeLimit', idleTimeLimit); diff --git a/packages/rocketchat-ui-account/client/accountProfile.js b/packages/rocketchat-ui-account/client/accountProfile.js index ddb1ea964b3c..d189dff7f22f 100644 --- a/packages/rocketchat-ui-account/client/accountProfile.js +++ b/packages/rocketchat-ui-account/client/accountProfile.js @@ -4,16 +4,18 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal, SideNav } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { modal, SideNav } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { Notifications } from 'meteor/rocketchat:notifications'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; const validateEmail = (email) => /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email); const validateUsername = (username) => { - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return reg.test(username); }; const validateName = (name) => name && name.length; @@ -26,7 +28,7 @@ const validatePassword = (password, confirmationPassword) => { }; const filterNames = (old) => { - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return [...old.replace(' ', '')].filter((f) => reg.test(f)).join(''); }; const filterEmail = (old) => old.replace(' ', ''); @@ -83,7 +85,7 @@ Template.accountProfile.helpers({ return Object.keys(suggestions.avatars).map((service) => ({ name: service, // TODO: improve this fix - service: !suggestions.avatars[service.toLowerCase()] ? RocketChat.settings.get(`Accounts_OAuth_${ s.capitalize(service.toLowerCase()) }`) : false, + service: !suggestions.avatars[service.toLowerCase()] ? settings.get(`Accounts_OAuth_${ s.capitalize(service.toLowerCase()) }`) : false, suggestion: suggestions.avatars[service.toLowerCase()], })) .filter(({ service, suggestion }) => service || suggestion); @@ -133,7 +135,7 @@ Template.accountProfile.helpers({ return; }, allowDeleteOwnAccount() { - return RocketChat.settings.get('Accounts_AllowDeleteOwnAccount'); + return settings.get('Accounts_AllowDeleteOwnAccount'); }, realname() { return Meteor.user().name; @@ -150,23 +152,23 @@ Template.accountProfile.helpers({ return isUserEmailVerified(user); }, allowRealNameChange() { - return RocketChat.settings.get('Accounts_AllowRealNameChange'); + return settings.get('Accounts_AllowRealNameChange'); }, allowUsernameChange() { - return RocketChat.settings.get('Accounts_AllowUsernameChange') && RocketChat.settings.get('LDAP_Enable') !== true; + return settings.get('Accounts_AllowUsernameChange') && settings.get('LDAP_Enable') !== true; }, allowEmailChange() { - return RocketChat.settings.get('Accounts_AllowEmailChange'); + return settings.get('Accounts_AllowEmailChange'); }, allowPasswordChange() { - return RocketChat.settings.get('Accounts_AllowPasswordChange'); + return settings.get('Accounts_AllowPasswordChange'); }, canConfirmNewPassword() { const password = Template.instance().password.get(); - return RocketChat.settings.get('Accounts_AllowPasswordChange') && password && password !== ''; + return settings.get('Accounts_AllowPasswordChange') && password && password !== ''; }, allowAvatarChange() { - return RocketChat.settings.get('Accounts_AllowUserAvatarChange'); + return settings.get('Accounts_AllowUserAvatarChange'); }, customFields() { return Meteor.user().customFields; @@ -187,7 +189,7 @@ Template.accountProfile.onCreated(function() { self.url = new ReactiveVar(''); self.usernameAvaliable = new ReactiveVar(true); - RocketChat.Notifications.onLogged('updateAvatar', () => self.avatar.set()); + Notifications.onLogged('updateAvatar', () => self.avatar.set()); self.getSuggestions = function() { self.suggestions.set(undefined); Meteor.call('getAvatarSuggestion', function(error, avatars) { @@ -207,7 +209,7 @@ Template.accountProfile.onCreated(function() { const instance = this; if (!newPassword) { return callback(); - } else if (!RocketChat.settings.get('Accounts_AllowPasswordChange')) { + } else if (!settings.get('Accounts_AllowPasswordChange')) { toastr.remove(); toastr.error(t('Password_Change_Disabled')); instance.clearForm(); @@ -229,7 +231,7 @@ Template.accountProfile.onCreated(function() { })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', avatar.service); + callbacks.run('userAvatarSet', avatar.service); } }); } @@ -239,11 +241,11 @@ Template.accountProfile.onCreated(function() { if (typedPassword) { data.typedPassword = typedPassword; } - if (s.trim(self.password.get()) && RocketChat.settings.get('Accounts_AllowPasswordChange')) { + if (s.trim(self.password.get()) && settings.get('Accounts_AllowPasswordChange')) { data.newPassword = self.password.get(); } if (s.trim(self.realname.get()) !== user.name) { - if (!RocketChat.settings.get('Accounts_AllowRealNameChange')) { + if (!settings.get('Accounts_AllowRealNameChange')) { toastr.remove(); toastr.error(t('RealName_Change_Disabled')); instance.clearForm(); @@ -253,7 +255,7 @@ Template.accountProfile.onCreated(function() { } } if (s.trim(self.username.get()) !== user.username) { - if (!RocketChat.settings.get('Accounts_AllowUsernameChange')) { + if (!settings.get('Accounts_AllowUsernameChange')) { toastr.remove(); toastr.error(t('Username_Change_Disabled')); instance.clearForm(); @@ -263,7 +265,7 @@ Template.accountProfile.onCreated(function() { } } if (s.trim(self.email.get()) !== getUserEmailAddress(user)) { - if (!RocketChat.settings.get('Accounts_AllowEmailChange')) { + if (!settings.get('Accounts_AllowEmailChange')) { toastr.remove(); toastr.error(t('Email_Change_Disabled')); instance.clearForm(); @@ -299,7 +301,7 @@ Template.accountProfile.onCreated(function() { Template.accountProfile.onRendered(function() { Tracker.afterFlush(() => { - if (!RocketChat.settings.get('Accounts_AllowUserProfileChange')) { + if (!settings.get('Accounts_AllowUserProfileChange')) { FlowRouter.go('home'); } this.clearForm(); @@ -326,7 +328,7 @@ Template.accountProfile.events({ })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', 'initials'); + callbacks.run('userAvatarSet', 'initials'); } }); }, @@ -527,7 +529,7 @@ Template.accountProfile.events({ contentType: blob.type, blob: reader.result, }); - RocketChat.callbacks.run('userAvatarSet', 'upload'); + callbacks.run('userAvatarSet', 'upload'); }; }); }, diff --git a/packages/rocketchat-ui-account/client/avatar/prompt.js b/packages/rocketchat-ui-account/client/avatar/prompt.js index db53a5a25a11..3089651357c9 100644 --- a/packages/rocketchat-ui-account/client/avatar/prompt.js +++ b/packages/rocketchat-ui-account/client/avatar/prompt.js @@ -3,8 +3,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { SideNav } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import { fileUploadHandler } from 'meteor/rocketchat:file-upload'; import s from 'underscore.string'; @@ -26,7 +27,7 @@ Template.avatarPrompt.onCreated(function() { Template.avatarPrompt.onRendered(function() { Tracker.afterFlush(function() { - if (!RocketChat.settings.get('Accounts_AllowUserAvatarChange')) { + if (!settings.get('Accounts_AllowUserAvatarChange')) { FlowRouter.go('home'); } SideNav.setFlex('accountFlex'); @@ -40,7 +41,7 @@ Template.avatarPrompt.helpers({ }, suggestAvatar(service) { const suggestions = Template.instance().suggestions.get(); - return RocketChat.settings.get(`Accounts_OAuth_${ s.capitalize(service) }`) && !suggestions.avatars[service]; + return settings.get(`Accounts_OAuth_${ s.capitalize(service) }`) && !suggestions.avatars[service]; }, upload() { return Template.instance().upload.get(); @@ -65,7 +66,7 @@ Template.avatarPrompt.events({ })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', 'initials'); + callbacks.run('userAvatarSet', 'initials'); } }); } else if (this.service === 'url') { @@ -81,7 +82,7 @@ Template.avatarPrompt.events({ } } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', 'url'); + callbacks.run('userAvatarSet', 'url'); } }); } else { @@ -113,7 +114,7 @@ Template.avatarPrompt.events({ upload.start((error, result) => { if (result) { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', this.service); + callbacks.run('userAvatarSet', this.service); } }); } else { @@ -125,7 +126,7 @@ Template.avatarPrompt.events({ })); } else { toastr.success(t('Avatar_changed_successfully')); - RocketChat.callbacks.run('userAvatarSet', tmpService); + callbacks.run('userAvatarSet', tmpService); } }); } @@ -163,7 +164,7 @@ Template.avatarPrompt.events({ contentType: blob.type, blob: reader.result, }); - RocketChat.callbacks.run('userAvatarSet', 'upload'); + callbacks.run('userAvatarSet', 'upload'); }; }); }, diff --git a/packages/rocketchat-ui-account/package.js b/packages/rocketchat-ui-account/package.js index 082dece03b28..822204bc47ea 100644 --- a/packages/rocketchat-ui-account/package.js +++ b/packages/rocketchat-ui-account/package.js @@ -17,6 +17,12 @@ Package.onUse(function(api) { 'rocketchat:lib', 'sha', 'rocketchat:utils', + 'rocketchat:custom-sounds', + 'rocketchat:authorization', + 'rocketchat:settings', + 'rocketchat:notifications', + 'rocketchat:callbacks', + 'rocketchat:ui-utils', 'rocketchat:lazy-load', 'rocketchat:file-upload', ]); diff --git a/packages/rocketchat-ui-admin/client/admin.js b/packages/rocketchat-ui-admin/client/admin.js index c5f17ab6d066..b9210bc0319f 100644 --- a/packages/rocketchat-ui-admin/client/admin.js +++ b/packages/rocketchat-ui-admin/client/admin.js @@ -6,19 +6,18 @@ import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { SideNav, modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { SideNav, modal } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { CachedCollection } from 'meteor/rocketchat:ui-cached-collection'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; const TempSettings = new Mongo.Collection(null); -RocketChat.TempSettings = TempSettings; - const getDefaultSetting = function(settingId) { - return RocketChat.settings.collectionPrivate.findOne({ + return settings.collectionPrivate.findOne({ _id: settingId, }); }; @@ -41,7 +40,7 @@ const setFieldValue = function(settingId, value, type, editor) { const selectedRooms = Template.instance().selectedRooms.get(); selectedRooms[settingId] = value; Template.instance().selectedRooms.set(selectedRooms); - TempSettings.update({ _id: settingId }, { $set: { value, changed: JSON.stringify(RocketChat.settings.collectionPrivate.findOne(settingId).value) !== JSON.stringify(value) } }); + TempSettings.update({ _id: settingId }, { $set: { value, changed: JSON.stringify(settings.collectionPrivate.findOne(settingId).value) !== JSON.stringify(value) } }); break; default: input.val(value).change(); @@ -49,17 +48,17 @@ const setFieldValue = function(settingId, value, type, editor) { }; Template.admin.onCreated(function() { - if (RocketChat.settings.cachedCollectionPrivate == null) { - RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ + if (settings.cachedCollectionPrivate == null) { + settings.cachedCollectionPrivate = new CachedCollection({ name: 'private-settings', eventType: 'onLogged', useCache: false, }); - RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection; - RocketChat.settings.cachedCollectionPrivate.init(); + settings.collectionPrivate = settings.cachedCollectionPrivate.collection; + settings.cachedCollectionPrivate.init(); } this.selectedRooms = new ReactiveVar({}); - RocketChat.settings.collectionPrivate.find().observe({ + settings.collectionPrivate.find().observe({ added: (data) => { const selectedRooms = this.selectedRooms.get(); if (data.type === 'roomPick') { @@ -108,23 +107,23 @@ Template.admin.helpers({ return result; }, isAppLanguage(key) { - const languageKey = RocketChat.settings.get('Language'); + const languageKey = settings.get('Language'); return typeof languageKey === 'string' && languageKey.toLowerCase() === key; }, group() { const groupId = FlowRouter.getParam('group'); - const group = RocketChat.settings.collectionPrivate.findOne({ + const group = settings.collectionPrivate.findOne({ _id: groupId, type: 'group', }); if (!group) { return; } - const settings = RocketChat.settings.collectionPrivate.find({ group: groupId }, { sort: { section: 1, sorter: 1, i18nLabel: 1 } }).fetch(); + const rcSettings = settings.collectionPrivate.find({ group: groupId }, { sort: { section: 1, sorter: 1, i18nLabel: 1 } }).fetch(); const sections = {}; - Object.keys(settings).forEach((key) => { - const setting = settings[key]; + Object.keys(rcSettings).forEach((key) => { + const setting = rcSettings[key]; let i18nDefaultQuery; if (setting.i18nDefaultQuery != null) { if (_.isString(setting.i18nDefaultQuery)) { @@ -137,7 +136,7 @@ Template.admin.helpers({ } Object.keys(i18nDefaultQuery).forEach((key) => { const item = i18nDefaultQuery[key]; - if (RocketChat.settings.collectionPrivate.findOne(item) != null) { + if (settings.collectionPrivate.findOne(item) != null) { setting.value = TAPi18n.__(`${ setting._id }_Default`); } }); @@ -273,7 +272,7 @@ Template.admin.helpers({ return Meteor.absoluteUrl(url); }, selectedOption(_id, val) { - const option = RocketChat.settings.collectionPrivate.findOne({ _id }); + const option = settings.collectionPrivate.findOne({ _id }); return option && option.value === val; }, random() { @@ -304,7 +303,7 @@ Template.admin.helpers({ } const onChange = function() { const value = codeMirror.getValue(); - TempSettings.update({ _id }, { $set: { value, changed: RocketChat.settings.collectionPrivate.findOne(_id).value !== value } }); + TempSettings.update({ _id }, { $set: { value, changed: settings.collectionPrivate.findOne(_id).value !== value } }); }; const onChangeDelayed = _.debounce(onChange, 500); codeMirror.on('change', onChangeDelayed); @@ -369,14 +368,14 @@ Template.admin.events({ }, { $set: { value, - changed: RocketChat.settings.collectionPrivate.findOne(this._id).value !== value, + changed: settings.collectionPrivate.findOne(this._id).value !== value, }, }); }, 500), 'change select[name=color-editor]'(e) { const value = s.trim($(e.target).val()); TempSettings.update({ _id: this._id }, { $set: { editor: value } }); - RocketChat.settings.collectionPrivate.update({ _id: this._id }, { $set: { editor: value } }); + settings.collectionPrivate.update({ _id: this._id }, { $set: { editor: value } }); }, 'click .rc-header__section-button .discard'() { const group = FlowRouter.getParam('group'); @@ -384,10 +383,10 @@ Template.admin.events({ group, changed: true, }; - const settings = TempSettings.find(query, { + const rcSettings = TempSettings.find(query, { fields: { _id: 1, value: 1, packageValue: 1 } }).fetch(); - settings.forEach(function(setting) { - const oldSetting = RocketChat.settings.collectionPrivate.findOne({ _id: setting._id }, { fields: { value: 1, type: 1, editor: 1 } }); + rcSettings.forEach(function(setting) { + const oldSetting = settings.collectionPrivate.findOne({ _id: setting._id }, { fields: { value: 1, type: 1, editor: 1 } }); setFieldValue(setting._id, oldSetting.value, oldSetting.type, oldSetting.editor); }); }, @@ -401,22 +400,22 @@ Template.admin.events({ setFieldValue(settingId, defaultValue.packageValue, defaultValue.type, defaultValue.editor); }, 'click .reset-group'(e) { - let settings; + let rcSettings; e.preventDefault(); const group = FlowRouter.getParam('group'); const section = $(e.target).data('section'); if (section === '') { - settings = TempSettings.find({ group, section: { $exists: false } }, { fields: { _id: 1 } }).fetch(); + rcSettings = TempSettings.find({ group, section: { $exists: false } }, { fields: { _id: 1 } }).fetch(); } else { - settings = TempSettings.find({ group, section }, { fields: { _id: 1 } }).fetch(); + rcSettings = TempSettings.find({ group, section }, { fields: { _id: 1 } }).fetch(); } - settings.forEach(function(setting) { + rcSettings.forEach(function(setting) { const defaultValue = getDefaultSetting(setting._id); setFieldValue(setting._id, defaultValue.packageValue, defaultValue.type, defaultValue.editor); TempSettings.update({ _id: setting._id }, { $set: { value: defaultValue.packageValue, - changed: RocketChat.settings.collectionPrivate.findOne(setting._id).value !== defaultValue.packageValue, + changed: settings.collectionPrivate.findOne(setting._id).value !== defaultValue.packageValue, }, }); }); @@ -424,21 +423,21 @@ Template.admin.events({ 'click .rc-header__section-button .save'() { const group = FlowRouter.getParam('group'); const query = { group, changed: true }; - const settings = TempSettings.find(query, { fields: { _id: 1, value: 1, editor: 1 } }).fetch() || []; - if (settings.length === 0) { + const rcSettings = TempSettings.find(query, { fields: { _id: 1, value: 1, editor: 1 } }).fetch() || []; + if (rcSettings.length === 0) { return; } - RocketChat.settings.batchSet(settings, (err) => { + settings.batchSet(rcSettings, (err) => { if (err) { return handleError(err); } TempSettings.update({ changed: true }, { $unset: { changed: 1 } }); - if (settings.some(({ _id }) => _id === 'Language')) { + if (rcSettings.some(({ _id }) => _id === 'Language')) { const lng = Meteor.user().language - || settings.filter(({ _id }) => _id === 'Language').shift().value + || rcSettings.filter(({ _id }) => _id === 'Language').shift().value || 'en'; return TAPi18n._loadLanguage(lng).then(() => toastr.success(TAPi18n.__('Settings_updated', { lng }))); } diff --git a/packages/rocketchat-ui-admin/client/adminFlex.js b/packages/rocketchat-ui-admin/client/adminFlex.js index 06830633eee3..e05a458245f8 100644 --- a/packages/rocketchat-ui-admin/client/adminFlex.js +++ b/packages/rocketchat-ui-admin/client/adminFlex.js @@ -1,22 +1,23 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; +import { CachedCollection } from 'meteor/rocketchat:ui-cached-collection'; +import { SideNav, AdminBox, Layout } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; Template.adminFlex.onCreated(function() { this.settingsFilter = new ReactiveVar(''); - if (RocketChat.settings.cachedCollectionPrivate == null) { - RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ + if (settings.cachedCollectionPrivate == null) { + settings.cachedCollectionPrivate = new CachedCollection({ name: 'private-settings', eventType: 'onLogged', useCache: false, }); - RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection; - RocketChat.settings.cachedCollectionPrivate.init(); + settings.collectionPrivate = settings.cachedCollectionPrivate.collection; + settings.cachedCollectionPrivate.init(); } }); @@ -36,7 +37,7 @@ Template.adminFlex.helpers({ }; if (filter) { const filterRegex = new RegExp(s.escapeRegExp(filter), 'i'); - const records = RocketChat.settings.collectionPrivate.find().fetch(); + const records = settings.collectionPrivate.find().fetch(); let groups = []; records.forEach(function(record) { if (filterRegex.test(TAPi18n.__(record.i18nLabel || record._id))) { @@ -50,7 +51,7 @@ Template.adminFlex.helpers({ }; } } - return RocketChat.settings.collectionPrivate.find(query).fetch().map(function(el) { + return settings.collectionPrivate.find(query).fetch().map(function(el) { el.label = label.apply(el); return el; }).sort(function(a, b) { @@ -63,7 +64,7 @@ Template.adminFlex.helpers({ }, label, adminBoxOptions() { - return RocketChat.AdminBox.getOptions(); + return AdminBox.getOptions(); }, menuItem(name, icon, section, group) { return { @@ -76,7 +77,7 @@ Template.adminFlex.helpers({ }; }, embeddedVersion() { - return RocketChat.Layout.isEmbedded(); + return Layout.isEmbedded(); }, }); diff --git a/packages/rocketchat-ui-admin/client/adminInfo.js b/packages/rocketchat-ui-admin/client/adminInfo.js index 235a461a6077..8791d3197fa9 100644 --- a/packages/rocketchat-ui-admin/client/adminInfo.js +++ b/packages/rocketchat-ui-admin/client/adminInfo.js @@ -3,8 +3,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { handleError, Info } from 'meteor/rocketchat:utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { SideNav } from 'meteor/rocketchat:ui-utils'; import s from 'underscore.string'; import moment from 'moment'; @@ -53,10 +54,10 @@ Template.adminInfo.helpers({ return s.numberFormat(number, 2); }, info() { - return RocketChat.Info; + return Info; }, build() { - return RocketChat.Info && (RocketChat.Info.compile || RocketChat.Info.build); + return Info && (Info.compile || Info.build); }, }); @@ -86,7 +87,7 @@ Template.adminInfo.onCreated(function() { this.statistics = new ReactiveVar({}); this.instances = new ReactiveVar({}); this.ready = new ReactiveVar(false); - if (RocketChat.authz.hasAllPermission('view-statistics')) { + if (hasAllPermission('view-statistics')) { Meteor.call('getStatistics', function(error, statistics) { instance.ready.set(true); if (error) { diff --git a/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js b/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js index ec8d61ca028e..c5a8c1bd0ec9 100644 --- a/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js +++ b/packages/rocketchat-ui-admin/client/rooms/adminRoomInfo.js @@ -3,10 +3,12 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; -import { call } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { call, modal } from 'meteor/rocketchat:ui-utils'; +import { hasAllPermission, hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { ChannelSettings } from 'meteor/rocketchat:channel-settings'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import { AdminChatRoom } from './adminRooms'; import toastr from 'toastr'; @@ -15,7 +17,7 @@ Template.adminRoomInfo.helpers({ return Session.get('adminRoomsSelected'); }, canEdit() { - return RocketChat.authz.hasAllPermission('edit-room', this.rid); + return hasAllPermission('edit-room', this.rid); }, editing(field) { return Template.instance().editing.get() === field; @@ -29,7 +31,7 @@ Template.adminRoomInfo.helpers({ return room && room.t; }, channelSettings() { - return RocketChat.ChannelSettings.getOptions(undefined, 'admin-room'); + return ChannelSettings.getOptions(undefined, 'admin-room'); }, roomTypeDescription() { const room = AdminChatRoom.findOne(this.rid, { fields: { t: 1 } }); @@ -68,7 +70,7 @@ Template.adminRoomInfo.helpers({ canDeleteRoom() { const room = AdminChatRoom.findOne(this.rid, { fields: { t: 1 } }); const roomType = room && room.t; - return (roomType != null) && RocketChat.authz.hasAtLeastOnePermission(`delete-${ roomType }`); + return (roomType != null) && hasAtLeastOnePermission(`delete-${ roomType }`); }, readOnly() { const room = AdminChatRoom.findOne(this.rid, { fields: { ro: 1 } }); @@ -150,13 +152,13 @@ Template.adminRoomInfo.onCreated(function() { this.validateRoomName = (rid) => { const room = AdminChatRoom.findOne(rid); let nameValidation; - if (!RocketChat.authz.hasAllPermission('edit-room', rid) || (room.t !== 'c' && room.t !== 'p')) { + if (!hasAllPermission('edit-room', rid) || (room.t !== 'c' && room.t !== 'p')) { toastr.error(t('error-not-allowed')); return false; } name = $('input[name=roomName]').val(); try { - nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + nameValidation = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); } catch (_error) { nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$'); } @@ -173,7 +175,7 @@ Template.adminRoomInfo.onCreated(function() { switch (this.editing.get()) { case 'roomName': if (this.validateRoomName(rid)) { - RocketChat.callbacks.run('roomNameChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomNameChanged', AdminChatRoom.findOne(rid)); Meteor.call('saveRoomSettings', rid, 'roomName', this.$('input[name=roomName]').val(), function(err) { if (err) { return handleError(err); @@ -189,7 +191,7 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_topic_changed_successfully')); - RocketChat.callbacks.run('roomTopicChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomTopicChanged', AdminChatRoom.findOne(rid)); }); } break; @@ -200,14 +202,14 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_announcement_changed_successfully')); - RocketChat.callbacks.run('roomAnnouncementChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomAnnouncementChanged', AdminChatRoom.findOne(rid)); }); } break; case 'roomType': const val = this.$('input[name=roomType]:checked').val(); if (this.validateRoomType(rid)) { - RocketChat.callbacks.run('roomTypeChanged', AdminChatRoom.findOne(rid)); + callbacks.run('roomTypeChanged', AdminChatRoom.findOne(rid)); const saveRoomSettings = function() { Meteor.call('saveRoomSettings', rid, 'roomType', val, function(err) { if (err) { @@ -243,7 +245,7 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_archived')); - RocketChat.callbacks.run('archiveRoom', AdminChatRoom.findOne(rid)); + callbacks.run('archiveRoom', AdminChatRoom.findOne(rid)); }); } } else if ((room && room.archived) === true) { @@ -252,7 +254,7 @@ Template.adminRoomInfo.onCreated(function() { return handleError(err); } toastr.success(TAPi18n.__('Room_unarchived')); - RocketChat.callbacks.run('unarchiveRoom', AdminChatRoom.findOne(rid)); + callbacks.run('unarchiveRoom', AdminChatRoom.findOne(rid)); }); } break; diff --git a/packages/rocketchat-ui-admin/client/rooms/adminRooms.js b/packages/rocketchat-ui-admin/client/rooms/adminRooms.js index 4b3d7e969520..22bf2e40b672 100644 --- a/packages/rocketchat-ui-admin/client/rooms/adminRooms.js +++ b/packages/rocketchat-ui-admin/client/rooms/adminRooms.js @@ -5,9 +5,10 @@ import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { SideNav } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; -import { RocketChat, RocketChatTabBar } from 'meteor/rocketchat:lib'; +import { SideNav, RocketChatTabBar, TabBar } from 'meteor/rocketchat:ui-utils'; +import { t, roomTypes } from 'meteor/rocketchat:utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { ChannelSettings } from 'meteor/rocketchat:channel-settings'; import _ from 'underscore'; import s from 'underscore.string'; @@ -42,10 +43,10 @@ Template.adminRooms.helpers({ return rooms && rooms.count(); }, name() { - return RocketChat.roomTypes.roomTypes[this.t].getDisplayName(this); + return roomTypes.roomTypes[this.t].getDisplayName(this); }, type() { - return TAPi18n.__(RocketChat.roomTypes.roomTypes[this.t].label); + return TAPi18n.__(roomTypes.roomTypes[this.t].label); }, 'default'() { if (this.default) { @@ -90,7 +91,7 @@ Template.adminRooms.onCreated(function() { this.ready = new ReactiveVar(true); this.tabBar = new RocketChatTabBar(); this.tabBar.showGroup(FlowRouter.current().route.name); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-rooms'], id: 'admin-room', i18nTitle: 'Room_Info', @@ -98,7 +99,7 @@ Template.adminRooms.onCreated(function() { template: 'adminRoomInfo', order: 1, }); - RocketChat.ChannelSettings.addOption({ + ChannelSettings.addOption({ group: ['admin-room'], id: 'make-default', template: 'channelSettingsDefault', @@ -106,7 +107,7 @@ Template.adminRooms.onCreated(function() { return Session.get('adminRoomsSelected'); }, validation() { - return RocketChat.authz.hasAllPermission('view-room-administration'); + return hasAllPermission('view-room-administration'); }, }); this.autorun(function() { diff --git a/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js b/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js index 6d2546912186..2c984795f9c4 100644 --- a/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js +++ b/packages/rocketchat-ui-admin/client/rooms/channelSettingsDefault.js @@ -2,8 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { t } from 'meteor/rocketchat:utils'; -import { handleError } from 'meteor/rocketchat:lib'; +import { t, handleError } from 'meteor/rocketchat:utils'; import { AdminChatRoom } from './adminRooms'; import toastr from 'toastr'; diff --git a/packages/rocketchat-ui-admin/client/users/adminInviteUser.js b/packages/rocketchat-ui-admin/client/users/adminInviteUser.js index d0462f0f1c4b..e504c72f319a 100644 --- a/packages/rocketchat-ui-admin/client/users/adminInviteUser.js +++ b/packages/rocketchat-ui-admin/client/users/adminInviteUser.js @@ -1,14 +1,14 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { t, handleError } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import toastr from 'toastr'; Template.adminInviteUser.helpers({ isAllowed() { - return RocketChat.authz.hasAtLeastOnePermission('bulk-register-user'); + return hasAtLeastOnePermission('bulk-register-user'); }, inviteEmails() { return Template.instance().inviteEmails.get(); diff --git a/packages/rocketchat-ui-admin/client/users/adminUsers.js b/packages/rocketchat-ui-admin/client/users/adminUsers.js index a47800d1f2a4..51d56b09abbb 100644 --- a/packages/rocketchat-ui-admin/client/users/adminUsers.js +++ b/packages/rocketchat-ui-admin/client/users/adminUsers.js @@ -3,8 +3,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { SideNav } from 'meteor/rocketchat:ui'; +import { SideNav, TabBar } from 'meteor/rocketchat:ui-utils'; import _ from 'underscore'; import s from 'underscore.string'; @@ -74,7 +73,7 @@ Template.adminUsers.onCreated(function() { this.tabBar = new RocketChatTabBar(); this.tabBar.showGroup(FlowRouter.current().route.name); this.tabBarData = new ReactiveVar; - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-users'], id: 'invite-user', i18nTitle: 'Invite_Users', @@ -82,7 +81,7 @@ Template.adminUsers.onCreated(function() { template: 'adminInviteUser', order: 1, }); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-users'], id: 'add-user', i18nTitle: 'Add_User', @@ -90,7 +89,7 @@ Template.adminUsers.onCreated(function() { template: 'adminUserEdit', order: 2, }); - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['admin-users'], id: 'admin-user-info', i18nTitle: 'User_Info', diff --git a/packages/rocketchat-ui-admin/package.js b/packages/rocketchat-ui-admin/package.js index 425121cefb67..cd3191308363 100644 --- a/packages/rocketchat-ui-admin/package.js +++ b/packages/rocketchat-ui-admin/package.js @@ -16,7 +16,13 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:callbacks', + 'rocketchat:ui-cached-collection', + 'rocketchat:authorization', + 'rocketchat:channel-settings', + 'rocketchat:ui-utils', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-ui-admin/server/publications/adminRooms.js b/packages/rocketchat-ui-admin/server/publications/adminRooms.js index 63ebdc918223..7b15874b44cd 100644 --- a/packages/rocketchat-ui-admin/server/publications/adminRooms.js +++ b/packages/rocketchat-ui-admin/server/publications/adminRooms.js @@ -1,5 +1,6 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { hasPermission } from 'meteor/rocketchat:authorization'; +import { Rooms } from 'meteor/rocketchat:models'; import _ from 'underscore'; import s from 'underscore.string'; @@ -7,7 +8,7 @@ Meteor.publish('adminRooms', function(filter, types, limit) { if (!this.userId) { return this.ready(); } - if (RocketChat.authz.hasPermission(this.userId, 'view-room-administration') !== true) { + if (hasPermission(this.userId, 'view-room-administration') !== true) { return this.ready(); } if (!_.isArray(types)) { @@ -40,12 +41,12 @@ Meteor.publish('adminRooms', function(filter, types, limit) { filter = s.trim(filter); if (filter && types.length) { // CACHE: can we stop using publications here? - return RocketChat.models.Rooms.findByNameContainingAndTypes(filter, types, options); + return Rooms.findByNameContainingAndTypes(filter, types, options); } else if (types.length) { // CACHE: can we stop using publications here? - return RocketChat.models.Rooms.findByTypes(types, options); + return Rooms.findByTypes(types, options); } else { // CACHE: can we stop using publications here? - return RocketChat.models.Rooms.findByNameContaining(filter, options); + return Rooms.findByNameContaining(filter, options); } }); diff --git a/packages/rocketchat-ui-clean-history/client/lib/startup.js b/packages/rocketchat-ui-clean-history/client/lib/startup.js index f8e992ff5d87..0b3b3b3ba9d4 100644 --- a/packages/rocketchat-ui-clean-history/client/lib/startup.js +++ b/packages/rocketchat-ui-clean-history/client/lib/startup.js @@ -1,9 +1,10 @@ import { Meteor } from 'meteor/meteor'; import { Session } from 'meteor/session'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { TabBar } from 'meteor/rocketchat:ui-utils'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; Meteor.startup(() => { - RocketChat.TabBar.addButton({ + TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'clean-history', anonymous: true, @@ -11,6 +12,6 @@ Meteor.startup(() => { icon: 'eraser', template: 'cleanHistory', order: 250, - condition: () => RocketChat.authz.hasAllPermission('clean-channel-history', Session.get('openedRoom')), + condition: () => hasAllPermission('clean-channel-history', Session.get('openedRoom')), }); }); diff --git a/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js b/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js index cb30481ae9cf..c48fbf47ccbd 100644 --- a/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js +++ b/packages/rocketchat-ui-clean-history/client/views/cleanHistory.js @@ -4,9 +4,10 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { AutoComplete } from 'meteor/mizzao:autocomplete'; -import { ChatRoom, modal } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; -import { RocketChat, call } from 'meteor/rocketchat:lib'; +import { ChatRoom } from 'meteor/rocketchat:models'; +import { t, roomTypes } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { modal, call } from 'meteor/rocketchat:ui-utils'; import moment from 'moment'; const getRoomName = function() { @@ -18,7 +19,7 @@ const getRoomName = function() { return `#${ room.name }`; } - return t('conversation_with_s', RocketChat.roomTypes.getRoomName(room.t, room)); + return t('conversation_with_s', roomTypes.getRoomName(room.t, room)); }; const purgeWorker = function(roomId, oldest, latest, inclusive, limit, excludePinned, filesOnly, fromUsers) { @@ -43,7 +44,7 @@ const getTimeZoneOffset = function() { const filterNames = (old) => { - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return [...old.replace(' ', '').toLocaleLowerCase()].filter((f) => reg.test(f)).join(''); }; diff --git a/packages/rocketchat-ui-clean-history/package.js b/packages/rocketchat-ui-clean-history/package.js index 4b8fce5043e1..73ed2a5848f4 100644 --- a/packages/rocketchat-ui-clean-history/package.js +++ b/packages/rocketchat-ui-clean-history/package.js @@ -15,8 +15,12 @@ Package.onUse(function(api) { 'mongo', 'ecmascript', 'templating', + 'mizzao:autocomplete', 'rocketchat:utils', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', + 'rocketchat:ui-utils', + 'rocketchat:authorization', ]); api.addFiles('client/views/stylesheets/cleanHistory.css', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-ui-flextab/client/flexTabBar.js b/packages/rocketchat-ui-flextab/client/flexTabBar.js index 0f773e70aeed..329c23b02142 100644 --- a/packages/rocketchat-ui-flextab/client/flexTabBar.js +++ b/packages/rocketchat-ui-flextab/client/flexTabBar.js @@ -4,7 +4,8 @@ import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; import { RocketChat } from 'meteor/rocketchat:lib'; -import { popover } from 'meteor/rocketchat:ui'; +import { hasAllPermission } from 'meteor/rocketchat:authorization'; +import { popover } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; import _ from 'underscore'; @@ -19,13 +20,13 @@ const commonHelpers = { }, }; function canShowAddUsersButton(rid) { - const canAddToChannel = RocketChat.authz.hasAllPermission( + const canAddToChannel = hasAllPermission( 'add-user-to-any-c-room', rid ); - const canAddToGroup = RocketChat.authz.hasAllPermission( + const canAddToGroup = hasAllPermission( 'add-user-to-any-p-room', rid ); - const canAddToJoinedRoom = RocketChat.authz.hasAllPermission( + const canAddToJoinedRoom = hasAllPermission( 'add-user-to-joined-room', rid ); if ( diff --git a/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js b/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js index 06f2ff61209c..cf1a45350362 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js +++ b/packages/rocketchat-ui-flextab/client/tabs/inviteUsers.js @@ -4,7 +4,7 @@ import { Blaze } from 'meteor/blaze'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { AutoComplete } from 'meteor/mizzao:autocomplete'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; import { t } from 'meteor/rocketchat:utils'; import { Deps } from 'meteor/deps'; import toastr from 'toastr'; @@ -35,11 +35,11 @@ const acEvents = { }; const filterNames = (old) => { - if (RocketChat.settings.get('UI_Allow_room_names_with_special_chars')) { + if (settings.get('UI_Allow_room_names_with_special_chars')) { return old; } - const reg = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`); + const reg = new RegExp(`^${ settings.get('UTF8_Names_Validation') }$`); return [...old.replace(' ', '').toLocaleLowerCase()].filter((f) => reg.test(f)).join(''); }; diff --git a/packages/rocketchat-ui-flextab/client/tabs/membersList.js b/packages/rocketchat-ui-flextab/client/tabs/membersList.js index 9988532feca7..fe501127736b 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/membersList.js +++ b/packages/rocketchat-ui-flextab/client/tabs/membersList.js @@ -3,9 +3,10 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { ChatRoom, RoomManager, popover } from 'meteor/rocketchat:ui'; -import { t, isRtl } from 'meteor/rocketchat:utils'; +import { RoomManager, popover } from 'meteor/rocketchat:ui-utils'; +import { ChatRoom, Subscriptions } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { t, isRtl, handleError, roomTypes } from 'meteor/rocketchat:utils'; import { WebRTC } from 'meteor/rocketchat:webrtc'; import _ from 'underscore'; import { getActions } from './userActions'; @@ -13,7 +14,7 @@ import { getActions } from './userActions'; Template.membersList.helpers({ ignored() { const { user } = this; - const sub = RocketChat.models.Subscriptions.findOne({ rid: Session.get('openedRoom') }); + const sub = Subscriptions.findOne({ rid: Session.get('openedRoom') }); return sub && sub.ignored && sub.ignored.indexOf(user._id) > -1 ? `(${ t('Ignored') })` : ''; }, tAddUsers() { @@ -22,7 +23,7 @@ Template.membersList.helpers({ isGroupChat() { const room = ChatRoom.findOne(this.rid, { reactive: false }); - return RocketChat.roomTypes.roomTypes[room.t].isGroupChat(); + return roomTypes.roomTypes[room.t].isGroupChat(); }, isDirectChat() { @@ -82,7 +83,7 @@ Template.membersList.helpers({ }; }); - if (RocketChat.settings.get('UI_Use_Real_Name')) { + if (settings.get('UI_Use_Real_Name')) { users = _.sortBy(users, (u) => u.user.name); } else { users = _.sortBy(users, (u) => u.user.username); @@ -114,7 +115,7 @@ Template.membersList.helpers({ canAddUser() { const roomData = Session.get(`roomData${ this._id }`); if (!roomData) { return ''; } - return (() => RocketChat.roomTypes.roomTypes[roomData.t].canAddUser(roomData))(); + return (() => roomTypes.roomTypes[roomData.t].canAddUser(roomData))(); }, autocompleteSettingsAddUser() { @@ -159,13 +160,13 @@ Template.membersList.helpers({ tabBar: Template.currentData().tabBar, username: Template.instance().userDetail.get(), clear: Template.instance().clearUserDetail, - showAll: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, - hideAdminControls: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, + showAll: roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, + hideAdminControls: roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, video: ['d'].includes(room != null ? room.t : undefined), }; }, displayName() { - if (RocketChat.settings.get('UI_Use_Real_Name') && this.user.name) { + if (settings.get('UI_Use_Real_Name') && this.user.name) { return this.user.name; } @@ -203,8 +204,8 @@ Template.membersList.events({ const room = Session.get(`roomData${ instance.data.rid }`); const _actions = getActions({ user: this.user.user, - hideAdminControls: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, - directActions: RocketChat.roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, + hideAdminControls: roomTypes.roomTypes[room.t].userDetailShowAdmin(room) || false, + directActions: roomTypes.roomTypes[room.t].userDetailShowAll(room) || false, }) .map((action) => (typeof action === 'function' ? action.call(this) : action)) .filter((action) => action && (!action.condition || action.condition.call(this))); @@ -256,7 +257,7 @@ Template.membersList.events({ const roomData = Session.get(`roomData${ template.data.rid }`); - if (RocketChat.roomTypes.roomTypes[roomData.t].canAddUser(roomData)) { + if (roomTypes.roomTypes[roomData.t].canAddUser(roomData)) { return Meteor.call('addUserToRoom', { rid: roomData._id, username: doc.username }, function(error) { if (error) { return handleError(error); diff --git a/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js b/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js index eb8bf714816c..48e21da20b43 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js +++ b/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js @@ -3,7 +3,7 @@ import { fixCordova } from 'meteor/rocketchat:lazy-load'; import { ReactiveVar } from 'meteor/reactive-var'; import { DateFormat } from 'meteor/rocketchat:lib'; import { t } from 'meteor/rocketchat:utils'; -import { popover } from 'meteor/rocketchat:ui'; +import { popover } from 'meteor/rocketchat:ui-utils'; import { Template } from 'meteor/templating'; import _ from 'underscore'; diff --git a/packages/rocketchat-ui-flextab/client/tabs/userActions.js b/packages/rocketchat-ui-flextab/client/tabs/userActions.js index 81ea34da70d4..1a9b63828f03 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userActions.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userActions.js @@ -2,29 +2,31 @@ import { Meteor } from 'meteor/meteor'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; import { WebRTC } from 'meteor/rocketchat:webrtc'; -import { modal, ChatRoom, ChatSubscription, RoomRoles } from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { ChatRoom, ChatSubscription, RoomRoles, Subscriptions } from 'meteor/rocketchat:models'; +import { modal } from 'meteor/rocketchat:ui-utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { hasAllPermission, hasRole } from 'meteor/rocketchat:authorization'; import _ from 'underscore'; import toastr from 'toastr'; export const getActions = function({ user, directActions, hideAdminControls }) { - const hasPermission = RocketChat.authz.hasAllPermission; + const hasPermission = hasAllPermission; const isIgnored = () => { - const sub = RocketChat.models.Subscriptions.findOne({ rid : Session.get('openedRoom') }); + const sub = Subscriptions.findOne({ rid : Session.get('openedRoom') }); return sub && sub.ignored && sub.ignored.indexOf(user._id) > -1; }; - const canSetLeader = () => RocketChat.authz.hasAllPermission('set-leader', Session.get('openedRoom')); + const canSetLeader = () => hasAllPermission('set-leader', Session.get('openedRoom')); const active = () => user && user.active; const hasAdminRole = () => { if (user && user._id) { - return RocketChat.authz.hasRole(user._id, 'admin'); + return hasRole(user._id, 'admin'); } }; - const canRemoveUser = () => RocketChat.authz.hasAllPermission('remove-user', Session.get('openedRoom')); - const canSetModerator = () => RocketChat.authz.hasAllPermission('set-moderator', Session.get('openedRoom')); + const canRemoveUser = () => hasAllPermission('remove-user', Session.get('openedRoom')); + const canSetModerator = () => hasAllPermission('set-moderator', Session.get('openedRoom')); const isDirect = () => { const room = ChatRoom.findOne(Session.get('openedRoom')); return (room != null ? room.t : undefined) === 'd'; @@ -48,15 +50,15 @@ export const getActions = function({ user, directActions, hideAdminControls }) { return !!RoomRoles.findOne({ rid: Session.get('openedRoom'), 'u._id': user._id, roles: 'moderator' }); } }; - const canSetOwner = () => RocketChat.authz.hasAllPermission('set-owner', Session.get('openedRoom')); + const canSetOwner = () => hasAllPermission('set-owner', Session.get('openedRoom')); const canDirectMessage = (username) => { const rid = Session.get('openedRoom'); - const subscription = RocketChat.models.Subscriptions.findOne({ rid }); - const canOpenDm = RocketChat.authz.hasAllPermission('create-d') || RocketChat.models.Subscriptions.findOne({ name: username }); + const subscription = Subscriptions.findOne({ rid }); + const canOpenDm = hasAllPermission('create-d') || Subscriptions.findOne({ name: username }); const dmIsNotAlreadyOpen = subscription && subscription.name !== username; return canOpenDm && dmIsNotAlreadyOpen; }; - const canMuteUser = () => RocketChat.authz.hasAllPermission('mute-user', Session.get('openedRoom')); + const canMuteUser = () => hasAllPermission('mute-user', Session.get('openedRoom')); const userMuted = () => { const room = ChatRoom.findOne(Session.get('openedRoom')); return _.isArray(room && room.muted) && (room.muted.indexOf(user && user.username) !== -1); @@ -331,7 +333,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { name: t('Unmute_user'), action:prevent(getUser, ({ username }) => { const rid = Session.get('openedRoom'); - if (!RocketChat.authz.hasAllPermission('mute-user', rid)) { + if (!hasAllPermission('mute-user', rid)) { return toastr.error(TAPi18n.__('error-not-allowed')); } Meteor.call('unmuteUserInRoom', { rid, username }, success(() => toastr.success(TAPi18n.__('User_unmuted_in_room')))); @@ -345,7 +347,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { action: prevent(getUser, ({ username }) => { const rid = Session.get('openedRoom'); const room = ChatRoom.findOne(rid); - if (!RocketChat.authz.hasAllPermission('mute-user', rid)) { + if (!hasAllPermission('mute-user', rid)) { return toastr.error(TAPi18n.__('error-not-allowed')); } modal.open({ @@ -379,7 +381,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { action: prevent(getUser, (user) => { const rid = Session.get('openedRoom'); const room = ChatRoom.findOne(rid); - if (!RocketChat.authz.hasAllPermission('remove-user', rid)) { + if (!hasAllPermission('remove-user', rid)) { return toastr.error(TAPi18n.__('error-not-allowed')); } modal.open({ @@ -416,7 +418,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { icon : 'trash', name: 'Delete', action: prevent(getUser, ({ _id }) => { - const erasureType = RocketChat.settings.get('Message_ErasureType'); + const erasureType = settings.get('Message_ErasureType'); const warningKey = `Delete_User_Warning_${ erasureType }`; modal.open({ @@ -487,7 +489,7 @@ export const getActions = function({ user, directActions, hideAdminControls }) { if (hideAdminControls || !hasPermission('reset-other-user-e2e-key')) { return; } - if (!RocketChat.settings.get('E2E_Enable')) { + if (!settings.get('E2E_Enable')) { return; } diff --git a/packages/rocketchat-ui-flextab/client/tabs/userEdit.js b/packages/rocketchat-ui-flextab/client/tabs/userEdit.js index f2b6280e59b8..f2089d9c754b 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userEdit.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userEdit.js @@ -3,8 +3,9 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Random } from 'meteor/random'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { t, handleError } from 'meteor/rocketchat:utils'; +import { Roles } from 'meteor/rocketchat:models'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; import toastr from 'toastr'; import s from 'underscore.string'; @@ -14,7 +15,7 @@ Template.userEdit.helpers({ return cursor.count() === 0 ? 'disabled' : ''; }, canEditOrAdd() { - return (Template.instance().user && RocketChat.authz.hasAtLeastOnePermission('edit-other-user-info')) || (!Template.instance().user && RocketChat.authz.hasAtLeastOnePermission('create-user')); + return (Template.instance().user && hasAtLeastOnePermission('edit-other-user-info')) || (!Template.instance().user && hasAtLeastOnePermission('create-user')); }, user() { @@ -27,7 +28,7 @@ Template.userEdit.helpers({ role() { const roles = Template.instance().roles.get(); - return RocketChat.models.Roles.find({ _id: { $nin:roles }, scope: 'Users' }, { sort: { description: 1, _id: 1 } }); + return Roles.find({ _id: { $nin:roles }, scope: 'Users' }, { sort: { description: 1, _id: 1 } }); }, userRoles() { diff --git a/packages/rocketchat-ui-flextab/client/tabs/userInfo.js b/packages/rocketchat-ui-flextab/client/tabs/userInfo.js index 9a1782f60097..79ca4ac55c04 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userInfo.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userInfo.js @@ -6,8 +6,11 @@ import { TAPi18n } from 'meteor/tap:i18n'; import _ from 'underscore'; import s from 'underscore.string'; import moment from 'moment'; -import { DateFormat, RocketChat } from 'meteor/rocketchat:lib'; -import { RoomRoles, popover, UserRoles } from 'meteor/rocketchat:ui'; +import { DateFormat } from 'meteor/rocketchat:lib'; +import { popover } from 'meteor/rocketchat:ui-utils'; +import { templateVarHandler } from 'meteor/rocketchat:utils'; +import { RoomRoles, UserRoles, Roles } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; import { getActions } from './userActions'; const more = function() { @@ -31,7 +34,7 @@ Template.userInfo.helpers({ .slice(0, 2); }, customField() { - const sCustomFieldsToShow = RocketChat.settings.get('Accounts_CustomFieldsToShowInUserInfo').trim(); + const sCustomFieldsToShow = settings.get('Accounts_CustomFieldsToShowInUserInfo').trim(); const customFields = []; if (sCustomFieldsToShow) { @@ -43,13 +46,13 @@ Template.userInfo.helpers({ let content = ''; if (_.isObject(el)) { _.map(el, (key, label) => { - const value = RocketChat.templateVarHandler(key, userCustomFields); + const value = templateVarHandler(key, userCustomFields); if (value) { content = { label, value }; } }); } else { - content = RocketChat.templateVarHandler(el, userCustomFields); + content = templateVarHandler(el, userCustomFields); } if (content) { customFields.push(content); @@ -169,12 +172,12 @@ Template.userInfo.helpers({ const userRoles = UserRoles.findOne(user._id) || {}; const roomRoles = RoomRoles.findOne({ 'u._id': user._id, rid: Session.get('openedRoom') }) || {}; const roles = _.union(userRoles.roles || [], roomRoles.roles || []); - return roles.length && RocketChat.models.Roles.find({ _id: { $in: roles }, description: { $exists: 1 } }, { fields: { description: 1 } }); + return roles.length && Roles.find({ _id: { $in: roles }, description: { $exists: 1 } }, { fields: { description: 1 } }); }, shouldDisplayReason() { const user = Template.instance().user.get(); - return RocketChat.settings.get('Accounts_ManuallyApproveNewUsers') && user.active === false && user.reason; + return settings.get('Accounts_ManuallyApproveNewUsers') && user.active === false && user.reason; }, }); diff --git a/packages/rocketchat-ui-flextab/package.js b/packages/rocketchat-ui-flextab/package.js index 1543254317da..33dbda91b25d 100644 --- a/packages/rocketchat-ui-flextab/package.js +++ b/packages/rocketchat-ui-flextab/package.js @@ -16,7 +16,11 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', + 'rocketchat:models', 'rocketchat:lib', + 'rocketchat:ui-utils', + 'rocketchat:settings', + 'rocketchat:authorization', 'mizzao:autocomplete', 'rocketchat:webrtc', ]); diff --git a/packages/rocketchat-ui-login/client/login/footer.js b/packages/rocketchat-ui-login/client/login/footer.js index e729fdb06b8a..8e06f8db521f 100644 --- a/packages/rocketchat-ui-login/client/login/footer.js +++ b/packages/rocketchat-ui-login/client/login/footer.js @@ -1,7 +1,7 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.loginFooter.onCreated(function() { this.suggestedLanguage = new ReactiveVar(); @@ -10,7 +10,7 @@ Template.loginFooter.onCreated(function() { const loadAndSetSuggestedLanguage = (language) => TAPi18n._loadLanguage(language) .then(() => this.suggestedLanguage.set(language)); - const serverLanguage = RocketChat.settings.get('Language'); + const serverLanguage = settings.get('Language'); if (serverLanguage !== language) { loadAndSetSuggestedLanguage(serverLanguage || 'en'); diff --git a/packages/rocketchat-ui-login/client/login/form.js b/packages/rocketchat-ui-login/client/login/form.js index 1e455dd69540..33241f77c3d7 100644 --- a/packages/rocketchat-ui-login/client/login/form.js +++ b/packages/rocketchat-ui-login/client/login/form.js @@ -4,8 +4,9 @@ import { Tracker } from 'meteor/tracker'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat, handleError } from 'meteor/rocketchat:lib'; -import { t } from 'meteor/rocketchat:utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { t, handleError } from 'meteor/rocketchat:utils'; import _ from 'underscore'; import s from 'underscore.string'; import toastr from 'toastr'; @@ -16,14 +17,14 @@ Template.loginForm.helpers({ return user && user.username; }, namePlaceholder() { - if (RocketChat.settings.get('Accounts_RequireNameForSignUp')) { + if (settings.get('Accounts_RequireNameForSignUp')) { return t('Name'); } else { return t('Name_optional'); } }, showFormLogin() { - return RocketChat.settings.get('Accounts_ShowFormLogin'); + return settings.get('Accounts_ShowFormLogin'); }, state(...state) { return state.indexOf(Template.instance().state.get()) > -1; @@ -44,32 +45,32 @@ Template.loginForm.helpers({ } }, loginTerms() { - return RocketChat.settings.get('Layout_Login_Terms'); + return settings.get('Layout_Login_Terms'); }, registrationAllowed() { const validSecretUrl = Template.instance().validSecretURL; - return RocketChat.settings.get('Accounts_RegistrationForm') === 'Public' || (validSecretUrl && validSecretUrl.get()); + return settings.get('Accounts_RegistrationForm') === 'Public' || (validSecretUrl && validSecretUrl.get()); }, linkReplacementText() { - return RocketChat.settings.get('Accounts_RegistrationForm_LinkReplacementText'); + return settings.get('Accounts_RegistrationForm_LinkReplacementText'); }, passwordResetAllowed() { - return RocketChat.settings.get('Accounts_PasswordReset'); + return settings.get('Accounts_PasswordReset'); }, requirePasswordConfirmation() { - return RocketChat.settings.get('Accounts_RequirePasswordConfirmation'); + return settings.get('Accounts_RequirePasswordConfirmation'); }, emailOrUsernamePlaceholder() { - return RocketChat.settings.get('Accounts_EmailOrUsernamePlaceholder') || t('Email_or_username'); + return settings.get('Accounts_EmailOrUsernamePlaceholder') || t('Email_or_username'); }, passwordPlaceholder() { - return RocketChat.settings.get('Accounts_PasswordPlaceholder') || t('Password'); + return settings.get('Accounts_PasswordPlaceholder') || t('Password'); }, confirmPasswordPlaceholder() { - return RocketChat.settings.get('Accounts_ConfirmPasswordPlaceholder') || t('Confirm_password'); + return settings.get('Accounts_ConfirmPasswordPlaceholder') || t('Confirm_password'); }, manuallyApproveNewUsers() { - return RocketChat.settings.get('Accounts_ManuallyApproveNewUsers'); + return settings.get('Accounts_ManuallyApproveNewUsers'); }, }); @@ -84,7 +85,7 @@ Template.loginForm.events({ if (state === 'email-verification') { Meteor.call('sendConfirmationEmail', s.trim(formData.email), () => { instance.loading.set(false); - RocketChat.callbacks.run('userConfirmationEmailRequested'); + callbacks.run('userConfirmationEmailRequested'); toastr.success(t('We_have_sent_registration_email')); return instance.state.set('login'); }); @@ -97,7 +98,7 @@ Template.loginForm.events({ return instance.state.set('login'); } else { instance.loading.set(false); - RocketChat.callbacks.run('userForgotPasswordEmailRequested'); + callbacks.run('userForgotPasswordEmailRequested'); toastr.success(t('If_this_email_is_registered')); return instance.state.set('login'); } @@ -116,7 +117,7 @@ Template.loginForm.events({ } return; } - RocketChat.callbacks.run('userRegistered'); + callbacks.run('userRegistered'); return Meteor.loginWithPassword(s.trim(formData.email), formData.pass, function(error) { if (error && error.error === 'error-invalid-email') { return instance.state.set('wait-email-activation'); @@ -129,10 +130,10 @@ Template.loginForm.events({ }); } else { let loginMethod = 'loginWithPassword'; - if (RocketChat.settings.get('LDAP_Enable')) { + if (settings.get('LDAP_Enable')) { loginMethod = 'loginWithLDAP'; } - if (RocketChat.settings.get('CROWD_Enable')) { + if (settings.get('CROWD_Enable')) { loginMethod = 'loginWithCrowd'; } return Meteor[loginMethod](s.trim(formData.emailOrUsername), formData.pass, function(error) { @@ -154,15 +155,15 @@ Template.loginForm.events({ }, 'click .register'() { Template.instance().state.set('register'); - return RocketChat.callbacks.run('loginPageStateChange', Template.instance().state.get()); + return callbacks.run('loginPageStateChange', Template.instance().state.get()); }, 'click .back-to-login'() { Template.instance().state.set('login'); - return RocketChat.callbacks.run('loginPageStateChange', Template.instance().state.get()); + return callbacks.run('loginPageStateChange', Template.instance().state.get()); }, 'click .forgot-password'() { Template.instance().state.set('forgot-password'); - return RocketChat.callbacks.run('loginPageStateChange', Template.instance().state.get()); + return callbacks.run('loginPageStateChange', Template.instance().state.get()); }, }); @@ -171,10 +172,10 @@ Template.loginForm.onCreated(function() { this.customFields = new ReactiveVar; this.loading = new ReactiveVar(false); Tracker.autorun(() => { - const Accounts_CustomFields = RocketChat.settings.get('Accounts_CustomFields'); + const Accounts_CustomFields = settings.get('Accounts_CustomFields'); if (typeof Accounts_CustomFields === 'string' && Accounts_CustomFields.trim() !== '') { try { - return this.customFields.set(JSON.parse(RocketChat.settings.get('Accounts_CustomFields'))); + return this.customFields.set(JSON.parse(settings.get('Accounts_CustomFields'))); } catch (error1) { return console.error('Invalid JSON for Accounts_CustomFields'); } @@ -239,13 +240,13 @@ Template.loginForm.onCreated(function() { } } if (state === 'register') { - if (RocketChat.settings.get('Accounts_RequireNameForSignUp') && !formObj.name) { + if (settings.get('Accounts_RequireNameForSignUp') && !formObj.name) { validationObj.name = t('Invalid_name'); } - if (RocketChat.settings.get('Accounts_RequirePasswordConfirmation') && formObj['confirm-pass'] !== formObj.pass) { + if (settings.get('Accounts_RequirePasswordConfirmation') && formObj['confirm-pass'] !== formObj.pass) { validationObj['confirm-pass'] = t('Invalid_confirm_pass'); } - if (RocketChat.settings.get('Accounts_ManuallyApproveNewUsers') && !formObj.reason) { + if (settings.get('Accounts_ManuallyApproveNewUsers') && !formObj.reason) { validationObj.reason = t('Invalid_reason'); } validateCustomFields(formObj, validationObj); @@ -274,7 +275,7 @@ Template.loginForm.onCreated(function() { Template.loginForm.onRendered(function() { Session.set('loginDefaultState'); return Tracker.autorun(() => { - RocketChat.callbacks.run('loginPageStateChange', this.state.get()); + callbacks.run('loginPageStateChange', this.state.get()); switch (this.state.get()) { case 'login': case 'forgot-password': diff --git a/packages/rocketchat-ui-login/client/login/header.js b/packages/rocketchat-ui-login/client/login/header.js index 40ad6b094c01..f1cd0c2595c5 100644 --- a/packages/rocketchat-ui-login/client/login/header.js +++ b/packages/rocketchat-ui-login/client/login/header.js @@ -1,9 +1,9 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.loginHeader.helpers({ logoUrl() { - const asset = RocketChat.settings.get('Assets_logo'); + const asset = settings.get('Assets_logo'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset != null) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; diff --git a/packages/rocketchat-ui-login/client/login/layout.js b/packages/rocketchat-ui-login/client/login/layout.js index 40d321215af1..9c702ab0e086 100644 --- a/packages/rocketchat-ui-login/client/login/layout.js +++ b/packages/rocketchat-ui-login/client/login/layout.js @@ -1,5 +1,5 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.loginLayout.onRendered(function() { $('#initial-page-loading').remove(); @@ -7,7 +7,7 @@ Template.loginLayout.onRendered(function() { Template.loginLayout.helpers({ backgroundUrl() { - const asset = RocketChat.settings.get('Assets_background'); + const asset = settings.get('Assets_background'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset && (asset.url || asset.defaultUrl)) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; diff --git a/packages/rocketchat-ui-login/client/reset-password/resetPassword.js b/packages/rocketchat-ui-login/client/reset-password/resetPassword.js index 90484e88b408..908fa27b95ea 100644 --- a/packages/rocketchat-ui-login/client/reset-password/resetPassword.js +++ b/packages/rocketchat-ui-login/client/reset-password/resetPassword.js @@ -2,9 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { FlowRouter } from 'meteor/kadira:flow-router'; import { Template } from 'meteor/templating'; -import { modal } from 'meteor/rocketchat:ui'; +import { modal } from 'meteor/rocketchat:ui-utils'; import { t } from 'meteor/rocketchat:utils'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Button } from 'meteor/rocketchat:ui'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import toastr from 'toastr'; Template.resetPassword.helpers({ @@ -35,7 +36,7 @@ Template.resetPassword.events({ event.preventDefault(); const button = instance.$('button.resetpass'); - RocketChat.Button.loading(button); + Button.loading(button); if (Meteor.userId() && !FlowRouter.getParam('token')) { Meteor.call('setUserPassword', instance.find('[name=newPassword]').value, function(error) { @@ -49,12 +50,12 @@ Template.resetPassword.events({ }); } else { Accounts.resetPassword(FlowRouter.getParam('token'), instance.find('[name=newPassword]').value, function(error) { - RocketChat.Button.reset(button); + Button.reset(button); if (error) { console.log(error); if (error.error === 'totp-required') { toastr.success(t('Password_changed_successfully')); - RocketChat.callbacks.run('userPasswordReset'); + callbacks.run('userPasswordReset'); FlowRouter.go('login'); } else { modal.open({ @@ -65,7 +66,7 @@ Template.resetPassword.events({ } else { FlowRouter.go('home'); toastr.success(t('Password_changed_successfully')); - RocketChat.callbacks.run('userPasswordReset'); + callbacks.run('userPasswordReset'); } }); } diff --git a/packages/rocketchat-ui-login/client/username/layout.js b/packages/rocketchat-ui-login/client/username/layout.js index 2f58d4fdb0d3..771d1d40f079 100644 --- a/packages/rocketchat-ui-login/client/username/layout.js +++ b/packages/rocketchat-ui-login/client/username/layout.js @@ -1,9 +1,9 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; Template.usernameLayout.helpers({ backgroundUrl() { - const asset = RocketChat.settings.get('Assets_background'); + const asset = settings.get('Assets_background'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset && (asset.url || asset.defaultUrl)) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; diff --git a/packages/rocketchat-ui-login/client/username/username.js b/packages/rocketchat-ui-login/client/username/username.js index 08f185b01647..20af7ab06f22 100644 --- a/packages/rocketchat-ui-login/client/username/username.js +++ b/packages/rocketchat-ui-login/client/username/username.js @@ -1,7 +1,9 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Button } from 'meteor/rocketchat:ui'; +import { callbacks } from 'meteor/rocketchat:callbacks'; import _ from 'underscore'; Template.username.onCreated(function() { @@ -23,7 +25,7 @@ Template.username.helpers({ }, backgroundUrl() { - const asset = RocketChat.settings.get('Assets_background'); + const asset = settings.get('Assets_background'); const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; if (asset && (asset.url || asset.defaultUrl)) { return `${ prefix }/${ asset.url || asset.defaultUrl }`; @@ -52,13 +54,13 @@ Template.username.events({ instance.username.set(username); const button = $(event.target).find('button.login'); - RocketChat.Button.loading(button); + Button.loading(button); const value = $('#username').val().trim(); if (value === '') { username.empty = true; instance.username.set(username); - RocketChat.Button.reset(button); + Button.reset(button); return; } @@ -74,9 +76,9 @@ Template.username.events({ username.escaped = _.escape(value); } - RocketChat.Button.reset(button); + Button.reset(button); instance.username.set(username); - return RocketChat.callbacks.run('usernameSet'); + return callbacks.run('usernameSet'); }); }, }); diff --git a/packages/rocketchat-ui-login/package.js b/packages/rocketchat-ui-login/package.js index 4a3e59d2849e..2fd43145df10 100644 --- a/packages/rocketchat-ui-login/package.js +++ b/packages/rocketchat-ui-login/package.js @@ -15,9 +15,12 @@ Package.onUse(function(api) { 'ecmascript', 'templating', 'rocketchat:utils', + 'rocketchat:ui-utils', 'rocketchat:lib', 'rocketchat:ui', 'rocketchat:assets', + 'rocketchat:settings', + 'rocketchat:callbacks', 'rocketchat:2fa', 'kadira:flow-router', 'kadira:blaze-layout', diff --git a/packages/rocketchat-ui-master/client/main.js b/packages/rocketchat-ui-master/client/main.js index 80fa33440954..58299aa53e79 100644 --- a/packages/rocketchat-ui-master/client/main.js +++ b/packages/rocketchat-ui-master/client/main.js @@ -15,7 +15,7 @@ import { tooltip } from 'meteor/rocketchat:tooltip'; import Clipboard from 'clipboard'; import s from 'underscore.string'; -settings.collection.find({ _id:/theme-color-rc/i }, { fields:{ value: 1 } }).observe({ changed: () => { DynamicCss.run(true); } }); +settings.collection.find({ _id:/theme-color-rc/i }, { fields:{ value: 1 } }).observe({ changed: () => { DynamicCss.run(true, settings); } }); Template.body.onRendered(function() { new Clipboard('.clipboard'); diff --git a/packages/rocketchat-ui-master/package.js b/packages/rocketchat-ui-master/package.js index b5ca30505859..47cfbfbbbd07 100644 --- a/packages/rocketchat-ui-master/package.js +++ b/packages/rocketchat-ui-master/package.js @@ -18,6 +18,7 @@ Package.onUse(function(api) { 'reactive-var', 'rocketchat:utils', 'rocketchat:tooltip', + 'rocketchat:settings', 'rocketchat:ui-utils', 'rocketchat:ui-sidenav', 'meteorhacks:inject-initial', diff --git a/packages/rocketchat-ui-master/server/dynamic-css.js b/packages/rocketchat-ui-master/server/dynamic-css.js index 95f48091978d..ff871155d635 100644 --- a/packages/rocketchat-ui-master/server/dynamic-css.js +++ b/packages/rocketchat-ui-master/server/dynamic-css.js @@ -144,9 +144,14 @@ DynamicCss.run = debounce(function () { var replace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var settings = arguments.length && arguments[1]; + + if (replace && !settings) { + console.error('You must provide settings to the "run" function in DynamicCss'); + } if (replace) { - var colors = RocketChat.settings.collection.find({ + var colors = settings.collection.find({ _id: /theme-color-rc/i }, { fields: { diff --git a/packages/rocketchat-ui-message/client/message.js b/packages/rocketchat-ui-message/client/message.js index be794edea2e5..06856251b427 100644 --- a/packages/rocketchat-ui-message/client/message.js +++ b/packages/rocketchat-ui-message/client/message.js @@ -7,11 +7,14 @@ import _ from 'underscore'; import moment from 'moment'; import { DateFormat } from 'meteor/rocketchat:lib'; import { renderEmoji } from 'meteor/rocketchat:emoji'; -import { renderMessageBody } from 'meteor/rocketchat:ui-utils'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { RoomRoles, UserRoles } from 'meteor/rocketchat:ui'; +import { renderMessageBody, MessageTypes, MessageAction } from 'meteor/rocketchat:ui-utils'; +import { settings } from 'meteor/rocketchat:settings'; +import { RoomRoles, UserRoles, Roles, Subscriptions, Rooms } from 'meteor/rocketchat:models'; import { AutoTranslate } from 'meteor/rocketchat:autotranslate'; -import { t } from 'meteor/rocketchat:utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { callbacks } from 'meteor/rocketchat:callbacks'; +import { Markdown } from 'meteor/rocketchat:markdown'; +import { t, getUserPreference, roomTypes } from 'meteor/rocketchat:utils'; async function renderPdfToCanvas(canvasId, pdfLink) { const isSafari = /constructor/i.test(window.HTMLElement) || @@ -87,7 +90,7 @@ Template.message.helpers({ } }, roleTags() { - if (!RocketChat.settings.get('UI_DisplayRoles') || RocketChat.getUserPreference(Meteor.userId(), 'hideRoles')) { + if (!settings.get('UI_DisplayRoles') || getUserPreference(Meteor.userId(), 'hideRoles')) { return []; } @@ -100,7 +103,7 @@ Template.message.helpers({ rid: this.rid, }); const roles = [...(userRoles && userRoles.roles) || [], ...(roomRoles && roomRoles.roles) || []]; - return RocketChat.models.Roles.find({ + return Roles.find({ _id: { $in: roles, }, @@ -142,10 +145,10 @@ Template.message.helpers({ if (!this.u) { return ''; } - return (RocketChat.settings.get('UI_Use_Real_Name') && this.u.name) || this.u.username; + return (settings.get('UI_Use_Real_Name') && this.u.name) || this.u.username; }, showUsername() { - return this.alias || (RocketChat.settings.get('UI_Use_Real_Name') && this.u && this.u.name); + return this.alias || (settings.get('UI_Use_Real_Name') && this.u && this.u.name); }, own() { if (this.u && this.u._id === Meteor.userId()) { @@ -156,7 +159,7 @@ Template.message.helpers({ return +this.ts; }, chatops() { - if (this.u && this.u.username === RocketChat.settings.get('Chatops_Username')) { + if (this.u && this.u.username === settings.get('Chatops_Username')) { return 'chatops-message'; } }, @@ -175,7 +178,7 @@ Template.message.helpers({ return Template.instance().body; }, system(returnClass) { - if (RocketChat.MessageTypes.isSystemMessage(this)) { + if (MessageTypes.isSystemMessage(this)) { if (returnClass) { return 'color-info-font-color'; } @@ -183,8 +186,8 @@ Template.message.helpers({ } }, showTranslated() { - if (RocketChat.settings.get('AutoTranslate_Enabled') && this.u && this.u._id !== Meteor.userId() && !RocketChat.MessageTypes.isSystemMessage(this)) { - const subscription = RocketChat.models.Subscriptions.findOne({ + if (settings.get('AutoTranslate_Enabled') && this.u && this.u._id !== Meteor.userId() && !MessageTypes.isSystemMessage(this)) { + const subscription = Subscriptions.findOne({ rid: this.rid, 'u._id': Meteor.userId(), }, { @@ -215,13 +218,13 @@ Template.message.helpers({ return (this.editedBy && this.editedBy.username) || '?'; }, canEdit() { - const hasPermission = RocketChat.authz.hasAtLeastOnePermission('edit-message', this.rid); - const isEditAllowed = RocketChat.settings.get('Message_AllowEditing'); + const hasPermission = hasAtLeastOnePermission('edit-message', this.rid); + const isEditAllowed = settings.get('Message_AllowEditing'); const editOwn = this.u && this.u._id === Meteor.userId(); if (!(hasPermission || (isEditAllowed && editOwn))) { return; } - const blockEditInMinutes = RocketChat.settings.get('Message_AllowEditing_BlockEditInMinutes'); + const blockEditInMinutes = settings.get('Message_AllowEditing_BlockEditInMinutes'); if (blockEditInMinutes) { let msgTs; if (this.ts != null) { @@ -237,13 +240,13 @@ Template.message.helpers({ } }, canDelete() { - const hasPermission = RocketChat.authz.hasAtLeastOnePermission('delete-message', this.rid); - const isDeleteAllowed = RocketChat.settings.get('Message_AllowDeleting'); + const hasPermission = hasAtLeastOnePermission('delete-message', this.rid); + const isDeleteAllowed = settings.get('Message_AllowDeleting'); const deleteOwn = this.u && this.u._id === Meteor.userId(); if (!(hasPermission || (isDeleteAllowed && deleteOwn))) { return; } - const blockDeleteInMinutes = RocketChat.settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); + const blockDeleteInMinutes = settings.get('Message_AllowDeleting_BlockDeleteInMinutes'); if (blockDeleteInMinutes) { let msgTs; if (this.ts != null) { @@ -259,7 +262,7 @@ Template.message.helpers({ } }, showEditedStatus() { - return RocketChat.settings.get('Message_ShowEditedStatus'); + return settings.get('Message_ShowEditedStatus'); }, label() { if (this.i18nLabel) { @@ -270,12 +273,12 @@ Template.message.helpers({ }, hasOembed() { // there is no URLs, there is no template to show the oembed (oembed package removed) or oembed is not enable - if (!(this.urls && this.urls.length > 0) || !Template.oembedBaseWidget || !RocketChat.settings.get('API_Embed')) { + if (!(this.urls && this.urls.length > 0) || !Template.oembedBaseWidget || !settings.get('API_Embed')) { return false; } // check if oembed is disabled for message's sender - if ((RocketChat.settings.get('API_EmbedDisabledFor') || '').split(',').map((username) => username.trim()).includes(this.u && this.u.username)) { + if ((settings.get('API_EmbedDisabledFor') || '').split(',').map((username) => username.trim()).includes(this.u && this.u.username)) { return false; } return true; @@ -337,7 +340,7 @@ Template.message.helpers({ data.index = index; }, hideCog() { - const subscription = RocketChat.models.Subscriptions.findOne({ + const subscription = Subscriptions.findOne({ rid: this.rid, }); if (subscription == null) { @@ -345,7 +348,7 @@ Template.message.helpers({ } }, channelName() { - const subscription = RocketChat.models.Subscriptions.findOne({ rid: this.rid }); + const subscription = Subscriptions.findOne({ rid: this.rid }); return subscription && subscription.name; }, roomIcon() { @@ -353,7 +356,7 @@ Template.message.helpers({ if (room && room.t === 'd') { return 'at'; } - return RocketChat.roomTypes.getIcon(room && room.t); + return roomTypes.getIcon(room && room.t); }, fromSearch() { return this.customClass === 'search'; @@ -373,7 +376,7 @@ Template.message.helpers({ context = 'message'; } - return RocketChat.MessageAction.getButtons(Template.currentData(), context, messageGroup); + return MessageAction.getButtons(Template.currentData(), context, messageGroup); }, isSnippet() { return this.actionContext === 'snippeted'; @@ -384,9 +387,9 @@ Template.message.helpers({ Template.message.onCreated(function() { let msg = Template.currentData(); - this.wasEdited = (msg.editedAt != null) && !RocketChat.MessageTypes.isSystemMessage(msg); + this.wasEdited = (msg.editedAt != null) && !MessageTypes.isSystemMessage(msg); - this.room = RocketChat.models.Rooms.findOne({ + this.room = Rooms.findOne({ _id: msg.rid, }, { fields: { @@ -395,8 +398,8 @@ Template.message.onCreated(function() { }); return this.body = (() => { - const isSystemMessage = RocketChat.MessageTypes.isSystemMessage(msg); - const messageType = RocketChat.MessageTypes.getType(msg) || {}; + const isSystemMessage = MessageTypes.isSystemMessage(msg); + const messageType = MessageTypes.getType(msg) || {}; if (messageType.render) { msg = messageType.render(msg); } else if (messageType.template) { @@ -407,16 +410,16 @@ Template.message.onCreated(function() { } else { msg = TAPi18n.__(messageType.message); } - } else if (msg.u && msg.u.username === RocketChat.settings.get('Chatops_Username')) { + } else if (msg.u && msg.u.username === settings.get('Chatops_Username')) { msg.html = msg.msg; - msg = RocketChat.callbacks.run('renderMentions', msg); + msg = callbacks.run('renderMentions', msg); msg = msg.html; } else { msg = renderMessageBody(msg); } if (isSystemMessage) { - msg.html = RocketChat.Markdown.parse(msg.html); + msg.html = Markdown.parse(msg.html); } return msg; })(); @@ -458,7 +461,7 @@ Template.message.onViewRendered = function(context) { } if (previousDataset.groupable === 'false' || currentDataset.groupable === 'false') { $currentNode.removeClass('sequential'); - } else if (previousDataset.username !== currentDataset.username || parseInt(currentDataset.timestamp) - parseInt(previousDataset.timestamp) > RocketChat.settings.get('Message_GroupingPeriod') * 1000) { + } else if (previousDataset.username !== currentDataset.username || parseInt(currentDataset.timestamp) - parseInt(previousDataset.timestamp) > settings.get('Message_GroupingPeriod') * 1000) { $currentNode.removeClass('sequential'); } else if (!$currentNode.hasClass('new-day')) { $currentNode.addClass('sequential'); @@ -472,7 +475,7 @@ Template.message.onViewRendered = function(context) { $nextNode.removeClass('new-day'); } if (nextDataset.groupable !== 'false') { - if (nextDataset.username !== currentDataset.username || parseInt(nextDataset.timestamp) - parseInt(currentDataset.timestamp) > RocketChat.settings.get('Message_GroupingPeriod') * 1000) { + if (nextDataset.username !== currentDataset.username || parseInt(nextDataset.timestamp) - parseInt(currentDataset.timestamp) > settings.get('Message_GroupingPeriod') * 1000) { $nextNode.removeClass('sequential'); } else if (!$nextNode.hasClass('new-day') && !$currentNode.hasClass('temp')) { $nextNode.addClass('sequential'); diff --git a/packages/rocketchat-ui-message/client/messageBox.js b/packages/rocketchat-ui-message/client/messageBox.js index 9a505346bc6c..4c782a1c6451 100644 --- a/packages/rocketchat-ui-message/client/messageBox.js +++ b/packages/rocketchat-ui-message/client/messageBox.js @@ -2,19 +2,14 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { katex } from 'meteor/rocketchat:katex'; -import { RocketChat } from 'meteor/rocketchat:lib'; import { settings } from 'meteor/rocketchat:settings'; -import { - ChatSubscription, - RoomManager, - KonchatNotification, - popover, - ChatMessages, - fileUpload, - chatMessages, -} from 'meteor/rocketchat:ui'; -import { t } from 'meteor/rocketchat:utils'; +import { Markdown } from 'meteor/rocketchat:markdown'; +import { EmojiPicker } from 'meteor/rocketchat:emoji'; +import { KonchatNotification, fileUpload, chatMessages, ChatMessages } from 'meteor/rocketchat:ui'; +import { RoomManager, popover, messageBox, Layout } from 'meteor/rocketchat:ui-utils'; +import { ChatSubscription } from 'meteor/rocketchat:models'; +import { t, roomTypes, getUserPreference } from 'meteor/rocketchat:utils'; +import { katex } from 'meteor/rocketchat:katex'; import moment from 'moment'; import './messageBoxReplyPreview'; import './messageBoxTyping'; @@ -28,45 +23,45 @@ const formattingButtons = [ icon: 'bold', pattern: '*{{text}}*', command: 'b', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') === 'original', + condition: () => Markdown && settings.get('Markdown_Parser') === 'original', }, { label: 'bold', icon: 'bold', pattern: '**{{text}}**', command: 'b', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') === 'marked', + condition: () => Markdown && settings.get('Markdown_Parser') === 'marked', }, { label: 'italic', icon: 'italic', pattern: '_{{text}}_', command: 'i', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') !== 'disabled', + condition: () => Markdown && settings.get('Markdown_Parser') !== 'disabled', }, { label: 'strike', icon: 'strike', pattern: '~{{text}}~', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') === 'original', + condition: () => Markdown && settings.get('Markdown_Parser') === 'original', }, { label: 'strike', icon: 'strike', pattern: '~~{{text}}~~', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') === 'marked', + condition: () => Markdown && settings.get('Markdown_Parser') === 'marked', }, { label: 'inline_code', icon: 'code', pattern: '`{{text}}`', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') !== 'disabled', + condition: () => Markdown && settings.get('Markdown_Parser') !== 'disabled', }, { label: 'multi_line', icon: 'multiline', pattern: '```\n{{text}}\n``` ', - condition: () => RocketChat.Markdown && settings.get('Markdown_Parser') !== 'disabled', + condition: () => Markdown && settings.get('Markdown_Parser') !== 'disabled', }, { label: 'KaTeX', @@ -137,11 +132,11 @@ function applyFormatting(event, instance) { Template.messageBox.onCreated(function() { - RocketChat.EmojiPicker.init(); + EmojiPicker.init(); this.replyMessageData = new ReactiveVar(); this.isMessageFieldEmpty = new ReactiveVar(true); this.sendIconDisabled = new ReactiveVar(false); - RocketChat.messageBox.emit('created', this); + messageBox.emit('created', this); }); Template.messageBox.onRendered(function() { @@ -172,16 +167,16 @@ Template.messageBox.onRendered(function() { Template.messageBox.helpers({ isEmbedded() { - return RocketChat.Layout.isEmbedded(); + return Layout.isEmbedded(); }, subscribed() { - return RocketChat.roomTypes.verifyCanSendMessage(this._id); + return roomTypes.verifyCanSendMessage(this._id); }, canSend() { - if (RocketChat.roomTypes.readOnly(this._id, Meteor.user())) { + if (roomTypes.readOnly(this._id, Meteor.user())) { return false; } - if (RocketChat.roomTypes.archived(this._id)) { + if (roomTypes.archived(this._id)) { return false; } const roomData = Session.get(`roomData${ this._id }`); @@ -216,7 +211,7 @@ Template.messageBox.helpers({ return Template.instance().replyMessageData.get(); }, isEmojiEnabled() { - return RocketChat.getUserPreference(Meteor.userId(), 'useEmojis'); + return getUserPreference(Meteor.userId(), 'useEmojis'); }, maxMessageLength() { return settings.get('Message_MaxAllowedSize'); @@ -233,7 +228,7 @@ Template.messageBox.helpers({ settings.get('FileUpload_MediaTypeWhiteList').match(/audio\/mp3|audio\/\*/i)); }, actions() { - const actionGroups = RocketChat.messageBox.actions.get(); + const actionGroups = messageBox.actions.get(); return Object.values(actionGroups) .reduce((actions, actionGroup) => [...actions, ...actionGroup], []); }, @@ -266,16 +261,16 @@ Template.messageBox.events({ event.stopPropagation(); event.preventDefault(); - if (!RocketChat.getUserPreference(Meteor.userId(), 'useEmojis')) { + if (!getUserPreference(Meteor.userId(), 'useEmojis')) { return; } - if (RocketChat.EmojiPicker.isOpened()) { - RocketChat.EmojiPicker.close(); + if (EmojiPicker.isOpened()) { + EmojiPicker.close(); return; } - RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => { + EmojiPicker.open(event.currentTarget, (emoji) => { const emojiValue = `:${ emoji }:`; const { input } = chatMessages[RoomManager.openedRoom]; @@ -355,7 +350,7 @@ Template.messageBox.events({ }); }, 'click .rc-message-box__action-menu'(event) { - const groups = RocketChat.messageBox.actions.get(); + const groups = messageBox.actions.get(); const config = { popoverClass: 'message-box', columns: [ diff --git a/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js b/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js index 51d3937fa0af..b910867792d6 100644 --- a/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js +++ b/packages/rocketchat-ui-message/client/popup/messagePopupChannel.js @@ -1,8 +1,8 @@ import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { roomTypes } from 'meteor/rocketchat:utils'; Template.messagePopupChannel.helpers({ channelIcon() { - return RocketChat.roomTypes.getIcon(this.t); + return roomTypes.getIcon(this.t); }, }); diff --git a/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js b/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js index 7b3184eb0a01..218b4ad3a971 100644 --- a/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js +++ b/packages/rocketchat-ui-message/client/popup/messagePopupConfig.js @@ -5,9 +5,11 @@ import { Blaze } from 'meteor/blaze'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Messages, Subscriptions, Users } from 'meteor/rocketchat:models'; +import { hasAllPermission, hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; +import { EmojiPicker, emoji } from 'meteor/rocketchat:emoji'; import { RoomManager } from 'meteor/rocketchat:ui-utils'; -import { t } from 'meteor/rocketchat:utils'; +import { t, getUserPreference, slashCommands } from 'meteor/rocketchat:utils'; import _ from 'underscore'; const usersFromRoomMessages = new Mongo.Collection(null); @@ -18,7 +20,7 @@ const reloadUsersFromRoomMessages = (userId, rid) => { usersFromRoomMessages.remove({}); const uniqueMessageUsersControl = {}; - RocketChat.models.Messages.find({ + Messages.find({ rid, 'u.username': { $ne: user.username }, t: { $exists: false }, @@ -93,7 +95,7 @@ const fetchUsersFromServer = (filterText, records, cb, rid) => { }; const fetchRoomsFromServer = (filterText, records, cb, rid) => { - if (!RocketChat.authz.hasAllPermission('view-outside-room')) { + if (!hasAllPermission('view-outside-room')) { return cb && cb([]); } @@ -128,7 +130,7 @@ const addEmojiToRecents = (emoji) => { const view = Blaze.getView(pickerEl); if (view) { Template._withTemplateInstanceFunc(view.templateInstance, () => { - RocketChat.EmojiPicker.addRecent(emoji.replace(/:/g, '')); + EmojiPicker.addRecent(emoji.replace(/:/g, '')); }); } } @@ -161,16 +163,16 @@ const seeColor = new RegExp('_t(?:o|$)(?:n|$)(?:e|$)(?:[1-5]|$)(?:\:|$)$'); const getEmojis = function(collection, filter) { const key = `:${ filter }`; - if (!RocketChat.getUserPreference(Meteor.userId(), 'useEmojis')) { + if (!getUserPreference(Meteor.userId(), 'useEmojis')) { return []; } - if (!RocketChat.emoji.packages.emojione || RocketChat.emoji.packages.emojione.asciiList[key]) { + if (!emoji.packages.emojione || emoji.packages.emojione.asciiList[key]) { return []; } const regExp = new RegExp(RegExp.escape(filter), 'i'); - const recents = RocketChat.EmojiPicker.getRecent().map((item) => `:${ item }:`); + const recents = EmojiPicker.getRecent().map((item) => `:${ item }:`); return Object.keys(collection).map((_id) => { const data = collection[key]; return { _id, data }; @@ -214,8 +216,8 @@ Template.messagePopupConfig.helpers({ // If needed, add to list the online users if (items.length < 5 && filterText !== '') { const usernamesAlreadyFetched = items.map(({ username }) => username); - if (!RocketChat.authz.hasAllPermission('view-outside-room')) { - const usernamesFromDMs = RocketChat.models.Subscriptions + if (!hasAllPermission('view-outside-room')) { + const usernamesFromDMs = Subscriptions .find( { t: 'd', @@ -236,7 +238,7 @@ Template.messagePopupConfig.helpers({ } ) .map(({ name }) => name); - const newItems = RocketChat.models.Users + const newItems = Users .find( { username: { @@ -344,7 +346,7 @@ Template.messagePopupConfig.helpers({ const self = this; const config = { title: t('Channels'), - collection: RocketChat.models.Subscriptions, + collection: Subscriptions, trigger: '#', suffix: ' ', textFilterDelay: 500, @@ -383,7 +385,7 @@ Template.messagePopupConfig.helpers({ const self = this; const config = { title: t('Commands'), - collection: RocketChat.slashCommands.commands, + collection: slashCommands.commands, trigger: '/', suffix: ' ', triggerAnywhere: false, @@ -409,21 +411,21 @@ Template.messagePopupConfig.helpers({ return true; } - return RocketChat.authz.hasAtLeastOnePermission(command.permission, Session.get('openedRoom')); + return hasAtLeastOnePermission(command.permission, Session.get('openedRoom')); }).sort((a, b) => a._id > b._id).slice(0, 11); }, }; return config; }, emojiEnabled() { - return RocketChat.emoji != null; + return emoji != null; }, popupEmojiConfig() { - if (RocketChat.emoji != null) { + if (emoji != null) { const self = this; return { title: t('Emoji'), - collection: RocketChat.emoji.list, + collection: emoji.list, template: 'messagePopupEmoji', trigger: ':', prefix: '', @@ -438,11 +440,11 @@ Template.messagePopupConfig.helpers({ } }, popupReactionEmojiConfig() { - if (RocketChat.emoji != null) { + if (emoji != null) { const self = this; return { title: t('Emoji'), - collection: RocketChat.emoji.list, + collection: emoji.list, template: 'messagePopupEmoji', trigger: '\\+:', prefix: '+', diff --git a/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js b/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js index 63090414a00a..bcc7717daee4 100644 --- a/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js +++ b/packages/rocketchat-ui-message/client/popup/messagePopupSlashCommandPreview.js @@ -2,7 +2,8 @@ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Session } from 'meteor/session'; import { Template } from 'meteor/templating'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { slashCommands } from 'meteor/rocketchat:utils'; +import { hasAtLeastOnePermission } from 'meteor/rocketchat:authorization'; import { toolbarSearch } from 'meteor/rocketchat:ui-sidenav'; import _ from 'underscore'; @@ -123,12 +124,12 @@ Template.messagePopupSlashCommandPreview.onCreated(function() { const matches = inputValueAtCursor.match(template.selectorRegex); const cmd = matches[1].replace('/', '').trim().toLowerCase(); - const command = RocketChat.slashCommands.commands[cmd]; + const command = slashCommands.commands[cmd]; // Ensure the command they're typing actually exists // And it provides a command preview // And if it provides a permission to check, they have permission to run the command - if (!command || !command.providesPreview || (command.permission && !RocketChat.authz.hasAtLeastOnePermission(command.permission, Session.get('openedRoom')))) { + if (!command || !command.providesPreview || (command.permission && !hasAtLeastOnePermission(command.permission, Session.get('openedRoom')))) { template.open.set(false); return; } diff --git a/packages/rocketchat-ui-message/client/startup/messageBoxActions.js b/packages/rocketchat-ui-message/client/startup/messageBoxActions.js index 510013f93cd2..92b9b40552b3 100644 --- a/packages/rocketchat-ui-message/client/startup/messageBoxActions.js +++ b/packages/rocketchat-ui-message/client/startup/messageBoxActions.js @@ -4,27 +4,29 @@ import { ReactiveVar } from 'meteor/reactive-var'; import { Tracker } from 'meteor/tracker'; import mime from 'mime-type/with-db'; import { VRecDialog } from 'meteor/rocketchat:ui-vrecord'; -import { RocketChat } from 'meteor/rocketchat:lib'; -import { modal, fileUpload } from 'meteor/rocketchat:ui'; +import { messageBox, modal } from 'meteor/rocketchat:ui-utils'; +import { fileUpload } from 'meteor/rocketchat:ui'; +import { settings } from 'meteor/rocketchat:settings'; import { t } from 'meteor/rocketchat:utils'; +import { geolocation } from '../messageBox'; -RocketChat.messageBox.actions.add('Create_new', 'Video_message', { +messageBox.actions.add('Create_new', 'Video_message', { id: 'video-message', icon: 'video', condition: () => (navigator.mediaDevices || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) && window.MediaRecorder && - RocketChat.settings.get('FileUpload_Enabled') && - RocketChat.settings.get('Message_VideoRecorderEnabled') && - (!RocketChat.settings.get('FileUpload_MediaTypeWhiteList') || - RocketChat.settings.get('FileUpload_MediaTypeWhiteList').match(/video\/webm|video\/\*/i)), + settings.get('FileUpload_Enabled') && + settings.get('Message_VideoRecorderEnabled') && + (!settings.get('FileUpload_MediaTypeWhiteList') || + settings.get('FileUpload_MediaTypeWhiteList').match(/video\/webm|video\/\*/i)), action: ({ messageBox }) => (VRecDialog.opened ? VRecDialog.close() : VRecDialog.open(messageBox)), }); -RocketChat.messageBox.actions.add('Add_files_from', 'Computer', { +messageBox.actions.add('Add_files_from', 'Computer', { id: 'file-upload', icon: 'computer', - condition: () => RocketChat.settings.get('FileUpload_Enabled'), + condition: () => settings.get('FileUpload_Enabled'), action({ event }) { event.preventDefault(); const $input = $(document.createElement('input')); @@ -61,14 +63,14 @@ RocketChat.messageBox.actions.add('Add_files_from', 'Computer', { }, }); -RocketChat.messageBox.actions.add('Share', 'My_location', { +messageBox.actions.add('Share', 'My_location', { id: 'share-location', icon: 'map-pin', - condition: () => RocketChat.Geolocation.get() !== false, + condition: () => geolocation.get() !== false, action({ rid }) { - const position = RocketChat.Geolocation.get(); + const position = geolocation.get(); const { latitude, longitude } = position.coords; - const text = `
`; + const text = `
`; modal.open({ title: t('Share_Location_Title'), diff --git a/packages/rocketchat-ui-message/package.js b/packages/rocketchat-ui-message/package.js index 550a41dc6d9d..1cc6fe32bcc3 100644 --- a/packages/rocketchat-ui-message/package.js +++ b/packages/rocketchat-ui-message/package.js @@ -17,7 +17,6 @@ Package.onUse(function(api) { 'templating', 'tracker', 'rocketchat:utils', - 'rocketchat:ui', 'rocketchat:ui-utils', 'rocketchat:emoji', 'rocketchat:katex', @@ -28,6 +27,11 @@ Package.onUse(function(api) { 'rocketchat:ui-sidenav', 'rocketchat:file-upload', 'rocketchat:autotranslate', + 'rocketchat:authorization', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:callbacks', + 'rocketchat:markdown', ]); api.addAssets('../../node_modules/pdfjs-dist/build/pdf.worker.js', 'client'); api.mainModule('client/index.js', 'client'); diff --git a/packages/rocketchat-ui/package.js b/packages/rocketchat-ui/package.js index 7f3ad27a60e2..7af0cd23ce2f 100644 --- a/packages/rocketchat-ui/package.js +++ b/packages/rocketchat-ui/package.js @@ -36,6 +36,8 @@ Package.onUse(function(api) { 'rocketchat:file-upload', 'konecty:user-presence', 'rocketchat:webrtc', + 'rocketchat:markdown', + 'rocketchat:emoji', ]); api.mainModule('client/index.js', 'client'); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-user-data-download/package.js b/packages/rocketchat-user-data-download/package.js index e10af05cc569..6fcd5038490d 100644 --- a/packages/rocketchat-user-data-download/package.js +++ b/packages/rocketchat-user-data-download/package.js @@ -10,7 +10,8 @@ Package.onUse(function(api) { 'ecmascript', 'rocketchat:file', 'rocketchat:file-upload', - 'rocketchat:lib', + 'rocketchat:settings', + 'rocketchat:models', 'webapp', ]); api.mainModule('server/index.js', 'server'); diff --git a/packages/rocketchat-user-data-download/server/cronProcessDownloads.js b/packages/rocketchat-user-data-download/server/cronProcessDownloads.js index f3fd2d60191f..260f6fb76c30 100644 --- a/packages/rocketchat-user-data-download/server/cronProcessDownloads.js +++ b/packages/rocketchat-user-data-download/server/cronProcessDownloads.js @@ -1,6 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Subscriptions, Rooms, Users, Uploads, Messages, UserDataFiles, ExportOperations } from 'meteor/rocketchat:models'; import { FileUpload } from 'meteor/rocketchat:file-upload'; import { SyncedCron } from 'meteor/littledata:synced-cron'; import fs from 'fs'; @@ -9,15 +10,15 @@ import archiver from 'archiver'; import * as Mailer from 'meteor/rocketchat:mailer'; let zipFolder = '/tmp/zipFiles'; -if (RocketChat.settings.get('UserData_FileSystemZipPath') != null) { - if (RocketChat.settings.get('UserData_FileSystemZipPath').trim() !== '') { - zipFolder = RocketChat.settings.get('UserData_FileSystemZipPath'); +if (settings.get('UserData_FileSystemZipPath') != null) { + if (settings.get('UserData_FileSystemZipPath').trim() !== '') { + zipFolder = settings.get('UserData_FileSystemZipPath'); } } let processingFrequency = 15; -if (RocketChat.settings.get('UserData_ProcessingFrequency') > 0) { - processingFrequency = RocketChat.settings.get('UserData_ProcessingFrequency'); +if (settings.get('UserData_ProcessingFrequency') > 0) { + processingFrequency = settings.get('UserData_ProcessingFrequency'); } const startFile = function(fileName, content) { @@ -38,16 +39,16 @@ const loadUserSubscriptions = function(exportOperation) { exportOperation.roomList = []; const exportUserId = exportOperation.userId; - const cursor = RocketChat.models.Subscriptions.findByUserId(exportUserId); + const cursor = Subscriptions.findByUserId(exportUserId); cursor.forEach((subscription) => { const roomId = subscription.rid; - const roomData = RocketChat.models.Rooms.findOneById(roomId); + const roomData = Rooms.findOneById(roomId); let roomName = (roomData && roomData.name) ? roomData.name : roomId; let userId = null; if (subscription.t === 'd') { userId = roomId.replace(exportUserId, ''); - const userData = RocketChat.models.Users.findOneById(userId); + const userData = Users.findOneById(userId); if (userData) { roomName = userData.name; @@ -108,7 +109,7 @@ const getAttachmentData = function(attachment) { const match = /^\/([^\/]+)\/([^\/]+)\/(.*)/.exec(url); if (match && match[2]) { - const file = RocketChat.models.Uploads.findOneById(match[2]); + const file = Uploads.findOneById(match[2]); if (file) { attachmentData.fileId = file._id; @@ -173,7 +174,7 @@ const copyFile = function(exportOperation, attachmentData) { return; } - const file = RocketChat.models.Uploads.findOneById(attachmentData.fileId); + const file = Uploads.findOneById(attachmentData.fileId); if (file) { if (FileUpload.copy(file, attachmentData.targetFile)) { @@ -197,13 +198,13 @@ const continueExportingRoom = function(exportOperation, exportOpRoomData) { } let limit = 100; - if (RocketChat.settings.get('UserData_MessageLimitPerRequest') > 0) { - limit = RocketChat.settings.get('UserData_MessageLimitPerRequest'); + if (settings.get('UserData_MessageLimitPerRequest') > 0) { + limit = settings.get('UserData_MessageLimitPerRequest'); } const skip = exportOpRoomData.exportedCount; - const cursor = RocketChat.models.Messages.findByRoomId(exportOpRoomData.roomId, { limit, skip }); + const cursor = Messages.findByRoomId(exportOpRoomData.roomId, { limit, skip }); const count = cursor.count(); cursor.forEach((msg) => { @@ -288,17 +289,17 @@ const isDownloadFinished = function(exportOperation) { }; const sendEmail = function(userId) { - const lastFile = RocketChat.models.UserDataFiles.findLastFileByUser(userId); + const lastFile = UserDataFiles.findLastFileByUser(userId); if (!lastFile) { return; } - const userData = RocketChat.models.Users.findOneById(userId); + const userData = Users.findOneById(userId); if (!userData || !userData.emails || !userData.emails[0] || !userData.emails[0].address) { return; } const emailAddress = `${ userData.name } <${ userData.emails[0].address }>`; - const fromAddress = RocketChat.settings.get('From_Email'); + const fromAddress = settings.get('From_Email'); const subject = TAPi18n.__('UserDataDownload_EmailSubject'); const download_link = lastFile.url; @@ -355,7 +356,7 @@ const uploadZipFile = function(exportOperation, callback) { const { size } = stat; const { userId } = exportOperation; - const user = RocketChat.models.Users.findOneById(userId); + const user = Users.findOneById(userId); const userDisplayName = user ? user.name : userId; const utcDate = new Date().toISOString().split('T')[0]; @@ -448,7 +449,7 @@ const continueExportOperation = function(exportOperation) { if (exportOperation.status === 'uploading') { uploadZipFile(exportOperation, () => { exportOperation.status = 'completed'; - RocketChat.models.ExportOperations.updateOperation(exportOperation); + ExportOperations.updateOperation(exportOperation); }); return; } @@ -458,14 +459,14 @@ const continueExportOperation = function(exportOperation) { }; function processDataDownloads() { - const cursor = RocketChat.models.ExportOperations.findAllPending({ limit: 1 }); + const cursor = ExportOperations.findAllPending({ limit: 1 }); cursor.forEach((exportOperation) => { if (exportOperation.status === 'completed') { return; } continueExportOperation(exportOperation); - RocketChat.models.ExportOperations.updateOperation(exportOperation); + ExportOperations.updateOperation(exportOperation); if (exportOperation.status === 'completed') { sendEmail(exportOperation.userId); diff --git a/packages/rocketchat-user-data-download/server/startup/settings.js b/packages/rocketchat-user-data-download/server/startup/settings.js index 6025752d35c1..352033683672 100644 --- a/packages/rocketchat-user-data-download/server/startup/settings.js +++ b/packages/rocketchat-user-data-download/server/startup/settings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('UserDataDownload', function() { +settings.addGroup('UserDataDownload', function() { this.add('UserData_EnableDownload', true, { type: 'boolean', diff --git a/packages/rocketchat-version-check/client/client.js b/packages/rocketchat-version-check/client/client.js index 6d37b5d73a78..631881e25e55 100644 --- a/packages/rocketchat-version-check/client/client.js +++ b/packages/rocketchat-version-check/client/client.js @@ -1,7 +1,7 @@ import { Meteor } from 'meteor/meteor'; import { Tracker } from 'meteor/tracker'; import { TAPi18n } from 'meteor/tap:i18n'; -import { alerts } from 'meteor/rocketchat:ui'; +import { alerts } from 'meteor/rocketchat:ui-utils'; Meteor.startup(function() { Tracker.autorun(() => { diff --git a/packages/rocketchat-version-check/package.js b/packages/rocketchat-version-check/package.js index 2f76c06b8c3e..970d9830290c 100644 --- a/packages/rocketchat-version-check/package.js +++ b/packages/rocketchat-version-check/package.js @@ -9,8 +9,11 @@ Package.onUse(function(api) { api.use([ 'mongo', 'ecmascript', - 'rocketchat:lib', + 'rocketchat:ui-utils', 'rocketchat:logger', + 'rocketchat:models', + 'rocketchat:settings', + 'rocketchat:utils', 'rocketchat:cloud', 'littledata:synced-cron', ]); diff --git a/packages/rocketchat-version-check/server/addSettings.js b/packages/rocketchat-version-check/server/addSettings.js index 9b41cd65615f..8715baf2154c 100644 --- a/packages/rocketchat-version-check/server/addSettings.js +++ b/packages/rocketchat-version-check/server/addSettings.js @@ -1,6 +1,6 @@ -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; -RocketChat.settings.addGroup('General', function() { +settings.addGroup('General', function() { this.section('Update', function() { this.add('Update_LatestAvailableVersion', '0.0.0', { type: 'string', diff --git a/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js b/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js index d5457605377b..85c9d079fb1e 100644 --- a/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js +++ b/packages/rocketchat-version-check/server/functions/checkVersionUpdate.js @@ -1,6 +1,8 @@ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; +import { Roles, Users } from 'meteor/rocketchat:models'; import semver from 'semver'; import logger from '../logger'; import getNewUpdates from './getNewUpdates'; @@ -17,13 +19,13 @@ export default () => { security: false, }; - const lastCheckedVersion = RocketChat.settings.get('Update_LatestAvailableVersion'); + const lastCheckedVersion = settings.get('Update_LatestAvailableVersion'); versions.forEach((version) => { if (semver.lte(version.version, lastCheckedVersion)) { return; } - if (semver.lte(version.version, RocketChat.Info.version)) { + if (semver.lte(version.version, Info.version)) { return; } @@ -36,8 +38,8 @@ export default () => { }); if (update.exists) { - RocketChat.settings.updateById('Update_LatestAvailableVersion', update.lastestVersion.version); - RocketChat.models.Roles.findUsersInRole('admin').forEach((adminUser) => { + settings.updateById('Update_LatestAvailableVersion', update.lastestVersion.version); + Roles.findUsersInRole('admin').forEach((adminUser) => { try { Meteor.runAsUser(adminUser._id, () => Meteor.call('createDirectMessage', 'rocket.cat')); @@ -51,7 +53,7 @@ export default () => { console.error(e); } - RocketChat.models.Users.addBannerById(adminUser._id, { + Users.addBannerById(adminUser._id, { id: 'versionUpdate', priority: 10, title: 'Update_your_RocketChat', @@ -63,12 +65,12 @@ export default () => { } if (alerts && alerts.length) { - RocketChat.models.Roles.findUsersInRole('admin').forEach((adminUser) => { + Roles.findUsersInRole('admin').forEach((adminUser) => { try { Meteor.runAsUser(adminUser._id, () => Meteor.call('createDirectMessage', 'rocket.cat')); alerts.forEach((alert) => { - if (RocketChat.models.Users.bannerExistsById(adminUser._id, `alert-${ alert.id }`)) { + if (Users.bannerExistsById(adminUser._id, `alert-${ alert.id }`)) { return; } @@ -84,7 +86,7 @@ export default () => { } alerts.forEach((alert) => { - RocketChat.models.Users.addBannerById(adminUser._id, { + Users.addBannerById(adminUser._id, { id: `alert-${ alert.id }`, priority: 10, title: alert.title, diff --git a/packages/rocketchat-version-check/server/functions/getNewUpdates.js b/packages/rocketchat-version-check/server/functions/getNewUpdates.js index 6480651a2f91..9880cd05b22b 100644 --- a/packages/rocketchat-version-check/server/functions/getNewUpdates.js +++ b/packages/rocketchat-version-check/server/functions/getNewUpdates.js @@ -1,19 +1,21 @@ import os from 'os'; import { HTTP } from 'meteor/http'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Settings } from 'meteor/rocketchat:models'; +import { settings } from 'meteor/rocketchat:settings'; +import { Info } from 'meteor/rocketchat:utils'; import { getWorkspaceAccessToken } from 'meteor/rocketchat:cloud'; import { MongoInternals } from 'meteor/mongo'; export default () => { try { - const uniqueID = RocketChat.models.Settings.findOne('uniqueID'); + const uniqueID = Settings.findOne('uniqueID'); const { _oplogHandle } = MongoInternals.defaultRemoteCollectionDriver().mongo; - const oplogEnabled = _oplogHandle && _oplogHandle.onOplogEntry && RocketChat.settings.get('Force_Disable_OpLog_For_Cache') !== true; + const oplogEnabled = _oplogHandle && _oplogHandle.onOplogEntry && settings.get('Force_Disable_OpLog_For_Cache') !== true; const data = { uniqueId: uniqueID.value, installedAt: uniqueID.createdAt, - version: RocketChat.Info.version, + version: Info.version, oplogEnabled, osType: os.type(), osPlatform: os.platform(), diff --git a/packages/rocketchat-version-check/server/methods/banner_dismiss.js b/packages/rocketchat-version-check/server/methods/banner_dismiss.js index cdbc2166ab02..eb5cef23fcbc 100644 --- a/packages/rocketchat-version-check/server/methods/banner_dismiss.js +++ b/packages/rocketchat-version-check/server/methods/banner_dismiss.js @@ -1,5 +1,5 @@ import { Meteor } from 'meteor/meteor'; -import { RocketChat } from 'meteor/rocketchat:lib'; +import { Users } from 'meteor/rocketchat:models'; Meteor.methods({ 'banner/dismiss'({ id }) { @@ -7,6 +7,6 @@ Meteor.methods({ throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'banner/dismiss' }); } - RocketChat.models.Users.setBannerReadById(this.userId, id); + Users.setBannerReadById(this.userId, id); }, }); diff --git a/packages/rocketchat-webdav/client/collections/WebdavAccounts.js b/packages/rocketchat-webdav/client/collections/WebdavAccounts.js index 831bfb51a00e..4e35e772f4cc 100644 --- a/packages/rocketchat-webdav/client/collections/WebdavAccounts.js +++ b/packages/rocketchat-webdav/client/collections/WebdavAccounts.js @@ -1,4 +1,4 @@ import { RocketChat } from 'meteor/rocketchat:lib'; -import { Mongo } from 'meteor/mongo'; +import { WebdavAccounts } from 'meteor/rocketchat:models'; -RocketChat.models.WebdavAccounts = new Mongo.Collection('rocketchat_webdav_accounts'); +RocketChat.models.WebdavAccounts = WebdavAccounts;