Add ESLint rules `prefer-template` and `template-curly-spacing` (#6456)

* Add ESLint rule `prefer-template`

* Add ESLint rule `template-curly-spacing `

* ESLint ignore rocketchat-livechat/assets/rocket-livechat.js

* Add ecmascript package to all packages

* Use ecmascript package for server and client on saml package

* Fix compilation
pull/6478/head
Rodrigo Nascimento 9 years ago committed by GitHub
parent 39e36b1b48
commit a2b4564d47
  1. 2
      .eslintrc
  2. 2
      client/routes/router.js
  3. 6
      client/startup/roomObserve.js
  4. 2
      client/startup/unread.js
  5. 6
      client/startup/usersObserve.js
  6. 4
      lib/fileUpload.js
  7. 8
      packages/meteor-accounts-saml/saml_client.js
  8. 46
      packages/meteor-accounts-saml/saml_rocketchat.js
  9. 26
      packages/meteor-accounts-saml/saml_server.js
  10. 80
      packages/meteor-accounts-saml/saml_utils.js
  11. 4
      packages/rocketchat-analytics/client/loadScript.js
  12. 14
      packages/rocketchat-analytics/client/trackEvents.js
  13. 6
      packages/rocketchat-api/server/api.js
  14. 16
      packages/rocketchat-api/server/v1/channels.js
  15. 4
      packages/rocketchat-api/server/v1/chat.js
  16. 10
      packages/rocketchat-api/server/v1/groups.js
  17. 12
      packages/rocketchat-api/server/v1/helpers/parseJsonQuery.js
  18. 8
      packages/rocketchat-api/server/v1/im.js
  19. 4
      packages/rocketchat-api/server/v1/users.js
  20. 28
      packages/rocketchat-assets/server/assets.js
  21. 10
      packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js
  22. 28
      packages/rocketchat-autotranslate/server/autotranslate.js
  23. 4
      packages/rocketchat-autotranslate/server/models/Messages.js
  24. 4
      packages/rocketchat-cas/cas_client.js
  25. 26
      packages/rocketchat-cas/cas_server.js
  26. 2
      packages/rocketchat-colors/client.js
  27. 2
      packages/rocketchat-cors/cors.js
  28. 14
      packages/rocketchat-custom-oauth/custom_oauth_client.js
  29. 20
      packages/rocketchat-custom-oauth/custom_oauth_server.js
  30. 2
      packages/rocketchat-custom-sounds/admin/adminSounds.js
  31. 6
      packages/rocketchat-custom-sounds/client/lib/CustomSounds.js
  32. 2
      packages/rocketchat-custom-sounds/server/methods/deleteCustomSound.js
  33. 4
      packages/rocketchat-custom-sounds/server/methods/insertOrUpdateSound.js
  34. 4
      packages/rocketchat-custom-sounds/server/methods/uploadCustomSound.js
  35. 4
      packages/rocketchat-custom-sounds/server/startup/custom-sounds.js
  36. 76
      packages/rocketchat-emoji-custom/client/lib/emojiCustom.js
  37. 2
      packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js
  38. 20
      packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js
  39. 4
      packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js
  40. 8
      packages/rocketchat-emoji-custom/server/startup/emoji-custom.js
  41. 2
      packages/rocketchat-emoji/emojiButton.js
  42. 2
      packages/rocketchat-emoji/emojiParser.js
  43. 30
      packages/rocketchat-emoji/emojiPicker.js
  44. 8
      packages/rocketchat-emoji/lib/EmojiPicker.js
  45. 2
      packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js
  46. 8
      packages/rocketchat-file-upload/server/config/configFileUploadAmazonS3.js
  47. 2
      packages/rocketchat-file-upload/server/config/configFileUploadFileSystem.js
  48. 10
      packages/rocketchat-file-upload/server/config/configFileUploadGoogleStorage.js
  49. 6
      packages/rocketchat-file-upload/server/config/configFileUploadGridFS.js
  50. 4
      packages/rocketchat-file-upload/server/lib/FileUpload.js
  51. 6
      packages/rocketchat-file-upload/server/methods/getS3FileUrl.js
  52. 4
      packages/rocketchat-file-upload/server/methods/sendFileMessage.js
  53. 2
      packages/rocketchat-highlight-words/client.js
  54. 6
      packages/rocketchat-i18n/package.js
  55. 4
      packages/rocketchat-iframe-login/iframe_client.js
  56. 26
      packages/rocketchat-importer-csv/server.js
  57. 52
      packages/rocketchat-importer-hipchat-enterprise/server.js
  58. 4
      packages/rocketchat-importer/server/methods/prepareImport.js
  59. 6
      packages/rocketchat-integrations/client/views/integrationsIncoming.js
  60. 2
      packages/rocketchat-integrations/client/views/integrationsOutgoing.js
  61. 80
      packages/rocketchat-integrations/server/lib/triggerHandler.js
  62. 6
      packages/rocketchat-katex/package.js
  63. 22
      packages/rocketchat-ldap/server/ldap.js
  64. 4
      packages/rocketchat-ldap/server/loginHandler.js
  65. 6
      packages/rocketchat-ldap/server/sync.js
  66. 6
      packages/rocketchat-lib/client/OAuthProxy.js
  67. 2
      packages/rocketchat-lib/client/lib/RocketChatTabBar.js
  68. 22
      packages/rocketchat-lib/client/lib/cachedCollection.js
  69. 2
      packages/rocketchat-lib/lib/getURL.js
  70. 2
      packages/rocketchat-lib/server/functions/checkEmailAvailability.js
  71. 6
      packages/rocketchat-lib/server/functions/createRoom.js
  72. 2
      packages/rocketchat-lib/server/functions/deleteUser.js
  73. 8
      packages/rocketchat-lib/server/functions/saveCustomFields.js
  74. 10
      packages/rocketchat-lib/server/functions/saveUser.js
  75. 2
      packages/rocketchat-lib/server/functions/setEmail.js
  76. 16
      packages/rocketchat-lib/server/functions/setUserAvatar.js
  77. 8
      packages/rocketchat-lib/server/lib/PushNotification.js
  78. 2
      packages/rocketchat-lib/server/lib/bugsnag.js
  79. 14
      packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js
  80. 2
      packages/rocketchat-lib/server/lib/validateEmailDomain.js
  81. 30
      packages/rocketchat-lib/server/methods/addOAuthService.js
  82. 30
      packages/rocketchat-lib/server/methods/removeOAuthService.js
  83. 8
      packages/rocketchat-lib/server/methods/setUsername.js
  84. 22
      packages/rocketchat-lib/server/models/_BaseCache.js
  85. 2
      packages/rocketchat-lib/server/models/_BaseDb.js
  86. 4
      packages/rocketchat-lib/server/oauth/google.js
  87. 4
      packages/rocketchat-lib/server/oauth/oauth.js
  88. 2
      packages/rocketchat-lib/server/oauth/proxy.js
  89. 2
      packages/rocketchat-lib/server/startup/statsTracker.js
  90. 2
      packages/rocketchat-lib/startup/defaultRoomTypes.js
  91. 2
      packages/rocketchat-livechat/app/client/lib/LivechatVideoCall.js
  92. 2
      packages/rocketchat-livechat/app/client/views/messages.js
  93. 4
      packages/rocketchat-livechat/client/views/app/livechatDepartmentForm.js
  94. 4
      packages/rocketchat-livechat/client/views/app/livechatInstallation.js
  95. 6
      packages/rocketchat-livechat/client/views/app/livechatOfficeHours.js
  96. 4
      packages/rocketchat-livechat/client/views/app/livechatTriggersForm.js
  97. 2
      packages/rocketchat-livechat/client/views/app/tabbar/externalSearch.js
  98. 2
      packages/rocketchat-livechat/client/views/app/tabbar/visitorHistory.js
  99. 8
      packages/rocketchat-livechat/client/views/app/tabbar/visitorInfo.js
  100. 2
      packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerAction.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -76,6 +76,8 @@
"use-isnan": 2,
"valid-typeof": 2,
"linebreak-style": [2, "unix"],
"prefer-template": 2,
"template-curly-spacing": [2, "always"],
"quotes": [2, "single"],
"semi": [2, "always"],
"prefer-const": 2,

@ -84,7 +84,7 @@ FlowRouter.route('/account/:group?', {
params.group = 'Preferences';
}
params.group = _.capitalize(params.group, true);
BlazeLayout.render('main', { center: `account${params.group}` });
BlazeLayout.render('main', { center: `account${ params.group }` });
}
});

@ -1,13 +1,13 @@
Meteor.startup(function() {
ChatRoom.find().observe({
added(data) {
Session.set('roomData' + data._id, data);
Session.set(`roomData${ data._id }`, data);
},
changed(data) {
Session.set('roomData' + data._id, data);
Session.set(`roomData${ data._id }`, data);
},
removed(data) {
Session.set('roomData' + data._id, undefined);
Session.set(`roomData${ data._id }`, undefined);
}
});
});

@ -78,6 +78,6 @@ Meteor.startup(function() {
});
}
document.title = unread === '' ? siteName : `(${unread}) ${siteName}`;
document.title = unread === '' ? siteName : `(${ unread }) ${ siteName }`;
});
});

