Add new eslint rules (#11800)

pull/10565/head^2
Diego Sampaio 7 years ago committed by GitHub
parent 88cb478501
commit db6aa025d0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 15
      .eslintrc
  2. 60
      .scripts/logs.js
  3. 48
      .scripts/md.js
  4. 76
      .scripts/set-version.js
  5. 16
      .scripts/start.js
  6. 4
      client/helpers/escapeCssUrl.js
  7. 4
      client/helpers/not.js
  8. 2
      client/lib/handleError.js
  9. 6
      client/methods/deleteMessage.js
  10. 8
      client/methods/hideRoom.js
  11. 8
      client/methods/openRoom.js
  12. 2
      client/methods/setUserActiveStatus.js
  13. 8
      client/methods/toggleFavorite.js
  14. 10
      client/methods/updateMessage.js
  15. 26
      client/notifications/UsersNameChanged.js
  16. 2
      client/notifications/notification.js
  17. 28
      client/routes/adminRouter.js
  18. 2
      client/routes/roomRoute.js
  19. 40
      client/routes/router.js
  20. 8
      client/startup/i18n.js
  21. 2
      client/startup/roomObserve.js
  22. 4
      client/startup/startup.js
  23. 6
      client/startup/unread.js
  24. 2
      client/startup/userSetUtcOffset.js
  25. 2
      client/startup/usersObserve.js
  26. 2
      imports/message-read-receipt/client/main.js
  27. 4
      imports/message-read-receipt/client/message.js
  28. 2
      imports/message-read-receipt/client/readReceipts.js
  29. 6
      imports/message-read-receipt/client/room.js
  30. 2
      imports/message-read-receipt/server/api/methods/getReadReceipts.js
  31. 4
      imports/message-read-receipt/server/dbIndexes.js
  32. 22
      imports/message-read-receipt/server/lib/ReadReceipt.js
  33. 4
      imports/message-read-receipt/server/models/ReadReceipts.js
  34. 4
      imports/message-read-receipt/server/settings.js
  35. 4
      packages/chatpal-search/client/route.js
  36. 14
      packages/chatpal-search/client/template/admin.js
  37. 16
      packages/chatpal-search/client/template/result.js
  38. 12
      packages/chatpal-search/package.js
  39. 52
      packages/chatpal-search/server/provider/index.js
  40. 96
      packages/chatpal-search/server/provider/provider.js
  41. 4
      packages/chatpal-search/server/utils/utils.js
  42. 8
      packages/meteor-accounts-saml/package.js
  43. 16
      packages/meteor-accounts-saml/saml_client.js
  44. 60
      packages/meteor-accounts-saml/saml_rocketchat.js
  45. 84
      packages/meteor-accounts-saml/saml_server.js
  46. 56
      packages/meteor-accounts-saml/saml_utils.js
  47. 52
      packages/meteor-autocomplete/client/autocomplete-client.js
  48. 10
      packages/meteor-autocomplete/client/templates.js
  49. 6
      packages/meteor-autocomplete/package.js
  50. 14
      packages/rocketchat-2fa/client/TOTPPassword.js
  51. 14
      packages/rocketchat-2fa/client/accountSecurity.js
  52. 4
      packages/rocketchat-2fa/package.js
  53. 8
      packages/rocketchat-2fa/server/lib/totp.js
  54. 2
      packages/rocketchat-2fa/server/loginHandler.js
  55. 4
      packages/rocketchat-2fa/server/methods/checkCodesRemaining.js
  56. 4
      packages/rocketchat-2fa/server/methods/disable.js
  57. 4
      packages/rocketchat-2fa/server/methods/enable.js
  58. 4
      packages/rocketchat-2fa/server/methods/regenerateCodes.js
  59. 4
      packages/rocketchat-2fa/server/methods/validateTempToken.js
  60. 30
      packages/rocketchat-2fa/server/models/users.js
  61. 6
      packages/rocketchat-2fa/server/startup/settings.js
  62. 6
      packages/rocketchat-accounts/package.js
  63. 10
      packages/rocketchat-accounts/server/config.js
  64. 2
      packages/rocketchat-accounts/server/index.js
  65. 6
      packages/rocketchat-action-links/both/lib/actionLinks.js
  66. 4
      packages/rocketchat-action-links/client/init.js
  67. 2
      packages/rocketchat-action-links/client/lib/actionLinks.js
  68. 2
      packages/rocketchat-action-links/package.js
  69. 4
      packages/rocketchat-action-links/server/actionLinkHandler.js
  70. 4
      packages/rocketchat-analytics/client/loadScript.js
  71. 12
      packages/rocketchat-analytics/client/trackEvents.js
  72. 12
      packages/rocketchat-analytics/package.js
  73. 28
      packages/rocketchat-analytics/server/settings.js
  74. 10
      packages/rocketchat-api/package.js
  75. 102
      packages/rocketchat-api/server/api.js
  76. 6
      packages/rocketchat-api/server/default/info.js
  77. 2
      packages/rocketchat-api/server/helpers/deprecationWarning.js
  78. 4
      packages/rocketchat-api/server/helpers/getLoggedInUser.js
  79. 2
      packages/rocketchat-api/server/helpers/getPaginationItems.js
  80. 2
      packages/rocketchat-api/server/helpers/getUserFromParams.js
  81. 6
      packages/rocketchat-api/server/helpers/getUserInfo.js
  82. 2
      packages/rocketchat-api/server/helpers/insertUserObject.js
  83. 2
      packages/rocketchat-api/server/helpers/parseJsonQuery.js
  84. 190
      packages/rocketchat-api/server/v1/channels.js
  85. 64
      packages/rocketchat-api/server/v1/chat.js
  86. 14
      packages/rocketchat-api/server/v1/commands.js
  87. 2
      packages/rocketchat-api/server/v1/emoji-custom.js
  88. 146
      packages/rocketchat-api/server/v1/groups.js
  89. 66
      packages/rocketchat-api/server/v1/im.js
  90. 24
      packages/rocketchat-api/server/v1/integrations.js
  91. 24
      packages/rocketchat-api/server/v1/misc.js
  92. 16
      packages/rocketchat-api/server/v1/permissions.js
  93. 10
      packages/rocketchat-api/server/v1/push.js
  94. 2
      packages/rocketchat-api/server/v1/roles.js
  95. 18
      packages/rocketchat-api/server/v1/rooms.js
  96. 32
      packages/rocketchat-api/server/v1/settings.js
  97. 10
      packages/rocketchat-api/server/v1/stats.js
  98. 14
      packages/rocketchat-api/server/v1/subscriptions.js
  99. 90
      packages/rocketchat-api/server/v1/users.js
  100. 4
      packages/rocketchat-apps/client/admin/appInstall.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -54,6 +54,19 @@
}],
"no-void": 2,
"no-var": 2,
"no-multiple-empty-lines": [2, { "max": 2 }],
"arrow-parens": [2, "always"],
"quote-props": [2, "as-needed"],
"no-array-constructor": 2,
"arrow-spacing": 2,
"arrow-body-style": [2, "as-needed"],
"no-confusing-arrow": [2, { "allowParens": true }],
"dot-notation": 2,
"no-unneeded-ternary": 2,
"spaced-comment": 2,
"space-infix-ops": 2,
"array-bracket-spacing": [2, "never"],
"object-curly-spacing": [2, "always"],
"one-var": [2, "never"],
"no-lonely-if": 2,
"no-trailing-spaces": 2,
@ -63,7 +76,7 @@
"space-before-blocks": [2, "always"],
"indent": [2, "tab", {"SwitchCase": 1}],
"eol-last": [2, "always"],
"comma-dangle": [2, "never"],
"comma-dangle": [2, "always-multiline"],
"keyword-spacing": 2,
"block-spacing": 2,
"brace-style": [2, "1tbs", { "allowSingleLine": true }],

