diff --git a/.eslintrc b/.eslintrc index e216b836fcd..0dd9f5a3deb 100644 --- a/.eslintrc +++ b/.eslintrc @@ -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, diff --git a/client/routes/router.js b/client/routes/router.js index fb7882344f0..9d5c7e6eb9d 100644 --- a/client/routes/router.js +++ b/client/routes/router.js @@ -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 }` }); } }); diff --git a/client/startup/roomObserve.js b/client/startup/roomObserve.js index ea3222a1fc6..f2b6bafd8ac 100644 --- a/client/startup/roomObserve.js +++ b/client/startup/roomObserve.js @@ -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); } }); }); diff --git a/client/startup/unread.js b/client/startup/unread.js index 702a826eb01..d624f08c0ed 100644 --- a/client/startup/unread.js +++ b/client/startup/unread.js @@ -78,6 +78,6 @@ Meteor.startup(function() { }); } - document.title = unread === '' ? siteName : `(${unread}) ${siteName}`; + document.title = unread === '' ? siteName : `(${ unread }) ${ siteName }`; }); }); diff --git a/client/startup/usersObserve.js b/client/startup/usersObserve.js index 76c2b4604e0..2dbddf94205 100644 --- a/client/startup/usersObserve.js +++ b/client/startup/usersObserve.js @@ -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); } }); diff --git a/lib/fileUpload.js b/lib/fileUpload.js index 2c52e75f6ad..fbb006f15b7 100644 --- a/lib/fileUpload.js +++ b/lib/fileUpload.js @@ -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({ diff --git a/packages/meteor-accounts-saml/saml_client.js b/packages/meteor-accounts-saml/saml_client.js index fef7b34d691..85502e72ad7 100644 --- a/packages/meteor-accounts-saml/saml_client.js +++ b/packages/meteor-accounts-saml/saml_client.js @@ -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) }`)); }); }; diff --git a/packages/meteor-accounts-saml/saml_rocketchat.js b/packages/meteor-accounts-saml/saml_rocketchat.js index 19132b755a0..31b5aeffa12 100644 --- a/packages/meteor-accounts-saml/saml_rocketchat.js +++ b/packages/meteor-accounts-saml/saml_rocketchat.js @@ -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`) } }; }; diff --git a/packages/meteor-accounts-saml/saml_server.js b/packages/meteor-accounts-saml/saml_server.js index b56aff3379f..67e32b7b30c 100644 --- a/packages/meteor-accounts-saml/saml_server.js +++ b/packages/meteor-accounts-saml/saml_server.js @@ -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 = '

Verified

'; if (err) { - content = '

Sorry, an annoying error occured

' + err + '
Close Window'; + content = `

Sorry, an annoying error occured

