Additional eslint rules (#11804)

pull/11797/head^2
Diego Sampaio 7 years ago committed by GitHub
parent a4b99e1e74
commit dcdcbfba9e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 34
      .eslintrc
  2. 2
      .scripts/logs.js
  3. 2
      .scripts/md.js
  4. 2
      .scripts/start.js
  5. 4
      imports/message-read-receipt/server/models/ReadReceipts.js
  6. 5
      package.json
  7. 3
      packages/chatpal-search/server/provider/provider.js
  8. 4
      packages/meteor-accounts-saml/saml_client.js
  9. 7
      packages/meteor-accounts-saml/saml_rocketchat.js
  10. 2
      packages/meteor-accounts-saml/saml_server.js
  11. 4
      packages/meteor-accounts-saml/saml_utils.js
  12. 2
      packages/meteor-autocomplete/client/autocomplete-client.js
  13. 2
      packages/rocketchat-2fa/client/TOTPPassword.js
  14. 6
      packages/rocketchat-api/server/api.js
  15. 20
      packages/rocketchat-api/server/v1/channels.js
  16. 15
      packages/rocketchat-api/server/v1/groups.js
  17. 14
      packages/rocketchat-api/server/v1/im.js
  18. 2
      packages/rocketchat-api/server/v1/integrations.js
  19. 28
      packages/rocketchat-api/server/v1/rooms.js
  20. 2
      packages/rocketchat-api/server/v1/settings.js
  21. 4
      packages/rocketchat-api/server/v1/users.js
  22. 2
      packages/rocketchat-apps/client/admin/appInstall.js
  23. 1
      packages/rocketchat-apps/client/admin/apps.js
  24. 6
      packages/rocketchat-apps/server/bridges/settings.js
  25. 2
      packages/rocketchat-apps/server/communication/rest.js
  26. 4
      packages/rocketchat-apps/server/storage/logs-storage.js
  27. 2
      packages/rocketchat-assets/server/assets.js
  28. 4
      packages/rocketchat-authorization/server/models/Permissions.js
  29. 4
      packages/rocketchat-authorization/server/models/Roles.js
  30. 2
      packages/rocketchat-autotranslate/client/lib/autotranslate.js
  31. 2
      packages/rocketchat-autotranslate/client/views/autoTranslateFlexTab.js
  32. 2
      packages/rocketchat-autotranslate/server/autotranslate.js
  33. 10
      packages/rocketchat-channel-settings-mail-messages/client/views/mailMessagesInstructions.js
  34. 8
      packages/rocketchat-channel-settings/client/views/channelSettings.js
  35. 4
      packages/rocketchat-channel-settings/server/functions/saveRoomType.js
  36. 10
      packages/rocketchat-cors/cors.js
  37. 22
      packages/rocketchat-crowd/client/loginHelper.js
  38. 8
      packages/rocketchat-custom-oauth/server/custom_oauth_server.js
  39. 2
      packages/rocketchat-custom-sounds/client/admin/soundEdit.js
  40. 2
      packages/rocketchat-custom-sounds/client/admin/soundInfo.js
  41. 2
      packages/rocketchat-emoji-custom/admin/emojiEdit.js
  42. 2
      packages/rocketchat-emoji-custom/admin/emojiInfo.js
  43. 4
      packages/rocketchat-emoji/client/emojiPicker.js
  44. 3
      packages/rocketchat-emoji/client/lib/EmojiPicker.js
  45. 4
      packages/rocketchat-emoji/client/lib/emojiRenderer.js
  46. 4
      packages/rocketchat-error-handler/server/lib/RocketChat.ErrorHandler.js
  47. 4
      packages/rocketchat-file-upload/server/lib/FileUpload.js
  48. 2
      packages/rocketchat-file/file.server.js
  49. 2
      packages/rocketchat-graphql/server/mocks/accounts/graphql-api.js
  50. 8
      packages/rocketchat-iframe-login/iframe_client.js
  51. 2
      packages/rocketchat-importer-hipchat/server/importer.js
  52. 2
      packages/rocketchat-importer/client/admin/adminImportPrepare.js
  53. 44
      packages/rocketchat-integrations/server/lib/triggerHandler.js
  54. 4
      packages/rocketchat-integrations/server/triggers.js
  55. 2
      packages/rocketchat-katex/katex.js
  56. 23
      packages/rocketchat-ldap/client/loginHelper.js
  57. 8
      packages/rocketchat-ldap/server/sync.js
  58. 14
      packages/rocketchat-lib/client/Notifications.js
  59. 4
      packages/rocketchat-lib/client/lib/cachedCollection.js
  60. 2
      packages/rocketchat-lib/client/lib/openRoom.js
  61. 32
      packages/rocketchat-lib/client/models/_Base.js
  62. 4
      packages/rocketchat-lib/client/views/customFieldsForm.js
  63. 16
      packages/rocketchat-lib/server/functions/Notifications.js
  64. 2
      packages/rocketchat-lib/server/functions/notifications/email.js
  65. 2
      packages/rocketchat-lib/server/functions/saveCustomFieldsWithoutValidation.js
  66. 2
      packages/rocketchat-lib/server/functions/sendMessage.js
  67. 4
      packages/rocketchat-lib/server/functions/setUsername.js
  68. 2
      packages/rocketchat-lib/server/lib/RateLimiter.js
  69. 6
      packages/rocketchat-lib/server/lib/bugsnag.js
  70. 14
      packages/rocketchat-lib/server/lib/debug.js
  71. 2
      packages/rocketchat-lib/server/lib/loginErrorMessageOverride.js
  72. 2
      packages/rocketchat-lib/server/lib/processDirectEmail.js
  73. 3
      packages/rocketchat-lib/server/lib/sendNotificationsOnMessage.js
  74. 2
      packages/rocketchat-lib/server/methods/filterATAllTag.js
  75. 2
      packages/rocketchat-lib/server/methods/filterATHereTag.js
  76. 4
      packages/rocketchat-lib/server/models/Rooms.js
  77. 4
      packages/rocketchat-lib/server/models/Settings.js
  78. 4
      packages/rocketchat-lib/server/models/Subscriptions.js
  79. 4
      packages/rocketchat-lib/server/models/Users.js
  80. 84
      packages/rocketchat-lib/server/models/_Base.js
  81. 58
      packages/rocketchat-lib/server/models/_BaseDb.js
  82. 3
      packages/rocketchat-lib/server/startup/settingsOnLoadDirectReply.js
  83. 2
      packages/rocketchat-livechat/.app/client/lib/CustomFields.js
  84. 111
      packages/rocketchat-livechat/.app/client/lib/LivechatFileUpload.js
  85. 10
      packages/rocketchat-livechat/.app/client/lib/LivechatVideoCall.js
  86. 2
      packages/rocketchat-livechat/.app/client/lib/autolinker.js
  87. 12
      packages/rocketchat-livechat/.app/client/lib/chatMessages.js
  88. 6
      packages/rocketchat-livechat/.app/client/lib/commands.js
  89. 2
      packages/rocketchat-livechat/.app/client/lib/error.js
  90. 18
      packages/rocketchat-livechat/.app/client/lib/fromApp/Notifications.js
  91. 42
      packages/rocketchat-livechat/.app/client/lib/fromApp/RoomHistoryManager.js
  92. 4
      packages/rocketchat-livechat/.app/client/lib/fromApp/avatar.js
  93. 2
      packages/rocketchat-livechat/.app/client/lib/hooks.js
  94. 2
      packages/rocketchat-livechat/.app/client/lib/msgTyping.js
  95. 2
      packages/rocketchat-livechat/.app/client/lib/parentCall.js
  96. 6
      packages/rocketchat-livechat/.app/client/lib/tapi18n.js
  97. 10
      packages/rocketchat-livechat/.app/client/lib/triggers.js
  98. 4
      packages/rocketchat-livechat/.app/client/methods/sendMessageExternal.js
  99. 4
      packages/rocketchat-livechat/.app/client/routes/router.js
  100. 6
      packages/rocketchat-livechat/.app/client/startup/visitor.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -39,6 +39,24 @@
"no-inner-declarations": [2, "functions"],
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-mixed-operators": [2, {
"groups": [
["%", "**"],
["%", "+"],
["%", "-"],
["%", "*"],
["%", "/"],
["**", "+"],
["**", "-"],
["**", "*"],
["**", "/"],
["&", "|", "^", "~", "<<", ">>", ">>>"],
["==", "!=", "===", "!==", ">", ">=", "<", "<="],
["&&", "||"],
["in", "instanceof"]
],
"allowSamePrecedence": false
}],
"no-mixed-spaces-and-tabs": 2,
"no-sparse-arrays": 2,
"no-negated-in-lhs": 2,
@ -55,6 +73,22 @@
"no-void": 2,
"no-var": 2,
"no-multiple-empty-lines": [2, { "max": 2 }],
"no-nested-ternary": 2,
"prefer-rest-params": 2,
"array-callback-return": 2,
"prefer-destructuring": [2, {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": false,
"object": false
}
}, {
"enforceForRenamedProperties": false
}],
"no-duplicate-imports": 2,
"arrow-parens": [2, "always"],
"quote-props": [2, "as-needed"],
"no-array-constructor": 2,