@ -22,7 +22,7 @@ let historyData = (() => {
octokit.authenticate({
type: 'token',
token: process.env.GITHUB_TOKEN
token: process.env.GITHUB_TOKEN,
});
const owner = 'RocketChat';
const repo = 'Rocket.Chat';
@ -31,8 +31,8 @@ function promiseRetryRateLimit(promiseFn, retryWait = 60000) {
return new Promise((resolve, reject) => {
function exec() {
promiseFn()
.then(data => resolve(data))
.catch(error => {
.then((data) => resolve(data))
.catch((error) => {
if (error.headers['x-ratelimit-remaining'] === '0') {
let reset = error.headers['x-ratelimit-reset'];
if (reset) {
@ -56,13 +56,13 @@ function getPRInfo(number, commit) {
process.exit(1);
}
return promiseRetryRateLimit(() => octokit.pullRequests.get({owner, repo, number}))
return promiseRetryRateLimit(() => octokit.pullRequests.get({ owner, repo, number }))
.catch(onError)
.then(pr => {
.then((pr) => {
const info = {
pr: number,
title: pr.data.title,
userLogin: pr.data.user.login
userLogin: pr.data.user.login,
};
// data.author_association: 'CONTRIBUTOR',
@ -70,10 +70,10 @@ function getPRInfo(number, commit) {
info.milestone = pr.data.milestone.title;
}
return promiseRetryRateLimit(() => octokit.pullRequests.getCommits({owner, repo, number}))
return promiseRetryRateLimit(() => octokit.pullRequests.getCommits({ owner, repo, number }))
.catch(onError)
.then(commits => {
info.contributors = _.unique(_.flatten(commits.data.map(i => {
.then((commits) => {
info.contributors = _.unique(_.flatten(commits.data.map((i) => {
if (!i.author || !i.committer) {
return;
}
@ -94,7 +94,7 @@ function getPRNumeberFromMessage(message, item) {
const number = match[2] || match[4];
if (!/^\d+$/.test(number)) {
console.error('Invalid number', {number, message});
console.error('Invalid number', { number, message });
process.exit(1);
}
@ -108,17 +108,17 @@ function getPullRequests(from, to) {
date: '%ai',
message: '%s',
author_name: '%aN',
author_email: '%ae'
author_email: '%ae',
};
return git.log(logParams).then((log) => {
const items = log.all
.filter(item => /^(\*\s)[0-9a-z]+$/.test(item.hash))
.map(item => {
.filter((item) => /^(\*\s)[0-9a-z]+$/.test(item.hash))
.map((item) => {
item.hash = item.hash.replace(/^(\*\s)/, '');
return item;
})
.filter(item => commitRegex.test(item.message));
.filter((item) => commitRegex.test(item.message));
const data = [];
@ -126,7 +126,7 @@ function getPullRequests(from, to) {
const bar = new ProgressBar(' [:bar] :current/:total :percent :etas', {
total: items.length,
incomplete: ' ',
width: 20
width: 20,
});
function process() {
@ -137,18 +137,16 @@ function getPullRequests(from, to) {
const partItems = items.splice(0, 10);
bar.tick(partItems.length);
const promises = partItems.map(item => {
return getPRInfo(getPRNumeberFromMessage(item.message, item), item);
});
const promises = partItems.map((item) => getPRInfo(getPRNumeberFromMessage(item.message, item), item));
return Promise.all(promises).then(result => {
return Promise.all(promises).then((result) => {
data.push(..._.compact(result));
if (items.length) {
setTimeout(process, 100);
} else {
resolve(data);
}
}).catch(error => reject(error));
}).catch((error) => reject(error));
}
process();
@ -158,7 +156,7 @@ function getPullRequests(from, to) {
function getTags() {
return git.tags().then((tags) => {
tags = tags.all.filter(tag => /^\d+\.\d+\.\d+(-rc\.\d+)?$/.test(tag));
tags = tags.all.filter((tag) => /^\d+\.\d+\.\d+(-rc\.\d+)?$/.test(tag));
tags = tags.sort((a, b) => {
if (semver.gt(a, b)) {
@ -173,13 +171,11 @@ function getTags() {
tags.push('HEAD');
return tags
.map((item, index) => {
return {
tag: item,
before: index ? tags[--index] : null
};
})
.filter(item => item.tag === 'HEAD' || semver.gte(item.tag, minTag))
.map((item, index) => ({
tag: item,
before: index ? tags[--index] : null,
}))
.filter((item) => item.tag === 'HEAD' || semver.gte(item.tag, minTag))
.reduce((value, item) => {
value[item.tag] = item;
return value;
@ -188,14 +184,14 @@ function getTags() {
}
function getMissingTags() {
return getTags().then(tags => {
return getTags().then((tags) => {
const missingTags = _.difference(Object.keys(tags), Object.keys(historyData));
missingTags.push('HEAD');
return _.pick(tags, missingTags);
});
}
getMissingTags().then(missingTags => {
getMissingTags().then((missingTags) => {
console.log('Missing tags:');
console.log(JSON.stringify(Object.keys(missingTags), null, 2));
missingTags = Object.values(missingTags);
@ -209,10 +205,10 @@ getMissingTags().then(missingTags => {
const from = item.before;
const to = item.tag;
console.log('Fetching data for tag:', to, `(from ${ from })`);
getPullRequests(from, to).then(prs => {
getPullRequests(from, to).then((prs) => {
// console.log(' ', prs.length, 'item(s) found');
historyData = Object.assign(historyData, {
[to]: prs
[to]: prs,
});
fs.writeFileSync(historyDataFile, JSON.stringify(historyData, null, 2));
loadMissingTag();

@ -30,14 +30,14 @@ const nonContributors = [
'rodrigok',
'renatobecker',
'sampaiodiego',
'SeanPackham'
'SeanPackham',
];
const GroupNames = {
FIX: '### 🐛 Bug fixes',
NEW: '### 🎉 New features',
BREAK: '### ⚠ BREAKING CHANGES',
MINOR: '🔍 Minor changes'
MINOR: '🔍 Minor changes',
};
const SummaryNameEmoticons = {
@ -45,7 +45,7 @@ const SummaryNameEmoticons = {
NEW: '🎉',
BREAK: '',
NOGROUP: '🔍',
contributor: '👩💻👨💻'
contributor: '👩💻👨💻',
};
const historyData = (() => {
@ -64,7 +64,7 @@ const historyManualData = (() => {
}
})();
Object.keys(historyManualData).forEach(tag => {
Object.keys(historyManualData).forEach((tag) => {
historyData[tag] = historyData[tag] || [];
historyData[tag].unshift(...historyManualData[tag]);
});
@ -74,10 +74,10 @@ function groupPRs(prs) {
BREAK: [],
NEW: [],
FIX: [],
NOGROUP: []
NOGROUP: [],
};
prs.forEach(pr => {
prs.forEach((pr) => {
const match = pr.title.match(/\[(FIX|NEW|BREAK)\]\s*(.+)/);
if (match) {
pr.title = match[2];
@ -98,26 +98,26 @@ function getLatestCommitDate() {
return execSync('git log --date=short --format=\'%ad\' -1').toString().replace(/\n/, '');
}
Object.keys(historyData).forEach(tag => {
Object.keys(historyData).forEach((tag) => {
historyData[tag] = {
prs: historyData[tag],
rcs: []
rcs: [],
};
});
Object.keys(historyData).forEach(tag => {
Object.keys(historyData).forEach((tag) => {
if (/-rc/.test(tag)) {
const mainTag = tag.replace(/-rc.*/, '');
historyData[mainTag] = historyData[mainTag] || {
noMainRelease: true,
prs: [],
rcs: []
rcs: [],
};
if (historyData[mainTag].noMainRelease) {
historyData[mainTag].rcs.push({
tag,
prs: historyData[tag].prs
prs: historyData[tag].prs,
});
} else {
historyData[mainTag].prs.push(...historyData[tag].prs);
@ -132,7 +132,7 @@ const file = [];
function getSummary(contributors, groupedPRs) {
const summary = [];
Object.keys(groupedPRs).forEach(group => {
Object.keys(groupedPRs).forEach((group) => {
if (groupedPRs[group].length) {
summary.push(`${ groupedPRs[group].length } ${ SummaryNameEmoticons[group] }`);
}
@ -153,7 +153,7 @@ function renderPRs(prs) {
const data = [];
const groupedPRs = groupPRs(prs);
Object.keys(groupedPRs).forEach(group => {
Object.keys(groupedPRs).forEach((group) => {
const prs = groupedPRs[group];
if (!prs.length) {
return;
@ -166,10 +166,10 @@ function renderPRs(prs) {
} else {
data.push(`\n${ groupName }\n`);
}
prs.forEach(pr => {
prs.forEach((pr) => {
let contributors = _.compact(_.difference(pr.contributors, nonContributors))
.sort()
.map(contributor => `[@${ contributor }](https://github.com/${ contributor })`)
.map((contributor) => `[@${ contributor }](https://github.com/${ contributor })`)
.join(' & ');
if (contributors) {
@ -184,21 +184,19 @@ function renderPRs(prs) {
}
});
const contributors = _.compact(_.difference(prs.reduce((value, pr) => {
return _.unique(value.concat(pr.contributors));
}, []), nonContributors));
const contributors = _.compact(_.difference(prs.reduce((value, pr) => _.unique(value.concat(pr.contributors)), []), nonContributors));
if (contributors.length) {
// TODO: Improve list like https://gist.github.com/paulmillr/2657075/
data.push('\n### 👩💻👨💻 Contributors 😍\n');
contributors.sort().forEach(contributor => {
contributors.sort().forEach((contributor) => {
data.push(`- [@${ contributor }](https://github.com/${ contributor })`);
});
}
return {
data,
summary: getSummary(contributors, groupedPRs)
summary: getSummary(contributors, groupedPRs),
};
}
@ -219,8 +217,8 @@ function sort(a, b) {
return 0;
}
Object.keys(historyData).sort(sort).forEach(tag => {
const {prs, rcs} = historyData[tag];
Object.keys(historyData).sort(sort).forEach((tag) => {
const { prs, rcs } = historyData[tag];
if (!prs.length && !rcs.length) {
return;
@ -228,7 +226,7 @@ Object.keys(historyData).sort(sort).forEach(tag => {
const tagDate = tag === 'HEAD' ? getLatestCommitDate() : getTagDate(tag);
const {data, summary} = renderPRs(prs);
const { data, summary } = renderPRs(prs);
const tagText = tag === 'HEAD' ? 'Next' : tag;
@ -242,8 +240,8 @@ Object.keys(historyData).sort(sort).forEach(tag => {
file.push(...data);
if (Array.isArray(rcs)) {
rcs.reverse().forEach(rc => {
const {data, summary} = renderPRs(rc.prs);
rcs.reverse().forEach((rc) => {
const { data, summary } = renderPRs(rc.prs);
if (historyData[tag].noMainRelease) {
const tagDate = getTagDate(rc.tag);

@ -26,33 +26,29 @@ const files = [
'./.circleci/update-releases.sh',
'./.docker/Dockerfile',
'./.docker/Dockerfile.rhel',
'./packages/rocketchat-lib/rocketchat.info'
'./packages/rocketchat-lib/rocketchat.info',
];
const readFile = (file) => {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
const readFile = (file) => new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
};
const writeFile = (file, data) => {
return new Promise((resolve, reject) => {
fs.writeFile(file, data, 'utf8', (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
});
const writeFile = (file, data) => new Promise((resolve, reject) => {
fs.writeFile(file, data, 'utf8', (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
};
});
let selectedVersion;
git.status()
.then(status => {
.then((status) => {
if (status.current === 'release-candidate') {
return semver.inc(pkgJson.version, 'prerelease', 'rc');
}
@ -64,63 +60,59 @@ git.status()
}
return Promise.reject(`No release action for branch ${ status.current }`);
})
.then(nextVersion => inquirer.prompt([{
.then((nextVersion) => inquirer.prompt([{
type: 'list',
message: `The current version is ${ pkgJson.version }. Update to version:`,
name: 'version',
choices: [
nextVersion,
'custom'
]
'custom',
],
}]))
.then(answers => {
.then((answers) => {
if (answers.version === 'custom') {
return inquirer.prompt([{
name: 'version',
message: 'Enter your custom version:'
message: 'Enter your custom version:',
}]);
}
return answers;
})
.then(({ version }) => {
selectedVersion = version;
return Promise.all(files.map(file => {
return readFile(file)
.then(data => {
return writeFile(file, data.replace(pkgJson.version, version));
});
}));
return Promise.all(files.map((file) => readFile(file)
.then((data) => writeFile(file, data.replace(pkgJson.version, version)))));
})
.then(() => {
.then(() =>
// execSync('conventional-changelog --config .github/changelog.js -i HISTORY.md -s');
return inquirer.prompt([{
inquirer.prompt([{
type: 'confirm',
message: 'Commit files?',
name: 'commit'
}]);
})
.then(answers => {
name: 'commit',
}])
)
.then((answers) => {
if (!answers.commit) {
return Promise.reject(answers);
}
return git.status();
})
.then(status => inquirer.prompt([{
.then((status) => inquirer.prompt([{
type: 'checkbox',
message: 'Select files to commit?',
name: 'files',
choices: status.files.map(file => { return {name: `${ file.working_dir } ${ file.path }`, checked: true}; })
choices: status.files.map((file) => ({ name: `${ file.working_dir } ${ file.path }`, checked: true })),
}]))
.then(answers => answers.files.length && git.add(answers.files.map(file => file.slice(2))))
.then((answers) => answers.files.length && git.add(answers.files.map((file) => file.slice(2))))
.then(() => git.commit(`Bump version to ${ selectedVersion }`))
.then(() => inquirer.prompt([{
type: 'confirm',
message: `Add tag ${ selectedVersion }?`,
name: 'tag'
name: 'tag',
}]))
.then(answers => answers.tag && git.addTag(selectedVersion))
.then((answers) => answers.tag && git.addTag(selectedVersion))
.catch((error) => {
console.error(error);
});

@ -12,8 +12,8 @@ const srcDir = path.resolve(baseDir);
const appOptions = {
env: {
PORT: 3000,
ROOT_URL: 'http://localhost:3000'
}
ROOT_URL: 'http://localhost:3000',
},
};
function startProcess(opts, callback) {
@ -38,7 +38,7 @@ function startProcess(opts, callback) {
}
if (opts.logFile) {
const logStream = fs.createWriteStream(opts.logFile, {flags: 'a'});
const logStream = fs.createWriteStream(opts.logFile, { flags: 'a' });
proc.stdout.pipe(logStream);
proc.stderr.pipe(logStream);
}
@ -60,8 +60,8 @@ function startApp(callback) {
waitForMessage: appOptions.waitForMessage,
options: {
cwd: srcDir,
env: extend(appOptions.env, process.env)
}
env: extend(appOptions.env, process.env),
},
}, callback);
}
@ -73,9 +73,9 @@ function startChimp() {
env: Object.assign({}, process.env, {
NODE_PATH: `${ process.env.NODE_PATH +
path.delimiter + srcDir +
path.delimiter + srcDir }/node_modules`
})
}
path.delimiter + srcDir }/node_modules`,
}),
},
});
}

@ -1,3 +1 @@
Template.registerHelper('escapeCssUrl', url => {
return url.replace(/(['"])/g, '\\$1');
});
Template.registerHelper('escapeCssUrl', (url) => url.replace(/(['"])/g, '\\$1'));

@ -1,3 +1 @@
Template.registerHelper('not', (value) => {
return !value;
});
Template.registerHelper('not', (value) => !value);

@ -13,7 +13,7 @@ this.handleError = function(error, useToastr = true) {
if (useToastr) {
const details = Object.entries(error.details || {})
.reduce((obj, [ key, value ]) => ({ ...obj, [key] : s.escapeHTML(value) }), {});
.reduce((obj, [key, value]) => ({ ...obj, [key] : s.escapeHTML(value) }), {});
const message = TAPi18n.__(error.error, details);
const title = details.errorTitle && TAPi18n.__(details.errorTitle);

@ -7,7 +7,7 @@ Meteor.methods({
return false;
}
//We're now only passed in the `_id` property to lower the amount of data sent to the server
// We're now only passed in the `_id` property to lower the amount of data sent to the server
message = ChatMessage.findOne({ _id: message._id });
const hasPermission = RocketChat.authz.hasAtLeastOnePermission('delete-message', message.rid);
@ -35,8 +35,8 @@ Meteor.methods({
Tracker.nonreactive(function() {
ChatMessage.remove({
_id: message._id,
'u._id': Meteor.userId()
'u._id': Meteor.userId(),
});
});
}
},
});

@ -6,12 +6,12 @@ Meteor.methods({
ChatSubscription.update({
rid,
'u._id': Meteor.userId()
'u._id': Meteor.userId(),
}, {
$set: {
alert: false,
open: false
}
open: false,
},
});
}
},
});

@ -6,11 +6,11 @@ Meteor.methods({
ChatSubscription.update({
rid,
'u._id': Meteor.userId()
'u._id': Meteor.userId(),
}, {
$set: {
open: true
}
open: true,
},
});
}
},
});

@ -2,5 +2,5 @@ Meteor.methods({
setUserActiveStatus(userId, active) {
Meteor.users.update(userId, { $set: { active } });
return true;
}
},
});

@ -6,11 +6,11 @@ Meteor.methods({
ChatSubscription.update({
rid,
'u._id': Meteor.userId()
'u._id': Meteor.userId(),
}, {
$set: {
f
}
f,
},
});
}
},
});

@ -48,11 +48,11 @@ Meteor.methods({
message.editedBy = {
_id: Meteor.userId(),
username: me.username
username: me.username,
};
message = RocketChat.callbacks.run('beforeSaveMessage', message);
const messageObject = {'editedAt': message.editedAt, 'editedBy': message.editedBy, msg: message.msg};
const messageObject = { editedAt: message.editedAt, editedBy: message.editedBy, msg: message.msg };
if (originalMessage.attachments) {
if (originalMessage.attachments[0].description !== undefined) {
@ -61,8 +61,8 @@ Meteor.methods({
}
ChatMessage.update({
_id: message._id,
'u._id': Meteor.userId()
}, {$set : messageObject});
'u._id': Meteor.userId(),
}, { $set : messageObject });
});
}
},
});

@ -1,34 +1,34 @@
Meteor.startup(function() {
RocketChat.Notifications.onLogged('Users:NameChanged', function({_id, name, username}) {
RocketChat.Notifications.onLogged('Users:NameChanged', function({ _id, name, username }) {
RocketChat.models.Messages.update({
'u._id': _id
'u._id': _id,
}, {
$set: {
'u.name': name
}
'u.name': name,
},
}, {
multi: true
multi: true,
});
RocketChat.models.Messages.update({
mentions: {
$elemMatch: { _id }
}
$elemMatch: { _id },
},
}, {
$set: {
'mentions.$.name': name
}
'mentions.$.name': name,
},
}, {
multi: true
multi: true,
});
RocketChat.models.Subscriptions.update({
name: username,
t: 'd'
t: 'd',
}, {
$set: {
fname: name
}
fname: name,
},
});
});
});

@ -34,7 +34,7 @@ Meteor.startup(function() {
fireGlobalEvent('notification', {
notification,
fromOpenedRoom: messageIsInOpenedRoom,
hasFocus
hasFocus,
});
if (RocketChat.Layout.isEmbedded()) {

@ -1,48 +1,48 @@
FlowRouter.route('/admin/users', {
name: 'admin-users',
action() {
BlazeLayout.render('main', {center: 'adminUsers'});
}
BlazeLayout.render('main', { center: 'adminUsers' });
},
});
FlowRouter.route('/admin/rooms', {
name: 'admin-rooms',
action() {
BlazeLayout.render('main', {center: 'adminRooms'});
}
BlazeLayout.render('main', { center: 'adminRooms' });
},
});
FlowRouter.route('/admin/info', {
name: 'admin-info',
action() {
BlazeLayout.render('main', {center: 'adminInfo'});
}
BlazeLayout.render('main', { center: 'adminInfo' });
},
});
FlowRouter.route('/admin/import', {
name: 'admin-import',
action() {
BlazeLayout.render('main', {center: 'adminImport'});
}
BlazeLayout.render('main', { center: 'adminImport' });
},
});
FlowRouter.route('/admin/import/prepare/:importer', {
name: 'admin-import-prepare',
action() {
BlazeLayout.render('main', {center: 'adminImportPrepare'});
}
BlazeLayout.render('main', { center: 'adminImportPrepare' });
},
});
FlowRouter.route('/admin/import/progress/:importer', {
name: 'admin-import-progress',
action() {
BlazeLayout.render('main', {center: 'adminImportProgress'});
}
BlazeLayout.render('main', { center: 'adminImportProgress' });
},
});
FlowRouter.route('/admin/:group?', {
name: 'admin',
action() {
BlazeLayout.render('main', {center: 'admin'});
}
BlazeLayout.render('main', { center: 'admin' });
},
});

@ -1,5 +1,5 @@
FlowRouter.goToRoomById = (roomId) => {
const subscription = ChatSubscription.findOne({rid: roomId});
const subscription = ChatSubscription.findOne({ rid: roomId });
if (subscription) {
RocketChat.roomTypes.openRouteLink(subscription.t, subscription, FlowRouter.current().queryParams);
}

@ -38,7 +38,7 @@ FlowRouter.route('/', {
c.stop();
}
});
}
},
});
@ -47,7 +47,7 @@ FlowRouter.route('/login', {
action() {
FlowRouter.go('home');
}
},
});
FlowRouter.route('/home', {
@ -59,25 +59,25 @@ FlowRouter.route('/home', {
Accounts.callLoginMethod({
methodArguments: [{
saml: true,
credentialToken: queryParams.saml_idp_credentialToken
credentialToken: queryParams.saml_idp_credentialToken,
}],
userCallback() { BlazeLayout.render('main', {center: 'home'}); }
userCallback() { BlazeLayout.render('main', { center: 'home' }); },
});
} else {
BlazeLayout.render('main', {center: 'home'});
BlazeLayout.render('main', { center: 'home' });
}
}
},
});
FlowRouter.route('/directory', {
name: 'directory',
action() {
BlazeLayout.render('main', {center: 'directory'});
BlazeLayout.render('main', { center: 'directory' });
},
triggersExit: [function() {
$('.main-content').addClass('rc-old');
}]
}],
});
FlowRouter.route('/account/:group?', {
@ -92,7 +92,7 @@ FlowRouter.route('/account/:group?', {
},
triggersExit: [function() {
$('.main-content').addClass('rc-old');
}]
}],
});
FlowRouter.route('/terms-of-service', {
@ -101,7 +101,7 @@ FlowRouter.route('/terms-of-service', {
action() {
Session.set('cmsPage', 'Layout_Terms_of_Service');
BlazeLayout.render('cmsPage');
}
},
});
FlowRouter.route('/privacy-policy', {
@ -110,16 +110,16 @@ FlowRouter.route('/privacy-policy', {
action() {
Session.set('cmsPage', 'Layout_Privacy_Policy');
BlazeLayout.render('cmsPage');
}
},
});
FlowRouter.route('/room-not-found/:type/:name', {
name: 'room-not-found',
action(params) {
Session.set('roomNotFound', {type: params.type, name: params.name});
BlazeLayout.render('main', {center: 'roomNotFound'});
}
Session.set('roomNotFound', { type: params.type, name: params.name });
BlazeLayout.render('main', { center: 'roomNotFound' });
},
});
FlowRouter.route('/fxos', {
@ -127,13 +127,13 @@ FlowRouter.route('/fxos', {
action() {
BlazeLayout.render('fxOsInstallPrompt');
}
},
});
FlowRouter.route('/register/:hash', {
name: 'register-secret-url',
action(/*params*/) {
action(/* params*/) {
BlazeLayout.render('secretURL');
// if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL'
@ -146,7 +146,7 @@ FlowRouter.route('/register/:hash', {
// BlazeLayout.render 'logoLayout', { render: 'invalidSecretURL' }
// else
// BlazeLayout.render 'logoLayout', { render: 'invalidSecretURL' }
}
},
});
FlowRouter.route('/setup-wizard', {
@ -154,7 +154,7 @@ FlowRouter.route('/setup-wizard', {
action() {
BlazeLayout.render('setupWizard');
}
},
});
FlowRouter.route('/setup-wizard/final', {
@ -162,12 +162,12 @@ FlowRouter.route('/setup-wizard/final', {
action() {
BlazeLayout.render('setupWizardFinal');
}
},
});
FlowRouter.notFound = {
action() {
BlazeLayout.render('pageNotFound');
}
},
};

@ -10,7 +10,7 @@ Meteor.startup(() => {
const availableLanguages = TAPi18n.getLanguages();
const filterLanguage = language => {
const filterLanguage = (language) => {
// Fix browsers having all-lowercase language settings eg. pt-br, en-us
const regex = /([a-z]{2})-([a-z]{2})/;
const matches = regex.exec(language);
@ -23,7 +23,7 @@ Meteor.startup(() => {
const getBrowserLanguage = () => filterLanguage(window.navigator.userLanguage || window.navigator.language);
const loadMomentLocale = language => new Promise((resolve, reject) => {
const loadMomentLocale = (language) => new Promise((resolve, reject) => {
if (moment.locales().includes(language.toLowerCase())) {
resolve(language);
return;
@ -53,7 +53,7 @@ Meteor.startup(() => {
document.documentElement.classList[isRtl(language) ? 'add' : 'remove']('rtl');
TAPi18n.setLanguage(language);
loadMomentLocale(language).then(locale => moment.locale(locale), error => console.error(error));
loadMomentLocale(language).then((locale) => moment.locale(locale), (error) => console.error(error));
};
const setLanguage = (language) => {
@ -67,7 +67,7 @@ Meteor.startup(() => {
window.defaultUserLanguage = defaultUserLanguage;
Tracker.autorun(() => {
const user = RocketChat.models.Users.findOne(Meteor.userId(), { fields: { language: 1 }});
const user = RocketChat.models.Users.findOne(Meteor.userId(), { fields: { language: 1 } });
setLanguage((user && user.language) || defaultUserLanguage());
});

@ -8,6 +8,6 @@ Meteor.startup(function() {
},
removed(data) {
Session.set(`roomData${ data._id }`, undefined);
}
},
});
});

@ -39,8 +39,8 @@ Meteor.startup(function() {
fields: {
status: 1,
'settings.preferences.idleTimeLimit': 1,
'settings.preferences.enableAutoAway': 1
}
'settings.preferences.enableAutoAway': 1,
},
});
if (!user) {

@ -5,7 +5,7 @@ Meteor.startup(function() {
let unreadCount = 0;
let unreadAlert = false;
const subscriptions = ChatSubscription.find({open: true, hideUnreadStatus: { $ne: true }}, { fields: { unread: 1, alert: 1, rid: 1, t: 1, name: 1, ls: 1, unreadAlert: 1 } });
const subscriptions = ChatSubscription.find({ open: true, hideUnreadStatus: { $ne: true } }, { fields: { unread: 1, alert: 1, rid: 1, t: 1, name: 1, ls: 1, unreadAlert: 1 } });
let openedRoomId = undefined;
Tracker.nonreactive(function() {
@ -63,7 +63,7 @@ Meteor.startup(function() {
Meteor.startup(function() {
window.favico = new Favico({
position: 'up',
animation: 'none'
animation: 'none',
});
Tracker.autorun(function() {
@ -74,7 +74,7 @@ Meteor.startup(function() {
if (favico) {
favico.badge(unread, {
bgColor: typeof unread !== 'number' ? '#3d8a3a' : '#ac1b1b'
bgColor: typeof unread !== 'number' ? '#3d8a3a' : '#ac1b1b',
});
}

@ -2,7 +2,7 @@ import moment from 'moment';
Meteor.startup(function() {
Tracker.autorun(function() {
const user = RocketChat.models.Users.findOne({_id: Meteor.userId()}, {fields: {statusConnection: 1, utcOffset: 1}});
const user = RocketChat.models.Users.findOne({ _id: Meteor.userId() }, { fields: { statusConnection: 1, utcOffset: 1 } });
if (user && user.statusConnection === 'online') {
const utcOffset = moment().utcOffset() / 60;
if (user.utcOffset !== utcOffset) {

@ -11,6 +11,6 @@ Meteor.startup(function() {
removed(user) {
Session.set(`user_${ user.username }_status`, null);
RoomManager.updateUserStatus(user, 'offline', null);
}
},
});
});

@ -3,5 +3,5 @@ Template.main.helpers({
if (RocketChat.settings.get('Message_Read_Receipt_Store_Users')) {
return 'read-receipts-enabled';
}
}
},
});

@ -7,7 +7,7 @@ Template.message.helpers({
}
return {
readByEveryone: (!this.unread && 'read') || 'color-component-color'
readByEveryone: (!this.unread && 'read') || 'color-component-color',
};
}
},
});

@ -16,7 +16,7 @@ Template.readReceipts.helpers({
},
isLoading() {
return Template.instance().loading.get();
}
},
});
Template.readReceipts.onCreated(function readReceiptsOnCreated() {

@ -9,16 +9,16 @@ RocketChat.MessageAction.addButton({
title: t('Message_info'),
content: 'readReceipts',
data: {
messageId: message._id
messageId: message._id,
},
showConfirmButton: true,
showCancelButton: false,
confirmButtonText: t('Close')
confirmButtonText: t('Close'),
});
},
condition() {
return RocketChat.settings.get('Message_Read_Receipt_Store_Users');
},
order: 1,
group: 'menu'
group: 'menu',
});

@ -24,5 +24,5 @@ Meteor.methods({
}
return ReadReceipt.getReceipts(message);
}
},
});

@ -1,5 +1,5 @@
RocketChat.models.Messages.tryEnsureIndex({
unread: 1
unread: 1,
}, {
sparse: true
sparse: true,
});

@ -55,15 +55,13 @@ export const ReadReceipt = {
storeReadReceipts(messages, roomId, userId) {
if (RocketChat.settings.get('Message_Read_Receipt_Store_Users')) {
const ts = new Date();
const receipts = messages.map(message => {
return {
_id: Random.id(),
roomId,
userId,
messageId: message._id,
ts
};
});
const receipts = messages.map((message) => ({
_id: Random.id(),
roomId,
userId,
messageId: message._id,
ts,
}));
if (receipts.length === 0) {
return;
@ -78,9 +76,9 @@ export const ReadReceipt = {
},
getReceipts(message) {
return ModelReadReceipts.findByMessageId(message._id).map(receipt => ({
return ModelReadReceipts.findByMessageId(message._id).map((receipt) => ({
...receipt,
user: RocketChat.models.Users.findOneById(receipt.userId, { fields: { username: 1, name: 1 }})
user: RocketChat.models.Users.findOneById(receipt.userId, { fields: { username: 1, name: 1 } }),
}));
}
},
};

@ -5,9 +5,9 @@ class ModelReadReceipts extends RocketChat.models._Base {
this.tryEnsureIndex({
roomId: 1,
userId: 1,
messageId: 1
messageId: 1,
}, {
unique: 1
unique: 1,
});
}

@ -1,12 +1,12 @@
RocketChat.settings.add('Message_Read_Receipt_Enabled', false, {
group: 'Message',
type: 'boolean',
public: true
public: true,
});
RocketChat.settings.add('Message_Read_Receipt_Store_Users', false, {
group: 'Message',
type: 'boolean',
public: true,
enableQuery: { _id: 'Message_Read_Receipt_Enabled', value: true }
enableQuery: { _id: 'Message_Read_Receipt_Enabled', value: true },
});

@ -3,7 +3,7 @@ FlowRouter.route('/admin/chatpal', {
action() {
return BlazeLayout.render('main', {
center: 'ChatpalAdmin',
pageTitle: t('Chatpal_AdminPage')
pageTitle: t('Chatpal_AdminPage'),
});
}
},
});

@ -4,9 +4,7 @@ Template.ChatpalAdmin.onCreated(function() {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
this.validateEmail = (email) => {
return re.test(email.toLowerCase());
};
this.validateEmail = (email) => re.test(email.toLowerCase());
this.apiKey = new ReactiveVar();
@ -32,7 +30,7 @@ Template.ChatpalAdmin.events({
if (!email || email === '') { return toastr.error(TAPi18n.__('Chatpal_ERROR_Email_must_be_set')); }
if (!t.validateEmail(email)) { return toastr.error(TAPi18n.__('Chatpal_ERROR_Email_must_be_valid')); }
//TODO register
// TODO register
try {
Meteor.call('chatpalUtilsCreateKey', email, (err, key) => {
if (!key) { return toastr.error(TAPi18n.__('Chatpal_ERROR_username_already_exists')); }
@ -44,12 +42,12 @@ Template.ChatpalAdmin.events({
} catch (e) {
console.log(e);
toastr.error(TAPi18n.__('Chatpal_ERROR_username_already_exists'));//TODO error messages
toastr.error(TAPi18n.__('Chatpal_ERROR_username_already_exists'));// TODO error messages
}
}
},
});
//template
// template
Template.ChatpalAdmin.helpers({
apiKey() {
return Template.instance().apiKey.get();
@ -59,5 +57,5 @@ Template.ChatpalAdmin.helpers({
},
tac() {
return Template.instance().tac.get();
}
},
});

@ -27,7 +27,7 @@ Template.ChatpalSearchResultTemplate.events = {
t.data.payload.rows = t.data.settings.PageSize;
t.resultType.set(t.data.parentPayload.resultType);
t.data.search();
}
},
};
Template.ChatpalSearchResultTemplate.helpers({
@ -74,10 +74,10 @@ Template.ChatpalSearchResultTemplate.helpers({
if (result) {
return {
currentPage: 1 + result.message.start / pageSize,
numOfPages: Math.ceil(result.message.numFound / pageSize)
numOfPages: Math.ceil(result.message.numFound / pageSize),
};
}
}
},
});
Template.ChatpalSearchSingleMessage.helpers({
@ -90,7 +90,7 @@ Template.ChatpalSearchSingleMessage.helpers({
},
roomLink() {
const subscription = RocketChat.models.Subscriptions.findOne({rid: this.rid});
const subscription = RocketChat.models.Subscriptions.findOne({ rid: this.rid });
return RocketChat.roomTypes.getRouteLink(subscription.t, subscription);
},
@ -104,7 +104,7 @@ Template.ChatpalSearchSingleMessage.helpers({
},
date() {
return moment(this.created).format(RocketChat.settings.get('Message_DateFormat'));
}
},
});
Template.ChatpalSearchSingleRoom.helpers({
@ -116,13 +116,13 @@ Template.ChatpalSearchSingleRoom.helpers({
return RocketChat.roomTypes.getIcon(room && room.t);
},
roomLink() {
const subscription = RocketChat.models.Subscriptions.findOne({rid: this._id});
const subscription = RocketChat.models.Subscriptions.findOne({ rid: this._id });
return RocketChat.roomTypes.getRouteLink(subscription.t, subscription);
}
},
});
Template.ChatpalSearchSingleUser.helpers({
cleanUsername() {
return this.user_username.replace(/<\/?em>/ig, '');
}
},
});

@ -2,7 +2,7 @@ Package.describe({
name: 'chatpal:search',
version: '0.0.1',
summary: 'Chatpal Search Provider',
git: ''
git: '',
});
Package.onUse(function(api) {
@ -13,18 +13,18 @@ Package.onUse(function(api) {
'rocketchat:logger',
'rocketchat:search',
'kadira:flow-router',
'meteorhacks:inject-initial'
'meteorhacks:inject-initial',
]);
api.addFiles('server/asset/chatpal-enter.svg', 'server', {isAsset:true});
api.addFiles('server/asset/chatpal-logo-icon-darkblue.svg', 'server', {isAsset:true});
api.addFiles('server/asset/chatpal-enter.svg', 'server', { isAsset:true });
api.addFiles('server/asset/chatpal-logo-icon-darkblue.svg', 'server', { isAsset:true });
api.addFiles([
'server/provider/provider.js',
'server/provider/index.js',
'server/utils/logger.js',
'server/utils/utils.js',
'server/asset/config.js'
'server/asset/config.js',
], 'server');
api.addFiles([
@ -35,6 +35,6 @@ Package.onUse(function(api) {
'client/template/admin.html',
'client/template/admin.js',
'client/style.css',
'client/route.js'
'client/route.js',
], 'client');
});

@ -18,8 +18,8 @@ class Backend {
index(docs) {
const options = {
data:docs,
params:{language:this._options.language},
...this._options.httpOptions
params:{ language:this._options.language },
...this._options.httpOptions,
};
try {
@ -33,7 +33,7 @@ class Backend {
}
} catch (e) {
//TODO how to deal with this
// TODO how to deal with this
ChatpalLogger.error('indexing failed', JSON.stringify(e, null, 2));
return false;
}
@ -52,11 +52,11 @@ class Backend {
const options = {
data:{
delete: {
query: `id:${ id } AND type:${ type }`
query: `id:${ id } AND type:${ type }`,
},
commit:{}
commit:{},
},
...this._options.httpOptions
...this._options.httpOptions,
};
try {
@ -69,7 +69,7 @@ class Backend {
}
count(type) {
return this.query({type, rows:0, text:'*'})[type].numFound;
return this.query({ type, rows:0, text:'*' })[type].numFound;
}
/**
@ -81,7 +81,7 @@ class Backend {
const options = {
params,
...this._options.httpOptions
...this._options.httpOptions,
};
ChatpalLogger.debug('query: ', JSON.stringify(options, null, 2));
@ -113,7 +113,7 @@ class Backend {
const options = {
params,
...this._options.httpOptions
...this._options.httpOptions,
};
HTTP.call('POST', this._options.baseurl + this._options.suggestionpath, options, (err, result) => {
@ -133,10 +133,10 @@ class Backend {
const options = {
data:{
delete: {
query: '*:*'
query: '*:*',
},
commit:{}
}, ...this._options.httpOptions
commit:{},
}, ...this._options.httpOptions,
};
try {
@ -157,9 +157,9 @@ class Backend {
const options = {
params: {
stats:true
stats:true,
},
...config.httpOptions
...config.httpOptions,
};
try {
@ -197,7 +197,7 @@ class BatchIndexer {
}
flush() {
this._func(this._values, this._rest);//TODO if flush does not work
this._func(this._values, this._rest);// TODO if flush does not work
this._values = [];
}
}
@ -242,7 +242,7 @@ export default class Index {
created: doc.ts,
updated: doc._updatedAt,
text: doc.msg,
type
type,
};
case 'room':
return {
@ -254,7 +254,7 @@ export default class Index {
room_name: doc.name,
room_announcement: doc.announcement,
room_description: doc.description,
room_topic: doc.topic
room_topic: doc.topic,
};
case 'user':
return {
@ -264,7 +264,7 @@ export default class Index {
type,
user_username: doc.username,
user_name: doc.name,
user_email: doc.emails && doc.emails.map((e) => { return e.address; })
user_email: doc.emails && doc.emails.map((e) => e.address),
};
default: throw new Error(`Cannot index type '${ type }'`);
}
@ -277,22 +277,22 @@ export default class Index {
* @private
*/
_existsDataOlderThan(date) {
return RocketChat.models.Messages.model.find({ts:{$lt: new Date(date)}, t:{$exists:false}}, {limit:1}).fetch().length > 0;
return RocketChat.models.Messages.model.find({ ts:{ $lt: new Date(date) }, t:{ $exists:false } }, { limit:1 }).fetch().length > 0;
}
_doesRoomCountDiffer() {
return RocketChat.models.Rooms.find({t:{$ne:'d'}}).count() !== this._backend.count('room');
return RocketChat.models.Rooms.find({ t:{ $ne:'d' } }).count() !== this._backend.count('room');
}
_doesUserCountDiffer() {
return Meteor.users.find({active:true}).count() !== this._backend.count('user');
return Meteor.users.find({ active:true }).count() !== this._backend.count('user');
}
/**
* Index users by using a database cursor
*/
_indexUsers() {
const cursor = Meteor.users.find({active:true});
const cursor = Meteor.users.find({ active:true });
ChatpalLogger.debug(`Start indexing ${ cursor.count() } users`);
@ -308,7 +308,7 @@ export default class Index {
* @private
*/
_indexRooms() {
const cursor = RocketChat.models.Rooms.find({t:{$ne:'d'}});
const cursor = RocketChat.models.Rooms.find({ t:{ $ne:'d' } });
ChatpalLogger.debug(`Start indexing ${ cursor.count() } rooms`);
@ -324,7 +324,7 @@ export default class Index {
const start = new Date(date - gap);
const end = new Date(date);
const cursor = RocketChat.models.Messages.model.find({ts:{$gt: start, $lt: end}, t:{$exists:false}});
const cursor = RocketChat.models.Messages.model.find({ ts:{ $gt: start, $lt: end }, t:{ $exists:false } });
ChatpalLogger.debug(`Start indexing ${ cursor.count() } messages between ${ start.toString() } and ${ end.toString() }`);
@ -433,7 +433,7 @@ export default class Index {
type,
start,
rows,
...params
...params,
}, callback);
}
@ -442,7 +442,7 @@ export default class Index {
text,
language,
acl,
type
type,
}, callback);
}

@ -1,5 +1,5 @@
import {searchProviderService} from 'meteor/rocketchat:search';
import {SearchProvider} from 'meteor/rocketchat:search';
import { searchProviderService } from 'meteor/rocketchat:search';
import { SearchProvider } from 'meteor/rocketchat:search';
import Index from './index';
import ChatpalLogger from '../utils/logger';
@ -18,88 +18,88 @@ class ChatpalProvider extends SearchProvider {
this._settings.add('Backend', 'select', 'cloud', {
values:[
{key: 'cloud', i18nLabel: 'Cloud Service'},
{key: 'onsite', i18nLabel: 'On-Site'}
{ key: 'cloud', i18nLabel: 'Cloud Service' },
{ key: 'onsite', i18nLabel: 'On-Site' },
],
i18nLabel: 'Chatpal_Backend',
i18nDescription: 'Chatpal_Backend_Description'
i18nDescription: 'Chatpal_Backend_Description',
});
this._settings.add('API_Key', 'string', '', {
enableQuery:[{
_id: 'Search.chatpalProvider.Backend',
value: 'cloud'
value: 'cloud',
}],
i18nLabel: 'Chatpal_API_Key',
i18nDescription: 'Chatpal_API_Key_Description'
i18nDescription: 'Chatpal_API_Key_Description',
});
this._settings.add('Base_URL', 'string', '', {
enableQuery:[{
_id: 'Search.chatpalProvider.Backend',
value: 'onsite'
value: 'onsite',
}],
i18nLabel: 'Chatpal_Base_URL',
i18nDescription: 'Chatpal_Base_URL_Description'
i18nDescription: 'Chatpal_Base_URL_Description',
});
this._settings.add('HTTP_Headers', 'string', '', {
enableQuery:[{
_id: 'Search.chatpalProvider.Backend',
value: 'onsite'
value: 'onsite',
}],
multiline: true,
i18nLabel: 'Chatpal_HTTP_Headers',
i18nDescription: 'Chatpal_HTTP_Headers_Description'
i18nDescription: 'Chatpal_HTTP_Headers_Description',
});
this._settings.add('Main_Language', 'select', 'en', {
values: [
{key: 'en', i18nLabel: 'English'},
{key: 'none', i18nLabel: 'Language_Not_set'},
{key: 'cs', i18nLabel: 'Czech'},
{key: 'de', i18nLabel: 'Deutsch'},
{key: 'el', i18nLabel: 'Greek'},
{key: 'es', i18nLabel: 'Spanish'},
{key: 'fi', i18nLabel: 'Finish'},
{key: 'fr', i18nLabel: 'French'},
{key: 'hu', i18nLabel: 'Hungarian'},
{key: 'it', i18nLabel: 'Italian'},
{key: 'nl', i18nLabel: 'Dutsch'},
{key: 'pl', i18nLabel: 'Polish'},
{key: 'pt', i18nLabel: 'Portuguese'},
{key: 'pt_BR', i18nLabel: 'Brasilian'},
{key: 'ro', i18nLabel: 'Romanian'},
{key: 'ru', i18nLabel: 'Russian'},
{key: 'sv', i18nLabel: 'Swedisch'},
{key: 'tr', i18nLabel: 'Turkish'},
{key: 'uk', i18nLabel: 'Ukrainian'}
{ key: 'en', i18nLabel: 'English' },
{ key: 'none', i18nLabel: 'Language_Not_set' },
{ key: 'cs', i18nLabel: 'Czech' },
{ key: 'de', i18nLabel: 'Deutsch' },
{ key: 'el', i18nLabel: 'Greek' },
{ key: 'es', i18nLabel: 'Spanish' },
{ key: 'fi', i18nLabel: 'Finish' },
{ key: 'fr', i18nLabel: 'French' },
{ key: 'hu', i18nLabel: 'Hungarian' },
{ key: 'it', i18nLabel: 'Italian' },
{ key: 'nl', i18nLabel: 'Dutsch' },
{ key: 'pl', i18nLabel: 'Polish' },
{ key: 'pt', i18nLabel: 'Portuguese' },
{ key: 'pt_BR', i18nLabel: 'Brasilian' },
{ key: 'ro', i18nLabel: 'Romanian' },
{ key: 'ru', i18nLabel: 'Russian' },
{ key: 'sv', i18nLabel: 'Swedisch' },
{ key: 'tr', i18nLabel: 'Turkish' },
{ key: 'uk', i18nLabel: 'Ukrainian' },
],
i18nLabel: 'Chatpal_Main_Language',
i18nDescription: 'Chatpal_Main_Language_Description'
i18nDescription: 'Chatpal_Main_Language_Description',
});
this._settings.add('DefaultResultType', 'select', 'All', {
values: [
{key: 'All', i18nLabel: 'All'},
{key: 'Messages', i18nLabel: 'Messages'}
{ key: 'All', i18nLabel: 'All' },
{ key: 'Messages', i18nLabel: 'Messages' },
],
i18nLabel: 'Chatpal_Default_Result_Type',
i18nDescription: 'Chatpal_Default_Result_Type_Description'
i18nDescription: 'Chatpal_Default_Result_Type_Description',
});
this._settings.add('PageSize', 'int', 15, {
i18nLabel: 'Search_Page_Size'
i18nLabel: 'Search_Page_Size',
});
this._settings.add('SuggestionEnabled', 'boolean', true, {
i18nLabel: 'Chatpal_Suggestion_Enabled',
alert: 'This feature is currently in beta and will be extended in the future'
alert: 'This feature is currently in beta and will be extended in the future',
});
this._settings.add('BatchSize', 'int', 100, {
i18nLabel: 'Chatpal_Batch_Size',
i18nDescription: 'Chatpal_Batch_Size_Description'
i18nDescription: 'Chatpal_Batch_Size_Description',
});
this._settings.add('TimeoutSize', 'int', 5000, {
i18nLabel: 'Chatpal_Timeout_Size',
i18nDescription: 'Chatpal_Timeout_Size_Description'
i18nDescription: 'Chatpal_Timeout_Size_Description',
});
this._settings.add('WindowSize', 'int', 48, {
i18nLabel: 'Chatpal_Window_Size',
i18nDescription: 'Chatpal_Window_Size_Description'
i18nDescription: 'Chatpal_Window_Size_Description',
});
}
@ -197,13 +197,13 @@ class ChatpalProvider extends SearchProvider {
if (stats) {
ChatpalLogger.debug('ping was successfull');
resolve({config, stats});
resolve({ config, stats });
} else {
ChatpalLogger.warn(`ping failed, retry in ${ timeout } ms`);
this._pingTimeout = Meteor.setTimeout(() => {
this._ping(config, resolve, reject, Math.min(maxTimeout, 2*timeout));
this._ping(config, resolve, reject, Math.min(maxTimeout, 2 * timeout));
}, timeout);
}
@ -218,7 +218,7 @@ class ChatpalProvider extends SearchProvider {
return new Promise((resolve, reject) => {
const config = {
backendtype: this._settings.get('Backend')
backendtype: this._settings.get('Backend'),
};
if (this._settings.get('Backend') === 'cloud') {
@ -231,8 +231,8 @@ class ChatpalProvider extends SearchProvider {
config.suggestionpath = '/search/suggest';
config.httpOptions = {
headers: {
'X-Api-Key': this._settings.get('API_Key')
}
'X-Api-Key': this._settings.get('API_Key'),
},
};
} else {
config.baseurl = this._settings.get('Base_URL').endsWith('/') ? this._settings.get('Base_URL').slice(0, -1) : this._settings.get('Base_URL');
@ -243,7 +243,7 @@ class ChatpalProvider extends SearchProvider {
config.clearpath = '/chatpal/clear';
config.suggestionpath = '/chatpal/suggest';
config.httpOptions = {
headers: this._parseHeaders()
headers: this._parseHeaders(),
};
}
@ -300,7 +300,7 @@ class ChatpalProvider extends SearchProvider {
* @private
*/
_getAcl(context) {
return RocketChat.models.Subscriptions.find({'u._id': context.uid}).fetch().map(room => room.rid);
return RocketChat.models.Subscriptions.find({ 'u._id': context.uid }).fetch().map((room) => room.rid);
}
/**
@ -309,7 +309,7 @@ class ChatpalProvider extends SearchProvider {
*/
search(text, context, payload, callback) {
if (!this.index) { return callback({msg:'Chatpal_currently_not_active'}); }
if (!this.index) { return callback({ msg:'Chatpal_currently_not_active' }); }
const type = payload.resultType === 'All' ? ['message', 'user', 'room'] : ['message'];
@ -330,7 +330,7 @@ class ChatpalProvider extends SearchProvider {
*/
suggest(text, context, payload, callback) {
if (!this.index) { return callback({msg:'Chatpal_currently_not_active'}); }
if (!this.index) { return callback({ msg:'Chatpal_currently_not_active' }); }
const type = payload.resultType === 'All' ? ['message', 'user', 'room'] : ['message'];

@ -1,7 +1,7 @@
Meteor.methods({
'chatpalUtilsCreateKey'(email) {
try {
const response = HTTP.call('POST', 'https://beta.chatpal.io/v1/account', {data: {email, tier: 'free'}});
const response = HTTP.call('POST', 'https://beta.chatpal.io/v1/account', { data: { email, tier: 'free' } });
if (response.statusCode === 201) {
return response.data.key;
} else {
@ -22,5 +22,5 @@ Meteor.methods({
} catch (e) {
return false;
}
}
},
});

@ -1,8 +1,8 @@
Package.describe({
'name': 'steffo:meteor-accounts-saml',
'summary': 'SAML Login (SP) for Meteor. Works with OpenAM, OpenIDP and provides Single Logout.',
'version': '0.0.1',
'git': 'https://github.com/steffow/meteor-accounts-saml.git'
name: 'steffo:meteor-accounts-saml',
summary: 'SAML Login (SP) for Meteor. Works with OpenAM, OpenIDP and provides Single Logout.',
version: '0.0.1',
git: 'https://github.com/steffow/meteor-accounts-saml.git',
});
Package.on_use(function(api) {

@ -17,7 +17,7 @@ if (!Accounts.saml) {
const MeteorLogout = Meteor.logout;
const logoutBehaviour = {
TERMINATE_SAML: 'SAML',
ONLY_RC: 'Local'
ONLY_RC: 'Local',
};
Meteor.logout = function() {
@ -49,7 +49,7 @@ const openCenteredPopup = function(url, width, height) {
const intervalId = setInterval(function() {
newwindow.executeScript({
'code': 'document.getElementsByTagName("script")[0].textContent'
code: 'document.getElementsByTagName("script")[0].textContent',
}, function(data) {
if (data && data.length > 0 && data[0] === 'window.close()') {
newwindow.close();
@ -116,26 +116,26 @@ Meteor.loginWithSaml = function(options, callback) {
const credentialToken = `id-${ Random.id() }`;
options.credentialToken = credentialToken;
Accounts.saml.initiateLogin(options, function(/*error, result*/) {
Accounts.saml.initiateLogin(options, function(/* error, result*/) {
Accounts.callLoginMethod({
methodArguments: [{
saml: true,
credentialToken
credentialToken,
}],
userCallback: callback
userCallback: callback,
});
});
};
Meteor.logoutWithSaml = function(options/*, callback*/) {
//Accounts.saml.idpInitiatedSLO(options, callback);
Meteor.logoutWithSaml = function(options/* , callback*/) {
// Accounts.saml.idpInitiatedSLO(options, callback);
Meteor.call('samlLogout', options.provider, function(err, result) {
if (err || !result) {
MeteorLogout.apply(Meteor);
return;
}
// 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='+result));
window.location.replace(Meteor.absoluteUrl(`_saml/sloRedirect/${ options.provider }/?redirect=${ encodeURIComponent(result) }`));
});
};

@ -1,9 +1,9 @@
const logger = new Logger('steffo:meteor-accounts-saml', {
methods: {
updated: {
type: 'info'
}
}
type: 'info',
},
},
});
RocketChat.settings.addGroup('SAML');
@ -14,88 +14,88 @@ Meteor.methods({
type: 'boolean',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Enable'
i18nLabel: 'Accounts_OAuth_Custom_Enable',
});
RocketChat.settings.add(`SAML_Custom_${ name }_provider`, 'provider-name', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Provider'
i18nLabel: 'SAML_Custom_Provider',
});
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'
i18nLabel: 'SAML_Custom_Entry_point',
});
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'
i18nLabel: 'SAML_Custom_IDP_SLO_Redirect_URL',
});
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'
i18nLabel: 'SAML_Custom_Issuer',
});
RocketChat.settings.add(`SAML_Custom_${ name }_cert`, '', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Cert',
multiline: true
multiline: true,
});
RocketChat.settings.add(`SAML_Custom_${ name }_public_cert`, '', {
type: 'string',
group: 'SAML',
section: name,
multiline: true,
i18nLabel: 'SAML_Custom_Public_Cert'
i18nLabel: 'SAML_Custom_Public_Cert',
});
RocketChat.settings.add(`SAML_Custom_${ name }_private_key`, '', {
type: 'string',
group: 'SAML',
section: name,
multiline: true,
i18nLabel: 'SAML_Custom_Private_Key'
i18nLabel: 'SAML_Custom_Private_Key',
});
RocketChat.settings.add(`SAML_Custom_${ name }_button_label_text`, '', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text'
i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Text',
});
RocketChat.settings.add(`SAML_Custom_${ name }_button_label_color`, '#FFFFFF', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color'
i18nLabel: 'Accounts_OAuth_Custom_Button_Label_Color',
});
RocketChat.settings.add(`SAML_Custom_${ name }_button_color`, '#13679A', {
type: 'string',
group: 'SAML',
section: name,
i18nLabel: 'Accounts_OAuth_Custom_Button_Color'
i18nLabel: 'Accounts_OAuth_Custom_Button_Color',
});
RocketChat.settings.add(`SAML_Custom_${ name }_generate_username`, false, {
type: 'boolean',
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Generate_Username'
i18nLabel: 'SAML_Custom_Generate_Username',
});
RocketChat.settings.add(`SAML_Custom_${ name }_logout_behaviour`, 'SAML', {
type: 'select',
values: [
{key: 'SAML', i18nLabel: 'SAML_Custom_Logout_Behaviour_Terminate_SAML_Session'},
{key: 'Local', i18nLabel: 'SAML_Custom_Logout_Behaviour_End_Only_RocketChat'}
{ key: 'SAML', i18nLabel: 'SAML_Custom_Logout_Behaviour_Terminate_SAML_Session' },
{ key: 'Local', i18nLabel: 'SAML_Custom_Logout_Behaviour_End_Only_RocketChat' },
],
group: 'SAML',
section: name,
i18nLabel: 'SAML_Custom_Logout_Behaviour'
i18nLabel: 'SAML_Custom_Logout_Behaviour',
});
}
},
});
const getSamlConfigs = function(service) {
@ -104,7 +104,7 @@ const getSamlConfigs = function(service) {
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`),
@ -114,8 +114,8 @@ const getSamlConfigs = function(service) {
secret: {
privateKey: RocketChat.settings.get(`${ service.key }_private_key`),
publicCert: RocketChat.settings.get(`${ service.key }_public_cert`),
cert: RocketChat.settings.get(`${ service.key }_cert`)
}
cert: RocketChat.settings.get(`${ service.key }_cert`),
},
};
};
@ -148,7 +148,7 @@ const configureSamlService = function(samlConfigs) {
issuer: samlConfigs.issuer,
cert: samlConfigs.secret.cert,
privateCert,
privateKey
privateKey,
};
};
@ -159,30 +159,28 @@ const updateServices = debounce(() => {
const samlConfigs = getSamlConfigs(service);
logger.updated(service.key);
ServiceConfiguration.configurations.upsert({
service: serviceName.toLowerCase()
service: serviceName.toLowerCase(),
}, {
$set: samlConfigs
$set: samlConfigs,
});
return configureSamlService(samlConfigs);
} else {
ServiceConfiguration.configurations.remove({
service: serviceName.toLowerCase()
service: serviceName.toLowerCase(),
});
}
}).filter(e => e);
}).filter((e) => e);
}, 2000);
RocketChat.settings.get(/^SAML_.+/, updateServices);
Meteor.startup(() => {
return Meteor.call('addSamlService', 'Default');
});
Meteor.startup(() => Meteor.call('addSamlService', 'Default'));
export {
updateServices,
configureSamlService,
getSamlConfigs,
debounce,
logger
logger,
};

@ -7,8 +7,8 @@ if (!Accounts.saml) {
settings: {
debug: true,
generateUsername: false,
providers: []
}
providers: [],
},
};
}
@ -45,9 +45,9 @@ Meteor.methods({
// This query should respect upcoming array of SAML logins
const user = Meteor.users.findOne({
_id: Meteor.userId(),
'services.saml.provider': provider
'services.saml.provider': provider,
}, {
'services.saml': 1
'services.saml': 1,
});
let nameID = user.services.saml.nameID;
const sessionIndex = user.services.saml.idpSession;
@ -60,18 +60,18 @@ Meteor.methods({
const request = _saml.generateLogoutRequest({
nameID,
sessionIndex
sessionIndex,
});
// request.request: actual XML SAML Request
// request.id: comminucation id which will be mentioned in the ResponseTo field of SAMLResponse
Meteor.users.update({
_id: Meteor.userId()
_id: Meteor.userId(),
}, {
$set: {
'services.saml.inResponseTo': request.id
}
'services.saml.inResponseTo': request.id,
},
});
const _syncRequestToUrl = Meteor.wrapAsync(_saml.requestToUrl, _saml);
@ -82,7 +82,7 @@ Meteor.methods({
return result;
}
},
});
Accounts.registerLoginHandler(function(loginRequest) {
@ -98,15 +98,15 @@ Accounts.registerLoginHandler(function(loginRequest) {
if (loginResult === undefined) {
return {
type: 'saml',
error: new Meteor.Error(Accounts.LoginCancelledError.numericError, 'No matching login attempt found')
error: new Meteor.Error(Accounts.LoginCancelledError.numericError, 'No matching login attempt found'),
};
}
if (loginResult && loginResult.profile && loginResult.profile.email) {
const emailList = Array.isArray(loginResult.profile.email) ? loginResult.profile.email : [loginResult.profile.email];
const emailRegex = new RegExp(emailList.map(email => `^${ RegExp.escape(email) }$`).join('|'), 'i');
const emailRegex = new RegExp(emailList.map((email) => `^${ RegExp.escape(email) }$`).join('|'), 'i');
let user = Meteor.users.findOne({
'emails.address': emailRegex
'emails.address': emailRegex,
});
if (!user) {
@ -114,12 +114,10 @@ Accounts.registerLoginHandler(function(loginRequest) {
name: loginResult.profile.cn || loginResult.profile.username,
active: true,
globalRoles: ['user'],
emails: emailList.map(email => {
return {
address: email,
verified: true
};
})
emails: emailList.map((email) => ({
address: email,
verified: true,
})),
};
if (Accounts.saml.settings.generateUsername === true) {
@ -135,34 +133,34 @@ Accounts.registerLoginHandler(function(loginRequest) {
user = Meteor.users.findOne(userId);
}
//creating the token and adding to the user
// creating the token and adding to the user
const stampedToken = Accounts._generateStampedLoginToken();
Meteor.users.update(user, {
$push: {
'services.resume.loginTokens': stampedToken
}
'services.resume.loginTokens': stampedToken,
},
});
const samlLogin = {
provider: Accounts.saml.RelayState,
idp: loginResult.profile.issuer,
idpSession: loginResult.profile.sessionIndex,
nameID: loginResult.profile.nameID
nameID: loginResult.profile.nameID,
};
Meteor.users.update({
_id: user._id
_id: user._id,
}, {
$set: {
// TBD this should be pushed, otherwise we're only able to SSO into a single IDP at a time
'services.saml': samlLogin
}
'services.saml': samlLogin,
},
});
//sending token along with the userId
// sending token along with the userId
const result = {
userId: user._id,
token: stampedToken.token
token: stampedToken.token,
};
return result;
@ -190,7 +188,7 @@ Accounts.saml.storeCredential = function(credentialToken, loginResult) {
const closePopup = function(res, err) {
res.writeHead(200, {
'Content-Type': 'text/html'
'Content-Type': 'text/html',
});
let content = '<html><head><script>window.close()</script></head><body><H1>Verified</H1></body></html>';
if (err) {
@ -217,7 +215,7 @@ const samlUrlToObject = function(url) {
const result = {
actionName: splitPath[2],
serviceName: splitPath[3],
credentialToken: splitPath[4]
credentialToken: splitPath[4],
};
if (Accounts.saml.settings.debug) {
console.log(result);
@ -257,7 +255,7 @@ const middleware = function(req, res, next) {
res.writeHead(200);
res.write(_saml.generateServiceProviderMetadata(service.callbackUrl));
res.end();
//closePopup(res);
// closePopup(res);
break;
case 'logout':
// This is where we receive SAML LogoutResponse
@ -269,25 +267,25 @@ const middleware = function(req, res, next) {
console.log(`Logging Out user via inResponseTo ${ inResponseTo }`);
}
const loggedOutUser = Meteor.users.find({
'services.saml.inResponseTo': inResponseTo
'services.saml.inResponseTo': inResponseTo,
}).fetch();
if (loggedOutUser.length === 1) {
if (Accounts.saml.settings.debug) {
console.log(`Found user ${ loggedOutUser[0]._id }`);
}
Meteor.users.update({
_id: loggedOutUser[0]._id
_id: loggedOutUser[0]._id,
}, {
$set: {
'services.resume.loginTokens': []
}
'services.resume.loginTokens': [],
},
});
Meteor.users.update({
_id: loggedOutUser[0]._id
_id: loggedOutUser[0]._id,
}, {
$unset: {
'services.saml': ''
}
'services.saml': '',
},
});
} else {
throw new Meteor.Error('Found multiple users matching SAML inResponseTo fields');
@ -300,7 +298,7 @@ const middleware = function(req, res, next) {
res.writeHead(302, {
'Location': req.query.RelayState
Location: req.query.RelayState,
});
res.end();
}
@ -312,7 +310,7 @@ const middleware = function(req, res, next) {
case 'sloRedirect':
res.writeHead(302, {
// credentialToken here is the SAML LogOut Request that we'll send back to IDP
'Location': req.query.redirect
Location: req.query.redirect,
});
res.end();
break;
@ -325,7 +323,7 @@ const middleware = function(req, res, next) {
throw new Error('Unable to generate authorize url');
}
res.writeHead(302, {
'Location': url
Location: url,
});
res.end();
});
@ -333,14 +331,14 @@ const middleware = function(req, res, next) {
case 'validate':
_saml = new SAML(service);
Accounts.saml.RelayState = req.body.RelayState;
_saml.validateResponse(req.body.SAMLResponse, req.body.RelayState, function(err, profile/*, loggedOut*/) {
_saml.validateResponse(req.body.SAMLResponse, req.body.RelayState, function(err, profile/* , loggedOut*/) {
if (err) {
throw new Error(`Unable to validate response url: ${ err }`);
}
const credentialToken = (profile.inResponseToId && profile.inResponseToId.value) || profile.inResponseToId || profile.InResponseTo || samlObject.credentialToken;
const loginResult = {
profile
profile,
};
if (!credentialToken) {
// No credentialToken in IdP-initiated SSO
@ -349,7 +347,7 @@ const middleware = function(req, res, next) {
const url = `${ Meteor.absoluteUrl('home') }?saml_idp_credentialToken=${ saml_idp_credentialToken }`;
res.writeHead(302, {
'Location': url
Location: url,
});
res.end();
} else {

@ -140,7 +140,7 @@ SAML.prototype.generateLogoutRequest = function(options) {
return {
request,
id
id,
};
};
@ -177,7 +177,7 @@ SAML.prototype.requestToUrl = function(request, operation, callback) {
const samlRequest = {
SAMLRequest: base64,
RelayState: relayState
RelayState: relayState,
};
if (self.options.privateCert) {
@ -253,7 +253,7 @@ SAML.prototype.validateStatus = function(doc) {
return {
success: successStatus,
message: messageText,
statusCode: status
statusCode: status,
};
};
@ -266,12 +266,12 @@ SAML.prototype.validateSignature = function(xml, cert) {
const sig = new xmlCrypto.SignedXml();
sig.keyInfoProvider = {
getKeyInfo(/*key*/) {
getKeyInfo(/* key*/) {
return '<X509Data></X509Data>';
},
getKey(/*keyInfo*/) {
getKey(/* keyInfo*/) {
return self.certToPEM(cert);
}
},
};
sig.loadSignature(signature);
@ -336,7 +336,7 @@ SAML.prototype.mapAttributes = function(attributeStatement, profile) {
value = values[0].textContent;
} else {
value = [];
for (let j=0;j<values.length;j++) {
for (let j = 0;j < values.length;j++) {
value.push(values[j].textContent);
}
}
@ -486,26 +486,26 @@ SAML.prototype.generateServiceProviderMetadata = function(callbackUrl) {
}
const metadata = {
'EntityDescriptor': {
EntityDescriptor: {
'@xmlns': 'urn:oasis:names:tc:SAML:2.0:metadata',
'@xmlns:ds': 'http://www.w3.org/2000/09/xmldsig#',
'@entityID': this.options.issuer,
'SPSSODescriptor': {
SPSSODescriptor: {
'@protocolSupportEnumeration': 'urn:oasis:names:tc:SAML:2.0:protocol',
'SingleLogoutService': {
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 }/`
'@ResponseLocation': `${ Meteor.absoluteUrl() }_saml/logout/${ this.options.provider }/`,
},
'NameIDFormat': this.options.identifierFormat,
'AssertionConsumerService': {
NameIDFormat: this.options.identifierFormat,
AssertionConsumerService: {
'@index': '1',
'@isDefault': 'true',
'@Binding': 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
'@Location': callbackUrl
}
}
}
'@Location': callbackUrl,
},
},
},
};
if (this.options.privateKey) {
@ -518,32 +518,32 @@ SAML.prototype.generateServiceProviderMetadata = function(callbackUrl) {
decryptionCert = decryptionCert.replace(/-+END CERTIFICATE-+\r?\n?/, '');
decryptionCert = decryptionCert.replace(/\r\n/g, '\n');
metadata['EntityDescriptor']['SPSSODescriptor']['KeyDescriptor'] = {
metadata.EntityDescriptor.SPSSODescriptor.KeyDescriptor = {
'ds:KeyInfo': {
'ds:X509Data': {
'ds:X509Certificate': {
'#text': decryptionCert
}
}
'#text': decryptionCert,
},
},
},
'EncryptionMethod': [
EncryptionMethod: [
// this should be the set that the xmlenc library supports
{
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#aes256-cbc'
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#aes256-cbc',
},
{
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#aes128-cbc'
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#aes128-cbc',
},
{
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc'
}
]
'@Algorithm': 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc',
},
],
};
}
return xmlbuilder.create(metadata).end({
pretty: true,
indent: ' ',
newline: '\n'
newline: '\n',
});
};

@ -36,7 +36,7 @@ const getFindParams = function(rule, filter, limit) {
// We need to extend so that we don't copy over rule.filter
const selector = _.extend({}, rule.filter || {});
const options = {
limit
limit,
};
if (!filter) {
// Match anything, no sort, limit X
@ -55,7 +55,7 @@ const getFindParams = function(rule, filter, limit) {
selector[rule.field] = {
$regex: rule.matchAll ? filter : `^${ filter }`,
// default is case insensitive search - empty string is not the same as undefined!
$options: typeof rule.options === 'undefined' ? 'i' : rule.options
$options: typeof rule.options === 'undefined' ? 'i' : rule.options,
};
}
return [selector, options];
@ -63,7 +63,7 @@ const getFindParams = function(rule, filter, limit) {
const getField = function(obj, str) {
const string = str.split('.');
string.forEach(key => {
string.forEach((key) => {
obj = obj[key];
});
return obj;
@ -78,21 +78,19 @@ this.AutoComplete = class {
this.selector = {
constainer: '.-autocomplete-container',
item: '.-autocomplete-item',
...settings.selector
...settings.selector,
};
const rules = this.rules;
Object.keys(rules).forEach(key => {
Object.keys(rules).forEach((key) => {
const rule = rules[key];
validateRule(rule);
});
this.expressions = (() => {
return Object.keys(rules).map(key => {
const rule = rules[key];
return getRegExp(rule);
});
})();
this.expressions = (() => Object.keys(rules).map((key) => {
const rule = rules[key];
return getRegExp(rule);
}))();
this.matched = -1;
this.loaded = true;
@ -171,7 +169,7 @@ this.AutoComplete = class {
setLoaded(val) {
if (val === this.loaded) {
return; //Don't cause redraws unnecessarily
return; // Don't cause redraws unnecessarily
}
this.loaded = val;
this.loadingDep.changed();
@ -179,7 +177,7 @@ this.AutoComplete = class {
onKeyUp() {
if (!this.$element) {
return; //Don't try to do this while loading
return; // Don't try to do this while loading
}
const startpos = this.element.selectionStart;
const val = this.getText().substring(0, startpos);
@ -223,23 +221,23 @@ this.AutoComplete = class {
return;
}
switch (e.keyCode) {
case 9: //TAB
case 13: //ENTER
if (this.select()) { //Don't jump fields or submit if select successful
case 9: // TAB
case 13: // ENTER
if (this.select()) { // Don't jump fields or submit if select successful
e.preventDefault();
e.stopPropagation();
}
break;
// preventDefault needed below to avoid moving cursor when selecting
case 40: //DOWN
case 40: // DOWN
e.preventDefault();
this.next();
break;
case 38: //UP
case 38: // UP
e.preventDefault();
this.prev();
break;
case 27: //ESCAPE
case 27: // ESCAPE
this.$element.blur();
this.hideList();
}
@ -270,7 +268,7 @@ this.AutoComplete = class {
filteredList() {
// @ruleDep.depend() # optional as long as we use depend on filter, because list will always get re-rendered
const filter = this.getFilter(); //Reactively depend on the filter
const filter = this.getFilter(); // Reactively depend on the filter
if (this.matched === -1) {
return null;
}
@ -317,7 +315,7 @@ this.AutoComplete = class {
}
const doc = Blaze.getData(node);
if (!doc) {
return false; //Don't select if nothing matched
return false; // Don't select if nothing matched
}
this.processSelection(doc, this.rules[this.matched]);
@ -392,10 +390,10 @@ this.AutoComplete = class {
if (rule && isWholeField(rule)) {
pos.left = position.left;
if (rule.doNotChangeWidth !== false) {
pos.width = this.$element.outerWidth(); //position.offsetWidth
pos.width = this.$element.outerWidth(); // position.offsetWidth
}
} else { //Normal positioning, at token word
} else { // Normal positioning, at token word
pos = { left: position.left + offset.left };
}
@ -427,22 +425,22 @@ this.AutoComplete = class {
const next = currentItem.next();
if (next.length) {
next.addClass('selected');
} else { //End of list or lost selection; Go back to first item
} else { // End of list or lost selection; Go back to first item
this.tmplInst.$(`${ this.selector.item }:first-child`).addClass('selected');
}
}
//Select previous item in list
// Select previous item in list
prev() {
const currentItem = this.tmplInst.$(`${ this.selector.item }.selected`);
if (!currentItem.length) {
return; //Don't try to iterate an empty list
return; // Don't try to iterate an empty list
}
currentItem.removeClass('selected');
const prev = currentItem.prev();
if (prev.length) {
prev.addClass('selected');
} else { //Beginning of list or lost selection; Go to end of list
} else { // Beginning of list or lost selection; Go to end of list
this.tmplInst.$(`${ this.selector.item }:last-child`).addClass('selected');
}
}

@ -14,7 +14,7 @@ const acEvents = {
},
'blur'(e, t) {
t.ac.onBlur(e);
}
},
};
Template.inputAutocomplete.events(acEvents);
@ -22,7 +22,7 @@ Template.inputAutocomplete.events(acEvents);
Template.textareaAutocomplete.events(acEvents);
const attributes = function() {
return _.omit(this, 'settings'); //Render all but the settings parameter
return _.omit(this, 'settings'); // Render all but the settings parameter
};
@ -41,7 +41,7 @@ const autocompleteHelpers = {
return Blaze.With(ac, function() { //eslint-disable-line
return Template._autocompleteContainer;
});
})
}),
};
Template.inputAutocomplete.helpers(autocompleteHelpers);
@ -69,7 +69,7 @@ Template._autocompleteContainer.events({
},
'mouseenter .-autocomplete-item'(e, t) {
t.data.onItemHover(this, e);
}
},
});
Template._autocompleteContainer.helpers({
@ -78,6 +78,6 @@ Template._autocompleteContainer.helpers({
},
noMatchTemplate() {
return this.matchedRule().noMatchTemplate || Template._noMatch;
}
},
});
export { acEvents, attributes, autocompleteHelpers };

@ -2,7 +2,7 @@ Package.describe({
name: 'mizzao:autocomplete',
summary: 'Client/server autocompletion designed for Meteor\'s collections and reactivity',
version: '0.5.1',
git: 'https://github.com/mizzao/meteor-autocomplete.git'
git: 'https://github.com/mizzao/meteor-autocomplete.git',
});
Package.onUse(function(api) {
@ -17,11 +17,11 @@ Package.onUse(function(api) {
'client/autocomplete.css',
'client/inputs.html',
'client/autocomplete-client.js',
'client/templates.js'
'client/templates.js',
], 'client');
api.addFiles([
'server/autocomplete-server.js'
'server/autocomplete-server.js',
], 'server');
api.export('Autocomplete', 'server');

@ -11,9 +11,9 @@ function reportError(error, callback) {
Meteor.loginWithPasswordAndTOTP = function(selector, password, code, callback) {
if (typeof selector === 'string') {
if (selector.indexOf('@') === -1) {
selector = {username: selector};
selector = { username: selector };
} else {
selector = {email: selector};
selector = { email: selector };
}
}
@ -22,10 +22,10 @@ Meteor.loginWithPasswordAndTOTP = function(selector, password, code, callback) {
totp: {
login: {
user: selector,
password: Accounts._hashPassword(password)
password: Accounts._hashPassword(password),
},
code
}
code,
},
}],
userCallback(error) {
if (error) {
@ -33,7 +33,7 @@ Meteor.loginWithPasswordAndTOTP = function(selector, password, code, callback) {
} else {
callback && callback();
}
}
},
});
};
@ -53,7 +53,7 @@ Meteor.loginWithPassword = function(email, password, cb) {
showCancelButton: true,
closeOnConfirm: true,
confirmButtonText: t('Verify'),
cancelButtonText: t('Cancel')
cancelButtonText: t('Cancel'),
}, (code) => {
if (code === false) {
return cb();

@ -27,7 +27,7 @@ Template.accountSecurity.helpers({
if (Template.instance().codesRemaining.get()) {
return t('You_have_n_codes_remaining', { number: Template.instance().codesRemaining.get() });
}
}
},
});
Template.accountSecurity.events({
@ -57,7 +57,7 @@ Template.accountSecurity.events({
showCancelButton: true,
closeOnConfirm: true,
confirmButtonText: t('Verify'),
cancelButtonText: t('Cancel')
cancelButtonText: t('Cancel'),
}, (code) => {
if (code === false) {
return;
@ -104,7 +104,7 @@ Template.accountSecurity.events({
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: t('Verify'),
cancelButtonText: t('Cancel')
cancelButtonText: t('Cancel'),
}, (code) => {
if (code === false) {
return;
@ -122,7 +122,7 @@ Template.accountSecurity.events({
}
});
});
}
},
});
Template.accountSecurity.onCreated(function() {
@ -135,14 +135,12 @@ Template.accountSecurity.onCreated(function() {
this.codesRemaining = new ReactiveVar();
this.showBackupCodes = (userCodes) => {
const backupCodes = userCodes.map((value, index) => {
return (index + 1) % 4 === 0 && index < 11 ? `${ value }\n` : `${ value } `;
}).join('');
const backupCodes = userCodes.map((value, index) => ((index + 1) % 4 === 0 && index < 11 ? `${ value }\n` : `${ value } `)).join('');
const codes = `<code class="text-center allow-text-selection">${ backupCodes }</code>`;
modal.open({
title: t('Backup_codes'),
text: `${ t('Make_sure_you_have_a_copy_of_your_codes', { codes }) }`,
html: true
html: true,
});
};

@ -3,7 +3,7 @@ Package.describe({
version: '0.0.1',
summary: '',
git: '',
documentation: 'README.md'
documentation: 'README.md',
});
Package.onUse(function(api) {
@ -13,7 +13,7 @@ Package.onUse(function(api) {
'templating',
'rocketchat:lib',
'sha',
'random'
'random',
]);
api.addFiles('client/accountSecurity.html', 'client');

@ -8,7 +8,7 @@ RocketChat.TOTP = {
generateOtpauthURL(secret, username) {
return speakeasy.otpauthURL({
secret: secret.ascii,
label: `Rocket.Chat:${ username }`
label: `Rocket.Chat:${ username }`,
});
},
@ -35,7 +35,7 @@ RocketChat.TOTP = {
secret,
encoding: 'base32',
token,
window: maxDelta
window: maxDelta,
});
return verifiedDelta !== undefined;
@ -44,7 +44,7 @@ RocketChat.TOTP = {
return speakeasy.totp.verify({
secret,
encoding: 'base32',
token
token,
});
},
@ -59,5 +59,5 @@ RocketChat.TOTP = {
}
return { codes, hashedCodes };
}
},
};

@ -22,7 +22,7 @@ RocketChat.callbacks.add('onValidateLogin', (login) => {
secret: login.user.services.totp.secret,
token: totp.code,
userId: login.user._id,
backupTokens: login.user.services.totp.hashedBackup
backupTokens: login.user.services.totp.hashedBackup,
});
if (verified !== true) {

@ -11,7 +11,7 @@ Meteor.methods({
}
return {
remaining: user.services.totp.hashedBackup.length
remaining: user.services.totp.hashedBackup.length,
};
}
},
});

@ -10,7 +10,7 @@ Meteor.methods({
secret: user.services.totp.secret,
token: code,
userId: Meteor.userId(),
backupTokens: user.services.totp.hashedBackup
backupTokens: user.services.totp.hashedBackup,
});
if (!verified) {
@ -18,5 +18,5 @@ Meteor.methods({
}
return RocketChat.models.Users.disable2FAByUserId(Meteor.userId());
}
},
});

@ -12,7 +12,7 @@ Meteor.methods({
return {
secret: secret.base32,
url: RocketChat.TOTP.generateOtpauthURL(secret, user.username)
url: RocketChat.TOTP.generateOtpauthURL(secret, user.username),
};
}
},
});

@ -14,7 +14,7 @@ Meteor.methods({
secret: user.services.totp.secret,
token: userToken,
userId: Meteor.userId(),
backupTokens: user.services.totp.hashedBackup
backupTokens: user.services.totp.hashedBackup,
});
if (verified) {
@ -23,5 +23,5 @@ Meteor.methods({
RocketChat.models.Users.update2FABackupCodesByUserId(Meteor.userId(), hashedCodes);
return { codes };
}
}
},
});

@ -12,7 +12,7 @@ Meteor.methods({
const verified = RocketChat.TOTP.verify({
secret: user.services.totp.tempSecret,
token: userToken
token: userToken,
});
if (verified) {
@ -21,5 +21,5 @@ Meteor.methods({
RocketChat.models.Users.enable2FAAndSetSecretAndCodesByUserId(Meteor.userId(), user.services.totp.tempSecret, hashedCodes);
return { codes };
}
}
},
});

@ -1,49 +1,49 @@
RocketChat.models.Users.disable2FAAndSetTempSecretByUserId = function(userId, tempToken) {
return this.update({
_id: userId
_id: userId,
}, {
$set: {
'services.totp': {
enabled: false,
tempSecret: tempToken
}
}
tempSecret: tempToken,
},
},
});
};
RocketChat.models.Users.enable2FAAndSetSecretAndCodesByUserId = function(userId, secret, backupCodes) {
return this.update({
_id: userId
_id: userId,
}, {
$set: {
'services.totp.enabled': true,
'services.totp.secret': secret,
'services.totp.hashedBackup': backupCodes
'services.totp.hashedBackup': backupCodes,
},
$unset: {
'services.totp.tempSecret': 1
}
'services.totp.tempSecret': 1,
},
});
};
RocketChat.models.Users.disable2FAByUserId = function(userId) {
return this.update({
_id: userId
_id: userId,
}, {
$set: {
'services.totp': {
enabled: false
}
}
enabled: false,
},
},
});
};
RocketChat.models.Users.update2FABackupCodesByUserId = function(userId, backupCodes) {
return this.update({
_id: userId
_id: userId,
}, {
$set: {
'services.totp.hashedBackup': backupCodes
}
'services.totp.hashedBackup': backupCodes,
},
});
};

@ -2,7 +2,7 @@ RocketChat.settings.addGroup('Accounts', function() {
this.section('Two Factor Authentication', function() {
this.add('Accounts_TwoFactorAuthentication_Enabled', true, {
type: 'boolean',
public: true
public: true,
});
this.add('Accounts_TwoFactorAuthentication_MaxDelta', 1, {
type: 'int',
@ -10,8 +10,8 @@ RocketChat.settings.addGroup('Accounts', function() {
i18nLabel: 'Accounts_TwoFactorAuthentication_MaxDelta',
enableQuery: {
_id: 'Accounts_TwoFactorAuthentication_Enabled',
value: true
}
value: true,
},
});
});
});

@ -2,13 +2,13 @@ Package.describe({
name: 'rocketchat:accounts',
version: '0.0.1',
summary: 'JS-Accounts integration',
git: ''
git: '',
});
Package.onUse(function(api) {
api.use([
'underscore',
'ecmascript'
'ecmascript',
]);
api.use('mongo', ['client', 'server']);
@ -18,5 +18,5 @@ Package.onUse(function(api) {
Npm.depends({
'@accounts/server': '0.0.18',
'@accounts/mongo': '0.0.12'
'@accounts/mongo': '0.0.12',
});

@ -7,18 +7,18 @@ Meteor.startup(() => {
const mongodb = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
const mongoAdapter = new MongoAdapter(mongodb, {
convertUserIdToMongoObjectId: false
convertUserIdToMongoObjectId: false,
});
AccountsServer.config({
tokenConfigs: {
accessToken: {
expiresIn: '3d'
expiresIn: '3d',
},
refreshToken: {
expiresIn: '30d'
}
expiresIn: '30d',
},
},
passwordHashAlgorithm: 'sha256'
passwordHashAlgorithm: 'sha256',
}, mongoAdapter);
});

@ -4,5 +4,5 @@ import AccountsServer from '@accounts/server';
export {
AccountsServer
AccountsServer,
};

@ -1,4 +1,4 @@
//Action Links namespace creation.
// Action Links namespace creation.
RocketChat.actionLinks = {
actions: {},
register(name, funct) {
@ -17,7 +17,7 @@ RocketChat.actionLinks = {
const subscription = RocketChat.models.Subscriptions.findOne({
rid: message.rid,
'u._id': userId
'u._id': userId,
});
if (!subscription) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { function: 'actionLinks.getMessage' });
@ -28,5 +28,5 @@ RocketChat.actionLinks = {
}
return message;
}
},
};

@ -10,7 +10,7 @@ Template.room.events({
return fireGlobalEvent('click-action-link', {
actionlink: $(event.currentTarget).data('actionlink'),
value: data._arguments[1]._id,
message: data._arguments[1]
message: data._arguments[1],
});
}
@ -21,5 +21,5 @@ Template.room.events({
}
});
}
}
},
});

@ -1,4 +1,4 @@
//Action Links Handler. This method will be called off the client.
// Action Links Handler. This method will be called off the client.
RocketChat.actionLinks.run = (name, messageId, instance) => {
const message = RocketChat.actionLinks.getMessage(name, messageId);

@ -2,7 +2,7 @@ Package.describe({
name: 'rocketchat:action-links',
version: '0.0.1',
summary: 'Add custom actions that call functions',
git: ''
git: '',
});
Package.onUse(function(api) {

@ -1,4 +1,4 @@
//Action Links Handler. This method will be called off the client.
// Action Links Handler. This method will be called off the client.
Meteor.methods({
actionLinkHandler(name, messageId) {
@ -11,5 +11,5 @@ Meteor.methods({
const actionLink = message.actionLinks[name];
RocketChat.actionLinks.actions[actionLink.method_id](message, actionLink.params);
}
},
});

@ -44,7 +44,7 @@ Template.body.onRendered(() => {
const addTrackers = JSON.parse(piwikAdditionalTracker);
for (let i = 0; i < addTrackers.length; i++) {
const tracker = addTrackers[i];
window._paq.push(['addTracker', `${ tracker['trackerURL'] }js/`, tracker['siteId']]);
window._paq.push(['addTracker', `${ tracker.trackerURL }js/`, tracker.siteId]);
}
}
} catch (e) {
@ -73,7 +73,7 @@ Template.body.onRendered(() => {
ga('create', googleId, 'auto');
ga('send', 'pageview');
/*eslint-enable */
/* eslint-enable */
}
}
});

@ -8,7 +8,7 @@ function trackEvent(category, action, label) {
}
if (!window._paq || window.ga) {
//Trigger the trackPageView manually as the page views are only loaded when the loadScript.js code is executed
// Trigger the trackPageView manually as the page views are only loaded when the loadScript.js code is executed
FlowRouter.triggers.enter([(route) => {
if (window._paq) {
const http = location.protocol;
@ -22,12 +22,12 @@ if (!window._paq || window.ga) {
}
}]);
//Login page has manual switches
// Login page has manual switches
RocketChat.callbacks.add('loginPageStateChange', (state) => {
trackEvent('Navigation', 'Login Page State Change', state);
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-login-state-change');
//Messsages
// Messsages
RocketChat.callbacks.add('afterSaveMessage', (message) => {
if ((window._paq || window.ga) && RocketChat.settings.get('Analytics_features_messages')) {
const room = ChatRoom.findOne({ _id: message.rid });
@ -35,7 +35,7 @@ if (!window._paq || window.ga) {
}
}, 2000, 'trackEvents');
//Rooms
// Rooms
RocketChat.callbacks.add('afterCreateChannel', (owner, room) => {
if (RocketChat.settings.get('Analytics_features_rooms')) {
trackEvent('Room', 'Create', `${ room.name } (${ room._id })`);
@ -78,8 +78,8 @@ if (!window._paq || window.ga) {
}
}, RocketChat.callbacks.priority.MEDIUM, 'analytics-unarchive-room');
//Users
//Track logins and associate user ids with piwik
// Users
// Track logins and associate user ids with piwik
(() => {
let oldUserId = null;

@ -2,15 +2,15 @@ Package.describe({
name: 'rocketchat:analytics',
version: '0.0.2',
summary: 'Analytics integeration for Rocket.Chat',
git: ''
git: '',
});
//Note: Piwik respects Google Chrome's No Track: http://piwik.org/docs/privacy/#step-4-respect-donottrack-preference
// Note: Piwik respects Google Chrome's No Track: http://piwik.org/docs/privacy/#step-4-respect-donottrack-preference
Package.onUse(function(api) {
api.use([ 'ecmascript', 'rocketchat:lib' ]);
api.use([ 'templating', 'kadira:flow-router'], 'client');
api.use(['ecmascript', 'rocketchat:lib']);
api.use(['templating', 'kadira:flow-router'], 'client');
api.addFiles([ 'client/loadScript.js', 'client/trackEvents.js' ], 'client');
api.addFiles([ 'server/settings.js' ], 'server');
api.addFiles(['client/loadScript.js', 'client/trackEvents.js'], 'client');
api.addFiles(['server/settings.js'], 'server');
});

@ -1,64 +1,64 @@
RocketChat.settings.addGroup('Analytics', function addSettings() {
this.section('Piwik', function() {
const enableQuery = {_id: 'PiwikAnalytics_enabled', value: true};
const enableQuery = { _id: 'PiwikAnalytics_enabled', value: true };
this.add('PiwikAnalytics_enabled', false, {
type: 'boolean',
public: true,
i18nLabel: 'Enable'
i18nLabel: 'Enable',
});
this.add('PiwikAnalytics_url', '', {
type: 'string',
public: true,
i18nLabel: 'URL',
enableQuery
enableQuery,
});
this.add('PiwikAnalytics_siteId', '', {
type: 'string',
public: true,
i18nLabel: 'Client_ID',
enableQuery
enableQuery,
});
this.add('PiwikAdditionalTrackers', '', {
type: 'string',
multiline: true,
public: true,
i18nLabel: 'PiwikAdditionalTrackers',
enableQuery
enableQuery,
});
this.add('PiwikAnalytics_prependDomain', false, {
type: 'boolean',
public: true,
i18nLabel: 'PiwikAnalytics_prependDomain',
enableQuery
enableQuery,
});
this.add('PiwikAnalytics_cookieDomain', false, {
type: 'boolean',
public: true,
i18nLabel: 'PiwikAnalytics_cookieDomain',
enableQuery
enableQuery,
});
this.add('PiwikAnalytics_domains', '', {
type: 'string',
multiline: true,
public: true,
i18nLabel: 'PiwikAnalytics_domains',
enableQuery
enableQuery,
});
});
this.section('Analytics_Google', function() {
const enableQuery = {_id: 'GoogleAnalytics_enabled', value: true};
const enableQuery = { _id: 'GoogleAnalytics_enabled', value: true };
this.add('GoogleAnalytics_enabled', false, {
type: 'boolean',
public: true,
i18nLabel: 'Enable'
i18nLabel: 'Enable',
});
this.add('GoogleAnalytics_ID', '', {
type: 'string',
public: true,
i18nLabel: 'Analytics_Google_id',
enableQuery
enableQuery,
});
});
@ -67,19 +67,19 @@ RocketChat.settings.addGroup('Analytics', function addSettings() {
type: 'boolean',
public: true,
i18nLabel: 'Messages',
i18nDescription: 'Analytics_features_messages_Description'
i18nDescription: 'Analytics_features_messages_Description',
});
this.add('Analytics_features_rooms', true, {
type: 'boolean',
public: true,
i18nLabel: 'Rooms',
i18nDescription: 'Analytics_features_rooms_Description'
i18nDescription: 'Analytics_features_rooms_Description',
});
this.add('Analytics_features_users', true, {
type: 'boolean',
public: true,
i18nLabel: 'Users',
i18nDescription: 'Analytics_features_users_Description'
i18nDescription: 'Analytics_features_users_Description',
});
});
});

@ -2,20 +2,20 @@ Package.describe({
name: 'rocketchat:api',
version: '0.0.1',
summary: 'Rest API',
git: ''
git: '',
});
Package.onUse(function(api) {
api.use([
'ecmascript',
'rocketchat:lib',
'nimble:restivus'
'nimble:restivus',
]);
api.addFiles('server/api.js', 'server');
api.addFiles('server/settings.js', 'server');
//Register helpers
// Register helpers
api.addFiles('server/helpers/requestParams.js', 'server');
api.addFiles('server/helpers/getPaginationItems.js', 'server');
api.addFiles('server/helpers/getUserFromParams.js', 'server');
@ -26,10 +26,10 @@ Package.onUse(function(api) {
api.addFiles('server/helpers/getLoggedInUser.js', 'server');
api.addFiles('server/helpers/insertUserObject.js', 'server');
//Add default routes
// Add default routes
api.addFiles('server/default/info.js', 'server');
//Add v1 routes
// Add v1 routes
api.addFiles('server/v1/channels.js', 'server');
api.addFiles('server/v1/roles.js', 'server');
api.addFiles('server/v1/rooms.js', 'server');

@ -10,7 +10,7 @@ class API extends Restivus {
this.defaultFieldsToExclude = {
joinCode: 0,
members: 0,
importIds: 0
importIds: 0,
};
this.limitedUserFieldsToExclude = {
avatarOrigin: 0,
@ -26,10 +26,10 @@ class API extends Restivus {
statusDefault: 0,
_updatedAt: 0,
customFields: 0,
settings: 0
settings: 0,
};
this.limitedUserFieldsToExcludeIfIsPrivilegedUser = {
services: 0
services: 0,
};
this._config.defaultOptionsEndpoint = function _defaultOptionsEndpoint() {
@ -37,7 +37,7 @@ class API extends Restivus {
if (RocketChat.settings.get('API_Enable_CORS') === true) {
this.response.writeHead(200, {
'Access-Control-Allow-Origin': RocketChat.settings.get('API_CORS_Origin'),
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-User-Id, X-Auth-Token'
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-User-Id, X-Auth-Token',
});
} else {
this.response.writeHead(405);
@ -74,7 +74,7 @@ class API extends Restivus {
result = {
statusCode: 200,
body: result
body: result,
};
logger.debug('Success', result);
@ -89,7 +89,7 @@ class API extends Restivus {
result = {
success: false,
error: result,
stack
stack,
};
if (errorType) {
@ -99,7 +99,7 @@ class API extends Restivus {
result = {
statusCode: 400,
body: result
body: result,
};
logger.debug('Failure', result);
@ -112,8 +112,8 @@ class API extends Restivus {
statusCode: 404,
body: {
success: false,
error: msg ? msg : 'Resource not found'
}
error: msg ? msg : 'Resource not found',
},
};
}
@ -122,19 +122,19 @@ class API extends Restivus {
statusCode: 403,
body: {
success: false,
error: msg ? msg : 'unauthorized'
}
error: msg ? msg : 'unauthorized',
},
};
}
addRoute(routes, options, endpoints) {
//Note: required if the developer didn't provide options
// Note: required if the developer didn't provide options
if (typeof endpoints === 'undefined') {
endpoints = options;
options = {};
}
//Allow for more than one route using the same option and endpoints
// Allow for more than one route using the same option and endpoints
if (!_.isArray(routes)) {
routes = [routes];
}
@ -142,20 +142,20 @@ class API extends Restivus {
const version = this._config.version;
routes.forEach((route) => {
//Note: This is required due to Restivus calling `addRoute` in the constructor of itself
// Note: This is required due to Restivus calling `addRoute` in the constructor of itself
Object.keys(endpoints).forEach((method) => {
if (typeof endpoints[method] === 'function') {
endpoints[method] = { action: endpoints[method] };
}
//Add a try/catch for each endpoint
// Add a try/catch for each endpoint
const originalAction = endpoints[method].action;
endpoints[method].action = function _internalRouteActionHandler() {
const rocketchatRestApiEnd = RocketChat.metrics.rocketchatRestApi.startTimer({
method,
version,
user_agent: this.request.headers['user-agent'],
entrypoint: route
entrypoint: route,
});
logger.debug(`${ this.request.method.toUpperCase() }: ${ this.request.url }`);
@ -170,7 +170,7 @@ class API extends Restivus {
result = result || RocketChat.API.v1.success();
rocketchatRestApiEnd({
status: result.statusCode
status: result.statusCode,
});
return result;
@ -182,7 +182,7 @@ class API extends Restivus {
}
}
//Allow the endpoints to make usage of the logger which respects the user's settings
// Allow the endpoints to make usage of the logger which respects the user's settings
endpoints[method].logger = logger;
});
@ -193,7 +193,7 @@ class API extends Restivus {
_initAuth() {
const loginCompatibility = (bodyParams) => {
// Grab the username or email that the user is logging in with
const {user, username, email, password, code} = bodyParams;
const { user, username, email, password, code } = bodyParams;
if (password == null) {
return bodyParams;
@ -204,15 +204,15 @@ class API extends Restivus {
}
const auth = {
password
password,
};
if (typeof user === 'string') {
auth.user = user.includes('@') ? {email: user} : {username: user};
auth.user = user.includes('@') ? { email: user } : { username: user };
} else if (username) {
auth.user = {username};
auth.user = { username };
} else if (email) {
auth.user = {email};
auth.user = { email };
}
if (auth.user == null) {
@ -222,7 +222,7 @@ class API extends Restivus {
if (auth.password.hashed) {
auth.password = {
digest: auth.password,
algorithm: 'sha-256'
algorithm: 'sha-256',
};
}
@ -230,8 +230,8 @@ class API extends Restivus {
return {
totp: {
code,
login: auth
}
login: auth,
},
};
}
@ -240,15 +240,15 @@ class API extends Restivus {
const self = this;
this.addRoute('login', {authRequired: false}, {
this.addRoute('login', { authRequired: false }, {
post() {
const args = loginCompatibility(this.bodyParams);
const getUserInfo = self.getHelperMethod('getUserInfo');
const invocation = new DDPCommon.MethodInvocation({
connection: {
close() {}
}
close() {},
},
});
let auth;
@ -259,7 +259,7 @@ class API extends Restivus {
if (error.reason === 'User not found') {
e = {
error: 'Unauthorized',
reason: 'Unauthorized'
reason: 'Unauthorized',
};
}
@ -268,13 +268,13 @@ class API extends Restivus {
body: {
status: 'error',
error: e.error,
message: e.reason || e.message
}
message: e.reason || e.message,
},
};
}
this.user = Meteor.users.findOne({
_id: auth.id
_id: auth.id,
});
this.userId = this.user._id;
@ -282,11 +282,11 @@ class API extends Restivus {
// Remove tokenExpires to keep the old behavior
Meteor.users.update({
_id: this.user._id,
'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(auth.token)
'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(auth.token),
}, {
$unset: {
'services.resume.loginTokens.$.when': 1
}
'services.resume.loginTokens.$.when': 1,
},
});
const response = {
@ -294,20 +294,20 @@ class API extends Restivus {
data: {
userId: this.userId,
authToken: auth.token,
me: getUserInfo(this.user)
}
me: getUserInfo(this.user),
},
};
const extraData = self._config.onLoggedIn && self._config.onLoggedIn.call(this);
if (extraData != null) {
_.extend(response.data, {
extra: extraData
extra: extraData,
});
}
return response;
}
},
});
const logout = function() {
@ -324,21 +324,21 @@ class API extends Restivus {
tokenRemovalQuery[tokenPath] = tokenToRemove;
Meteor.users.update(this.user._id, {
$pull: tokenRemovalQuery
$pull: tokenRemovalQuery,
});
const response = {
status: 'success',
data: {
message: 'You\'ve been logged out!'
}
message: 'You\'ve been logged out!',
},
};
// Call the logout hook with the authenticated user attached
const extraData = self._config.onLoggedOut && self._config.onLoggedOut.call(this);
if (extraData != null) {
_.extend(response.data, {
extra: extraData
extra: extraData,
});
}
return response;
@ -350,14 +350,14 @@ class API extends Restivus {
adding hook).
*/
return this.addRoute('logout', {
authRequired: true
authRequired: true,
}, {
get() {
console.warn('Warning: Default logout via GET will be removed in Restivus v1.0. Use POST instead.');
console.warn(' See https://github.com/kahmali/meteor-restivus/issues/100');
return logout.call(this);
},
post: logout
post: logout,
});
}
}
@ -389,16 +389,16 @@ const getUserAuth = function _getUserAuth() {
return {
userId: this.request.headers['x-user-id'],
token
token,
};
}
},
};
};
RocketChat.API = {
helperMethods: new Map(),
getUserAuth,
ApiClass: API
ApiClass: API,
};
const createApi = function _createApi(enableCors) {
@ -408,7 +408,7 @@ const createApi = function _createApi(enableCors) {
useDefaultAuth: true,
prettyJson: process.env.NODE_ENV === 'development',
enableCors,
auth: getUserAuth()
auth: getUserAuth(),
});
}
@ -417,7 +417,7 @@ const createApi = function _createApi(enableCors) {
useDefaultAuth: true,
prettyJson: process.env.NODE_ENV === 'development',
enableCors,
auth: getUserAuth()
auth: getUserAuth(),
});
}
};

@ -4,12 +4,12 @@ RocketChat.API.default.addRoute('info', { authRequired: false }, {
if (user && RocketChat.authz.hasRole(user._id, 'admin')) {
return RocketChat.API.v1.success({
info: RocketChat.Info
info: RocketChat.Info,
});
}
return RocketChat.API.v1.success({
version: RocketChat.Info.version
version: RocketChat.Info.version,
});
}
},
});

@ -4,7 +4,7 @@ RocketChat.API.helperMethods.set('deprecationWarning', function _deprecationWarn
if (process.env.NODE_ENV === 'development') {
return {
warning: warningMessage,
...response
...response,
};
}

@ -3,8 +3,8 @@ RocketChat.API.helperMethods.set('getLoggedInUser', function _getLoggedInUser()
if (this.request.headers['x-auth-token'] && this.request.headers['x-user-id']) {
user = RocketChat.models.Users.findOne({
'_id': this.request.headers['x-user-id'],
'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(this.request.headers['x-auth-token'])
_id: this.request.headers['x-user-id'],
'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(this.request.headers['x-auth-token']),
});
}

@ -25,6 +25,6 @@ RocketChat.API.helperMethods.set('getPaginationItems', function _getPaginationIt
return {
offset,
count
count,
};
});

@ -1,4 +1,4 @@
//Convenience method, almost need to turn it into a middleware of sorts
// Convenience method, almost need to turn it into a middleware of sorts
RocketChat.API.helperMethods.set('getUserFromParams', function _getUserFromParams() {
const doesntExist = { _doesntExist: true };
let user;

@ -11,7 +11,7 @@ const getInfoFromUserObject = (user) => {
language,
roles,
settings,
customFields
customFields,
} = user;
return {
_id,
@ -25,7 +25,7 @@ const getInfoFromUserObject = (user) => {
language,
roles,
settings,
customFields
customFields,
};
};
@ -51,7 +51,7 @@ RocketChat.API.helperMethods.set('getUserInfo', function _getUserInfo(user) {
const verifiedEmail = isVerifiedEmail();
me.email = verifiedEmail ? verifiedEmail.address : undefined;
me.settings = {
preferences: getUserPreferences()
preferences: getUserPreferences(),
};
return me;

@ -5,7 +5,7 @@ RocketChat.API.helperMethods.set('insertUserObject', function _addUserToObject({
object.user = {
_id: userId,
username: user.username,
name: user.name
name: user.name,
};
}

@ -75,6 +75,6 @@ RocketChat.API.helperMethods.set('parseJsonQuery', function _parseJsonQuery() {
return {
sort,
fields,
query
query,
};
});

@ -1,6 +1,6 @@
import _ from 'underscore';
//Returns the channel IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property
// Returns the channel IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property
function findChannelByIdOrName({ params, checkedArchived = true }) {
if ((!params.roomId || !params.roomId.trim()) && (!params.roomName || !params.roomName.trim())) {
throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" or "roomName" is required');
@ -35,9 +35,9 @@ RocketChat.API.v1.addRoute('channels.addAll', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.addModerator', { authRequired: true }, {
@ -51,7 +51,7 @@ RocketChat.API.v1.addRoute('channels.addModerator', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.addOwner', { authRequired: true }, {
@ -65,7 +65,7 @@ RocketChat.API.v1.addRoute('channels.addOwner', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.archive', { authRequired: true }, {
@ -77,7 +77,7 @@ RocketChat.API.v1.addRoute('channels.archive', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.close', { authRequired: true }, {
@ -99,7 +99,7 @@ RocketChat.API.v1.addRoute('channels.close', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, {
@ -123,7 +123,7 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, {
}
const room = findChannelByIdOrName({
params: this.requestParams(),
returnUsernames: true
returnUsernames: true,
});
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(room._id, user);
const lm = room.lm ? room.lm : room._updatedAt;
@ -148,9 +148,9 @@ RocketChat.API.v1.addRoute('channels.counters', { authRequired: true }, {
unreadsFrom,
msgs,
latest,
userMentions
userMentions,
});
}
},
});
// Channel -> create
@ -185,14 +185,14 @@ function createChannel(userId, params) {
});
return {
channel: RocketChat.models.Rooms.findOneById(id.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(id.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
};
}
RocketChat.API.channels = {};
RocketChat.API.channels.create = {
validate: createChannelValidator,
execute: createChannel
execute: createChannel,
};
RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, {
@ -205,16 +205,16 @@ RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, {
try {
RocketChat.API.channels.create.validate({
user: {
value: userId
value: userId,
},
name: {
value: bodyParams.name,
key: 'name'
key: 'name',
},
members: {
value: bodyParams.members,
key: 'members'
}
key: 'members',
},
});
} catch (e) {
if (e.message === 'unauthorized') {
@ -229,7 +229,7 @@ RocketChat.API.v1.addRoute('channels.create', { authRequired: true }, {
}
return RocketChat.API.v1.success(RocketChat.API.channels.create.execute(userId, bodyParams));
}
},
});
RocketChat.API.v1.addRoute('channels.delete', { authRequired: true }, {
@ -241,9 +241,9 @@ RocketChat.API.v1.addRoute('channels.delete', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: findResult
channel: findResult,
});
}
},
});
RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, {
@ -269,7 +269,7 @@ RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
@ -277,9 +277,9 @@ RocketChat.API.v1.addRoute('channels.files', { authRequired: true }, {
count:
files.length,
offset,
total: RocketChat.models.Uploads.find(ourQuery).count()
total: RocketChat.models.Uploads.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, {
@ -296,12 +296,12 @@ RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, {
}
let ourQuery = {
channel: `#${ findResult.name }`
channel: `#${ findResult.name }`,
};
if (includeAllPublicChannels) {
ourQuery.channel = {
$in: [ourQuery.channel, 'all_public_channels']
$in: [ourQuery.channel, 'all_public_channels'],
};
}
@ -314,16 +314,16 @@ RocketChat.API.v1.addRoute('channels.getIntegrations', { authRequired: true }, {
sort: sort ? sort : { _createdAt: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
integrations,
count: integrations.length,
offset,
total: RocketChat.models.Integrations.find(ourQuery).count()
total: RocketChat.models.Integrations.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, {
@ -363,7 +363,7 @@ RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, {
oldest: oldestDate,
inclusive,
count,
unreads
unreads,
});
});
@ -372,7 +372,7 @@ RocketChat.API.v1.addRoute('channels.history', { authRequired: true }, {
}
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute('channels.info', { authRequired: true }, {
@ -380,9 +380,9 @@ RocketChat.API.v1.addRoute('channels.info', { authRequired: true }, {
const findResult = findChannelByIdOrName({ params: this.requestParams(), checkedArchived: false });
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.invite', { authRequired: true }, {
@ -396,9 +396,9 @@ RocketChat.API.v1.addRoute('channels.invite', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.join', { authRequired: true }, {
@ -410,9 +410,9 @@ RocketChat.API.v1.addRoute('channels.join', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.kick', { authRequired: true }, {
@ -426,9 +426,9 @@ RocketChat.API.v1.addRoute('channels.kick', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.leave', { authRequired: true }, {
@ -440,14 +440,14 @@ RocketChat.API.v1.addRoute('channels.leave', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, {
get: {
//This is defined as such only to provide an example of how the routes can be defined :X
// This is defined as such only to provide an example of how the routes can be defined :X
action() {
const { offset, count } = this.getPaginationItems();
const { sort, fields, query } = this.parseJsonQuery();
@ -459,7 +459,7 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, {
if (!RocketChat.authz.hasPermission(this.userId, 'view-joined-room')) {
return RocketChat.API.v1.unauthorized();
}
const roomIds = RocketChat.models.Subscriptions.findByUserIdAndType(this.userId, 'c', { fields: { rid: 1 } }).fetch().map(s => s.rid);
const roomIds = RocketChat.models.Subscriptions.findByUserIdAndType(this.userId, 'c', { fields: { rid: 1 } }).fetch().map((s) => s.rid);
ourQuery._id = { $in: roomIds };
}
@ -467,7 +467,7 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
});
const total = cursor.count();
@ -478,10 +478,10 @@ RocketChat.API.v1.addRoute('channels.list', { authRequired: true }, {
channels: rooms,
count: rooms.length,
offset,
total
total,
});
}
}
},
},
});
RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, {
@ -494,7 +494,7 @@ RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
});
const totalCount = cursor.count();
@ -504,16 +504,16 @@ RocketChat.API.v1.addRoute('channels.list.joined', { authRequired: true }, {
channels: rooms,
offset,
count: rooms.length,
total: totalCount
total: totalCount,
});
}
},
});
RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, {
get() {
const findResult = findChannelByIdOrName({
params: this.requestParams(),
checkedArchived: false
checkedArchived: false,
});
if (findResult.broadcast && !RocketChat.authz.hasPermission(this.userId, 'view-broadcast-member-list')) {
@ -527,39 +527,39 @@ RocketChat.API.v1.addRoute('channels.members', { authRequired: true }, {
fields: { 'u._id': 1 },
sort: { 'u.username': sort.username != null ? sort.username : 1 },
skip: offset,
limit: count
limit: count,
});
const total = subscriptions.count();
const members = subscriptions.fetch().map(s => s.u && s.u._id);
const members = subscriptions.fetch().map((s) => s.u && s.u._id);
const users = RocketChat.models.Users.find({ _id: { $in: members } }, {
fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 },
sort: { username: sort.username != null ? sort.username : 1 }
sort: { username: sort.username != null ? sort.username : 1 },
}).fetch();
return RocketChat.API.v1.success({
members: users,
count: users.length,
offset,
total
total,
});
}
},
});
RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, {
get() {
const findResult = findChannelByIdOrName({
params: this.requestParams(),
checkedArchived: false
checkedArchived: false,
});
const { offset, count } = this.getPaginationItems();
const { sort, fields, query } = this.parseJsonQuery();
const ourQuery = Object.assign({}, query, { rid: findResult._id });
//Special check for the permissions
// Special check for the permissions
if (RocketChat.authz.hasPermission(this.userId, 'view-joined-room') && !RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(findResult._id, this.userId, { fields: { _id: 1 } })) {
return RocketChat.API.v1.unauthorized();
}
@ -571,7 +571,7 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, {
sort: sort ? sort : { ts: -1 },
skip: offset,
limit: count,
fields
fields,
});
const total = cursor.count();
@ -581,9 +581,9 @@ RocketChat.API.v1.addRoute('channels.messages', { authRequired: true }, {
messages,
count: messages.length,
offset,
total
total,
});
}
},
});
// TODO: CACHE: I dont like this method( functionality and how we implemented ) its very expensive
// TODO check if this code is better or not
@ -626,24 +626,24 @@ RocketChat.API.v1.addRoute('channels.online', { authRequired: true }, {
}
const online = RocketChat.models.Users.findUsersNotOffline({
fields: { username: 1 }
fields: { username: 1 },
}).fetch();
const onlineInRoom = [];
online.forEach(user => {
online.forEach((user) => {
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(root._id, user._id, { fields: { _id: 1 } });
if (subscription) {
onlineInRoom.push({
_id: user._id,
username: user.username
username: user.username,
});
}
});
return RocketChat.API.v1.success({
online: onlineInRoom
online: onlineInRoom,
});
}
},
});
RocketChat.API.v1.addRoute('channels.open', { authRequired: true }, {
@ -665,7 +665,7 @@ RocketChat.API.v1.addRoute('channels.open', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.removeModerator', { authRequired: true }, {
@ -679,7 +679,7 @@ RocketChat.API.v1.addRoute('channels.removeModerator', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.removeOwner', { authRequired: true }, {
@ -693,7 +693,7 @@ RocketChat.API.v1.addRoute('channels.removeOwner', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.rename', { authRequired: true }, {
@ -713,9 +713,9 @@ RocketChat.API.v1.addRoute('channels.rename', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.setCustomFields', { authRequired: true }, {
@ -731,9 +731,9 @@ RocketChat.API.v1.addRoute('channels.setCustomFields', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.setDefault', { authRequired: true }, {
@ -753,9 +753,9 @@ RocketChat.API.v1.addRoute('channels.setDefault', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.setDescription', { authRequired: true }, {
@ -775,9 +775,9 @@ RocketChat.API.v1.addRoute('channels.setDescription', { authRequired: true }, {
});
return RocketChat.API.v1.success({
description: this.bodyParams.description
description: this.bodyParams.description,
});
}
},
});
RocketChat.API.v1.addRoute('channels.setJoinCode', { authRequired: true }, {
@ -793,9 +793,9 @@ RocketChat.API.v1.addRoute('channels.setJoinCode', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.setPurpose', { authRequired: true }, {
@ -815,9 +815,9 @@ RocketChat.API.v1.addRoute('channels.setPurpose', { authRequired: true }, {
});
return RocketChat.API.v1.success({
purpose: this.bodyParams.purpose
purpose: this.bodyParams.purpose,
});
}
},
});
RocketChat.API.v1.addRoute('channels.setReadOnly', { authRequired: true }, {
@ -837,9 +837,9 @@ RocketChat.API.v1.addRoute('channels.setReadOnly', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.setTopic', { authRequired: true }, {
@ -859,9 +859,9 @@ RocketChat.API.v1.addRoute('channels.setTopic', { authRequired: true }, {
});
return RocketChat.API.v1.success({
topic: this.bodyParams.topic
topic: this.bodyParams.topic,
});
}
},
});
RocketChat.API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, {
@ -877,9 +877,9 @@ RocketChat.API.v1.addRoute('channels.setAnnouncement', { authRequired: true }, {
});
return RocketChat.API.v1.success({
announcement: this.bodyParams.announcement
announcement: this.bodyParams.announcement,
});
}
},
});
RocketChat.API.v1.addRoute('channels.setType', { authRequired: true }, {
@ -899,9 +899,9 @@ RocketChat.API.v1.addRoute('channels.setType', { authRequired: true }, {
});
return RocketChat.API.v1.success({
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude })
channel: RocketChat.models.Rooms.findOneById(findResult._id, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('channels.unarchive', { authRequired: true }, {
@ -917,7 +917,7 @@ RocketChat.API.v1.addRoute('channels.unarchive', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequired: true }, {
@ -935,22 +935,22 @@ RocketChat.API.v1.addRoute('channels.getAllUserMentionsByChannel', { authRequire
options: {
sort: sort ? sort : { ts: 1 },
skip: offset,
limit: count
}
limit: count,
},
}));
const allMentions = Meteor.runAsUser(this.userId, () => Meteor.call('getUserMentionsByChannel', {
roomId,
options: {}
options: {},
}));
return RocketChat.API.v1.success({
mentions,
count: mentions.length,
offset,
total: allMentions.length
total: allMentions.length,
});
}
},
});
RocketChat.API.v1.addRoute('channels.roles', { authRequired: true }, {
@ -960,7 +960,7 @@ RocketChat.API.v1.addRoute('channels.roles', { authRequired: true }, {
const roles = Meteor.runAsUser(this.userId, () => Meteor.call('getRoomRoles', findResult._id));
return RocketChat.API.v1.success({
roles
roles,
});
}
},
});

@ -5,7 +5,7 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, {
check(this.bodyParams, Match.ObjectIncluding({
msgId: String,
roomId: String,
asUser: Match.Maybe(Boolean)
asUser: Match.Maybe(Boolean),
}));
const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 } });
@ -29,9 +29,9 @@ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, {
return RocketChat.API.v1.success({
_id: msg._id,
ts: Date.now(),
message: msg
message: msg,
});
}
},
});
RocketChat.API.v1.addRoute('chat.syncMessages', { authRequired: true }, {
@ -58,9 +58,9 @@ RocketChat.API.v1.addRoute('chat.syncMessages', { authRequired: true }, {
}
return RocketChat.API.v1.success({
result
result,
});
}
},
});
RocketChat.API.v1.addRoute('chat.getMessage', { authRequired: true }, {
@ -79,9 +79,9 @@ RocketChat.API.v1.addRoute('chat.getMessage', { authRequired: true }, {
}
return RocketChat.API.v1.success({
message: msg
message: msg,
});
}
},
});
RocketChat.API.v1.addRoute('chat.pinMessage', { authRequired: true }, {
@ -100,9 +100,9 @@ RocketChat.API.v1.addRoute('chat.pinMessage', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => pinnedMessage = Meteor.call('pinMessage', msg));
return RocketChat.API.v1.success({
message: pinnedMessage
message: pinnedMessage,
});
}
},
});
RocketChat.API.v1.addRoute('chat.postMessage', { authRequired: true }, {
@ -116,9 +116,9 @@ RocketChat.API.v1.addRoute('chat.postMessage', { authRequired: true }, {
return RocketChat.API.v1.success({
ts: Date.now(),
channel: messageReturn.channel,
message: messageReturn.message
message: messageReturn.message,
});
}
},
});
RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, {
@ -138,9 +138,9 @@ RocketChat.API.v1.addRoute('chat.search', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => result = Meteor.call('messageSearch', searchText, roomId, count).message.docs);
return RocketChat.API.v1.success({
messages: result
messages: result,
});
}
},
});
// The difference between `chat.postMessage` and `chat.sendMessage` is that `chat.sendMessage` allows
@ -156,9 +156,9 @@ RocketChat.API.v1.addRoute('chat.sendMessage', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => message = Meteor.call('sendMessage', this.bodyParams.message));
return RocketChat.API.v1.success({
message
message,
});
}
},
});
RocketChat.API.v1.addRoute('chat.starMessage', { authRequired: true }, {
@ -176,11 +176,11 @@ RocketChat.API.v1.addRoute('chat.starMessage', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('starMessage', {
_id: msg._id,
rid: msg.rid,
starred: true
starred: true,
}));
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('chat.unPinMessage', { authRequired: true }, {
@ -198,7 +198,7 @@ RocketChat.API.v1.addRoute('chat.unPinMessage', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('unpinMessage', msg));
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('chat.unStarMessage', { authRequired: true }, {
@ -216,11 +216,11 @@ RocketChat.API.v1.addRoute('chat.unStarMessage', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('starMessage', {
_id: msg._id,
rid: msg.rid,
starred: false
starred: false,
}));
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, {
@ -228,12 +228,12 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, {
check(this.bodyParams, Match.ObjectIncluding({
roomId: String,
msgId: String,
text: String //Using text to be consistant with chat.postMessage
text: String, // Using text to be consistant with chat.postMessage
}));
const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId);
//Ensure the message exists
// Ensure the message exists
if (!msg) {
return RocketChat.API.v1.failure(`No message found with the id of "${ this.bodyParams.msgId }".`);
}
@ -242,15 +242,15 @@ RocketChat.API.v1.addRoute('chat.update', { authRequired: true }, {
return RocketChat.API.v1.failure('The room id provided does not match where the message is from.');
}
//Permission checks are already done in the updateMessage method, so no need to duplicate them
// Permission checks are already done in the updateMessage method, so no need to duplicate them
Meteor.runAsUser(this.userId, () => {
Meteor.call('updateMessage', { _id: msg._id, msg: this.bodyParams.text, rid: msg.rid });
});
return RocketChat.API.v1.success({
message: RocketChat.models.Messages.findOneById(msg._id)
message: RocketChat.models.Messages.findOneById(msg._id),
});
}
},
});
RocketChat.API.v1.addRoute('chat.react', { authRequired: true }, {
@ -274,7 +274,7 @@ RocketChat.API.v1.addRoute('chat.react', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('setReaction', emoji, msg._id, this.bodyParams.shouldReact));
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('chat.getMessageReadReceipts', { authRequired: true }, {
@ -282,21 +282,21 @@ RocketChat.API.v1.addRoute('chat.getMessageReadReceipts', { authRequired: true }
const { messageId } = this.queryParams;
if (!messageId) {
return RocketChat.API.v1.failure({
error: 'The required \'messageId\' param is missing.'
error: 'The required \'messageId\' param is missing.',
});
}
try {
const messageReadReceipts = Meteor.runAsUser(this.userId, () => Meteor.call('getReadReceipts', { messageId }));
return RocketChat.API.v1.success({
receipts: messageReadReceipts
receipts: messageReadReceipts,
});
} catch (error) {
return RocketChat.API.v1.failure({
error: error.message
error: error.message,
});
}
}
},
});
RocketChat.API.v1.addRoute('chat.reportMessage', { authRequired: true }, {
@ -313,7 +313,7 @@ RocketChat.API.v1.addRoute('chat.reportMessage', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('reportMessage', messageId, description));
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('chat.ignoreUser', { authRequired: true }, {
@ -334,5 +334,5 @@ RocketChat.API.v1.addRoute('chat.ignoreUser', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('ignoreUser', { rid, userId, ignore }));
return RocketChat.API.v1.success();
}
},
});

@ -13,7 +13,7 @@ RocketChat.API.v1.addRoute('commands.get', { authRequired: true }, {
}
return RocketChat.API.v1.success({ command: cmd });
}
},
});
RocketChat.API.v1.addRoute('commands.list', { authRequired: true }, {
@ -32,16 +32,16 @@ RocketChat.API.v1.addRoute('commands.list', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
});
return RocketChat.API.v1.success({
commands,
offset,
count: commands.length,
total: totalCount
total: totalCount,
});
}
},
});
// Expects a body of: { command: 'gimme', params: 'any string value', roomId: 'value' }
@ -77,12 +77,12 @@ RocketChat.API.v1.addRoute('commands.run', { authRequired: true }, {
result = RocketChat.slashCommands.run(cmd, params, {
_id: Random.id(),
rid: body.roomId,
msg: `/${ cmd } ${ params }`
msg: `/${ cmd } ${ params }`,
});
});
return RocketChat.API.v1.success({ result });
}
},
});
RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, {
@ -160,5 +160,5 @@ RocketChat.API.v1.addRoute('commands.preview', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});

@ -3,5 +3,5 @@ RocketChat.API.v1.addRoute('emoji-custom', { authRequired: true }, {
const emojis = Meteor.call('listEmojiCustom');
return RocketChat.API.v1.success({ emojis });
}
},
});

@ -1,6 +1,6 @@
import _ from 'underscore';
//Returns the private group subscription IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property
// Returns the private group subscription IF found otherwise it will return the failure of why it didn't. Check the `statusCode` property
function findPrivateGroupByIdOrName({ params, userId, checkedArchived = true }) {
if ((!params.roomId || !params.roomId.trim()) && (!params.roomName || !params.roomName.trim())) {
throw new Meteor.Error('error-room-param-not-provided', 'The parameter "roomId" or "roomName" is required');
@ -33,9 +33,9 @@ RocketChat.API.v1.addRoute('groups.addAll', { authRequired: true }, {
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.addModerator', { authRequired: true }, {
@ -49,7 +49,7 @@ RocketChat.API.v1.addRoute('groups.addModerator', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.addOwner', { authRequired: true }, {
@ -63,7 +63,7 @@ RocketChat.API.v1.addRoute('groups.addOwner', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.addLeader', { authRequired: true }, {
@ -75,10 +75,10 @@ RocketChat.API.v1.addRoute('groups.addLeader', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
//Archives a private group only if it wasn't
// Archives a private group only if it wasn't
RocketChat.API.v1.addRoute('groups.archive', { authRequired: true }, {
post() {
const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId });
@ -88,7 +88,7 @@ RocketChat.API.v1.addRoute('groups.archive', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.close', { authRequired: true }, {
@ -104,7 +104,7 @@ RocketChat.API.v1.addRoute('groups.close', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, {
@ -170,12 +170,12 @@ RocketChat.API.v1.addRoute('groups.counters', { authRequired: true }, {
unreadsFrom,
msgs,
latest,
userMentions
userMentions,
});
}
},
});
//Create Private Group
// Create Private Group
RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, {
post() {
if (!RocketChat.authz.hasPermission(this.userId, 'create-p')) {
@ -205,9 +205,9 @@ RocketChat.API.v1.addRoute('groups.create', { authRequired: true }, {
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(id.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(id.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.delete', { authRequired: true }, {
@ -219,9 +219,9 @@ RocketChat.API.v1.addRoute('groups.delete', { authRequired: true }, {
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.files', { authRequired: true }, {
@ -243,16 +243,16 @@ RocketChat.API.v1.addRoute('groups.files', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
files: files.map(addUserObjectToEveryObject),
count: files.length,
offset,
total: RocketChat.models.Uploads.find(ourQuery).count()
total: RocketChat.models.Uploads.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, {
@ -281,16 +281,16 @@ RocketChat.API.v1.addRoute('groups.getIntegrations', { authRequired: true }, {
sort: sort ? sort : { _createdAt: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
integrations,
count: integrations.length,
offset,
total: RocketChat.models.Integrations.find(ourQuery).count()
total: RocketChat.models.Integrations.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, {
@ -332,7 +332,7 @@ RocketChat.API.v1.addRoute('groups.history', { authRequired: true }, {
}
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute('groups.info', { authRequired: true }, {
@ -340,9 +340,9 @@ RocketChat.API.v1.addRoute('groups.info', { authRequired: true }, {
const findResult = findPrivateGroupByIdOrName({ params: this.requestParams(), userId: this.userId, checkedArchived: false });
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, {
@ -364,9 +364,9 @@ RocketChat.API.v1.addRoute('groups.invite', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('addUserToRoom', { rid, username }));
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.kick', { authRequired: true }, {
@ -380,7 +380,7 @@ RocketChat.API.v1.addRoute('groups.kick', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.leave', { authRequired: true }, {
@ -392,21 +392,21 @@ RocketChat.API.v1.addRoute('groups.leave', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
//List Private Groups a user has access to
// List Private Groups a user has access to
RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, {
get() {
const { offset, count } = this.getPaginationItems();
const { sort, fields} = this.parseJsonQuery();
const { sort, fields } = this.parseJsonQuery();
// TODO: CACHE: Add Breacking notice since we removed the query param
const cursor = RocketChat.models.Rooms.findBySubscriptionTypeAndUserId('p', this.userId, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
});
const totalCount = cursor.count();
@ -417,9 +417,9 @@ RocketChat.API.v1.addRoute('groups.list', { authRequired: true }, {
groups: rooms,
offset,
count: rooms.length,
total: totalCount
total: totalCount,
});
}
},
});
@ -439,16 +439,16 @@ RocketChat.API.v1.addRoute('groups.listAll', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
});
return RocketChat.API.v1.success({
groups: rooms,
offset,
count: rooms.length,
total: totalCount
total: totalCount,
});
}
},
});
RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, {
@ -467,25 +467,25 @@ RocketChat.API.v1.addRoute('groups.members', { authRequired: true }, {
fields: { 'u._id': 1 },
sort: { 'u.username': sort.username != null ? sort.username : 1 },
skip: offset,
limit: count
limit: count,
});
const total = subscriptions.count();
const members = subscriptions.fetch().map(s => s.u && s.u._id);
const members = subscriptions.fetch().map((s) => s.u && s.u._id);
const users = RocketChat.models.Users.find({ _id: { $in: members } }, {
fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 },
sort: { username: sort.username != null ? sort.username : 1 }
sort: { username: sort.username != null ? sort.username : 1 },
}).fetch();
return RocketChat.API.v1.success({
members: users,
count: users.length,
offset,
total
total,
});
}
},
});
RocketChat.API.v1.addRoute('groups.messages', { authRequired: true }, {
@ -500,16 +500,16 @@ RocketChat.API.v1.addRoute('groups.messages', { authRequired: true }, {
sort: sort ? sort : { ts: -1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
messages,
count: messages.length,
offset,
total: RocketChat.models.Messages.find(ourQuery).count()
total: RocketChat.models.Messages.find(ourQuery).count(),
});
}
},
});
// TODO: CACHE: same as channels.online
RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, {
@ -525,25 +525,25 @@ RocketChat.API.v1.addRoute('groups.online', { authRequired: true }, {
const online = RocketChat.models.Users.findUsersNotOffline({
fields: {
username: 1
}
username: 1,
},
}).fetch();
const onlineInRoom = [];
online.forEach(user => {
online.forEach((user) => {
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(root._id, user._id, { fields: { _id: 1 } });
if (subscription) {
onlineInRoom.push({
_id: user._id,
username: user.username
username: user.username,
});
}
});
return RocketChat.API.v1.success({
online: onlineInRoom
online: onlineInRoom,
});
}
},
});
RocketChat.API.v1.addRoute('groups.open', { authRequired: true }, {
@ -559,7 +559,7 @@ RocketChat.API.v1.addRoute('groups.open', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.removeModerator', { authRequired: true }, {
@ -573,7 +573,7 @@ RocketChat.API.v1.addRoute('groups.removeModerator', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.removeOwner', { authRequired: true }, {
@ -587,7 +587,7 @@ RocketChat.API.v1.addRoute('groups.removeOwner', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.removeLeader', { authRequired: true }, {
@ -601,7 +601,7 @@ RocketChat.API.v1.addRoute('groups.removeLeader', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.rename', { authRequired: true }, {
@ -610,16 +610,16 @@ RocketChat.API.v1.addRoute('groups.rename', { authRequired: true }, {
return RocketChat.API.v1.failure('The bodyParam "name" is required');
}
const findResult = findPrivateGroupByIdOrName({ params: { roomId: this.bodyParams.roomId}, userId: this.userId });
const findResult = findPrivateGroupByIdOrName({ params: { roomId: this.bodyParams.roomId }, userId: this.userId });
Meteor.runAsUser(this.userId, () => {
Meteor.call('saveRoomSettings', findResult.rid, 'roomName', this.bodyParams.name);
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.setCustomFields', { authRequired: true }, {
@ -635,9 +635,9 @@ RocketChat.API.v1.addRoute('groups.setCustomFields', { authRequired: true }, {
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.setDescription', { authRequired: true }, {
@ -653,9 +653,9 @@ RocketChat.API.v1.addRoute('groups.setDescription', { authRequired: true }, {
});
return RocketChat.API.v1.success({
description: this.bodyParams.description
description: this.bodyParams.description,
});
}
},
});
RocketChat.API.v1.addRoute('groups.setPurpose', { authRequired: true }, {
@ -671,9 +671,9 @@ RocketChat.API.v1.addRoute('groups.setPurpose', { authRequired: true }, {
});
return RocketChat.API.v1.success({
purpose: this.bodyParams.purpose
purpose: this.bodyParams.purpose,
});
}
},
});
RocketChat.API.v1.addRoute('groups.setReadOnly', { authRequired: true }, {
@ -693,9 +693,9 @@ RocketChat.API.v1.addRoute('groups.setReadOnly', { authRequired: true }, {
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.setTopic', { authRequired: true }, {
@ -711,9 +711,9 @@ RocketChat.API.v1.addRoute('groups.setTopic', { authRequired: true }, {
});
return RocketChat.API.v1.success({
topic: this.bodyParams.topic
topic: this.bodyParams.topic,
});
}
},
});
RocketChat.API.v1.addRoute('groups.setType', { authRequired: true }, {
@ -733,9 +733,9 @@ RocketChat.API.v1.addRoute('groups.setType', { authRequired: true }, {
});
return RocketChat.API.v1.success({
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude })
group: RocketChat.models.Rooms.findOneById(findResult.rid, { fields: RocketChat.API.v1.defaultFieldsToExclude }),
});
}
},
});
RocketChat.API.v1.addRoute('groups.unarchive', { authRequired: true }, {
@ -747,7 +747,7 @@ RocketChat.API.v1.addRoute('groups.unarchive', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('groups.roles', { authRequired: true }, {
@ -757,7 +757,7 @@ RocketChat.API.v1.addRoute('groups.roles', { authRequired: true }, {
const roles = Meteor.runAsUser(this.userId, () => Meteor.call('getRoomRoles', findResult.rid));
return RocketChat.API.v1.success({
roles
roles,
});
}
},
});

@ -6,7 +6,7 @@ function findDirectMessageRoom(params, user) {
const room = RocketChat.getRoomByNameOrIdWithOptionToJoin({
currentUserId: user._id,
nameOrId: params.username || params.roomId,
type: 'd'
type: 'd',
});
if (!room || room.t !== 'd') {
@ -17,7 +17,7 @@ function findDirectMessageRoom(params, user) {
return {
room,
subscription
subscription,
};
}
@ -26,9 +26,9 @@ RocketChat.API.v1.addRoute(['dm.create', 'im.create'], { authRequired: true }, {
const findResult = findDirectMessageRoom(this.requestParams(), this.user);
return RocketChat.API.v1.success({
room: findResult.room
room: findResult.room,
});
}
},
});
RocketChat.API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, {
@ -44,7 +44,7 @@ RocketChat.API.v1.addRoute(['dm.close', 'im.close'], { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true }, {
@ -67,7 +67,7 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true
}
user = ruserId;
}
const rs = findDirectMessageRoom(this.requestParams(), {'_id': user});
const rs = findDirectMessageRoom(this.requestParams(), { _id: user });
const room = rs.room;
const dm = rs.subscription;
lm = room.lm ? room.lm : room._updatedAt;
@ -94,9 +94,9 @@ RocketChat.API.v1.addRoute(['dm.counters', 'im.counters'], { authRequired: true
unreadsFrom,
msgs,
latest,
userMentions
userMentions,
});
}
},
});
RocketChat.API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, {
@ -118,16 +118,16 @@ RocketChat.API.v1.addRoute(['dm.files', 'im.files'], { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
files: files.map(addUserObjectToEveryObject),
count: files.length,
offset,
total: RocketChat.models.Uploads.find(ourQuery).count()
total: RocketChat.models.Uploads.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true }, {
@ -167,7 +167,7 @@ RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true },
oldest: oldestDate,
inclusive,
count,
unreads
unreads,
});
});
@ -176,7 +176,7 @@ RocketChat.API.v1.addRoute(['dm.history', 'im.history'], { authRequired: true },
}
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true }, {
@ -188,25 +188,25 @@ RocketChat.API.v1.addRoute(['dm.members', 'im.members'], { authRequired: true },
const cursor = RocketChat.models.Subscriptions.findByRoomId(findResult._id, {
sort: { 'u.username': sort.username != null ? sort.username : 1 },
skip: offset,
limit: count
limit: count,
});
const total = cursor.count();
const members = cursor.fetch().map(s => s.u && s.u.username);
const members = cursor.fetch().map((s) => s.u && s.u.username);
const users = RocketChat.models.Users.find({ username: { $in: members } }, {
fields: { _id: 1, username: 1, name: 1, status: 1, utcOffset: 1 },
sort: { username: sort.username != null ? sort.username : 1 }
sort: { username: sort.username != null ? sort.username : 1 },
}).fetch();
return RocketChat.API.v1.success({
members: users,
count: members.length,
offset,
total
total,
});
}
},
});
RocketChat.API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true }, {
@ -223,16 +223,16 @@ RocketChat.API.v1.addRoute(['dm.messages', 'im.messages'], { authRequired: true
sort: sort ? sort : { ts: -1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
messages,
count: messages.length,
offset,
total: RocketChat.models.Messages.find(ourQuery).count()
total: RocketChat.models.Messages.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authRequired: true }, {
@ -263,16 +263,16 @@ RocketChat.API.v1.addRoute(['dm.messages.others', 'im.messages.others'], { authR
sort: sort ? sort : { ts: -1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
messages: msgs,
offset,
count: msgs.length,
total: RocketChat.models.Messages.find(ourQuery).count()
total: RocketChat.models.Messages.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, {
@ -286,7 +286,7 @@ RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, {
sort,
skip: offset,
limit: count,
fields
fields,
});
const total = cursor.count();
@ -296,9 +296,9 @@ RocketChat.API.v1.addRoute(['dm.list', 'im.list'], { authRequired: true }, {
ims: rooms,
offset,
count: rooms.length,
total
total,
});
}
},
});
RocketChat.API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequired: true }, {
@ -316,16 +316,16 @@ RocketChat.API.v1.addRoute(['dm.list.everyone', 'im.list.everyone'], { authRequi
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
ims: rooms,
offset,
count: rooms.length,
total: RocketChat.models.Rooms.find(ourQuery).count()
total: RocketChat.models.Rooms.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, {
@ -339,7 +339,7 @@ RocketChat.API.v1.addRoute(['dm.open', 'im.open'], { authRequired: true }, {
}
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true }, {
@ -355,7 +355,7 @@ RocketChat.API.v1.addRoute(['dm.setTopic', 'im.setTopic'], { authRequired: true
});
return RocketChat.API.v1.success({
topic: this.bodyParams.topic
topic: this.bodyParams.topic,
});
}
},
});

@ -15,7 +15,7 @@ RocketChat.API.v1.addRoute('integrations.create', { authRequired: true }, {
token: Match.Maybe(String),
scriptEnabled: Boolean,
script: Match.Maybe(String),
targetChannel: Match.Maybe(String)
targetChannel: Match.Maybe(String),
}));
let integration;
@ -36,7 +36,7 @@ RocketChat.API.v1.addRoute('integrations.create', { authRequired: true }, {
}
return RocketChat.API.v1.success({ integration });
}
},
});
RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, {
@ -58,16 +58,16 @@ RocketChat.API.v1.addRoute('integrations.history', { authRequired: true }, {
sort: sort ? sort : { _updatedAt: -1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
history,
offset,
items: history.length,
total: RocketChat.models.IntegrationHistory.find(ourQuery).count()
total: RocketChat.models.IntegrationHistory.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('integrations.list', { authRequired: true }, {
@ -84,16 +84,16 @@ RocketChat.API.v1.addRoute('integrations.list', { authRequired: true }, {
sort: sort ? sort : { ts: -1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
integrations,
offset,
items: integrations.length,
total: RocketChat.models.Integrations.find(ourQuery).count()
total: RocketChat.models.Integrations.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, {
@ -101,7 +101,7 @@ RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, {
check(this.bodyParams, Match.ObjectIncluding({
type: String,
target_url: Match.Maybe(String),
integrationId: Match.Maybe(String)
integrationId: Match.Maybe(String),
}));
if (!this.bodyParams.target_url && !this.bodyParams.integrationId) {
@ -126,7 +126,7 @@ RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, {
});
return RocketChat.API.v1.success({
integration
integration,
});
case 'webhook-incoming':
integration = RocketChat.models.Integrations.findOne({ _id: this.bodyParams.integrationId });
@ -140,10 +140,10 @@ RocketChat.API.v1.addRoute('integrations.remove', { authRequired: true }, {
});
return RocketChat.API.v1.success({
integration
integration,
});
default:
return RocketChat.API.v1.failure('Invalid integration type.');
}
}
},
});

@ -5,22 +5,22 @@ RocketChat.API.v1.addRoute('info', { authRequired: false }, {
if (user && RocketChat.authz.hasRole(user._id, 'admin')) {
return RocketChat.API.v1.success({
info: RocketChat.Info
info: RocketChat.Info,
});
}
return RocketChat.API.v1.success({
info: {
'version': RocketChat.Info.version
}
version: RocketChat.Info.version,
},
});
}
},
});
RocketChat.API.v1.addRoute('me', { authRequired: true }, {
get() {
return RocketChat.API.v1.success(this.getUserInfo(RocketChat.models.Users.findOneById(this.userId)));
}
},
});
let onlineCache = 0;
@ -118,15 +118,15 @@ RocketChat.API.v1.addRoute('shield.svg', { authRequired: false }, {
<text x="${ leftSize + 7 }" y="14">${ text }</text>
</g>
</svg>
`.trim().replace(/\>[\s]+\</gm, '><')
`.trim().replace(/\>[\s]+\</gm, '><'),
};
}
},
});
RocketChat.API.v1.addRoute('spotlight', { authRequired: true }, {
get() {
check(this.queryParams, {
query: String
query: String,
});
const { query } = this.queryParams;
@ -136,7 +136,7 @@ RocketChat.API.v1.addRoute('spotlight', { authRequired: true }, {
);
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute('directory', { authRequired: true }, {
@ -157,7 +157,7 @@ RocketChat.API.v1.addRoute('directory', { authRequired: true }, {
sortBy,
sortDirection,
page: offset,
limit: count
limit: count,
}));
if (!result) {
@ -167,7 +167,7 @@ RocketChat.API.v1.addRoute('directory', { authRequired: true }, {
result: result.results,
count: result.results.length,
offset,
total: result.total
total: result.total,
});
}
},
});

@ -13,7 +13,7 @@ RocketChat.API.v1.addRoute('permissions', { authRequired: true }, {
const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get'));
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute('permissions.list', { authRequired: true }, {
@ -21,9 +21,9 @@ RocketChat.API.v1.addRoute('permissions.list', { authRequired: true }, {
const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get'));
return RocketChat.API.v1.success({
permissions: result
permissions: result,
});
}
},
});
RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, {
@ -36,9 +36,9 @@ RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, {
permissions: [
Match.ObjectIncluding({
_id: String,
roles: [String]
})
]
roles: [String],
}),
],
});
let permissionNotFound = false;
@ -74,7 +74,7 @@ RocketChat.API.v1.addRoute('permissions.update', { authRequired: true }, {
const result = Meteor.runAsUser(this.userId, () => Meteor.call('permissions/get'));
return RocketChat.API.v1.success({
permissions: result
permissions: result,
});
}
},
});

@ -29,7 +29,7 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, {
id,
token: { [type]: value },
appName,
userId: this.userId
userId: this.userId,
}));
return RocketChat.API.v1.success({ result });
@ -43,11 +43,11 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, {
const affectedRecords = Push.appCollection.remove({
$or: [{
'token.apn': token
'token.apn': token,
}, {
'token.gcm': token
'token.gcm': token,
}],
userId: this.userId
userId: this.userId,
});
if (affectedRecords === 0) {
@ -55,5 +55,5 @@ RocketChat.API.v1.addRoute('push.token', { authRequired: true }, {
}
return RocketChat.API.v1.success();
}
},
});

@ -3,5 +3,5 @@ RocketChat.API.v1.addRoute('roles.list', { authRequired: true }, {
const roles = RocketChat.models.Roles.find({}, { fields: { _updatedAt: 0 } }).fetch();
return RocketChat.API.v1.success({ roles });
}
},
});

@ -1,6 +1,6 @@
import Busboy from 'busboy';
function findRoomByIdOrName({ params, checkedArchived = true}) {
function findRoomByIdOrName({ params, checkedArchived = true }) {
if ((!params.roomId || !params.roomId.trim()) && (!params.roomName || !params.roomName.trim())) {
throw new Meteor.Error('error-roomid-param-not-provided', 'The parameter "roomId" or "roomName" is required');
}
@ -42,12 +42,12 @@ RocketChat.API.v1.addRoute('rooms.get', { authRequired: true }, {
if (Array.isArray(result)) {
result = {
update: result,
remove: []
remove: [],
};
}
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, {
@ -69,7 +69,7 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, {
}
const fileDate = [];
file.on('data', data => fileDate.push(data));
file.on('data', (data) => fileDate.push(data));
file.on('end', () => {
files.push({ fieldname, file, filename, encoding, mimetype, fileBuffer: Buffer.concat(fileDate) });
@ -100,7 +100,7 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, {
size: file.fileBuffer.length,
type: file.mimetype,
rid: this.urlParams.rid,
userId: this.userId
userId: this.userId,
};
Meteor.runAsUser(this.userId, () => {
@ -114,7 +114,7 @@ RocketChat.API.v1.addRoute('rooms.upload/:rid', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, {
@ -137,7 +137,7 @@ RocketChat.API.v1.addRoute('rooms.saveNotification', { authRequired: true }, {
saveNotifications(notifications, roomId);
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('rooms.favorite', { authRequired: true }, {
@ -153,7 +153,7 @@ RocketChat.API.v1.addRoute('rooms.favorite', { authRequired: true }, {
Meteor.runAsUser(this.userId, () => Meteor.call('toggleFavorite', room._id, favorite));
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, {
@ -181,6 +181,6 @@ RocketChat.API.v1.addRoute('rooms.cleanHistory', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});

@ -8,7 +8,7 @@ RocketChat.API.v1.addRoute('settings.public', { authRequired: false }, {
let ourQuery = {
hidden: { $ne: true },
'public': true
public: true,
};
ourQuery = Object.assign({}, query, ourQuery);
@ -17,16 +17,16 @@ RocketChat.API.v1.addRoute('settings.public', { authRequired: false }, {
sort: sort ? sort : { _id: 1 },
skip: offset,
limit: count,
fields: Object.assign({ _id: 1, value: 1 }, fields)
fields: Object.assign({ _id: 1, value: 1 }, fields),
}).fetch();
return RocketChat.API.v1.success({
settings,
count: settings.length,
offset,
total: RocketChat.models.Settings.find(ourQuery).count()
total: RocketChat.models.Settings.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('settings.oauth', { authRequired: false }, {
@ -46,15 +46,15 @@ RocketChat.API.v1.addRoute('settings.oauth', { authRequired: false }, {
buttonLabelText: service.buttonLabelText || '',
buttonColor: service.buttonColor || '',
buttonLabelColor: service.buttonLabelColor || '',
custom: false
custom: false,
};
});
};
return RocketChat.API.v1.success({
services: mountOAuthServices()
services: mountOAuthServices(),
});
}
},
});
RocketChat.API.v1.addRoute('settings', { authRequired: true }, {
@ -63,7 +63,7 @@ RocketChat.API.v1.addRoute('settings', { authRequired: true }, {
const { sort, fields, query } = this.parseJsonQuery();
let ourQuery = {
hidden: { $ne: true }
hidden: { $ne: true },
};
if (!RocketChat.authz.hasPermission(this.userId, 'view-privileged-setting')) {
@ -76,16 +76,16 @@ RocketChat.API.v1.addRoute('settings', { authRequired: true }, {
sort: sort ? sort : { _id: 1 },
skip: offset,
limit: count,
fields: Object.assign({ _id: 1, value: 1 }, fields)
fields: Object.assign({ _id: 1, value: 1 }, fields),
}).fetch();
return RocketChat.API.v1.success({
settings,
count: settings.length,
offset,
total: RocketChat.models.Settings.find(ourQuery).count()
total: RocketChat.models.Settings.find(ourQuery).count(),
});
}
},
});
RocketChat.API.v1.addRoute('settings/:_id', { authRequired: true }, {
@ -104,7 +104,7 @@ RocketChat.API.v1.addRoute('settings/:_id', { authRequired: true }, {
// allow special handling of particular setting types
const setting = RocketChat.models.Settings.findOneNotHiddenById(this.urlParams._id);
if (setting.type === 'action' && this.bodyParams && this.bodyParams.execute) {
//execute the configured method
// execute the configured method
Meteor.call(setting.value);
return RocketChat.API.v1.success();
}
@ -116,14 +116,14 @@ RocketChat.API.v1.addRoute('settings/:_id', { authRequired: true }, {
}
check(this.bodyParams, {
value: Match.Any
value: Match.Any,
});
if (RocketChat.models.Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value)) {
return RocketChat.API.v1.success();
}
return RocketChat.API.v1.failure();
}
},
});
RocketChat.API.v1.addRoute('service.configurations', { authRequired: false }, {
@ -131,7 +131,7 @@ RocketChat.API.v1.addRoute('service.configurations', { authRequired: false }, {
const ServiceConfiguration = Package['service-configuration'].ServiceConfiguration;
return RocketChat.API.v1.success({
configurations: ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch()
configurations: ServiceConfiguration.configurations.find({}, { fields: { secret: 0 } }).fetch(),
});
}
},
});

@ -11,9 +11,9 @@ RocketChat.API.v1.addRoute('statistics', { authRequired: true }, {
});
return RocketChat.API.v1.success({
statistics: stats
statistics: stats,
});
}
},
});
RocketChat.API.v1.addRoute('statistics.list', { authRequired: true }, {
@ -29,14 +29,14 @@ RocketChat.API.v1.addRoute('statistics.list', { authRequired: true }, {
sort: sort ? sort : { name: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
statistics,
count: statistics.length,
offset,
total: RocketChat.models.Statistics.find(query).count()
total: RocketChat.models.Statistics.find(query).count(),
});
}
},
});

@ -17,12 +17,12 @@ RocketChat.API.v1.addRoute('subscriptions.get', { authRequired: true }, {
if (Array.isArray(result)) {
result = {
update: result,
remove: []
remove: [],
};
}
return RocketChat.API.v1.success(result);
}
},
});
RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, {
@ -36,9 +36,9 @@ RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, {
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId);
return RocketChat.API.v1.success({
subscription
subscription,
});
}
},
});
/**
@ -52,7 +52,7 @@ RocketChat.API.v1.addRoute('subscriptions.getOne', { authRequired: true }, {
RocketChat.API.v1.addRoute('subscriptions.read', { authRequired: true }, {
post() {
check(this.bodyParams, {
rid: String
rid: String,
});
Meteor.runAsUser(this.userId, () =>
@ -60,7 +60,7 @@ RocketChat.API.v1.addRoute('subscriptions.read', { authRequired: true }, {
);
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('subscriptions.unread', { authRequired: true }, {
@ -75,7 +75,7 @@ RocketChat.API.v1.addRoute('subscriptions.unread', { authRequired: true }, {
);
return RocketChat.API.v1.success();
}
},
});

@ -14,10 +14,10 @@ RocketChat.API.v1.addRoute('users.create', { authRequired: true }, {
requirePasswordChange: Match.Maybe(Boolean),
sendWelcomeEmail: Match.Maybe(Boolean),
verified: Match.Maybe(Boolean),
customFields: Match.Maybe(Object)
customFields: Match.Maybe(Object),
});
//New change made by pull request #5152
// New change made by pull request #5152
if (typeof this.bodyParams.joinDefaultChannels === 'undefined') {
this.bodyParams.joinDefaultChannels = true;
}
@ -40,7 +40,7 @@ RocketChat.API.v1.addRoute('users.create', { authRequired: true }, {
}
return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(newUserId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) });
}
},
});
RocketChat.API.v1.addRoute('users.delete', { authRequired: true }, {
@ -56,7 +56,7 @@ RocketChat.API.v1.addRoute('users.delete', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, {
@ -74,7 +74,7 @@ RocketChat.API.v1.addRoute('users.deleteOwnAccount', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, {
@ -86,9 +86,9 @@ RocketChat.API.v1.addRoute('users.getAvatar', { authRequired: false }, {
return {
statusCode: 307,
body: url
body: url,
};
}
},
});
RocketChat.API.v1.addRoute('users.getPresence', { authRequired: true }, {
@ -98,16 +98,16 @@ RocketChat.API.v1.addRoute('users.getPresence', { authRequired: true }, {
return RocketChat.API.v1.success({
presence: user.status,
connectionStatus: user.statusConnection,
lastLogin: user.lastLogin
lastLogin: user.lastLogin,
});
}
const user = this.getUserFromParams();
return RocketChat.API.v1.success({
presence: user.status
presence: user.status,
});
}
},
});
RocketChat.API.v1.addRoute('users.info', { authRequired: true }, {
@ -124,9 +124,9 @@ RocketChat.API.v1.addRoute('users.info', { authRequired: true }, {
}
return RocketChat.API.v1.success({
user: result[0]
user: result[0],
});
}
},
});
RocketChat.API.v1.addRoute('users.list', { authRequired: true }, {
@ -142,16 +142,16 @@ RocketChat.API.v1.addRoute('users.list', { authRequired: true }, {
sort: sort ? sort : { username: 1 },
skip: offset,
limit: count,
fields
fields,
}).fetch();
return RocketChat.API.v1.success({
users,
count: users.length,
offset,
total: RocketChat.models.Users.find(query).count()
total: RocketChat.models.Users.find(query).count(),
});
}
},
});
RocketChat.API.v1.addRoute('users.register', { authRequired: false }, {
@ -160,20 +160,20 @@ RocketChat.API.v1.addRoute('users.register', { authRequired: false }, {
return RocketChat.API.v1.failure('Logged in users can not register again.');
}
//We set their username here, so require it
//The `registerUser` checks for the other requirements
// We set their username here, so require it
// The `registerUser` checks for the other requirements
check(this.bodyParams, Match.ObjectIncluding({
username: String
username: String,
}));
//Register the user
// Register the user
const userId = Meteor.call('registerUser', this.bodyParams);
//Now set their username
// Now set their username
Meteor.runAsUser(userId, () => Meteor.call('setUsername', this.bodyParams.username));
return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) });
}
},
});
RocketChat.API.v1.addRoute('users.resetAvatar', { authRequired: true }, {
@ -189,7 +189,7 @@ RocketChat.API.v1.addRoute('users.resetAvatar', { authRequired: true }, {
}
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, {
@ -197,7 +197,7 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, {
check(this.bodyParams, Match.ObjectIncluding({
avatarUrl: Match.Maybe(String),
userId: Match.Maybe(String),
username: Match.Maybe(String)
username: Match.Maybe(String),
}));
let user;
@ -238,7 +238,7 @@ RocketChat.API.v1.addRoute('users.setAvatar', { authRequired: true }, {
});
return RocketChat.API.v1.success();
}
},
});
RocketChat.API.v1.addRoute('users.update', { authRequired: true }, {
@ -256,8 +256,8 @@ RocketChat.API.v1.addRoute('users.update', { authRequired: true }, {
requirePasswordChange: Match.Maybe(Boolean),
sendWelcomeEmail: Match.Maybe(Boolean),
verified: Match.Maybe(Boolean),
customFields: Match.Maybe(Object)
})
customFields: Match.Maybe(Object),
}),
});
const userData = _.extend({ _id: this.bodyParams.userId }, this.bodyParams.data);
@ -275,7 +275,7 @@ RocketChat.API.v1.addRoute('users.update', { authRequired: true }, {
}
return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(this.bodyParams.userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) });
}
},
});
RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, {
@ -286,9 +286,9 @@ RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, {
name: Match.Maybe(String),
username: Match.Maybe(String),
currentPassword: Match.Maybe(String),
newPassword: Match.Maybe(String)
newPassword: Match.Maybe(String),
}),
customFields: Match.Maybe(Object)
customFields: Match.Maybe(Object),
});
const userData = {
@ -296,13 +296,13 @@ RocketChat.API.v1.addRoute('users.updateOwnBasicInfo', { authRequired: true }, {
realname: this.bodyParams.data.name,
username: this.bodyParams.data.username,
newPassword: this.bodyParams.data.newPassword,
typedPassword: this.bodyParams.data.currentPassword
typedPassword: this.bodyParams.data.currentPassword,
};
Meteor.runAsUser(this.userId, () => Meteor.call('saveUserProfile', userData, this.bodyParams.customFields));
return RocketChat.API.v1.success({ user: RocketChat.models.Users.findOneById(this.userId, { fields: RocketChat.API.v1.defaultFieldsToExclude }) });
}
},
});
RocketChat.API.v1.addRoute('users.createToken', { authRequired: true }, {
@ -313,7 +313,7 @@ RocketChat.API.v1.addRoute('users.createToken', { authRequired: true }, {
data = Meteor.call('createToken', user._id);
});
return data ? RocketChat.API.v1.success({ data }) : RocketChat.API.v1.unauthorized();
}
},
});
RocketChat.API.v1.addRoute('users.getPreferences', { authRequired: true }, {
@ -321,15 +321,15 @@ RocketChat.API.v1.addRoute('users.getPreferences', { authRequired: true }, {
const user = RocketChat.models.Users.findOneById(this.userId);
if (user.settings) {
const preferences = user.settings.preferences;
preferences['language'] = user.language;
preferences.language = user.language;
return RocketChat.API.v1.success({
preferences
preferences,
});
} else {
return RocketChat.API.v1.failure(TAPi18n.__('Accounts_Default_User_Preferences_not_available').toUpperCase());
}
}
},
});
RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, {
@ -366,16 +366,16 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, {
sidebarViewMode: Match.Optional(String),
sidebarHideAvatar: Match.Optional(Boolean),
sidebarGroupByType: Match.Optional(Boolean),
muteFocusedConversations: Match.Optional(Boolean)
})
muteFocusedConversations: Match.Optional(Boolean),
}),
});
const userId = this.bodyParams.userId ? this.bodyParams.userId : this.userId;
const userData = {
_id: userId,
settings: {
preferences: this.bodyParams.data
}
preferences: this.bodyParams.data,
},
};
if (this.bodyParams.data.language) {
@ -389,11 +389,11 @@ RocketChat.API.v1.addRoute('users.setPreferences', { authRequired: true }, {
return RocketChat.API.v1.success({
user: RocketChat.models.Users.findOneById(userId, {
fields: {
'settings.preferences': 1
}
})
'settings.preferences': 1,
},
}),
});
}
},
});
RocketChat.API.v1.addRoute('users.forgotPassword', { authRequired: false }, {
@ -408,7 +408,7 @@ RocketChat.API.v1.addRoute('users.forgotPassword', { authRequired: false }, {
return RocketChat.API.v1.success();
}
return RocketChat.API.v1.failure('User not found');
}
},
});
RocketChat.API.v1.addRoute('users.getUsernameSuggestion', { authRequired: true }, {
@ -416,5 +416,5 @@ RocketChat.API.v1.addRoute('users.getUsernameSuggestion', { authRequired: true }
const result = Meteor.runAsUser(this.userId, () => Meteor.call('getUsernameSuggestion'));
return RocketChat.API.v1.success({ result });
}
},
});

@ -26,7 +26,7 @@ Template.appInstall.helpers({
const instance = Template.instance();
return !!instance.isUpdatingId.get();
}
},
});
Template.appInstall.onCreated(function() {
@ -129,5 +129,5 @@ Template.appInstall.events({
}
t.isInstalling.set(false);
}
},
});

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

Loading…
Cancel
Save