${ err }
Close Window`; } 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) { diff --git a/packages/meteor-accounts-saml/saml_utils.js b/packages/meteor-accounts-saml/saml_utils.js index 51d17d7afb6..5d8396e88ec 100644 --- a/packages/meteor-accounts-saml/saml_utils.js +++ b/packages/meteor-accounts-saml/saml_utils.js @@ -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 = - '' + - '' + this.options.issuer + '\n'; + `` + + `${ this.options.issuer }\n`; if (this.options.identifierFormat) { - request += '\n'; + request += `\n`; } request += @@ -107,29 +107,29 @@ SAML.prototype.generateLogoutRequest = function(options) { // sessionIndex: sessionIndex // --- NO SAMLsettings: ' + - '' + this.options.issuer + '' + - '' + options.nameID + '' + + let request = `${ '` + + `${ this.options.issuer }` + + `${ options.nameID }` + ''; - request = '' + - '' + this.options.issuer + '' + + `${ this.options.issuer }` + '' + - options.nameID + '' + - '' + options.sessionIndex + '' + + `SPNameQualifier="${ this.options.issuer }" ` + + `Format="${ this.options.identifierFormat }">${ + options.nameID }` + + `${ options.sessionIndex }` + ''; 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': { diff --git a/packages/rocketchat-analytics/client/loadScript.js b/packages/rocketchat-analytics/client/loadScript.js index a22e8afe317..ee5ff00380b 100644 --- a/packages/rocketchat-analytics/client/loadScript.js +++ b/packages/rocketchat-analytics/client/loadScript.js @@ -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); })(); } diff --git a/packages/rocketchat-analytics/client/trackEvents.js b/packages/rocketchat-analytics/client/trackEvents.js index c672e8bb73d..5ecaff9b6ac 100644 --- a/packages/rocketchat-analytics/client/trackEvents.js +++ b/packages/rocketchat-analytics/client/trackEvents.js @@ -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'); diff --git a/packages/rocketchat-api/server/api.js b/packages/rocketchat-api/server/api.js index 10e5b561999..f1e71eeaa5a 100644 --- a/packages/rocketchat-api/server/api.js +++ b/packages/rocketchat-api/server/api.js @@ -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); } diff --git a/packages/rocketchat-api/server/v1/channels.js b/packages/rocketchat-api/server/v1/channels.js index bb820176ecb..4e7ae8cca47 100644 --- a/packages/rocketchat-api/server/v1/channels.js +++ b/packages/rocketchat-api/server/v1/channels.js @@ -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, () => { diff --git a/packages/rocketchat-api/server/v1/chat.js b/packages/rocketchat-api/server/v1/chat.js index 384ee2602ec..a003368c9c1 100644 --- a/packages/rocketchat-api/server/v1/chat.js +++ b/packages/rocketchat-api/server/v1/chat.js @@ -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) { diff --git a/packages/rocketchat-api/server/v1/groups.js b/packages/rocketchat-api/server/v1/groups.js index a976d1bdfa5..0e12ecdd19e 100644 --- a/packages/rocketchat-api/server/v1/groups.js +++ b/packages/rocketchat-api/server/v1/groups.js @@ -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, () => { diff --git a/packages/rocketchat-api/server/v1/helpers/parseJsonQuery.js b/packages/rocketchat-api/server/v1/helpers/parseJsonQuery.js index 073ebf4e83f..1a07cacfa42 100644 --- a/packages/rocketchat-api/server/v1/helpers/parseJsonQuery.js +++ b/packages/rocketchat-api/server/v1/helpers/parseJsonQuery.js @@ -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' }); } } diff --git a/packages/rocketchat-api/server/v1/im.js b/packages/rocketchat-api/server/v1/im.js index ead2beed8eb..f0f2c08c8da 100644 --- a/packages/rocketchat-api/server/v1/im.js +++ b/packages/rocketchat-api/server/v1/im.js @@ -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, () => { diff --git a/packages/rocketchat-api/server/v1/users.js b/packages/rocketchat-api/server/v1/users.js index 6892a54d1f2..b1b002afca3 100644 --- a/packages/rocketchat-api/server/v1/users.js +++ b/packages/rocketchat-api/server/v1/users.js @@ -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({ diff --git a/packages/rocketchat-assets/server/assets.js b/packages/rocketchat-assets/server/assets.js index d55848474d1..643ce5d7071 100644 --- a/packages/rocketchat-assets/server/assets.js +++ b/packages/rocketchat-assets/server/assets.js @@ -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); diff --git a/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js b/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js index 5a0b3e73014..7dac9ab423c 100644 --- a/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js +++ b/packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js @@ -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') { diff --git a/packages/rocketchat-autotranslate/server/autotranslate.js b/packages/rocketchat-autotranslate/server/autotranslate.js index c61c7544456..c5349120f1f 100644 --- a/packages/rocketchat-autotranslate/server/autotranslate.js +++ b/packages/rocketchat-autotranslate/server/autotranslate.js @@ -28,7 +28,7 @@ class AutoTranslate { } let count = message.tokens.length; message.msg = message.msg.replace(/:[+\w\d]+:/g, function(match) { - const token = `{${count++}}`; + const token = `{${ count++ }}`; 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 = `{${count++}}`; + message.msg = message.msg.replace(new RegExp(`(!?\\[)([^\\]]+)(\\]\\((?:${ schemes }):\\/\\/[^\\)]+\\))`, 'gm'), function(match, pre, text, post) { + const pretoken = `{${ count++ }}`; message.tokens.push({ token: pretoken, text: pre }); - const posttoken = `{${count++}}`; + const posttoken = `{${ count++ }}`; message.tokens.push({ token: posttoken, text: post @@ -65,14 +65,14 @@ class AutoTranslate { }); // Support - message.msg = message.msg.replace(new RegExp(`((?:<|<)(?:${schemes}):\\/\\/[^\\|]+\\|)(.+?)(?=>|>)((?:>|>))`, 'gm'), function(match, pre, text, post) { - const pretoken = `{${count++}}`; + message.msg = message.msg.replace(new RegExp(`((?:<|<)(?:${ schemes }):\\/\\/[^\\|]+\\|)(.+?)(?=>|>)((?:>|>))`, 'gm'), function(match, pre, text, post) { + const pretoken = `{${ count++ }}`; message.tokens.push({ token: pretoken, text: pre }); - const posttoken = `{${count++}}`; + const posttoken = `{${ count++ }}`; 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 = `{${count++}}`; + const newToken = `{${ count++ }}`; 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 = `{${count++}}`; + message.msg = message.msg.replace(new RegExp(`(@${ mention.username })`, 'gm'), match => { + const token = `{${ count++ }}`; 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 = `{${count++}}`; + message.msg = message.msg.replace(new RegExp(`(#${ channel.name })`, 'gm'), match => { + const token = `{${ count++ }}`; 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 })) { diff --git a/packages/rocketchat-autotranslate/server/models/Messages.js b/packages/rocketchat-autotranslate/server/models/Messages.js index f8b1db60f25..5297e722ca5 100644 --- a/packages/rocketchat-autotranslate/server/models/Messages.js +++ b/packages/rocketchat-autotranslate/server/models/Messages.js @@ -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 }); }; diff --git a/packages/rocketchat-cas/cas_client.js b/packages/rocketchat-cas/cas_client.js index 9b3468f56df..b8d2cc8b0ae 100644 --- a/packages/rocketchat-cas/cas_client.js +++ b/packages/rocketchat-cas/cas_client.js @@ -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, diff --git a/packages/rocketchat-cas/cas_server.js b/packages/rocketchat-cas/cas_server.js index a78a280d533..6a8516cd180 100644 --- a/packages/rocketchat-cas/cas_server.js +++ b/packages/rocketchat-cas/cas_server.js @@ -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) { diff --git a/packages/rocketchat-colors/client.js b/packages/rocketchat-colors/client.js index 80102c8c18a..6b80ee8ce20 100644 --- a/packages/rocketchat-colors/client.js +++ b/packages/rocketchat-colors/client.js @@ -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, '
' + (completeColor.toUpperCase()) + '
'); + return match.replace(completeColor, `
${ completeColor.toUpperCase() }
`); }); message.html = msg; } diff --git a/packages/rocketchat-cors/cors.js b/packages/rocketchat-cors/cors.js index b35d22e1717..9b07501d8d3 100644 --- a/packages/rocketchat-cors/cors.js +++ b/packages/rocketchat-cors/cors.js @@ -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; diff --git a/packages/rocketchat-custom-oauth/custom_oauth_client.js b/packages/rocketchat-custom-oauth/custom_oauth_client.js index 6c3ed5084e4..191706d9a8d 100644 --- a/packages/rocketchat-custom-oauth/custom_oauth_client.js +++ b/packages/rocketchat-custom-oauth/custom_oauth_client.js @@ -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, diff --git a/packages/rocketchat-custom-oauth/custom_oauth_server.js b/packages/rocketchat-custom-oauth/custom_oauth_server.js index 4a938be3517..8a331d95051 100644 --- a/packages/rocketchat-custom-oauth/custom_oauth_server.js +++ b/packages/rocketchat-custom-oauth/custom_oauth_server.js @@ -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 diff --git a/packages/rocketchat-custom-sounds/admin/adminSounds.js b/packages/rocketchat-custom-sounds/admin/adminSounds.js index 7dc22fa0973..63972ce1bfd 100644 --- a/packages/rocketchat-custom-sounds/admin/adminSounds.js +++ b/packages/rocketchat-custom-sounds/admin/adminSounds.js @@ -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(); } diff --git a/packages/rocketchat-custom-sounds/client/lib/CustomSounds.js b/packages/rocketchat-custom-sounds/client/lib/CustomSounds.js index 28c096106cf..a1e54b8e772 100644 --- a/packages/rocketchat-custom-sounds/client/lib/CustomSounds.js +++ b/packages/rocketchat-custom-sounds/client/lib/CustomSounds.js @@ -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() { diff --git a/packages/rocketchat-custom-sounds/server/methods/deleteCustomSound.js b/packages/rocketchat-custom-sounds/server/methods/deleteCustomSound.js index 82d01933e02..f02eecab307 100644 --- a/packages/rocketchat-custom-sounds/server/methods/deleteCustomSound.js +++ b/packages/rocketchat-custom-sounds/server/methods/deleteCustomSound.js @@ -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}); diff --git a/packages/rocketchat-custom-sounds/server/methods/insertOrUpdateSound.js b/packages/rocketchat-custom-sounds/server/methods/insertOrUpdateSound.js index c0dc2b72009..3f4b4a2a4e0 100644 --- a/packages/rocketchat-custom-sounds/server/methods/insertOrUpdateSound.js +++ b/packages/rocketchat-custom-sounds/server/methods/insertOrUpdateSound.js @@ -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) { diff --git a/packages/rocketchat-custom-sounds/server/methods/uploadCustomSound.js b/packages/rocketchat-custom-sounds/server/methods/uploadCustomSound.js index 9dabf715edc..a0c52aaacce 100644 --- a/packages/rocketchat-custom-sounds/server/methods/uploadCustomSound.js +++ b/packages/rocketchat-custom-sounds/server/methods/uploadCustomSound.js @@ -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) diff --git a/packages/rocketchat-custom-sounds/server/startup/custom-sounds.js b/packages/rocketchat-custom-sounds/server/startup/custom-sounds.js index 2cc290603f6..7655a35435b 100644 --- a/packages/rocketchat-custom-sounds/server/startup/custom-sounds.js +++ b/packages/rocketchat-custom-sounds/server/startup/custom-sounds.js @@ -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) { diff --git a/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js b/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js index 2927f89f4db..89756e7cf67 100644 --- a/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js +++ b/packages/rocketchat-emoji-custom/client/lib/emojiCustom.js @@ -5,7 +5,7 @@ RocketChat.emoji.packages.emojiCustom = { list: [], render(html) { - const regShortNames = new RegExp(']*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(' + RocketChat.emoji.packages.emojiCustom.list.join('|') + ')', 'gi'); + const regShortNames = new RegExp(`]*>.*?<\/object>|]*>.*?<\/span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|(${ 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 `${shortname}`; + return `${ shortname }`; } }); @@ -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 += `
  • ${renderedEmoji}
  • `; + const renderedEmoji = RocketChat.emoji.packages.emojiCustom.render(`:${ entry }:`); + html += `
  • ${ renderedEmoji }
  • `; } $('.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 }; diff --git a/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js b/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js index 09269cac0eb..4a36eccf7d4 100644 --- a/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/server/methods/deleteEmojiCustom.js @@ -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}); diff --git a/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js b/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js index 76db39a2d10..adbe895dc2e 100644 --- a/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js +++ b/packages/rocketchat-emoji-custom/server/methods/insertOrUpdateEmoji.js @@ -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); } diff --git a/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js b/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js index 0f61eab8b0e..d3c9295b203 100644 --- a/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js +++ b/packages/rocketchat-emoji-custom/server/methods/uploadEmojiCustom.js @@ -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) diff --git a/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js b/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js index a69e748c3ac..00cae00a13e 100644 --- a/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js +++ b/packages/rocketchat-emoji-custom/server/startup/emoji-custom.js @@ -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 = ` - + - ${initials} + ${ initials } `; diff --git a/packages/rocketchat-emoji/emojiButton.js b/packages/rocketchat-emoji/emojiButton.js index 76c977fb485..07f20ed6ca9 100644 --- a/packages/rocketchat-emoji/emojiButton.js +++ b/packages/rocketchat-emoji/emojiButton.js @@ -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(); diff --git a/packages/rocketchat-emoji/emojiParser.js b/packages/rocketchat-emoji/emojiParser.js index 7c494858b8c..9c417305c12 100644 --- a/packages/rocketchat-emoji/emojiParser.js +++ b/packages/rocketchat-emoji/emojiParser.js @@ -16,7 +16,7 @@ RocketChat.callbacks.add('renderMessage', (message) => { message.html = RocketChat.emoji.packages[emojiPackage].render(message.html); }); - const checkEmojiOnly = $(`
    ${message.html}
    `); + const checkEmojiOnly = $(`
    ${ message.html }
    `); let emojiOnly = true; for (const childNode in checkEmojiOnly[0].childNodes) { if (checkEmojiOnly[0].childNodes.hasOwnProperty(childNode)) { diff --git a/packages/rocketchat-emoji/emojiPicker.js b/packages/rocketchat-emoji/emojiPicker.js index 2d0d7dcd45b..db72fca46aa 100644 --- a/packages/rocketchat-emoji/emojiPicker.js +++ b/packages/rocketchat-emoji/emojiPicker.js @@ -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 += `
  • ${image}
  • `; + html += `
  • ${ image }
  • `; } } } @@ -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 += `
  • ${image}
  • `; + const image = RocketChat.emoji.packages[emojiPackage].render(`:${ emoji }${ tone }:`); + html += `
  • ${ image }
  • `; } } } @@ -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; }; }); diff --git a/packages/rocketchat-emoji/lib/EmojiPicker.js b/packages/rocketchat-emoji/lib/EmojiPicker.js index 4543cae0521..42a4c56634c 100644 --- a/packages/rocketchat-emoji/lib/EmojiPicker.js +++ b/packages/rocketchat-emoji/lib/EmojiPicker.js @@ -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 += `
  • ${renderedEmoji}
  • `; + if (isSetNotNull(() => RocketChat.emoji.list[`:${ emoji }:`])) { + const emojiPackage = RocketChat.emoji.list[`:${ emoji }:`].emojiPackage; + const renderedEmoji = RocketChat.emoji.packages[emojiPackage].render(`:${ emoji }:`); + html += `
  • ${ renderedEmoji }
  • `; } else { this.recent = _.without(this.recent, emoji); } diff --git a/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js b/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js index 3deae37746d..276e3c6ddd4 100644 --- a/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js +++ b/packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js @@ -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 }); diff --git a/packages/rocketchat-file-upload/server/config/configFileUploadAmazonS3.js b/packages/rocketchat-file-upload/server/config/configFileUploadAmazonS3.js index 09a901c24e0..daac0ea1993 100644 --- a/packages/rocketchat-file-upload/server/config/configFileUploadAmazonS3.js +++ b/packages/rocketchat-file-upload/server/config/configFileUploadAmazonS3.js @@ -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, diff --git a/packages/rocketchat-file-upload/server/config/configFileUploadFileSystem.js b/packages/rocketchat-file-upload/server/config/configFileUploadFileSystem.js index 8cdb9d9655d..f4a0de0f219 100644 --- a/packages/rocketchat-file-upload/server/config/configFileUploadFileSystem.js +++ b/packages/rocketchat-file-upload/server/config/configFileUploadFileSystem.js @@ -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); diff --git a/packages/rocketchat-file-upload/server/config/configFileUploadGoogleStorage.js b/packages/rocketchat-file-upload/server/config/configFileUploadGoogleStorage.js index f19bcf1c0b0..9e8d5219ba6 100644 --- a/packages/rocketchat-file-upload/server/config/configFileUploadGoogleStorage.js +++ b/packages/rocketchat-file-upload/server/config/configFileUploadGoogleStorage.js @@ -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; diff --git a/packages/rocketchat-file-upload/server/config/configFileUploadGridFS.js b/packages/rocketchat-file-upload/server/config/configFileUploadGridFS.js index 7b8b9656b27..21ac212db8e 100644 --- a/packages/rocketchat-file-upload/server/config/configFileUploadGridFS.js +++ b/packages/rocketchat-file-upload/server/config/configFileUploadGridFS.js @@ -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 diff --git a/packages/rocketchat-file-upload/server/lib/FileUpload.js b/packages/rocketchat-file-upload/server/lib/FileUpload.js index 6bff6073b22..cb0aadbc06c 100644 --- a/packages/rocketchat-file-upload/server/lib/FileUpload.js +++ b/packages/rocketchat-file-upload/server/lib/FileUpload.js @@ -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; diff --git a/packages/rocketchat-file-upload/server/methods/getS3FileUrl.js b/packages/rocketchat-file-upload/server/methods/getS3FileUrl.js index 4ab03d27845..ef48ddc2163 100644 --- a/packages/rocketchat-file-upload/server/methods/getS3FileUrl.js +++ b/packages/rocketchat-file-upload/server/methods/getS3FileUrl.js @@ -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) }` }; } }); diff --git a/packages/rocketchat-file-upload/server/methods/sendFileMessage.js b/packages/rocketchat-file-upload/server/methods/sendFileMessage.js index a63279a695f..6a3e98b8398 100644 --- a/packages/rocketchat-file-upload/server/methods/sendFileMessage.js +++ b/packages/rocketchat-file-upload/server/methods/sendFileMessage.js @@ -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 diff --git a/packages/rocketchat-highlight-words/client.js b/packages/rocketchat-highlight-words/client.js index 57ed309e147..8972dd03e87 100644 --- a/packages/rocketchat-highlight-words/client.js +++ b/packages/rocketchat-highlight-words/client.js @@ -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$2$3'); + return msg = msg.replace(new RegExp(`(^|\\b|[\\s\\n\\r\\t.,،'\\\"\\+!?:-])(${ s.escapeRegExp(highlight) })($|\\b|[\\s\\n\\r\\t.,،'\\\"\\+!?:-])(?![^<]*>|[^<>]*<\\/)`, 'gmi'), '$1$2$3'); } }); } diff --git a/packages/rocketchat-i18n/package.js b/packages/rocketchat-i18n/package.js index fa65cda9204..2c535df63c5 100644 --- a/packages/rocketchat-i18n/package.js +++ b/packages/rocketchat-i18n/package.js @@ -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 }`); } }); diff --git a/packages/rocketchat-iframe-login/iframe_client.js b/packages/rocketchat-iframe-login/iframe_client.js index 6b5b1692ccd..125481fcd2f 100644 --- a/packages/rocketchat-iframe-login/iframe_client.js +++ b/packages/rocketchat-iframe-login/iframe_client.js @@ -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) => { diff --git a/packages/rocketchat-importer-csv/server.js b/packages/rocketchat-importer-csv/server.js index d4c7b902d0e..183346fb358 100644 --- a/packages/rocketchat-importer-csv/server.js +++ b/packages/rocketchat-importer-csv/server.js @@ -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(); diff --git a/packages/rocketchat-importer-hipchat-enterprise/server.js b/packages/rocketchat-importer-hipchat-enterprise/server.js index 91e55ebf65a..40f3762df62 100644 --- a/packages/rocketchat-importer-hipchat-enterprise/server.js +++ b/packages/rocketchat-importer-hipchat-enterprise/server.js @@ -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; } } diff --git a/packages/rocketchat-importer/server/methods/prepareImport.js b/packages/rocketchat-importer/server/methods/prepareImport.js index 73c5903daa4..9c1865abb17 100644 --- a/packages/rocketchat-importer/server/methods/prepareImport.js +++ b/packages/rocketchat-importer/server/methods/prepareImport.js @@ -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' }); } } }); diff --git a/packages/rocketchat-integrations/client/views/integrationsIncoming.js b/packages/rocketchat-integrations/client/views/integrationsIncoming.js index 2548e5dcb0a..1825d51a002 100644 --- a/packages/rocketchat-integrations/client/views/integrationsIncoming.js +++ b/packages/rocketchat-integrations/client/views/integrationsIncoming.js @@ -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() { diff --git a/packages/rocketchat-integrations/client/views/integrationsOutgoing.js b/packages/rocketchat-integrations/client/views/integrationsOutgoing.js index ee6ff6aa044..d8a9418fd47 100644 --- a/packages/rocketchat-integrations/client/views/integrationsOutgoing.js +++ b/packages/rocketchat-integrations/client/views/integrationsOutgoing.js @@ -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) => { diff --git a/packages/rocketchat-integrations/server/lib/triggerHandler.js b/packages/rocketchat-integrations/server/lib/triggerHandler.js index 68c2fc24c60..fc7212477f2 100644 --- a/packages/rocketchat-integrations/server/lib/triggerHandler.js +++ b/packages/rocketchat-integrations/server/lib/triggerHandler.js @@ -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); diff --git a/packages/rocketchat-katex/package.js b/packages/rocketchat-katex/package.js index a6b0eb88c25..033ea7efeee 100644 --- a/packages/rocketchat-katex/package.js +++ b/packages/rocketchat-katex/package.js @@ -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; }); diff --git a/packages/rocketchat-ldap/server/ldap.js b/packages/rocketchat-ldap/server/ldap.js index 15e497e4e24..412ffa1d679 100644 --- a/packages/rocketchat-ldap/server/ldap.js +++ b/packages/rocketchat-ldap/server/ldap.js @@ -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(')'); diff --git a/packages/rocketchat-ldap/server/loginHandler.js b/packages/rocketchat-ldap/server/loginHandler.js index 67fc2ab8d4b..25e5af9045c 100644 --- a/packages/rocketchat-ldap/server/loginHandler.js +++ b/packages/rocketchat-ldap/server/loginHandler.js @@ -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'); diff --git a/packages/rocketchat-ldap/server/sync.js b/packages/rocketchat-ldap/server/sync.js index 506fab17947..0b0b218d24e 100644 --- a/packages/rocketchat-ldap/server/sync.js +++ b/packages/rocketchat-ldap/server/sync.js @@ -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); diff --git a/packages/rocketchat-lib/client/OAuthProxy.js b/packages/rocketchat-lib/client/OAuthProxy.js index 6683dddc29b..5c8b5296192 100644 --- a/packages/rocketchat-lib/client/OAuthProxy.js +++ b/packages/rocketchat-lib/client/OAuthProxy.js @@ -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); diff --git a/packages/rocketchat-lib/client/lib/RocketChatTabBar.js b/packages/rocketchat-lib/client/lib/RocketChatTabBar.js index 6c66c344ddd..5395f5b3d47 100644 --- a/packages/rocketchat-lib/client/lib/RocketChatTabBar.js +++ b/packages/rocketchat-lib/client/lib/RocketChatTabBar.js @@ -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', ''); } diff --git a/packages/rocketchat-lib/client/lib/cachedCollection.js b/packages/rocketchat-lib/client/lib/cachedCollection.js index da8a0271569..23fd088e169 100644 --- a/packages/rocketchat-lib/client/lib/cachedCollection.js +++ b/packages/rocketchat-lib/client/lib/cachedCollection.js @@ -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); } diff --git a/packages/rocketchat-lib/lib/getURL.js b/packages/rocketchat-lib/lib/getURL.js index d611c69ca2e..c70735b079e 100644 --- a/packages/rocketchat-lib/lib/getURL.js +++ b/packages/rocketchat-lib/lib/getURL.js @@ -14,5 +14,5 @@ RocketChat.getURL = (path, { cdn = true, full = false } = {}) => { basePath = pathPrefix; } - return basePath + '/' + finalPath; + return `${ basePath }/${ finalPath }`; }; diff --git a/packages/rocketchat-lib/server/functions/checkEmailAvailability.js b/packages/rocketchat-lib/server/functions/checkEmailAvailability.js index 8d8e9322e75..e5dee1791ba 100644 --- a/packages/rocketchat-lib/server/functions/checkEmailAvailability.js +++ b/packages/rocketchat-lib/server/functions/checkEmailAvailability.js @@ -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') } }); }; diff --git a/packages/rocketchat-lib/server/functions/createRoom.js b/packages/rocketchat-lib/server/functions/createRoom.js index 76682f03368..916c9871ba8 100644 --- a/packages/rocketchat-lib/server/functions/createRoom.js +++ b/packages/rocketchat-lib/server/functions/createRoom.js @@ -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 }); } } diff --git a/packages/rocketchat-lib/server/functions/deleteUser.js b/packages/rocketchat-lib/server/functions/deleteUser.js index 9a560a4372e..a139389b064 100644 --- a/packages/rocketchat-lib/server/functions/deleteUser.js +++ b/packages/rocketchat-lib/server/functions/deleteUser.js @@ -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. diff --git a/packages/rocketchat-lib/server/functions/saveCustomFields.js b/packages/rocketchat-lib/server/functions/saveCustomFields.js index 9e598f8d119..4b3717897f0 100644 --- a/packages/rocketchat-lib/server/functions/saveCustomFields.js +++ b/packages/rocketchat-lib/server/functions/saveCustomFields.js @@ -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' }); } }); diff --git a/packages/rocketchat-lib/server/functions/saveUser.js b/packages/rocketchat-lib/server/functions/saveUser.js index fb0783d48a2..ac9c31abc14 100644 --- a/packages/rocketchat-lib/server/functions/saveUser.js +++ b/packages/rocketchat-lib/server/functions/saveUser.js @@ -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 }); } }); } diff --git a/packages/rocketchat-lib/server/functions/setEmail.js b/packages/rocketchat-lib/server/functions/setEmail.js index f20482710c4..280e22425b1 100644 --- a/packages/rocketchat-lib/server/functions/setEmail.js +++ b/packages/rocketchat-lib/server/functions/setEmail.js @@ -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 diff --git a/packages/rocketchat-lib/server/functions/setUserAvatar.js b/packages/rocketchat-lib/server/functions/setUserAvatar.js index 754372acd4f..e80a8c7cdd7 100644 --- a/packages/rocketchat-lib/server/functions/setUserAvatar.js +++ b/packages/rocketchat-lib/server/functions/setUserAvatar.js @@ -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); diff --git a/packages/rocketchat-lib/server/lib/PushNotification.js b/packages/rocketchat-lib/server/lib/PushNotification.js index 05c576189d2..fd1bdb8db60 100644 --- a/packages/rocketchat-lib/server/lib/PushNotification.js +++ b/packages/rocketchat-lib/server/lib/PushNotification.js @@ -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 = { diff --git a/packages/rocketchat-lib/server/lib/bugsnag.js b/packages/rocketchat-lib/server/lib/bugsnag.js index 9a5d6636ee9..43c1e46d9fe 100644 --- a/packages/rocketchat-lib/server/lib/bugsnag.js +++ b/packages/rocketchat-lib/server/lib/bugsnag.js @@ -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) { diff --git a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js index 3acf3f44fff..735ac1340de 100644 --- a/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js +++ b/packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js @@ -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'); } } diff --git a/packages/rocketchat-lib/server/lib/validateEmailDomain.js b/packages/rocketchat-lib/server/lib/validateEmailDomain.js index 8b366505a88..54d06f24be6 100644 --- a/packages/rocketchat-lib/server/lib/validateEmailDomain.js +++ b/packages/rocketchat-lib/server/lib/validateEmailDomain.js @@ -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); diff --git a/packages/rocketchat-lib/server/methods/addOAuthService.js b/packages/rocketchat-lib/server/methods/addOAuthService.js index b378b87afcf..f2c450dab79 100644 --- a/packages/rocketchat-lib/server/methods/addOAuthService.js +++ b/packages/rocketchat-lib/server/methods/addOAuthService.js @@ -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 }); }}); diff --git a/packages/rocketchat-lib/server/methods/removeOAuthService.js b/packages/rocketchat-lib/server/methods/removeOAuthService.js index 0520bb84b8b..10830261850 100644 --- a/packages/rocketchat-lib/server/methods/removeOAuthService.js +++ b/packages/rocketchat-lib/server/methods/removeOAuthService.js @@ -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`); } }); diff --git a/packages/rocketchat-lib/server/methods/setUsername.js b/packages/rocketchat-lib/server/methods/setUsername.js index b64b1ddc5b3..9f5af1436a9 100644 --- a/packages/rocketchat-lib/server/methods/setUsername.js +++ b/packages/rocketchat-lib/server/methods/setUsername.js @@ -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', `${_.escape(username)} is already in use :(`, { method: 'setUsername', field: username }); + throw new Meteor.Error('error-field-unavailable', `${ _.escape(username) } is already in use :(`, { method: 'setUsername', field: username }); } } } else if (!RocketChat.checkUsernameAvailability(username)) { - throw new Meteor.Error('error-field-unavailable', `${_.escape(username)} is already in use :(`, { method: 'setUsername', field: username }); + throw new Meteor.Error('error-field-unavailable', `${ _.escape(username) } is already in use :(`, { method: 'setUsername', field: username }); } if (!RocketChat.setUsername(user._id, username)) { diff --git a/packages/rocketchat-lib/server/models/_BaseCache.js b/packages/rocketchat-lib/server/models/_BaseCache.js index 6ca56b82b83..f31a0230d3c 100644 --- a/packages/rocketchat-lib/server/models/_BaseCache.js +++ b/packages/rocketchat-lib/server/models/_BaseCache.js @@ -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; diff --git a/packages/rocketchat-lib/server/models/_BaseDb.js b/packages/rocketchat-lib/server/models/_BaseDb.js index 42f2dfb173d..9e9db35504d 100644 --- a/packages/rocketchat-lib/server/models/_BaseDb.js +++ b/packages/rocketchat-lib/server/models/_BaseDb.js @@ -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 }); diff --git a/packages/rocketchat-lib/server/oauth/google.js b/packages/rocketchat-lib/server/oauth/google.js index b65a2519909..37e4222e3f7 100644 --- a/packages/rocketchat-lib/server/oauth/google.js +++ b/packages/rocketchat-lib/server/oauth/google.js @@ -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}); } } diff --git a/packages/rocketchat-lib/server/oauth/oauth.js b/packages/rocketchat-lib/server/oauth/oauth.js index 9cf20c61f58..2c7655fa879 100644 --- a/packages/rocketchat-lib/server/oauth/oauth.js +++ b/packages/rocketchat-lib/server/oauth/oauth.js @@ -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 }` ) }; } diff --git a/packages/rocketchat-lib/server/oauth/proxy.js b/packages/rocketchat-lib/server/oauth/proxy.js index 320f0dfbf17..593eac4611a 100644 --- a/packages/rocketchat-lib/server/oauth/proxy.js +++ b/packages/rocketchat-lib/server/oauth/proxy.js @@ -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); } diff --git a/packages/rocketchat-lib/server/startup/statsTracker.js b/packages/rocketchat-lib/server/startup/statsTracker.js index dea74cdbb3d..dbb7776eeb2 100644 --- a/packages/rocketchat-lib/server/startup/statsTracker.js +++ b/packages/rocketchat-lib/server/startup/statsTracker.js @@ -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() { diff --git a/packages/rocketchat-lib/startup/defaultRoomTypes.js b/packages/rocketchat-lib/startup/defaultRoomTypes.js index c4a73a56ccd..2826e4a99c4 100644 --- a/packages/rocketchat-lib/startup/defaultRoomTypes.js +++ b/packages/rocketchat-lib/startup/defaultRoomTypes.js @@ -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`); } }); diff --git a/packages/rocketchat-livechat/app/client/lib/LivechatVideoCall.js b/packages/rocketchat-livechat/app/client/lib/LivechatVideoCall.js index a756a838f4e..88bdd62e0f2 100644 --- a/packages/rocketchat-livechat/app/client/lib/LivechatVideoCall.js +++ b/packages/rocketchat-livechat/app/client/lib/LivechatVideoCall.js @@ -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`); } } diff --git a/packages/rocketchat-livechat/app/client/views/messages.js b/packages/rocketchat-livechat/app/client/views/messages.js index 3bd088b3129..9c0fe36b43e 100644 --- a/packages/rocketchat-livechat/app/client/views/messages.js +++ b/packages/rocketchat-livechat/app/client/views/messages.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() { diff --git a/packages/rocketchat-livechat/client/views/app/livechatDepartmentForm.js b/packages/rocketchat-livechat/client/views/app/livechatDepartmentForm.js index bed59d6f24c..a48be4a9a89 100644 --- a/packages/rocketchat-livechat/client/views/app/livechatDepartmentForm.js +++ b/packages/rocketchat-livechat/client/views/app/livechatDepartmentForm.js @@ -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); }); diff --git a/packages/rocketchat-livechat/client/views/app/livechatInstallation.js b/packages/rocketchat-livechat/client/views/app/livechatInstallation.js index ab0be923c51..4511a0bcea5 100644 --- a/packages/rocketchat-livechat/client/views/app/livechatInstallation.js +++ b/packages/rocketchat-livechat/client/views/app/livechatInstallation.js @@ -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'); `; } diff --git a/packages/rocketchat-livechat/client/views/app/livechatOfficeHours.js b/packages/rocketchat-livechat/client/views/app/livechatOfficeHours.js index a028c641c92..cba5a0b8771 100644 --- a/packages/rocketchat-livechat/client/views/app/livechatOfficeHours.js +++ b/packages/rocketchat-livechat/client/views/app/livechatOfficeHours.js @@ -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(); diff --git a/packages/rocketchat-livechat/client/views/app/livechatTriggersForm.js b/packages/rocketchat-livechat/client/views/app/livechatTriggersForm.js index 2b16ff6583a..651b2367a09 100644 --- a/packages/rocketchat-livechat/client/views/app/livechatTriggersForm.js +++ b/packages/rocketchat-livechat/client/views/app/livechatTriggersForm.js @@ -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() }); } }); diff --git a/packages/rocketchat-livechat/client/views/app/tabbar/externalSearch.js b/packages/rocketchat-livechat/client/views/app/tabbar/externalSearch.js index c6f52ac2926..a5d10f80470 100644 --- a/packages/rocketchat-livechat/client/views/app/tabbar/externalSearch.js +++ b/packages/rocketchat-livechat/client/views/app/tabbar/externalSearch.js @@ -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(); } }); diff --git a/packages/rocketchat-livechat/client/views/app/tabbar/visitorHistory.js b/packages/rocketchat-livechat/client/views/app/tabbar/visitorHistory.js index 9cc0d34cd24..de1504aba59 100644 --- a/packages/rocketchat-livechat/client/views/app/tabbar/visitorHistory.js +++ b/packages/rocketchat-livechat/client/views/app/tabbar/visitorHistory.js @@ -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; diff --git a/packages/rocketchat-livechat/client/views/app/tabbar/visitorInfo.js b/packages/rocketchat-livechat/client/views/app/tabbar/visitorInfo.js index a2e425c444b..92d1a22ab44 100644 --- a/packages/rocketchat-livechat/client/views/app/tabbar/visitorInfo.js +++ b/packages/rocketchat-livechat/client/views/app/tabbar/visitorInfo.js @@ -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; diff --git a/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerAction.js b/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerAction.js index a0ee322dfc2..f47ad1c549e 100644 --- a/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerAction.js +++ b/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerAction.js @@ -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'); } }); diff --git a/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerCondition.js b/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerCondition.js index a14e0a9c1ca..e90681367fa 100644 --- a/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerCondition.js +++ b/packages/rocketchat-livechat/client/views/app/triggers/livechatTriggerCondition.js @@ -22,7 +22,7 @@ Template.livechatTriggerCondition.helpers({ Template.livechatTriggerCondition.events({ 'change .trigger-condition'(e, instance) { instance.$('.trigger-condition-value ').addClass('hidden'); - instance.$('.' + e.currentTarget.value).removeClass('hidden'); + instance.$(`.${ e.currentTarget.value }`).removeClass('hidden'); } }); diff --git a/packages/rocketchat-livechat/client/views/sideNav/livechat.js b/packages/rocketchat-livechat/client/views/sideNav/livechat.js index 756a0e0b42b..087760f6867 100644 --- a/packages/rocketchat-livechat/client/views/sideNav/livechat.js +++ b/packages/rocketchat-livechat/client/views/sideNav/livechat.js @@ -106,7 +106,7 @@ Template.livechat.events({ swal({ title: t('Livechat_Take_Confirm'), - text: t('Message') + ': ' + this.message, + text: `${ t('Message') }: ${ this.message }`, showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', diff --git a/packages/rocketchat-livechat/livechat.js b/packages/rocketchat-livechat/livechat.js index 570d1cef0c7..1e306b55754 100644 --- a/packages/rocketchat-livechat/livechat.js +++ b/packages/rocketchat-livechat/livechat.js @@ -23,22 +23,22 @@ WebApp.connectHandlers.use('/livechat', Meteor.bindEnvironment((req, res, next) return next(); } - res.setHeader('X-FRAME-OPTIONS', `ALLOW-FROM ${referer.protocol}//${referer.host}`); + res.setHeader('X-FRAME-OPTIONS', `ALLOW-FROM ${ referer.protocol }//${ referer.host }`); } const head = Assets.getText('public/head.html'); const html = ` - + - ${head} + ${ head } - + `; diff --git a/packages/rocketchat-livechat/plugin/build-livechat.js b/packages/rocketchat-livechat/plugin/build-livechat.js index 398708c2969..9483df7fae6 100644 --- a/packages/rocketchat-livechat/plugin/build-livechat.js +++ b/packages/rocketchat-livechat/plugin/build-livechat.js @@ -11,7 +11,7 @@ const packagePath = path.join(path.resolve('.'), 'packages', 'rocketchat-livecha const pluginPath = path.join(packagePath, 'plugin'); if (process.platform === 'win32') { - shell.exec(pluginPath+'/build.bat'); + shell.exec(`${ pluginPath }/build.bat`); } else { - shell.exec('sh '+pluginPath+'/build.sh'); + shell.exec(`sh ${ pluginPath }/build.sh`); } diff --git a/packages/rocketchat-livechat/roomType.js b/packages/rocketchat-livechat/roomType.js index 98eefbcae8e..c59fdf9a803 100644 --- a/packages/rocketchat-livechat/roomType.js +++ b/packages/rocketchat-livechat/roomType.js @@ -39,7 +39,7 @@ RocketChat.roomTypes.add('l', 5, { getUserStatus(roomId) { let guestName; - const room = Session.get('roomData' + roomId); + const room = Session.get(`roomData${ roomId }`); if (room) { guestName = room.v && room.v.username; @@ -49,7 +49,7 @@ RocketChat.roomTypes.add('l', 5, { } if (guestName) { - return Session.get('user_' + guestName + '_status'); + return Session.get(`user_${ guestName }_status`); } }, diff --git a/packages/rocketchat-livechat/server/hooks/externalMessage.js b/packages/rocketchat-livechat/server/hooks/externalMessage.js index 3ee5916532b..ad9f228399d 100644 --- a/packages/rocketchat-livechat/server/hooks/externalMessage.js +++ b/packages/rocketchat-livechat/server/hooks/externalMessage.js @@ -42,7 +42,7 @@ RocketChat.callbacks.add('afterSaveMessage', function(message, room) { }, headers: { 'Content-Type': 'application/json; charset=utf-8', - 'Authorization': 'Bearer ' + apiaiKey + 'Authorization': `Bearer ${ apiaiKey }` } }); diff --git a/packages/rocketchat-livechat/server/lib/Livechat.js b/packages/rocketchat-livechat/server/lib/Livechat.js index ac20df2168f..d5801811af2 100644 --- a/packages/rocketchat-livechat/server/lib/Livechat.js +++ b/packages/rocketchat-livechat/server/lib/Livechat.js @@ -352,7 +352,7 @@ RocketChat.Livechat = { }; return HTTP.post(RocketChat.settings.get('Livechat_webhookUrl'), options); } catch (e) { - RocketChat.Livechat.logger.webhook.error('Response error on ' + trying + ' try ->', e); + RocketChat.Livechat.logger.webhook.error(`Response error on ${ trying } try ->`, e); // try 10 times after 10 seconds each if (trying < 10) { RocketChat.Livechat.logger.webhook.warn('Will try again in 10 seconds ...'); @@ -388,8 +388,8 @@ RocketChat.Livechat = { phone: null, department: visitor.department, ip: visitor.ip, - os: ua.getOS().name && (ua.getOS().name + ' ' + ua.getOS().version), - browser: ua.getBrowser().name && (ua.getBrowser().name + ' ' + ua.getBrowser().version), + os: ua.getOS().name && (`${ ua.getOS().name } ${ ua.getOS().version }`), + browser: ua.getBrowser().name && (`${ ua.getBrowser().name } ${ ua.getBrowser().version }`), customFields: visitor.livechatData }, agent: { diff --git a/packages/rocketchat-livechat/server/methods/sendOfflineMessage.js b/packages/rocketchat-livechat/server/methods/sendOfflineMessage.js index 9dedcaec19a..ef161d651ed 100644 --- a/packages/rocketchat-livechat/server/methods/sendOfflineMessage.js +++ b/packages/rocketchat-livechat/server/methods/sendOfflineMessage.js @@ -16,13 +16,13 @@ Meteor.methods({ const header = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Header') || ''); const footer = RocketChat.placeholders.replace(RocketChat.settings.get('Email_Footer') || ''); - const message = (data.message + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '
    ' + '$2'); + const message = (`${ data.message }`).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '
    ' + '$2'); const html = `

    New livechat message

    -

    Visitor name: ${data.name}

    -

    Visitor email: ${data.email}

    -

    Message:
    ${message}

    `; +

    Visitor name: ${ data.name }

    +

    Visitor email: ${ data.email }

    +

    Message:
    ${ message }

    `; let fromEmail = RocketChat.settings.get('From_Email').match(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i); @@ -45,9 +45,9 @@ Meteor.methods({ Meteor.defer(() => { Email.send({ to: RocketChat.settings.get('Livechat_offline_email'), - from: `${data.name} - ${data.email} <${fromEmail}>`, - replyTo: `${data.name} <${data.email}>`, - subject: `Livechat offline message from ${data.name}: ${(data.message + '').substring(0, 20)}`, + from: `${ data.name } - ${ data.email } <${ fromEmail }>`, + replyTo: `${ data.name } <${ data.email }>`, + subject: `Livechat offline message from ${ data.name }: ${ (`${ data.message }`).substring(0, 20) }`, html: header + html + footer }); }); diff --git a/packages/rocketchat-livechat/server/methods/sendTranscript.js b/packages/rocketchat-livechat/server/methods/sendTranscript.js index e42d9ed9240..a37a874a9c4 100644 --- a/packages/rocketchat-livechat/server/methods/sendTranscript.js +++ b/packages/rocketchat-livechat/server/methods/sendTranscript.js @@ -35,13 +35,13 @@ Meteor.methods({ const datetime = moment(message.ts).locale(userLanguage).format('LLL'); const singleMessage = ` -

    ${author} ${datetime}

    -

    ${message.msg}

    +

    ${ author } ${ datetime }

    +

    ${ message.msg }

    `; html = html + singleMessage; }); - html = html + ''; + html = `${ html }`; let fromEmail = RocketChat.settings.get('From_Email').match(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i); diff --git a/packages/rocketchat-livechat/server/models/LivechatOfficeHour.js b/packages/rocketchat-livechat/server/models/LivechatOfficeHour.js index d5d15bc24d1..954ea8611b8 100644 --- a/packages/rocketchat-livechat/server/models/LivechatOfficeHour.js +++ b/packages/rocketchat-livechat/server/models/LivechatOfficeHour.js @@ -56,8 +56,8 @@ class LivechatOfficeHour extends RocketChat.models._Base { return false; } - const start = moment.utc(todaysOfficeHours.day + ':' + todaysOfficeHours.start, 'dddd:HH:mm'); - const finish = moment.utc(todaysOfficeHours.day + ':' + todaysOfficeHours.finish, 'dddd:HH:mm'); + const start = moment.utc(`${ todaysOfficeHours.day }:${ todaysOfficeHours.start }`, 'dddd:HH:mm'); + const finish = moment.utc(`${ todaysOfficeHours.day }:${ todaysOfficeHours.finish }`, 'dddd:HH:mm'); // console.log(finish.isBefore(start)); if (finish.isBefore(start)) { @@ -86,7 +86,7 @@ class LivechatOfficeHour extends RocketChat.models._Base { return false; } - const start = moment.utc(todaysOfficeHours.day + ':' + todaysOfficeHours.start, 'dddd:HH:mm'); + const start = moment.utc(`${ todaysOfficeHours.day }:${ todaysOfficeHours.start }`, 'dddd:HH:mm'); return start.isSame(currentTime, 'minute'); } @@ -101,7 +101,7 @@ class LivechatOfficeHour extends RocketChat.models._Base { return false; } - const finish = moment.utc(todaysOfficeHours.day + ':' + todaysOfficeHours.finish, 'dddd:HH:mm'); + const finish = moment.utc(`${ todaysOfficeHours.day }:${ todaysOfficeHours.finish }`, 'dddd:HH:mm'); return finish.isSame(currentTime, 'minute'); } diff --git a/packages/rocketchat-livechat/server/models/Rooms.js b/packages/rocketchat-livechat/server/models/Rooms.js index 9a57fb5e62f..f2275590196 100644 --- a/packages/rocketchat-livechat/server/models/Rooms.js +++ b/packages/rocketchat-livechat/server/models/Rooms.js @@ -31,7 +31,7 @@ RocketChat.models.Rooms.updateLivechatDataByToken = function(token, key, value, const update = { $set: { - [`livechatData.${key}`]: value + [`livechatData.${ key }`]: value } }; diff --git a/packages/rocketchat-livechat/server/models/Users.js b/packages/rocketchat-livechat/server/models/Users.js index 02202960476..75cd14114d7 100644 --- a/packages/rocketchat-livechat/server/models/Users.js +++ b/packages/rocketchat-livechat/server/models/Users.js @@ -180,7 +180,7 @@ RocketChat.models.Users.updateLivechatDataByToken = function(token, key, value, const update = { $set: { - [`livechatData.${key}`]: value + [`livechatData.${ key }`]: value } }; @@ -219,7 +219,7 @@ RocketChat.models.Users.getNextVisitorUsername = function() { const livechatCount = findAndModify(query, null, update); - return 'guest-' + (livechatCount.value.value + 1); + return `guest-${ livechatCount.value.value + 1 }`; }; RocketChat.models.Users.saveGuestById = function(_id, data) { @@ -273,7 +273,7 @@ RocketChat.models.Users.saveGuestById = function(_id, data) { RocketChat.models.Users.findOneGuestByEmailAddress = function(emailAddress) { const query = { - 'visitorEmails.address': new RegExp('^' + s.escapeRegExp(emailAddress) + '$', 'i') + 'visitorEmails.address': new RegExp(`^${ s.escapeRegExp(emailAddress) }$`, 'i') }; return this.findOne(query); diff --git a/packages/rocketchat-logger/ansispan.js b/packages/rocketchat-logger/ansispan.js index 550cb2f7fef..0a494a139fc 100644 --- a/packages/rocketchat-logger/ansispan.js +++ b/packages/rocketchat-logger/ansispan.js @@ -5,17 +5,17 @@ ansispan = function(str) { str = str.replace(/'; + const span = ``; // // `\033[Xm` == `\033[0;Xm` sets foreground color to `X`. // str = str.replace( - new RegExp('\0o33\\[' + ansi + 'm', 'g'), + new RegExp(`\0o33\\[${ ansi }m`, 'g'), span ).replace( - new RegExp('\0o33\\[0;' + ansi + 'm', 'g'), + new RegExp(`\0o33\\[0;${ ansi }m`, 'g'), span ); }); diff --git a/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js b/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js index befaab73f6d..5d59bbc3a57 100644 --- a/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js +++ b/packages/rocketchat-message-mark-as-unread/server/unreadMessages.js @@ -24,7 +24,7 @@ Meteor.methods({ if (firstUnreadMessage.ts >= lastSeen) { return logger.connection.debug('Provided message is already marked as unread'); } - logger.connection.debug('Updating unread message of ' + originalMessage.ts + ' as the first unread'); + logger.connection.debug(`Updating unread message of ${ originalMessage.ts } as the first unread`); return RocketChat.models.Subscriptions.setAsUnreadByRoomIdAndUserId(originalMessage.rid, Meteor.userId(), originalMessage.ts); } }); diff --git a/packages/rocketchat-message-snippet/client/actionButton.js b/packages/rocketchat-message-snippet/client/actionButton.js index 0ba1eb676a0..53d6b0d711f 100644 --- a/packages/rocketchat-message-snippet/client/actionButton.js +++ b/packages/rocketchat-message-snippet/client/actionButton.js @@ -32,7 +32,7 @@ Meteor.startup(function() { if (error) { return handleError(error); } - swal('Nice!', `Snippet '${filename}' created.`, 'success'); + swal('Nice!', `Snippet '${ filename }' created.`, 'success'); }); }); diff --git a/packages/rocketchat-message-snippet/client/messageType.js b/packages/rocketchat-message-snippet/client/messageType.js index f7fe37c7f30..f6fa6da3399 100644 --- a/packages/rocketchat-message-snippet/client/messageType.js +++ b/packages/rocketchat-message-snippet/client/messageType.js @@ -4,7 +4,7 @@ Meteor.startup(function() { system: true, message: 'Snippeted_a_message', data(message) { - const snippetLink = `${message.snippetName}`; + const snippetLink = `${ message.snippetName }`; return { snippetLink }; } }); diff --git a/packages/rocketchat-message-snippet/client/tabBar/views/snippetMessage.js b/packages/rocketchat-message-snippet/client/tabBar/views/snippetMessage.js index b5bceb98c9f..2f4d0967e5e 100644 --- a/packages/rocketchat-message-snippet/client/tabBar/views/snippetMessage.js +++ b/packages/rocketchat-message-snippet/client/tabBar/views/snippetMessage.js @@ -13,6 +13,6 @@ Template.snippetMessage.helpers({ } }, body() { - return `${this.snippetName}`; + return `${ this.snippetName }`; } }); diff --git a/packages/rocketchat-message-snippet/server/requests.js b/packages/rocketchat-message-snippet/server/requests.js index 2f3008d9567..5f9a9513473 100644 --- a/packages/rocketchat-message-snippet/server/requests.js +++ b/packages/rocketchat-message-snippet/server/requests.js @@ -45,7 +45,7 @@ WebApp.connectHandlers.use('/snippet/download', function(req, res) { return false; } - res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(snippet.snippetName)}`); + res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${ encodeURIComponent(snippet.snippetName) }`); res.setHeader('Content-Type', 'application/octet-stream'); // Removing the ``` contained in the msg. diff --git a/packages/rocketchat-otr/client/rocketchat.otr.room.js b/packages/rocketchat-otr/client/rocketchat.otr.room.js index 81786a388ad..47513a7e8c9 100644 --- a/packages/rocketchat-otr/client/rocketchat.otr.room.js +++ b/packages/rocketchat-otr/client/rocketchat.otr.room.js @@ -53,7 +53,7 @@ RocketChat.OTR.Room = class { } this.userOnlineComputation = Tracker.autorun(() => { - const $room = $('#chat-window-' + this.roomId); + const $room = $(`#chat-window-${ this.roomId }`); const $title = $('.fixed-title h2', $room); if (this.established.get()) { if ($room.length && $title.length && !$('.otr-icon', $title).length) { @@ -202,7 +202,7 @@ RocketChat.OTR.Room = class { } swal({ - title: '' + TAPi18n.__('OTR'), + title: `${ TAPi18n.__('OTR') }`, text: TAPi18n.__('Username_wants_to_start_otr_Do_you_want_to_accept', { username: user.username }), html: true, showCancelButton: true, @@ -237,7 +237,7 @@ RocketChat.OTR.Room = class { this.reset(); const user = Meteor.users.findOne(this.peerId); swal({ - title: '' + TAPi18n.__('OTR'), + title: `${ TAPi18n.__('OTR') }`, text: TAPi18n.__('Username_denied_the_OTR_session', { username: user.username }), html: true }); @@ -249,7 +249,7 @@ RocketChat.OTR.Room = class { this.reset(); const user = Meteor.users.findOne(this.peerId); swal({ - title: '' + TAPi18n.__('OTR'), + title: `${ TAPi18n.__('OTR') }`, text: TAPi18n.__('Username_ended_the_OTR_session', { username: user.username }), html: true }); diff --git a/packages/rocketchat-push-notifications/client/views/pushNotificationsFlexTab.js b/packages/rocketchat-push-notifications/client/views/pushNotificationsFlexTab.js index fb813ac0445..e83f4bc12be 100644 --- a/packages/rocketchat-push-notifications/client/views/pushNotificationsFlexTab.js +++ b/packages/rocketchat-push-notifications/client/views/pushNotificationsFlexTab.js @@ -162,7 +162,7 @@ Template.pushNotificationsFlexTab.onCreated(function() { case 'audioNotification': return true; default: - const value = this.$('input[name='+ field +']:checked').val(); + const value = this.$(`input[name=${ field }]:checked`).val(); if (['all', 'mentions', 'nothing', 'default'].indexOf(value) === -1) { toastr.error(t('Invalid_notification_setting_s', value || '')); return false; @@ -176,10 +176,10 @@ Template.pushNotificationsFlexTab.onCreated(function() { let value; switch (field) { case 'audioNotification': - value = this.$('select[name='+field+']').val(); + value = this.$(`select[name=${ field }]`).val(); break; default: - value = this.$('input[name='+ field +']:checked').val(); + value = this.$(`input[name=${ field }]:checked`).val(); break; } const duration = $('input[name=duration]').val(); @@ -231,14 +231,14 @@ Template.pushNotificationsFlexTab.events({ e.preventDefault(); let audio = $(e.currentTarget).data('play'); if (audio && audio !== 'none') { - const $audio = $('audio#' + audio); + const $audio = $(`audio#${ audio }`); if ($audio && $audio[0] && $audio[0].play) { $audio[0].play(); } } else { audio = Meteor.user() && Meteor.user().settings && Meteor.user().settings.preferences && Meteor.user().settings.preferences.newMessageNotification || 'chime'; if (audio && audio !== 'none') { - const $audio = $('audio#' + audio); + const $audio = $(`audio#${ audio }`); if ($audio && $audio[0] && $audio[0].play) { $audio[0].play(); } @@ -250,7 +250,7 @@ Template.pushNotificationsFlexTab.events({ e.preventDefault(); const audio = $(e.currentTarget).val(); if (audio && audio !== 'none') { - const $audio = $('audio#' + audio); + const $audio = $(`audio#${ audio }`); if ($audio && $audio[0] && $audio[0].play) { $audio[0].play(); } diff --git a/packages/rocketchat-reactions/client/init.js b/packages/rocketchat-reactions/client/init.js index 393a3d3f063..6b3d3ce54d5 100644 --- a/packages/rocketchat-reactions/client/init.js +++ b/packages/rocketchat-reactions/client/init.js @@ -12,7 +12,7 @@ Template.room.events({ } RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => { - Meteor.call('setReaction', ':' + emoji + ':', data._arguments[1]._id); + Meteor.call('setReaction', `:${ emoji }:`, data._arguments[1]._id); }); }, @@ -50,7 +50,7 @@ Meteor.startup(function() { event.stopPropagation(); RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => { - Meteor.call('setReaction', ':' + emoji + ':', data._arguments[1]._id); + Meteor.call('setReaction', `:${ emoji }:`, data._arguments[1]._id); }); }, validation(message) { diff --git a/packages/rocketchat-sandstorm/server/powerbox.js b/packages/rocketchat-sandstorm/server/powerbox.js index 68f6d9513e8..87e8cb86f9a 100644 --- a/packages/rocketchat-sandstorm/server/powerbox.js +++ b/packages/rocketchat-sandstorm/server/powerbox.js @@ -31,7 +31,7 @@ if (process.env.SANDSTORM === '1') { const viewInfo = waitPromise(cap.getViewInfo()); const appTitle = viewInfo.appTitle; const asset = waitPromise(viewInfo.grainIcon.getUrl()); - const appIconUrl = asset.protocol + '://' + asset.hostPath; + const appIconUrl = `${ asset.protocol }://${ asset.hostPath }`; return { token: newToken, appTitle, diff --git a/packages/rocketchat-slackbridge/slackbridge.js b/packages/rocketchat-slackbridge/slackbridge.js index 21fa5a898f3..2dd320a735f 100644 --- a/packages/rocketchat-slackbridge/slackbridge.js +++ b/packages/rocketchat-slackbridge/slackbridge.js @@ -179,7 +179,7 @@ class SlackBridge { findRocketUser(slackUserID) { const rocketUser = RocketChat.models.Users.findOneByImportId(slackUserID); if (rocketUser && !this.userTags[slackUserID]) { - this.userTags[slackUserID] = { slack: `<@${slackUserID}>`, rocket: `@${rocketUser.username}` }; + this.userTags[slackUserID] = { slack: `<@${ slackUserID }>`, rocket: `@${ rocketUser.username }` }; } return rocketUser; } @@ -257,7 +257,7 @@ class SlackBridge { } RocketChat.models.Users.addImportIds(rocketUserData.rocketId, importIds); if (!this.userTags[slackUserID]) { - this.userTags[slackUserID] = { slack: `<@${slackUserID}>`, rocket: `@${rocketUserData.name}` }; + this.userTags[slackUserID] = { slack: `<@${ slackUserID }>`, rocket: `@${ rocketUserData.name }` }; } return RocketChat.models.Users.findOneById(rocketUserData.rocketId); } @@ -339,7 +339,7 @@ class SlackBridge { } if (rocketMsg && rocketUser) { - const rocketReaction = ':' + slackReactionMsg.reaction + ':'; + const rocketReaction = `:${ slackReactionMsg.reaction }:`; //If the Rocket user has already been removed, then this is an echo back from slack if (rocketMsg.reactions) { @@ -355,7 +355,7 @@ class SlackBridge { } //Stash this away to key off it later so we don't send it back to Slack - this.reactionsMap.set('unset'+rocketMsg._id+rocketReaction, rocketUser); + this.reactionsMap.set(`unset${ rocketMsg._id }${ rocketReaction }`, rocketUser); logger.class.debug('Removing reaction from Slack'); Meteor.runAsUser(rocketUser._id, () => { Meteor.call('setReaction', rocketReaction, rocketMsg._id); @@ -385,7 +385,7 @@ class SlackBridge { } if (rocketMsg && rocketUser) { - const rocketReaction = ':' + slackReactionMsg.reaction + ':'; + const rocketReaction = `:${ slackReactionMsg.reaction }:`; //If the Rocket user has already reacted, then this is Slack echoing back to us if (rocketMsg.reactions) { @@ -398,7 +398,7 @@ class SlackBridge { } //Stash this away to key off it later so we don't send it back to Slack - this.reactionsMap.set('set'+rocketMsg._id+rocketReaction, rocketUser); + this.reactionsMap.set(`set${ rocketMsg._id }${ rocketReaction }`, rocketUser); logger.class.debug('Adding reaction from Slack'); Meteor.runAsUser(rocketUser._id, () => { Meteor.call('setReaction', rocketReaction, rocketMsg._id); @@ -452,7 +452,7 @@ class SlackBridge { return rocketMsgObj; case 'me_message': return this.addAliasToRocketMsg(rocketUser.username, { - msg: `_${this.convertSlackMsgTxtToRocketTxtFormat(slackMessage.text)}_` + msg: `_${ this.convertSlackMsgTxtToRocketTxtFormat(slackMessage.text) }_` }); case 'channel_join': if (isImporting) { @@ -528,7 +528,7 @@ class SlackBridge { case 'file_share': if (slackMessage.file && slackMessage.file.url_private_download !== undefined) { const details = { - message_id: `slack-${slackMessage.ts.replace(/\./g, '-')}`, + message_id: `slack-${ slackMessage.ts.replace(/\./g, '-') }`, name: slackMessage.file.name, size: slackMessage.file.size, type: slackMessage.file.mimetype, @@ -562,7 +562,7 @@ class SlackBridge { }; if (!isImporting) { - RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${slackMessage.attachments[0].channel_id}-${slackMessage.attachments[0].ts.replace(/\./g, '-')}`, rocketMsgObj.u, true, new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000)); + RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${ slackMessage.attachments[0].channel_id }-${ slackMessage.attachments[0].ts.replace(/\./g, '-') }`, rocketMsgObj.u, true, new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000)); } return rocketMsgObj; @@ -589,7 +589,7 @@ class SlackBridge { const url = Npm.require('url'); const requestModule = /https/i.test(slackFileURL) ? Npm.require('https') : Npm.require('http'); const parsedUrl = url.parse(slackFileURL, true); - parsedUrl.headers = { 'Authorization': 'Bearer ' + this.apiToken }; + parsedUrl.headers = { 'Authorization': `Bearer ${ this.apiToken }` }; requestModule.get(parsedUrl, Meteor.bindEnvironment((stream) => { const fileId = Meteor.fileStore.create(details); if (fileId) { @@ -600,7 +600,7 @@ class SlackBridge { } else { const url = file.url.replace(Meteor.absoluteUrl(), '/'); const attachment = { - title: `File Uploaded: ${file.name}`, + title: `File Uploaded: ${ file.name }`, title_link: url }; @@ -919,7 +919,7 @@ class SlackBridge { importFromHistory(family, options) { logger.class.debug('Importing messages history'); - const response = HTTP.get('https://slack.com/api/' + family + '.history', { params: _.extend({ token: this.apiToken }, options) }); + const response = HTTP.get(`https://slack.com/api/${ family }.history`, { params: _.extend({ token: this.apiToken }, options) }); if (response && response.data && _.isArray(response.data.messages) && response.data.messages.length > 0) { let latest = 0; for (const message of response.data.messages.reverse()) { @@ -936,7 +936,7 @@ class SlackBridge { copySlackChannelInfo(rid, channelMap) { logger.class.debug('Copying users from Slack channel to Rocket.Chat', channelMap.id, rid); - const response = HTTP.get('https://slack.com/api/' + channelMap.family + '.info', { params: { token: this.apiToken, channel: channelMap.id } }); + const response = HTTP.get(`https://slack.com/api/${ channelMap.family }.info`, { params: { token: this.apiToken, channel: channelMap.id } }); if (response && response.data) { const data = channelMap.family === 'channels' ? response.data.channel : response.data.group; if (data && _.isArray(data.members) && data.members.length > 0) { @@ -1000,7 +1000,7 @@ class SlackBridge { }] }; - RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${pin.channel}-${pin.message.ts.replace(/\./g, '-')}`, msgObj.u, true, new Date(parseInt(pin.message.ts.split('.')[0]) * 1000)); + RocketChat.models.Messages.setPinnedByIdAndUserId(`slack-${ pin.channel }-${ pin.message.ts.replace(/\./g, '-') }`, msgObj.u, true, new Date(parseInt(pin.message.ts.split('.')[0]) * 1000)); } } } @@ -1071,7 +1071,7 @@ class SlackBridge { logger.class.debug('onRocketSetReaction'); if (rocketMsgID && reaction) { - if (this.reactionsMap.delete('set'+rocketMsgID+reaction)) { + if (this.reactionsMap.delete(`set${ rocketMsgID }${ reaction }`)) { //This was a Slack reaction, we don't need to tell Slack about it return; } @@ -1088,7 +1088,7 @@ class SlackBridge { logger.class.debug('onRocketUnSetReaction'); if (rocketMsgID && reaction) { - if (this.reactionsMap.delete('unset'+rocketMsgID+reaction)) { + if (this.reactionsMap.delete(`unset${ rocketMsgID }${ reaction }`)) { //This was a Slack unset reaction, we don't need to tell Slack about it return; } @@ -1199,7 +1199,7 @@ class SlackBridge { const postResult = HTTP.post('https://slack.com/api/chat.postMessage', { params: data }); if (postResult.statusCode === 200 && postResult.data && postResult.data.message && postResult.data.message.bot_id && postResult.data.message.ts) { RocketChat.models.Messages.setSlackBotIdAndSlackTs(rocketMessage._id, postResult.data.message.bot_id, postResult.data.message.ts); - logger.class.debug('RocketMsgID=' + rocketMessage._id + ' SlackMsgID=' + postResult.data.message.ts + ' SlackBotID=' + postResult.data.message.bot_id); + logger.class.debug(`RocketMsgID=${ rocketMessage._id } SlackMsgID=${ postResult.data.message.ts } SlackBotID=${ postResult.data.message.bot_id }`); } } } @@ -1357,7 +1357,7 @@ class SlackBridge { } createRocketID(slackChannel, ts) { - return `slack-${slackChannel}-${ts.replace(/\./g, '-')}`; + return `slack-${ slackChannel }-${ ts.replace(/\./g, '-') }`; } } diff --git a/packages/rocketchat-slashcommand-asciiarts/gimme.js b/packages/rocketchat-slashcommand-asciiarts/gimme.js index 340236c9db9..f8997115d32 100644 --- a/packages/rocketchat-slashcommand-asciiarts/gimme.js +++ b/packages/rocketchat-slashcommand-asciiarts/gimme.js @@ -7,7 +7,7 @@ function Gimme(command, params, item) { if (command === 'gimme') { const msg = item; - msg.msg = '༼ つ ◕_◕ ༽つ ' + params; + msg.msg = `༼ つ ◕_◕ ༽つ ${ params }`; Meteor.call('sendMessage', msg); } } diff --git a/packages/rocketchat-slashcommand-asciiarts/lenny.js b/packages/rocketchat-slashcommand-asciiarts/lenny.js index 8ab03a02b2c..5272a7b6786 100644 --- a/packages/rocketchat-slashcommand-asciiarts/lenny.js +++ b/packages/rocketchat-slashcommand-asciiarts/lenny.js @@ -7,7 +7,7 @@ function LennyFace(command, params, item) { if (command === 'lennyface') { const msg = item; - msg.msg = params + ' ( ͡° ͜ʖ ͡°)'; + msg.msg = `${ params } ( ͡° ͜ʖ ͡°)`; Meteor.call('sendMessage', msg); } } diff --git a/packages/rocketchat-slashcommand-asciiarts/shrug.js b/packages/rocketchat-slashcommand-asciiarts/shrug.js index 9bf47b6d442..656c739e354 100644 --- a/packages/rocketchat-slashcommand-asciiarts/shrug.js +++ b/packages/rocketchat-slashcommand-asciiarts/shrug.js @@ -7,7 +7,7 @@ function Shrug(command, params, item) { if (command === 'shrug') { const msg = item; - msg.msg = params + ' ¯\\_(ツ)_/¯'; + msg.msg = `${ params } ¯\\_(ツ)_/¯`; Meteor.call('sendMessage', msg); } } diff --git a/packages/rocketchat-slashcommand-asciiarts/tableflip.js b/packages/rocketchat-slashcommand-asciiarts/tableflip.js index 6f1caffc848..1d7d172c628 100644 --- a/packages/rocketchat-slashcommand-asciiarts/tableflip.js +++ b/packages/rocketchat-slashcommand-asciiarts/tableflip.js @@ -7,7 +7,7 @@ function Tableflip(command, params, item) { if (command === 'tableflip') { const msg = item; - msg.msg = params + ' (╯°□°)╯︵ ┻━┻'; + msg.msg = `${ params } (╯°□°)╯︵ ┻━┻`; Meteor.call('sendMessage', msg); } } diff --git a/packages/rocketchat-slashcommand-asciiarts/unflip.js b/packages/rocketchat-slashcommand-asciiarts/unflip.js index 7d83d42f952..3df04e43d6c 100644 --- a/packages/rocketchat-slashcommand-asciiarts/unflip.js +++ b/packages/rocketchat-slashcommand-asciiarts/unflip.js @@ -7,7 +7,7 @@ function Unflip(command, params, item) { if (command === 'unflip') { const msg = item; - msg.msg = params + ' ┬─┬ ノ( ゜-゜ノ)'; + msg.msg = `${ params } ┬─┬ ノ( ゜-゜ノ)`; Meteor.call('sendMessage', msg); } } diff --git a/packages/rocketchat-smarsh-connector/server/functions/generateEml.js b/packages/rocketchat-smarsh-connector/server/functions/generateEml.js index 58c884a0a5b..b4ce38d6b7b 100644 --- a/packages/rocketchat-smarsh-connector/server/functions/generateEml.js +++ b/packages/rocketchat-smarsh-connector/server/functions/generateEml.js @@ -39,7 +39,7 @@ RocketChat.smarsh.generateEml = () => { msgs: 0, files: [], time: smarshHistory ? moment(date).diff(moment(smarshHistory.lastRan), 'minutes') : moment(date).diff(moment(room.ts), 'minutes'), - room: room.name ? `#${room.name}` : `Direct Message Between: ${room.usernames.join(' & ')}` + room: room.name ? `#${ room.name }` : `Direct Message Between: ${ room.usernames.join(' & ') }` }; RocketChat.models.Messages.find(query).forEach((message) => { @@ -59,9 +59,9 @@ RocketChat.smarsh.generateEml = () => { //Get the user's email, can be nothing if it is an unconfigured bot account (like rocket.cat) if (sender.emails && sender.emails[0] && sender.emails[0].address) { - rows.push(`${sender.name} <${sender.emails[0].address}>`); + rows.push(`${ sender.name } <${ sender.emails[0].address }>`); } else { - rows.push(`${sender.name} <${smarshMissingEmail}>`); + rows.push(`${ sender.name } <${ smarshMissingEmail }>`); } rows.push(closetd); @@ -73,11 +73,11 @@ RocketChat.smarsh.generateEml = () => { if (messageType) { rows.push(TAPi18n.__(messageType.message, messageType.data ? messageType.data(message) : '', 'en')); } else { - rows.push(`${message.msg} (${message.t})`); + rows.push(`${ message.msg } (${ message.t })`); } } else if (message.file) { data.files.push(message.file._id); - rows.push(`${message.attachments[0].title} (${_getLink(message.attachments[0])})`); + rows.push(`${ message.attachments[0].title } (${ _getLink(message.attachments[0]) })`); } else if (message.attachments) { const attaches = []; _.each(message.attachments, function _loopThroughMessageAttachments(a) { @@ -90,7 +90,7 @@ RocketChat.smarsh.generateEml = () => { // } }); - rows.push(`${message.msg} (${attaches.join(', ')})`); + rows.push(`${ message.msg } (${ attaches.join(', ') })`); } else { rows.push(message.msg); } @@ -110,7 +110,7 @@ RocketChat.smarsh.generateEml = () => { RocketChat.smarsh.sendEmail({ body: result, - subject: `Rocket.Chat, ${data.users.length} Users, ${data.msgs} Messages, ${data.files.length} Files, ${data.time} Minutes, in ${data.room}`, + subject: `Rocket.Chat, ${ data.users.length } Users, ${ data.msgs } Messages, ${ data.files.length } Files, ${ data.time } Minutes, in ${ data.room }`, files: data.files }); } diff --git a/packages/rocketchat-sms/services/twilio.js b/packages/rocketchat-sms/services/twilio.js index 2dc82ee4ad5..e9e9ad2d165 100644 --- a/packages/rocketchat-sms/services/twilio.js +++ b/packages/rocketchat-sms/services/twilio.js @@ -42,13 +42,13 @@ class Twilio { error(error) { let message = ''; if (error.reason) { - message = `${error.reason}`; + message = `${ error.reason }`; } return { headers: { 'Content-Type': 'text/xml' }, - body: `${message}` + body: `${ message }` }; } } diff --git a/packages/rocketchat-spotify/lib/spotify.js b/packages/rocketchat-spotify/lib/spotify.js index 0e6b633da29..501822d81b6 100644 --- a/packages/rocketchat-spotify/lib/spotify.js +++ b/packages/rocketchat-spotify/lib/spotify.js @@ -37,8 +37,8 @@ class Spotify { while ((match = re.exec(part))) { const data = _.filter(match.slice(1), value => value != null); const path = _.map(data, value => _.escape(value)).join('/'); - const url = `https://open.spotify.com/${path}`; - urls.push({url, 'source': `spotify:${data.join(':')}`}); + const url = `https://open.spotify.com/${ path }`; + urls.push({url, 'source': `spotify:${ data.join(':') }`}); changed = true; } @@ -58,8 +58,8 @@ class Spotify { for (const item of Array.from(message.urls)) { if (item.source) { const quotedSource = item.source.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'); - const re = new RegExp(`(^|\\s)${quotedSource}(\\s|$)`, 'g'); - msgParts[index] = part.replace(re, `$1${item.source}$2`); + const re = new RegExp(`(^|\\s)${ quotedSource }(\\s|$)`, 'g'); + msgParts[index] = part.replace(re, `$1${ item.source }$2`); } } return message.html = msgParts.join(''); diff --git a/packages/rocketchat-tooltip/rocketchat-tooltip.js b/packages/rocketchat-tooltip/rocketchat-tooltip.js index 658a9c43eb9..c733281aa1a 100644 --- a/packages/rocketchat-tooltip/rocketchat-tooltip.js +++ b/packages/rocketchat-tooltip/rocketchat-tooltip.js @@ -61,7 +61,7 @@ RocketChat.tooltip = { if (left < 0) { $('.tooltip .tooltip-arrow').css({ - 'margin-left': (left - 5) + 'px' + 'margin-left': `${ left - 5 }px` }); left = 0; } else { @@ -79,8 +79,8 @@ RocketChat.tooltip = { return tip .css({ - top: top + 'px', - left: left + 'px' + top: `${ top }px`, + left: `${ left }px` }); } }; diff --git a/packages/rocketchat-tutum/startup.js b/packages/rocketchat-tutum/startup.js index 0d59d8450ed..c71d01e8812 100644 --- a/packages/rocketchat-tutum/startup.js +++ b/packages/rocketchat-tutum/startup.js @@ -12,14 +12,14 @@ if (process.env.DOCKERCLOUD_REDIS_HOST != null) { client.on('error', err => console.log('Redis error ->', err)); - client.del(`frontend:${process.env.DOCKERCLOUD_CLIENT_HOST}`); - client.rpush(`frontend:${process.env.DOCKERCLOUD_CLIENT_HOST}`, process.env.DOCKERCLOUD_CLIENT_NAME); + client.del(`frontend:${ process.env.DOCKERCLOUD_CLIENT_HOST }`); + client.rpush(`frontend:${ process.env.DOCKERCLOUD_CLIENT_HOST }`, process.env.DOCKERCLOUD_CLIENT_NAME); const port = process.env.PORT || 3000; - client.rpush(`frontend:${process.env.DOCKERCLOUD_CLIENT_HOST}`, `http://${process.env.DOCKERCLOUD_IP_ADDRESS.split('/')[0]}:${port}`); + client.rpush(`frontend:${ process.env.DOCKERCLOUD_CLIENT_HOST }`, `http://${ process.env.DOCKERCLOUD_IP_ADDRESS.split('/')[0] }:${ port }`); // removes the redis entry in 90 seconds on a SIGTERM - process.on('SIGTERM', () => client.expire(`frontend:${process.env.DOCKERCLOUD_CLIENT_HOST}`, 90)); + process.on('SIGTERM', () => client.expire(`frontend:${ process.env.DOCKERCLOUD_CLIENT_HOST }`, 90)); - process.on('SIGINT', () => client.expire(`frontend:${process.env.DOCKERCLOUD_CLIENT_HOST}`, 90)); + process.on('SIGINT', () => client.expire(`frontend:${ process.env.DOCKERCLOUD_CLIENT_HOST }`, 90)); } diff --git a/packages/rocketchat-ui-flextab/client/tabs/membersList.js b/packages/rocketchat-ui-flextab/client/tabs/membersList.js index 54e721a5674..826854bb1b2 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/membersList.js +++ b/packages/rocketchat-ui-flextab/client/tabs/membersList.js @@ -38,9 +38,9 @@ Template.membersList.helpers({ if (utcOffset === userUtcOffset) { utcOffset = ''; } else if (utcOffset > 0) { - utcOffset = `+${utcOffset}`; + utcOffset = `+${ utcOffset }`; } else { - utcOffset = `(UTC ${utcOffset})`; + utcOffset = `(UTC ${ utcOffset })`; } } } @@ -79,7 +79,7 @@ Template.membersList.helpers({ }, canAddUser() { - const roomData = Session.get(`roomData${this._id}`); + const roomData = Session.get(`roomData${ this._id }`); if (!roomData) { return ''; } return (() => { switch (roomData.t) { @@ -150,7 +150,7 @@ Template.membersList.events({ 'autocompleteselect #user-add-search'(event, template, doc) { - const roomData = Session.get(`roomData${template.data.rid}`); + const roomData = Session.get(`roomData${ template.data.rid }`); if (['c', 'p'].includes(roomData.t)) { return Meteor.call('addUserToRoom', { rid: roomData._id, username: doc.username }, function(error) { diff --git a/packages/rocketchat-ui-flextab/client/tabs/messageSearch.js b/packages/rocketchat-ui-flextab/client/tabs/messageSearch.js index 74fa53ac44f..e62719d4d32 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/messageSearch.js +++ b/packages/rocketchat-ui-flextab/client/tabs/messageSearch.js @@ -75,13 +75,13 @@ Template.messageSearch.events({ const message_id = $(e.currentTarget).closest('.message').attr('id'); const searchResult = t.searchResult.get(); RocketChat.MessageAction.hideDropDown(); - t.$(`\#${message_id} .message-dropdown`).remove(); + t.$(`\#${ message_id } .message-dropdown`).remove(); if (searchResult) { const message = _.findWhere(searchResult.messages, { _id: message_id }); const actions = RocketChat.MessageAction.getButtons(message, 'search'); const el = Blaze.toHTMLWithData(Template.messageDropdown, { actions }); - t.$(`\#${message_id} .message-cog-container`).append(el); - const dropDown = t.$(`\#${message_id} .message-dropdown`); + t.$(`\#${ message_id } .message-cog-container`).append(el); + const dropDown = t.$(`\#${ message_id } .message-dropdown`); return dropDown.show(); } }, diff --git a/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js b/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js index 38539524e97..056967d6871 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js +++ b/packages/rocketchat-ui-flextab/client/tabs/uploadedFilesList.js @@ -37,7 +37,7 @@ Template.uploadedFilesList.helpers({ }, url() { - return `/file-upload/${this._id}/${this.name}`; + return `/file-upload/${ this._id }/${ this.name }`; }, fixCordova(url) { @@ -47,11 +47,11 @@ Template.uploadedFilesList.helpers({ if (Meteor.isCordova && ((url != null ? url[0] : undefined) === '/')) { url = Meteor.absoluteUrl().replace(/\/$/, '') + url; - const query = `rc_uid=${Meteor.userId()}&rc_token=${Meteor._localStorage.getItem('Meteor.loginToken')}`; + const query = `rc_uid=${ Meteor.userId() }&rc_token=${ Meteor._localStorage.getItem('Meteor.loginToken') }`; if (url.indexOf('?') === -1) { - url = url + '?' + query; + url = `${ url }?${ query }`; } else { - url = url + '&' + query; + url = `${ url }&${ query }`; } } diff --git a/packages/rocketchat-ui-flextab/client/tabs/userInfo.js b/packages/rocketchat-ui-flextab/client/tabs/userInfo.js index ac8ec8ac70e..2ec2dbc6cd0 100644 --- a/packages/rocketchat-ui-flextab/client/tabs/userInfo.js +++ b/packages/rocketchat-ui-flextab/client/tabs/userInfo.js @@ -22,7 +22,7 @@ Template.userInfo.helpers({ const user = Template.instance().user.get(); if (user && user.utcOffset != null) { if (user.utcOffset > 0) { - return `+${user.utcOffset}`; + return `+${ user.utcOffset }`; } return user.utcOffset; } diff --git a/packages/rocketchat-ui-master/server/inject.js b/packages/rocketchat-ui-master/server/inject.js index 42a92b4bbb3..5c022c0ca76 100644 --- a/packages/rocketchat-ui-master/server/inject.js +++ b/packages/rocketchat-ui-master/server/inject.js @@ -75,7 +75,7 @@ RocketChat.settings.get('Assets_SvgFavicon_Enable', (key, value) => { if (value) { Inject.rawHead(key, - `${standardFavicons} + `${ standardFavicons } `); } else { Inject.rawHead(key, standardFavicons); @@ -83,9 +83,9 @@ RocketChat.settings.get('Assets_SvgFavicon_Enable', (key, value) => { }); RocketChat.settings.get('theme-color-primary-background-color', (key, value = '#04436a') => { - Inject.rawHead(key, `` + - `` + - ``); + Inject.rawHead(key, `` + + `` + + ``); }); RocketChat.settings.get('Accounts_ForgetUserSessionOnWindowClose', (key, value) => { @@ -98,7 +98,7 @@ RocketChat.settings.get('Accounts_ForgetUserSessionOnWindowClose', (key, value) } `; - return html.replace(/<\/body>/, script + '\n'); + return html.replace(/<\/body>/, `${ script }\n`); }); } else { Inject.rawModHtml(key, (html) => { @@ -109,31 +109,31 @@ RocketChat.settings.get('Accounts_ForgetUserSessionOnWindowClose', (key, value) RocketChat.settings.get('Site_Name', (key, value = 'Rocket.Chat') => { Inject.rawHead(key, - `${value}` + - `` + - ``); + `${ value }` + + `` + + ``); }); RocketChat.settings.get('Meta_language', (key, value = '') => { Inject.rawHead(key, - `` + - ``); + `` + + ``); }); RocketChat.settings.get('Meta_robots', (key, value = '') => { - Inject.rawHead(key, ``); + Inject.rawHead(key, ``); }); RocketChat.settings.get('Meta_msvalidate01', (key, value = '') => { - Inject.rawHead(key, ``); + Inject.rawHead(key, ``); }); RocketChat.settings.get('Meta_google-site-verification', (key, value = '') => { - Inject.rawHead(key, ``); + Inject.rawHead(key, ``); }); RocketChat.settings.get('Meta_fb_app_id', (key, value = '') => { - Inject.rawHead(key, ``); + Inject.rawHead(key, ``); }); RocketChat.settings.get('Meta_custom', (key, value = '') => { @@ -150,6 +150,6 @@ Meteor.defer(() => { if (/\/$/.test(baseUrl) === false) { baseUrl += '/'; } - Inject.rawHead('base', ``); + Inject.rawHead('base', ``); }); diff --git a/packages/rocketchat-ui-sidenav/client/accountBox.js b/packages/rocketchat-ui-sidenav/client/accountBox.js index 0e9ed0a96aa..8ba0b4cfe51 100644 --- a/packages/rocketchat-ui-sidenav/client/accountBox.js +++ b/packages/rocketchat-ui-sidenav/client/accountBox.js @@ -2,7 +2,7 @@ Template.accountBox.helpers({ myUserInfo() { let visualStatus = 'online'; const username = Meteor.user() && Meteor.user().username; - switch (Session.get('user_' + username + '_status')) { + switch (Session.get(`user_${ username }_status`)) { case 'away': visualStatus = t('away'); break; @@ -14,8 +14,8 @@ Template.accountBox.helpers({ break; } return { - name: Session.get('user_' + username + '_name'), - status: Session.get('user_' + username + '_status'), + name: Session.get(`user_${ username }_name`), + status: Session.get(`user_${ username }_status`), visualStatus, _id: Meteor.userId(), username diff --git a/packages/rocketchat-ui-sidenav/client/chatRoomItem.js b/packages/rocketchat-ui-sidenav/client/chatRoomItem.js index 4d6e64bf8de..96844128dfd 100644 --- a/packages/rocketchat-ui-sidenav/client/chatRoomItem.js +++ b/packages/rocketchat-ui-sidenav/client/chatRoomItem.js @@ -16,7 +16,7 @@ Template.chatRoomItem.helpers({ userStatus() { const userStatus = RocketChat.roomTypes.getUserStatus(this.t, this.rid); - return `status-${userStatus || 'offline'}`; + return `status-${ userStatus || 'offline' }`; }, name() { @@ -34,7 +34,7 @@ Template.chatRoomItem.helpers({ }, canLeave() { - const roomData = Session.get('roomData' + this.rid); + const roomData = Session.get(`roomData${ this.rid }`); if (!roomData) { return false; } diff --git a/packages/rocketchat-ui-sidenav/client/toolbar.js b/packages/rocketchat-ui-sidenav/client/toolbar.js index 163a25d2928..1c8d22e904e 100644 --- a/packages/rocketchat-ui-sidenav/client/toolbar.js +++ b/packages/rocketchat-ui-sidenav/client/toolbar.js @@ -94,9 +94,9 @@ Template.toolbar.helpers({ if (!Meteor.Device.isDesktop()) { return placeholder; } else if (window.navigator.platform.toLowerCase().includes('mac')) { - placeholder = placeholder+' (CMD+K)'; + placeholder = `${ placeholder } (CMD+K)`; } else { - placeholder = placeholder+' (Ctrl+K)'; + placeholder = `${ placeholder } (Ctrl+K)`; } return placeholder; @@ -214,9 +214,9 @@ Template.toolbarSearchList.helpers({ }, userStatus() { if (this.t === 'd') { - return 'status-' + (Session.get(`user_${this.name}_status`) || 'offline'); + return `status-${ Session.get(`user_${ this.name }_status`) || 'offline' }`; } else { - return 'status-' + (RocketChat.roomTypes.getUserStatus(this.t, this.rid || this._id) || 'offline'); + return `status-${ RocketChat.roomTypes.getUserStatus(this.t, this.rid || this._id) || 'offline' }`; } } }); diff --git a/packages/rocketchat-ui-vrecord/client/vrecord.js b/packages/rocketchat-ui-vrecord/client/vrecord.js index bae39734c0f..a72a7a14d58 100644 --- a/packages/rocketchat-ui-vrecord/client/vrecord.js +++ b/packages/rocketchat-ui-vrecord/client/vrecord.js @@ -39,7 +39,7 @@ Template.vrecDialog.events({ 'click .vrec-dialog .ok'() { const cb = blob => { - fileUpload([{ file: blob, type: 'video', name: TAPi18n.__('Video record') + '.webm' }]); + fileUpload([{ file: blob, type: 'video', name: `${ TAPi18n.__('Video record') }.webm` }]); VRecDialog.close(); }; VideoRecorder.stop(cb); diff --git a/packages/rocketchat-ui/client/lib/codeMirror/codeMirrorComponent.js b/packages/rocketchat-ui/client/lib/codeMirror/codeMirrorComponent.js index 283160f9254..60190e97c5d 100644 --- a/packages/rocketchat-ui/client/lib/codeMirror/codeMirrorComponent.js +++ b/packages/rocketchat-ui/client/lib/codeMirror/codeMirrorComponent.js @@ -36,7 +36,7 @@ Template.CodeMirror.rendered = function() { Template.CodeMirror.destroyed = function() { delete CodeMirrors[this.data.id || 'code-mirror-textarea']; - this.$('#' + (this.data.id || 'code-mirror-textarea')).next('.CodeMirror').remove(); + this.$(`#${ this.data.id || 'code-mirror-textarea' }`).next('.CodeMirror').remove(); }; Template.CodeMirror.helpers({ diff --git a/packages/rocketchat-ui/client/lib/iframeCommands.js b/packages/rocketchat-ui/client/lib/iframeCommands.js index 896f8b64abb..066bb3e1330 100644 --- a/packages/rocketchat-ui/client/lib/iframeCommands.js +++ b/packages/rocketchat-ui/client/lib/iframeCommands.js @@ -19,7 +19,7 @@ const commands = { }, event.origin); }; - const siteUrl = Meteor.settings.Site_Url + '/'; + const siteUrl = `${ Meteor.settings.Site_Url }/`; if (typeof data.redirectUrl !== 'string' || !data.redirectUrl.startsWith(siteUrl)) { data.redirectUrl = null; } @@ -28,7 +28,7 @@ const commands = { const customOauth = ServiceConfiguration.configurations.findOne({service: data.service}); if (customOauth) { - const customLoginWith = Meteor['loginWith' + _.capitalize(customOauth.service, true)]; + const customLoginWith = Meteor[`loginWith${ _.capitalize(customOauth.service, true) }`]; const customRedirectUri = data.redirectUrl || siteUrl; customLoginWith.call(Meteor, {'redirectUrl': customRedirectUri}, customOAuthCallback); } diff --git a/packages/rocketchat-ui/client/views/app/photoswipe.js b/packages/rocketchat-ui/client/views/app/photoswipe.js index beda817757b..7dbc1783062 100644 --- a/packages/rocketchat-ui/client/views/app/photoswipe.js +++ b/packages/rocketchat-ui/client/views/app/photoswipe.js @@ -44,7 +44,7 @@ Meteor.startup(() => { galleryOptions.index = images.index; galleryOptions.addCaptionHTMLFn = function(item, captionEl) { - captionEl.children[0].innerHTML = `${item.title}
    ${item.description} `; + captionEl.children[0].innerHTML = `${ item.title }
    ${ item.description } `; return true; }; diff --git a/packages/rocketchat-videobridge/client/tabBar.js b/packages/rocketchat-videobridge/client/tabBar.js index 6f143a29944..27119404462 100644 --- a/packages/rocketchat-videobridge/client/tabBar.js +++ b/packages/rocketchat-videobridge/client/tabBar.js @@ -29,7 +29,7 @@ Meteor.startup(function() { // Load from the jitsi meet instance. 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`); } // Compare current time to call started timeout. If its past then call is probably over. diff --git a/packages/rocketchat-videobridge/client/views/videoFlexTab.js b/packages/rocketchat-videobridge/client/views/videoFlexTab.js index 15829437616..08706abf593 100644 --- a/packages/rocketchat-videobridge/client/views/videoFlexTab.js +++ b/packages/rocketchat-videobridge/client/views/videoFlexTab.js @@ -71,11 +71,11 @@ Template.videoFlexTab.onRendered(function() { timeOut = Meteor.setInterval(() => Meteor.call('jitsi:updateTimeout', roomId), 10*1000); let newWindow = null; if (Meteor.isCordova) { - newWindow = window.open((noSsl ? 'http://' : 'https://') + domain + '/' + jitsiRoom, '_system'); + newWindow = window.open(`${ (noSsl ? 'http://' : 'https://') + domain }/${ jitsiRoom }`, '_system'); closePanel(); clearInterval(timeOut); } else { - newWindow = window.open((noSsl ? 'http://' : 'https://') + domain + '/' + jitsiRoom, jitsiRoom); + newWindow = window.open(`${ (noSsl ? 'http://' : 'https://') + domain }/${ jitsiRoom }`, jitsiRoom); const closeInterval = setInterval(() => { if (newWindow.closed !== false) { closePanel(); diff --git a/private/node_scripts/auto-translate.js b/private/node_scripts/auto-translate.js index b603b907f42..e78ad5eabc7 100644 --- a/private/node_scripts/auto-translate.js +++ b/private/node_scripts/auto-translate.js @@ -16,8 +16,8 @@ googleTranslate.getSupportedLanguages(function(err, langs) { } async.eachSeries(['../../packages/rocketchat-lib/i18n/', '../../packages/rocketchat-livechat/app/i18n/'], function(path, callback) { - console.log('Translating files in: ' + path); - const enContents = fs.readFileSync(path + 'en.i18n.json', 'utf-8'); + console.log(`Translating files in: ${ path }`); + const enContents = fs.readFileSync(`${ path }en.i18n.json`, 'utf-8'); const enUnsorted = JSON.parse(enContents); const en = {}; _.keys(enUnsorted).sort(function(a, b) { @@ -29,7 +29,7 @@ googleTranslate.getSupportedLanguages(function(err, langs) { }).forEach(function(key) { en[key] = enUnsorted[key]; }); - fs.writeFileSync(path + 'en.i18n.json', JSON.stringify(en, null, ' ').replace(/": "/g, '" : "'), 'utf8'); + fs.writeFileSync(`${ path }en.i18n.json`, JSON.stringify(en, null, ' ').replace(/": "/g, '" : "'), 'utf8'); const files = fs.readdirSync(path); async.eachSeries(files, function(file, callback) { @@ -48,7 +48,7 @@ googleTranslate.getSupportedLanguages(function(err, langs) { for (let key in en) { if (en.hasOwnProperty(key)) { - key = key + ''; + key = `${ key }`; if (destJson[key]) { newContent[key] = destJson[key]; } else { diff --git a/private/node_scripts/check-unused-i18n.js b/private/node_scripts/check-unused-i18n.js index 7faa5832a3e..f5bdbc8b73e 100644 --- a/private/node_scripts/check-unused-i18n.js +++ b/private/node_scripts/check-unused-i18n.js @@ -2,7 +2,7 @@ const fs = require('fs'); const path = require('path'); const _ = require('underscore'); -let contents = fs.readFileSync(__dirname + '/../../packages/rocketchat-lib/i18n/en.i18n.json', 'utf-8'); +let contents = fs.readFileSync(`${ __dirname }/../../packages/rocketchat-lib/i18n/en.i18n.json`, 'utf-8'); const keys = _.keys(JSON.parse(contents)); // var keys = _.keys(JSON.parse(contents)).filter(function(key) { return ['_Description', '_male', '_female', 'theme-color-'].every(function(word) { return key.indexOf(word) === -1; }); }); const keysFound = []; @@ -54,7 +54,7 @@ const walk = function(dir, done) { }); }; -walk(__dirname + '/../..', function(err, files) { +walk(`${ __dirname }/../..`, function(err, files) { if (err) { throw err; } diff --git a/server/lib/accounts.js b/server/lib/accounts.js index 495c1c359f8..a9675794ba9 100644 --- a/server/lib/accounts.js +++ b/server/lib/accounts.js @@ -7,12 +7,12 @@ Accounts.config(accountsConfig); Accounts.emailTemplates.siteName = RocketChat.settings.get('Site_Name'); -Accounts.emailTemplates.from = `${RocketChat.settings.get('Site_Name')} <${RocketChat.settings.get('From_Email')}>`; +Accounts.emailTemplates.from = `${ RocketChat.settings.get('Site_Name') } <${ RocketChat.settings.get('From_Email') }>`; const verifyEmailHtml = Accounts.emailTemplates.verifyEmail.text; Accounts.emailTemplates.verifyEmail.html = function(user, url) { - url = url.replace(Meteor.absoluteUrl(), `${Meteor.absoluteUrl()}login/`); + url = url.replace(Meteor.absoluteUrl(), `${ Meteor.absoluteUrl() }login/`); return verifyEmailHtml(user, url); }; @@ -198,7 +198,7 @@ Accounts.validateNewUser(function(user) { if (user.emails && user.emails.length > 0) { const email = user.emails[0].address; - const inWhiteList = domainWhiteList.some(domain => email.match('@' + RegExp.escape(domain) + '$')); + const inWhiteList = domainWhiteList.some(domain => email.match(`@${ RegExp.escape(domain) }$`)); if (inWhiteList === false) { throw new Meteor.Error('error-invalid-domain'); diff --git a/server/lib/cordova.js b/server/lib/cordova.js index d2f53080d9d..b168db9819b 100644 --- a/server/lib/cordova.js +++ b/server/lib/cordova.js @@ -52,10 +52,10 @@ Meteor.methods({ Push.send({ from: 'push', - title: `@${user.username}`, + title: `@${ user.username }`, text: TAPi18n.__('This_is_a_push_test_messsage'), apn: { - text: `@${user.username}:\n${TAPi18n.__('This_is_a_push_test_messsage')}` + text: `@${ user.username }:\n${ TAPi18n.__('This_is_a_push_test_messsage') }` }, sound: 'default', query: { @@ -78,7 +78,7 @@ function sendPush(service, token, options, tries = 0) { } }; - return HTTP.post(RocketChat.settings.get('Push_gateway') + `/push/${service}/send`, data, function(error, response) { + return HTTP.post(`${ RocketChat.settings.get('Push_gateway') }/push/${ service }/send`, data, function(error, response) { if (response && response.statusCode === 406) { console.log('removing push token', token); Push.appCollection.remove({ @@ -95,7 +95,7 @@ function sendPush(service, token, options, tries = 0) { return; } - SystemLogger.error(`Error sending push to gateway (${tries} try) ->`, error); + SystemLogger.error(`Error sending push to gateway (${ tries } try) ->`, error); if (tries <= 6) { const milli = Math.pow(10, tries + 2); @@ -175,7 +175,7 @@ function configurePush() { throw new Error('Push.send: option "text" not a string'); } if (RocketChat.settings.get('Push_debug')) { - console.log(`Push: send message "${options.title}" via query`, options.query); + console.log(`Push: send message "${ options.title }" via query`, options.query); } const query = { diff --git a/server/lib/cordova/facebook-login.js b/server/lib/cordova/facebook-login.js index 78acf1e2c7c..c7a6c73dc82 100644 --- a/server/lib/cordova/facebook-login.js +++ b/server/lib/cordova/facebook-login.js @@ -6,7 +6,7 @@ function getIdentity(accessToken) { } }).data; } catch (error) { - throw _.extend(new Error(`Failed to fetch identity from Facebook. ${error.message}`), { + throw _.extend(new Error(`Failed to fetch identity from Facebook. ${ error.message }`), { response: error.response }); } diff --git a/server/methods/eraseRoom.js b/server/methods/eraseRoom.js index 6ffc0280a41..f6501542a29 100644 --- a/server/methods/eraseRoom.js +++ b/server/methods/eraseRoom.js @@ -17,7 +17,7 @@ Meteor.methods({ }); } - if (RocketChat.authz.hasPermission(fromId, `delete-${room.t}`, rid)) { + if (RocketChat.authz.hasPermission(fromId, `delete-${ room.t }`, rid)) { RocketChat.models.Messages.removeByRoomId(rid); RocketChat.models.Subscriptions.removeByRoomId(rid); return RocketChat.models.Rooms.removeById(rid); diff --git a/server/methods/getAvatarSuggestion.js b/server/methods/getAvatarSuggestion.js index e8160901d4a..cf956adbe2a 100644 --- a/server/methods/getAvatarSuggestion.js +++ b/server/methods/getAvatarSuggestion.js @@ -8,7 +8,7 @@ function getAvatarSuggestionForUser(user) { if (user.services.facebook && user.services.facebook.id && RocketChat.settings.get('Accounts_OAuth_Facebook')) { avatars.push({ service: 'facebook', - url: 'https://graph.facebook.com/' + user.services.facebook.id + '/picture?type=large' + url: `https://graph.facebook.com/${ user.services.facebook.id }/picture?type=large` }); } @@ -22,7 +22,7 @@ function getAvatarSuggestionForUser(user) { if (user.services.github && user.services.github.username && RocketChat.settings.get('Accounts_OAuth_Github')) { avatars.push({ service: 'github', - url: 'https://avatars.githubusercontent.com/' + user.services.github.username + '?s=200' + url: `https://avatars.githubusercontent.com/${ user.services.github.username }?s=200` }); } @@ -90,7 +90,7 @@ function getAvatarSuggestionForUser(user) { }); if (result.statusCode === 200) { - let blob = 'data:' + result.headers['content-type'] + ';base64,'; + let blob = `data:${ result.headers['content-type'] };base64,`; blob += Buffer.from(result.content, 'binary').toString('base64'); avatar.blob = blob; avatar.contentType = result.headers['content-type']; diff --git a/server/methods/getUsernameSuggestion.js b/server/methods/getUsernameSuggestion.js index 42d5c09990d..30440f15139 100644 --- a/server/methods/getUsernameSuggestion.js +++ b/server/methods/getUsernameSuggestion.js @@ -15,7 +15,7 @@ function usernameIsAvaliable(username) { } return !RocketChat.models.Users.findOneByUsername({ - $regex: new RegExp(`^${username}$`, 'i') + $regex: new RegExp(`^${ username }$`, 'i') }); } @@ -98,8 +98,8 @@ function generateSuggestion(user) { let index = 0; while (!username) { index++; - if (usernameIsAvaliable(`${usernames[0]}-${index}`)) { - username = `${usernames[0]}-${index}`; + if (usernameIsAvaliable(`${ usernames[0] }-${ index }`)) { + username = `${ usernames[0] }-${ index }`; } } diff --git a/server/methods/loadLocale.js b/server/methods/loadLocale.js index 460c278e7b2..22f878668d6 100644 --- a/server/methods/loadLocale.js +++ b/server/methods/loadLocale.js @@ -3,7 +3,7 @@ Meteor.methods({ check(locale, String); try { - return Assets.getText(`moment-locales/${locale.toLowerCase()}.js`); + return Assets.getText(`moment-locales/${ locale.toLowerCase() }.js`); } catch (error) { return console.log(error); } diff --git a/server/methods/muteUserInRoom.js b/server/methods/muteUserInRoom.js index d9887a28d3d..862ee9a9511 100644 --- a/server/methods/muteUserInRoom.js +++ b/server/methods/muteUserInRoom.js @@ -28,7 +28,7 @@ Meteor.methods({ } if (['c', 'p'].includes(room.t) === false) { - throw new Meteor.Error('error-invalid-room-type', `${room.t} is not a valid room type`, { + throw new Meteor.Error('error-invalid-room-type', `${ room.t } is not a valid room type`, { method: 'muteUserInRoom', type: room.t }); diff --git a/server/methods/resetAvatar.js b/server/methods/resetAvatar.js index 3ccdc96fa19..8b5d1fed219 100644 --- a/server/methods/resetAvatar.js +++ b/server/methods/resetAvatar.js @@ -13,7 +13,7 @@ Meteor.methods({ } const user = Meteor.user(); - RocketChatFileAvatarInstance.deleteFile(`${user.username}.jpg`); + RocketChatFileAvatarInstance.deleteFile(`${ user.username }.jpg`); RocketChat.models.Users.unsetAvatarOrigin(user._id); RocketChat.Notifications.notifyLogged('updateAvatar', { username: user.username diff --git a/server/methods/sendConfirmationEmail.js b/server/methods/sendConfirmationEmail.js index 3a0121bb047..82d761a970e 100644 --- a/server/methods/sendConfirmationEmail.js +++ b/server/methods/sendConfirmationEmail.js @@ -22,7 +22,7 @@ Meteor.methods({ try { Accounts.sendVerificationEmail(user._id, email); } catch (error) { - throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${error.message}`, { + throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${ error.message }`, { method: 'registerUser', message: error.message }); diff --git a/server/methods/sendForgotPasswordEmail.js b/server/methods/sendForgotPasswordEmail.js index 669e2d50655..9fcef298612 100644 --- a/server/methods/sendForgotPasswordEmail.js +++ b/server/methods/sendForgotPasswordEmail.js @@ -7,7 +7,7 @@ Meteor.methods({ const user = RocketChat.models.Users.findOneByEmailAddress(email); if (user) { - const regex = new RegExp(`^${s.escapeRegExp(email)}$`, 'i'); + const regex = new RegExp(`^${ s.escapeRegExp(email) }$`, 'i'); email = (user.emails || []).map(item => item.address).find(userEmail => regex.test(userEmail)); if (RocketChat.settings.get('Forgot_Password_Customized')) { @@ -28,7 +28,7 @@ Meteor.methods({ try { Accounts.sendResetPasswordEmail(user._id, email); } catch (error) { - throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${error.message}`, { + throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${ error.message }`, { method: 'registerUser', message: error.message }); diff --git a/server/methods/unmuteUserInRoom.js b/server/methods/unmuteUserInRoom.js index 2f6cf3c9f17..3c75b44921f 100644 --- a/server/methods/unmuteUserInRoom.js +++ b/server/methods/unmuteUserInRoom.js @@ -22,7 +22,7 @@ Meteor.methods({ } if (['c', 'p'].includes(room.t) === false) { - throw new Meteor.Error('error-invalid-room-type', `${room.t} is not a valid room type`, { + throw new Meteor.Error('error-invalid-room-type', `${ room.t } is not a valid room type`, { method: 'unmuteUserInRoom', type: room.t }); diff --git a/server/startup/avatar.js b/server/startup/avatar.js index e0c873b07d9..6aca22c6659 100644 --- a/server/startup/avatar.js +++ b/server/startup/avatar.js @@ -10,10 +10,10 @@ Meteor.startup(function() { const RocketChatStore = RocketChatFile[storeType]; if (!RocketChatStore) { - throw new Error(`Invalid RocketChatStore type [${storeType}]`); + throw new Error(`Invalid RocketChatStore type [${ storeType }]`); } - console.log((`Using ${storeType} for Avatar storage`).green); + console.log((`Using ${ storeType } for Avatar storage`).green); function transformWrite(file, readStream, writeStream) { if (RocketChatFile.enabled === false || RocketChat.settings.get('Accounts_AvatarResize') !== true) { @@ -21,7 +21,7 @@ Meteor.startup(function() { } const height = RocketChat.settings.get('Accounts_AvatarSize'); const width = height; - return RocketChatFile.gm(readStream, file.fileName).background('#ffffff').resize(width, height + '^').gravity('Center').crop(width, height).extent(width, height).stream('jpeg').pipe(writeStream); + return RocketChatFile.gm(readStream, file.fileName).background('#ffffff').resize(width, `${ height }^`).gravity('Center').crop(width, height).extent(width, height).stream('jpeg').pipe(writeStream); } let path = '~/uploads'; @@ -62,7 +62,7 @@ Meteor.startup(function() { } } - file = RocketChatFileAvatarInstance.getFileWithReadStream(encodeURIComponent(`${username}.jpg`)); + file = RocketChatFileAvatarInstance.getFileWithReadStream(encodeURIComponent(`${ username }.jpg`)); } res.setHeader('Content-Disposition', 'inline'); @@ -114,7 +114,7 @@ Meteor.startup(function() { initials = initials.toUpperCase(); } - const svg = '\n\n \n ' + initials + '\n \n'; + const svg = `\n\n \n ${ initials }\n \n`; res.write(svg); res.end(); diff --git a/server/startup/cron.js b/server/startup/cron.js index f60056d1ae4..ea7ee0d8eb6 100644 --- a/server/startup/cron.js +++ b/server/startup/cron.js @@ -37,7 +37,7 @@ Meteor.startup(function() { SyncedCron.add({ name: 'Generate and save statistics', schedule(parser) { - return parser.cron(new Date().getMinutes() + ' * * * *'); + return parser.cron(`${ new Date().getMinutes() } * * * *`); }, job: generateStatistics }); @@ -46,7 +46,7 @@ Meteor.startup(function() { name: 'Cleanup OEmbed cache', schedule(parser) { const now = new Date(); - return parser.cron(now.getMinutes() + ' ' + now.getHours() + ' * * *'); + return parser.cron(`${ now.getMinutes() } ${ now.getHours() } * * *`); }, job: cleanupOEmbedCache }); diff --git a/server/startup/i18n-validation.js b/server/startup/i18n-validation.js index d5b9e01ce39..96f39e52137 100644 --- a/server/startup/i18n-validation.js +++ b/server/startup/i18n-validation.js @@ -3,7 +3,7 @@ function flat(obj, newObj = {}, path = '') { const value = obj[key]; if (_.isObject(value)) { - flat(value, newObj, key + '.'); + flat(value, newObj, `${ key }.`); } else { newObj[path + key] = value; } @@ -39,7 +39,7 @@ RocketChat.i18nValidation = function i18nValidation() { continue; } - const error = ((_.difference(langs, present).join(',')) + ': missing translation for ').red + key.white + ('. Present in [' + (present.join(',')) + ']').red; + const error = (`${ _.difference(langs, present).join(',') }: missing translation for `).red + key.white + (`. Present in [${ present.join(',') }]`).red; errors.push(error); @@ -52,7 +52,7 @@ RocketChat.i18nValidation = function i18nValidation() { console.log('+'.red + s.rpad('', len - 28, '-').red + '+'.red); for (const error of errors) { - console.log('|'.red, s.rpad('' + error, len).red, '|'.red); + console.log('|'.red, s.rpad(`${ error }`, len).red, '|'.red); } return console.log('+'.red + s.rpad('', len - 28, '-').red + '+'.red); diff --git a/server/startup/initialData.js b/server/startup/initialData.js index 5827928fe27..298d76c1911 100644 --- a/server/startup/initialData.js +++ b/server/startup/initialData.js @@ -49,7 +49,7 @@ Meteor.startup(function() { adminUser.name = process.env.ADMIN_NAME; } - console.log(('Name: ' + adminUser.name).green); + console.log((`Name: ${ adminUser.name }`).green); if (process.env.ADMIN_EMAIL) { const re = /^[^@].*@[^@]+$/i; @@ -61,7 +61,7 @@ Meteor.startup(function() { verified: true }]; - console.log(('Email: ' + process.env.ADMIN_EMAIL).green); + console.log((`Email: ${ process.env.ADMIN_EMAIL }`).green); } else { console.log('Email provided already exists; Ignoring environment variables ADMIN_EMAIL'.red); } @@ -74,7 +74,7 @@ Meteor.startup(function() { 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-_.]+$'); } @@ -90,7 +90,7 @@ Meteor.startup(function() { } } - console.log(('Username: ' + adminUser.username).green); + console.log((`Username: ${ adminUser.username }`).green); adminUser.type = 'user'; @@ -98,7 +98,7 @@ Meteor.startup(function() { Accounts.setPassword(id, process.env.ADMIN_PASS); - console.log(('Password: ' + process.env.ADMIN_PASS).green); + console.log((`Password: ${ process.env.ADMIN_PASS }`).green); RocketChat.authz.addUserRoles(id, 'admin'); } else { @@ -138,7 +138,7 @@ Meteor.startup(function() { if (oldestUser) { RocketChat.authz.addUserRoles(oldestUser._id, 'admin'); - console.log(`No admins are found. Set ${oldestUser.username} as admin for being the oldest user`); + console.log(`No admins are found. Set ${ oldestUser.username } as admin for being the oldest user`); } } @@ -164,17 +164,17 @@ Meteor.startup(function() { type: 'user' }; - console.log((`Name: ${adminUser.name}`).green); - console.log((`Email: ${adminUser.emails[0].address}`).green); - console.log((`Username: ${adminUser.username}`).green); - console.log((`Password: ${adminUser._id}`).green); + console.log((`Name: ${ adminUser.name }`).green); + console.log((`Email: ${ adminUser.emails[0].address }`).green); + console.log((`Username: ${ adminUser.username }`).green); + console.log((`Password: ${ adminUser._id }`).green); if (RocketChat.models.Users.db.findOneByEmailAddress(adminUser.emails[0].address)) { - throw new Meteor.Error(`Email ${adminUser.emails[0].address} already exists`, 'Rocket.Chat can\'t run in test mode'); + throw new Meteor.Error(`Email ${ adminUser.emails[0].address } already exists`, 'Rocket.Chat can\'t run in test mode'); } if (!RocketChat.checkUsernameAvailability(adminUser.username)) { - throw new Meteor.Error(`Username ${adminUser.username} already exists`, 'Rocket.Chat can\'t run in test mode'); + throw new Meteor.Error(`Username ${ adminUser.username } already exists`, 'Rocket.Chat can\'t run in test mode'); } RocketChat.models.Users.create(adminUser); diff --git a/server/startup/migrations/v002.js b/server/startup/migrations/v002.js index fb099d21220..ad2d589a3cb 100644 --- a/server/startup/migrations/v002.js +++ b/server/startup/migrations/v002.js @@ -26,7 +26,7 @@ RocketChat.Migrations.add({ const {image, contentType} = RocketChatFile.dataURIParse(dataURI); const rs = RocketChatFile.bufferToStream(new Buffer(image, 'base64')); - const ws = RocketChatFileAvatarInstance.createWriteStream(`${user.username}.jpg`, contentType); + const ws = RocketChatFileAvatarInstance.createWriteStream(`${ user.username }.jpg`, contentType); ws.on('end', Meteor.bindEnvironment(function() { return RocketChat.models.Users.setAvatarOrigin(user._id, service); diff --git a/server/startup/migrations/v004.js b/server/startup/migrations/v004.js index 92b117a34db..a7ddc8be9fb 100644 --- a/server/startup/migrations/v004.js +++ b/server/startup/migrations/v004.js @@ -48,7 +48,7 @@ RocketChat.Migrations.add({ $ne: room._id } }).forEach((item) => { - const name = room.name + '-' + Random.id(2).toLowerCase(); + const name = `${ room.name }-${ Random.id(2).toLowerCase() }`; RocketChat.models.Rooms.setNameById(item._id, name); diff --git a/server/startup/migrations/v005.js b/server/startup/migrations/v005.js index 57a532ecce0..685917f9362 100644 --- a/server/startup/migrations/v005.js +++ b/server/startup/migrations/v005.js @@ -45,7 +45,7 @@ RocketChat.Migrations.add({ } } } - console.log(`Adding: username ${newUserName} to all user ${user._id}`); + console.log(`Adding: username ${ newUserName } to all user ${ user._id }`); return RocketChat.models.Users.setUsername(user._id, newUserName); }); @@ -58,7 +58,7 @@ RocketChat.Migrations.add({ newId = ids.sort().join(''); if (newId !== room._id) { - console.log(`Fixing: _id ${room._id} to ${newId}`); + console.log(`Fixing: _id ${ room._id } to ${ newId }`); RocketChat.models.Subscriptions.update({ rid: room._id }, { @@ -105,7 +105,7 @@ RocketChat.Migrations.add({ RocketChat.models.Users.find({}, { username: 1 }).forEach((user) => { - console.log(`Adding: u.username ${user.username} to all document`); + console.log(`Adding: u.username ${ user.username } to all document`); RocketChat.models.Rooms.update({ 'u._id': user._id }, { diff --git a/server/startup/migrations/v007.js b/server/startup/migrations/v007.js index e4b28335841..715c2981a41 100644 --- a/server/startup/migrations/v007.js +++ b/server/startup/migrations/v007.js @@ -14,7 +14,7 @@ RocketChat.Migrations.add({ const count = query.count(); query.forEach((message, index) => { - console.log(`${index + 1} / ${count}`); + console.log(`${ index + 1 } / ${ count }`); message.urls = message.urls.map((url) => { if (_.isString(url)) { diff --git a/server/startup/migrations/v009.js b/server/startup/migrations/v009.js index 8ef1f68871a..22c4df0726e 100644 --- a/server/startup/migrations/v009.js +++ b/server/startup/migrations/v009.js @@ -28,7 +28,7 @@ RocketChat.Migrations.add({ const {target, source} = collection; // rawCollection available as of Meteor 1.0.4 - console.log(`Migrating data from: ${source.rawCollection().collectionName} to: ${target.rawCollection().collectionName}`); + console.log(`Migrating data from: ${ source.rawCollection().collectionName } to: ${ target.rawCollection().collectionName }`); source.find().forEach((doc) => { // use upsert to account for GENERAL room created by initialData @@ -41,7 +41,7 @@ RocketChat.Migrations.add({ return Meteor.wrapAsync(rawSource.drop, rawSource)(function(err/*, res*/) { if (err) { - return console.log(`Error dropping ${rawSource.collectionName} collection due to: ${err.errmsg}`); + return console.log(`Error dropping ${ rawSource.collectionName } collection due to: ${ err.errmsg }`); } }); diff --git a/server/startup/migrations/v010.js b/server/startup/migrations/v010.js index aa1be21af1f..f04e1cdf08a 100644 --- a/server/startup/migrations/v010.js +++ b/server/startup/migrations/v010.js @@ -28,6 +28,6 @@ RocketChat.Migrations.add({ } }); - return console.log(`Removed duplicated usernames from ${count} rooms`); + return console.log(`Removed duplicated usernames from ${ count } rooms`); } }); diff --git a/server/startup/migrations/v012.js b/server/startup/migrations/v012.js index 945c4d15a64..3f7284bf4de 100644 --- a/server/startup/migrations/v012.js +++ b/server/startup/migrations/v012.js @@ -28,7 +28,7 @@ RocketChat.Migrations.add({ } }); - return console.log(`Set ${oldestUser.username} as admin for being the oldest user`); + return console.log(`Set ${ oldestUser.username } as admin for being the oldest user`); } } } diff --git a/server/startup/migrations/v015.js b/server/startup/migrations/v015.js index 85e45c7eb64..f5076993b92 100644 --- a/server/startup/migrations/v015.js +++ b/server/startup/migrations/v015.js @@ -16,13 +16,13 @@ RocketChat.Migrations.add({ }).forEach((cfsRecord) => { const nameParts = cfsRecord.original.name && cfsRecord.original.name.split('.'); let extension = ''; - let url = `ufs/rocketchat_uploads/${cfsRecord._id}`; + let url = `ufs/rocketchat_uploads/${ cfsRecord._id }`; console.log('migrating file', url); if (nameParts && nameParts.length > 1) { extension = nameParts.pop(); - url = url + '.' + extension; + url = `${ url }.${ extension }`; } const record = { @@ -70,19 +70,19 @@ RocketChat.Migrations.add({ RocketChat.models.Messages.find({ $or: [{ - 'urls.url': `https://demo.rocket.chat/cfs/files/Files/${cfsRecord._id}` + 'urls.url': `https://demo.rocket.chat/cfs/files/Files/${ cfsRecord._id }` }, { - 'urls.url': `https://rocket.chat/cfs/files/Files/${cfsRecord._id}` + 'urls.url': `https://rocket.chat/cfs/files/Files/${ cfsRecord._id }` }] }).forEach((message) => { for (const urlsItem of message.urls) { - if (urlsItem.url === (`https://demo.rocket.chat/cfs/files/Files/${cfsRecord._id}`) || urlsItem.url === (`https://rocket.chat/cfs/files/Files/${cfsRecord._id}`)) { + if (urlsItem.url === (`https://demo.rocket.chat/cfs/files/Files/${ cfsRecord._id }`) || urlsItem.url === (`https://rocket.chat/cfs/files/Files/${ cfsRecord._id }`)) { urlsItem.url = Meteor.absoluteUrl() + url; if (urlsItem.parsedUrl && urlsItem.parsedUrl.pathname) { - urlsItem.parsedUrl.pathname = `/${url}`; + urlsItem.parsedUrl.pathname = `/${ url }`; } - message.msg = message.msg.replace(`https://demo.rocket.chat/cfs/files/Files/${cfsRecord._id}`, Meteor.absoluteUrl() + url); - message.msg = message.msg.replace(`https://rocket.chat/cfs/files/Files/${cfsRecord._id}`, Meteor.absoluteUrl() + url); + message.msg = message.msg.replace(`https://demo.rocket.chat/cfs/files/Files/${ cfsRecord._id }`, Meteor.absoluteUrl() + url); + message.msg = message.msg.replace(`https://rocket.chat/cfs/files/Files/${ cfsRecord._id }`, Meteor.absoluteUrl() + url); } } diff --git a/server/startup/migrations/v019.js b/server/startup/migrations/v019.js index 6392e679143..10d08d43e54 100644 --- a/server/startup/migrations/v019.js +++ b/server/startup/migrations/v019.js @@ -29,7 +29,7 @@ RocketChat.Migrations.add({ let usernames = _.pluck(admins, 'username').join(', '); - console.log((`Migrate ${usernames} from admin field to 'admin' role`).green); + console.log((`Migrate ${ usernames } from admin field to 'admin' role`).green); // Add 'user' role to all users const users = Meteor.users.find().fetch(); @@ -38,7 +38,7 @@ RocketChat.Migrations.add({ }); usernames = _.pluck(users, 'username').join(', '); - console.log((`Add ${usernames} to 'user' role`).green); + console.log((`Add ${ usernames } to 'user' role`).green); // Add 'moderator' role to channel/group creators const rooms = RocketChat.models.Rooms.findByTypes(['c', 'p']).fetch(); diff --git a/server/startup/migrations/v030.js b/server/startup/migrations/v030.js index 00e2adb8566..1d18a899f7c 100644 --- a/server/startup/migrations/v030.js +++ b/server/startup/migrations/v030.js @@ -23,7 +23,7 @@ RocketChat.Migrations.add({ if (WebRTC_TURN_Server) { servers += ', '; if (WebRTC_TURN_Username != null) { - servers += encodeURIComponent(WebRTC_TURN_Username) + ':' + encodeURIComponent(WebRTC_TURN_Password) + '@'; + servers += `${ encodeURIComponent(WebRTC_TURN_Username) }:${ encodeURIComponent(WebRTC_TURN_Password) }@`; } servers += WebRTC_TURN_Server; } diff --git a/server/startup/migrations/v033.js b/server/startup/migrations/v033.js index c355dac4024..f3703251ace 100644 --- a/server/startup/migrations/v033.js +++ b/server/startup/migrations/v033.js @@ -33,13 +33,13 @@ RocketChat.Migrations.add({ integrations.forEach(function(integration) { let script = ''; if (integration.processIncomingRequestScript) { - script += integration.processIncomingRequestScript + '\n\n'; + script += `${ integration.processIncomingRequestScript }\n\n`; } if (integration.prepareOutgoingRequestScript) { - script += integration.prepareOutgoingRequestScript + '\n\n'; + script += `${ integration.prepareOutgoingRequestScript }\n\n`; } if (integration.processOutgoingResponseScript) { - script += integration.processOutgoingResponseScript + '\n\n'; + script += `${ integration.processOutgoingResponseScript }\n\n`; } return RocketChat.models.Integrations.update(integration._id, { diff --git a/server/startup/migrations/v040.js b/server/startup/migrations/v040.js index e5b2df54c04..26c2d219072 100644 --- a/server/startup/migrations/v040.js +++ b/server/startup/migrations/v040.js @@ -4,13 +4,13 @@ RocketChat.Migrations.add({ RocketChat.models.Settings.find({ _id: /Accounts_OAuth_Custom_/, i18nLabel: 'Accounts_OAuth_Custom_Enable' }).forEach(function(customOauth) { const parts = customOauth._id.split('_'); const name = parts[3]; - const id = 'Accounts_OAuth_Custom_' + name + '_token_sent_via'; + const id = `Accounts_OAuth_Custom_${ name }_token_sent_via`; if (!RocketChat.models.Settings.findOne({ _id: id })) { RocketChat.models.Settings.insert({ '_id': id, 'type': 'select', 'group': 'OAuth', - 'section': 'Custom OAuth: ' + name, + 'section': `Custom OAuth: ${ name }`, 'i18nLabel': 'Accounts_OAuth_Custom_Token_Sent_Via', 'persistent': true, 'values': [ @@ -29,7 +29,7 @@ RocketChat.Migrations.add({ 'hidden': false, 'blocked': false, 'sorter': 255, - 'i18nDescription': 'Accounts_OAuth_Custom_' + name + '_token_sent_via_Description', + 'i18nDescription': `Accounts_OAuth_Custom_${ name }_token_sent_via_Description`, 'createdAt': new Date(), 'value': 'payload' }); diff --git a/server/startup/migrations/v042.js b/server/startup/migrations/v042.js index a59bfbc49ea..787a86b3e1a 100644 --- a/server/startup/migrations/v042.js +++ b/server/startup/migrations/v042.js @@ -27,9 +27,9 @@ RocketChat.Migrations.add({ if (oldFile) { const extension = RocketChat.Assets.mime.extension(oldFile.contentType); - RocketChat.settings.removeById(`Assets_${from}`); - RocketChat.settings.updateById(`Assets_${to}`, { - url: `/assets/${to}.${extension}`, + RocketChat.settings.removeById(`Assets_${ from }`); + RocketChat.settings.updateById(`Assets_${ to }`, { + url: `/assets/${ to }.${ extension }`, defaultUrl: RocketChat.Assets.assets[to].defaultUrl }); diff --git a/server/startup/serverRunning.js b/server/startup/serverRunning.js index 0d3cd3f6091..39e05c533ed 100644 --- a/server/startup/serverRunning.js +++ b/server/startup/serverRunning.js @@ -18,20 +18,20 @@ Meteor.startup(function() { return Meteor.setTimeout(function() { let msg = [ - `Rocket.Chat Version: ${RocketChat.Info.version}`, - ` NodeJS Version: ${process.versions.node} - ${process.arch}`, - ` Platform: ${process.platform}`, - ` Process Port: ${process.env.PORT}`, - ` Site URL: ${RocketChat.settings.get('Site_Url')}`, - ` ReplicaSet OpLog: ${oplogState}` + `Rocket.Chat Version: ${ RocketChat.Info.version }`, + ` NodeJS Version: ${ process.versions.node } - ${ process.arch }`, + ` Platform: ${ process.platform }`, + ` Process Port: ${ process.env.PORT }`, + ` Site URL: ${ RocketChat.settings.get('Site_Url') }`, + ` ReplicaSet OpLog: ${ oplogState }` ]; if (RocketChat.Info.commit && RocketChat.Info.commit.hash) { - msg.push(` Commit Hash: ${RocketChat.Info.commit.hash.substr(0, 10)}`); + msg.push(` Commit Hash: ${ RocketChat.Info.commit.hash.substr(0, 10) }`); } if (RocketChat.Info.commit && RocketChat.Info.commit.branch) { - msg.push(` Commit Branch: ${RocketChat.Info.commit.branch}`); + msg.push(` Commit Branch: ${ RocketChat.Info.commit.branch }`); } msg = msg.join('\n'); @@ -40,7 +40,7 @@ Meteor.startup(function() { return SystemLogger.startup_box(msg, 'SERVER RUNNING'); } - msg += ['', '', 'YOUR CURRENT NODEJS VERSION IS NOT SUPPORTED,', `PLEASE UPGRADE / DOWNGRADE TO VERSION ${desiredNodeVersionMajor}.X.X`].join('\n'); + msg += ['', '', 'YOUR CURRENT NODEJS VERSION IS NOT SUPPORTED,', `PLEASE UPGRADE / DOWNGRADE TO VERSION ${ desiredNodeVersionMajor }.X.X`].join('\n'); SystemLogger.error_box(msg, 'SERVER ERROR'); diff --git a/server/stream/streamBroadcast.js b/server/stream/streamBroadcast.js index d7b71a0f84b..6de334e34b9 100644 --- a/server/stream/streamBroadcast.js +++ b/server/stream/streamBroadcast.js @@ -14,15 +14,15 @@ const logger = new Logger('StreamBroadcast', { }); function _authorizeConnection(instance) { - logger.auth.info(`Authorizing with ${instance}`); + logger.auth.info(`Authorizing with ${ instance }`); return connections[instance].call('broadcastAuth', InstanceStatus.id(), connections[instance].instanceId, function(err, ok) { if (err != null) { - return logger.auth.error(`broadcastAuth error ${instance} ${InstanceStatus.id()} ${connections[instance].instanceId}`, err); + return logger.auth.error(`broadcastAuth error ${ instance } ${ InstanceStatus.id() } ${ connections[instance].instanceId }`, err); } connections[instance].broadcastAuth = ok; - return logger.auth.info(`broadcastAuth with ${instance}`, ok); + return logger.auth.info(`broadcastAuth with ${ instance }`, ok); }); } @@ -55,7 +55,7 @@ function startMatrixBroadcast() { return InstanceStatus.getCollection().find(query, options).observe({ added(record) { - let instance = `${record.extraInformation.host}:${record.extraInformation.port}`; + let instance = `${ record.extraInformation.host }:${ record.extraInformation.port }`; if (record.extraInformation.port === process.env.PORT && record.extraInformation.host === process.env.INSTANCE_IP) { logger.auth.info('prevent self connect', instance); @@ -63,7 +63,7 @@ function startMatrixBroadcast() { } if (record.extraInformation.host === process.env.INSTANCE_IP && RocketChat.isDocker() === false) { - instance = `localhost:${record.extraInformation.port}`; + instance = `localhost:${ record.extraInformation.port }`; } if (connections[instance] && connections[instance].instanceRecord) { @@ -90,10 +90,10 @@ function startMatrixBroadcast() { }, removed(record) { - let instance = `${record.extraInformation.host}:${record.extraInformation.port}`; + let instance = `${ record.extraInformation.host }:${ record.extraInformation.port }`; if (record.extraInformation.host === process.env.INSTANCE_IP && RocketChat.isDocker() === false) { - instance = 'localhost:' + record.extraInformation.port; + instance = `localhost:${ record.extraInformation.port }`; } const query = { @@ -213,7 +213,7 @@ function startStreamBroadcast() { }); function broadcast(streamName, eventName, args/*, userId*/) { - const fromInstance = `${process.env.INSTANCE_IP}:${process.env.PORT}`; + const fromInstance = `${ process.env.INSTANCE_IP }:${ process.env.PORT }`; const results = []; for (const instance of Object.keys(connections)) { @@ -227,18 +227,18 @@ function startStreamBroadcast() { switch (response) { case 'self-not-authorized': - logger.stream.error((`Stream broadcast from '${fromInstance}' to '${connection._stream.endpoint}' with name ${streamName} to self is not authorized`).red); + logger.stream.error((`Stream broadcast from '${ fromInstance }' to '${ connection._stream.endpoint }' with name ${ streamName } to self is not authorized`).red); logger.stream.debug(' -> connection authorized'.red, connection.broadcastAuth); logger.stream.debug(' -> connection status'.red, connection.status()); return logger.stream.debug(' -> arguments'.red, eventName, args); case 'not-authorized': - logger.stream.error((`Stream broadcast from '${fromInstance}' to '${connection._stream.endpoint}' with name ${streamName} not authorized`).red); + logger.stream.error((`Stream broadcast from '${ fromInstance }' to '${ connection._stream.endpoint }' with name ${ streamName } not authorized`).red); logger.stream.debug(' -> connection authorized'.red, connection.broadcastAuth); logger.stream.debug(' -> connection status'.red, connection.status()); logger.stream.debug(' -> arguments'.red, eventName, args); return authorizeConnection(instance); case 'stream-not-exists': - logger.stream.error((`Stream broadcast from '${fromInstance}' to '${connection._stream.endpoint}' with name ${streamName} does not exist`).red); + logger.stream.error((`Stream broadcast from '${ fromInstance }' to '${ connection._stream.endpoint }' with name ${ streamName } does not exist`).red); logger.stream.debug(' -> connection authorized'.red, connection.broadcastAuth); logger.stream.debug(' -> connection status'.red, connection.status()); return logger.stream.debug(' -> arguments'.red, eventName, args); diff --git a/tests/data/api-data.js b/tests/data/api-data.js index 813f113b217..43a61859bc4 100644 --- a/tests/data/api-data.js +++ b/tests/data/api-data.js @@ -4,10 +4,10 @@ import supertest from 'supertest'; export const request = supertest('http://localhost:3000'); const prefix = '/api/v1/'; -export const apiUsername = 'api'+username; -export const apiEmail = 'api'+email; -export const apiPublicChannelName= 'api'+publicChannelName; -export const apiPrivateChannelName = 'api'+privateChannelName; +export const apiUsername = `api${ username }`; +export const apiEmail = `api${ email }`; +export const apiPublicChannelName= `api${ publicChannelName }`; +export const apiPrivateChannelName = `api${ privateChannelName }`; export const targetUser = {}; export const channel = {}; diff --git a/tests/data/channel.js b/tests/data/channel.js index 616faab6b23..123c1baf346 100644 --- a/tests/data/channel.js +++ b/tests/data/channel.js @@ -1,2 +1,2 @@ -export const publicChannelName = 'channel-test-'+Date.now(); -export const privateChannelName = 'private-channel-test-'+Date.now(); +export const publicChannelName = `channel-test-${ Date.now() }`; +export const privateChannelName = `private-channel-test-${ Date.now() }`; diff --git a/tests/data/user.js b/tests/data/user.js index 3693d2244fc..92294f99dfc 100644 --- a/tests/data/user.js +++ b/tests/data/user.js @@ -1,7 +1,7 @@ -export const username = 'user.test.'+Date.now(); -export const email = username+'@rocket.chat'; +export const username = `user.test.${ Date.now() }`; +export const email = `${ username }@rocket.chat`; export const password = 'rocket.chat'; export const adminUsername = 'rocketchat.internal.admin.test'; -export const adminEmail = adminUsername+'@rocket.chat'; +export const adminEmail = `${ adminUsername }@rocket.chat`; export const adminPassword = adminUsername; diff --git a/tests/end-to-end/api/01-users.js b/tests/end-to-end/api/01-users.js index 396146e05d1..7d86025fb56 100644 --- a/tests/end-to-end/api/01-users.js +++ b/tests/end-to-end/api/01-users.js @@ -135,8 +135,8 @@ describe('Users', function() { userId: targetUser._id, data :{ email: apiEmail, - name: 'edited'+apiUsername, - username: 'edited'+apiUsername, + name: `edited${ apiUsername }`, + username: `edited${ apiUsername }`, password, active: true, roles: ['user'] @@ -146,10 +146,10 @@ describe('Users', function() { .expect(200) .expect((res) => { expect(res.body).to.have.property('success', true); - expect(res.body).to.have.deep.property('user.username', 'edited'+apiUsername); + expect(res.body).to.have.deep.property('user.username', `edited${ apiUsername }`); expect(res.body).to.have.deep.property('user.emails[0].address', apiEmail); expect(res.body).to.have.deep.property('user.active', true); - expect(res.body).to.have.deep.property('user.name', 'edited'+apiUsername); + expect(res.body).to.have.deep.property('user.name', `edited${ apiUsername }`); }) .end(done); }); diff --git a/tests/end-to-end/api/02-channels.js b/tests/end-to-end/api/02-channels.js index eea72bdf637..cb01dbbe02b 100644 --- a/tests/end-to-end/api/02-channels.js +++ b/tests/end-to-end/api/02-channels.js @@ -383,14 +383,14 @@ describe('channels', function() { .set(credentials) .send({ roomId: channel._id, - name: 'EDITED'+apiPublicChannelName + name: `EDITED${ apiPublicChannelName }` }) .expect('Content-Type', 'application/json') .expect(200) .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('channel._id'); - expect(res.body).to.have.deep.property('channel.name', 'EDITED'+apiPublicChannelName); + expect(res.body).to.have.deep.property('channel.name', `EDITED${ apiPublicChannelName }`); expect(res.body).to.have.deep.property('channel.t', 'c'); expect(res.body).to.have.deep.property('channel.msgs', roomInfo.channel.msgs + 1); }) @@ -424,7 +424,7 @@ describe('channels', function() { .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('channel._id'); - expect(res.body).to.have.deep.property('channel.name', 'EDITED'+apiPublicChannelName); + expect(res.body).to.have.deep.property('channel.name', `EDITED${ apiPublicChannelName }`); expect(res.body).to.have.deep.property('channel.t', 'c'); }) .end(done); @@ -444,7 +444,7 @@ describe('channels', function() { .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('channel._id'); - expect(res.body).to.have.deep.property('channel.name', 'EDITED'+apiPublicChannelName); + expect(res.body).to.have.deep.property('channel.name', `EDITED${ apiPublicChannelName }`); expect(res.body).to.have.deep.property('channel.t', 'c'); expect(res.body).to.have.deep.property('channel.msgs', roomInfo.channel.msgs); }) @@ -465,7 +465,7 @@ describe('channels', function() { .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('channel._id'); - expect(res.body).to.have.deep.property('channel.name', 'EDITED'+apiPublicChannelName); + expect(res.body).to.have.deep.property('channel.name', `EDITED${ apiPublicChannelName }`); expect(res.body).to.have.deep.property('channel.t', 'c'); expect(res.body).to.have.deep.property('channel.msgs', roomInfo.channel.msgs); }) @@ -485,7 +485,7 @@ describe('channels', function() { .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('channel._id'); - expect(res.body).to.have.deep.property('channel.name', 'EDITED'+apiPublicChannelName); + expect(res.body).to.have.deep.property('channel.name', `EDITED${ apiPublicChannelName }`); expect(res.body).to.have.deep.property('channel.t', 'c'); expect(res.body).to.have.deep.property('channel.msgs', roomInfo.channel.msgs + 1); }) @@ -506,7 +506,7 @@ describe('channels', function() { .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('channel._id'); - expect(res.body).to.have.deep.property('channel.name', 'EDITED'+apiPublicChannelName); + expect(res.body).to.have.deep.property('channel.name', `EDITED${ apiPublicChannelName }`); expect(res.body).to.have.deep.property('channel.t', 'p'); expect(res.body).to.have.deep.property('channel.msgs', roomInfo.channel.msgs + 1); }) diff --git a/tests/end-to-end/api/03-groups.js b/tests/end-to-end/api/03-groups.js index 3452b05ad15..17ccdfb9f2f 100644 --- a/tests/end-to-end/api/03-groups.js +++ b/tests/end-to-end/api/03-groups.js @@ -345,14 +345,14 @@ describe('groups', function() { .set(credentials) .send({ roomId: group._id, - name: 'EDITED'+apiPrivateChannelName + name: `EDITED${ apiPrivateChannelName }` }) .expect('Content-Type', 'application/json') .expect(200) .expect((res) => { expect(res.body).to.have.property('success', true); expect(res.body).to.have.deep.property('group._id'); - expect(res.body).to.have.deep.property('group.name', 'EDITED'+apiPrivateChannelName); + expect(res.body).to.have.deep.property('group.name', `EDITED${ apiPrivateChannelName }`); expect(res.body).to.have.deep.property('group.t', 'p'); expect(res.body).to.have.deep.property('group.msgs', roomInfo.group.msgs + 1); }) diff --git a/tests/end-to-end/ui/06-messaging.js b/tests/end-to-end/ui/06-messaging.js index 5e642e40369..b6b23e03147 100644 --- a/tests/end-to-end/ui/06-messaging.js +++ b/tests/end-to-end/ui/06-messaging.js @@ -13,7 +13,7 @@ import {checkIfUserIsValid, publicChannelCreated, privateChannelCreated, directM //Test data -const message = 'message from '+username; +const message = `message from ${ username }`; let currentTest = 'none'; function messagingTest() { @@ -208,7 +208,7 @@ function messageActionsTest() { }); describe('Message quote', () => { - const message = 'Message for quote Tests - ' + Date.now(); + const message = `Message for quote Tests - ${ Date.now() }`; before(() => { mainContent.sendMessage(message); diff --git a/tests/end-to-end/ui/09-channel.js b/tests/end-to-end/ui/09-channel.js index 8b21b32c888..43dc3b0109e 100644 --- a/tests/end-to-end/ui/09-channel.js +++ b/tests/end-to-end/ui/09-channel.js @@ -175,7 +175,7 @@ describe('channel', ()=> { it('edit the name input', ()=> { flexTab.editNameTextInput.waitForVisible(); - flexTab.editNameTextInput.setValue('NAME-EDITED-'+publicChannelName); + flexTab.editNameTextInput.setValue(`NAME-EDITED-${ publicChannelName }`); }); it('save the name', ()=> { @@ -183,8 +183,8 @@ describe('channel', ()=> { }); it('should show the new name', ()=> { - const channelName = sideNav.getChannelFromList('NAME-EDITED-'+publicChannelName); - channelName.getText().should.equal('NAME-EDITED-'+publicChannelName); + const channelName = sideNav.getChannelFromList(`NAME-EDITED-${ publicChannelName }`); + channelName.getText().should.equal(`NAME-EDITED-${ publicChannelName }`); }); }); @@ -345,7 +345,7 @@ describe('channel', ()=> { describe('channel quit and enter', () => { it('leave the channel', () => { - const channel = sideNav.getChannelFromList('NAME-EDITED-'+publicChannelName); + const channel = sideNav.getChannelFromList(`NAME-EDITED-${ publicChannelName }`); channel.click(); channel.moveToObject(); sideNav.channelLeave.waitForVisible(5000); @@ -364,20 +364,20 @@ describe('channel', ()=> { }); it('should not show the channel on the list', () => { - sideNav.getChannelFromList('NAME-EDITED-'+publicChannelName).waitForVisible(5000, true); - sideNav.getChannelFromList('NAME-EDITED-'+publicChannelName).isVisible().should.be.false; + sideNav.getChannelFromList(`NAME-EDITED-${ publicChannelName }`).waitForVisible(5000, true); + sideNav.getChannelFromList(`NAME-EDITED-${ publicChannelName }`).isVisible().should.be.false; }); it('should search and enter the channel with the spotlight', () => { - sideNav.searchChannel('NAME-EDITED-'+publicChannelName); + sideNav.searchChannel(`NAME-EDITED-${ publicChannelName }`); mainContent.joinChannelBtn.waitForVisible(5000); mainContent.joinChannelBtn.click(); }); it('should show the channel on the list', () => { - sideNav.getChannelFromList('NAME-EDITED-'+publicChannelName).waitForVisible(10000); - sideNav.getChannelFromList('NAME-EDITED-'+publicChannelName).isVisible().should.be.true; + sideNav.getChannelFromList(`NAME-EDITED-${ publicChannelName }`).waitForVisible(10000); + sideNav.getChannelFromList(`NAME-EDITED-${ publicChannelName }`).isVisible().should.be.true; }); }); }); diff --git a/tests/end-to-end/ui/10-user-preferences.js b/tests/end-to-end/ui/10-user-preferences.js index 0c050f680b4..5e987c46545 100644 --- a/tests/end-to-end/ui/10-user-preferences.js +++ b/tests/end-to-end/ui/10-user-preferences.js @@ -69,15 +69,15 @@ describe('user preferences', ()=> { }); it('change the name field', ()=> { - preferencesMainContent.changeRealName('EditedRealName'+username); + preferencesMainContent.changeRealName(`EditedRealName${ username }`); }); it('change the Username field', ()=> { - preferencesMainContent.changeUsername('EditedUserName'+username); + preferencesMainContent.changeUsername(`EditedUserName${ username }`); }); it.skip('change the email field', ()=> { - preferencesMainContent.changeEmail('EditedUserEmail'+username+'@gmail.com'); + preferencesMainContent.changeEmail(`EditedUserEmail${ username }@gmail.com`); }); it('save the settings', ()=> { @@ -112,23 +112,23 @@ describe('user preferences', ()=> { }); it.skip('the name on the last message should be the edited one', () => { - mainContent.waitForLastMessageUserEqualsText('EditedUserName'+username); - mainContent.lastMessageUser.getText().should.equal('EditedUserName'+username); + mainContent.waitForLastMessageUserEqualsText(`EditedUserName${ username }`); + mainContent.lastMessageUser.getText().should.equal(`EditedUserName${ username }`); }); it('the name on the nav bar should be the edited one', () => { - sideNav.accountBoxUserName.getText().should.equal('EditedUserName'+username); + sideNav.accountBoxUserName.getText().should.equal(`EditedUserName${ username }`); }); it.skip('the user name on the members flex tab should be the edited one', () => { mainContent.lastMessageUser.click(); flexTab.memberUserName.waitForVisible(5000); - flexTab.memberUserName.getText().should.equal('EditedUserName'+username); + flexTab.memberUserName.getText().should.equal(`EditedUserName${ username }`); }); it.skip('the real name on the members flex tab should be the edited one', () => { flexTab.memberRealName.waitForVisible(5000); - flexTab.memberRealName.getText().should.equal('EditedRealName'+username); + flexTab.memberRealName.getText().should.equal(`EditedRealName${ username }`); }); }); }); diff --git a/tests/end-to-end/ui/12-settings.js b/tests/end-to-end/ui/12-settings.js index b4ade1fefb8..d618be22bea 100644 --- a/tests/end-to-end/ui/12-settings.js +++ b/tests/end-to-end/ui/12-settings.js @@ -454,8 +454,8 @@ describe('Changing settings via api', () => { loginPage.registerButton.waitForVisible(5000); loginPage.registerButton.click(); loginPage.nameField.waitForVisible(5000); - loginPage.nameField.setValue('setting'+username); - loginPage.emailField.setValue('setting'+email); + loginPage.nameField.setValue(`setting${ username }`); + loginPage.emailField.setValue(`setting${ email }`); loginPage.passwordField.setValue(password); loginPage.confirmPasswordField.setValue(password); @@ -478,11 +478,11 @@ describe('Changing settings via api', () => { it('search the user', () => { admin.usersFilter.click(); - admin.usersFilter.setValue('setting'+username); + admin.usersFilter.setValue(`setting${ username }`); }); it('opens the user', () => { - const userEl = admin.getUserFromList('setting'+username); + const userEl = admin.getUserFromList(`setting${ username }`); userEl.waitForVisible(5000); userEl.click(); flexTab.usersView.waitForVisible(5000); diff --git a/tests/end-to-end/ui/13-permissions.js b/tests/end-to-end/ui/13-permissions.js index 34593c8af56..3a1cd269023 100644 --- a/tests/end-to-end/ui/13-permissions.js +++ b/tests/end-to-end/ui/13-permissions.js @@ -89,9 +89,9 @@ describe('Admin settings', () => { }); it('create a user', () => { - flexTab.usersAddUserName.setValue('adminCreated'+username); - flexTab.usersAddUserUsername.setValue('adminCreated'+username); - flexTab.usersAddUserEmail.setValue('adminCreated'+email); + flexTab.usersAddUserName.setValue(`adminCreated${ username }`); + flexTab.usersAddUserUsername.setValue(`adminCreated${ username }`); + flexTab.usersAddUserEmail.setValue(`adminCreated${ email }`); flexTab.usersAddUserVerifiedCheckbox.click(); flexTab.usersAddUserPassword.setValue(password); flexTab.usersAddUserChangePasswordCheckbox.click(); @@ -165,7 +165,7 @@ describe('Admin settings', () => { sideNav.preferencesClose.waitForVisible(5000); sideNav.preferencesClose.click(); - checkIfUserIsValid('adminCreated'+username, 'adminCreated'+email, password); + checkIfUserIsValid(`adminCreated${ username }`, `adminCreated${ email }`, password); }); it('should not show the plus icon on toolbar ', () => { diff --git a/tests/pageobjects/Page.js b/tests/pageobjects/Page.js index 84cd621dbb7..7aa4a8a1918 100644 --- a/tests/pageobjects/Page.js +++ b/tests/pageobjects/Page.js @@ -7,7 +7,7 @@ class Page { height: 800 }); - browser.url('http://localhost:3000/' + path); + browser.url(`http://localhost:3000/${ path }`); this.body.waitForExist(); } diff --git a/tests/pageobjects/administration.page.js b/tests/pageobjects/administration.page.js index 7ea5a7325f0..baa509a4430 100644 --- a/tests/pageobjects/administration.page.js +++ b/tests/pageobjects/administration.page.js @@ -117,7 +117,7 @@ class Administration extends Page { get generalUTF8NamesSlugReset() { return browser.element('.reset-setting[data-setting="UTF8_Names_Slugify"]'); } checkUserList(user) { - const element = browser.element('td=adminCreated'+user); + const element = browser.element(`td=adminCreated${ user }`); element.waitForVisible(5000); browser.pause(500); const result = element.isVisible(); @@ -125,7 +125,7 @@ class Administration extends Page { } getUserFromList(user) { - const element = browser.element('td='+user); + const element = browser.element(`td=${ user }`); element.waitForVisible(5000); return element; } diff --git a/tests/pageobjects/flex-tab.page.js b/tests/pageobjects/flex-tab.page.js index 83c1982652c..802aee3ec09 100644 --- a/tests/pageobjects/flex-tab.page.js +++ b/tests/pageobjects/flex-tab.page.js @@ -91,7 +91,7 @@ class FlexTab extends Page { get usersActivate() { return browser.element('.button.activate'); } get usersDeactivate() { return browser.element('.button.deactivate'); } - getUserEl(username) { return browser.element(`.flex-tab button[title="${username}"] > p`); } + getUserEl(username) { return browser.element(`.flex-tab button[title="${ username }"] > p`); } archiveChannel() { this.archiveBtn.waitForVisible(); diff --git a/tests/pageobjects/side-nav.page.js b/tests/pageobjects/side-nav.page.js index 7e9638b097a..f83e9a693ea 100644 --- a/tests/pageobjects/side-nav.page.js +++ b/tests/pageobjects/side-nav.page.js @@ -40,7 +40,7 @@ class SideNav extends Page { get channelLeave() { return browser.element('.leave-room'); } openChannel(channelName) { - browser.click('.rooms-list > .wrapper > ul [title="'+channelName+'"]'); + browser.click(`.rooms-list > .wrapper > ul [title="${ channelName }"]`); this.messageInput.waitForExist(5000); browser.waitUntil(function() { return browser.getText('.room-title') === channelName; @@ -51,8 +51,8 @@ class SideNav extends Page { this.spotlightSearch.waitForVisible(5000); this.spotlightSearch.click(); this.spotlightSearch.setValue(channelName); - browser.waitForVisible('.room-title='+channelName, 10000); - browser.click('.room-title='+channelName); + browser.waitForVisible(`.room-title=${ channelName }`, 10000); + browser.click(`.room-title=${ channelName }`); browser.waitUntil(function() { return browser.getText('.room-title') === channelName; }, 5000); @@ -62,12 +62,12 @@ class SideNav extends Page { this.spotlightSearch.waitForVisible(5000); this.spotlightSearch.click(); this.spotlightSearch.setValue(channelName); - browser.waitForVisible('.room-title='+channelName, 5000); - return browser.element('.room-title='+channelName); + browser.waitForVisible(`.room-title=${ channelName }`, 5000); + return browser.element(`.room-title=${ channelName }`); } getChannelFromList(channelName) { - return browser.element('.rooms-list > .wrapper > ul [title="'+channelName+'"]'); + return browser.element(`.rooms-list > .wrapper > ul [title="${ channelName }"]`); } createChannel(channelName, isPrivate, isReadOnly) { @@ -88,7 +88,7 @@ class SideNav extends Page { browser.pause(500); this.saveChannelBtn.click(); browser.pause(500); - browser.waitForExist('[title="'+channelName+'"]', 10000); + browser.waitForExist(`[title="${ channelName }"]`, 10000); this.channelType.waitForVisible(5000, true); } @@ -102,8 +102,8 @@ class SideNav extends Page { removePeopleFromChannel(user) { this.membersTab.click(); - browser.waitForVisible('[title="'+user+'"]'); - browser.click('[title="'+user+'"]'); + browser.waitForVisible(`[title="${ user }"]`); + browser.click(`[title="${ user }"]`); this.removeUserBtn.click(); } }