@ -1,15 +1,15 @@
Meteor.startup(function() {
Meteor.users.find({}, { fields: { name: 1, username: 1, pictures: 1, status: 1, emails: 1, phone: 1, services: 1, utcOffset: 1 } }).observe({
added(user) {
Session.set('user_' + user.username + '_status', user.status);
Session.set(`user_${ user.username }_status`, user.status);
RoomManager.updateUserStatus(user, user.status, user.utcOffset);
},
changed(user) {
Session.set('user_' + user.username + '_status', user.status);
Session.set(`user_${ user.username }_status`, user.status);
RoomManager.updateUserStatus(user, user.status, user.utcOffset);
},
removed(user) {
Session.set('user_' + user.username + '_status', null);
Session.set(`user_${ user.username }_status`, null);
RoomManager.updateUserStatus(user, 'offline', null);
}
});

@ -5,8 +5,8 @@ if (UploadFS) {
const initFileStore = function() {
const cookie = new Cookies();
if (Meteor.isClient) {
document.cookie = 'rc_uid=' + escape(Meteor.userId()) + '; path=/';
document.cookie = 'rc_token=' + escape(Accounts._storedLoginToken()) + '; path=/';
document.cookie = `rc_uid=${ escape(Meteor.userId()) }; path=/`;
document.cookie = `rc_token=${ escape(Accounts._storedLoginToken()) }; path=/`;
}
Meteor.fileStore = new UploadFS.store.GridFS({

@ -60,8 +60,8 @@ const openCenteredPopup = function(url, width, height) {
// positioning the popup centered relative to the current window
const left = screenX + (outerWidth - width) / 2;
const top = screenY + (outerHeight - height) / 2;
const features = ('width=' + width + ',height=' + height +
',left=' + left + ',top=' + top + ',scrollbars=yes');
const features = (`width=${ width },height=${ height
},left=${ left },top=${ top },scrollbars=yes`);
newwindow = window.open(url, 'Login', features);
if (newwindow.focus) {
@ -74,7 +74,7 @@ const openCenteredPopup = function(url, width, height) {
Accounts.saml.initiateLogin = function(options, callback, dimensions) {
// default dimensions that worked well for facebook and google
const popup = openCenteredPopup(
Meteor.absoluteUrl('_saml/authorize/' + options.provider + '/' + options.credentialToken), (dimensions && dimensions.width) || 650, (dimensions && dimensions.height) || 500);
Meteor.absoluteUrl(`_saml/authorize/${ options.provider }/${ options.credentialToken }`), (dimensions && dimensions.width) || 650, (dimensions && dimensions.height) || 500);
const checkPopupOpen = setInterval(function() {
let popupClosed;
@ -124,6 +124,6 @@ Meteor.logoutWithSaml = function(options/*, callback*/) {
}
// A nasty bounce: 'result' has the SAML LogoutRequest but we need a proper 302 to redirected from the server.
//window.location.replace(Meteor.absoluteUrl('_saml/sloRedirect/' + options.provider + '/?redirect='+result));
window.location.replace(Meteor.absoluteUrl('_saml/sloRedirect/' + options.provider + '/?redirect=' + encodeURIComponent(result)));
window.location.replace(Meteor.absoluteUrl(`_saml/sloRedirect/${ options.provider }/?redirect=${ encodeURIComponent(result) }`));
});
};

@ -10,76 +10,76 @@ RocketChat.settings.addGroup('SAML');
Meteor.methods({
addSamlService(name) {
RocketChat.settings.add(`SAML_Custom_${name}`, false, {
RocketChat.settings.add(`SAML_Custom_${ name }`, false, {
type: 'boolean',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Enable'
});
RocketChat.settings.add(`SAML_Custom_${name}_provider`, 'provider-name', {
RocketChat.settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Provider'
});
RocketChat.settings.add(`SAML_Custom_${name}_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', {
RocketChat.settings.add(`SAML_Custom_${ name }_entry_point`, 'https://example.com/simplesaml/saml2/idp/SSOService.php', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Entry_point'
});
RocketChat.settings.add(`SAML_Custom_${name}_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', {
RocketChat.settings.add(`SAML_Custom_${ name }_idp_slo_redirect_url`, 'https://example.com/simplesaml/saml2/idp/SingleLogoutService.php', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_IDP_SLO_Redirect_URL'
});
RocketChat.settings.add(`SAML_Custom_${name}_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', {
RocketChat.settings.add(`SAML_Custom_${ name }_issuer`, 'https://your-rocket-chat/_saml/metadata/provider-name', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Issuer'
});
RocketChat.settings.add(`SAML_Custom_${name}_cert`, '', {
RocketChat.settings.add(`SAML_Custom_${ name }_cert`, '', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Cert',
multiline: true
});
RocketChat.settings.add(`SAML_Custom_${name}_public_cert`, '', {
RocketChat.settings.add(`SAML_Custom_${ name }_public_cert`, '', {
type: 'string',
group: 'SAML',
section: name,
multiline: true,
i18nLabel: 'SAML_Custom_Public_Cert'
});
RocketChat.settings.add(`SAML_Custom_${name}_private_key`, '', {
RocketChat.settings.add(`SAML_Custom_${ name }_private_key`, '', {
type: 'string',
group: 'SAML',
section: name,
multiline: true,
i18nLabel: 'SAML_Custom_Private_Key'
});
RocketChat.settings.add(`SAML_Custom_${name}_button_label_text`, '', {
RocketChat.settings.add(`SAML_Custom_${ name }_button_label_text`, '', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text'
});
RocketChat.settings.add(`SAML_Custom_${name}_button_label_color`, '#FFFFFF', {
RocketChat.settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color'
});
RocketChat.settings.add(`SAML_Custom_${name}_button_color`, '#13679A', {
RocketChat.settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Button_Color'
});
RocketChat.settings.add(`SAML_Custom_${name}_generate_username`, false, {
RocketChat.settings.add(`SAML_Custom_${ name }_generate_username`, false, {
type: 'boolean',
group: 'SAML',
section: name,
@ -90,20 +90,20 @@ Meteor.methods({
const getSamlConfigs = function(service) {
return {
buttonLabelText: RocketChat.settings.get(service.key + '_button_label_text'),
buttonLabelColor: RocketChat.settings.get(service.key + '_button_label_color'),
buttonColor: RocketChat.settings.get(service.key + '_button_color'),
buttonLabelText: RocketChat.settings.get(`${ service.key }_button_label_text`),
buttonLabelColor: RocketChat.settings.get(`${ service.key }_button_label_color`),
buttonColor: RocketChat.settings.get(`${ service.key }_button_color`),
clientConfig: {
provider: RocketChat.settings.get(service.key + '_provider')
provider: RocketChat.settings.get(`${ service.key }_provider`)
},
entryPoint: RocketChat.settings.get(service.key + '_entry_point'),
idpSLORedirectURL: RocketChat.settings.get(service.key + '_idp_slo_redirect_url'),
generateUsername: RocketChat.settings.get(service.key + '_generate_username'),
issuer: RocketChat.settings.get(service.key + '_issuer'),
entryPoint: RocketChat.settings.get(`${ service.key }_entry_point`),
idpSLORedirectURL: RocketChat.settings.get(`${ service.key }_idp_slo_redirect_url`),
generateUsername: RocketChat.settings.get(`${ service.key }_generate_username`),
issuer: RocketChat.settings.get(`${ service.key }_issuer`),
secret: {
privateKey: RocketChat.settings.get(service.key + '_private_key'),
publicCert: RocketChat.settings.get(service.key + '_public_cert'),
cert: RocketChat.settings.get(service.key + '_cert')
privateKey: RocketChat.settings.get(`${ service.key }_private_key`),
publicCert: RocketChat.settings.get(`${ service.key }_public_cert`),
cert: RocketChat.settings.get(`${ service.key }_cert`)
}
};
};

@ -39,7 +39,7 @@ Meteor.methods({
const providerConfig = getSamlProviderConfig(provider);
if (Accounts.saml.settings.debug) {
console.log('Logout request from ' + JSON.stringify(providerConfig));
console.log(`Logout request from ${ JSON.stringify(providerConfig) }`);
}
// This query should respect upcoming array of SAML logins
const user = Meteor.users.findOne({
@ -52,7 +52,7 @@ Meteor.methods({
const sessionIndex = user.services.saml.idpSession;
nameID = sessionIndex;
if (Accounts.saml.settings.debug) {
console.log('NameID for user ' + Meteor.userId() + ' found: ' + JSON.stringify(nameID));
console.log(`NameID for user ${ Meteor.userId() } found: ${ JSON.stringify(nameID) }`);
}
const _saml = new SAML(providerConfig);
@ -76,7 +76,7 @@ Meteor.methods({
const _syncRequestToUrl = Meteor.wrapAsync(_saml.requestToUrl, _saml);
const result = _syncRequestToUrl(request.request, 'logout');
if (Accounts.saml.settings.debug) {
console.log('SAML Logout Request ' + result);
console.log(`SAML Logout Request ${ result }`);
}
@ -91,7 +91,7 @@ Accounts.registerLoginHandler(function(loginRequest) {
const loginResult = Accounts.saml.retrieveCredential(loginRequest.credentialToken);
if (Accounts.saml.settings.debug) {
console.log('RESULT :' + JSON.stringify(loginResult));
console.log(`RESULT :${ JSON.stringify(loginResult) }`);
}
if (loginResult === undefined) {
@ -186,7 +186,7 @@ const closePopup = function(res, err) {
});
let content = '<html><head><script>window.close()</script></head><body><H1>Verified</H1></body></html>';
if (err) {
content = '<html><body><h2>Sorry, an annoying error occured</h2><div>' + err + '</div><a onclick="window.close();">Close Window</a></body></html>';
content = `<html><body><h2>Sorry, an annoying error occured</h2><div>${ err }</div><a onclick="window.close();">Close Window</a></body></html>`;
}
res.end(content, 'utf-8');
};
@ -239,13 +239,13 @@ const middleware = function(req, res, next) {
// Skip everything if there's no service set by the saml middleware
if (!service) {
throw new Error('Unexpected SAML service ' + samlObject.serviceName);
throw new Error(`Unexpected SAML service ${ samlObject.serviceName }`);
}
let _saml;
switch (samlObject.actionName) {
case 'metadata':
_saml = new SAML(service);
service.callbackUrl = Meteor.absoluteUrl('_saml/validate/' + service.provider);
service.callbackUrl = Meteor.absoluteUrl(`_saml/validate/${ service.provider }`);
res.writeHead(200);
res.write(_saml.generateServiceProviderMetadata(service.callbackUrl));
res.end();
@ -258,14 +258,14 @@ const middleware = function(req, res, next) {
if (!err) {
const logOutUser = function(inResponseTo) {
if (Accounts.saml.settings.debug) {
console.log('Logging Out user via inResponseTo ' + inResponseTo);
console.log(`Logging Out user via inResponseTo ${ inResponseTo }`);
}
const loggedOutUser = Meteor.users.find({
'services.saml.inResponseTo': inResponseTo
}).fetch();
if (loggedOutUser.length === 1) {
if (Accounts.saml.settings.debug) {
console.log('Found user ' + loggedOutUser[0]._id);
console.log(`Found user ${ loggedOutUser[0]._id }`);
}
Meteor.users.update({
_id: loggedOutUser[0]._id
@ -309,7 +309,7 @@ const middleware = function(req, res, next) {
res.end();
break;
case 'authorize':
service.callbackUrl = Meteor.absoluteUrl('_saml/validate/' + service.provider);
service.callbackUrl = Meteor.absoluteUrl(`_saml/validate/${ service.provider }`);
service.id = samlObject.credentialToken;
_saml = new SAML(service);
_saml.getAuthorizeUrl(req, function(err, url) {
@ -327,7 +327,7 @@ const middleware = function(req, res, next) {
Accounts.saml.RelayState = req.body.RelayState;
_saml.validateResponse(req.body.SAMLResponse, req.body.RelayState, function(err, profile/*, loggedOut*/) {
if (err) {
throw new Error('Unable to validate response url: ' + err);
throw new Error(`Unable to validate response url: ${ err }`);
}
const credentialToken = profile.inResponseToId || profile.InResponseTo || samlObject.credentialToken;
@ -337,7 +337,7 @@ const middleware = function(req, res, next) {
Accounts.saml._loginResultForCredentialToken[saml_idp_credentialToken] = {
profile
};
const url = Meteor.absoluteUrl('home') + '?saml_idp_credentialToken='+saml_idp_credentialToken;
const url = `${ Meteor.absoluteUrl('home') }?saml_idp_credentialToken=${ saml_idp_credentialToken }`;
res.writeHead(302, {
'Location': url
});
@ -351,7 +351,7 @@ const middleware = function(req, res, next) {
});
break;
default:
throw new Error('Unexpected SAML action ' + samlObject.actionName);
throw new Error(`Unexpected SAML action ${ samlObject.actionName }`);
}
} catch (err) {

@ -67,7 +67,7 @@ SAML.prototype.signRequest = function(xml) {
};
SAML.prototype.generateAuthorizeRequest = function(req) {
let id = '_' + this.generateUniqueID();
let id = `_${ this.generateUniqueID() }`;
const instant = this.generateInstant();
// Post-auth destination
@ -83,14 +83,14 @@ SAML.prototype.generateAuthorizeRequest = function(req) {
}
let request =
'<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="' + id + '" Version="2.0" IssueInstant="' + instant +
'" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="' + callbackUrl + '" Destination="' +
this.options.entryPoint + '">' +
'<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">' + this.options.issuer + '</saml:Issuer>\n';
`<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="${ id }" Version="2.0" IssueInstant="${ instant
}" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="${ callbackUrl }" Destination="${
this.options.entryPoint }">` +
`<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${ this.options.issuer }</saml:Issuer>\n`;
if (this.options.identifierFormat) {
request += '<samlp:NameIDPolicy xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Format="' + this.options.identifierFormat +
'" AllowCreate="true"></samlp:NameIDPolicy>\n';
request += `<samlp:NameIDPolicy xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Format="${ this.options.identifierFormat
}" AllowCreate="true"></samlp:NameIDPolicy>\n`;
}
request +=
@ -107,29 +107,29 @@ SAML.prototype.generateLogoutRequest = function(options) {
// sessionIndex: sessionIndex
// --- NO SAMLsettings: <Meteor.setting.saml entry for the provider you want to SLO from
const id = '_' + this.generateUniqueID();
const id = `_${ this.generateUniqueID() }`;
const instant = this.generateInstant();
let request = '<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' +
'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="' + id + '" Version="2.0" IssueInstant="' + instant +
'" Destination="' + this.options.idpSLORedirectURL + '">' +
'<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">' + this.options.issuer + '</saml:Issuer>' +
'<saml:NameID Format="' + this.options.identifierFormat + '">' + options.nameID + '</saml:NameID>' +
let request = `${ '<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' +
'xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="' }${ id }" Version="2.0" IssueInstant="${ instant
}" Destination="${ this.options.idpSLORedirectURL }">` +
`<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${ this.options.issuer }</saml:Issuer>` +
`<saml:NameID Format="${ this.options.identifierFormat }">${ options.nameID }</saml:NameID>` +
'</samlp:LogoutRequest>';
request = '<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' +
'ID="' + id + '" ' +
request = `${ '<samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ' +
'ID="' }${ id }" ` +
'Version="2.0" ' +
'IssueInstant="' + instant + '" ' +
'Destination="' + this.options.idpSLORedirectURL + '" ' +
`IssueInstant="${ instant }" ` +
`Destination="${ this.options.idpSLORedirectURL }" ` +
'>' +
'<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">' + this.options.issuer + '</saml:Issuer>' +
`<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">${ this.options.issuer }</saml:Issuer>` +
'<saml:NameID xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ' +
'NameQualifier="http://id.init8.net:8080/openam" ' +
'SPNameQualifier="' + this.options.issuer + '" ' +
'Format="' + this.options.identifierFormat + '">' +
options.nameID + '</saml:NameID>' +
'<samlp:SessionIndex xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">' + options.sessionIndex + '</samlp:SessionIndex>' +
`SPNameQualifier="${ this.options.issuer }" ` +
`Format="${ this.options.identifierFormat }">${
options.nameID }</saml:NameID>` +
`<samlp:SessionIndex xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">${ options.sessionIndex }</samlp:SessionIndex>` +
'</samlp:LogoutRequest>';
if (Meteor.settings.debug) {
console.log('------- SAML Logout request -----------');
@ -185,7 +185,7 @@ SAML.prototype.requestToUrl = function(request, operation, callback) {
target += querystring.stringify(samlRequest);
if (Meteor.settings.debug) {
console.log('requestToUrl: ' + target);
console.log(`requestToUrl: ${ target }`);
}
if (operation === 'logout') {
// in case of logout we want to be redirected back to the Meteor app.
@ -211,8 +211,8 @@ SAML.prototype.getLogoutUrl = function(req, callback) {
SAML.prototype.certToPEM = function(cert) {
cert = cert.match(/.{1,64}/g).join('\n');
cert = '-----BEGIN CERTIFICATE-----\n' + cert;
cert = cert + '\n-----END CERTIFICATE-----\n';
cert = `-----BEGIN CERTIFICATE-----\n${ cert }`;
cert = `${ cert }\n-----END CERTIFICATE-----\n`;
return cert;
};
@ -250,14 +250,14 @@ SAML.prototype.validateSignature = function(xml, cert) {
};
SAML.prototype.getElement = function(parentElement, elementName) {
if (parentElement['saml:' + elementName]) {
return parentElement['saml:' + elementName];
} else if (parentElement['samlp:' + elementName]) {
return parentElement['samlp:' + elementName];
} else if (parentElement['saml2p:' + elementName]) {
return parentElement['saml2p:' + elementName];
} else if (parentElement['saml2:' + elementName]) {
return parentElement['saml2:' + elementName];
if (parentElement[`saml:${ elementName }`]) {
return parentElement[`saml:${ elementName }`];
} else if (parentElement[`samlp:${ elementName }`]) {
return parentElement[`samlp:${ elementName }`];
} else if (parentElement[`saml2p:${ elementName }`]) {
return parentElement[`saml2p:${ elementName }`];
} else if (parentElement[`saml2:${ elementName }`]) {
return parentElement[`saml2:${ elementName }`];
}
return parentElement[elementName];
};
@ -283,12 +283,12 @@ SAML.prototype.validateLogoutResponse = function(samlResponse, callback) {
// TBD. Check if this msg corresponds to one we sent
const inResponseTo = response.$.InResponseTo;
if (Meteor.settings.debug) {
console.log('In Response to: ' + inResponseTo);
console.log(`In Response to: ${ inResponseTo }`);
}
const status = self.getElement(response, 'Status');
const statusCode = self.getElement(status[0], 'StatusCode')[0].$.Value;
if (Meteor.settings.debug) {
console.log('StatusCode: ' + JSON.stringify(statusCode));
console.log(`StatusCode: ${ JSON.stringify(statusCode) }`);
}
if (statusCode === 'urn:oasis:names:tc:SAML:2.0:status:Success') {
// In case of a successful logout at IDP we return inResponseTo value.
@ -311,7 +311,7 @@ SAML.prototype.validateResponse = function(samlResponse, relayState, callback) {
const xml = new Buffer(samlResponse, 'base64').toString('utf8');
// We currently use RelayState to save SAML provider
if (Meteor.settings.debug) {
console.log('Validating response with relay state: ' + xml);
console.log(`Validating response with relay state: ${ xml }`);
}
const parser = new xml2js.Parser({
explicitRoot: true
@ -372,7 +372,7 @@ SAML.prototype.validateResponse = function(samlResponse, relayState, callback) {
profile.sessionIndex = authnStatement[0].$.SessionIndex;
if (Meteor.settings.debug) {
console.log('Session Index: ' + profile.sessionIndex);
console.log(`Session Index: ${ profile.sessionIndex }`);
}
} else if (Meteor.settings.debug) {
console.log('No Session Index Found');
@ -412,7 +412,7 @@ SAML.prototype.validateResponse = function(samlResponse, relayState, callback) {
profile.email = profile.nameID;
}
if (Meteor.settings.debug) {
console.log('NameID: ' + JSON.stringify(profile));
console.log(`NameID: ${ JSON.stringify(profile) }`);
}
callback(null, profile, false);
@ -492,8 +492,8 @@ SAML.prototype.generateServiceProviderMetadata = function(callbackUrl) {
'KeyDescriptor': keyDescriptor,
'SingleLogoutService': {
'@Binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
'@Location': Meteor.absoluteUrl() + '_saml/logout/' + this.options.provider + '/',
'@ResponseLocation': Meteor.absoluteUrl() + '_saml/logout/' + this.options.provider + '/'
'@Location': `${ Meteor.absoluteUrl() }_saml/logout/${ this.options.provider }/`,
'@ResponseLocation': `${ Meteor.absoluteUrl() }_saml/logout/${ this.options.provider }/`
},
'NameIDFormat': this.options.identifierFormat,
'AssertionConsumerService': {

@ -15,7 +15,7 @@ Template.body.onRendered(() => {
window._paq.push(['trackPageView']);
window._paq.push(['enableLinkTracking']);
(() => {
window._paq.push(['setTrackerUrl', piwikUrl + 'piwik.php']);
window._paq.push(['setTrackerUrl', `${ piwikUrl }piwik.php`]);
window._paq.push(['setSiteId', Number.parseInt(piwikSiteId)]);
const d = document;
const g = d.createElement('script');
@ -23,7 +23,7 @@ Template.body.onRendered(() => {
g.type = 'text/javascript';
g.async = true;
g.defer = true;
g.src = piwikUrl + 'piwik.js';
g.src = `${ piwikUrl }piwik.js`;
s.parentNode.insertBefore(g, s);
})();
}

@ -31,44 +31,44 @@ if (!window._paq || window.ga) {
RocketChat.callbacks.add('afterSaveMessage', (message) => {
if ((window._paq || window.ga) && RocketChat.settings.get('Analytics_features_messages')) {
const room = ChatRoom.findOne({ _id: message.rid });
trackEvent('Message', 'Send', room.name + ' (' + room._id + ')');
trackEvent('Message', 'Send', `${ room.name } (${ room._id })`);
}
}, 2000, 'trackEvents');
//Rooms
RocketChat.callbacks.add('afterCreateChannel', (owner, room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Create', room.name + ' (' + room._id + ')');
trackEvent('Room', 'Create', `${ room.name } (${ room._id })`);
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-after-create-channel');
RocketChat.callbacks.add('roomNameChanged', (room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Changed Name', room.name + ' (' + room._id + ')');
trackEvent('Room', 'Changed Name', `${ room.name } (${ room._id })`);
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-name-changed');
RocketChat.callbacks.add('roomTopicChanged', (room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Changed Topic', room.name + ' (' + room._id + ')');
trackEvent('Room', 'Changed Topic', `${ room.name } (${ room._id })`);
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-topic-changed');
RocketChat.callbacks.add('roomTypeChanged', (room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Changed Room Type', room.name + ' (' + room._id + ')');
trackEvent('Room', 'Changed Room Type', `${ room.name } (${ room._id })`);
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-room-type-changed');
RocketChat.callbacks.add('archiveRoom', (room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Archived', room.name + ' (' + room._id + ')');
trackEvent('Room', 'Archived', `${ room.name } (${ room._id })`);
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-archive-room');
RocketChat.callbacks.add('unarchiveRoom', (room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Unarchived', room.name + ' (' + room._id + ')');
trackEvent('Room', 'Unarchived', `${ room.name } (${ room._id })`);
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-unarchive-room');

@ -2,7 +2,7 @@
class API extends Restivus {
constructor(properties) {
super(properties);
this.logger = new Logger(`API ${properties.version ? properties.version : 'default'} Logger`, {});
this.logger = new Logger(`API ${ properties.version ? properties.version : 'default' } Logger`, {});
this.authMethods = [];
this.helperMethods = new Map();
this.defaultFieldsToExclude = {
@ -99,12 +99,12 @@ class API extends Restivus {
//Add a try/catch for each much
const originalAction = endpoints[method].action;
endpoints[method].action = function() {
this.logger.debug(`${this.request.method.toUpperCase()}: ${this.request.url}`);
this.logger.debug(`${ this.request.method.toUpperCase() }: ${ this.request.url }`);
let result;
try {
result = originalAction.apply(this);
} catch (e) {
this.logger.debug(`${method} ${route} threw an error:`, e);
this.logger.debug(`${ method } ${ route } threw an error:`, e);
return RocketChat.API.v1.failure(e.message, e.error);
}

@ -7,11 +7,11 @@ function findChannelById({ roomId, checkedArchived = true }) {
const room = RocketChat.models.Rooms.findOneById(roomId, { fields: RocketChat.API.v1.defaultFieldsToExclude });
if (!room || room.t !== 'c') {
throw new Meteor.Error('error-room-not-found', `No channel found by the id of: ${roomId}`);
throw new Meteor.Error('error-room-not-found', `No channel found by the id of: ${ roomId }`);
}
if (checkedArchived && room.archived) {
throw new Meteor.Error('error-room-archived', `The channel, ${room.name}, is archived`);
throw new Meteor.Error('error-room-archived', `The channel, ${ room.name }, is archived`);
}
return room;
@ -106,11 +106,11 @@ RocketChat.API.v1.addRoute('channels.close', { authRequired: true }, {
const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId);
if (!sub) {
return RocketChat.API.v1.failure(`The user/callee is not in the channel "${findResult.name}.`);
return RocketChat.API.v1.failure(`The user/callee is not in the channel "${ findResult.name }.`);
}
if (!sub.open) {
return RocketChat.API.v1.failure(`The channel, ${findResult.name}, is already closed to the sender`);
return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is already closed to the sender`);
}
Meteor.runAsUser(this.userId, () => {
@ -185,7 +185,7 @@ RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, {
}
let ourQuery = {
channel: `#${findResult.name}`
channel: `#${ findResult.name }`
};
if (includeAllPublicChannels) {
@ -414,11 +414,11 @@ RocketChat.API.v1.addRoute('channels.open', { authRequired: true }, {
const sub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId);
if (!sub) {
return RocketChat.API.v1.failure(`The user/callee is not in the channel "${findResult.name}".`);
return RocketChat.API.v1.failure(`The user/callee is not in the channel "${ findResult.name }".`);
}
if (sub.open) {
return RocketChat.API.v1.failure(`The channel, ${findResult.name}, is already open to the sender`);
return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is already open to the sender`);
}
Meteor.runAsUser(this.userId, () => {
@ -612,7 +612,7 @@ RocketChat.API.v1.addRoute('channels.unarchive', { authRequired: true }, {
const findResult = findChannelById({ roomId: this.bodyParams.roomId, checkedArchived: false });
if (!findResult.archived) {
return RocketChat.API.v1.failure(`The channel, ${findResult.name}, is not archived`);
return RocketChat.API.v1.failure(`The channel, ${ findResult.name }, is not archived`);
}
Meteor.runAsUser(this.userId, () => {

@ -10,7 +10,7 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, {
const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 }});
if (!msg) {
return RocketChat.API.v1.failure(`No message found with the id of "${this.bodyParams.msgId}".`);
return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`);
}
if (this.bodyParams.roomId !== msg.rid) {
@ -56,7 +56,7 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, {
//Ensure the message exists
if (!msg) {
return RocketChat.API.v1.failure(`No message found with the id of "${this.bodyParams.msgId}".`);
return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`);
}
if (this.bodyParams.roomId !== msg.rid) {

@ -12,11 +12,11 @@ function findPrivateGroupByIdOrName({ roomId, roomName, userId, checkedArchived
}
if (!roomSub || roomSub.t !== 'p') {
throw new Meteor.Error('error-room-not-found', `No private group by the id of: ${roomId}`);
throw new Meteor.Error('error-room-not-found', `No private group by the id of: ${ roomId }`);
}
if (checkedArchived && roomSub.archived) {
throw new Meteor.Error('error-room-archived', `The private group, ${roomSub.name}, is archived`);
throw new Meteor.Error('error-room-archived', `The private group, ${ roomSub.name }, is archived`);
}
return roomSub;
@ -68,7 +68,7 @@ RocketChat.API.v1.addRoute('groups.close', { authRequired: true }, {
const findResult = findPrivateGroupByIdOrName({ roomId: this.bodyParams.roomId, userId: this.userId, checkedArchived: false });
if (!findResult.open) {
return RocketChat.API.v1.failure(`The private group with an id "${this.bodyParams.roomId}" is already closed to the sender`);
return RocketChat.API.v1.failure(`The private group with an id "${ this.bodyParams.roomId }" is already closed to the sender`);
}
Meteor.runAsUser(this.userId, () => {
@ -141,7 +141,7 @@ RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, {
includeAllPrivateGroups = this.queryParams.includeAllPrivateGroups === 'true';
}
const channelsToSearch = [`#${findResult.name}`];
const channelsToSearch = [`#${ findResult.name }`];
if (includeAllPrivateGroups) {
channelsToSearch.push('all_private_groups');
}
@ -320,7 +320,7 @@ RocketChat.API.v1.addRoute('groups.open', { authRequired: true }, {
const findResult = findPrivateGroupByIdOrName({ roomId: this.bodyParams.roomId, userId: this.userId, checkedArchived: false });
if (findResult.open) {
return RocketChat.API.v1.failure(`The private group, ${this.bodyParams.name}, is already open for the sender`);
return RocketChat.API.v1.failure(`The private group, ${ this.bodyParams.name }, is already open for the sender`);
}
Meteor.runAsUser(this.userId, () => {

@ -4,8 +4,8 @@ RocketChat.API.v1.helperMethods.set('parseJsonQuery', function _parseJsonQuery()
try {
sort = JSON.parse(this.queryParams.sort);
} catch (e) {
this.logger.warn(`Invalid sort parameter provided "${this.queryParams.sort}":`, e);
throw new Meteor.Error('error-invalid-sort', `Invalid sort parameter provided: "${this.queryParams.sort}"`, { helperMethod: 'parseJsonQuery' });
this.logger.warn(`Invalid sort parameter provided "${ this.queryParams.sort }":`, e);
throw new Meteor.Error('error-invalid-sort', `Invalid sort parameter provided: "${ this.queryParams.sort }"`, { helperMethod: 'parseJsonQuery' });
}
}
@ -14,8 +14,8 @@ RocketChat.API.v1.helperMethods.set('parseJsonQuery', function _parseJsonQuery()
try {
fields = JSON.parse(this.queryParams.fields);
} catch (e) {
this.logger.warn(`Invalid fields parameter provided "${this.queryParams.fields}":`, e);
throw new Meteor.Error('error-invalid-fields', `Invalid fields parameter provided: "${this.queryParams.fields}"`, { helperMethod: 'parseJsonQuery' });
this.logger.warn(`Invalid fields parameter provided "${ this.queryParams.fields }":`, e);
throw new Meteor.Error('error-invalid-fields', `Invalid fields parameter provided: "${ this.queryParams.fields }"`, { helperMethod: 'parseJsonQuery' });
}
}
@ -24,8 +24,8 @@ RocketChat.API.v1.helperMethods.set('parseJsonQuery', function _parseJsonQuery()
try {
query = JSON.parse(this.queryParams.query);
} catch (e) {
this.logger.warn(`Invalid query parameter provided "${this.queryParams.query}":`, e);
throw new Meteor.Error('error-invalid-query', `Invalid query parameter provided: "${this.queryParams.query}"`, { helperMethod: 'parseJsonQuery' });
this.logger.warn(`Invalid query parameter provided "${ this.queryParams.query }":`, e);
throw new Meteor.Error('error-invalid-query', `Invalid query parameter provided: "${ this.queryParams.query }"`, { helperMethod: 'parseJsonQuery' });
}
}

@ -6,7 +6,7 @@ function findDirectMessageRoomById(roomId, userId) {
const roomSub = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, userId);
if (!roomSub || roomSub.t !== 'd') {
return RocketChat.API.v1.failure(`No direct message room found by the id of: ${roomId}`);
return RocketChat.API.v1.failure(`No direct message room found by the id of: ${ roomId }`);
}
return roomSub;
@ -22,7 +22,7 @@ RocketChat.API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, {
}
if (!findResult.open) {
return RocketChat.API.v1.failure(`The direct message room, ${this.bodyParams.name}, is already closed to the sender`);
return RocketChat.API.v1.failure(`The direct message room, ${ this.bodyParams.name }, is already closed to the sender`);
}
Meteor.runAsUser(this.userId, () => {
@ -95,7 +95,7 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR
const room = RocketChat.models.Rooms.findOneById(roomId);
if (!room || room.t !== 'd') {
throw new Meteor.Error('error-room-not-found', `No direct message room found by the id of: ${roomId}`);
throw new Meteor.Error('error-room-not-found', `No direct message room found by the id of: ${ roomId }`);
}
const { offset, count } = this.getPaginationItems();
@ -178,7 +178,7 @@ RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, {
}
if (findResult.open) {
return RocketChat.API.v1.failure(`The direct message room, ${this.bodyParams.name}, is already open for the sender`);
return RocketChat.API.v1.failure(`The direct message room, ${ this.bodyParams.name }, is already open for the sender`);
}
Meteor.runAsUser(this.userId, () => {

@ -55,7 +55,7 @@ RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, {
get() {
const user = this.getUserFromParams();
const url = RocketChat.getURL(`/avatar/${user.username}`, { cdn: false, full: true });
const url = RocketChat.getURL(`/avatar/${ user.username }`, { cdn: false, full: true });
this.response.setHeader('Location', url);
return {
@ -95,7 +95,7 @@ RocketChat.API.v1.addRoute('users.info', { authRequired: true }, {
});
if (!result || result.length !== 1) {
return RocketChat.API.v1.failure(`Failed to get the user data for the userId of "${user._id}".`);
return RocketChat.API.v1.failure(`Failed to get the user data for the userId of "${ user._id }".`);
}
return RocketChat.API.v1.success({

@ -173,7 +173,7 @@ RocketChat.Assets = new (class {
const extension = mime.extension(contentType);
if (assets[asset].constraints.extensions.includes(extension) === false) {
throw new Meteor.Error(contentType, `Invalid file type: ${contentType}`, {
throw new Meteor.Error(contentType, `Invalid file type: ${ contentType }`, {
function: 'RocketChat.Assets.setAsset',
errorTitle: 'error-invalid-file-type'
});
@ -198,9 +198,9 @@ RocketChat.Assets = new (class {
const ws = RocketChatAssetsInstance.createWriteStream(asset, contentType);
ws.on('end', Meteor.bindEnvironment(function() {
return Meteor.setTimeout(function() {
const key = `Assets_${asset}`;
const key = `Assets_${ asset }`;
const value = {
url: `assets/${asset}.${extension}`,
url: `assets/${ asset }.${ extension }`,
defaultUrl: assets[asset].defaultUrl
};
@ -220,7 +220,7 @@ RocketChat.Assets = new (class {
}
RocketChatAssetsInstance.deleteFile(asset);
const key = `Assets_${asset}`;
const key = `Assets_${ asset }`;
const value = {
defaultUrl: assets[asset].defaultUrl
};
@ -262,14 +262,14 @@ RocketChat.Assets = new (class {
const extension = settingValue.url.split('.').pop();
return assetValue.cache = {
path: `assets/${assetKey}.${extension}`,
path: `assets/${ assetKey }.${ extension }`,
cacheable: false,
sourceMapUrl: undefined,
where: 'client',
type: 'asset',
content: file.buffer,
extension,
url: `/assets/${assetKey}.${extension}?${hash}`,
url: `/assets/${ assetKey }.${ extension }?${ hash }`,
size: file.length,
uploadDate: file.uploadDate,
contentType: file.contentType,
@ -287,7 +287,7 @@ RocketChat.settings.add('Assets_SvgFavicon_Enable', true, {
});
function addAssetToSetting(key, value) {
return RocketChat.settings.add(`Assets_${key}`, {
return RocketChat.settings.add(`Assets_${ key }`, {
defaultUrl: value.defaultUrl
}, {
type: 'asset',
@ -347,22 +347,22 @@ WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeCon
size: value.cache.size,
hash: value.cache.hash
};
WebAppInternals.staticFiles[`/__cordova/assets/${key}`] = value.cache;
WebAppInternals.staticFiles[`/__cordova/assets/${key}.${value.cache.extension}`] = value.cache;
WebAppInternals.staticFiles[`/__cordova/assets/${ key }`] = value.cache;
WebAppInternals.staticFiles[`/__cordova/assets/${ key }.${ value.cache.extension }`] = value.cache;
} else {
const extension = value.defaultUrl.split('.').pop();
cache = {
path: `assets/${key}.${extension}`,
path: `assets/${ key }.${ extension }`,
cacheable: false,
sourceMapUrl: undefined,
where: 'client',
type: 'asset',
url: `/assets/${key}.${extension}?v3`,
url: `/assets/${ key }.${ extension }?v3`,
hash: 'v3'
};
WebAppInternals.staticFiles[`/__cordova/assets/${key}`] = WebAppInternals.staticFiles[`/__cordova/${value.defaultUrl}`];
WebAppInternals.staticFiles[`/__cordova/assets/${key}.${extension}`] = WebAppInternals.staticFiles[`/__cordova/${value.defaultUrl}`];
WebAppInternals.staticFiles[`/__cordova/assets/${ key }`] = WebAppInternals.staticFiles[`/__cordova/${ value.defaultUrl }`];
WebAppInternals.staticFiles[`/__cordova/assets/${ key }.${ extension }`] = WebAppInternals.staticFiles[`/__cordova/${ value.defaultUrl }`];
}
const manifestItem = _.findWhere(manifest, {
@ -445,7 +445,7 @@ WebApp.connectHandlers.use('/assets/', Meteor.bindEnvironment(function(req, res,
if (!file) {
if (assets[params.asset] && assets[params.asset].defaultUrl) {
req.url = `/${assets[params.asset].defaultUrl}`;
req.url = `/${ assets[params.asset].defaultUrl }`;
WebAppInternals.staticFilesMiddleware(WebAppInternals.staticFiles, req, res, next);
} else {
res.writeHead(404);

@ -80,7 +80,7 @@ Template.autoTranslateFlexTab.onCreated(function() {
case 'autoTranslate':
return true;
case 'autoTranslateLanguage':
value = this.$('select[name='+ field +']').val();
value = this.$(`select[name=${ field }]`).val();
if (!_.findWhere(this.supportedLanguages.get(), { language: value })) {
toastr.error(t('Invalid_setting_s', value || ''));
return false;
@ -96,10 +96,10 @@ Template.autoTranslateFlexTab.onCreated(function() {
let value;
switch (field) {
case 'autoTranslate':
value = this.$('input[name='+field+']').prop('checked') ? '1' : '0';
value = this.$(`input[name=${ field }]`).prop('checked') ? '1' : '0';
break;
case 'autoTranslateLanguage':
value = this.$('select[name='+ field +']').val();
value = this.$(`select[name=${ field }]`).val();
break;
}
@ -111,9 +111,9 @@ Template.autoTranslateFlexTab.onCreated(function() {
const query = { rid: this.data.rid, 'u._id': { $ne: Meteor.userId() } };
if (field === 'autoTranslateLanguage') {
query.$or = [ { [`translations.${previousLanguage}`]: { $exists: 1 } }, { [`translations.${value}`]: { $exists: 1 } }, { [`attachments.translations.${previousLanguage}`]: { $exists: 1 } }, { [`attachments.translations.${value}`]: { $exists: 1 } } ];
query.$or = [ { [`translations.${ previousLanguage }`]: { $exists: 1 } }, { [`translations.${ value }`]: { $exists: 1 } }, { [`attachments.translations.${ previousLanguage }`]: { $exists: 1 } }, { [`attachments.translations.${ value }`]: { $exists: 1 } } ];
} else {
query.$or = [ { [`translations.${subscription.autoTranslateLanguage}`]: { $exists: 1 } }, { [`attachments.translations.${subscription.autoTranslateLanguage}`]: { $exists: 1 } } ];
query.$or = [ { [`translations.${ subscription.autoTranslateLanguage }`]: { $exists: 1 } }, { [`attachments.translations.${ subscription.autoTranslateLanguage }`]: { $exists: 1 } } ];
}
if (field === 'autoTranslate' && value === '0') {

@ -28,7 +28,7 @@ class AutoTranslate {
}
let count = message.tokens.length;
message.msg = message.msg.replace(/:[+\w\d]+:/g, function(match) {
const token = `<i class=notranslate>{${count++}}</i>`;
const token = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token,
text: match
@ -48,14 +48,14 @@ class AutoTranslate {
const schemes = RocketChat.settings.get('Markdown_SupportSchemesForLink').split(',').join('|');
// Support ![alt text](http://image url) and [text](http://link)
message.msg = message.msg.replace(new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${schemes}):\\/\\/[^\\)]+\\))`, 'gm'), function(match, pre, text, post) {
const pretoken = `<i class=notranslate>{${count++}}</i>`;
message.msg = message.msg.replace(new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${ schemes }):\\/\\/[^\\)]+\\))`, 'gm'), function(match, pre, text, post) {
const pretoken = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token: pretoken,
text: pre
});
const posttoken = `<i class=notranslate>{${count++}}</i>`;
const posttoken = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token: posttoken,
text: post
@ -65,14 +65,14 @@ class AutoTranslate {
});
// Support <http://link|Text>
message.msg = message.msg.replace(new RegExp(`((?:<|&lt;)(?:${schemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;))`, 'gm'), function(match, pre, text, post) {
const pretoken = `<i class=notranslate>{${count++}}</i>`;
message.msg = message.msg.replace(new RegExp(`((?:<|&lt;)(?:${ schemes }):\\/\\/[^\\|]+\\|)(.+?)(?=>|&gt;)((?:>|&gt;))`, 'gm'), function(match, pre, text, post) {
const pretoken = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token: pretoken,
text: pre
});
const posttoken = `<i class=notranslate>{${count++}}</i>`;
const posttoken = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token: posttoken,
text: post
@ -99,7 +99,7 @@ class AutoTranslate {
if (message.tokens.hasOwnProperty(tokenIndex)) {
const token = message.tokens[tokenIndex].token;
if (token.indexOf('notranslate') === -1) {
const newToken = `<i class=notranslate>{${count++}}</i>`;
const newToken = `<i class=notranslate>{${ count++ }}</i>`;
message.msg = message.msg.replace(token, newToken);
message.tokens[tokenIndex].token = newToken;
}
@ -117,8 +117,8 @@ class AutoTranslate {
if (message.mentions && message.mentions.length > 0) {
message.mentions.forEach(mention => {
message.msg = message.msg.replace(new RegExp(`(@${mention.username})`, 'gm'), match => {
const token = `<i class=notranslate>{${count++}}</i>`;
message.msg = message.msg.replace(new RegExp(`(@${ mention.username })`, 'gm'), match => {
const token = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token,
text: match
@ -130,8 +130,8 @@ class AutoTranslate {
if (message.channels && message.channels.length > 0) {
message.channels.forEach(channel => {
message.msg = message.msg.replace(new RegExp(`(#${channel.name})`, 'gm'), match => {
const token = `<i class=notranslate>{${count++}}</i>`;
message.msg = message.msg.replace(new RegExp(`(#${ channel.name })`, 'gm'), match => {
const token = `<i class=notranslate>{${ count++ }}</i>`;
message.tokens.push({
token,
text: match
@ -171,7 +171,7 @@ class AutoTranslate {
let msgs = targetMessage.msg.split('\n');
msgs = msgs.map(msg => encodeURIComponent(msg));
const query = `q=${msgs.join('&q=')}`;
const query = `q=${ msgs.join('&q=') }`;
const supportedLanguages = this.getSupportedLanguages('en');
targetLanguages.forEach(language => {
@ -203,7 +203,7 @@ class AutoTranslate {
const attachment = message.attachments[index];
const translations = {};
if (attachment.description || attachment.text) {
const query = `q=${encodeURIComponent(attachment.description || attachment.text)}`;
const query = `q=${ encodeURIComponent(attachment.description || attachment.text) }`;
const supportedLanguages = this.getSupportedLanguages('en');
targetLanguages.forEach(language => {
if (language.indexOf('-') !== -1 && !_.findWhere(supportedLanguages, { language })) {

@ -2,7 +2,7 @@ RocketChat.models.Messages.addTranslations = function(messageId, translations) {
const updateObj = {};
Object.keys(translations).forEach((key) => {
const translation = translations[key];
updateObj[`translations.${key}`] = translation;
updateObj[`translations.${ key }`] = translation;
});
return this.update({ _id: messageId }, { $set: updateObj });
};
@ -11,7 +11,7 @@ RocketChat.models.Messages.addAttachmentTranslations = function(messageId, attac
const updateObj = {};
Object.keys(translations).forEach((key) => {
const translation = translations[key];
updateObj[`attachments.${attachmentIndex}.translations.${key}`] = translation;
updateObj[`attachments.${ attachmentIndex }.translations.${ key }`] = translation;
});
return this.update({ _id: messageId }, { $set: updateObj });
};

@ -10,7 +10,7 @@ const openCenteredPopup = function(url, width, height) {
// positioning the popup centered relative to the current window
const left = screenX + (outerWidth - width) / 2;
const top = screenY + (outerHeight - height) / 2;
const features = ('width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=yes');
const features = (`width=${ width },height=${ height },left=${ left },top=${ top },scrollbars=yes`);
const newwindow = window.open(url, 'Login', features);
if (newwindow.focus) {
@ -33,7 +33,7 @@ Meteor.loginWithCas = function(options, callback) {
}
const appUrl = Meteor.absoluteUrl().replace(/\/$/, '') + __meteor_runtime_config__.ROOT_URL_PATH_PREFIX;
const loginUrl = login_url + '?service=' + appUrl + '/_cas/' + credentialToken;
const loginUrl = `${ login_url }?service=${ appUrl }/_cas/${ credentialToken }`;
const popup = openCenteredPopup(
loginUrl,

@ -29,19 +29,19 @@ const casTicket = function(req, token, callback) {
const baseUrl = RocketChat.settings.get('CAS_base_url');
const cas_version = parseFloat(RocketChat.settings.get('CAS_version'));
const appUrl = Meteor.absoluteUrl().replace(/\/$/, '') + __meteor_runtime_config__.ROOT_URL_PATH_PREFIX;
logger.debug('Using CAS_base_url: ' + baseUrl);
logger.debug(`Using CAS_base_url: ${ baseUrl }`);
const cas = new CAS({
base_url: baseUrl,
version: cas_version,
service: appUrl + '/_cas/' + token
service: `${ appUrl }/_cas/${ token }`
});
cas.validate(ticketId, function(err, status, username, details) {
if (err) {
logger.error('error when trying to validate: ' + err.message);
logger.error(`error when trying to validate: ${ err.message }`);
} else if (status) {
logger.info('Validated user: ' + username);
logger.info(`Validated user: ${ username }`);
const user_info = { username };
// CAS 2.0 attributes handling
@ -50,7 +50,7 @@ const casTicket = function(req, token, callback) {
}
_casCredentialTokens[token] = user_info;
} else {
logger.error('Unable to validate ticket: ' + ticketId);
logger.error(`Unable to validate ticket: ${ ticketId }`);
}
//logger.debug("Receveied response: " + JSON.stringify(details, null , 4));
@ -87,7 +87,7 @@ const middleware = function(req, res, next) {
});
} catch (err) {
logger.error('Unexpected error : ' + err.message);
logger.error(`Unexpected error : ${ err.message }`);
closePopup(res);
}
};
@ -169,21 +169,21 @@ Accounts.registerLoginHandler(function(options) {
// Source is our String to interpolate
if (_.isString(source)) {
_.each(ext_attrs, function(value, ext_name) {
source = source.replace('%' + ext_name + '%', ext_attrs[ext_name]);
source = source.replace(`%${ ext_name }%`, ext_attrs[ext_name]);
});
int_attrs[int_name] = source;
logger.debug('Sourced internal attribute: ' + int_name + ' = ' + source);
logger.debug(`Sourced internal attribute: ${ int_name } = ${ source }`);
}
});
}
// Search existing user by its external service id
logger.debug('Looking up user by id: ' + result.username);
logger.debug(`Looking up user by id: ${ result.username }`);
let user = Meteor.users.findOne({ 'services.cas.external_id': result.username });
if (user) {
logger.debug('Using existing user for \'' + result.username + '\' with id: ' + user._id);
logger.debug(`Using existing user for '${ result.username }' with id: ${ user._id }`);
if (sync_enabled) {
logger.debug('Syncing user attributes');
// Update name
@ -228,15 +228,15 @@ Accounts.registerLoginHandler(function(options) {
}
// Create the user
logger.debug('User "' + result.username + '" does not exist yet, creating it');
logger.debug(`User "${ result.username }" does not exist yet, creating it`);
const userId = Accounts.insertUserDoc({}, newUser);
// Fetch and use it
user = Meteor.users.findOne(userId);
logger.debug('Created new user for \'' + result.username + '\' with id: ' + user._id);
logger.debug(`Created new user for '${ result.username }' with id: ${ user._id }`);
//logger.debug(JSON.stringify(user, undefined, 4));
logger.debug('Joining user to attribute channels: ' + int_attrs.rooms);
logger.debug(`Joining user to attribute channels: ${ int_attrs.rooms }`);
if (int_attrs.rooms) {
_.each(int_attrs.rooms.split(','), function(room_name) {
if (room_name) {

@ -8,7 +8,7 @@ function HexColorPreview(message) {
if (_.trim(message.html) && RocketChat.settings.get('HexColorPreview_Enabled')) {
msg = message.html;
msg = msg.replace(/(?:^|\s|\n)(#[A-Fa-f0-9]{3}([A-Fa-f0-9]{3})?)\b/g, function(match, completeColor) {
return match.replace(completeColor, '<div class="message-color"><div class="message-color-sample" style="background-color:' + completeColor + '"></div>' + (completeColor.toUpperCase()) + '</div>');
return match.replace(completeColor, `<div class="message-color"><div class="message-color-sample" style="background-color:${ completeColor }"></div>${ completeColor.toUpperCase() }</div>`);
});
message.html = msg;
}

@ -97,7 +97,7 @@ WebApp.httpServer.addListener('request', function(req, res) {
let host = req.headers['host'] || url.parse(Meteor.absoluteUrl()).hostname;
host = host.replace(/:\d+$/, '');
res.writeHead(302, {
'Location': 'https://' + host + req.url
'Location': `https://${ host }${ req.url }`
});
res.end();
return;

@ -46,7 +46,7 @@ export class CustomOAuth {
}
configureLogin() {
const loginWithService = 'loginWith' + s.capitalize(this.name);
const loginWithService = `loginWith${ s.capitalize(this.name) }`;
Meteor[loginWithService] = (options, callback) => {
// support a callback without options
@ -78,12 +78,12 @@ export class CustomOAuth {
const credentialToken = Random.secret();
const loginStyle = OAuth._loginStyle(this.name, config, options);
const loginUrl = this.authorizePath +
'?client_id=' + config.clientId +
'&redirect_uri=' + OAuth._redirectUri(this.name, config) +
'&response_type=code' +
'&state=' + OAuth._stateParam(loginStyle, credentialToken, options.redirectUrl) +
'&scope=' + this.scope;
const loginUrl = `${ this.authorizePath
}?client_id=${ config.clientId
}&redirect_uri=${ OAuth._redirectUri(this.name, config)
}&response_type=code` +
`&state=${ OAuth._stateParam(loginStyle, credentialToken, options.redirectUrl)
}&scope=${ this.scope }`;
OAuth.launchLogin({
loginService: this.name,

@ -25,7 +25,7 @@ export class CustomOAuth {
this.userAgent = 'Meteor';
if (Meteor.release) {
this.userAgent += '/' + Meteor.release;
this.userAgent += `/${ Meteor.release }`;
}
Accounts.oauth.registerService(this.name);
@ -79,7 +79,7 @@ export class CustomOAuth {
let response = undefined;
try {
response = HTTP.post(this.tokenPath, {
auth: config.clientId + ':' + OAuth.openSecret(config.secret),
auth: `${ config.clientId }:${ OAuth.openSecret(config.secret) }`,
headers: {
Accept: 'application/json',
'User-Agent': this.userAgent
@ -94,12 +94,12 @@ export class CustomOAuth {
}
});
} catch (err) {
const error = new Error(`Failed to complete OAuth handshake with ${this.name} at ${this.tokenPath}. ${err.message}`);
const error = new Error(`Failed to complete OAuth handshake with ${ this.name } at ${ this.tokenPath }. ${ err.message }`);
throw _.extend(error, {response: err.response});
}
if (response.data.error) { //if the http response was a json object with an error attribute
throw new Error(`Failed to complete OAuth handshake with ${this.name} at ${this.tokenPath}. ${response.data.error}`);
throw new Error(`Failed to complete OAuth handshake with ${ this.name } at ${ this.tokenPath }. ${ response.data.error }`);
} else {
return response.data.access_token;
}
@ -112,7 +112,7 @@ export class CustomOAuth {
};
if (this.tokenSentVia === 'header') {
headers['Authorization'] = 'Bearer ' + accessToken;
headers['Authorization'] = `Bearer ${ accessToken }`;
} else {
params['access_token'] = accessToken;
}
@ -135,7 +135,7 @@ export class CustomOAuth {
return data;
} catch (err) {
const error = new Error(`Failed to fetch identity from ${this.name} at ${this.identityPath}. ${err.message}`);
const error = new Error(`Failed to fetch identity from ${ this.name } at ${ this.identityPath }. ${ err.message }`);
throw _.extend(error, {response: err.response});
}
}
@ -229,14 +229,14 @@ export class CustomOAuth {
if (this.usernameField.indexOf('#{') > -1) {
username = this.usernameField.replace(/#{(.+?)}/g, function(match, field) {
if (!data[field]) {
throw new Meteor.Error('field_not_found', `Username template item "${field}" not found in data`, data);
throw new Meteor.Error('field_not_found', `Username template item "${ field }" not found in data`, data);
}
return data[field];
});
} else {
username = data[this.usernameField];
if (!username) {
throw new Meteor.Error('field_not_found', `Username field "${this.usernameField}" not found in data`, data);
throw new Meteor.Error('field_not_found', `Username field "${ this.usernameField }" not found in data`, data);
}
}
@ -263,10 +263,10 @@ export class CustomOAuth {
}
if (this.mergeUsers !== true) {
throw new Meteor.Error('CustomOAuth', `User with username ${user.username} already exists`);
throw new Meteor.Error('CustomOAuth', `User with username ${ user.username } already exists`);
}
const serviceIdKey = `services.${serviceName}.id`;
const serviceIdKey = `services.${ serviceName }.id`;
const update = {
$set: {
[serviceIdKey]: serviceData.id

@ -124,7 +124,7 @@ Template.adminSounds.events({
'click .icon-play-circled'(e) {
e.preventDefault();
e.stopPropagation();
const $audio = $('audio#' + this._id);
const $audio = $(`audio#${ this._id }`);
if ($audio && $audio[0] && $audio[0].play) {
$audio[0].play();
}

@ -30,11 +30,11 @@ class CustomSounds {
const list = this.list.get();
delete list[sound._id];
this.list.set(list);
$('#' + sound._id).remove();
$(`#${ sound._id }`).remove();
}
update(sound) {
const audio = $(`#${sound._id}`);
const audio = $(`#${ sound._id }`);
if (audio && audio[0]) {
const list = this.list.get();
list[sound._id] = sound;
@ -48,7 +48,7 @@ class CustomSounds {
getURL(sound) {
const path = (Meteor.isCordova) ? Meteor.absoluteUrl().replace(/\/$/, '') : __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
return `${path}/custom-sounds/${sound._id}.${sound.extension}?_dc=${sound.random || 0}`;
return `${ path }/custom-sounds/${ sound._id }.${ sound.extension }?_dc=${ sound.random || 0 }`;
}
getList() {

@ -13,7 +13,7 @@ Meteor.methods({
throw new Meteor.Error('Custom_Sound_Error_Invalid_Sound', 'Invalid sound', { method: 'deleteCustomSound' });
}
RocketChatFileCustomSoundsInstance.deleteFile(`${sound._id}.${sound.extension}`);
RocketChatFileCustomSoundsInstance.deleteFile(`${ sound._id }.${ sound.extension }`);
RocketChat.models.CustomSounds.removeByID(_id);
RocketChat.Notifications.notifyAll('deleteCustomSound', {soundData: sound});

@ -19,7 +19,7 @@ Meteor.methods({
soundData.name = soundData.name.replace(/:/g, '');
if (nameValidation.test(soundData.name)) {
throw new Meteor.Error('error-input-is-not-a-valid-field', `${soundData.name} is not a valid name`, { method: 'insertOrUpdateSound', input: soundData.name, field: 'Name' });
throw new Meteor.Error('error-input-is-not-a-valid-field', `${ soundData.name } is not a valid name`, { method: 'insertOrUpdateSound', input: soundData.name, field: 'Name' });
}
let matchingResults = [];
@ -48,7 +48,7 @@ Meteor.methods({
} else {
//update sound
if (soundData.newFile) {
RocketChatFileCustomSoundsInstance.deleteFile(`${soundData._id}.${soundData.previousExtension}`);
RocketChatFileCustomSoundsInstance.deleteFile(`${ soundData._id }.${ soundData.previousExtension }`);
}
if (soundData.name !== soundData.previousName) {

@ -8,8 +8,8 @@ Meteor.methods({
const file = new Buffer(binaryContent, 'binary');
const rs = RocketChatFile.bufferToStream(file);
RocketChatFileCustomSoundsInstance.deleteFile(`${soundData._id}.${soundData.extension}`);
const ws = RocketChatFileCustomSoundsInstance.createWriteStream(`${soundData._id}.${soundData.extension}`, contentType);
RocketChatFileCustomSoundsInstance.deleteFile(`${ soundData._id }.${ soundData.extension }`);
const ws = RocketChatFileCustomSoundsInstance.createWriteStream(`${ soundData._id }.${ soundData.extension }`, contentType);
ws.on('end', Meteor.bindEnvironment(() =>
Meteor.setTimeout(() => RocketChat.Notifications.notifyAll('updateCustomSound', {soundData})
, 500)

@ -9,10 +9,10 @@ Meteor.startup(function() {
const RocketChatStore = RocketChatFile[storeType];
if (RocketChatStore == null) {
throw new Error(`Invalid RocketChatStore type [${storeType}]`);
throw new Error(`Invalid RocketChatStore type [${ storeType }]`);
}
console.log(`Using ${storeType} for custom sounds storage`.green);
console.log(`Using ${ storeType } for custom sounds storage`.green);
let path = '~/uploads';
if (RocketChat.settings.get('CustomSounds_FileSystemPath') != null) {

@ -5,7 +5,7 @@ RocketChat.emoji.packages.emojiCustom = {
list: [],
render(html) {
const regShortNames = new RegExp('<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(' + RocketChat.emoji.packages.emojiCustom.list.join('|') + ')', 'gi');
const regShortNames = new RegExp(`<object[^>]*>.*?<\/object>|<span[^>]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(${ RocketChat.emoji.packages.emojiCustom.list.join('|') })`, 'gi');
// replace regular shortnames first
html = html.replace(regShortNames, function(shortname) {
@ -19,10 +19,10 @@ RocketChat.emoji.packages.emojiCustom = {
let dataCheck = RocketChat.emoji.list[shortname];
if (dataCheck.hasOwnProperty('aliasOf')) {
emojiAlias = dataCheck['aliasOf'];
dataCheck = RocketChat.emoji.list[`:${emojiAlias}:`];
dataCheck = RocketChat.emoji.list[`:${ emojiAlias }:`];
}
return `<span class="emoji" style="background-image:url(${getEmojiUrlFromName(emojiAlias, dataCheck['extension'])});" data-emoji="${emojiAlias}" title="${shortname}">${shortname}</span>`;
return `<span class="emoji" style="background-image:url(${ getEmojiUrlFromName(emojiAlias, dataCheck['extension']) });" data-emoji="${ emojiAlias }" title="${ shortname }">${ shortname }</span>`;
}
});
@ -33,7 +33,7 @@ RocketChat.emoji.packages.emojiCustom = {
getEmojiUrlFromName = function(name, extension) {
Session.get;
const key = `emoji_random_${name}`;
const key = `emoji_random_${ name }`;
let random = 0;
if (isSetNotNull(() => Session.keys[key])) {
@ -44,7 +44,7 @@ getEmojiUrlFromName = function(name, extension) {
return;
}
const path = (Meteor.isCordova) ? Meteor.absoluteUrl().replace(/\/$/, '') : __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
return `${path}/emoji-custom/${encodeURIComponent(name)}.${extension}?_dc=${random}`;
return `${ path }/emoji-custom/${ encodeURIComponent(name) }.${ extension }?_dc=${ random }`;
};
Blaze.registerHelper('emojiUrlFromName', getEmojiUrlFromName);
@ -52,27 +52,27 @@ Blaze.registerHelper('emojiUrlFromName', getEmojiUrlFromName);
function updateEmojiPickerList() {
let html = '';
for (const entry of RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket) {
const renderedEmoji = RocketChat.emoji.packages.emojiCustom.render(`:${entry}:`);
html += `<li class="emoji-${entry}" data-emoji="${entry}">${renderedEmoji}</li>`;
const renderedEmoji = RocketChat.emoji.packages.emojiCustom.render(`:${ entry }:`);
html += `<li class="emoji-${ entry }" data-emoji="${ entry }">${ renderedEmoji }</li>`;
}
$('.rocket.emoji-list').empty().append(html);
RocketChat.EmojiPicker.updateRecent();
}
deleteEmojiCustom = function(emojiData) {
delete RocketChat.emoji.list[`:${emojiData.name}:`];
delete RocketChat.emoji.list[`:${ emojiData.name }:`];
const arrayIndex = RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(emojiData.name);
if (arrayIndex !== -1) {
RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1);
}
const arrayIndexList = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${emojiData.name}:`);
const arrayIndexList = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.name }:`);
if (arrayIndexList !== -1) {
RocketChat.emoji.packages.emojiCustom.list.splice(arrayIndexList, 1);
}
if (isSetNotNull(() => emojiData.aliases)) {
for (const alias of emojiData.aliases) {
delete RocketChat.emoji.list[`:${alias}:`];
const aliasIndex = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${alias}:`);
delete RocketChat.emoji.list[`:${ alias }:`];
const aliasIndex = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`);
if (aliasIndex !== -1) {
RocketChat.emoji.packages.emojiCustom.list.splice(aliasIndex, 1);
}
@ -82,16 +82,16 @@ deleteEmojiCustom = function(emojiData) {
};
updateEmojiCustom = function(emojiData) {
let key = `emoji_random_${emojiData.name}`;
let key = `emoji_random_${ emojiData.name }`;
Session.set(key, Math.round(Math.random() * 1000));
const previousExists = isSetNotNull(() => emojiData.previousName);
const currentAliases = isSetNotNull(() => emojiData.aliases);
if (previousExists && isSetNotNull(() => RocketChat.emoji.list[`:${emojiData.previousName}:`].aliases)) {
for (const alias of RocketChat.emoji.list[`:${emojiData.previousName}:`].aliases) {
delete RocketChat.emoji.list[`:${alias}:`];
const aliasIndex = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${alias}:`);
if (previousExists && isSetNotNull(() => RocketChat.emoji.list[`:${ emojiData.previousName }:`].aliases)) {
for (const alias of RocketChat.emoji.list[`:${ emojiData.previousName }:`].aliases) {
delete RocketChat.emoji.list[`:${ alias }:`];
const aliasIndex = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ alias }:`);
if (aliasIndex !== -1) {
RocketChat.emoji.packages.emojiCustom.list.splice(aliasIndex, 1);
}
@ -103,25 +103,25 @@ updateEmojiCustom = function(emojiData) {
if (arrayIndex !== -1) {
RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.splice(arrayIndex, 1);
}
const arrayIndexList = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${emojiData.previousName}:`);
const arrayIndexList = RocketChat.emoji.packages.emojiCustom.list.indexOf(`:${ emojiData.previousName }:`);
if (arrayIndexList !== -1) {
RocketChat.emoji.packages.emojiCustom.list.splice(arrayIndexList, 1);
}
delete RocketChat.emoji.list[`:${emojiData.previousName}:`];
delete RocketChat.emoji.list[`:${ emojiData.previousName }:`];
}
const categoryIndex = RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(`${emojiData.name}`);
const categoryIndex = RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.indexOf(`${ emojiData.name }`);
if (categoryIndex === -1) {
RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.push(`${emojiData.name}`);
RocketChat.emoji.packages.emojiCustom.list.push(`:${emojiData.name}:`);
RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.push(`${ emojiData.name }`);
RocketChat.emoji.packages.emojiCustom.list.push(`:${ emojiData.name }:`);
}
RocketChat.emoji.list[`:${emojiData.name}:`] = Object.assign({ emojiPackage: 'emojiCustom' }, RocketChat.emoji.list[`:${emojiData.name}:`], emojiData);
RocketChat.emoji.list[`:${ emojiData.name }:`] = Object.assign({ emojiPackage: 'emojiCustom' }, RocketChat.emoji.list[`:${ emojiData.name }:`], emojiData);
if (currentAliases) {
for (const alias of emojiData.aliases) {
RocketChat.emoji.packages.emojiCustom.list.push(`:${alias}:`);
RocketChat.emoji.list[`:${alias}:`] = {};
RocketChat.emoji.list[`:${alias}:`].emojiPackage = 'emojiCustom';
RocketChat.emoji.list[`:${alias}:`].aliasOf = emojiData.name;
RocketChat.emoji.packages.emojiCustom.list.push(`:${ alias }:`);
RocketChat.emoji.list[`:${ alias }:`] = {};
RocketChat.emoji.list[`:${ alias }:`].emojiPackage = 'emojiCustom';
RocketChat.emoji.list[`:${ alias }:`].aliasOf = emojiData.name;
}
}
@ -129,17 +129,17 @@ updateEmojiCustom = function(emojiData) {
//update in admin interface
if (previousExists && emojiData.name !== emojiData.previousName) {
$(document).find(`.emojiAdminPreview-image[data-emoji='${emojiData.previousName}']`).css('background-image', `url('${url})'`).attr('data-emoji', `${emojiData.name}`);
$(document).find(`.emojiAdminPreview-image[data-emoji='${ emojiData.previousName }']`).css('background-image', `url('${ url })'`).attr('data-emoji', `${ emojiData.name }`);
} else {
$(document).find(`.emojiAdminPreview-image[data-emoji='${emojiData.name}']`).css('background-image', `url('${url}')`);
$(document).find(`.emojiAdminPreview-image[data-emoji='${ emojiData.name }']`).css('background-image', `url('${ url }')`);
}
//update in picker
if (previousExists && emojiData.name !== emojiData.previousName) {
$(document).find(`li[data-emoji='${emojiData.previousName}'] span`).css('background-image', `url('${url}')`).attr('data-emoji', `${emojiData.name}`);
$(document).find(`li[data-emoji='${emojiData.previousName}']`).attr('data-emoji', `${emojiData.name}`).attr('class', `emoji-${emojiData.name}`);
$(document).find(`li[data-emoji='${ emojiData.previousName }'] span`).css('background-image', `url('${ url }')`).attr('data-emoji', `${ emojiData.name }`);
$(document).find(`li[data-emoji='${ emojiData.previousName }']`).attr('data-emoji', `${ emojiData.name }`).attr('class', `emoji-${ emojiData.name }`);
} else {
$(document).find(`li[data-emoji='${emojiData.name}'] span`).css('background-image', `url('${url}')`);
$(document).find(`li[data-emoji='${ emojiData.name }'] span`).css('background-image', `url('${ url }')`);
}
//update in picker and opened rooms
@ -147,9 +147,9 @@ updateEmojiCustom = function(emojiData) {
if (RoomManager.openedRooms.hasOwnProperty(key)) {
const room = RoomManager.openedRooms[key];
if (previousExists && emojiData.name !== emojiData.previousName) {
$(room.dom).find(`span[data-emoji='${emojiData.previousName}']`).css('background-image', `url('${url}')`).attr('data-emoji', `${emojiData.name}`);
$(room.dom).find(`span[data-emoji='${ emojiData.previousName }']`).css('background-image', `url('${ url }')`).attr('data-emoji', `${ emojiData.name }`);
} else {
$(room.dom).find(`span[data-emoji='${emojiData.name}']`).css('background-image', `url('${url}')`);
$(room.dom).find(`span[data-emoji='${ emojiData.name }']`).css('background-image', `url('${ url }')`);
}
}
}
@ -162,12 +162,12 @@ Meteor.startup(() =>
RocketChat.emoji.packages.emojiCustom.emojisByCategory = { rocket: [] };
for (const emoji of result) {
RocketChat.emoji.packages.emojiCustom.emojisByCategory.rocket.push(emoji.name);
RocketChat.emoji.packages.emojiCustom.list.push(`:${emoji.name}:`);
RocketChat.emoji.list[`:${emoji.name}:`] = emoji;
RocketChat.emoji.list[`:${emoji.name}:`].emojiPackage = 'emojiCustom';
RocketChat.emoji.packages.emojiCustom.list.push(`:${ emoji.name }:`);
RocketChat.emoji.list[`:${ emoji.name }:`] = emoji;
RocketChat.emoji.list[`:${ emoji.name }:`].emojiPackage = 'emojiCustom';
for (const alias of emoji['aliases']) {
RocketChat.emoji.packages.emojiCustom.list.push(`:${alias}:`);
RocketChat.emoji.list[`:${alias}:`] = {
RocketChat.emoji.packages.emojiCustom.list.push(`:${ alias }:`);
RocketChat.emoji.list[`:${ alias }:`] = {
emojiPackage: 'emojiCustom',
aliasOf: emoji.name
};

@ -13,7 +13,7 @@ Meteor.methods({
throw new Meteor.Error('Custom_Emoji_Error_Invalid_Emoji', 'Invalid emoji', { method: 'deleteEmojiCustom' });
}
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emoji.name}.${emoji.extension}`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emoji.name }.${ emoji.extension }`));
RocketChat.models.EmojiCustom.removeByID(emojiID);
RocketChat.Notifications.notifyLogged('deleteEmojiCustom', {emojiData: emoji});

@ -22,12 +22,12 @@ Meteor.methods({
emojiData.aliases = emojiData.aliases.replace(/:/g, '');
if (nameValidation.test(emojiData.name)) {
throw new Meteor.Error('error-input-is-not-a-valid-field', `${emojiData.name} is not a valid name`, { method: 'insertOrUpdateEmoji', input: emojiData.name, field: 'Name' });
throw new Meteor.Error('error-input-is-not-a-valid-field', `${ emojiData.name } is not a valid name`, { method: 'insertOrUpdateEmoji', input: emojiData.name, field: 'Name' });
}
if (emojiData.aliases) {
if (aliasValidation.test(emojiData.aliases)) {
throw new Meteor.Error('error-input-is-not-a-valid-field', `${emojiData.aliases} is not a valid alias set`, { method: 'insertOrUpdateEmoji', input: emojiData.aliases, field: 'Alias_Set' });
throw new Meteor.Error('error-input-is-not-a-valid-field', `${ emojiData.aliases } is not a valid alias set`, { method: 'insertOrUpdateEmoji', input: emojiData.aliases, field: 'Alias_Set' });
}
emojiData.aliases = emojiData.aliases.split(/[\s,]/);
emojiData.aliases = emojiData.aliases.filter(Boolean);
@ -70,19 +70,19 @@ Meteor.methods({
} else {
//update emoji
if (emojiData.newFile) {
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.name}.${emojiData.extension}`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.name}.${emojiData.previousExtension}`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.previousName}.${emojiData.extension}`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.previousName}.${emojiData.previousExtension}`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.previousExtension }`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.extension }`));
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`));
RocketChat.models.EmojiCustom.setExtension(emojiData._id, emojiData.extension);
} else if (emojiData.name !== emojiData.previousName) {
const rs = RocketChatFileEmojiCustomInstance.getFileWithReadStream(encodeURIComponent(`${emojiData.previousName}.${emojiData.previousExtension}`));
const rs = RocketChatFileEmojiCustomInstance.getFileWithReadStream(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`));
if (rs !== null) {
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.name}.${emojiData.extension}`));
const ws = RocketChatFileEmojiCustomInstance.createWriteStream(encodeURIComponent(`${emojiData.name}.${emojiData.previousExtension}`), rs.contentType);
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`));
const ws = RocketChatFileEmojiCustomInstance.createWriteStream(encodeURIComponent(`${ emojiData.name }.${ emojiData.previousExtension }`), rs.contentType);
ws.on('end', Meteor.bindEnvironment(() =>
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.previousName}.${emojiData.previousExtension}`))
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.previousName }.${ emojiData.previousExtension }`))
));
rs.readStream.pipe(ws);
}

@ -10,8 +10,8 @@ Meteor.methods({
const file = new Buffer(binaryContent, 'binary');
const rs = RocketChatFile.bufferToStream(file);
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${emojiData.name}.${emojiData.extension}`));
const ws = RocketChatFileEmojiCustomInstance.createWriteStream(encodeURIComponent(`${emojiData.name}.${emojiData.extension}`), contentType);
RocketChatFileEmojiCustomInstance.deleteFile(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`));
const ws = RocketChatFileEmojiCustomInstance.createWriteStream(encodeURIComponent(`${ emojiData.name }.${ emojiData.extension }`), contentType);
ws.on('end', Meteor.bindEnvironment(() =>
Meteor.setTimeout(() => RocketChat.Notifications.notifyLogged('updateEmojiCustom', {emojiData})
, 500)

@ -9,10 +9,10 @@ Meteor.startup(function() {
const RocketChatStore = RocketChatFile[storeType];
if (RocketChatStore == null) {
throw new Error(`Invalid RocketChatStore type [${storeType}]`);
throw new Error(`Invalid RocketChatStore type [${ storeType }]`);
}
console.log(`Using ${storeType} for custom emoji storage`.green);
console.log(`Using ${ storeType } for custom emoji storage`.green);
let path = '~/uploads';
if (RocketChat.settings.get('EmojiUpload_FileSystemPath') != null) {
@ -61,9 +61,9 @@ Meteor.startup(function() {
const initials = '?';
const svg = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="50" height="50" style="width: 50px; height: 50px; background-color: ${color};">
<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="50" height="50" style="width: 50px; height: 50px; background-color: ${ color };">
<text text-anchor="middle" y="50%" x="50%" dy="0.36em" pointer-events="auto" fill="#ffffff" font-family="Helvetica, Arial, Lucida Grande, sans-serif" style="font-weight: 400; font-size: 28px;">
${initials}
${ initials }
</text>
</svg>`;

@ -8,7 +8,7 @@ Template.messageBox.events({
RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => {
const input = $(event.currentTarget).parent().parent().find('.input-message');
const emojiValue = ':' + emoji + ':';
const emojiValue = `:${ emoji }:`;
const caretPos = input.prop('selectionStart');
const textAreaTxt = input.val();

@ -16,7 +16,7 @@ RocketChat.callbacks.add('renderMessage', (message) => {
message.html = RocketChat.emoji.packages[emojiPackage].render(message.html);
});
const checkEmojiOnly = $(`<div>${message.html}</div>`);
const checkEmojiOnly = $(`<div>${ message.html }</div>`);
let emojiOnly = true;
for (const childNode in checkEmojiOnly[0].childNodes) {
if (checkEmojiOnly[0].childNodes.hasOwnProperty(childNode)) {

@ -33,16 +33,16 @@ function getEmojisByCategory(category) {
let tone = '';
if (actualTone > 0 && RocketChat.emoji.packages[emojiPackage].toneList.hasOwnProperty(emoji)) {
tone = '_tone' + actualTone;
tone = `_tone${ actualTone }`;
}
//set correctPackage here to allow for recent emojis to work properly
if (isSetNotNull(() => RocketChat.emoji.list[`:${emoji}:`].emojiPackage)) {
const correctPackage = RocketChat.emoji.list[`:${emoji}:`].emojiPackage;
if (isSetNotNull(() => RocketChat.emoji.list[`:${ emoji }:`].emojiPackage)) {
const correctPackage = RocketChat.emoji.list[`:${ emoji }:`].emojiPackage;
const image = RocketChat.emoji.packages[correctPackage].render(`:${emoji}${tone}:`);
const image = RocketChat.emoji.packages[correctPackage].render(`:${ emoji }${ tone }:`);
html += `<li class="emoji-${emoji}" data-emoji="${emoji}" title="${emoji}">${image}</li>`;
html += `<li class="emoji-${ emoji }" data-emoji="${ emoji }" title="${ emoji }">${ image }</li>`;
}
}
}
@ -70,7 +70,7 @@ function getEmojisBySearchTerm(searchTerm) {
emoji = emoji.replace(/:/g, '');
if (actualTone > 0 && RocketChat.emoji.packages[emojiPackage].toneList.hasOwnProperty(emoji)) {
tone = '_tone' + actualTone;
tone = `_tone${ actualTone }`;
}
let emojiFound = false;
@ -86,8 +86,8 @@ function getEmojisBySearchTerm(searchTerm) {
}
if (emojiFound) {
const image = RocketChat.emoji.packages[emojiPackage].render(`:${emoji}${tone}:`);
html += `<li class="emoji-${emoji}" data-emoji="${emoji}" title="${emoji}">${image}</li>`;
const image = RocketChat.emoji.packages[emojiPackage].render(`:${ emoji }${ tone }:`);
html += `<li class="emoji-${ emoji }" data-emoji="${ emoji }" title="${ emoji }">${ image }</li>`;
}
}
}
@ -129,7 +129,7 @@ Template.emojiPicker.helpers({
//clear dynamic categories to prevent duplication issues
if (category === 'recent' || category === 'rocket') {
$(`.${category}.emoji-list`).empty();
$(`.${ category }.emoji-list`).empty();
}
if (searchTerm.length > 0) {
@ -139,7 +139,7 @@ Template.emojiPicker.helpers({
}
},
currentTone() {
return 'tone-' + Template.instance().tone;
return `tone-${ Template.instance().tone }`;
},
/**
* Returns true if a given emoji category is active
@ -199,7 +199,7 @@ Template.emojiPicker.events({
let newTone;
if (tone > 0) {
newTone = '_tone' + tone;
newTone = `_tone${ tone }`;
} else {
newTone = '';
}
@ -209,7 +209,7 @@ Template.emojiPicker.events({
if (RocketChat.emoji.packages[emojiPackage].hasOwnProperty('toneList')) {
for (const emoji in RocketChat.emoji.packages[emojiPackage].toneList) {
if (RocketChat.emoji.packages[emojiPackage].toneList.hasOwnProperty(emoji)) {
$('.emoji-'+emoji).html(RocketChat.emoji.packages[emojiPackage].render(':' + emoji + newTone + ':'));
$(`.emoji-${ emoji }`).html(RocketChat.emoji.packages[emojiPackage].render(`:${ emoji }${ newTone }:`));
}
}
}
@ -232,7 +232,7 @@ Template.emojiPicker.events({
for (const emojiPackage in RocketChat.emoji.packages) {
if (RocketChat.emoji.packages.hasOwnProperty(emojiPackage)) {
if (actualTone > 0 && RocketChat.emoji.packages[emojiPackage].toneList.hasOwnProperty(emoji)) {
tone = '_tone' + actualTone;
tone = `_tone${ actualTone }`;
}
}
}
@ -272,8 +272,8 @@ Template.emojiPicker.onCreated(function() {
});
this.setCurrentTone = (newTone) => {
$('.current-tone').removeClass('tone-' + this.tone);
$('.current-tone').addClass('tone-' + newTone);
$('.current-tone').removeClass(`tone-${ this.tone }`);
$('.current-tone').addClass(`tone-${ newTone }`);
this.tone = newTone;
};
});

@ -124,10 +124,10 @@ RocketChat.EmojiPicker = {
for (let i = 0; i < total; i++) {
const emoji = RocketChat.emoji.packages.base.emojisByCategory.recent[i];
if (isSetNotNull(() => RocketChat.emoji.list[`:${emoji}:`])) {
const emojiPackage = RocketChat.emoji.list[`:${emoji}:`].emojiPackage;
const renderedEmoji = RocketChat.emoji.packages[emojiPackage].render(`:${emoji}:`);
html += `<li class="emoji-${emoji}" data-emoji="${emoji}">${renderedEmoji}</li>`;
if (isSetNotNull(() => RocketChat.emoji.list[`:${ emoji }:`])) {
const emojiPackage = RocketChat.emoji.list[`:${ emoji }:`].emojiPackage;
const renderedEmoji = RocketChat.emoji.packages[emojiPackage].render(`:${ emoji }:`);
html += `<li class="emoji-${ emoji }" data-emoji="${ emoji }">${ renderedEmoji }</li>`;
} else {
this.recent = _.without(this.recent, emoji);
}

@ -52,7 +52,7 @@ class ErrorHandler {
const user = RocketChat.models.Users.findOneById('rocket.cat');
if (stack) {
message = message + '\n```\n' + stack + '\n```';
message = `${ message }\n\`\`\`\n${ stack }\n\`\`\``;
}
RocketChat.sendMessage(user, { msg: message }, { _id: this.rid });

@ -9,11 +9,11 @@ const generateURL = function(file) {
if (!file || !file.s3) {
return;
}
const resourceURL = '/' + file.s3.bucket + '/' + file.s3.path + file._id;
const resourceURL = `/${ file.s3.bucket }/${ file.s3.path }${ file._id }`;
const expires = parseInt(new Date().getTime() / 1000) + Math.max(5, S3expiryTimeSpan);
const StringToSign = 'GET\n\n\n' + expires +'\n'+resourceURL;
const StringToSign = `GET\n\n\n${ expires }\n${ resourceURL }`;
const signature = crypto.createHmac('sha1', S3secretKey).update(new Buffer(StringToSign, 'utf-8')).digest('base64');
return file.url + '?AWSAccessKeyId='+encodeURIComponent(S3accessKey)+'&Expires='+expires+'&Signature='+encodeURIComponent(signature);
return `${ file.url }?AWSAccessKeyId=${ encodeURIComponent(S3accessKey) }&Expires=${ expires }&Signature=${ encodeURIComponent(signature) }`;
};
FileUpload.addHandler('s3', {
@ -62,7 +62,7 @@ const createS3Directive = _.debounce(() => {
AWSAccessKeyId: accessKey,
AWSSecretAccessKey: secretKey,
key(file, metaContext) {
const path = RocketChat.hostname + '/' + metaContext.rid + '/' + this.userId + '/';
const path = `${ RocketChat.hostname }/${ metaContext.rid }/${ this.userId }/`;
const upload = { s3: {
bucket,

@ -59,7 +59,7 @@ FileUpload.addHandler(storeName, {
if (stat && stat.isFile()) {
file = FileUpload.addExtensionTo(file);
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`);
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${ encodeURIComponent(file.name) }`);
res.setHeader('Last-Modified', file.uploadedAt.toUTCString());
res.setHeader('Content-Type', file.type);
res.setHeader('Content-Length', file.size);

@ -25,9 +25,9 @@ function generateGetURL({ file }) {
}
const expires = new Date().getTime() + 120000;
const signature = crypto.createSign('RSA-SHA256').update(`GET\n\n\n${expires}\n/${file.googleCloudStorage.bucket}/${parts.path}`).sign(parts.secret, 'base64');
const signature = crypto.createSign('RSA-SHA256').update(`GET\n\n\n${ expires }\n/${ file.googleCloudStorage.bucket }/${ parts.path }`).sign(parts.secret, 'base64');
return `${file.url}?GoogleAccessId=${parts.accessId}&Expires=${expires}&Signature=${encodeURIComponent(signature)}`;
return `${ file.url }?GoogleAccessId=${ parts.accessId }&Expires=${ expires }&Signature=${ encodeURIComponent(signature) }`;
}
function generateDeleteUrl({ file }) {
@ -38,9 +38,9 @@ function generateDeleteUrl({ file }) {
}
const expires = new Date().getTime() + 5000;
const signature = crypto.createSign('RSA-SHA256').update(`DELETE\n\n\n${expires}\n/${file.googleCloudStorage.bucket}/${encodeURIComponent(parts.path)}`).sign(parts.secret, 'base64');
const signature = crypto.createSign('RSA-SHA256').update(`DELETE\n\n\n${ expires }\n/${ file.googleCloudStorage.bucket }/${ encodeURIComponent(parts.path) }`).sign(parts.secret, 'base64');
return `https://${file.googleCloudStorage.bucket}.storage.googleapis.com/${encodeURIComponent(parts.path)}?GoogleAccessId=${parts.accessId}&Expires=${expires}&Signature=${encodeURIComponent(signature)}`;
return `https://${ file.googleCloudStorage.bucket }.storage.googleapis.com/${ encodeURIComponent(parts.path) }?GoogleAccessId=${ parts.accessId }&Expires=${ expires }&Signature=${ encodeURIComponent(signature) }`;
}
FileUpload.addHandler('googleCloudStorage', {
@ -88,7 +88,7 @@ const createGoogleStorageDirective = _.debounce(() => {
GoogleAccessId: accessId,
GoogleSecretKey: secret,
key: function _googleCloudStorageKey(file, metaContext) {
const path = RocketChat.settings.get('uniqueID') + '/' + metaContext.rid + '/' + this.userId + '/';
const path = `${ RocketChat.settings.get('uniqueID') }/${ metaContext.rid }/${ this.userId }/`;
const fileId = RocketChat.models.Uploads.insertFileInit(metaContext.rid, this.userId, 'googleCloudStorage', file, { googleCloudStorage: { bucket, path }});
return path + fileId;

@ -108,11 +108,11 @@ const readFromGridFS = function(storeName, fileId, file, headers, req, res) {
delete headers['Content-Type'];
delete headers['Content-Disposition'];
delete headers['Last-Modified'];
headers['Content-Range'] = 'bytes */' + file.size;
headers['Content-Range'] = `bytes */${ file.size }`;
res.writeHead(416, headers);
res.end();
} else if (range) {
headers['Content-Range'] = 'bytes ' + range.start + '-' + range.stop + '/' + file.size;
headers['Content-Range'] = `bytes ${ range.start }-${ range.stop }/${ file.size }`;
delete headers['Content-Length'];
headers['Content-Length'] = range.stop - range.start + 1;
res.writeHead(206, headers);
@ -128,7 +128,7 @@ FileUpload.addHandler('rocketchat_uploads', {
get(file, req, res) {
file = FileUpload.addExtensionTo(file);
const headers = {
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`,
'Content-Disposition': `attachment; filename*=UTF-8''${ encodeURIComponent(file.name) }`,
'Last-Modified': file.uploadedAt.toUTCString(),
'Content-Type': file.type,
'Content-Length': file.size

@ -35,8 +35,8 @@ FileUpload.addExtensionTo = function(file) {
}
const ext = mime.extension(file.type);
if (ext && false === new RegExp(`\.${ext}$`, 'i').test(file.name)) {
file.name = `${file.name}.${ext}`;
if (ext && false === new RegExp(`\.${ ext }$`, 'i').test(file.name)) {
file.name = `${ file.name }.${ ext }`;
}
return file;

@ -26,12 +26,12 @@ Meteor.methods({
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'sendFileMessage' });
}
const file = RocketChat.models.Uploads.findOneById(fileId);
const resourceURL = '/' + file.s3.bucket + '/' + file.s3.path + file._id;
const resourceURL = `/${ file.s3.bucket }/${ file.s3.path }${ file._id }`;
const expires = parseInt(new Date().getTime() / 1000) + Math.max(5, S3expiryTimeSpan);
const StringToSign = 'GET\n\n\n' + expires +'\n'+resourceURL;
const StringToSign = `GET\n\n\n${ expires }\n${ resourceURL }`;
const signature = crypto.createHmac('sha1', S3secretKey).update(new Buffer(StringToSign, 'utf-8')).digest('base64');
return {
url:file.url + '?AWSAccessKeyId='+encodeURIComponent(S3accessKey)+'&Expires='+expires+'&Signature='+encodeURIComponent(signature)
url:`${ file.url }?AWSAccessKeyId=${ encodeURIComponent(S3accessKey) }&Expires=${ expires }&Signature=${ encodeURIComponent(signature) }`
};
}
});

@ -20,10 +20,10 @@ Meteor.methods({
RocketChat.models.Uploads.updateFileComplete(file._id, Meteor.userId(), _.omit(file, '_id'));
const fileUrl = '/file-upload/' + file._id + '/' + file.name;
const fileUrl = `/file-upload/${ file._id }/${ file.name }`;
const attachment = {
title: `${TAPi18n.__('Attachment_File_Uploaded')}: ${file.name}`,
title: `${ TAPi18n.__('Attachment_File_Uploaded') }: ${ file.name }`,
description: file.description,
title_link: fileUrl,
title_link_download: true

@ -17,7 +17,7 @@ function HighlightWordsClient(message) {
if (Array.isArray(to_highlight)) {
to_highlight.forEach((highlight) => {
if (!_.isBlank(highlight)) {
return msg = msg.replace(new RegExp('(^|\\b|[\\s\\n\\r\\t.,،\'\\\"\\+!?:-])(' + s.escapeRegExp(highlight) + ')($|\\b|[\\s\\n\\r\\t.,،\'\\\"\\+!?:-])(?![^<]*>|[^<>]*<\\/)', 'gmi'), '$1<span class="highlight-text">$2</span>$3');
return msg = msg.replace(new RegExp(`(^|\\b|[\\s\\n\\r\\t.,،'\\\"\\+!?:-])(${ s.escapeRegExp(highlight) })($|\\b|[\\s\\n\\r\\t.,،'\\\"\\+!?:-])(?![^<]*>|[^<>]*<\\/)`, 'gmi'), '$1<span class="highlight-text">$2</span>$3');
}
});
}

@ -10,9 +10,9 @@ Package.onUse(function(api) {
const fs = Npm.require('fs');
const workingDir = process.env.PWD || '.';
fs.readdirSync(workingDir + '/packages/rocketchat-i18n/i18n').forEach(function(filename) {
if (filename.indexOf('.json') > -1 && fs.statSync(workingDir + '/packages/rocketchat-i18n/i18n/' + filename).size > 16) {
api.addFiles('i18n/' + filename);
fs.readdirSync(`${ workingDir }/packages/rocketchat-i18n/i18n`).forEach(function(filename) {
if (filename.indexOf('.json') > -1 && fs.statSync(`${ workingDir }/packages/rocketchat-i18n/i18n/${ filename }`).size > 16) {
api.addFiles(`i18n/${ filename }`);
}
});

@ -59,9 +59,9 @@ class IframeLogin {
}
if (window.cordova) {
iframeUrl += separator + 'client=cordova';
iframeUrl += `${ separator }client=cordova`;
} else if (navigator.userAgent.indexOf('Electron') > -1) {
iframeUrl += separator + 'client=electron';
iframeUrl += `${ separator }client=electron`;
}
HTTP.call(this.apiMethod, this.apiUrl, options, (error, result) => {

@ -20,17 +20,17 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
let tempUsers = [];
const tempMessages = new Map();
for (const entry of zipEntries) {
this.logger.debug(`Entry: ${entry.entryName}`);
this.logger.debug(`Entry: ${ entry.entryName }`);
//Ignore anything that has `__MACOSX` in it's name, as sadly these things seem to mess everything up
if (entry.entryName.indexOf('__MACOSX') > -1) {
this.logger.debug(`Ignoring the file: ${entry.entryName}`);
this.logger.debug(`Ignoring the file: ${ entry.entryName }`);
continue;
}
//Directories are ignored, since they are "virtual" in a zip file
if (entry.isDirectory) {
this.logger.debug(`Ignoring the directory entry: ${entry.entryName}`);
this.logger.debug(`Ignoring the directory entry: ${ entry.entryName }`);
continue;
}
@ -73,7 +73,7 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
try {
msgs = this.csvParser(entry.getData().toString());
} catch (e) {
this.logger.warn(`The file ${entry.entryName} contains invalid syntax`, e);
this.logger.warn(`The file ${ entry.entryName } contains invalid syntax`, e);
continue;
}
@ -105,15 +105,15 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
for (const [msgGroupData, msgs] of messagesMap.entries()) {
messagesCount += msgs.length;
super.updateRecord({ 'messagesstatus': `${channel}/${msgGroupData}` });
super.updateRecord({ 'messagesstatus': `${ channel }/${ msgGroupData }` });
if (Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize) {
Importer.Base.getBSONSafeArraysFromAnArray(msgs).forEach((splitMsg, i) => {
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${channel}/${msgGroupData}.${i}`, 'messages': splitMsg });
this.messages.get(channel).set(`${msgGroupData}.${i}`, this.collection.findOne(messagesId));
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${ channel }/${ msgGroupData }.${ i }`, 'messages': splitMsg });
this.messages.get(channel).set(`${ msgGroupData }.${ i }`, this.collection.findOne(messagesId));
});
} else {
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${channel}/${msgGroupData}`, 'messages': msgs });
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${ channel }/${ msgGroupData }`, 'messages': msgs });
this.messages.get(channel).set(msgGroupData, this.collection.findOne(messagesId));
}
}
@ -124,7 +124,7 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
//Ensure we have some users, channels, and messages
if (tempUsers.length === 0 || tempChannels.length === 0 || messagesCount === 0) {
this.logger.warn(`The loaded users count ${tempUsers.length}, the loaded channels ${tempChannels.length}, and the loaded messages ${messagesCount}`);
this.logger.warn(`The loaded users count ${ tempUsers.length }, the loaded channels ${ tempChannels.length }, and the loaded messages ${ messagesCount }`);
super.updateProgress(Importer.ProgressStep.ERROR);
return super.getProgress();
}
@ -243,10 +243,10 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
const room = RocketChat.models.Rooms.findOneById(csvChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } });
Meteor.runAsUser(startedByUserId, () => {
for (const [msgGroupData, msgs] of messagesMap.entries()) {
super.updateRecord({ 'messagesstatus': `${ch}/${msgGroupData}.${msgs.messages.length}` });
super.updateRecord({ 'messagesstatus': `${ ch }/${ msgGroupData }.${ msgs.messages.length }` });
for (const msg of msgs.messages) {
if (isNaN(new Date(parseInt(msg.ts)))) {
this.logger.warn(`Timestamp on a message in ${ch}/${msgGroupData} is invalid`);
this.logger.warn(`Timestamp on a message in ${ ch }/${ msgGroupData } is invalid`);
super.addCountCompleted(1);
continue;
}
@ -254,7 +254,7 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
const creator = this.getUserFromUsername(msg.username);
if (creator) {
const msgObj = {
_id: `csv-${csvChannel.id}-${msg.ts}`,
_id: `csv-${ csvChannel.id }-${ msg.ts }`,
ts: new Date(parseInt(msg.ts)),
msg: msg.text,
rid: room._id,
@ -276,7 +276,7 @@ Importer.CSV = class ImporterCSV extends Importer.Base {
super.updateProgress(Importer.ProgressStep.FINISHING);
super.updateProgress(Importer.ProgressStep.DONE);
const timeTook = Date.now() - started;
this.logger.log(`CSV Import took ${timeTook} milliseconds.`);
this.logger.log(`CSV Import took ${ timeTook } milliseconds.`);
});
return super.getProgress();

@ -27,7 +27,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
const info = this.path.parse(header.name);
stream.on('data', Meteor.bindEnvironment((chunk) => {
this.logger.debug(`Processing the file: ${header.name}`);
this.logger.debug(`Processing the file: ${ header.name }`);
const file = JSON.parse(chunk);
if (info.base === 'users.json') {
@ -58,7 +58,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
}
} else if (info.base === 'history.json') {
const dirSplit = info.dir.split('/'); //['.', 'users', '1']
const roomIdentifier = `${dirSplit[1]}/${dirSplit[2]}`;
const roomIdentifier = `${ dirSplit[1] }/${ dirSplit[2] }`;
if (dirSplit[1] === 'users') {
const msgs = [];
@ -66,10 +66,10 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
if (m.PrivateUserMessage) {
msgs.push({
type: 'user',
id: `hipchatenterprise-${m.PrivateUserMessage.id}`,
id: `hipchatenterprise-${ m.PrivateUserMessage.id }`,
senderId: m.PrivateUserMessage.sender.id,
receiverId: m.PrivateUserMessage.receiver.id,
text: m.PrivateUserMessage.message.indexOf('/me ') === -1 ? m.PrivateUserMessage.message : `${m.PrivateUserMessage.message.replace(/\/me /, '_')}_`,
text: m.PrivateUserMessage.message.indexOf('/me ') === -1 ? m.PrivateUserMessage.message : `${ m.PrivateUserMessage.message.replace(/\/me /, '_') }_`,
ts: new Date(m.PrivateUserMessage.timestamp.split(' ')[0])
});
}
@ -82,15 +82,15 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
if (m.UserMessage) {
roomMsgs.push({
type: 'user',
id: `hipchatenterprise-${dirSplit[2]}-${m.UserMessage.id}`,
id: `hipchatenterprise-${ dirSplit[2] }-${ m.UserMessage.id }`,
userId: m.UserMessage.sender.id,
text: m.UserMessage.message.indexOf('/me ') === -1 ? m.UserMessage.message : `${m.UserMessage.message.replace(/\/me /, '_')}_`,
text: m.UserMessage.message.indexOf('/me ') === -1 ? m.UserMessage.message : `${ m.UserMessage.message.replace(/\/me /, '_') }_`,
ts: new Date(m.UserMessage.timestamp.split(' ')[0])
});
} else if (m.TopicRoomMessage) {
roomMsgs.push({
type: 'topic',
id: `hipchatenterprise-${dirSplit[2]}-${m.TopicRoomMessage.id}`,
id: `hipchatenterprise-${ dirSplit[2] }-${ m.TopicRoomMessage.id }`,
userId: m.TopicRoomMessage.sender.id,
ts: new Date(m.TopicRoomMessage.timestamp.split(' ')[0]),
text: m.TopicRoomMessage.message
@ -101,11 +101,11 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
}
tempMessages.set(roomIdentifier, roomMsgs);
} else {
this.logger.warn(`HipChat Enterprise importer isn't configured to handle "${dirSplit[1]}" files.`);
this.logger.warn(`HipChat Enterprise importer isn't configured to handle "${ dirSplit[1] }" files.`);
}
} else {
//What are these files!?
this.logger.warn(`HipChat Enterprise importer doesn't know what to do with the file "${header.name}" :o`, info);
this.logger.warn(`HipChat Enterprise importer doesn't know what to do with the file "${ header.name }" :o`, info);
}
}));
@ -148,17 +148,17 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
if (Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize) {
Importer.Base.getBSONSafeArraysFromAnArray(msgs).forEach((splitMsg, i) => {
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${channel}/${i}`, 'messages': splitMsg });
this.messages.get(channel).set(`${channel}.${i}`, this.collection.findOne(messagesId));
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${ channel }/${ i }`, 'messages': splitMsg });
this.messages.get(channel).set(`${ channel }.${ i }`, this.collection.findOne(messagesId));
});
} else {
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${channel}`, 'messages': msgs });
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'messages', 'name': `${ channel }`, 'messages': msgs });
this.messages.get(channel).set(channel, this.collection.findOne(messagesId));
}
}
for (const [directMsgUser, msgs] of tempDirectMessages.entries()) {
this.logger.debug(`Preparing the direct messages for: ${directMsgUser}`);
this.logger.debug(`Preparing the direct messages for: ${ directMsgUser }`);
if (!this.directMessages.get(directMsgUser)) {
this.directMessages.set(directMsgUser, new Map());
}
@ -168,11 +168,11 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
if (Importer.Base.getBSONSize(msgs) > Importer.Base.MaxBSONSize) {
Importer.Base.getBSONSafeArraysFromAnArray(msgs).forEach((splitMsg, i) => {
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'directMessages', 'name': `${directMsgUser}/${i}`, 'messages': splitMsg });
this.directMessages.get(directMsgUser).set(`${directMsgUser}.${i}`, this.collection.findOne(messagesId));
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'directMessages', 'name': `${ directMsgUser }/${ i }`, 'messages': splitMsg });
this.directMessages.get(directMsgUser).set(`${ directMsgUser }.${ i }`, this.collection.findOne(messagesId));
});
} else {
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'directMessages', 'name': `${directMsgUser}`, 'messages': msgs });
const messagesId = this.collection.insert({ 'import': this.importRecord._id, 'importer': this.name, 'type': 'directMessages', 'name': `${ directMsgUser }`, 'messages': msgs });
this.directMessages.get(directMsgUser).set(directMsgUser, this.collection.findOne(messagesId));
}
}
@ -182,7 +182,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
//Ensure we have some users, channels, and messages
if (tempUsers.length === 0 || tempRooms.length === 0 || messagesCount === 0) {
this.logger.warn(`The loaded users count ${tempUsers.length}, the loaded rooms ${tempRooms.length}, and the loaded messages ${messagesCount}`);
this.logger.warn(`The loaded users count ${ tempUsers.length }, the loaded rooms ${ tempRooms.length }, and the loaded messages ${ messagesCount }`);
super.updateProgress(Importer.ProgressStep.ERROR);
reject();
return;
@ -236,7 +236,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
super.updateProgress(Importer.ProgressStep.IMPORTING_USERS);
//Import the users
for (const u of this.users.users) {
this.logger.debug(`Starting the user import: ${u.username} and are we importing them? ${u.do_import}`);
this.logger.debug(`Starting the user import: ${ u.username } and are we importing them? ${ u.do_import }`);
if (!u.do_import) {
continue;
}
@ -262,7 +262,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
//TODO: Think about using a custom field for the users "title" field
if (u.avatar) {
Meteor.call('setAvatarFromService', `data:image/png;base64,${u.avatar}`);
Meteor.call('setAvatarFromService', `data:image/png;base64,${ u.avatar }`);
}
//Deleted users are 'inactive' users in Rocket.Chat
@ -327,10 +327,10 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
const room = RocketChat.models.Rooms.findOneById(hipChannel.rocketId, { fields: { usernames: 1, t: 1, name: 1 } });
Meteor.runAsUser(startedByUserId, () => {
for (const [msgGroupData, msgs] of messagesMap.entries()) {
super.updateRecord({ 'messagesstatus': `${ch}/${msgGroupData}.${msgs.messages.length}` });
super.updateRecord({ 'messagesstatus': `${ ch }/${ msgGroupData }.${ msgs.messages.length }` });
for (const msg of msgs.messages) {
if (isNaN(msg.ts)) {
this.logger.warn(`Timestamp on a message in ${ch}/${msgGroupData} is invalid`);
this.logger.warn(`Timestamp on a message in ${ ch }/${ msgGroupData } is invalid`);
super.addCountCompleted(1);
continue;
}
@ -375,10 +375,10 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
}
for (const [msgGroupData, msgs] of directMessagesMap.entries()) {
super.updateRecord({ 'messagesstatus': `${directMsgRoom}/${msgGroupData}.${msgs.messages.length}` });
super.updateRecord({ 'messagesstatus': `${ directMsgRoom }/${ msgGroupData }.${ msgs.messages.length }` });
for (const msg of msgs.messages) {
if (isNaN(msg.ts)) {
this.logger.warn(`Timestamp on a message in ${directMsgRoom}/${msgGroupData} is invalid`);
this.logger.warn(`Timestamp on a message in ${ directMsgRoom }/${ msgGroupData } is invalid`);
super.addCountCompleted(1);
continue;
}
@ -422,7 +422,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
super.updateProgress(Importer.ProgressStep.FINISHING);
super.updateProgress(Importer.ProgressStep.DONE);
const timeTook = Date.now() - started;
this.logger.log(`HipChat Enterprise Import took ${timeTook} milliseconds.`);
this.logger.log(`HipChat Enterprise Import took ${ timeTook } milliseconds.`);
});
return super.getProgress();
@ -437,7 +437,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
getChannelFromRoomIdentifier(roomIdentifier) {
for (const ch of this.channels.channels) {
if (`rooms/${ch.id}` === roomIdentifier) {
if (`rooms/${ ch.id }` === roomIdentifier) {
return ch;
}
}
@ -445,7 +445,7 @@ Importer.HipChatEnterprise = class ImporterHipChatEnterprise extends Importer.Ba
getUserFromDirectMessageIdentifier(directIdentifier) {
for (const u of this.users.users) {
if (`users/${u.id}` === directIdentifier) {
if (`users/${ u.id }` === directIdentifier) {
return u;
}
}

@ -25,9 +25,9 @@ Meteor.methods({
}
}
} else if (!name) {
throw new Meteor.Error('error-importer-not-defined', `No Importer Found: "${name}"`, { method: 'prepareImport' });
throw new Meteor.Error('error-importer-not-defined', `No Importer Found: "${ name }"`, { method: 'prepareImport' });
} else {
throw new Meteor.Error('error-importer-not-defined', `The importer, "${name}", was not defined correctly, it is missing the Import class.`, { method: 'prepareImport' });
throw new Meteor.Error('error-importer-not-defined', `The importer, "${ name }", was not defined correctly, it is missing the Import class.`, { method: 'prepareImport' });
}
}
});

@ -26,8 +26,8 @@ Template.integrationsIncoming.helpers({
}
if (data) {
const completeToken = `${data._id}/${data.token}`;
data.url = Meteor.absoluteUrl(`hooks/${completeToken}`);
const completeToken = `${ data._id }/${ data.token }`;
data.url = Meteor.absoluteUrl(`hooks/${ completeToken }`);
data.completeToken = completeToken;
Template.instance().record.set(data);
return data;
@ -118,7 +118,7 @@ Template.integrationsIncoming.helpers({
}
});
return `curl -X POST -H 'Content-Type: application/json' --data 'payload=${JSON.stringify(data)}' ${record.url}`;
return `curl -X POST -H 'Content-Type: application/json' --data 'payload=${ JSON.stringify(data) }' ${ record.url }`;
},
editorOptions() {

@ -205,7 +205,7 @@ Template.integrationsOutgoing.events({
},
'click .button.history': () => {
FlowRouter.go(`/admin/integrations/outgoing/${FlowRouter.getParam('id')}/history`);
FlowRouter.go(`/admin/integrations/outgoing/${ FlowRouter.getParam('id') }/history`);
},
'click .expand': (e) => {

@ -25,7 +25,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
addIntegration(record) {
logger.outgoing.debug(`Adding the integration ${record.name} of the event ${record.event}!`);
logger.outgoing.debug(`Adding the integration ${ record.name } of the event ${ record.event }!`);
let channels;
if (record.event && !RocketChat.integrations.outgoingEvents[record.event].use.channel) {
logger.outgoing.debug('The integration doesnt rely on channels.');
@ -163,11 +163,11 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
//If no room could be found, we won't be sending any messages but we'll warn in the logs
if (!tmpRoom) {
logger.outgoing.warn(`The Integration "${trigger.name}" doesn't have a room configured nor did it provide a room to send the message to.`);
logger.outgoing.warn(`The Integration "${ trigger.name }" doesn't have a room configured nor did it provide a room to send the message to.`);
return;
}
logger.outgoing.debug(`Found a room for ${trigger.name} which is: ${tmpRoom.name} with a type of ${tmpRoom.t}`);
logger.outgoing.debug(`Found a room for ${ trigger.name } which is: ${ tmpRoom.name } with a type of ${ tmpRoom.t }`);
message.bot = { i: trigger._id };
@ -178,9 +178,9 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
};
if (tmpRoom.t === 'd') {
message.channel = '@' + tmpRoom._id;
message.channel = `@${ tmpRoom._id }`;
} else {
message.channel = '#' + tmpRoom._id;
message.channel = `#${ tmpRoom._id }`;
}
message = processWebhookMessage(message, user, defaultValues);
@ -240,7 +240,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
return this.compiledScripts[integration._id].script;
}
} catch (e) {
logger.outgoing.error(`Error evaluating Script in Trigger ${integration.name}:`);
logger.outgoing.error(`Error evaluating Script in Trigger ${ integration.name }:`);
logger.outgoing.error(script.replace(/^/gm, ' '));
logger.outgoing.error('Stack Trace:');
logger.outgoing.error(e.stack.replace(/^/gm, ' '));
@ -248,7 +248,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
if (!sandbox.Script) {
logger.outgoing.error(`Class "Script" not in Trigger ${integration.name}:`);
logger.outgoing.error(`Class "Script" not in Trigger ${ integration.name }:`);
throw new Meteor.Error('class-script-not-found');
}
}
@ -278,8 +278,8 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
if (!script[method]) {
logger.outgoing.error(`Method "${method}" no found in the Integration "${integration.name}"`);
this.updateHistory({ historyId, step: `execute-script-no-method-${method}` });
logger.outgoing.error(`Method "${ method }" no found in the Integration "${ integration.name }"`);
this.updateHistory({ historyId, step: `execute-script-no-method-${ method }` });
return;
}
@ -289,16 +289,16 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
sandbox.method = method;
sandbox.params = params;
this.updateHistory({ historyId, step: `execute-script-before-running-${method}` });
this.updateHistory({ historyId, step: `execute-script-before-running-${ method }` });
const result = this.vm.runInNewContext('script[method](params)', sandbox, { timeout: 3000 });
logger.outgoing.debug(`Script method "${method}" result of the Integration "${integration.name}" is:`);
logger.outgoing.debug(`Script method "${ method }" result of the Integration "${ integration.name }" is:`);
logger.outgoing.debug(result);
return result;
} catch (e) {
this.updateHistory({ historyId, step: `execute-script-error-running-${method}`, error: true, errorStack: e.stack.replace(/^/gm, ' ') });
logger.outgoing.error(`Error running Script in the Integration ${integration.name}:`);
this.updateHistory({ historyId, step: `execute-script-error-running-${ method }`, error: true, errorStack: e.stack.replace(/^/gm, ' ') });
logger.outgoing.error(`Error running Script in the Integration ${ integration.name }:`);
logger.outgoing.debug(integration.scriptCompiled.replace(/^/gm, ' ')); // Only output the compiled script if debugging is enabled, so the logs don't get spammed.
logger.outgoing.error('Stack:');
logger.outgoing.error(e.stack.replace(/^/gm, ' '));
@ -351,12 +351,12 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
break;
default:
logger.outgoing.warn(`An Unhandled Trigger Event was called: ${argObject.event}`);
logger.outgoing.warn(`An Unhandled Trigger Event was called: ${ argObject.event }`);
argObject.event = undefined;
break;
}
logger.outgoing.debug(`Got the event arguments for the event: ${argObject.event}`, argObject);
logger.outgoing.debug(`Got the event arguments for the event: ${ argObject.event }`, argObject);
return argObject;
}
@ -461,8 +461,8 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
const id = room._id.replace(message.u._id, '');
const username = _.without(room.usernames, message.u.username)[0];
if (this.triggers['@'+id]) {
for (const trigger of Object.values(this.triggers['@'+id])) {
if (this.triggers[`@${ id }`]) {
for (const trigger of Object.values(this.triggers[`@${ id }`])) {
triggersToExecute.push(trigger);
}
}
@ -473,8 +473,8 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
}
if (id !== username && this.triggers['@'+username]) {
for (const trigger of Object.values(this.triggers['@'+username])) {
if (id !== username && this.triggers[`@${ username }`]) {
for (const trigger of Object.values(this.triggers[`@${ username }`])) {
triggersToExecute.push(trigger);
}
}
@ -487,14 +487,14 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
}
if (this.triggers['#'+room._id]) {
for (const trigger of Object.values(this.triggers['#'+room._id])) {
if (this.triggers[`#${ room._id }`]) {
for (const trigger of Object.values(this.triggers[`#${ room._id }`])) {
triggersToExecute.push(trigger);
}
}
if (room._id !== room.name && this.triggers['#'+room.name]) {
for (const trigger of Object.values(this.triggers['#'+room.name])) {
if (room._id !== room.name && this.triggers[`#${ room.name }`]) {
for (const trigger of Object.values(this.triggers[`#${ room.name }`])) {
triggersToExecute.push(trigger);
}
}
@ -507,14 +507,14 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
}
if (this.triggers['#'+room._id]) {
for (const trigger of Object.values(this.triggers['#'+room._id])) {
if (this.triggers[`#${ room._id }`]) {
for (const trigger of Object.values(this.triggers[`#${ room._id }`])) {
triggersToExecute.push(trigger);
}
}
if (room._id !== room.name && this.triggers['#'+room.name]) {
for (const trigger of Object.values(this.triggers['#'+room.name])) {
if (room._id !== room.name && this.triggers[`#${ room.name }`]) {
for (const trigger of Object.values(this.triggers[`#${ room.name }`])) {
triggersToExecute.push(trigger);
}
}
@ -529,10 +529,10 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
}
logger.outgoing.debug(`Found ${triggersToExecute.length} to iterate over and see if the match the event.`);
logger.outgoing.debug(`Found ${ triggersToExecute.length } to iterate over and see if the match the event.`);
for (const triggerToExecute of triggersToExecute) {
logger.outgoing.debug(`Is ${triggerToExecute.name} enabled, ${triggerToExecute.enabled}, and what is the event? ${triggerToExecute.event}`);
logger.outgoing.debug(`Is ${ triggerToExecute.name } enabled, ${ triggerToExecute.enabled }, and what is the event? ${ triggerToExecute.event }`);
if (triggerToExecute.enabled === true && triggerToExecute.event === event) {
this.executeTrigger(triggerToExecute, argObject);
}
@ -546,7 +546,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
executeTriggerUrl(url, trigger, { event, message, room, owner, user }, theHistoryId, tries = 0) {
logger.outgoing.debug(`Starting to execute trigger: ${trigger.name} (${trigger._id})`);
logger.outgoing.debug(`Starting to execute trigger: ${ trigger.name } (${ trigger._id })`);
let word;
//Not all triggers/events support triggerWords
@ -564,7 +564,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
// Stop if there are triggerWords but none match
if (!word) {
logger.outgoing.debug(`The trigger word which "${trigger.name}" was expecting could not be found, not executing.`);
logger.outgoing.debug(`The trigger word which "${ trigger.name }" was expecting could not be found, not executing.`);
return;
}
}
@ -584,7 +584,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
this.mapEventArgsToData(data, { trigger, event, message, room, owner, user });
this.updateHistory({ historyId, step: 'mapped-args-to-data', data, triggerWord: word });
logger.outgoing.info(`Will be executing the Integration "${trigger.name}" to the url: ${url}`);
logger.outgoing.info(`Will be executing the Integration "${ trigger.name }" to the url: ${ url }`);
logger.outgoing.debug(data);
let opts = {
@ -626,9 +626,9 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
this.updateHistory({ historyId, step: 'pre-http-call', url: opts.url, httpCallData: opts.data });
HTTP.call(opts.method, opts.url, opts, (error, result) => {
if (!result) {
logger.outgoing.warn(`Result for the Integration ${trigger.name} to ${url} is empty`);
logger.outgoing.warn(`Result for the Integration ${ trigger.name } to ${ url } is empty`);
} else {
logger.outgoing.info(`Status code for the Integration ${trigger.name} to ${url} is ${result.statusCode}`);
logger.outgoing.info(`Status code for the Integration ${ trigger.name } to ${ url } is ${ result.statusCode }`);
}
this.updateHistory({ historyId, step: 'after-http-call', httpError: error, httpResult: result });
@ -662,24 +662,24 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
// if the result contained nothing or wasn't a successful statusCode
if (!result || !this.successResults.includes(result.statusCode)) {
if (error) {
logger.outgoing.error(`Error for the Integration "${trigger.name}" to ${url} is:`);
logger.outgoing.error(`Error for the Integration "${ trigger.name }" to ${ url } is:`);
logger.outgoing.error(error);
}
if (result) {
logger.outgoing.error(`Error for the Integration "${trigger.name}" to ${url} is:`);
logger.outgoing.error(`Error for the Integration "${ trigger.name }" to ${ url } is:`);
logger.outgoing.error(result);
if (result.statusCode === 410) {
this.updateHistory({ historyId, step: 'after-process-http-status-410', error: true });
logger.outgoing.error(`Disabling the Integration "${trigger.name}" because the status code was 401 (Gone).`);
logger.outgoing.error(`Disabling the Integration "${ trigger.name }" because the status code was 401 (Gone).`);
RocketChat.models.Integrations.update({ _id: trigger._id }, { $set: { enabled: false }});
return;
}
if (result.statusCode === 500) {
this.updateHistory({ historyId, step: 'after-process-http-status-500', error: true });
logger.outgoing.error(`Error "500" for the Integration "${trigger.name}" to ${url}.`);
logger.outgoing.error(`Error "500" for the Integration "${ trigger.name }" to ${ url }.`);
logger.outgoing.error(result.content);
return;
}
@ -687,7 +687,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
if (trigger.retryFailedCalls) {
if (tries < trigger.retryCount && trigger.retryDelay) {
this.updateHistory({ historyId, error: true, step: `going-to-retry-${tries + 1}` });
this.updateHistory({ historyId, error: true, step: `going-to-retry-${ tries + 1 }` });
let waitTime;
@ -710,7 +710,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
return;
}
logger.outgoing.info(`Trying the Integration ${trigger.name} to ${url} again in ${waitTime} milliseconds.`);
logger.outgoing.info(`Trying the Integration ${ trigger.name } to ${ url } again in ${ waitTime } milliseconds.`);
Meteor.setTimeout(() => {
this.executeTriggerUrl(url, trigger, { event, message, room, owner, user }, historyId, tries + 1);
}, waitTime);

@ -18,13 +18,13 @@ Package.onUse(function(api) {
api.addFiles('client/style.css', 'client');
const katexPath = 'node_modules/katex/dist/';
api.addFiles(katexPath + 'katex.min.css', 'client');
api.addFiles(`${ katexPath }katex.min.css`, 'client');
const _ = Npm.require('underscore');
const fs = Npm.require('fs');
const fontsPath = katexPath + 'fonts/';
const fontFiles = _.map(fs.readdirSync('packages/rocketchat-katex/' + fontsPath), function(filename) {
const fontsPath = `${ katexPath }fonts/`;
const fontFiles = _.map(fs.readdirSync(`packages/rocketchat-katex/${ fontsPath }`), function(filename) {
return fontsPath + filename;
});

@ -57,7 +57,7 @@ LDAP = class LDAP {
let replied = false;
const connectionOptions = {
url: `${self.options.host}:${self.options.port}`,
url: `${ self.options.host }:${ self.options.port }`,
timeout: 1000 * 60 * 10,
connectTimeout: self.options.connect_timeout,
idleTimeout: self.options.idle_timeout,
@ -84,10 +84,10 @@ LDAP = class LDAP {
}
if (self.options.encryption === 'ssl') {
connectionOptions.url = `ldaps://${connectionOptions.url}`;
connectionOptions.url = `ldaps://${ connectionOptions.url }`;
connectionOptions.tlsOptions = tlsOptions;
} else {
connectionOptions.url = `ldap://${connectionOptions.url}`;
connectionOptions.url = `ldap://${ connectionOptions.url }`;
}
logger.connection.info('Connecting', connectionOptions.url);
@ -173,24 +173,24 @@ LDAP = class LDAP {
const filter = ['(&'];
if (self.options.domain_search_object_category !== '') {
filter.push(`(objectCategory=${self.options.domain_search_object_category})`);
filter.push(`(objectCategory=${ self.options.domain_search_object_category })`);
}
if (self.options.domain_search_object_class !== '') {
filter.push(`(objectclass=${self.options.domain_search_object_class})`);
filter.push(`(objectclass=${ self.options.domain_search_object_class })`);
}
if (self.options.domain_search_filter !== '') {
filter.push(`(${self.options.domain_search_filter})`);
filter.push(`(${ self.options.domain_search_filter })`);
}
const domain_search_user_id = self.options.domain_search_user_id.split(',');
if (domain_search_user_id.length === 1) {
filter.push(`(${domain_search_user_id[0]}=#{username})`);
filter.push(`(${ domain_search_user_id[0] }=#{username})`);
} else {
filter.push('(|');
domain_search_user_id.forEach((item) => {
filter.push(`(${item}=#{username})`);
filter.push(`(${ item }=#{username})`);
});
filter.push(')');
}
@ -326,15 +326,15 @@ LDAP = class LDAP {
const filter = ['(&'];
if (self.options.group_filter_object_class !== '') {
filter.push(`(objectclass=${self.options.group_filter_object_class})`);
filter.push(`(objectclass=${ self.options.group_filter_object_class })`);
}
if (self.options.group_filter_group_member_attribute !== '') {
filter.push(`(${self.options.group_filter_group_member_attribute}=${self.options.group_filter_group_member_format})`);
filter.push(`(${ self.options.group_filter_group_member_attribute }=${ self.options.group_filter_group_member_format })`);
}
if (self.options.group_filter_group_id_attribute !== '') {
filter.push(`(${self.options.group_filter_group_id_attribute}=${self.options.group_filter_group_name})`);
filter.push(`(${ self.options.group_filter_group_id_attribute }=${ self.options.group_filter_group_name })`);
}
filter.push(')');

@ -69,7 +69,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) {
return fallbackDefaultAccountSystem(self, loginRequest.username, loginRequest.ldapPass);
}
throw new Meteor.Error('LDAP-login-error', 'LDAP Authentication failed with provided username ['+loginRequest.username+']');
throw new Meteor.Error('LDAP-login-error', `LDAP Authentication failed with provided username [${ loginRequest.username }]`);
}
let username;
@ -111,7 +111,7 @@ Accounts.registerLoginHandler('ldap', function(loginRequest) {
if (user) {
if (user.ldap !== true && RocketChat.settings.get('LDAP_Merge_Existing_Users') !== true) {
logger.info('User exists without "ldap: true"');
throw new Meteor.Error('LDAP-login-error', 'LDAP Authentication succeded, but there\'s already an existing user with provided username ['+username+'] in Mongo.');
throw new Meteor.Error('LDAP-login-error', `LDAP Authentication succeded, but there's already an existing user with provided username [${ username }] in Mongo.`);
}
logger.info('Logging user');

@ -140,8 +140,8 @@ syncUserData = function syncUserData(user, ldapUser) {
if (avatar) {
logger.info('Syncing user avatar');
const rs = RocketChatFile.bufferToStream(avatar);
RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(`${user.username}.jpg`));
const ws = RocketChatFileAvatarInstance.createWriteStream(encodeURIComponent(`${user.username}.jpg`), 'image/jpeg');
RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(`${ user.username }.jpg`));
const ws = RocketChatFileAvatarInstance.createWriteStream(encodeURIComponent(`${ user.username }.jpg`), 'image/jpeg');
ws.on('end', Meteor.bindEnvironment(function() {
Meteor.setTimeout(function() {
RocketChat.models.Users.setAvatarOrigin(user._id, 'ldap');
@ -165,7 +165,7 @@ addLdapUser = function addLdapUser(ldapUser, username, password) {
} else if (ldapUser.object.mail && ldapUser.object.mail.indexOf('@') > -1) {
userObject.email = ldapUser.object.mail;
} else if (RocketChat.settings.get('LDAP_Default_Domain') !== '') {
userObject.email = username + '@' + RocketChat.settings.get('LDAP_Default_Domain');
userObject.email = `${ username }@${ RocketChat.settings.get('LDAP_Default_Domain') }`;
} else {
const error = new Meteor.Error('LDAP-login-error', 'LDAP Authentication succeded, there is no email to create an account. Have you tried setting your Default Domain in LDAP Settings?');
logger.error(error);

@ -4,9 +4,9 @@ OAuth.launchLogin = _.wrap(OAuth.launchLogin, function(func, options) {
const proxy = RocketChat.settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(',');
if (proxy.includes(options.loginService)) {
const redirect_uri = options.loginUrl.match(/(&redirect_uri=)([^&]+|$)/)[2];
options.loginUrl = options.loginUrl.replace(/(&redirect_uri=)([^&]+|$)/, `$1${encodeURIComponent(RocketChat.settings.get('Accounts_OAuth_Proxy_host'))}/oauth_redirect`);
options.loginUrl = options.loginUrl.replace(/(&state=)([^&]+|$)/, `$1${redirect_uri}!$2`);
options.loginUrl = RocketChat.settings.get('Accounts_OAuth_Proxy_host')+'/redirect/'+encodeURIComponent(options.loginUrl);
options.loginUrl = options.loginUrl.replace(/(&redirect_uri=)([^&]+|$)/, `$1${ encodeURIComponent(RocketChat.settings.get('Accounts_OAuth_Proxy_host')) }/oauth_redirect`);
options.loginUrl = options.loginUrl.replace(/(&state=)([^&]+|$)/, `$1${ redirect_uri }!$2`);
options.loginUrl = `${ RocketChat.settings.get('Accounts_OAuth_Proxy_host') }/redirect/${ encodeURIComponent(options.loginUrl) }`;
}
return func(options);

@ -49,7 +49,7 @@ RocketChatTabBar = class RocketChatTabBar {
button = RocketChat.TabBar.getButton(button);
}
if (button.width) {
$('.flex-tab').css('width', `${button.width}px`);
$('.flex-tab').css('width', `${ button.width }px`);
} else {
$('.flex-tab').css('width', '');
}

@ -105,9 +105,9 @@ class CachedCollection {
this.ready = new ReactiveVar(false);
this.name = name;
this.methodName = methodName || `${name}/get`;
this.syncMethodName = syncMethodName || `${name}/get`;
this.eventName = eventName || `${name}-changed`;
this.methodName = methodName || `${ name }/get`;
this.syncMethodName = syncMethodName || `${ name }/get`;
this.eventName = eventName || `${ name }-changed`;
this.eventType = eventType;
this.useSync = useSync;
this.useCache = useCache;
@ -136,16 +136,16 @@ class CachedCollection {
log(...args) {
if (this.debug === true) {
console.log(`CachedCollection ${this.name} =>`, ...args);
console.log(`CachedCollection ${ this.name } =>`, ...args);
}
}
countQueries() {
this.log(`${Object.keys(this.collection._collection.queries).length} queries`);
this.log(`${ Object.keys(this.collection._collection.queries).length } queries`);
}
recomputeCollectionQueries() {
this.log(`recomputing ${Object.keys(this.collection._collection.queries).length} queries`);
this.log(`recomputing ${ Object.keys(this.collection._collection.queries).length } queries`);
_.each(this.collection._collection.queries, (query) => {
this.collection._collection._recomputeResults(query);
});
@ -179,7 +179,7 @@ class CachedCollection {
}
if (data && data.records && data.records.length > 0) {
this.log(`${data.records.length} records loaded from cache`);
this.log(`${ data.records.length } records loaded from cache`);
data.records.forEach((record) => {
record.__cache__ = true;
this.collection.upsert({ _id: record._id }, _.omit(record, '_id'));
@ -201,7 +201,7 @@ class CachedCollection {
loadFromServer(callback = () => {}) {
Meteor.call(this.methodName, (error, data) => {
this.log(`${data.length} records loaded from server`);
this.log(`${ data.length } records loaded from server`);
data.forEach((record) => {
delete record.$loki;
this.collection.upsert({ _id: record._id }, _.omit(record, '_id'));
@ -232,18 +232,18 @@ class CachedCollection {
return false;
}
this.log(`syncing from ${this.updatedAt}`);
this.log(`syncing from ${ this.updatedAt }`);
Meteor.call(this.syncMethodName, this.updatedAt, (error, data) => {
let changes = [];
if (data.update && data.update.length > 0) {
this.log(`${data.update.length} records updated in sync`);
this.log(`${ data.update.length } records updated in sync`);
changes.push(...data.update);
}
if (data.remove && data.remove.length > 0) {
this.log(`${data.remove.length} records removed in sync`);
this.log(`${ data.remove.length } records removed in sync`);
changes.push(...data.remove);
}

@ -14,5 +14,5 @@ RocketChat.getURL = (path, { cdn = true, full = false } = {}) => {
basePath = pathPrefix;
}
return basePath + '/' + finalPath;
return `${ basePath }/${ finalPath }`;
};

@ -1,3 +1,3 @@
RocketChat.checkEmailAvailability = function(email) {
return !Meteor.users.findOne({ 'emails.address': { $regex : new RegExp('^' + s.trim(s.escapeRegExp(email)) + '$', 'i') } });
return !Meteor.users.findOne({ 'emails.address': { $regex : new RegExp(`^${ s.trim(s.escapeRegExp(email)) }$`, 'i') } });
};

@ -15,7 +15,7 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData
let nameValidation;
try {
nameValidation = new RegExp('^' + RocketChat.settings.get('UTF8_Names_Validation') + '$');
nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`);
} catch (error) {
nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$');
}
@ -33,9 +33,9 @@ RocketChat.createRoom = function(type, name, owner, members, readOnly, extraData
let room = RocketChat.models.Rooms.findOneByName(name);
if (room) {
if (room.archived) {
throw new Meteor.Error('error-archived-duplicate-name', 'There\'s an archived channel with name ' + name, { function: 'RocketChat.createRoom', room_name: name });
throw new Meteor.Error('error-archived-duplicate-name', `There's an archived channel with name ${ name }`, { function: 'RocketChat.createRoom', room_name: name });
} else {
throw new Meteor.Error('error-duplicate-channel-name', 'A channel with name \'' + name + '\' exists', { function: 'RocketChat.createRoom', room_name: name });
throw new Meteor.Error('error-duplicate-channel-name', `A channel with name '${ name }' exists`, { function: 'RocketChat.createRoom', room_name: name });
}
}

@ -22,7 +22,7 @@ RocketChat.deleteUser = function(userId) {
// removes user's avatar
if (user.avatarOrigin === 'upload' || user.avatarOrigin === 'url') {
RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(user.username + '.jpg'));
RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(`${ user.username }.jpg`));
}
RocketChat.models.Integrations.disableByUserId(userId); // Disables all the integrations which rely on the user being deleted.

@ -14,19 +14,19 @@ RocketChat.saveCustomFields = function(userId, formData) {
customFields[fieldName] = formData[fieldName];
if (field.required && !formData[fieldName]) {
throw new Meteor.Error('error-user-registration-custom-field', `Field ${fieldName} is required`, { method: 'registerUser' });
throw new Meteor.Error('error-user-registration-custom-field', `Field ${ fieldName } is required`, { method: 'registerUser' });
}
if (field.type === 'select' && field.options.indexOf(formData[fieldName]) === -1) {
throw new Meteor.Error('error-user-registration-custom-field', `Value for field ${fieldName} is invalid`, { method: 'registerUser' });
throw new Meteor.Error('error-user-registration-custom-field', `Value for field ${ fieldName } is invalid`, { method: 'registerUser' });
}
if (field.maxLength && formData[fieldName].length > field.maxLength) {
throw new Meteor.Error('error-user-registration-custom-field', `Max length of field ${fieldName} ${field.maxLength}`, { method: 'registerUser' });
throw new Meteor.Error('error-user-registration-custom-field', `Max length of field ${ fieldName } ${ field.maxLength }`, { method: 'registerUser' });
}
if (field.minLength && formData[fieldName].length < field.minLength) {
throw new Meteor.Error('error-user-registration-custom-field', `Min length of field ${fieldName} ${field.minLength}`, { method: 'registerUser' });
throw new Meteor.Error('error-user-registration-custom-field', `Min length of field ${ fieldName } ${ field.minLength }`, { method: 'registerUser' });
}
});

@ -30,13 +30,13 @@ RocketChat.saveUser = function(userId, userData) {
let nameValidation;
try {
nameValidation = new RegExp('^' + RocketChat.settings.get('UTF8_Names_Validation') + '$');
nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`);
} catch (e) {
nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$');
}
if (userData.username && !nameValidation.test(userData.username)) {
throw new Meteor.Error('error-input-is-not-a-valid-field', `${_.escape(userData.username)} is not a valid username`, { method: 'insertOrUpdateUser', input: userData.username, field: 'Username' });
throw new Meteor.Error('error-input-is-not-a-valid-field', `${ _.escape(userData.username) } is not a valid username`, { method: 'insertOrUpdateUser', input: userData.username, field: 'Username' });
}
if (!userData._id && !userData.password) {
@ -45,11 +45,11 @@ RocketChat.saveUser = function(userId, userData) {
if (!userData._id) {
if (!RocketChat.checkUsernameAvailability(userData.username)) {
throw new Meteor.Error('error-field-unavailable', `${_.escape(userData.username)} is already in use :(`, { method: 'insertOrUpdateUser', field: userData.username });
throw new Meteor.Error('error-field-unavailable', `${ _.escape(userData.username) } is already in use :(`, { method: 'insertOrUpdateUser', field: userData.username });
}
if (userData.email && !RocketChat.checkEmailAvailability(userData.email)) {
throw new Meteor.Error('error-field-unavailable', `${_.escape(userData.email)} is already in use :(`, { method: 'insertOrUpdateUser', field: userData.email });
throw new Meteor.Error('error-field-unavailable', `${ _.escape(userData.email) } is already in use :(`, { method: 'insertOrUpdateUser', field: userData.email });
}
RocketChat.validateEmailDomain(userData.email);
@ -116,7 +116,7 @@ RocketChat.saveUser = function(userId, userData) {
try {
Email.send(email);
} catch (error) {
throw new Meteor.Error('error-email-send-failed', 'Error trying to send email: ' + error.message, { function: 'RocketChat.saveUser', message: error.message });
throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${ error.message }`, { function: 'RocketChat.saveUser', message: error.message });
}
});
}

@ -19,7 +19,7 @@ RocketChat._setEmail = function(userId, email) {
// Check email availability
if (!RocketChat.checkEmailAvailability(email)) {
throw new Meteor.Error('error-field-unavailable', email + ' is already in use :(', { function: '_setEmail', field: email });
throw new Meteor.Error('error-field-unavailable', `${ email } is already in use :(`, { function: '_setEmail', field: email });
}
// Set new email

@ -11,19 +11,19 @@ RocketChat.setUserAvatar = function(user, dataURI, contentType, service) {
result = HTTP.get(dataURI, { npmRequestOptions: {encoding: 'binary'} });
} catch (error) {
if (error.response.statusCode !== 404) {
console.log(`Error while handling the setting of the avatar from a url (${dataURI}) for ${user.username}:`, error);
throw new Meteor.Error('error-avatar-url-handling', `Error while handling avatar setting from a URL (${dataURI}) for ${user.username}`, { function: 'RocketChat.setUserAvatar', url: dataURI, username: user.username });
console.log(`Error while handling the setting of the avatar from a url (${ dataURI }) for ${ user.username }:`, error);
throw new Meteor.Error('error-avatar-url-handling', `Error while handling avatar setting from a URL (${ dataURI }) for ${ user.username }`, { function: 'RocketChat.setUserAvatar', url: dataURI, username: user.username });
}
}
if (result.statusCode !== 200) {
console.log(`Not a valid response, ${result.statusCode}, from the avatar url: ${dataURI}`);
throw new Meteor.Error('error-avatar-invalid-url', `Invalid avatar URL: ${dataURI}`, { function: 'RocketChat.setUserAvatar', url: dataURI });
console.log(`Not a valid response, ${ result.statusCode }, from the avatar url: ${ dataURI }`);
throw new Meteor.Error('error-avatar-invalid-url', `Invalid avatar URL: ${ dataURI }`, { function: 'RocketChat.setUserAvatar', url: dataURI });
}
if (!/image\/.+/.test(result.headers['content-type'])) {
console.log(`Not a valid content-type from the provided url, ${result.headers['content-type']}, from the avatar url: ${dataURI}`);
throw new Meteor.Error('error-avatar-invalid-url', `Invalid avatar URL: ${dataURI}`, { function: 'RocketChat.setUserAvatar', url: dataURI });
console.log(`Not a valid content-type from the provided url, ${ result.headers['content-type'] }, from the avatar url: ${ dataURI }`);
throw new Meteor.Error('error-avatar-invalid-url', `Invalid avatar URL: ${ dataURI }`, { function: 'RocketChat.setUserAvatar', url: dataURI });
}
encoding = 'binary';
@ -40,8 +40,8 @@ RocketChat.setUserAvatar = function(user, dataURI, contentType, service) {
}
const rs = RocketChatFile.bufferToStream(new Buffer(image, encoding));
RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(`${user.username}.jpg`));
const ws = RocketChatFileAvatarInstance.createWriteStream(encodeURIComponent(`${user.username}.jpg`), contentType);
RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(`${ user.username }.jpg`));
const ws = RocketChatFileAvatarInstance.createWriteStream(encodeURIComponent(`${ user.username }.jpg`), contentType);
ws.on('end', Meteor.bindEnvironment(function() {
Meteor.setTimeout(function() {
RocketChat.models.Users.setAvatarOrigin(user._id, service);

@ -2,7 +2,7 @@
class PushNotification {
getNotificationId(roomId) {
const serverId = RocketChat.settings.get('uniqueID');
return this.hash(`${serverId}|${roomId}`); // hash
return this.hash(`${ serverId }|${ roomId }`); // hash
}
hash(str) {
@ -19,10 +19,10 @@ class PushNotification {
send({ roomName, roomId, username, message, usersTo, payload }) {
let title;
if (roomName && roomName !== '') {
title = `${roomName}`;
message = `${username}: ${message}`;
title = `${ roomName }`;
message = `${ username }: ${ message }`;
} else {
title = `${username}`;
title = `${ username }`;
}
const icon = RocketChat.settings.get('Assets_favicon_192').url || RocketChat.settings.get('Assets_favicon_192').defaultUrl;
const config = {

@ -10,7 +10,7 @@ RocketChat.settings.get('Bugsnag_api_key', (key, value) => {
const notify = function(message, stack) {
if (typeof stack === 'string') {
message += ' ' + stack;
message += ` ${ stack }`;
}
let options = {};
if (RocketChat.Info) {

@ -103,7 +103,7 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) {
let push_room;
if (RocketChat.settings.get('Push_show_username_room')) {
push_username = user.username;
push_room = '#' + room.name;
push_room = `#${ room.name }`;
} else {
push_username = '';
push_room = '';
@ -123,12 +123,12 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) {
// Always notify Sandstorm
if (userOfMention != null) {
RocketChat.Sandstorm.notify(message, [userOfMention._id],
'@' + user.username + ': ' + message.msg, 'privateMessage');
`@${ user.username }: ${ message.msg }`, 'privateMessage');
}
if ((userOfMention != null) && canBeNotified(userOfMentionId, 'mobile')) {
RocketChat.Notifications.notifyUser(userOfMention._id, 'notification', {
title: '@' + user.username,
title: `@${ user.username }`,
text: message.msg,
duration: settings.desktopNotificationDurations[userOfMention._id],
payload: {
@ -273,9 +273,9 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) {
if (userIdsToNotify.length > 0) {
for (const usersOfMentionId of userIdsToNotify) {
let title = '@' + user.username;
let title = `@${ user.username }`;
if (room.name) {
title += ' @ #' + room.name;
title += ` @ #${ room.name }`;
}
RocketChat.Notifications.notifyUser(usersOfMentionId, 'notification', {
title,
@ -318,10 +318,10 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) {
const allUserIdsToNotify = _.unique(userIdsToNotify.concat(userIdsToPushNotify));
if (room.t === 'p') {
RocketChat.Sandstorm.notify(message, allUserIdsToNotify,
'@' + user.username + ': ' + message.msg, 'privateMessage');
`@${ user.username }: ${ message.msg }`, 'privateMessage');
} else {
RocketChat.Sandstorm.notify(message, allUserIdsToNotify,
'@' + user.username + ': ' + message.msg, 'message');
`@${ user.username }: ${ message.msg }`, 'message');
}
}

@ -21,7 +21,7 @@ RocketChat.settings.get('Accounts_UseDNSDomainCheck', function(key, value) {
RocketChat.validateEmailDomain = function(email) {
const emailValidation = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (!emailValidation.test(email)) {
throw new Meteor.Error('error-invalid-email', 'Invalid email ' + email, { function: 'RocketChat.validateEmailDomain', email });
throw new Meteor.Error('error-invalid-email', `Invalid email ${ email }`, { function: 'RocketChat.validateEmailDomain', email });
}
const emailDomain = email.substr(email.lastIndexOf('@') + 1);

@ -16,19 +16,19 @@ Meteor.methods({
name = name.toLowerCase().replace(/[^a-z0-9_]/g, '');
name = s.capitalize(name);
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Enable', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-url` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'URL', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-token_path` , '/oauth/token' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Token_Path', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-identity_path` , '/me' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Path', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-authorize_path` , '/oauth/authorize', { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Authorize_Path', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-scope` , 'openid' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Scope', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-token_sent_via` , 'payload' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Token_Sent_Via', persistent: true, values: [ { key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' } ] });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-id` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_id', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-secret` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Secret', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-login_style` , 'popup' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [ { key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' } ] });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-button_label_text` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-button_label_color`, '#FFFFFF' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-button_color` , '#13679A' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-username_field` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Username_Field', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${name}-merge_users` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${name}`, i18nLabel: 'Accounts_OAuth_Custom_Merge_Users', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Enable', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-url` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'URL', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-token_path` , '/oauth/token' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Path', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-identity_path` , '/me' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Identity_Path', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-authorize_path` , '/oauth/authorize', { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Authorize_Path', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-scope` , 'openid' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Scope', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-token_sent_via` , 'payload' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Token_Sent_Via', persistent: true, values: [ { key: 'header', i18nLabel: 'Header' }, { key: 'payload', i18nLabel: 'Payload' } ] });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-id` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_id', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-secret` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Secret', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-login_style` , 'popup' , { type: 'select' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Login_Style', persistent: true, values: [ { key: 'redirect', i18nLabel: 'Redirect' }, { key: 'popup', i18nLabel: 'Popup' }, { key: '', i18nLabel: 'Default' } ] });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_label_text` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_label_color`, '#FFFFFF' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-button_color` , '#13679A' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Button_Color', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-username_field` , '' , { type: 'string' , group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Username_Field', persistent: true });
RocketChat.settings.add(`Accounts_OAuth_Custom-${ name }-merge_users` , false , { type: 'boolean', group: 'OAuth', section: `Custom OAuth: ${ name }`, i18nLabel: 'Accounts_OAuth_Custom_Merge_Users', persistent: true });
}});

@ -13,20 +13,20 @@ Meteor.methods({
name = name.toLowerCase().replace(/[^a-z0-9_]/g, '');
name = s.capitalize(name);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-url`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-token_path`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-identity_path`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-authorize_path`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-scope`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-token_sent_via`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-id`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-secret`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-button_label_text`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-button_label_color`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-button_color`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-login_style`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-username_field`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${name}-merge_users`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-url`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-token_path`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-identity_path`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-authorize_path`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-scope`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-token_sent_via`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-id`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-secret`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_text`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_label_color`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-button_color`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-login_style`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-username_field`);
RocketChat.settings.removeById(`Accounts_OAuth_Custom-${ name }-merge_users`);
}
});

@ -19,23 +19,23 @@ Meteor.methods({
let nameValidation;
try {
nameValidation = new RegExp(`^${RocketChat.settings.get('UTF8_Names_Validation')}$`);
nameValidation = new RegExp(`^${ RocketChat.settings.get('UTF8_Names_Validation') }$`);
} catch (error) {
nameValidation = new RegExp('^[0-9a-zA-Z-_.]+$');
}
if (!nameValidation.test(username)) {
throw new Meteor.Error('username-invalid', `${_.escape(username)} is not a valid username, use only letters, numbers, dots, hyphens and underscores`);
throw new Meteor.Error('username-invalid', `${ _.escape(username) } is not a valid username, use only letters, numbers, dots, hyphens and underscores`);
}
if (user.username !== undefined) {
if (!username.toLowerCase() === user.username.toLowerCase()) {
if (!RocketChat.checkUsernameAvailability(username)) {
throw new Meteor.Error('error-field-unavailable', `<strong>${_.escape(username)}</strong> is already in use :(`, { method: 'setUsername', field: username });
throw new Meteor.Error('error-field-unavailable', `<strong>${ _.escape(username) }</strong> is already in use :(`, { method: 'setUsername', field: username });
}
}
} else if (!RocketChat.checkUsernameAvailability(username)) {
throw new Meteor.Error('error-field-unavailable', `<strong>${_.escape(username)}</strong> is already in use :(`, { method: 'setUsername', field: username });
throw new Meteor.Error('error-field-unavailable', `<strong>${ _.escape(username) }</strong> is already in use :(`, { method: 'setUsername', field: username });
}
if (!RocketChat.setUsername(user._id, username)) {

@ -90,7 +90,7 @@ function traceMethodCalls(target) {
setInterval(function() {
for (const property in target._stats) {
if (target._stats.hasOwnProperty(property) && target._stats[property].time > 0) {
const tags = [`property:${property}`, `collection:${target.collectionName}`];
const tags = [`property:${ property }`, `collection:${ target.collectionName }`];
RocketChat.statsTracker.timing('cache.methods.time', target._stats[property].avg, tags);
RocketChat.statsTracker.increment('cache.methods.totalTime', target._stats[property].time, tags);
RocketChat.statsTracker.increment('cache.methods.count', target._stats[property].calls, tags);
@ -168,7 +168,7 @@ class ModelsBaseCache extends EventEmitter {
join({join, field, link, multi}) {
if (!RocketChat.models[join]) {
console.log(`Invalid cache model ${join}`);
console.log(`Invalid cache model ${ join }`);
return;
}
@ -240,8 +240,8 @@ class ModelsBaseCache extends EventEmitter {
localRecord[field] = record;
}
this.emit(`join:${field}:inserted`, localRecord, record);
this.emit(`join:${field}:changed`, 'inserted', localRecord, record);
this.emit(`join:${ field }:inserted`, localRecord, record);
this.emit(`join:${ field }:changed`, 'inserted', localRecord, record);
}
}
@ -265,8 +265,8 @@ class ModelsBaseCache extends EventEmitter {
localRecord[field] = record;
}
this.emit(`join:${field}:inserted`, localRecord, record);
this.emit(`join:${field}:changed`, 'inserted', localRecord, record);
this.emit(`join:${ field }:inserted`, localRecord, record);
this.emit(`join:${ field }:changed`, 'inserted', localRecord, record);
}
}
@ -296,8 +296,8 @@ class ModelsBaseCache extends EventEmitter {
localRecord[field] = undefined;
}
this.emit(`join:${field}:removed`, localRecord, record);
this.emit(`join:${field}:changed`, 'removed', localRecord, record);
this.emit(`join:${ field }:removed`, localRecord, record);
this.emit(`join:${ field }:changed`, 'removed', localRecord, record);
}
}
@ -324,7 +324,7 @@ class ModelsBaseCache extends EventEmitter {
addToIndex(indexName, record) {
const index = this.indexes[indexName];
if (!index) {
console.error(`Index not defined ${indexName}`);
console.error(`Index not defined ${ indexName }`);
return;
}
@ -359,7 +359,7 @@ class ModelsBaseCache extends EventEmitter {
removeFromIndex(indexName, record) {
const index = this.indexes[indexName];
if (!this.indexes[indexName]) {
console.error(`Index not defined ${indexName}`);
console.error(`Index not defined ${ indexName }`);
return;
}
@ -448,7 +448,7 @@ class ModelsBaseCache extends EventEmitter {
this.insert(data[i]);
}
console.log(String(data.length), 'records load from', this.collectionName);
RocketChat.statsTracker.timing('cache.load', RocketChat.statsTracker.now() - time, [`collection:${this.collectionName}`]);
RocketChat.statsTracker.timing('cache.load', RocketChat.statsTracker.now() - time, [`collection:${ this.collectionName }`]);
this.startSync();
this.loaded = true;

@ -3,7 +3,7 @@
const baseName = 'rocketchat_';
import {EventEmitter} from 'events';
const trash = new Mongo.Collection(baseName + '_trash');
const trash = new Mongo.Collection(`${ baseName }_trash`);
try {
trash._ensureIndex({ collection: 1 });
trash._ensureIndex({ _deletedAt: 1 }, { expireAfterSeconds: 60 * 60 * 24 * 30 });

@ -6,7 +6,7 @@ function getIdentity(accessToken) {
'https://www.googleapis.com/oauth2/v1/userinfo',
{params: {access_token: accessToken}}).data;
} catch (err) {
throw _.extend(new Error('Failed to fetch identity from Google. ' + err.message), {response: err.response});
throw _.extend(new Error(`Failed to fetch identity from Google. ${ err.message }`), {response: err.response});
}
}
@ -16,7 +16,7 @@ function getScopes(accessToken) {
'https://www.googleapis.com/oauth2/v1/tokeninfo',
{params: {access_token: accessToken}}).data.scope.split(' ');
} catch (err) {
throw _.extend(new Error('Failed to fetch tokeninfo from Google. ' + err.message), {response: err.response});
throw _.extend(new Error(`Failed to fetch tokeninfo from Google. ${ err.message }`), {response: err.response});
}
}

@ -22,7 +22,7 @@ Accounts.registerLoginHandler(function(options) {
// Skip everything if there's no service set by the oauth middleware
if (!service) {
throw new Error(`Unexpected AccessToken service ${options.serviceName}`);
throw new Error(`Unexpected AccessToken service ${ options.serviceName }`);
}
// Make sure we're configured
@ -38,7 +38,7 @@ Accounts.registerLoginHandler(function(options) {
type: 'oauth',
error: new Meteor.Error(
Accounts.LoginCancelledError.numericError,
`No registered oauth service found for: ${service.serviceName}`
`No registered oauth service found for: ${ service.serviceName }`
)
};
}

@ -3,7 +3,7 @@
OAuth._redirectUri = _.wrap(OAuth._redirectUri, function(func, serviceName, ...args) {
const proxy = RocketChat.settings.get('Accounts_OAuth_Proxy_services').replace(/\s/g, '').split(',');
if (proxy.includes(serviceName)) {
return RocketChat.settings.get('Accounts_OAuth_Proxy_host')+'/oauth_redirect';
return `${ RocketChat.settings.get('Accounts_OAuth_Proxy_host') }/oauth_redirect`;
} else {
return func(serviceName, ...args);
}

@ -5,7 +5,7 @@ RocketChat.statsTracker = new (class StatsTracker {
}
track(type, stats, ...args) {
this.dogstatsd[type](`RocketChat.${stats}`, ...args);
this.dogstatsd[type](`RocketChat.${ stats }`, ...args);
}
now() {

@ -76,7 +76,7 @@ RocketChat.roomTypes.add('d', 20, {
const subscription = RocketChat.models.Subscriptions.findOne({rid: roomId});
if (subscription == null) { return; }
return Session.get(`user_${subscription.name}_status`);
return Session.get(`user_${ subscription.name }_status`);
}
});

@ -7,7 +7,7 @@ LivechatVideoCall = new (class LivechatVideoCall {
if (typeof JitsiMeetExternalAPI === 'undefined') {
const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
$.getScript(`${prefix}/packages/rocketchat_videobridge/client/public/external_api.js`);
$.getScript(`${ prefix }/packages/rocketchat_videobridge/client/public/external_api.js`);
}
}

@ -56,7 +56,7 @@ Template.messages.helpers({
return {
multi: true,
selfTyping: MsgTyping.selfTyping.get(),
users: usernames.join(` ${t('and')} `)
users: usernames.join(` ${ t('and') } `)
};
},
agentData() {

@ -51,8 +51,8 @@ Template.livechatDepartmentForm.events({
const departmentAgents = [];
instance.selectedAgents.get().forEach((agent) => {
agent.count = instance.$('.count-' + agent.agentId).val();
agent.order = instance.$('.order-' + agent.agentId).val();
agent.count = instance.$(`.count-${ agent.agentId }`).val();
agent.order = instance.$(`.order-${ agent.agentId }`).val();
departmentAgents.push(agent);
});

@ -7,9 +7,9 @@ Template.livechatInstallation.helpers({
(function(w, d, s, u) {
w.RocketChat = function(c) { w.RocketChat._.push(c) }; w.RocketChat._ = []; w.RocketChat.url = u;
var h = d.getElementsByTagName(s)[0], j = d.createElement(s);
j.async = true; j.src = '${siteUrl}/packages/rocketchat_livechat/assets/rocketchat-livechat.min.js?_=201702160944';
j.async = true; j.src = '${ siteUrl }/packages/rocketchat_livechat/assets/rocketchat-livechat.min.js?_=201702160944';
h.parentNode.insertBefore(j, h);
})(window, document, 'script', '${siteUrl}/livechat');
})(window, document, 'script', '${ siteUrl }/livechat');
</script>
<!-- End of Rocket.Chat Livechat Script -->`;
}

@ -7,13 +7,13 @@ Template.livechatOfficeHours.helpers({
return LivechatOfficeHour.find({}, { sort: { code: 1 } });
},
startName(day) {
return day.day + '_start';
return `${ day.day }_start`;
},
finishName(day) {
return day.day + '_finish';
return `${ day.day }_finish`;
},
openName(day) {
return day.day + '_open';
return `${ day.day }_open`;
},
start(day) {
return Template.instance().dayVars[day.day].start.get();

@ -50,7 +50,7 @@ Template.livechatTriggersForm.events({
$('.each-condition').each(function() {
data.conditions.push({
name: $('.trigger-condition', this).val(),
value: $('.' + $('.trigger-condition', this).val() + '-value').val()
value: $(`.${ $('.trigger-condition', this).val() }-value`).val()
});
});
@ -66,7 +66,7 @@ Template.livechatTriggersForm.events({
} else {
data.actions.push({
name: $('.trigger-action', this).val(),
value: $('.' + $('.trigger-action', this).val() + '-value').val()
value: $(`.${ $('.trigger-action', this).val() }-value`).val()
});
}
});

@ -8,7 +8,7 @@ Template.externalSearch.events({
'click button.pick-message'(event, instance) {
event.preventDefault();
$('#chat-window-' + instance.roomId + ' .input-message').val(this.msg).focus();
$(`#chat-window-${ instance.roomId } .input-message`).val(this.msg).focus();
}
});

@ -20,7 +20,7 @@ Template.visitorHistory.helpers({
let title = moment(this.ts).format('L LTS');
if (this.label) {
title += ' - ' + this.label;
title += ` - ${ this.label }`;
}
return title;

@ -8,14 +8,14 @@ Template.visitorInfo.helpers({
const ua = new UAParser();
ua.setUA(user.userAgent);
user.os = ua.getOS().name + ' ' + ua.getOS().version;
user.os = `${ ua.getOS().name } ${ ua.getOS().version }`;
if (['Mac OS', 'iOS'].indexOf(ua.getOS().name) !== -1) {
user.osIcon = 'icon-apple';
} else {
user.osIcon = 'icon-' + ua.getOS().name.toLowerCase();
user.osIcon = `icon-${ ua.getOS().name.toLowerCase() }`;
}
user.browser = ua.getBrowser().name + ' ' + ua.getBrowser().version;
user.browserIcon = 'icon-' + ua.getBrowser().name.toLowerCase();
user.browser = `${ ua.getBrowser().name } ${ ua.getBrowser().version }`;
user.browserIcon = `icon-${ ua.getBrowser().name.toLowerCase() }`;
}
return user;

@ -12,7 +12,7 @@ Template.livechatTriggerAction.helpers({
Template.livechatTriggerAction.events({
'change .trigger-action'(e, instance) {
instance.$('.trigger-action-value ').addClass('hidden');
instance.$('.' + e.currentTarget.value).removeClass('hidden');
instance.$(`.${ e.currentTarget.value }`).removeClass('hidden');
}
});

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save