@ -75,7 +75,7 @@ function getPRInfo(number, commit) {
.then((commits) => {
info.contributors = _.unique(_.flatten(commits.data.map((i) => {
if (!i.author || !i.committer) {
return;
return null;
}
return [i.author.login, i.committer.login];

@ -2,7 +2,7 @@ const path = require('path');
const fs = require('fs');
const semver = require('semver');
const _ = require('underscore');
const execSync = require('child_process').execSync;
const { execSync } = require('child_process');
const historyDataFile = path.join(__dirname, '../.github/history.json');
const historyManualDataFile = path.join(__dirname, '../.github/history-manual.json');

@ -3,7 +3,7 @@
const path = require('path');
const fs = require('fs');
const extend = require('util')._extend;
const exec = require('child_process').exec;
const { exec } = require('child_process');
const processes = [];
const baseDir = path.resolve(__dirname, '..');

@ -1,6 +1,6 @@
class ModelReadReceipts extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
this.tryEnsureIndex({
roomId: 1,

@ -63,8 +63,9 @@
"start": "meteor npm i && meteor",
"debug": "meteor run --inspect",
"debug-brk": "meteor run --inspect-brk",
"lint": "eslint .",
"lint-fix": "eslint . --fix",
"livechat-lint": "eslint ./packages/rocketchat-livechat/.app/",
"core-lint": "eslint .",
"lint": "npm run core-lint && npm run livechat-lint",
"stylelint": "stylelint packages/**/*.css",
"test": "node .scripts/start.js",
"deploy": "npm run build && pm2 startOrRestart pm2.json",

@ -1,5 +1,4 @@
import { searchProviderService } from 'meteor/rocketchat:search';
import { SearchProvider } from 'meteor/rocketchat:search';
import { searchProviderService, SearchProvider } from 'meteor/rocketchat:search';
import Index from './index';
import ChatpalLogger from '../utils/logger';

@ -20,7 +20,7 @@ const logoutBehaviour = {
ONLY_RC: 'Local',
};
Meteor.logout = function() {
Meteor.logout = function(...args) {
const samlService = ServiceConfiguration.configurations.findOne({ service: 'saml' });
if (samlService) {
const provider = samlService.clientConfig && samlService.clientConfig.provider;
@ -37,7 +37,7 @@ Meteor.logout = function() {
}
}
}
return MeteorLogout.apply(Meteor, arguments);
return MeteorLogout.apply(Meteor, args);
};
const openCenteredPopup = function(url, width, height) {

@ -164,11 +164,10 @@ const updateServices = debounce(() => {
$set: samlConfigs,
});
return configureSamlService(samlConfigs);
} else {
ServiceConfiguration.configurations.remove({
service: serviceName.toLowerCase(),
});
}
return ServiceConfiguration.configurations.remove({
service: serviceName.toLowerCase(),
});
}).filter((e) => e);
}, 2000);

@ -49,7 +49,7 @@ Meteor.methods({
}, {
'services.saml': 1,
});
let nameID = user.services.saml.nameID;
let { nameID } = user.services.saml;
const sessionIndex = user.services.saml.idpSession;
nameID = sessionIndex;
if (Accounts.saml.settings.debug) {

@ -15,9 +15,9 @@ SAML = function(options) {
this.options = this.initialize(options);
};
function debugLog() {
function debugLog(...args) {
if (Meteor.settings.debug) {
console.log.apply(this, arguments);
console.log.apply(this, args);
}
}

@ -80,7 +80,7 @@ this.AutoComplete = class {
item: '.-autocomplete-item',
...settings.selector,
};
const rules = this.rules;
const { rules } = this;
Object.keys(rules).forEach((key) => {
const rule = rules[key];

@ -37,7 +37,7 @@ Meteor.loginWithPasswordAndTOTP = function(selector, password, code, callback) {
});
};
const loginWithPassword = Meteor.loginWithPassword;
const { loginWithPassword } = Meteor;
Meteor.loginWithPassword = function(email, password, cb) {
loginWithPassword(email, password, (error) => {

@ -139,7 +139,7 @@ class API extends Restivus {
routes = [routes];
}
const version = this._config.version;
const { version } = this._config;
routes.forEach((route) => {
// Note: This is required due to Restivus calling `addRoute` in the constructor of itself
@ -362,7 +362,7 @@ class API extends Restivus {
}
}
const getUserAuth = function _getUserAuth() {
const getUserAuth = function _getUserAuth(...args) {
const invalidResults = [undefined, null, false];
return {
token: 'services.resume.loginTokens.hashedToken',
@ -375,7 +375,7 @@ const getUserAuth = function _getUserAuth() {
const method = RocketChat.API.v1.authMethods[i];
if (typeof method === 'function') {
const result = method.apply(this, arguments);
const result = method.apply(this, args);
if (!invalidResults.includes(result)) {
return result;
}

@ -105,7 +105,7 @@ RocketChat.API.v1.addRoute('channels.close', { authRequired: true }, {
RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, {
get() {
const access = RocketChat.authz.hasPermission(this.userId, 'view-room-administration');
const userId = this.requestParams().userId;
const { userId } = this.requestParams();
let user = this.userId;
let unreads = null;
let userMentions = null;
@ -174,10 +174,7 @@ function createChannelValidator(params) {
}
function createChannel(userId, params) {
let readOnly = false;
if (typeof params.readOnly !== 'undefined') {
readOnly = params.readOnly;
}
const readOnly = typeof params.readOnly !== 'undefined' ? params.readOnly : false;
let id;
Meteor.runAsUser(userId, () => {
@ -197,8 +194,7 @@ RocketChat.API.channels.create = {
RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, {
post() {
const userId = this.userId;
const bodyParams = this.bodyParams;
const { userId, bodyParams } = this;
let error;
@ -340,20 +336,14 @@ RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, {
oldestDate = new Date(this.queryParams.oldest);
}
let inclusive = false;
if (this.queryParams.inclusive) {
inclusive = this.queryParams.inclusive;
}
const inclusive = this.queryParams.inclusive || false;
let count = 20;
if (this.queryParams.count) {
count = parseInt(this.queryParams.count);
}
let unreads = false;
if (this.queryParams.unreads) {
unreads = this.queryParams.unreads;
}
const unreads = this.queryParams.unreads || false;
let result;
Meteor.runAsUser(this.userId, () => {

@ -194,10 +194,7 @@ RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, {
return RocketChat.API.v1.failure('Body param "customFields" must be an object if provided');
}
let readOnly = false;
if (typeof this.bodyParams.readOnly !== 'undefined') {
readOnly = this.bodyParams.readOnly;
}
const readOnly = typeof this.bodyParams.readOnly !== 'undefined' ? this.bodyParams.readOnly : false;
let id;
Meteor.runAsUser(this.userId, () => {
@ -307,20 +304,14 @@ RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, {
oldestDate = new Date(this.queryParams.oldest);
}
let inclusive = false;
if (this.queryParams.inclusive) {
inclusive = this.queryParams.inclusive;
}
const inclusive = this.queryParams.inclusive || false;
let count = 20;
if (this.queryParams.count) {
count = parseInt(this.queryParams.count);
}
let unreads = false;
if (this.queryParams.unreads) {
unreads = this.queryParams.unreads;
}
const unreads = this.queryParams.unreads || false;
let result;
Meteor.runAsUser(this.userId, () => {

@ -68,7 +68,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true
user = ruserId;
}
const rs = findDirectMessageRoom(this.requestParams(), { _id: user });
const room = rs.room;
const { room } = rs;
const dm = rs.subscription;
lm = room.lm ? room.lm : room._updatedAt;
@ -144,20 +144,14 @@ RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true },
oldestDate = new Date(this.queryParams.oldest);
}
let inclusive = false;
if (this.queryParams.inclusive) {
inclusive = this.queryParams.inclusive;
}
const inclusive = this.queryParams.inclusive || false;
let count = 20;
if (this.queryParams.count) {
count = parseInt(this.queryParams.count);
}
let unreads = false;
if (this.queryParams.unreads) {
unreads = this.queryParams.unreads;
}
const unreads = this.queryParams.unreads || false;
let result;
Meteor.runAsUser(this.userId, () => {
@ -245,7 +239,7 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR
return RocketChat.API.v1.unauthorized();
}
const roomId = this.queryParams.roomId;
const { roomId } = this.queryParams;
if (!roomId || !roomId.trim()) {
throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" is required');
}

@ -49,7 +49,7 @@ RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, {
return RocketChat.API.v1.failure('Invalid integration id.');
}
const id = this.queryParams.id;
const { id } = this.queryParams;
const { offset, count } = this.getPaginationItems();
const { sort, fields, query } = this.parseJsonQuery();

@ -120,9 +120,11 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, {
RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, {
post() {
const saveNotifications = (notifications, roomId) => {
Object.keys(notifications).map((notificationKey) => {
Meteor.runAsUser(this.userId, () => Meteor.call('saveNotificationSettings', roomId, notificationKey, notifications[notificationKey]));
});
Object.keys(notifications).forEach((notificationKey) =>
Meteor.runAsUser(this.userId, () =>
Meteor.call('saveNotificationSettings', roomId, notificationKey, notifications[notificationKey])
)
);
};
const { roomId, notifications } = this.bodyParams;
@ -171,14 +173,18 @@ RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, {
const latest = new Date(this.bodyParams.latest);
const oldest = new Date(this.bodyParams.oldest);
let inclusive = false;
if (typeof this.bodyParams.inclusive !== 'undefined') {
inclusive = this.bodyParams.inclusive;
}
Meteor.runAsUser(this.userId, () => {
Meteor.call('cleanRoomHistory', { roomId: findResult._id, latest, oldest, inclusive, limit: this.bodyParams.limit, excludePinned: this.bodyParams.excludePinned, filesOnly: this.bodyParams.filesOnly, fromUsers: this.bodyParams.users });
});
const inclusive = this.bodyParams.inclusive || false;
Meteor.runAsUser(this.userId, () => Meteor.call('cleanRoomHistory', {
roomId: findResult._id,
latest,
oldest,
inclusive,
limit: this.bodyParams.limit,
excludePinned: this.bodyParams.excludePinned,
filesOnly: this.bodyParams.filesOnly,
fromUsers: this.bodyParams.users,
}));
return RocketChat.API.v1.success();
},

@ -128,7 +128,7 @@ RocketChat.API.v1.addRoute('settings/:_id', { authRequired: true }, {
RocketChat.API.v1.addRoute('service.configurations', { authRequired: false }, {
get() {
const ServiceConfiguration = Package['service-configuration'].ServiceConfiguration;
const { ServiceConfiguration } = Package['service-configuration'];
return RocketChat.API.v1.success({
configurations: ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch(),

@ -320,7 +320,7 @@ RocketChat.API.v1.addRoute('users.getPreferences', { authRequired: true }, {
get() {
const user = RocketChat.models.Users.findOneById(this.userId);
if (user.settings) {
const preferences = user.settings.preferences;
const { preferences } = user.settings;
preferences.language = user.language;
return RocketChat.API.v1.success({
@ -379,7 +379,7 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, {
};
if (this.bodyParams.data.language) {
const language = this.bodyParams.data.language;
const { language } = this.bodyParams.data;
delete this.bodyParams.data.language;
userData.language = language;
}

@ -88,7 +88,7 @@ Template.appInstall.events({
return;
}
const files = $('#upload-app')[0].files;
const { files } = $('#upload-app')[0];
if (!(files instanceof FileList)) {
return;
}

@ -44,6 +44,7 @@ Template.apps.onCreated(function() {
index = i;
return true;
}
return false;
});
apps.splice(index, 1);

@ -22,9 +22,9 @@ export class AppSettingBridge {
async getAll(appId) {
console.log(`The App ${ appId } is getting all the settings.`);
return RocketChat.models.Settings.find({ _id: { $nin: this.disallowedSettings } }).fetch().map((s) => {
this.orch.getConverters().get('settings').convertToApp(s);
});
return RocketChat.models.Settings.find({ _id: { $nin: this.disallowedSettings } })
.fetch()
.map((s) => this.orch.getConverters().get('settings').convertToApp(s));
}
async getOneById(id, appId) {

@ -256,7 +256,7 @@ export class AppsRestApi {
return RocketChat.API.v1.notFound(`No App found by the id of: ${ this.urlParams.id }`);
}
const settings = prl.getStorageItem().settings;
const { settings } = prl.getStorageItem();
const updated = [];
this.bodyParams.settings.forEach((s) => {

@ -7,12 +7,12 @@ export class AppRealLogsStorage extends AppLogStorage {
this.db = model;
}
find() {
find(...args) {
return new Promise((resolve, reject) => {
let docs;
try {
docs = this.db.find(...arguments).fetch();
docs = this.db.find(...args).fetch();
} catch (e) {
return reject(e);
}

@ -352,7 +352,7 @@ Meteor.startup(function() {
}, 200);
});
const calculateClientHash = WebAppHashing.calculateClientHash;
const { calculateClientHash } = WebAppHashing;
WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) {
for (const key of Object.keys(assets)) {

@ -1,6 +1,6 @@
class ModelPermissions extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
}
// FIND

@ -1,6 +1,6 @@
class ModelRoles extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
this.tryEnsureIndex({ name: 1 });
this.tryEnsureIndex({ scope: 1 });
}

@ -9,7 +9,7 @@ RocketChat.AutoTranslate = {
if (rid) {
subscription = RocketChat.models.Subscriptions.findOne({ rid }, { fields: { autoTranslateLanguage: 1 } });
}
const language = subscription && subscription.autoTranslateLanguage || Meteor.user().language || window.defaultUserLanguage();
const language = (subscription && subscription.autoTranslateLanguage) || Meteor.user().language || window.defaultUserLanguage();
if (language.indexOf('-') !== -1) {
if (!_.findWhere(this.supportedLanguages, { language })) {
return language.substr(0, 2);

@ -33,7 +33,7 @@ Template.autoTranslateFlexTab.helpers({
autoTranslateLanguage: 1,
},
});
const autoTranslateLanguage = sub && sub.autoTranslateLanguage || Meteor.user().language || window.defaultUserLanguage() || '';
const autoTranslateLanguage = (sub && sub.autoTranslateLanguage) || Meteor.user().language || window.defaultUserLanguage() || '';
const supportedLanguages = Template.instance().supportedLanguages.get();
let language = _.findWhere(supportedLanguages, { language: autoTranslateLanguage });
if (language) {

@ -93,7 +93,7 @@ class AutoTranslate {
for (const tokenIndex in message.tokens) {
if (message.tokens.hasOwnProperty(tokenIndex)) {
const token = message.tokens[tokenIndex].token;
const { token } = message.tokens[tokenIndex];
if (token.indexOf('notranslate') === -1) {
const newToken = `<i class=notranslate>{${ count++ }}</i>`;
message.msg = message.msg.replace(token, newToken);

@ -111,10 +111,8 @@ Template.mailMessagesInstructions.events({
t.reset(true);
},
'click .js-send'(e, instance) {
const selectedUsers = instance.selectedUsers;
const selectedEmails = instance.selectedEmails;
const { selectedUsers, selectedEmails, selectedMessages } = instance;
const $emailsInput = instance.$('[name="emails"]');
const selectedMessages = instance.selectedMessages;
const subject = instance.$('[name="subject"]').val();
if (!selectedUsers.get().length && !selectedEmails.get().length && $emailsInput.val().trim() === '') {
@ -171,7 +169,7 @@ Template.mailMessagesInstructions.events({
'input [name="users"]'(e, t) {
const input = e.target;
const position = input.selectionEnd || input.selectionStart;
const length = input.value.length;
const { length } = input.value;
const modified = filterNames(input.value);
input.value = modified;
document.activeElement === input && e && /input/i.test(e.type) && (input.selectionEnd = position + input.value.length - length);
@ -229,10 +227,10 @@ Template.mailMessagesInstructions.onRendered(function() {
users.set(usersArr);
});
const selectedMessages = this.selectedMessages;
const { selectedMessages } = this;
$('.messages-box .message').on('click', function() {
const id = this.id;
const { id } = this;
const messages = selectedMessages.get();
if ($(this).hasClass('selected')) {

@ -150,13 +150,15 @@ Template.channelSettingsEditing.events({
value: 'disabled',
}];
const value = this.value.get() ? 'enabled' : this.value.get() === false ? 'disabled' : 'default';
const falseOrDisabled = this.value.get() === false ? 'disabled' : 'default';
const value = this.value.get() ? 'enabled' : falseOrDisabled;
const config = {
popoverClass: 'notifications-preferences',
template: 'pushNotificationsPopover',
data: {
change : (value) => {
const realValue = value === 'enabled' ? true : value === 'disabled' ? false : undefined;
const falseOrUndefined = value === 'disabled' ? false : undefined;
const realValue = value === 'enabled' ? true : falseOrUndefined;
return this.value.set(realValue);
},
value,
@ -695,7 +697,7 @@ Template.channelSettingsEditing.helpers({
},
retentionEnabled(value) {
const { room } = Template.instance();
return value || value === undefined && retentionEnabled(room);
return (value || value === undefined) && retentionEnabled(room);
},
retentionMaxAgeLabel(label) {
const { room } = Template.instance();

@ -28,11 +28,11 @@ RocketChat.saveRoomType = function(rid, roomType, user, sendMessage = true) {
let message;
if (roomType === 'c') {
message = TAPi18n.__('Channel', {
lng: user && user.language || RocketChat.settings.get('language') || 'en',
lng: (user && user.language) || RocketChat.settings.get('language') || 'en',
});
} else {
message = TAPi18n.__('Private_Group', {
lng: user && user.language || RocketChat.settings.get('language') || 'en',
lng: (user && user.language) || RocketChat.settings.get('language') || 'en',
});
}
RocketChat.models.Messages.createRoomSettingsChangedWithTypeRoomIdMessageAndUser('room_changed_privacy', rid, message, user);

@ -65,12 +65,12 @@ WebApp.rawConnectHandlers.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
const setHeader = res.setHeader;
res.setHeader = function(key, val) {
const { setHeader } = res;
res.setHeader = function(key, val, ...args) {
if (key.toLowerCase() === 'access-control-allow-origin' && val === 'http://meteor.local') {
return;
}
return setHeader.apply(this, arguments);
return setHeader.apply(this, [key, val, ...args]);
};
return next();
});
@ -86,10 +86,10 @@ const oldHttpServerListeners = WebApp.httpServer.listeners('request').slice(0);
WebApp.httpServer.removeAllListeners('request');
WebApp.httpServer.addListener('request', function(req, res) {
WebApp.httpServer.addListener('request', function(req, res, ...args) {
const next = () => {
for (const oldListener of oldHttpServerListeners) {
oldListener.apply(WebApp.httpServer, arguments);
oldListener.apply(WebApp.httpServer, [req, res, ...args]);
}
};

@ -1,12 +1,9 @@
Meteor.loginWithCrowd = function(username, password, callback) {
// Retrieve arguments as array
const args = [];
for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
Meteor.loginWithCrowd = function(...args) {
// Pull username and password
username = args.shift();
password = args.shift();
const username = args.shift();
const password = args.shift();
const callback = args.shift();
const loginRequest = {
crowd: true,
username,
@ -15,12 +12,11 @@ Meteor.loginWithCrowd = function(username, password, callback) {
Accounts.callLoginMethod({
methodArguments: [loginRequest],
userCallback(error) {
if (error) {
if (callback) {
callback(error);
if (callback) {
if (error) {
return callback(error);
}
} else if (callback) {
callback();
return callback();
}
},
});

@ -326,11 +326,11 @@ export class CustomOAuth {
}
const updateOrCreateUserFromExternalService = Accounts.updateOrCreateUserFromExternalService;
Accounts.updateOrCreateUserFromExternalService = function(/* serviceName, serviceData, options*/) {
const { updateOrCreateUserFromExternalService } = Accounts;
Accounts.updateOrCreateUserFromExternalService = function(...args /* serviceName, serviceData, options*/) {
for (const hook of BeforeUpdateOrCreateUserFromExternalService) {
hook.apply(this, arguments);
hook.apply(this, args);
}
return updateOrCreateUserFromExternalService.apply(this, arguments);
return updateOrCreateUserFromExternalService.apply(this, args);
};

@ -27,7 +27,7 @@ Template.soundEdit.events({
'change input[type=file]'(ev) {
const e = (ev.originalEvent != null) ? ev.originalEvent : ev;
let files = e.target.files;
let { files } = e.target;
if (e.target.files == null || files.length === 0) {
if (e.dataTransfer.files != null) {
files = e.dataTransfer.files;

@ -38,7 +38,7 @@ Template.soundInfo.events({
e.preventDefault();
const sound = instance.sound.get();
if (sound != null) {
const _id = sound._id;
const { _id } = sound;
modal.open({
title: t('Are_you_sure'),
text: t('Custom_Sound_Delete_Warning'),

@ -27,7 +27,7 @@ Template.emojiEdit.events({
'change input[type=file]'(ev) {
const e = ev.originalEvent != null ? ev.originalEvent : ev;
let files = e.target.files;
let { files } = e.target;
if (files == null || files.length === 0) {
if (e.dataTransfer != null && e.dataTransfer.files != null) {
files = e.dataTransfer.files;

@ -46,7 +46,7 @@ Template.emojiInfo.events({
e.preventDefault();
const emoji = instance.emoji.get();
if (emoji != null) {
const _id = emoji._id;
const { _id } = emoji;
modal.open({
title: t('Are_you_sure'),
text: t('Custom_Emoji_Delete_Warning'),

@ -65,7 +65,7 @@ function getEmojisBySearchTerm(searchTerm) {
if (searchRegExp.test(emoji)) {
const emojiObject = RocketChat.emoji.list[emoji];
const emojiPackage = emojiObject.emojiPackage;
const { emojiPackage } = emojiObject;
let tone = '';
emoji = emoji.replace(/:/g, '');
@ -228,7 +228,7 @@ Template.emojiPicker.events({
'click .emoji-list li'(event, instance) {
event.stopPropagation();
const emoji = event.currentTarget.dataset.emoji;
const { emoji } = event.currentTarget.dataset;
const actualTone = instance.tone;
let tone = '';

@ -57,8 +57,7 @@ RocketChat.EmojiPicker = {
const windowHeight = window.innerHeight;
const windowBorder = 10;
const sourcePos = $(this.source).offset();
const left = sourcePos.left;
const top = sourcePos.top;
const { left, top } = sourcePos;
const cssProperties = { top, left };
if (top + this.height >= windowHeight) {

@ -1,7 +1,7 @@
/* globals HTML, isSetNotNull, renderEmoji:true */
renderEmoji = function(emoji) {
if (isSetNotNull(() => RocketChat.emoji.list[emoji].emojiPackage)) {
const emojiPackage = RocketChat.emoji.list[emoji].emojiPackage;
const { emojiPackage } = RocketChat.emoji.list[emoji];
return RocketChat.emoji.packages[emojiPackage].render(emoji);
}
};
@ -13,7 +13,7 @@ Template.registerHelper('renderEmoji', new Template('renderEmoji', function() {
const emoji = Blaze.getData(view);
if (isSetNotNull(() => RocketChat.emoji.list[emoji].emojiPackage)) {
const emojiPackage = RocketChat.emoji.list[emoji].emojiPackage;
const { emojiPackage } = RocketChat.emoji.list[emoji];
return new HTML.Raw(RocketChat.emoji.packages[emojiPackage].render(emoji));
}

@ -33,12 +33,12 @@ class ErrorHandler {
const self = this;
const originalMeteorDebug = Meteor._debug;
Meteor._debug = function(message, stack) {
Meteor._debug = function(message, stack, ...args) {
if (!self.reporting) {
return originalMeteorDebug.call(this, message, stack);
}
self.trackError(message, stack);
return originalMeteorDebug.apply(this, arguments);
return originalMeteorDebug.apply(this, [message, stack, ...args]);
};
}

@ -112,7 +112,7 @@ Object.assign(FileUpload, {
if (err != null) {
console.error(err);
}
const size = fs.lstatSync(tempFilePath).size;
const { size } = fs.lstatSync(tempFilePath);
this.getCollection().direct.update({ _id: file._id }, { $set: { size } });
future.return();
}));
@ -170,7 +170,7 @@ Object.assign(FileUpload, {
.then(Meteor.bindEnvironment(() => {
fs.unlink(tmpFile, Meteor.bindEnvironment(() => {
fs.rename(`${ tmpFile }.tmp`, tmpFile, Meteor.bindEnvironment(() => {
const size = fs.lstatSync(tmpFile).size;
const { size } = fs.lstatSync(tmpFile);
this.getCollection().direct.update({ _id: file._id }, {
$set: {
size,

@ -38,7 +38,7 @@ RocketChatFile.GridFS = class {
this.name = name;
this.transformWrite = transformWrite;
const mongo = Package.mongo.MongoInternals.NpmModule;
const db = Package.mongo.MongoInternals.defaultRemoteCollectionDriver().mongo.db;
const { db } = Package.mongo.MongoInternals.defaultRemoteCollectionDriver().mongo;
this.store = new Grid(db, mongo);
this.findOneSync = Meteor.wrapAsync(this.store.collection(this.name).findOne.bind(this.store.collection(this.name)));
this.removeSync = Meteor.wrapAsync(this.store.remove.bind(this.store));

@ -5,7 +5,7 @@
// See: https://github.com/meteor/meteor/blob/a362e20a37547362b581fed52f7171d022e83b62/packages/promise/server.js
// Opened issue: https://github.com/js-accounts/graphql/issues/16
export const authenticated = (Accounts, func) => (async(root, args, context, info) => {
const authToken = context.authToken;
const { authToken } = context;
if (!authToken || authToken === '' || authToken === null) {
throw new Error('Unable to find authorization token in request');

@ -2,10 +2,10 @@
import _ from 'underscore';
const _unstoreLoginToken = Accounts._unstoreLoginToken;
Accounts._unstoreLoginToken = function() {
const { _unstoreLoginToken } = Accounts;
Accounts._unstoreLoginToken = function(...args) {
RocketChat.iframeLogin.tryLogin();
_unstoreLoginToken.apply(Accounts, arguments);
_unstoreLoginToken.apply(Accounts, args);
};
class IframeLogin {
@ -54,7 +54,7 @@ class IframeLogin {
},
};
let iframeUrl = this.iframeUrl;
let { iframeUrl } = this;
let separator = '?';
if (iframeUrl.indexOf('?') > -1) {
separator = '&';

@ -23,7 +23,7 @@ export class HipChatImporter extends Base {
prepare(dataURI, sentContentType, fileName) {
super.prepare(dataURI, sentContentType, fileName);
const image = RocketChatFile.dataURIParse(dataURI).image;
const { image } = RocketChatFile.dataURIParse(dataURI);
// const contentType = ref.contentType;
const zip = new this.AdmZip(new Buffer(image, 'base64'));
const zipEntries = zip.getEntries();

@ -38,7 +38,7 @@ Template.adminImportPrepare.events({
files = (e.dataTransfer != null ? e.dataTransfer.files : undefined) || [];
}
return Array.from(files).map((file) => {
Array.from(files).forEach((file) => {
template.preparing.set(true);
const reader = new FileReader();

@ -342,48 +342,48 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
}
eventNameArgumentsToObject() {
eventNameArgumentsToObject(...args) {
const argObject = {
event: arguments[0],
event: args[0],
};
switch (argObject.event) {
case 'sendMessage':
if (arguments.length >= 3) {
argObject.message = arguments[1];
argObject.room = arguments[2];
if (args.length >= 3) {
argObject.message = args[1];
argObject.room = args[2];
}
break;
case 'fileUploaded':
if (arguments.length >= 2) {
const arghhh = arguments[1];
if (args.length >= 2) {
const arghhh = args[1];
argObject.user = arghhh.user;
argObject.room = arghhh.room;
argObject.message = arghhh.message;
}
break;
case 'roomArchived':
if (arguments.length >= 3) {
argObject.room = arguments[1];
argObject.user = arguments[2];
if (args.length >= 3) {
argObject.room = args[1];
argObject.user = args[2];
}
break;
case 'roomCreated':
if (arguments.length >= 3) {
argObject.owner = arguments[1];
argObject.room = arguments[2];
if (args.length >= 3) {
argObject.owner = args[1];
argObject.room = args[2];
}
break;
case 'roomJoined':
case 'roomLeft':
if (arguments.length >= 3) {
argObject.user = arguments[1];
argObject.room = arguments[2];
if (args.length >= 3) {
argObject.user = args[1];
argObject.room = args[2];
}
break;
case 'userCreated':
if (arguments.length >= 2) {
argObject.user = arguments[1];
if (args.length >= 2) {
argObject.user = args[1];
}
break;
default:
@ -479,10 +479,10 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
}
}
executeTriggers() {
logger.outgoing.debug('Execute Trigger:', arguments[0]);
executeTriggers(...args) {
logger.outgoing.debug('Execute Trigger:', args[0]);
const argObject = this.eventNameArgumentsToObject(...arguments);
const argObject = this.eventNameArgumentsToObject(...args);
const { event, message, room } = argObject;
// Each type of event should have an event and a room attached, otherwise we
@ -793,7 +793,7 @@ RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler
throw new Meteor.Error('history-data-must-be-defined', 'The history data must be defined to replay an integration.');
}
const event = history.event;
const { event } = history;
const message = RocketChat.models.Messages.findOneById(history.data.message_id);
const room = RocketChat.models.Rooms.findOneById(history.data.channel_id);
const user = RocketChat.models.Users.findOneById(history.data.user_id);

@ -1,6 +1,6 @@
const callbackHandler = function _callbackHandler(eventType) {
return function _wrapperFunction() {
return RocketChat.integrations.triggerHandler.executeTriggers(eventType, ...arguments);
return function _wrapperFunction(...args) {
return RocketChat.integrations.triggerHandler.executeTriggers(eventType, ...args);
};
};

@ -101,7 +101,7 @@ class Katex {
const outer = new Boundary;
// The closing delimiter matching to the opening one
const closer = opening_delimiter_match.options.closer;
const { closer } = opening_delimiter_match.options;
outer.start = opening_delimiter_match.pos;
inner.start = opening_delimiter_match.pos + closer.length;

@ -2,30 +2,17 @@
// customLdapOptions should be passed in if you want to override LDAP_DEFAULTS
// on any particular call (if you have multiple ldap servers you'd like to connect to)
// You'll likely want to set the dn value here {dn: "..."}
Meteor.loginWithLDAP = function(username, password, customLdapOptions, callback) {
// Retrieve arguments as array
const args = [];
for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
Meteor.loginWithLDAP = function(...args) {
// Pull username and password
username = args.shift();
password = args.shift();
const username = args.shift();
const password = args.shift();
// Check if last argument is a function
// if it is, pop it off and set callback to it
if (typeof args[args.length - 1] === 'function') {
callback = args.pop();
} else {
callback = null;
}
const callback = typeof args[args.length - 1] === 'function' ? args.pop() : null;
// if args still holds options item, grab it
if (args.length > 0) {
customLdapOptions = args.shift();
} else {
customLdapOptions = {};
}
const customLdapOptions = args.length > 0 ? args.shift() : {};
// Set up loginRequest object
const loginRequest = {

@ -129,11 +129,11 @@ export function getDataToSyncUserData(ldapUser, user) {
// TODO: Find a better solution.
const dKeys = userField.split('.');
const lastKey = _.last(dKeys);
_.reduce(dKeys, (obj, currKey) =>
((currKey === lastKey)
_.reduce(dKeys, (obj, currKey) => (
(currKey === lastKey)
? obj[currKey] = tmpLdapField
: obj[currKey] = obj[currKey] || {})
, userData);
: obj[currKey] = obj[currKey] || {}
), userData);
logger.debug(`user.${ userField } changed to: ${ tmpLdapField }`);
}
}

@ -1,5 +1,5 @@
RocketChat.Notifications = new class {
constructor() {
constructor(...args) {
this.logged = Meteor.userId() !== null;
this.loginCb = [];
Tracker.autorun(() => {
@ -16,10 +16,10 @@ RocketChat.Notifications = new class {
this.streamUser = new Meteor.Streamer('notify-user');
if (this.debug === true) {
this.onAll(function() {
return console.log('RocketChat.Notifications: onAll', arguments);
return console.log('RocketChat.Notifications: onAll', args);
});
this.onUser(function() {
return console.log('RocketChat.Notifications: onAll', arguments);
return console.log('RocketChat.Notifications: onAll', args);
});
}
}
@ -32,21 +32,21 @@ RocketChat.Notifications = new class {
}
notifyRoom(room, eventName, ...args) {
if (this.debug === true) {
console.log('RocketChat.Notifications: notifyRoom', arguments);
console.log('RocketChat.Notifications: notifyRoom', [room, eventName, ...args]);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoom.emit.apply(this.streamRoom, args);
}
notifyUser(userId, eventName, ...args) {
if (this.debug === true) {
console.log('RocketChat.Notifications: notifyUser', arguments);
console.log('RocketChat.Notifications: notifyUser', [userId, eventName, ...args]);
}
args.unshift(`${ userId }/${ eventName }`);
return this.streamUser.emit.apply(this.streamUser, args);
}
notifyUsersOfRoom(room, eventName, ...args) {
if (this.debug === true) {
console.log('RocketChat.Notifications: notifyUsersOfRoom', arguments);
console.log('RocketChat.Notifications: notifyUsersOfRoom', [room, eventName, ...args]);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoomUsers.emit.apply(this.streamRoomUsers, args);
@ -60,7 +60,7 @@ RocketChat.Notifications = new class {
onRoom(room, eventName, callback) {
if (this.debug === true) {
this.streamRoom.on(room, function() {
return console.log(`RocketChat.Notifications: onRoom ${ room }`, arguments);
return console.log(`RocketChat.Notifications: onRoom ${ room }`, [room, eventName, callback]);
});
}
return this.streamRoom.on(`${ room }/${ eventName }`, callback);

@ -9,7 +9,7 @@ class CachedCollectionManager {
this.loginCb = [];
this.logged = false;
const _unstoreLoginToken = Accounts._unstoreLoginToken;
const { _unstoreLoginToken } = Accounts;
Accounts._unstoreLoginToken = (...args) => {
_unstoreLoginToken.apply(Accounts, args);
this.clearAllCacheOnLogout();
@ -20,7 +20,7 @@ class CachedCollectionManager {
Meteor.setTimeout(() => {
let connectionWasOnline = true;
Tracker.autorun(() => {
const connected = Meteor.connection.status().connected;
const { connected } = Meteor.connection.status();
if (connected === true && connectionWasOnline === false) {
for (const cb of this.reconnectCb) {

@ -9,7 +9,7 @@ function openRoom(type, name) {
return Meteor.defer(() =>
currentTracker = Tracker.autorun(function(c) {
const user = Meteor.user();
if ((user && user.username == null) || user == null && RocketChat.settings.get('Accounts_AllowAnonymousRead') === false) {
if ((user && user.username == null) || (user == null && RocketChat.settings.get('Accounts_AllowAnonymousRead') === false)) {
BlazeLayout.render('main');
return;
}

@ -9,36 +9,36 @@ RocketChat.models._Base = class {
return this.model = new Mongo.Collection(this._baseName() + name);
}
find() {
return this.model.find.apply(this.model, arguments);
find(...args) {
return this.model.find.apply(this.model, args);
}
findOne() {
return this.model.findOne.apply(this.model, arguments);
findOne(...args) {
return this.model.findOne.apply(this.model, args);
}
insert() {
return this.model.insert.apply(this.model, arguments);
insert(...args) {
return this.model.insert.apply(this.model, args);
}
update() {
return this.model.update.apply(this.model, arguments);
update(...args) {
return this.model.update.apply(this.model, args);
}
upsert() {
return this.model.upsert.apply(this.model, arguments);
upsert(...args) {
return this.model.upsert.apply(this.model, args);
}
remove() {
return this.model.remove.apply(this.model, arguments);
remove(...args) {
return this.model.remove.apply(this.model, args);
}
allow() {
return this.model.allow.apply(this.model, arguments);
allow(...args) {
return this.model.allow.apply(this.model, args);
}
deny() {
return this.model.deny.apply(this.model, arguments);
deny(...args) {
return this.model.deny.apply(this.model, args);
}
ensureIndex() {}

@ -25,7 +25,7 @@ Template.customFieldsForm.helpers({
return customFieldsArray;
},
selectedField(current, field) {
const formData = Template.instance().formData;
const { formData } = Template.instance();
if (typeof formData[field.fieldName] !== 'undefined') {
return formData[field.fieldName] === current;
@ -34,7 +34,7 @@ Template.customFieldsForm.helpers({
}
},
fieldValue() {
const formData = Template.instance().formData;
const { formData } = Template.instance();
return formData[this.fieldName];
},

@ -50,7 +50,7 @@ RocketChat.Notifications = new class {
notifyAll(eventName, ...args) {
if (this.debug === true) {
console.log('notifyAll', arguments);
console.log('notifyAll', [eventName, ...args]);
}
args.unshift(eventName);
return this.streamAll.emit.apply(this.streamAll, args);
@ -58,7 +58,7 @@ RocketChat.Notifications = new class {
notifyLogged(eventName, ...args) {
if (this.debug === true) {
console.log('notifyLogged', arguments);
console.log('notifyLogged', [eventName, ...args]);
}
args.unshift(eventName);
return this.streamLogged.emit.apply(this.streamLogged, args);
@ -66,7 +66,7 @@ RocketChat.Notifications = new class {
notifyRoom(room, eventName, ...args) {
if (this.debug === true) {
console.log('notifyRoom', arguments);
console.log('notifyRoom', [room, eventName, ...args]);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoom.emit.apply(this.streamRoom, args);
@ -74,7 +74,7 @@ RocketChat.Notifications = new class {
notifyUser(userId, eventName, ...args) {
if (this.debug === true) {
console.log('notifyUser', arguments);
console.log('notifyUser', [userId, eventName, ...args]);
}
args.unshift(`${ userId }/${ eventName }`);
return this.streamUser.emit.apply(this.streamUser, args);
@ -82,7 +82,7 @@ RocketChat.Notifications = new class {
notifyAllInThisInstance(eventName, ...args) {
if (this.debug === true) {
console.log('notifyAll', arguments);
console.log('notifyAll', [eventName, ...args]);
}
args.unshift(eventName);
return this.streamAll.emitWithoutBroadcast.apply(this.streamAll, args);
@ -90,7 +90,7 @@ RocketChat.Notifications = new class {
notifyLoggedInThisInstance(eventName, ...args) {
if (this.debug === true) {
console.log('notifyLogged', arguments);
console.log('notifyLogged', [eventName, ...args]);
}
args.unshift(eventName);
return this.streamLogged.emitWithoutBroadcast.apply(this.streamLogged, args);
@ -98,7 +98,7 @@ RocketChat.Notifications = new class {
notifyRoomInThisInstance(room, eventName, ...args) {
if (this.debug === true) {
console.log('notifyRoomAndBroadcast', arguments);
console.log('notifyRoomAndBroadcast', [room, eventName, ...args]);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoom.emitWithoutBroadcast.apply(this.streamRoom, args);
@ -106,7 +106,7 @@ RocketChat.Notifications = new class {
notifyUserInThisInstance(userId, eventName, ...args) {
if (this.debug === true) {
console.log('notifyUserAndBroadcast', arguments);
console.log('notifyUserAndBroadcast', [userId, eventName, ...args]);
}
args.unshift(`${ userId }/${ eventName }`);
return this.streamUser.emitWithoutBroadcast.apply(this.streamUser, args);

@ -13,7 +13,7 @@ RocketChat.settings.get('Email_Footer', (key, value) => {
const divisorMessage = '<hr style="margin: 20px auto; border: none; border-bottom: 1px solid #dddddd;">';
function getEmailContent({ message, user, room }) {
const lng = user && user.language || RocketChat.settings.get('language') || 'en';
const lng = (user && user.language) || RocketChat.settings.get('language') || 'en';
const roomName = s.escapeHTML(`#${ RocketChat.roomTypes.getRoomName(room.t, room) }`);
const userName = s.escapeHTML(RocketChat.settings.get('UI_Use_Real_Name') ? message.u.name || message.u.username : message.u.username);

@ -21,7 +21,7 @@ RocketChat.saveCustomFieldsWithoutValidation = function(userId, formData) {
return;
}
const modifyRecordField = customFieldsMeta[fieldName].modifyRecordField;
const { modifyRecordField } = customFieldsMeta[fieldName];
const update = {};
if (modifyRecordField.array) {
update.$addToSet = {};

@ -134,7 +134,7 @@ RocketChat.sendMessage = function(user, message, room, upsert = false) {
}
if (message._id && upsert) {
const _id = message._id;
const { _id } = message;
delete message._id;
RocketChat.models.Messages.upsert({
_id,

@ -45,9 +45,9 @@ RocketChat._setUsername = function(userId, u) {
RocketChat.setUserAvatar(user, avatarData.blob, avatarData.contentType, service);
gravatar = null;
return true;
} else {
gravatar = avatarData;
}
gravatar = avatarData;
return false;
});
if (gravatar != null) {
RocketChat.setUserAvatar(user, gravatar.blob, gravatar.contentType, 'gravatar');

@ -16,7 +16,7 @@ RocketChat.RateLimiter = new class {
rateLimiter.increment(match);
const rateLimitResult = rateLimiter.check(match);
if (rateLimitResult.allowed) {
return fn.apply(null, arguments);
return fn.apply(null, args);
} else {
throw new Meteor.Error('error-too-many-requests', `Error, too many requests. Please slow down. You must wait ${ Math.ceil(rateLimitResult.timeToReset / 1000) } seconds before trying again.`, {
timeToReset: rateLimitResult.timeToReset,

@ -27,7 +27,7 @@ process.on('uncaughtException', Meteor.bindEnvironment((error) => {
}));
const originalMeteorDebug = Meteor._debug;
Meteor._debug = function() {
notify(...arguments);
return originalMeteorDebug(...arguments);
Meteor._debug = function(...args) {
notify(...args);
return originalMeteorDebug(...args);
};

@ -44,18 +44,18 @@ const traceConnection = (enable, filter, prefix, name, connection, userId) => {
};
const wrapMethods = function(name, originalHandler, methodsMap) {
methodsMap[name] = function() {
methodsMap[name] = function(...originalArgs) {
traceConnection(Log_Trace_Methods, Log_Trace_Methods_Filter, 'method', name, this.connection, this.userId);
const end = RocketChat.metrics.meteorMethods.startTimer({
method: name,
has_connection: this.connection != null,
has_user: this.userId != null,
});
const args = name === 'ufsWrite' ? Array.prototype.slice.call(arguments, 1) : arguments;
const args = name === 'ufsWrite' ? Array.prototype.slice.call(originalArgs, 1) : originalArgs;
logger.method(name, '-> userId:', Meteor.userId(), ', arguments: ', args);
this.unblock();
const result = originalHandler.apply(this, arguments);
const result = originalHandler.apply(this, originalArgs);
end();
return result;
};
@ -73,18 +73,18 @@ Meteor.methods = function(methodMap) {
const originalMeteorPublish = Meteor.publish;
Meteor.publish = function(name, func) {
return originalMeteorPublish(name, function() {
return originalMeteorPublish(name, function(...args) {
traceConnection(Log_Trace_Subscriptions, Log_Trace_Subscriptions_Filter, 'subscription', name, this.connection, this.userId);
logger.publish(name, '-> userId:', this.userId, ', arguments: ', arguments);
logger.publish(name, '-> userId:', this.userId, ', arguments: ', args);
const end = RocketChat.metrics.meteorSubscriptions.startTimer({ subscription: name });
const originalReady = this.ready;
this.ready = function() {
end();
return originalReady.apply(this, arguments);
return originalReady.apply(this, args);
};
return func.apply(this, arguments);
return func.apply(this, args);
});
};

@ -1,5 +1,5 @@
// Do not disclose if user exists when password is invalid
const _runLoginHandlers = Accounts._runLoginHandlers;
const { _runLoginHandlers } = Accounts;
Accounts._runLoginHandlers = function(methodInvocation, options) {
const result = _runLoginHandlers.call(Accounts, methodInvocation, options);

@ -75,7 +75,7 @@ RocketChat.processDirectEmail = function(email) {
message.msg = prevMessageLink + message.msg;
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(message.rid, user._id);
if (subscription && subscription.blocked || subscription.blocker) {
if (subscription && (subscription.blocked || subscription.blocker)) {
// room is blocked
return false;
}

@ -134,6 +134,7 @@ const sendNotification = ({
return true;
}
return false;
});
}
@ -184,7 +185,7 @@ function sendAllNotifications(message, room) {
}],
};
['audio', 'desktop', 'mobile', 'email'].map((kind) => {
['audio', 'desktop', 'mobile', 'email'].forEach((kind) => {
const notificationField = `${ kind === 'mobile' ? 'mobilePush' : kind }Notifications`;
const filter = { [notificationField]: 'all' };

@ -9,7 +9,7 @@ RocketChat.callbacks.add('beforeSaveMessage', function(message) {
if (!RocketChat.authz.hasPermission(message.u._id, 'mention-all') && !RocketChat.authz.hasPermission(message.u._id, 'mention-all', message.rid)) {
// Get the language of the user for the error notification.
const language = RocketChat.models.Users.findOneById(message.u._id).language;
const { language } = RocketChat.models.Users.findOneById(message.u._id);
const action = TAPi18n.__('Notify_all_in_this_room', {}, language);
// Add a notification to the chat, informing the user that this

@ -9,7 +9,7 @@ RocketChat.callbacks.add('beforeSaveMessage', function(message) {
if (!RocketChat.authz.hasPermission(message.u._id, 'mention-here') && !RocketChat.authz.hasPermission(message.u._id, 'mention-here', message.rid)) {
// Get the language of the user for the error notification.
const language = RocketChat.models.Users.findOneById(message.u._id).language;
const { language } = RocketChat.models.Users.findOneById(message.u._id);
const action = TAPi18n.__('Notify_active_in_this_room', {}, language);
// Add a notification to the chat, informing the user that this

@ -2,8 +2,8 @@ import _ from 'underscore';
import s from 'underscore.string';
class ModelRooms extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
this.tryEnsureIndex({ name: 1 }, { unique: 1, sparse: 1 });
this.tryEnsureIndex({ default: 1 });

@ -1,6 +1,6 @@
class ModelSettings extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
this.tryEnsureIndex({ blocked: 1 }, { sparse: 1 });
this.tryEnsureIndex({ hidden: 1 }, { sparse: 1 });

@ -1,6 +1,6 @@
class ModelSubscriptions extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
this.tryEnsureIndex({ rid: 1, 'u._id': 1 }, { unique: 1 });
this.tryEnsureIndex({ rid: 1, 'u.username': 1 });

@ -2,8 +2,8 @@ import _ from 'underscore';
import s from 'underscore.string';
class ModelUsers extends RocketChat.models._Base {
constructor() {
super(...arguments);
constructor(...args) {
super(...args);
this.tryEnsureIndex({ roles: 1 }, { sparse: 1 });
this.tryEnsureIndex({ name: 1 });

@ -33,98 +33,98 @@ class ModelsBase {
};
}
setUpdatedAt(/* record, checkQuery, query*/) {
return this._db.setUpdatedAt(...arguments);
setUpdatedAt(...args/* record, checkQuery, query*/) {
return this._db.setUpdatedAt(...args);
}
find() {
find(...args) {
try {
return this[this.origin].find(...arguments);
return this[this.origin].find(...args);
} catch (e) {
console.error('Exception on find', e, ...arguments);
console.error('Exception on find', e, ...args);
}
}
findOne() {
findOne(...args) {
try {
return this[this.origin].findOne(...arguments);
return this[this.origin].findOne(...args);
} catch (e) {
console.error('Exception on find', e, ...arguments);
console.error('Exception on find', e, ...args);
}
}
findOneById() {
findOneById(...args) {
try {
return this[this.origin].findOneById(...arguments);
return this[this.origin].findOneById(...args);
} catch (e) {
console.error('Exception on find', e, ...arguments);
console.error('Exception on find', e, ...args);
}
}
findOneByIds(ids, options) {
findOneByIds(ids, options, ...args) {
check(ids, [String]);
try {
return this[this.origin].findOneByIds(ids, options);
} catch (e) {
console.error('Exception on find', e, ...arguments);
console.error('Exception on find', e, [ids, options, ...args]);
}
}
insert(/* record*/) {
return this._db.insert(...arguments);
insert(...args/* record*/) {
return this._db.insert(...args);
}
update(/* query, update, options*/) {
return this._db.update(...arguments);
update(...args/* query, update, options*/) {
return this._db.update(...args);
}
upsert(/* query, update*/) {
return this._db.upsert(...arguments);
upsert(...args/* query, update*/) {
return this._db.upsert(...args);
}
remove(/* query*/) {
return this._db.remove(...arguments);
remove(...args/* query*/) {
return this._db.remove(...args);
}
insertOrUpsert() {
return this._db.insertOrUpsert(...arguments);
insertOrUpsert(...args) {
return this._db.insertOrUpsert(...args);
}
allow() {
return this._db.allow(...arguments);
allow(...args) {
return this._db.allow(...args);
}
deny() {
return this._db.deny(...arguments);
deny(...args) {
return this._db.deny(...args);
}
ensureIndex() {
return this._db.ensureIndex(...arguments);
ensureIndex(...args) {
return this._db.ensureIndex(...args);
}
dropIndex() {
return this._db.dropIndex(...arguments);
dropIndex(...args) {
return this._db.dropIndex(...args);
}
tryEnsureIndex() {
return this._db.tryEnsureIndex(...arguments);
tryEnsureIndex(...args) {
return this._db.tryEnsureIndex(...args);
}
tryDropIndex() {
return this._db.tryDropIndex(...arguments);
tryDropIndex(...args) {
return this._db.tryDropIndex(...args);
}
trashFind(/* query, options*/) {
return this._db.trashFind(...arguments);
trashFind(...args/* query, options*/) {
return this._db.trashFind(...args);
}
trashFindOneById(/* _id, options*/) {
return this._db.trashFindOneById(...arguments);
trashFindOneById(...args/* _id, options*/) {
return this._db.trashFindOneById(...args);
}
trashFindDeletedAfter(/* deletedAt, query, options*/) {
return this._db.trashFindDeletedAfter(...arguments);
trashFindDeletedAfter(...args/* deletedAt, query, options*/) {
return this._db.trashFindDeletedAfter(...args);
}
processQueryOptionsOnResult(result, options = {}) {
@ -219,6 +219,8 @@ class ModelsBase {
if (fieldsToGet.length > 0) {
return pickFields(record, fieldsToGet);
}
return null;
});
} else {
if (fieldsToRemove.length > 0) {

@ -87,16 +87,16 @@ class ModelsBaseDb extends EventEmitter {
};
const self = this;
this.model.insert = function() {
return self.insert(...arguments);
this.model.insert = function(...args) {
return self.insert(...args);
};
this.model.update = function() {
return self.update(...arguments);
this.model.update = function(...args) {
return self.update(...args);
};
this.model.remove = function() {
return self.remove(...arguments);
this.model.remove = function(...args) {
return self.remove(...args);
};
}
@ -110,14 +110,14 @@ class ModelsBaseDb extends EventEmitter {
}
}
find() {
this._doNotMixInclusionAndExclusionFields(arguments[1]);
return this.model.find(...arguments);
find(...args) {
this._doNotMixInclusionAndExclusionFields(args[1]);
return this.model.find(...args);
}
findOne() {
this._doNotMixInclusionAndExclusionFields(arguments[1]);
return this.model.findOne(...arguments);
findOne(...args) {
this._doNotMixInclusionAndExclusionFields(args[1]);
return this.model.findOne(...args);
}
findOneById(_id, options) {
@ -198,10 +198,10 @@ class ModelsBaseDb extends EventEmitter {
}
}
insert(record) {
insert(record, ...args) {
this.setUpdatedAt(record);
const result = this.originals.insert(...arguments);
const result = this.originals.insert(record, ...args);
record._id = result;
@ -307,7 +307,7 @@ class ModelsBaseDb extends EventEmitter {
insertOrUpsert(...args) {
if (args[0] && args[0]._id) {
const _id = args[0]._id;
const { _id } = args[0];
delete args[0]._id;
args.unshift({
_id,
@ -320,35 +320,35 @@ class ModelsBaseDb extends EventEmitter {
}
}
allow() {
return this.model.allow(...arguments);
allow(...args) {
return this.model.allow(...args);
}
deny() {
return this.model.deny(...arguments);
deny(...args) {
return this.model.deny(...args);
}
ensureIndex() {
return this.model._ensureIndex(...arguments);
ensureIndex(...args) {
return this.model._ensureIndex(...args);
}
dropIndex() {
return this.model._dropIndex(...arguments);
dropIndex(...args) {
return this.model._dropIndex(...args);
}
tryEnsureIndex() {
tryEnsureIndex(...args) {
try {
return this.ensureIndex(...arguments);
return this.ensureIndex(...args);
} catch (e) {
console.error('Error creating index:', this.name, '->', ...arguments, e);
console.error('Error creating index:', this.name, '->', ...args, e);
}
}
tryDropIndex() {
tryDropIndex(...args) {
try {
return this.dropIndex(...arguments);
return this.dropIndex(...args);
} catch (e) {
console.error('Error dropping index:', this.name, '->', ...arguments, e);
console.error('Error dropping index:', this.name, '->', ...args, e);
}
}

@ -1,6 +1,5 @@
import _ from 'underscore';
import { IMAPIntercepter } from '../lib/interceptDirectReplyEmails.js';
import { POP3Helper } from '../lib/interceptDirectReplyEmails.js';
import { IMAPIntercepter, POP3Helper } from '../lib/interceptDirectReplyEmails.js';
const startEmailIntercepter = _.debounce(Meteor.bindEnvironment(function() {
console.log('Starting Email Intercepter...');

@ -29,6 +29,6 @@ this.CustomFields = (function() {
return {
init,
setCustomField
setCustomField,
};
}());

@ -1,36 +1,36 @@
/* globals, fileUpload, Livechat, Handlebars */
/* exported LivechatFileUpload */
/* globals fileUpload, Livechat, Handlebars, showError, sendFileUpload */
/* exported LivechatFileUpload, fileUpload, sendFileUpload */
import visitor from '../../imports/client/visitor';
import swal from 'sweetalert2';
const handleRequestError = response => {
const handleRequestError = (response) => {
if (!response.success) {
let reason = t('FileUpload_Error');
switch (response.reason) {
case 'error-type-not-allowed':
reason = t('FileUpload_MediaType_NotAccepted');
reason = t('FileUpload_MediaType_NotAccepted');
break;
case 'error-size-not-allowed':
reason = t('File_exceeds_allowed_size_of_bytes', {size: response.sizeAllowed});
reason = t('File_exceeds_allowed_size_of_bytes', { size: response.sizeAllowed });
}
swal({
text: reason,
type: 'error',
timer: 4000
timer: 4000,
});
}
}
};
function sendFileRequest(file, roomId, token) {
const url = `${ Meteor.absoluteUrl() }api/v1/livechat/upload/${ roomId }`;
const form = new FormData();
form.append('file', file)
form.append('file', file);
const request = new XMLHttpRequest();
request.open("POST", url);
request.open('POST', url);
request.responseType = 'json';
request.setRequestHeader("X-Visitor-Token", token);
request.setRequestHeader('X-Visitor-Token', token);
request.onload = () => {
if (request.status !== 200) {
@ -47,7 +47,7 @@ function sendFileRequest(file, roomId, token) {
function readAsDataURL(file, callback) {
const reader = new FileReader();
reader.onload = ev => callback(ev.target.result, file);
reader.onload = (ev) => callback(ev.target.result, file);
return reader.readAsDataURL(file);
}
@ -60,7 +60,7 @@ function getUploadPreview(file, callback) {
callback(file, null);
} else if ((file.file.type.indexOf('audio') > -1) || (file.file.type.indexOf('video') > -1) || (file.file.type.indexOf('image') > -1)) {
file.type = file.file.type.split('/')[0];
return readAsDataURL(file.file, content => callback(file, content));
return readAsDataURL(file.file, (content) => callback(file, content));
} else {
return callback(file, null);
}
@ -80,7 +80,7 @@ function formatBytes(bytes, decimals) {
'MB',
'GB',
'TB',
'PB'
'PB',
];
const i = Math.floor(Math.log(bytes) / Math.log(k));
@ -106,67 +106,64 @@ function sendFileMessage(file, roomId) {
});
}
sendFileUpload = file => {
return getUploadPreview(file, function(file, preview) {
let html = '';
if (file.type === 'audio') {
html = `<div class='upload-preview'><audio style="width: 100%;" controls="controls"><source src="${ preview }" type="audio/wav">Your browser does not support the audio element.</audio></div>`;
} else if (file.type === 'video') {
html = `<div class='upload-preview'><video style="width: 100%;" controls="controls"><source src="${ preview }" type="video/webm">Your browser does not support the video element.</video></div>`;
} else if (file.type === 'image') {
html = `<div class='upload-preview'><div class='upload-preview-file' style='background-image: url(${ preview })'></div></div>`;
} else {
const fileSize = formatBytes(file.file.size);
html = `<div class='upload-preview'><div>${ Handlebars._escape(file.name) } - ${ fileSize }</div></div>`;
sendFileUpload = (file) => getUploadPreview(file, function(file, preview) {
let html = '';
if (file.type === 'audio') {
html = `<div class='upload-preview'><audio style="width: 100%;" controls="controls"><source src="${ preview }" type="audio/wav">Your browser does not support the audio element.</audio></div>`;
} else if (file.type === 'video') {
html = `<div class='upload-preview'><video style="width: 100%;" controls="controls"><source src="${ preview }" type="video/webm">Your browser does not support the video element.</video></div>`;
} else if (file.type === 'image') {
html = `<div class='upload-preview'><div class='upload-preview-file' style='background-image: url(${ preview })'></div></div>`;
} else {
const fileSize = formatBytes(file.file.size);
html = `<div class='upload-preview'><div>${ Handlebars._escape(file.name) } - ${ fileSize }</div></div>`;
}
swal({
title: t('Upload_file_question'),
html,
showCancelButton: true,
cancelButtonText: t('No'),
confirmButtonText: t('Yes'),
}).then((result) => {
if (!result.value) {
return;
}
swal({
title: t('Upload_file_question'),
html,
showCancelButton: true,
cancelButtonText: t('No'),
confirmButtonText: t('Yes')
}).then((result) => {
if (!result.value) {
return;
}
const roomId = visitor.getRoom(true);
const roomId = visitor.getRoom(true);
if (visitor.getId()) {
return sendFileMessage(file.file, roomId);
}
if (visitor.getId()) {
return sendFileMessage(file.file, roomId);
}
const guest = {
token: visitor.getToken(),
};
const guest = {
token: visitor.getToken()
};
if (Livechat.department) {
guest.department = Livechat.department;
}
if (Livechat.department) {
guest.department = Livechat.department;
Meteor.call('livechat:registerGuest', guest, (error, result) => {
if (error) {
return showError(error.reason);
}
Meteor.call('livechat:registerGuest', guest, (error, result) => {
if (error) {
return showError(error.reason);
}
visitor.setId(result.userId);
sendFileMessage(file.file, roomId);
});
visitor.setId(result.userId);
sendFileMessage(file.file, roomId);
});
});
}
});
fileUpload = file => {
fileUpload = (file) => {
if (file.size === 0) {
swal({
title: t('FileUpload_File_Empty'),
text: reason,
text: '',
type: 'error',
timer: 1000,
showConfirmButton: false
showConfirmButton: false,
});
return;

@ -48,11 +48,11 @@ LivechatVideoCall = new (class LivechatVideoCall {
start(domain, room) {
Meteor.defer(() => {
const interfaceConfig = {};
interfaceConfig['TOOLBAR_BUTTONS'] = '[""]';
interfaceConfig['APP_NAME'] = '"Livechat"';
interfaceConfig['INITIAL_TOOLBAR_TIMEOUT'] = '5000';
interfaceConfig['MIN_WIDTH'] = '300';
interfaceConfig['FILM_STRIP_MAX_HEIGHT'] = '50';
interfaceConfig.TOOLBAR_BUTTONS = '[""]';
interfaceConfig.APP_NAME = '"Livechat"';
interfaceConfig.INITIAL_TOOLBAR_TIMEOUT = '5000';
interfaceConfig.MIN_WIDTH = '300';
interfaceConfig.FILM_STRIP_MAX_HEIGHT = '50';
this.api = new JitsiMeetExternalAPI(domain, room, $('.video-call').width(), $('.video-call').height(), $('.video-call .container').get(0), {}, interfaceConfig);

@ -2,5 +2,5 @@ import Autolinker from 'autolinker';
this.livechatAutolinker = new Autolinker({
twitter: false,
phone: false
phone: false,
});

@ -18,7 +18,7 @@ this.ChatMessages = class ChatMessages {
resize() {
const dif = 60 + $('.messages-container').find('footer').outerHeight();
return $('.messages-box').css({
height: `calc(100% - ${ dif }px)`
height: `calc(100% - ${ dif }px)`,
});
}
@ -108,7 +108,7 @@ this.ChatMessages = class ChatMessages {
_id: Random.id(),
rid,
msg,
token: visitor.getToken()
token: visitor.getToken(),
};
MsgTyping.stop(rid);
@ -117,7 +117,7 @@ this.ChatMessages = class ChatMessages {
if (currentAgent) {
agent = {
agentId: currentAgent._id,
username: currentAgent.username
username: currentAgent.username,
};
}
@ -142,7 +142,7 @@ this.ChatMessages = class ChatMessages {
if (!visitor.getId()) {
const guest = {
token: visitor.getToken()
token: visitor.getToken(),
};
if (Livechat.department) {
@ -202,7 +202,7 @@ this.ChatMessages = class ChatMessages {
$('.input-message').autogrow({
postGrowCallback: () => {
this.resize();
}
},
});
}
}
@ -226,7 +226,7 @@ this.ChatMessages = class ChatMessages {
34, // Page Down
35, // Page Up
144, // Num Lock
145 // Scroll Lock
145, // Scroll Lock
];
for (i = 35; i <= 40; i++) { keyCodes.push(i); } // Home, End, Arrow Keys
for (i = 112; i <= 123; i++) { keyCodes.push(i); } // F1 - F12

@ -28,7 +28,7 @@ this.Commands = {
inputPlaceholder: t('Type_your_email'),
showCancelButton: true,
cancelButtonText: t('no'),
confirmButtonText: t('yes')
confirmButtonText: t('yes'),
}).then((result) => {
if ((typeof result.value === 'boolean') && !result.value) {
return true;
@ -47,7 +47,7 @@ this.Commands = {
title: t('transcript_sent'),
type: 'success',
timer: 1000,
showConfirmButton: false
showConfirmButton: false,
});
});
});
@ -56,5 +56,5 @@ this.Commands = {
connected() {
Livechat.connecting = false;
}
},
};

@ -1,3 +1,3 @@
this.showError = msg => {
this.showError = (msg) => {
$('.error').addClass('show').find('span').html(msg);
};

@ -1,12 +1,12 @@
import visitor from '../../../imports/client/visitor';
this.Notifications = new class {
constructor() {
constructor(...args) {
this.logged = visitor.getId() !== null;
this.loginCb = [];
Tracker.autorun(() => {
if (visitor.getId() !== null && this.logged === false) {
this.loginCb.forEach(cb => cb());
this.loginCb.forEach((cb) => cb());
}
return this.logged = visitor.getId() !== null;
});
@ -18,10 +18,10 @@ this.Notifications = new class {
this.streamUser = new Meteor.Streamer('notify-user');
if (this.debug === true) {
this.onAll(function() {
return console.log('RocketChat.Notifications: onAll', arguments);
return console.log('RocketChat.Notifications: onAll', args);
});
this.onUser(function() {
return console.log('RocketChat.Notifications: onAll', arguments);
return console.log('RocketChat.Notifications: onAll', args);
});
}
}
@ -34,14 +34,14 @@ this.Notifications = new class {
}
notifyRoom(room, eventName, ...args) {
if (this.debug === true) {
console.log('RocketChat.Notifications: notifyRoom', arguments);
console.log('RocketChat.Notifications: notifyRoom', room, eventName, ...args);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoom.emit.apply(this.streamRoom, args);
}
notifyUser(userId, eventName, ...args) {
if (this.debug === true) {
console.log('RocketChat.Notifications: notifyUser', arguments);
console.log('RocketChat.Notifications: notifyUser', userId, eventName, ...args);
}
args.unshift(`${ userId }/${ eventName }`);
return this.streamUser.emit.apply(this.streamUser, args);
@ -50,14 +50,12 @@ this.Notifications = new class {
return this.streamAll.on(eventName, { token: visitor.getToken() }, callback);
}
onLogged(eventName, callback) {
return this.onLogin(() => {
return this.streamLogged.on(eventName, { token: visitor.getToken() }, callback);
});
return this.onLogin(() => this.streamLogged.on(eventName, { token: visitor.getToken() }, callback));
}
onRoom(room, eventName, callback) {
if (this.debug === true) {
this.streamRoom.on(room, { token: visitor.getToken() }, function() {
return console.log(`RocketChat.Notifications: onRoom ${ room }`, arguments);
return console.log(`RocketChat.Notifications: onRoom ${ room }`, room, eventName, callback);
});
}
return this.streamRoom.on(`${ room }/${ eventName }`, { token: visitor.getToken() }, callback);

@ -16,7 +16,7 @@ export const RoomHistoryManager = new class {
isLoading: new ReactiveVar(false),
unreadNotLoaded: new ReactiveVar(0),
firstUnread: new ReactiveVar,
loaded: undefined
loaded: undefined,
};
}
@ -32,9 +32,9 @@ export const RoomHistoryManager = new class {
room.isLoading.set(true);
//$('.messages-box .wrapper').data('previous-height', $('.messages-box .wrapper').get(0)?.scrollHeight - $('.messages-box .wrapper').get(0)?.scrollTop)
// $('.messages-box .wrapper').data('previous-height', $('.messages-box .wrapper').get(0)?.scrollHeight - $('.messages-box .wrapper').get(0)?.scrollTop)
// ScrollListener.setLoader true
const lastMessage = ChatMessage.findOne({rid}, { fields: { ts: 1 }, sort: { ts: 1 }});
const lastMessage = ChatMessage.findOne({ rid }, { fields: { ts: 1 }, sort: { ts: 1 } });
// lastMessage ?= ChatMessage.findOne({rid: rid}, {sort: {ts: 1}})
let ts;
@ -52,7 +52,7 @@ export const RoomHistoryManager = new class {
if (result && result.messages) {
result.messages.forEach((item) => {
if (item.t !== 'command') {
ChatMessage.upsert({_id: item._id}, item);
ChatMessage.upsert({ _id: item._id }, item);
}
});
room.isLoading.set(false);
@ -76,16 +76,16 @@ export const RoomHistoryManager = new class {
room.isLoading.set(true);
const lastMessage = ChatMessage.findOne({rid}, {sort: {ts: -1}});
const lastMessage = ChatMessage.findOne({ rid }, { sort: { ts: -1 } });
let typeName = undefined;
const subscription = ChatSubscription.findOne({rid});
const subscription = ChatSubscription.findOne({ rid });
if (subscription != null) {
// const { ls } = subscription;
typeName = subscription.t + subscription.name;
} else {
const curRoomDoc = ChatRoom.findOne({_id: rid});
const curRoomDoc = ChatRoom.findOne({ _id: rid });
typeName = (curRoomDoc != null ? curRoomDoc.t : undefined) + (curRoomDoc != null ? curRoomDoc.name : undefined);
}
@ -96,11 +96,11 @@ export const RoomHistoryManager = new class {
for (const item of Array.from((result != null ? result.messages : undefined) || [])) {
if (item.t !== 'command') {
const roles = [
(item.u && item.u._id && UserRoles.findOne(item.u._id, { fields: { roles: 1 }})) || {},
(item.u && item.u._id && RoomRoles.findOne({rid: item.rid, 'u._id': item.u._id})) || {}
].map(e => e.roles);
(item.u && item.u._id && UserRoles.findOne(item.u._id, { fields: { roles: 1 } })) || {},
(item.u && item.u._id && RoomRoles.findOne({ rid: item.rid, 'u._id': item.u._id })) || {},
].map((e) => e.roles);
item.roles = _.union.apply(_.union, roles);
ChatMessage.upsert({_id: item._id}, item);
ChatMessage.upsert({ _id: item._id }, item);
}
}
@ -128,9 +128,9 @@ export const RoomHistoryManager = new class {
if (ChatMessage.findOne(message._id)) {
const wrapper = $('.messages-box .wrapper');
const msgElement = $(`#${ message._id }`, wrapper);
const pos = (wrapper.scrollTop() + msgElement.offset().top) - (wrapper.height()/2);
const pos = (wrapper.scrollTop() + msgElement.offset().top) - (wrapper.height() / 2);
wrapper.animate({
scrollTop: pos
scrollTop: pos,
}, 500);
msgElement.addClass('highlight');
@ -147,12 +147,12 @@ export const RoomHistoryManager = new class {
let typeName = undefined;
const subscription = ChatSubscription.findOne({rid: message.rid});
const subscription = ChatSubscription.findOne({ rid: message.rid });
if (subscription) {
// const { ls } = subscription;
typeName = subscription.t + subscription.name;
} else {
const curRoomDoc = ChatRoom.findOne({_id: message.rid});
const curRoomDoc = ChatRoom.findOne({ _id: message.rid });
typeName = (curRoomDoc != null ? curRoomDoc.t : undefined) + (curRoomDoc != null ? curRoomDoc.name : undefined);
}
@ -160,11 +160,11 @@ export const RoomHistoryManager = new class {
for (const item of Array.from((result != null ? result.messages : undefined) || [])) {
if (item.t !== 'command') {
const roles = [
(item.u && item.u._id && UserRoles.findOne(item.u._id, { fields: { roles: 1 }})) || {},
(item.u && item.u._id && RoomRoles.findOne({rid: item.rid, 'u._id': item.u._id})) || {}
].map(e => e.roles);
(item.u && item.u._id && UserRoles.findOne(item.u._id, { fields: { roles: 1 } })) || {},
(item.u && item.u._id && RoomRoles.findOne({ rid: item.rid, 'u._id': item.u._id })) || {},
].map((e) => e.roles);
item.roles = _.union.apply(_.union, roles);
ChatMessage.upsert({_id: item._id}, item);
ChatMessage.upsert({ _id: item._id }, item);
}
}
@ -173,9 +173,9 @@ export const RoomHistoryManager = new class {
RoomManager.updateMentionsMarksOfRoom(typeName);
const wrapper = $('.messages-box .wrapper');
const msgElement = $(`#${ message._id }`, wrapper);
const pos = (wrapper.scrollTop() + msgElement.offset().top) - (wrapper.height()/2);
const pos = (wrapper.scrollTop() + msgElement.offset().top) - (wrapper.height() / 2);
wrapper.animate({
scrollTop: pos
scrollTop: pos,
}, 500);
msgElement.addClass('highlight');

@ -1,4 +1,4 @@
this.getAvatarUrlFromUsername = username => {
this.getAvatarUrlFromUsername = (username) => {
const key = `avatar_random_${ username }`;
const random = Session.keys[key] || 0;
if (!username) {
@ -8,7 +8,7 @@ this.getAvatarUrlFromUsername = username => {
return `${ Meteor.absoluteUrl() }avatar/${ username }.jpg?_dc=${ random }`;
};
this.updateAvatarOfUsername = username => {
this.updateAvatarOfUsername = (username) => {
const key = `avatar_random_${ username }`;
Session.set(key, Math.round(Math.random() * 1000));

@ -65,7 +65,7 @@ const api = {
visitor.setToken(result.visitor.token);
}
});
}
},
};
window.addEventListener('message', function(msg) {

@ -17,7 +17,7 @@ export const MsgTyping = (function() {
return;
}
usersTyping[room] = { users: {} };
return Notifications.onRoom(room, 'typing', function(username, typing, extraData) {
return Notifications.onRoom(room, 'typing', function(username, typing/* , extraData*/) {
const user = Meteor.user();
if (username === (user && user.username)) {
return;

@ -2,7 +2,7 @@ this.parentCall = (method, args = []) => {
const data = {
src: 'rocketchat',
fn: method,
args
args,
};
window.parent.postMessage(data, '*');

@ -6,7 +6,7 @@ this.t = function(key, ...replaces) {
} else {
return TAPi18n.__(key, {
postProcess: 'sprintf',
sprintf: replaces
sprintf: replaces,
});
}
};
@ -17,12 +17,12 @@ this.tr = function(key, options, ...replaces) {
} else {
return TAPi18n.__(key, options, {
postProcess: 'sprintf',
sprintf: replaces
sprintf: replaces,
});
}
};
this.isRtl = (lang) => {
const language = lang ? lang : localStorage.getItem('userLanguage') ? localStorage.getItem('userLanguage') : 'en-US';
const language = lang || localStorage.getItem('userLanguage') || 'en-US';
return ['ar', 'dv', 'fa', 'he', 'ku', 'ps', 'sd', 'ug', 'ur', 'yi'].includes(language.split('-').shift().toLowerCase());
};

@ -17,21 +17,21 @@ function getAgent(triggerAction) {
Meteor.call('livechat:getNextAgent', {
token: visitor.getToken(),
department: Livechat.department
department: Livechat.department,
}, (error, result) => {
if (error) {
return reject(error);
}
localStorage.setItem('triggerAgent', JSON.stringify({
agent: result,
ts: Date.now()
ts: Date.now(),
}));
resolve(result);
});
} else if (params.sender === 'custom') {
resolve({
username: params.name
username: params.name,
});
} else {
reject('Unknown sender');
@ -66,7 +66,7 @@ this.Triggers = (function() {
ChatMessage.insert({
msg: action.params.msg,
rid: roomId,
u: agent
u: agent,
});
if (agent._id) {
@ -137,6 +137,6 @@ this.Triggers = (function() {
processRequest,
setTriggers,
setDisabled,
setEnabled
setEnabled,
};
}());

@ -14,7 +14,7 @@ Meteor.methods({
message.u = {
_id: visitor.getId(),
username: user && user.username || 'visitor'
username: (user && user.username) || 'visitor',
};
message.temp = true;
@ -23,5 +23,5 @@ Meteor.methods({
ChatMessage.insert(message);
}
}
},
});

@ -5,9 +5,9 @@ BlazeLayout.setRoot('body');
FlowRouter.route('/livechat', {
name: 'index',
triggersEnter: [
() => visitor.register()
() => visitor.register(),
],
action() {
BlazeLayout.render('main', { center: 'livechatWindow' });
}
},
});

@ -4,7 +4,7 @@ Meteor.startup(() => {
if (!localStorage.getItem('rocketChatLivechat')) {
localStorage.setItem('rocketChatLivechat', Random.id());
} else {
Tracker.autorun(c => {
Tracker.autorun((c) => {
if (!visitor.getId() && visitor.getToken()) {
Meteor.call('livechat:loginByToken', visitor.getToken(), (err, result) => {
if (result && result._id) {
@ -20,12 +20,12 @@ Meteor.startup(() => {
Meteor.startup(() => {
let connected = false;
Tracker.autorun(function() {
var connectionStatus = Meteor.status();
const connectionStatus = Meteor.status();
if (visitor.getRoom() && visitor.getToken() && connectionStatus.connected && !connected) {
connected = connectionStatus.connected;
document.cookie = `rc_rid=${ visitor.getRoom() }; path=/`;
document.cookie = `rc_token=${ visitor.getToken() }; path=/`;
document.cookie = `rc_room_type=l; path=/`;
document.cookie = 'rc_room_type=l; path=/';
visitor.setConnected();
}
});

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

Loading…
Cancel
Save