Skip to content

Commit

Permalink
Remove some dependencies inside rocketchat-lib/server/lib (#13217)
Browse files Browse the repository at this point in the history
* Move integrations models to rc-models

* Move composeMessage function to rc-utils

* Move PushNotifications class to push-notifications package

* Import variables to remove dependency of RC namespace

* Import variables to remove RC namespace dependency inside rc-lib/server/lib
  • Loading branch information
MarcosSpessatto authored and rodrigok committed Jan 22, 2019
1 parent 118634c commit 2bf63fb
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 77 deletions.
8 changes: 5 additions & 3 deletions packages/rocketchat-lib/server/lib/bugsnag.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Meteor } from 'meteor/meteor';
import { settings } from 'meteor/rocketchat:settings';
import { Info } from 'meteor/rocketchat:utils';
import bugsnag from 'bugsnag';

RocketChat.bugsnag = bugsnag;

RocketChat.settings.get('Bugsnag_api_key', (key, value) => {
settings.get('Bugsnag_api_key', (key, value) => {
if (value) {
bugsnag.register(value);
}
Expand All @@ -14,8 +16,8 @@ const notify = function(message, stack) {
message += ` ${ stack }`;
}
let options = {};
if (RocketChat.Info) {
options = { app: { version: RocketChat.Info.version, info: RocketChat.Info } };
if (Info) {
options = { app: { version: Info.version, info: Info } };
}
const error = new Error(message);
error.stack = stack;
Expand Down
7 changes: 4 additions & 3 deletions packages/rocketchat-lib/server/lib/configLogger.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { Meteor } from 'meteor/meteor';
import { LoggerManager } from 'meteor/rocketchat:logger';
import { settings } from 'meteor/rocketchat:settings';

RocketChat.settings.get('Log_Package', function(key, value) {
settings.get('Log_Package', function(key, value) {
return LoggerManager.showPackage = value;
});

RocketChat.settings.get('Log_File', function(key, value) {
settings.get('Log_File', function(key, value) {
return LoggerManager.showFileAndLine = value;
});

RocketChat.settings.get('Log_Level', function(key, value) {
settings.get('Log_Level', function(key, value) {
if (value != null) {
LoggerManager.logLevel = parseInt(value);
Meteor.setTimeout(() => LoggerManager.enable(true), 200);
Expand Down
14 changes: 8 additions & 6 deletions packages/rocketchat-lib/server/lib/debug.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { InstanceStatus } from 'meteor/konecty:multiple-instances-status';
import { settings } from 'meteor/rocketchat:settings';
import { metrics } from 'meteor/rocketchat:metrics';
import _ from 'underscore';
import { Logger } from 'meteor/rocketchat:logger';

Expand All @@ -17,13 +19,13 @@ const logger = new Logger('Meteor', {

let Log_Trace_Methods;
let Log_Trace_Subscriptions;
RocketChat.settings.get('Log_Trace_Methods', (key, value) => Log_Trace_Methods = value);
RocketChat.settings.get('Log_Trace_Subscriptions', (key, value) => Log_Trace_Subscriptions = value);
settings.get('Log_Trace_Methods', (key, value) => Log_Trace_Methods = value);
settings.get('Log_Trace_Subscriptions', (key, value) => Log_Trace_Subscriptions = value);

let Log_Trace_Methods_Filter;
let Log_Trace_Subscriptions_Filter;
RocketChat.settings.get('Log_Trace_Methods_Filter', (key, value) => Log_Trace_Methods_Filter = value ? new RegExp(value) : undefined);
RocketChat.settings.get('Log_Trace_Subscriptions_Filter', (key, value) => Log_Trace_Subscriptions_Filter = value ? new RegExp(value) : undefined);
settings.get('Log_Trace_Methods_Filter', (key, value) => Log_Trace_Methods_Filter = value ? new RegExp(value) : undefined);
settings.get('Log_Trace_Subscriptions_Filter', (key, value) => Log_Trace_Subscriptions_Filter = value ? new RegExp(value) : undefined);

const traceConnection = (enable, filter, prefix, name, connection, userId) => {
if (!enable) {
Expand All @@ -49,7 +51,7 @@ const traceConnection = (enable, filter, prefix, name, connection, userId) => {
const wrapMethods = function(name, originalHandler, methodsMap) {
methodsMap[name] = function(...originalArgs) {
traceConnection(Log_Trace_Methods, Log_Trace_Methods_Filter, 'method', name, this.connection, this.userId);
const end = RocketChat.metrics.meteorMethods.startTimer({
const end = metrics.meteorMethods.startTimer({
method: name,
has_connection: this.connection != null,
has_user: this.userId != null,
Expand Down Expand Up @@ -89,7 +91,7 @@ Meteor.publish = function(name, func) {
return originalMeteorPublish(name, function(...args) {
traceConnection(Log_Trace_Subscriptions, Log_Trace_Subscriptions_Filter, 'subscription', name, this.connection, this.userId);
logger.publish(name, '-> userId:', this.userId, ', arguments: ', args);
const end = RocketChat.metrics.meteorSubscriptions.startTimer({ subscription: name });
const end = metrics.meteorSubscriptions.startTimer({ subscription: name });

const originalReady = this.ready;
this.ready = function() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
RocketChat.emailDomainDefaultBlackList = [
export const emailDomainDefaultBlackList = [
'0-mail.com',
'0815.ru',
'0815.su',
Expand Down
27 changes: 14 additions & 13 deletions packages/rocketchat-lib/server/lib/interceptDirectReplyEmails.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { Meteor } from 'meteor/meteor';
import { settings } from 'meteor/rocketchat:settings';
import IMAP from 'imap';
import POP3 from 'poplib';
import { simpleParser } from 'mailparser';

export class IMAPIntercepter {
constructor() {
this.imap = new IMAP({
user: RocketChat.settings.get('Direct_Reply_Username'),
password: RocketChat.settings.get('Direct_Reply_Password'),
host: RocketChat.settings.get('Direct_Reply_Host'),
port: RocketChat.settings.get('Direct_Reply_Port'),
debug: RocketChat.settings.get('Direct_Reply_Debug') ? console.log : false,
tls: !RocketChat.settings.get('Direct_Reply_IgnoreTLS'),
user: settings.get('Direct_Reply_Username'),
password: settings.get('Direct_Reply_Password'),
host: settings.get('Direct_Reply_Host'),
port: settings.get('Direct_Reply_Port'),
debug: settings.get('Direct_Reply_Debug') ? console.log : false,
tls: !settings.get('Direct_Reply_IgnoreTLS'),
connTimeout: 30000,
keepalive: true,
});

this.delete = RocketChat.settings.get('Direct_Reply_Delete') ? RocketChat.settings.get('Direct_Reply_Delete') : true;
this.delete = settings.get('Direct_Reply_Delete') ? settings.get('Direct_Reply_Delete') : true;

// On successfully connected.
this.imap.on('ready', Meteor.bindEnvironment(() => {
Expand Down Expand Up @@ -140,16 +141,16 @@ export class IMAPIntercepter {

export class POP3Intercepter {
constructor() {
this.pop3 = new POP3(RocketChat.settings.get('Direct_Reply_Port'), RocketChat.settings.get('Direct_Reply_Host'), {
enabletls: !RocketChat.settings.get('Direct_Reply_IgnoreTLS'),
debug: RocketChat.settings.get('Direct_Reply_Debug') ? console.log : false,
this.pop3 = new POP3(settings.get('Direct_Reply_Port'), settings.get('Direct_Reply_Host'), {
enabletls: !settings.get('Direct_Reply_IgnoreTLS'),
debug: settings.get('Direct_Reply_Debug') ? console.log : false,
});

this.totalMsgCount = 0;
this.currentMsgCount = 0;

this.pop3.on('connect', Meteor.bindEnvironment(() => {
this.pop3.login(RocketChat.settings.get('Direct_Reply_Username'), RocketChat.settings.get('Direct_Reply_Password'));
this.pop3.login(settings.get('Direct_Reply_Username'), settings.get('Direct_Reply_Password'));
}));

this.pop3.on('login', Meteor.bindEnvironment((status) => {
Expand Down Expand Up @@ -242,13 +243,13 @@ export class POP3Helper {

start() {
// run every x-minutes
if (RocketChat.settings.get('Direct_Reply_Frequency')) {
if (settings.get('Direct_Reply_Frequency')) {
RocketChat.POP3 = new POP3Intercepter();

this.running = Meteor.setInterval(() => {
// get new emails and process
RocketChat.POP3 = new POP3Intercepter();
}, Math.max(RocketChat.settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000));
}, Math.max(settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000));
}
}

Expand Down
37 changes: 20 additions & 17 deletions packages/rocketchat-lib/server/lib/notifyUsersOnMessage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import _ from 'underscore';
import s from 'underscore.string';
import moment from 'moment';
import { Rooms, Subscriptions } from 'meteor/rocketchat:models';
import { settings } from 'meteor/rocketchat:settings';
import { callbacks } from 'meteor/rocketchat:callbacks';

/**
* Chechs if a messages contains a user highlight
Expand All @@ -24,19 +27,19 @@ function notifyUsersOnMessage(message, room) {
// skips this callback if the message was edited and increments it if the edit was way in the past (aka imported)
if (message.editedAt && Math.abs(moment(message.editedAt).diff()) > 60000) {
// TODO: Review as I am not sure how else to get around this as the incrementing of the msgs count shouldn't be in this callback
RocketChat.models.Rooms.incMsgCountById(message.rid, 1);
Rooms.incMsgCountById(message.rid, 1);
return message;
} else if (message.editedAt) {

// only updates last message if it was edited (skip rest of callback)
if (RocketChat.settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) {
RocketChat.models.Rooms.setLastMessageById(message.rid, message);
if (settings.get('Store_Last_Message') && (!room.lastMessage || room.lastMessage._id === message._id)) {
Rooms.setLastMessageById(message.rid, message);
}
return message;
}

if (message.ts && Math.abs(moment(message.ts).diff()) > 60000) {
RocketChat.models.Rooms.incMsgCountById(message.rid, 1);
Rooms.incMsgCountById(message.rid, 1);
return message;
}

Expand All @@ -45,7 +48,7 @@ function notifyUsersOnMessage(message, room) {
let toHere = false;
const mentionIds = [];
const highlightsIds = [];
const highlights = RocketChat.models.Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch();
const highlights = Subscriptions.findByRoomWithUserHighlights(room._id, { fields: { userHighlights: 1, 'u._id': 1 } }).fetch();
if (message.mentions != null) {
message.mentions.forEach(function(mention) {
if (!toAll && mention._id === 'all') {
Expand All @@ -69,47 +72,47 @@ function notifyUsersOnMessage(message, room) {
});

if (room.t === 'd') {
const unreadCountDM = RocketChat.settings.get('Unread_Count_DM');
const unreadCountDM = settings.get('Unread_Count_DM');

if (unreadCountDM === 'all_messages') {
RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id);
Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id);
} else if (toAll || toHere) {
RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1);
Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, 1);
} else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) {
RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1);
Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, 1);
}
} else {
const unreadCount = RocketChat.settings.get('Unread_Count');
const unreadCount = settings.get('Unread_Count');

if (toAll || toHere) {
let incUnread = 0;
if (['all_messages', 'group_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) {
incUnread = 1;
}
RocketChat.models.Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread);
Subscriptions.incGroupMentionsAndUnreadForRoomIdExcludingUserId(room._id, message.u._id, 1, incUnread);

} else if ((mentionIds && mentionIds.length > 0) || (highlightsIds && highlightsIds.length > 0)) {
let incUnread = 0;
if (['all_messages', 'user_mentions_only', 'user_and_group_mentions_only'].includes(unreadCount)) {
incUnread = 1;
}
RocketChat.models.Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread);
Subscriptions.incUserMentionsAndUnreadForRoomIdAndUserIds(room._id, _.compact(_.unique(mentionIds.concat(highlightsIds))), 1, incUnread);
} else if (unreadCount === 'all_messages') {
RocketChat.models.Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id);
Subscriptions.incUnreadForRoomIdExcludingUserId(room._id, message.u._id);
}
}
}

// Update all the room activity tracker fields
// This method take so long to execute on gient rooms cuz it will trugger the cache rebuild for the releations of that room
RocketChat.models.Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, RocketChat.settings.get('Store_Last_Message') && message);
Rooms.incMsgCountAndSetLastMessageById(message.rid, 1, message.ts, settings.get('Store_Last_Message') && message);
// Update all other subscriptions to alert their owners but witout incrementing
// the unread counter, as it is only for mentions and direct messages
// We now set alert and open properties in two separate update commands. This proved to be more efficient on MongoDB - because it uses a more efficient index.
RocketChat.models.Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id);
RocketChat.models.Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id);
Subscriptions.setAlertForRoomIdExcludingUserId(message.rid, message.u._id);
Subscriptions.setOpenForRoomIdExcludingUserId(message.rid, message.u._id);

return message;
}

RocketChat.callbacks.add('afterSaveMessage', notifyUsersOnMessage, RocketChat.callbacks.priority.LOW, 'notifyUsersOnMessage');
callbacks.add('afterSaveMessage', notifyUsersOnMessage, callbacks.priority.LOW, 'notifyUsersOnMessage');
22 changes: 12 additions & 10 deletions packages/rocketchat-lib/server/lib/passwordPolicy.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { settings } from 'meteor/rocketchat:settings';
import PasswordPolicy from './PasswordPolicyClass';

RocketChat.passwordPolicy = new PasswordPolicy();
const passwordPolicy = new PasswordPolicy();
RocketChat.passwordPolicy = passwordPolicy;

RocketChat.settings.get('Accounts_Password_Policy_Enabled', (key, value) => RocketChat.passwordPolicy.enabled = value);
RocketChat.settings.get('Accounts_Password_Policy_MinLength', (key, value) => RocketChat.passwordPolicy.minLength = value);
RocketChat.settings.get('Accounts_Password_Policy_MaxLength', (key, value) => RocketChat.passwordPolicy.maxLength = value);
RocketChat.settings.get('Accounts_Password_Policy_ForbidRepeatingCharacters', (key, value) => RocketChat.passwordPolicy.forbidRepeatingCharacters = value);
RocketChat.settings.get('Accounts_Password_Policy_ForbidRepeatingCharactersCount', (key, value) => RocketChat.passwordPolicy.forbidRepeatingCharactersCount = value);
RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneLowercase', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneLowercase = value);
RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneUppercase', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneUppercase = value);
RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneNumber', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneNumber = value);
RocketChat.settings.get('Accounts_Password_Policy_AtLeastOneSpecialCharacter', (key, value) => RocketChat.passwordPolicy.mustContainAtLeastOneSpecialCharacter = value);
settings.get('Accounts_Password_Policy_Enabled', (key, value) => passwordPolicy.enabled = value);
settings.get('Accounts_Password_Policy_MinLength', (key, value) => passwordPolicy.minLength = value);
settings.get('Accounts_Password_Policy_MaxLength', (key, value) => passwordPolicy.maxLength = value);
settings.get('Accounts_Password_Policy_ForbidRepeatingCharacters', (key, value) => passwordPolicy.forbidRepeatingCharacters = value);
settings.get('Accounts_Password_Policy_ForbidRepeatingCharactersCount', (key, value) => passwordPolicy.forbidRepeatingCharactersCount = value);
settings.get('Accounts_Password_Policy_AtLeastOneLowercase', (key, value) => passwordPolicy.mustContainAtLeastOneLowercase = value);
settings.get('Accounts_Password_Policy_AtLeastOneUppercase', (key, value) => passwordPolicy.mustContainAtLeastOneUppercase = value);
settings.get('Accounts_Password_Policy_AtLeastOneNumber', (key, value) => passwordPolicy.mustContainAtLeastOneNumber = value);
settings.get('Accounts_Password_Policy_AtLeastOneSpecialCharacter', (key, value) => passwordPolicy.mustContainAtLeastOneSpecialCharacter = value);
17 changes: 10 additions & 7 deletions packages/rocketchat-lib/server/lib/processDirectEmail.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { Meteor } from 'meteor/meteor';
import { settings } from 'meteor/rocketchat:settings';
import { Rooms, Messages, Users, Subscriptions } from 'meteor/rocketchat:models';
import { metrics } from 'meteor/rocketchat:metrics';
import { EmailReplyParser as reply } from 'emailreplyparser';
import moment from 'moment';

Expand All @@ -20,14 +23,14 @@ RocketChat.processDirectEmail = function(email) {
message.ts = new Date();
}

if (message.msg && message.msg.length > RocketChat.settings.get('Message_MaxAllowedSize')) {
if (message.msg && message.msg.length > settings.get('Message_MaxAllowedSize')) {
return false;
}

// reduce new lines in multiline message
message.msg = message.msg.split('\n\n').join('\n');

const user = RocketChat.models.Users.findOneByEmailAddress(email.headers.from, {
const user = Users.findOneByEmailAddress(email.headers.from, {
fields: {
username: 1,
name: 1,
Expand All @@ -38,7 +41,7 @@ RocketChat.processDirectEmail = function(email) {
return false;
}

const prevMessage = RocketChat.models.Messages.findOneById(email.headers.mid, {
const prevMessage = Messages.findOneById(email.headers.mid, {
rid: 1,
u: 1,
});
Expand All @@ -53,7 +56,7 @@ RocketChat.processDirectEmail = function(email) {
return false;
}

const roomInfo = RocketChat.models.Rooms.findOneById(message.rid, {
const roomInfo = Rooms.findOneById(message.rid, {
t: 1,
name: 1,
});
Expand All @@ -75,7 +78,7 @@ RocketChat.processDirectEmail = function(email) {
// add reply message link
message.msg = prevMessageLink + message.msg;

const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id);
const subscription = Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id);
if (subscription && (subscription.blocked || subscription.blocker)) {
// room is blocked
return false;
Expand All @@ -86,11 +89,11 @@ RocketChat.processDirectEmail = function(email) {
return false;
}

if (message.alias == null && RocketChat.settings.get('Message_SetNameToAliasEnabled')) {
if (message.alias == null && settings.get('Message_SetNameToAliasEnabled')) {
message.alias = user.name;
}

RocketChat.metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736
metrics.messagesSent.inc(); // TODO This line needs to be moved to it's proper place. See the comments on: https://github.com/RocketChat/Rocket.Chat/pull/5736

return RocketChat.sendMessage(user, message, room);
}
Expand Down
Loading

0 comments on commit 2bf63fb

Please sign in to comment.