From 1a960aafa41a667bcdf220b095222790cae35bf7 Mon Sep 17 00:00:00 2001 From: James Nylen Date: Fri, 25 Jan 2019 01:47:41 -0500 Subject: [PATCH 01/15] Fix SlackBridge private channels --- .../server/RocketAdapter.js | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/rocketchat-slackbridge/server/RocketAdapter.js b/packages/rocketchat-slackbridge/server/RocketAdapter.js index f75886b9f8eb..0989be032a04 100644 --- a/packages/rocketchat-slackbridge/server/RocketAdapter.js +++ b/packages/rocketchat-slackbridge/server/RocketAdapter.js @@ -235,15 +235,21 @@ export default class RocketAdapter { addChannel(slackChannelID, hasRetried = false) { logger.rocket.debug('Adding Rocket.Chat channel from Slack', slackChannelID); let slackResults = null; - let isGroup = false; - if (slackChannelID.charAt(0) === 'C') { - slackResults = HTTP.get('https://slack.com/api/channels.info', { params: { token: this.slackBridge.apiToken, channel: slackChannelID } }); - } else if (slackChannelID.charAt(0) === 'G') { - slackResults = HTTP.get('https://slack.com/api/groups.info', { params: { token: this.slackBridge.apiToken, channel: slackChannelID } }); - isGroup = true; + let slackMembers = null; + + slackResults = HTTP.get('https://slack.com/api/conversations.info', { params: { token: this.slackBridge.apiToken, channel: slackChannelID } }); + if (slackResults && slackResults.data && slackResults.data.ok === true) { + slackMembers = HTTP.get('https://slack.com/api/conversations.members', { params: { token: this.slackBridge.apiToken, channel: slackChannelID } }); + if (slackMembers && slackMembers.data && slackMembers.data.ok === true) { + slackResults.data.channel.members = slackMembers.data.members; + } else { + slackResults = null; + logger.rocket.error('Could not fetch room members'); + } } + if (slackResults && slackResults.data && slackResults.data.ok === true) { - const rocketChannelData = isGroup ? slackResults.data.group : slackResults.data.channel; + const rocketChannelData = slackResults.data.channel; const existingRocketRoom = RocketChat.models.Rooms.findOneByName(rocketChannelData.name); // If the room exists, make sure we have its id in importIds @@ -267,7 +273,8 @@ export default class RocketAdapter { } try { - const rocketChannel = RocketChat.createRoom(isGroup ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); + const isPrivate = rocketChannelData.is_private; + const rocketChannel = RocketChat.createRoom(isPrivate ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); rocketChannelData.rocketId = rocketChannel.rid; } catch (e) { if (!hasRetried) { From ddb73bd908f8803e9b74df45e6a2ac0e89333dfa Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 10 Apr 2019 15:37:37 -0300 Subject: [PATCH 02/15] WIP: fix slackbridge private rooms does not send message back to slack --- app/slackbridge/server/RocketAdapter.js | 2 +- app/slackbridge/server/SlackAdapter.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index 09668a5df232..5763eb278c15 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -300,8 +300,8 @@ export default class RocketAdapter { roomUpdate.topic = rocketChannelData.purpose.value; } Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); - this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); } + this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); return Rooms.findOneById(rocketChannelData.rocketId); } logger.rocket.debug('Channel not added'); diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 9e351623e872..0f4b73d02c2f 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -546,9 +546,9 @@ export default class SlackAdapter { } populateMembershipChannelMapByGroups() { - const response = HTTP.get('https://slack.com/api/groups.list', { params: { token: this.apiToken } }); - if (response && response.data && _.isArray(response.data.groups) && response.data.groups.length > 0) { - for (const slackGroup of response.data.groups) { + const response = HTTP.get('https://slack.com/api/conversations.list', { params: { token: this.apiToken, types: 'private_channel' } }); + if (response && response.data && _.isArray(response.data.channels) && response.data.channels.length > 0) { + for (const slackGroup of response.data.channels) { const rocketchat_room = Rooms.findOneByName(slackGroup.name, { fields: { _id: 1 } }); if (rocketchat_room) { if (slackGroup.is_member) { From e732a46d94c5027cd1ef2fb1dc4f534b879d5675 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 10 Apr 2019 15:52:00 -0300 Subject: [PATCH 03/15] Fix lint --- app/apps/client/admin/appManage.js | 10 +++--- app/apps/client/admin/apps.js | 8 ++--- .../client/views/channelSettings.js | 2 +- app/e2e/client/rocketchat.e2e.js | 4 +-- app/e2e/client/rocketchat.e2e.room.js | 2 +- app/emoji-custom/client/lib/emojiCustom.js | 2 +- .../server/mocks/accounts/graphql-api.js | 2 +- .../resolvers/accounts/oauthProviders.js | 2 +- .../server/resolvers/users/User-type.js | 4 +-- .../server/importer.js | 10 +++--- .../server/lib/sendNotificationsOnMessage.js | 4 +-- app/livestream/client/oauth.js | 2 +- app/livestream/client/views/broadcastView.js | 8 ++--- app/livestream/server/functions/livestream.js | 6 ++-- app/metrics/server/lib/metrics.js | 6 ++-- .../client/views/pushNotificationsFlexTab.js | 4 +-- app/threads/client/flextab/thread.js | 4 +-- app/threads/client/flextab/threads.js | 6 ++-- app/ui-admin/client/rooms/adminRoomInfo.js | 2 +- .../client/models/CachedCollection.js | 2 +- app/ui-master/public/generateHTML.js | 6 ++-- app/ui-master/public/generateSprite.js | 6 ++-- .../client/messageBoxAudioMessage.js | 2 +- .../client/popup/messagePopupConfig.js | 4 +-- app/ui-utils/client/lib/ChannelActions.js | 2 +- app/ui-utils/client/lib/prependReplies.js | 4 +-- app/ui/client/lib/fileUpload.js | 6 ++-- client/routes/roomRoute.js | 2 +- server/startup/migrations/v123.js | 2 +- tests/end-to-end/api/02-channels.js | 32 +++++++++---------- tests/end-to-end/api/03-groups.js | 20 ++++++------ tests/end-to-end/ui/14-message-popup.js | 4 +-- 32 files changed, 90 insertions(+), 90 deletions(-) diff --git a/app/apps/client/admin/appManage.js b/app/apps/client/admin/appManage.js index 5373f8c25fb0..5050cc7c129f 100644 --- a/app/apps/client/admin/appManage.js +++ b/app/apps/client/admin/appManage.js @@ -360,7 +360,7 @@ Template.appManage.events({ setActivate(false, e, t); }, - 'click .js-uninstall': async(e, t) => { + 'click .js-uninstall': async (e, t) => { t.ready.set(false); try { await APIClient.delete(`apps/${ t.id.get() }`); @@ -372,7 +372,7 @@ Template.appManage.events({ } }, - 'click .js-install': async(e, t) => { + 'click .js-install': async (e, t) => { installAppFromEvent(e, t); }, @@ -381,7 +381,7 @@ Template.appManage.events({ APIClient.get(`apps?buildBuyUrl=true&appId=${ rl.id }`) .then((data) => { - data.successCallback = async() => { + data.successCallback = async () => { installAppFromEvent(e, t); }; @@ -404,11 +404,11 @@ Template.appManage.events({ FlowRouter.go(`/admin/apps/${ t.id.get() }/logs`, {}, { version: FlowRouter.getQueryParam('version') }); }, - 'click .js-cancel-editing': async(e, t) => { + 'click .js-cancel-editing': async (e, t) => { t.onSettingUpdated({ appId: t.id.get() }); }, - 'click .js-save': async(e, t) => { + 'click .js-save': async (e, t) => { if (t.loading.get()) { return; } diff --git a/app/apps/client/admin/apps.js b/app/apps/client/admin/apps.js index 41174adb0d62..491ac2ac4189 100644 --- a/app/apps/client/admin/apps.js +++ b/app/apps/client/admin/apps.js @@ -36,7 +36,7 @@ const tagAlreadyInstalledApps = (installedApps, apps) => { return tagged; }; -const getApps = async(instance) => { +const getApps = async (instance) => { instance.isLoading.set(true); const data = await APIClient.get('apps?marketplace=true'); @@ -49,7 +49,7 @@ const getApps = async(instance) => { } }; -const getInstalledApps = async(instance) => { +const getInstalledApps = async (instance) => { const data = await APIClient.get('apps'); const apps = data.apps.map((app) => ({ latest: app })); instance.installedApps.set(apps); @@ -279,7 +279,7 @@ Template.apps.events({ marketplace: true, version: this.latest.version, }) - .then(async() => { + .then(async () => { await Promise.all([ getInstalledApps(template), getApps(template), @@ -312,7 +312,7 @@ Template.apps.events({ marketplace: true, version: this.latest.version, }) - .then(async() => { + .then(async () => { await Promise.all([ getInstalledApps(template), getApps(template), diff --git a/app/channel-settings/client/views/channelSettings.js b/app/channel-settings/client/views/channelSettings.js index 454c15eadb70..06f1eb4ab265 100644 --- a/app/channel-settings/client/views/channelSettings.js +++ b/app/channel-settings/client/views/channelSettings.js @@ -193,7 +193,7 @@ Template.channelSettingsEditing.events({ }, async 'click .js-save'(e, t) { const { settings } = t; - Object.keys(settings).forEach(async(name) => { + Object.keys(settings).forEach(async (name) => { const setting = settings[name]; const value = setting.value.get(); if (setting.default.get() !== value) { diff --git a/app/e2e/client/rocketchat.e2e.js b/app/e2e/client/rocketchat.e2e.js index aff7e9820cda..3ac3cf6ebad2 100644 --- a/app/e2e/client/rocketchat.e2e.js +++ b/app/e2e/client/rocketchat.e2e.js @@ -210,7 +210,7 @@ class E2E { } setupListeners() { - Notifications.onUser('e2ekeyRequest', async(roomId, keyId) => { + Notifications.onUser('e2ekeyRequest', async (roomId, keyId) => { const e2eRoom = await this.getInstanceByRoomId(roomId); if (!e2eRoom) { return; @@ -438,7 +438,7 @@ class E2E { return; } - return await Messages.find({ t: 'e2e', e2e: 'pending' }).forEach(async(item) => { + return await Messages.find({ t: 'e2e', e2e: 'pending' }).forEach(async (item) => { await this.decryptMessage(item); }); } diff --git a/app/e2e/client/rocketchat.e2e.room.js b/app/e2e/client/rocketchat.e2e.room.js index 549791cbe51c..3ca4c811dde2 100644 --- a/app/e2e/client/rocketchat.e2e.room.js +++ b/app/e2e/client/rocketchat.e2e.room.js @@ -39,7 +39,7 @@ export class E2ERoom { this._ready.set(true); this.establishing.set(false); - Notifications.onRoom(this.roomId, 'e2ekeyRequest', async(keyId) => { + Notifications.onRoom(this.roomId, 'e2ekeyRequest', async (keyId) => { this.provideKeyToUser(keyId); }); }); diff --git a/app/emoji-custom/client/lib/emojiCustom.js b/app/emoji-custom/client/lib/emojiCustom.js index ad96b6796c3d..9b70def17a03 100644 --- a/app/emoji-custom/client/lib/emojiCustom.js +++ b/app/emoji-custom/client/lib/emojiCustom.js @@ -158,7 +158,7 @@ emoji.packages.emojiCustom = { }; Meteor.startup(() => - CachedCollectionManager.onLogin(async() => { + CachedCollectionManager.onLogin(async () => { const emojis = await call('listEmojiCustom'); emoji.packages.emojiCustom.emojisByCategory = { rocket: [] }; diff --git a/app/graphql/server/mocks/accounts/graphql-api.js b/app/graphql/server/mocks/accounts/graphql-api.js index 764bce7a35dc..d45aa90d2da9 100644 --- a/app/graphql/server/mocks/accounts/graphql-api.js +++ b/app/graphql/server/mocks/accounts/graphql-api.js @@ -4,7 +4,7 @@ // maybe Promise is not wrapped with Fiber // See: https://github.com/meteor/meteor/blob/a362e20a37547362b581fed52f7171d022e83b62/packages/promise/server.js // Opened issue: https://github.com/js-accounts/graphql/issues/16 -export const authenticated = (Accounts, func) => (async(root, args, context, info) => { +export const authenticated = (Accounts, func) => (async (root, args, context, info) => { const { authToken } = context; if (!authToken || authToken === '' || authToken === null) { diff --git a/app/graphql/server/resolvers/accounts/oauthProviders.js b/app/graphql/server/resolvers/accounts/oauthProviders.js index 51c72ce54639..0719d944174a 100644 --- a/app/graphql/server/resolvers/accounts/oauthProviders.js +++ b/app/graphql/server/resolvers/accounts/oauthProviders.js @@ -14,7 +14,7 @@ function isJSON(obj) { const resolver = { Query: { - oauthProviders: async() => { + oauthProviders: async () => { // depends on rocketchat:grant package try { const result = HTTP.get(Meteor.absoluteUrl('_oauth_apps/providers')).content; diff --git a/app/graphql/server/resolvers/users/User-type.js b/app/graphql/server/resolvers/users/User-type.js index de33382d9cbd..c9c4add527fa 100644 --- a/app/graphql/server/resolvers/users/User-type.js +++ b/app/graphql/server/resolvers/users/User-type.js @@ -8,7 +8,7 @@ const resolver = { User: { id: property('_id'), status: ({ status }) => status.toUpperCase(), - avatar: async({ _id }) => { + avatar: async ({ _id }) => { // XXX js-accounts/graphql#16 const avatar = await Avatars.model.rawCollection().findOne({ userId: _id, @@ -18,7 +18,7 @@ const resolver = { return avatar.url; } }, - channels: Meteor.bindEnvironment(async({ _id }) => await Rooms.findBySubscriptionUserId(_id).fetch()), + channels: Meteor.bindEnvironment(async ({ _id }) => await Rooms.findBySubscriptionUserId(_id).fetch()), directMessages: ({ username }) => Rooms.findDirectRoomContainingUsername(username).fetch(), }, }; diff --git a/app/importer-hipchat-enterprise/server/importer.js b/app/importer-hipchat-enterprise/server/importer.js index fa80b15d2203..dc90f01672a3 100644 --- a/app/importer-hipchat-enterprise/server/importer.js +++ b/app/importer-hipchat-enterprise/server/importer.js @@ -466,7 +466,7 @@ export class HipChatEnterpriseImporter extends Base { // This object will keep track of messages that have already been prepared so it doesn't try to do it twice this.preparedMessages = {}; - const promise = new Promise(async(resolve, reject) => { + const promise = new Promise(async (resolve, reject) => { try { await this._prepareFolderEntry(fullFolderPath, '.'); this._finishPreparationProcess(resolve, reject); @@ -552,7 +552,7 @@ export class HipChatEnterpriseImporter extends Base { }, }, { $group: { _id: '$channels.id' }, - }]).forEach(async(channel) => { + }]).forEach(async (channel) => { const userIds = (await this.collection.model.rawCollection().aggregate([{ $match: { $or: [ @@ -614,7 +614,7 @@ export class HipChatEnterpriseImporter extends Base { pos += chunk.length; })); - stream.on('end', Meteor.bindEnvironment(async() => { + stream.on('end', Meteor.bindEnvironment(async () => { this.logger.info(`Processing the file: ${ header.name }`); await this.prepareFile(info, data, header.name); data = undefined; @@ -879,7 +879,7 @@ export class HipChatEnterpriseImporter extends Base { this._applyUserSelections(importSelection); const startedByUserId = Meteor.userId(); - Meteor.defer(async() => { + Meteor.defer(async () => { try { await super.updateProgress(ProgressStep.IMPORTING_USERS); await this._importUsers(startedByUserId); @@ -1106,7 +1106,7 @@ export class HipChatEnterpriseImporter extends Base { 'count.completed': this.progress.count.completed, }); - await Meteor.runAsUser(startedByUserId, async() => { + await Meteor.runAsUser(startedByUserId, async () => { let msgCount = 0; try { for (const msg of list.messages) { diff --git a/app/lib/server/lib/sendNotificationsOnMessage.js b/app/lib/server/lib/sendNotificationsOnMessage.js index 807f2db4c75e..52d31597ab00 100644 --- a/app/lib/server/lib/sendNotificationsOnMessage.js +++ b/app/lib/server/lib/sendNotificationsOnMessage.js @@ -11,7 +11,7 @@ import { sendSinglePush, shouldNotifyMobile } from '../functions/notifications/m import { notifyDesktopUser, shouldNotifyDesktop } from '../functions/notifications/desktop'; import { notifyAudioUser, shouldNotifyAudio } from '../functions/notifications/audio'; -export const sendNotification = async({ +export const sendNotification = async ({ subscription, sender, hasReplyToThread, @@ -310,7 +310,7 @@ async function sendAllNotifications(message, room) { }); Promise.all(mentions - .map(async(userId) => { + .map(async (userId) => { await callJoinRoom(userId, room._id); return userId; diff --git a/app/livestream/client/oauth.js b/app/livestream/client/oauth.js index 2d840eee6c3b..fa3ea4713e60 100644 --- a/app/livestream/client/oauth.js +++ b/app/livestream/client/oauth.js @@ -10,7 +10,7 @@ export const close = (popup) => new Promise(function(resolve) { }, 300); }); -export const auth = async() => { +export const auth = async () => { const oauthWindow = window.open(`${ settings.get('Site_Url') }/api/v1/livestream/oauth?userId=${ Meteor.userId() }`, 'youtube-integration-oauth', 'width=400,height=600'); return await close(oauthWindow); }; diff --git a/app/livestream/client/views/broadcastView.js b/app/livestream/client/views/broadcastView.js index 7010dea788da..4033c56856f7 100644 --- a/app/livestream/client/views/broadcastView.js +++ b/app/livestream/client/views/broadcastView.js @@ -32,8 +32,8 @@ export const call = (...args) => new Promise(function(resolve, reject) { const delay = (time) => new Promise((resolve) => setTimeout(resolve, time)); -const waitForStreamStatus = async(id, status) => { - const streamActive = new Promise(async(resolve) => { +const waitForStreamStatus = async (id, status) => { + const streamActive = new Promise(async (resolve) => { while (true) { // eslint-disable-line no-constant-condition const currentStatus = await call('livestreamStreamStatus', { streamId: id }); if (currentStatus === status) { @@ -44,8 +44,8 @@ const waitForStreamStatus = async(id, status) => { }); await streamActive; }; -const waitForBroadcastStatus = async(id, status) => { - const broadcastActive = new Promise(async(resolve) => { +const waitForBroadcastStatus = async (id, status) => { + const broadcastActive = new Promise(async (resolve) => { while (true) { // eslint-disable-line no-constant-condition const currentStatus = await call('getBroadcastStatus', { broadcastId: id }); if (currentStatus === status) { diff --git a/app/livestream/server/functions/livestream.js b/app/livestream/server/functions/livestream.js index 2b91962bf99b..a5e6f8ab5f7e 100644 --- a/app/livestream/server/functions/livestream.js +++ b/app/livestream/server/functions/livestream.js @@ -11,7 +11,7 @@ const p = (fn) => new Promise(function(resolve, reject) { }); }); -export const getBroadcastStatus = async({ +export const getBroadcastStatus = async ({ id, access_token, refresh_token, @@ -32,7 +32,7 @@ export const getBroadcastStatus = async({ return result.items && result.items[0] && result.items[0].status.lifeCycleStatus; }; -export const statusStreamLiveStream = async({ +export const statusStreamLiveStream = async ({ id, access_token, refresh_token, @@ -102,7 +102,7 @@ export const setBroadcastStatus = ({ }, resolve)); }; -export const createLiveStream = async({ +export const createLiveStream = async ({ room, access_token, refresh_token, diff --git a/app/metrics/server/lib/metrics.js b/app/metrics/server/lib/metrics.js index b0e47550363a..9d93284faedb 100644 --- a/app/metrics/server/lib/metrics.js +++ b/app/metrics/server/lib/metrics.js @@ -77,7 +77,7 @@ metrics.totalPrivateGroupMessages = new client.Gauge({ name: 'rocketchat_private metrics.totalDirectMessages = new client.Gauge({ name: 'rocketchat_direct_messages_total', help: 'total of messages in direct rooms' }); metrics.totalLivechatMessages = new client.Gauge({ name: 'rocketchat_livechat_messages_total', help: 'total of messages in livechat rooms' }); -const setPrometheusData = async() => { +const setPrometheusData = async () => { client.register.setDefaultLabels({ uniqueId: settings.get('uniqueID'), siteUrl: settings.get('Site_Url'), @@ -156,7 +156,7 @@ app.use('/', (req, res) => { const server = http.createServer(app); let timer; -const updatePrometheusConfig = async() => { +const updatePrometheusConfig = async () => { const port = process.env.PROMETHEUS_PORT || settings.get('Prometheus_Port'); const enabled = settings.get('Prometheus_Enabled'); if (port == null || enabled == null) { @@ -175,7 +175,7 @@ const updatePrometheusConfig = async() => { } }; -Meteor.startup(async() => { +Meteor.startup(async () => { settings.get('Prometheus_Enabled', updatePrometheusConfig); settings.get('Prometheus_Port', updatePrometheusConfig); }); diff --git a/app/push-notifications/client/views/pushNotificationsFlexTab.js b/app/push-notifications/client/views/pushNotificationsFlexTab.js index 3bc146934f19..f255ce84e67f 100644 --- a/app/push-notifications/client/views/pushNotificationsFlexTab.js +++ b/app/push-notifications/client/views/pushNotificationsFlexTab.js @@ -159,8 +159,8 @@ Template.pushNotificationsFlexTab.onCreated(function() { muteGroupMentions: new ReactiveVar(muteGroupMentions), }; - this.saveSetting = async() => { - Object.keys(this.original).forEach(async(field) => { + this.saveSetting = async () => { + Object.keys(this.original).forEach(async (field) => { if (this.original[field].get() === this.form[field].get()) { return; } diff --git a/app/threads/client/flextab/thread.js b/app/threads/client/flextab/thread.js index 685985e66d75..d8dbaf39500a 100644 --- a/app/threads/client/flextab/thread.js +++ b/app/threads/client/flextab/thread.js @@ -117,7 +117,7 @@ Template.thread.onRendered(function() { }); Tracker.afterFlush(() => { - this.autorun(async() => { + this.autorun(async () => { const { mainMessage } = Template.currentData(); this.state.set({ tmid: mainMessage._id, @@ -132,7 +132,7 @@ Template.thread.onCreated(async function() { this.state = new ReactiveDict(); - this.loadMore = _.debounce(async() => { + this.loadMore = _.debounce(async () => { if (this.state.get('loading')) { return; } diff --git a/app/threads/client/flextab/threads.js b/app/threads/client/flextab/threads.js index c8fbb6a18c8c..ffc4e2adfe47 100644 --- a/app/threads/client/flextab/threads.js +++ b/app/threads/client/flextab/threads.js @@ -79,7 +79,7 @@ Template.threads.onCreated(async function() { this.loadMore(); }; - this.loadMore = _.debounce(async() => { + this.loadMore = _.debounce(async () => { if (this.state.get('loading')) { return; } @@ -95,7 +95,7 @@ Template.threads.onCreated(async function() { }, 500); Tracker.afterFlush(() => { - this.autorun(async() => { + this.autorun(async () => { const { rid, mid } = Template.currentData(); this.close = !!mid; @@ -149,7 +149,7 @@ Template.threads.onCreated(async function() { }); }); - this.autorun(async() => { + this.autorun(async () => { const mid = this.state.get('mid'); return this.state.set('thread', mid && this.Threads.findOne({ _id: mid }, { fields: { tcount: 0, tlm: 0, replies: 0, _updatedAt: 0 } })); }); diff --git a/app/ui-admin/client/rooms/adminRoomInfo.js b/app/ui-admin/client/rooms/adminRoomInfo.js index 62acbbe6825a..9315413c6abb 100644 --- a/app/ui-admin/client/rooms/adminRoomInfo.js +++ b/app/ui-admin/client/rooms/adminRoomInfo.js @@ -269,7 +269,7 @@ Template.adminRoomInfo.onCreated(function() { this.editing.set(); }; - this.autorun(async() => { + this.autorun(async () => { this.roomOwner.set(null); for (const { roles, u } of await call('getRoomRoles', Session.get('adminRoomsSelected').rid)) { if (roles.includes('owner')) { diff --git a/app/ui-cached-collection/client/models/CachedCollection.js b/app/ui-cached-collection/client/models/CachedCollection.js index 9a31e3aaf9f4..72672d5b7a15 100644 --- a/app/ui-cached-collection/client/models/CachedCollection.js +++ b/app/ui-cached-collection/client/models/CachedCollection.js @@ -346,7 +346,7 @@ export class CachedCollection { } async setupListener(eventType, eventName) { - Meteor.startup(async() => { + Meteor.startup(async () => { const { RoomManager } = await import('../../../ui-utils'); const { ChatRoom, CachedChatRoom } = await import('../../../models'); Notifications[eventType || this.eventType](eventName || this.eventName, (t, record) => { diff --git a/app/ui-master/public/generateHTML.js b/app/ui-master/public/generateHTML.js index e240a336a6e3..729eb69e11ce 100644 --- a/app/ui-master/public/generateHTML.js +++ b/app/ui-master/public/generateHTML.js @@ -38,12 +38,12 @@ const header = `
`; -const start = async() => { +const start = async () => { const html = fs.createWriteStream('icons.html', { flags: 'w' }); html.write(header); try { await new Promise((resolve) => { - fs.readdir('./icons', async(err, files) => { + fs.readdir('./icons', async (err, files) => { files .sort(sort) .filter((file) => { @@ -52,7 +52,7 @@ const start = async() => { return false; } return true; - }).forEach(async(file) => { + }).forEach(async (file) => { const name = file.replace('.svg', '').toLocaleLowerCase(); console.log(name); html.write(iconHTML(name)); diff --git a/app/ui-master/public/generateSprite.js b/app/ui-master/public/generateSprite.js index b0ff105e2a6d..457cb109f3b0 100644 --- a/app/ui-master/public/generateSprite.js +++ b/app/ui-master/public/generateSprite.js @@ -33,13 +33,13 @@ const toSymbol = (id, viewBox, { id: _, ...args }) => ({ }); const xml = ''; -const start = async() => { +const start = async () => { const stream = fs.createWriteStream('icons.svg', { flags: 'w' }); stream.write(`${ xml }\n`); try { await new Promise((resolve) => { const path = './icons'; - fs.readdir(path, async(err, files) => { + fs.readdir(path, async (err, files) => { const promises = files .sort(sort) .filter((file) => { @@ -48,7 +48,7 @@ const start = async() => { return false; } return true; - }).map(async(file) => { + }).map(async (file) => { const name = file.replace('.svg', '').toLocaleLowerCase(); try { const content = fs.readFileSync(`${ path }/${ file }`, 'utf8'); diff --git a/app/ui-message/client/messageBoxAudioMessage.js b/app/ui-message/client/messageBoxAudioMessage.js index 9061223e604c..88a940fac416 100644 --- a/app/ui-message/client/messageBoxAudioMessage.js +++ b/app/ui-message/client/messageBoxAudioMessage.js @@ -39,7 +39,7 @@ const unregisterUploadProgress = (upload) => setTimeout(() => { Session.set('uploading', uploads.filter(({ id }) => id !== upload.id)); }, 2000); -const uploadRecord = async({ rid, tmid, blob }) => { +const uploadRecord = async ({ rid, tmid, blob }) => { const upload = fileUploadHandler('Uploads', { name: `${ t('Audio record') }.mp3`, size: blob.size, diff --git a/app/ui-message/client/popup/messagePopupConfig.js b/app/ui-message/client/popup/messagePopupConfig.js index 70897167458a..d839a7ad0ce2 100644 --- a/app/ui-message/client/popup/messagePopupConfig.js +++ b/app/ui-message/client/popup/messagePopupConfig.js @@ -53,7 +53,7 @@ const reloadUsersFromRoomMessages = (rid) => { })); }; -const fetchUsersFromServer = _.throttle(async(filterText, records, rid, cb) => { +const fetchUsersFromServer = _.throttle(async (filterText, records, rid, cb) => { const usernames = records.map(({ username }) => username); const { users } = await call('spotlight', filterText, usernames, { users: true }, rid); @@ -81,7 +81,7 @@ const fetchUsersFromServer = _.throttle(async(filterText, records, rid, cb) => { cb && cb(records); }, 1000); -const fetchRoomsFromServer = _.throttle(async(filterText, records, rid, cb) => { +const fetchRoomsFromServer = _.throttle(async (filterText, records, rid, cb) => { if (!hasAllPermission('view-outside-room')) { cb && cb([]); return; diff --git a/app/ui-utils/client/lib/ChannelActions.js b/app/ui-utils/client/lib/ChannelActions.js index b0cd7e577810..ae4623ada8ba 100644 --- a/app/ui-utils/client/lib/ChannelActions.js +++ b/app/ui-utils/client/lib/ChannelActions.js @@ -81,7 +81,7 @@ export function erase(rid) { cancelButtonText: t('Cancel'), closeOnConfirm: false, html: false, - }, async() => { + }, async () => { await call('eraseRoom', rid); modal.open({ title: t('Deleted'), diff --git a/app/ui-utils/client/lib/prependReplies.js b/app/ui-utils/client/lib/prependReplies.js index 370652a72274..b7a944eeca05 100644 --- a/app/ui-utils/client/lib/prependReplies.js +++ b/app/ui-utils/client/lib/prependReplies.js @@ -2,10 +2,10 @@ import { Meteor } from 'meteor/meteor'; import { MessageAction } from './MessageAction'; import { Rooms, Users } from '../../../models/client'; -export const prependReplies = async(msg, replies = [], mention = false) => { +export const prependReplies = async (msg, replies = [], mention = false) => { const { username } = Users.findOne({ _id: Meteor.userId() }, { fields: { username: 1 } }); - const chunks = await Promise.all(replies.map(async({ _id, rid, u }) => { + const chunks = await Promise.all(replies.map(async ({ _id, rid, u }) => { const permalink = await MessageAction.getPermaLink(_id); const room = Rooms.findOne(rid, { fields: { t: 1 } }); diff --git a/app/ui/client/lib/fileUpload.js b/app/ui/client/lib/fileUpload.js index 4a1e8186bd64..696e54be9461 100644 --- a/app/ui/client/lib/fileUpload.js +++ b/app/ui/client/lib/fileUpload.js @@ -114,7 +114,7 @@ const getGenericUploadPreview = (file) => `\
`; -const getUploadPreview = async(file, preview) => { +const getUploadPreview = async (file, preview) => { if (file.type === 'audio') { return getAudioUploadPreview(file, preview); } @@ -137,7 +137,7 @@ const getUploadPreview = async(file, preview) => { return getGenericUploadPreview(file, preview); }; -export const fileUpload = async(files, input, { rid, tmid }) => { +export const fileUpload = async (files, input, { rid, tmid }) => { files = [].concat(files); const replies = $(input).data('reply') || []; @@ -170,7 +170,7 @@ export const fileUpload = async(files, input, { rid, tmid }) => { return; } - showUploadPreview(file, async(file, preview) => modal.open({ + showUploadPreview(file, async (file, preview) => modal.open({ title: t('Upload_file_question'), text: await getUploadPreview(file, preview), showCancelButton: true, diff --git a/client/routes/roomRoute.js b/client/routes/roomRoute.js index e2c977252220..ef0c29aef73c 100644 --- a/client/routes/roomRoute.js +++ b/client/routes/roomRoute.js @@ -7,7 +7,7 @@ import { call } from '../../app/ui-utils'; const getRoomById = mem((rid) => call('getRoomById', rid)); -FlowRouter.goToRoomById = async(rid) => { +FlowRouter.goToRoomById = async (rid) => { if (!rid) { return; } diff --git a/server/startup/migrations/v123.js b/server/startup/migrations/v123.js index a33563eabfa0..8c7ee9e7037c 100644 --- a/server/startup/migrations/v123.js +++ b/server/startup/migrations/v123.js @@ -85,7 +85,7 @@ Migrations.add({ /* * Move visitor navigation history to messages */ - Meteor.setTimeout(async() => { + Meteor.setTimeout(async () => { const pages = pageVisitedCollection.find({}); const total = await pages.count(); await pages.close(); diff --git a/tests/end-to-end/api/02-channels.js b/tests/end-to-end/api/02-channels.js index 6f1548a48ed9..40d3a5925fe1 100644 --- a/tests/end-to-end/api/02-channels.js +++ b/tests/end-to-end/api/02-channels.js @@ -176,7 +176,7 @@ describe('[Channels]', function() { }); }); - it('/channels.invite', async(done) => { + it('/channels.invite', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.invite')) @@ -257,7 +257,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.kick', async(done) => { + it('/channels.kick', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.kick')) @@ -278,7 +278,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.invite', async(done) => { + it('/channels.invite', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.invite')) @@ -533,7 +533,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.rename', async(done) => { + it('/channels.rename', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.rename')) @@ -646,7 +646,7 @@ describe('[Channels]', function() { }) .end(done); }); - it('change customFields', async(done) => { + it('change customFields', async (done) => { const customFields = { field9:'value9' }; request.post(api('channels.setCustomFields')) .set(credentials) @@ -704,7 +704,7 @@ describe('[Channels]', function() { done(); }); }); - it('set customFields with one nested field', async(done) => { + it('set customFields with one nested field', async (done) => { const customFields = { field1:'value1' }; request.post(api('channels.setCustomFields')) .set(credentials) @@ -723,7 +723,7 @@ describe('[Channels]', function() { }) .end(done); }); - it('set customFields with multiple nested fields', async(done) => { + it('set customFields with multiple nested fields', async (done) => { const customFields = { field2:'value2', field3:'value3', field4:'value4' }; request.post(api('channels.setCustomFields')) @@ -746,7 +746,7 @@ describe('[Channels]', function() { }) .end(done); }); - it('set customFields to empty object', async(done) => { + it('set customFields to empty object', async (done) => { const customFields = {}; request.post(api('channels.setCustomFields')) @@ -768,7 +768,7 @@ describe('[Channels]', function() { }) .end(done); }); - it('set customFields as a string -> should return 400', async(done) => { + it('set customFields as a string -> should return 400', async (done) => { const customFields = ''; request.post(api('channels.setCustomFields')) @@ -799,7 +799,7 @@ describe('[Channels]', function() { }); }); - it('/channels.setJoinCode', async(done) => { + it('/channels.setJoinCode', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.setJoinCode')) @@ -820,7 +820,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.setReadOnly', async(done) => { + it('/channels.setReadOnly', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.setReadOnly')) @@ -841,7 +841,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.setDefault', async(done) => { + it('/channels.setDefault', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.setDefault')) @@ -862,7 +862,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.leave', async(done) => { + it('/channels.leave', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.leave')) @@ -882,7 +882,7 @@ describe('[Channels]', function() { .end(done); }); - it('/channels.setType', async(done) => { + it('/channels.setType', async (done) => { const roomInfo = await getRoomInfo(channel._id); request.post(api('channels.setType')) @@ -978,7 +978,7 @@ describe('[Channels]', function() { done(); }); }); - it('/channels.invite', async(done) => { + it('/channels.invite', async (done) => { request.post(api('channels.invite')) .set(credentials) .send({ @@ -1048,7 +1048,7 @@ describe('[Channels]', function() { done(); }); }); - it('/channels.invite', async(done) => { + it('/channels.invite', async (done) => { request.post(api('channels.invite')) .set(credentials) .send({ diff --git a/tests/end-to-end/api/03-groups.js b/tests/end-to-end/api/03-groups.js index 3fa5094f9726..0bc80ac621af 100644 --- a/tests/end-to-end/api/03-groups.js +++ b/tests/end-to-end/api/03-groups.js @@ -169,7 +169,7 @@ describe('[Groups]', function() { }); }); - it('/groups.invite', async(done) => { + it('/groups.invite', async (done) => { const roomInfo = await getRoomInfo(group._id); request.post(api('groups.invite')) @@ -295,7 +295,7 @@ describe('[Groups]', function() { .end(done); }); - it('/groups.invite', async(done) => { + it('/groups.invite', async (done) => { const roomInfo = await getRoomInfo(group._id); request.post(api('groups.invite')) @@ -502,7 +502,7 @@ describe('[Groups]', function() { .end(done); }); - it('/groups.rename', async(done) => { + it('/groups.rename', async (done) => { const roomInfo = await getRoomInfo(group._id); request.post(api('groups.rename')) @@ -628,7 +628,7 @@ describe('[Groups]', function() { }) .end(done); }); - it('change customFields', async(done) => { + it('change customFields', async (done) => { const customFields = { field9:'value9' }; request.post(api('groups.setCustomFields')) .set(credentials) @@ -686,7 +686,7 @@ describe('[Groups]', function() { done(); }); }); - it('set customFields with one nested field', async(done) => { + it('set customFields with one nested field', async (done) => { const customFields = { field1:'value1' }; request.post(api('groups.setCustomFields')) .set(credentials) @@ -705,7 +705,7 @@ describe('[Groups]', function() { }) .end(done); }); - it('set customFields with multiple nested fields', async(done) => { + it('set customFields with multiple nested fields', async (done) => { const customFields = { field2:'value2', field3:'value3', field4:'value4' }; request.post(api('groups.setCustomFields')) @@ -728,7 +728,7 @@ describe('[Groups]', function() { }) .end(done); }); - it('set customFields to empty object', async(done) => { + it('set customFields to empty object', async (done) => { const customFields = {}; request.post(api('groups.setCustomFields')) @@ -750,7 +750,7 @@ describe('[Groups]', function() { }) .end(done); }); - it('set customFields as a string -> should return 400', async(done) => { + it('set customFields as a string -> should return 400', async (done) => { const customFields = ''; request.post(api('groups.setCustomFields')) @@ -836,7 +836,7 @@ describe('[Groups]', function() { done(); }); }); - it('/groups.invite', async(done) => { + it('/groups.invite', async (done) => { request.post(api('groups.invite')) .set(credentials) .send({ @@ -906,7 +906,7 @@ describe('[Groups]', function() { done(); }); }); - it('/groups.invite', async(done) => { + it('/groups.invite', async (done) => { request.post(api('groups.invite')) .set(credentials) .send({ diff --git a/tests/end-to-end/ui/14-message-popup.js b/tests/end-to-end/ui/14-message-popup.js index 1b2267936bd1..781dedfdf107 100644 --- a/tests/end-to-end/ui/14-message-popup.js +++ b/tests/end-to-end/ui/14-message-popup.js @@ -20,7 +20,7 @@ const users = new Array(10).fill(null) isMentionable: i % 2 === 0, })); -const createTestUser = async({ email, name, username, password, isMentionable }) => { +const createTestUser = async ({ email, name, username, password, isMentionable }) => { await new Promise((done) => getCredentials(done)); await new Promise((done) => request.post(api('users.create')) @@ -72,7 +72,7 @@ describe('[Message Popup]', () => { Meteor.logout(done); }); - browser.call(async() => { + browser.call(async () => { for (const user of users) { await createTestUser(user); } From 902cfda9db7dad6dc0c9fdb8c82e4360cb48083c Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Wed, 10 Apr 2019 17:20:40 -0300 Subject: [PATCH 04/15] WIP: move slack api calls to a specififc file --- app/slackbridge/server/SlackAPI.js | 37 +++++++++++++ app/slackbridge/server/SlackAdapter.js | 53 +++++++++---------- .../server/slackbridge_import.server.js | 2 +- 3 files changed, 64 insertions(+), 28 deletions(-) create mode 100644 app/slackbridge/server/SlackAPI.js diff --git a/app/slackbridge/server/SlackAPI.js b/app/slackbridge/server/SlackAPI.js new file mode 100644 index 000000000000..70e90c84e66a --- /dev/null +++ b/app/slackbridge/server/SlackAPI.js @@ -0,0 +1,37 @@ +import { HTTP } from 'meteor/http'; + +export class SlackAPI { + + constructor(apiToken) { + this.apiToken = apiToken; + } + + getChannels() { + const response = HTTP.get('https://slack.com/api/conversations.list', { params: { token: this.apiToken, types: 'public_channel' } }); + return response && response.data && Array.isArray(response.data.channels) && response.data.channels.length > 0 + ? response.data.channels + : []; + } + + getChannelInfo(channelId) { + const response = HTTP.get('https://slack.com/api/channels.info', { params: { token: this.apiToken, channel: channelId } }); + + return response && response.data && response.data.channel; + } + + getGroups() { + const response = HTTP.get('https://slack.com/api/conversations.list', { params: { token: this.apiToken, types: 'private_channel' } }); + return response && response.data && Array.isArray(response.data.channels) && response.data.channels.length > 0 + ? response.data.channels + : []; + } + + getGroupInfo() { + + } + + react(data) { + const response = HTTP.post('https://slack.com/api/reactions.add', { params: data }); + return response && response.data && response.data.ok; + } +} \ No newline at end of file diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 0f4b73d02c2f..532965f2c73f 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -1,3 +1,9 @@ +import _ from 'underscore'; +import url from 'url'; +import http from 'http'; +import https from 'https'; +import { RTMClient } from '@slack/client'; + import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; import { getAvatarUrlFromUsername } from '../../utils'; @@ -15,17 +21,13 @@ import { import { saveRoomName, saveRoomTopic } from '../../channel-settings'; import { FileUpload } from '../../file-upload'; import { logger } from './logger'; -import _ from 'underscore'; -import url from 'url'; -import http from 'http'; -import https from 'https'; +import { SlackAPI } from './SlackAPI'; export default class SlackAdapter { constructor(slackBridge) { logger.slack.debug('constructor'); this.slackBridge = slackBridge; - this.slackClient = require('@slack/client'); this.rtm = {}; // slack-client Real Time Messaging API this.apiToken = {}; // Slack API Token passed in via Connect // On Slack, a rocket integration bot will be added to slack channels, this is the list of those channels, key is Rocket Ch ID @@ -40,10 +42,10 @@ export default class SlackAdapter { connect(apiToken) { this.apiToken = apiToken; - const { RTMClient } = this.slackClient; if (RTMClient != null) { RTMClient.disconnect; } + this.slackAPI = new SlackAPI(apiToken); this.rtm = new RTMClient(this.apiToken); this.rtm.start(); this.registerForEvents(); @@ -332,7 +334,7 @@ export default class SlackAdapter { */ onReactionRemoved(slackReactionMsg) { if (slackReactionMsg) { - if (! this.slackBridge.isReactionsEnabled) { + if (!this.slackBridge.isReactionsEnabled) { return; } const rocketUser = this.rocket.getUser(slackReactionMsg.user); @@ -376,7 +378,7 @@ export default class SlackAdapter { */ onReactionAdded(slackReactionMsg) { if (slackReactionMsg) { - if (! this.slackBridge.isReactionsEnabled) { + if (!this.slackBridge.isReactionsEnabled) { return; } const rocketUser = this.rocket.getUser(slackReactionMsg.user); @@ -451,25 +453,22 @@ export default class SlackAdapter { postGetChannelInfo(slackChID) { logger.slack.debug('Getting slack channel info', slackChID); - const response = HTTP.get('https://slack.com/api/channels.info', { params: { token: this.apiToken, channel: slackChID } }); - if (response && response.data) { - return response.data.channel; - } + return this.slackAPI.getChannelInfo(slackChID); } postFindChannel(rocketChannelName) { logger.slack.debug('Searching for Slack channel or group', rocketChannelName); - let response = HTTP.get('https://slack.com/api/channels.list', { params: { token: this.apiToken } }); - if (response && response.data && _.isArray(response.data.channels) && response.data.channels.length > 0) { - for (const channel of response.data.channels) { + const channels = this.slackAPI.getChannels(); + if (channels && channels.length > 0) { + for (const channel of channels) { if (channel.name === rocketChannelName && channel.is_member === true) { return channel; } } } - response = HTTP.get('https://slack.com/api/groups.list', { params: { token: this.apiToken } }); - if (response && response.data && _.isArray(response.data.groups) && response.data.groups.length > 0) { - for (const group of response.data.groups) { + const groups = this.slackAPI.getGroups(); + if (groups && groups.length > 0) { + for (const group of groups) { if (group.name === rocketChannelName) { return group; } @@ -532,9 +531,9 @@ export default class SlackAdapter { } populateMembershipChannelMapByChannels() { - const response = HTTP.get('https://slack.com/api/channels.list', { params: { token: this.apiToken } }); - if (response && response.data && _.isArray(response.data.channels) && response.data.channels.length > 0) { - for (const slackChannel of response.data.channels) { + const channels = this.slackAPI.getChannels(); + if (channels && channels.length > 0) { + for (const slackChannel of channels) { const rocketchat_room = Rooms.findOneByName(slackChannel.name, { fields: { _id: 1 } }); if (rocketchat_room) { if (slackChannel.is_member) { @@ -546,9 +545,9 @@ export default class SlackAdapter { } populateMembershipChannelMapByGroups() { - const response = HTTP.get('https://slack.com/api/conversations.list', { params: { token: this.apiToken, types: 'private_channel' } }); - if (response && response.data && _.isArray(response.data.channels) && response.data.channels.length > 0) { - for (const slackGroup of response.data.channels) { + const groups = this.slackAPI.getGroups(); + if (groups && groups.length > 0) { + for (const slackGroup of groups) { const rocketchat_room = Rooms.findOneByName(slackGroup.name, { fields: { _id: 1 } }); if (rocketchat_room) { if (slackGroup.is_member) { @@ -578,8 +577,8 @@ export default class SlackAdapter { }; logger.slack.debug('Posting Add Reaction to Slack'); - const postResult = HTTP.post('https://slack.com/api/reactions.add', { params: data }); - if (postResult.statusCode === 200 && postResult.data && postResult.data.ok === true) { + const postResult = this.slackAPI.react(data); + if (postResult) { logger.slack.debug('Reaction added to Slack'); } } @@ -1132,7 +1131,7 @@ export default class SlackAdapter { logger.slack.info('importMessages: ', rid); const rocketchat_room = Rooms.findOneById(rid); if (rocketchat_room) { - if (this.getSlackChannel(rid)) { + if (this.getSlackChannel(rid) && false) { this.copyChannelInfo(rid, this.getSlackChannel(rid)); logger.slack.debug('Importing messages from Slack to Rocket.Chat', this.getSlackChannel(rid), rid); diff --git a/app/slackbridge/server/slackbridge_import.server.js b/app/slackbridge/server/slackbridge_import.server.js index dc835e41a406..5693839cfc50 100644 --- a/app/slackbridge/server/slackbridge_import.server.js +++ b/app/slackbridge/server/slackbridge_import.server.js @@ -28,7 +28,7 @@ function SlackBridgeImport(command, params, item) { }); try { - SlackBridge.importMessages(item.rid, (error) => { + SlackBridge.slack.importMessages(item.rid, (error) => { if (error) { msgStream.emit(item.rid, { _id: Random.id(), From aeafd79575868548fe55d65dac94c6656c2559da Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 12 Apr 2019 17:19:38 -0300 Subject: [PATCH 05/15] Changed all references directly to the slack api --- app/slackbridge/server/RocketAdapter.js | 101 ++++++++++++++---- app/slackbridge/server/SlackAPI.js | 131 ++++++++++++++++++------ app/slackbridge/server/SlackAdapter.js | 43 ++++---- app/slackbridge/server/slackbridge.js | 1 + 4 files changed, 204 insertions(+), 72 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index 5763eb278c15..f8bf096da4be 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -1,3 +1,6 @@ +import _ from 'underscore'; +import util from 'util'; + import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; @@ -7,8 +10,7 @@ import { settings } from '../../settings'; import { Messages, Rooms, Users } from '../../models'; import { createRoom, sendMessage, setUserAvatar } from '../../lib'; import { logger } from './logger'; -import _ from 'underscore'; -import util from 'util'; +import { SlackAPI } from './SlackAPI'; export default class RocketAdapter { constructor(slackBridge) { @@ -17,6 +19,11 @@ export default class RocketAdapter { this.util = util; this.userTags = {}; this.slack = {}; + this.slackAPI = {}; + } + + setSlackAPI(apiToken) { + this.slackAPI = new SlackAPI(apiToken); } connect() { @@ -49,7 +56,7 @@ export default class RocketAdapter { onMessageDelete(rocketMessageDeleted) { try { - if (! this.slack.getSlackChannel(rocketMessageDeleted.rid)) { + if (!this.slack.getSlackChannel(rocketMessageDeleted.rid)) { // This is on a channel that the rocket bot is not subscribed return; } @@ -116,7 +123,7 @@ export default class RocketAdapter { onMessage(rocketMessage) { try { - if (! this.slack.getSlackChannel(rocketMessage.rid)) { + if (!this.slack.getSlackChannel(rocketMessage.rid)) { // This is on a channel that the rocket bot is not subscribed return; } @@ -238,19 +245,22 @@ export default class RocketAdapter { addChannel(slackChannelID, hasRetried = false) { logger.rocket.debug('Adding Rocket.Chat channel from Slack', slackChannelID); let slackResults = null; - let slackMembers = null; - slackResults = HTTP.get('https://slack.com/api/conversations.info', { params: { token: this.slackBridge.apiToken, channel: slackChannelID } }); - if (slackResults && slackResults.data && slackResults.data.ok === true) { - slackMembers = HTTP.get('https://slack.com/api/conversations.members', { params: { token: this.slackBridge.apiToken, channel: slackChannelID } }); - if (slackMembers && slackMembers.data && slackMembers.data.ok === true) { - slackResults.data.channel.members = slackMembers.data.members; - } else { - slackResults = null; + let members = null; + const channel = this.slackAPI.getRoomInfo(slackChannelID); + if (channel) { + members = this.slackAPI.getMembers(slackChannelID); + if (!members) { logger.rocket.error('Could not fetch room members'); } + // if (slackMembers && slackMembers.data && slackMembers.data.ok === true) { + // slackResults.data.channel.members = slackMembers.data.members; + // } else { + // slackResults = null; + // logger.rocket.error('Could not fetch room members'); + // } } - if (slackResults && slackResults.data && slackResults.data.ok === true) { - const rocketChannelData = slackResults.data.channel; + if (channel && members) { + const rocketChannelData = channel; const existingRocketRoom = Rooms.findOneByName(rocketChannelData.name); // If the room exists, make sure we have its id in importIds @@ -259,7 +269,7 @@ export default class RocketAdapter { Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); } else { const rocketUsers = []; - for (const member of rocketChannelData.members) { + for (const member of members) { if (member !== rocketChannelData.creator) { const rocketUser = this.findUser(member) || this.addUser(member); if (rocketUser && rocketUser.username) { @@ -304,6 +314,61 @@ export default class RocketAdapter { this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); return Rooms.findOneById(rocketChannelData.rocketId); } + // if (slackResults && slackResults.data && slackResults.data.ok === true) { + // const rocketChannelData = slackResults.data.channel; + // const existingRocketRoom = Rooms.findOneByName(rocketChannelData.name); + // + // // If the room exists, make sure we have its id in importIds + // if (existingRocketRoom || rocketChannelData.is_general) { + // rocketChannelData.rocketId = rocketChannelData.is_general ? 'GENERAL' : existingRocketRoom._id; + // Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); + // } else { + // const rocketUsers = []; + // for (const member of rocketChannelData.members) { + // if (member !== rocketChannelData.creator) { + // const rocketUser = this.findUser(member) || this.addUser(member); + // if (rocketUser && rocketUser.username) { + // rocketUsers.push(rocketUser.username); + // } + // } + // } + // const rocketUserCreator = rocketChannelData.creator ? this.findUser(rocketChannelData.creator) || this.addUser(rocketChannelData.creator) : null; + // if (!rocketUserCreator) { + // logger.rocket.error('Could not fetch room creator information', rocketChannelData.creator); + // return; + // } + // + // try { + // const isPrivate = rocketChannelData.is_private; + // const rocketChannel = createRoom(isPrivate ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); + // rocketChannelData.rocketId = rocketChannel.rid; + // } catch (e) { + // if (!hasRetried) { + // logger.rocket.debug('Error adding channel from Slack. Will retry in 1s.', e.message); + // // If first time trying to create channel fails, could be because of multiple messages received at the same time. Try again once after 1s. + // Meteor._sleepForMs(1000); + // return this.findChannel(slackChannelID) || this.addChannel(slackChannelID, true); + // } else { + // console.log(e.message); + // } + // } + // + // const roomUpdate = { + // ts: new Date(rocketChannelData.created * 1000), + // }; + // let lastSetTopic = 0; + // if (!_.isEmpty(rocketChannelData.topic && rocketChannelData.topic.value)) { + // roomUpdate.topic = rocketChannelData.topic.value; + // lastSetTopic = rocketChannelData.topic.last_set; + // } + // if (!_.isEmpty(rocketChannelData.purpose && rocketChannelData.purpose.value) && rocketChannelData.purpose.last_set > lastSetTopic) { + // roomUpdate.topic = rocketChannelData.purpose.value; + // } + // Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); + // } + // this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); + // return Rooms.findOneById(rocketChannelData.rocketId); + // } logger.rocket.debug('Channel not added'); return; } @@ -318,9 +383,9 @@ export default class RocketAdapter { addUser(slackUserID) { logger.rocket.debug('Adding Rocket.Chat user from Slack', slackUserID); - const slackResults = HTTP.get('https://slack.com/api/users.info', { params: { token: this.slackBridge.apiToken, user: slackUserID } }); - if (slackResults && slackResults.data && slackResults.data.ok === true && slackResults.data.user) { - const rocketUserData = slackResults.data.user; + const user = this.slackAPI.getUser(slackUserID); + if (user) { + const rocketUserData = user; const isBot = rocketUserData.is_bot === true; const email = (rocketUserData.profile && rocketUserData.profile.email) || ''; let existingRocketUser; diff --git a/app/slackbridge/server/SlackAPI.js b/app/slackbridge/server/SlackAPI.js index 70e90c84e66a..812a76c2c964 100644 --- a/app/slackbridge/server/SlackAPI.js +++ b/app/slackbridge/server/SlackAPI.js @@ -2,36 +2,101 @@ import { HTTP } from 'meteor/http'; export class SlackAPI { - constructor(apiToken) { - this.apiToken = apiToken; - } - - getChannels() { - const response = HTTP.get('https://slack.com/api/conversations.list', { params: { token: this.apiToken, types: 'public_channel' } }); - return response && response.data && Array.isArray(response.data.channels) && response.data.channels.length > 0 - ? response.data.channels - : []; - } - - getChannelInfo(channelId) { - const response = HTTP.get('https://slack.com/api/channels.info', { params: { token: this.apiToken, channel: channelId } }); - - return response && response.data && response.data.channel; - } - - getGroups() { - const response = HTTP.get('https://slack.com/api/conversations.list', { params: { token: this.apiToken, types: 'private_channel' } }); - return response && response.data && Array.isArray(response.data.channels) && response.data.channels.length > 0 - ? response.data.channels - : []; - } - - getGroupInfo() { - - } - - react(data) { - const response = HTTP.post('https://slack.com/api/reactions.add', { params: data }); - return response && response.data && response.data.ok; - } -} \ No newline at end of file + constructor(apiToken) { + this.apiToken = apiToken; + } + + getChannels() { + const response = HTTP.get('https://slack.com/api/conversations.list', { + params: { + token: this.apiToken, + types: 'public_channel', + }, + }); + return response && response.data && Array.isArray(response.data.channels) && response.data.channels.length > 0 + ? response.data.channels + : []; + } + + getGroups() { + const response = HTTP.get('https://slack.com/api/conversations.list', { + params: { + token: this.apiToken, + types: 'private_channel', + }, + }); + return response && response.data && Array.isArray(response.data.channels) && response.data.channels.length > 0 + ? response.data.channels + : []; + } + + getRoomInfo(roomId) { + const response = HTTP.get('https://slack.com/api/conversations.info', { + params: { + token: this.apiToken, + channel: roomId, + }, + }); + return response && response.data && response.statusCode === 200 && response.data.ok && response.data.channel; + } + + getMembers(channelId) { + const response = HTTP.get('https://slack.com/api/conversations.members', { + params: { + token: this.apiToken, + channel: channelId, + }, + }); + return response && response.data && response.statusCode === 200 && response.data.ok && response.data.members; + } + + react(data) { + const response = HTTP.post('https://slack.com/api/reactions.add', { params: data }); + return response && response.statusCode === 200 && response.data && response.data.ok; + } + + removeReaction(data) { + const response = HTTP.post('https://slack.com/api/reactions.remove', { params: data }); + return response && response.statusCode === 200 && response.data && response.data.ok; + } + + removeMessage(data) { + const response = HTTP.post('https://slack.com/api/chat.delete', { params: data }); + return response && response.statusCode === 200 && response.data && response.data.ok; + } + + sendMessage(data) { + return HTTP.post('https://slack.com/api/chat.postMessage', { params: data }); + } + + updateMessage(data) { + const response = HTTP.post('https://slack.com/api/chat.update', { params: data }); + return response && response.statusCode === 200 && response.data && response.data.ok; + } + + getHistory(family, options) { + const response = HTTP.get(`https://slack.com/api/${ family }.history`, { params: Object.assign({ token: this.apiToken }, options) }); + return response && response.data; + } + + getPins(channelId) { + const response = HTTP.get('https://slack.com/api/pins.list', { + params: { + token: this.apiToken, + channel: channelId, + }, + }); + return response && response.data && response.statusCode === 200 && response.data.ok && response.data.items; + } + + getUser(userId) { + const response = HTTP.get('https://slack.com/api/users.info', { + params: { + token: this.apiToken, + user: userId, + }, + }); + return response && response.data && response.statusCode === 200 && response.data.ok && response.data.user; + } + +} diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 532965f2c73f..1c22a71db79d 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -45,7 +45,7 @@ export default class SlackAdapter { if (RTMClient != null) { RTMClient.disconnect; } - this.slackAPI = new SlackAPI(apiToken); + this.slackAPI = new SlackAPI(this.apiToken); this.rtm = new RTMClient(this.apiToken); this.rtm.start(); this.registerForEvents(); @@ -453,7 +453,7 @@ export default class SlackAdapter { postGetChannelInfo(slackChID) { logger.slack.debug('Getting slack channel info', slackChID); - return this.slackAPI.getChannelInfo(slackChID); + return this.slackAPI.getRoomInfo(slackChID); } postFindChannel(rocketChannelName) { @@ -597,8 +597,8 @@ export default class SlackAdapter { }; logger.slack.debug('Posting Remove Reaction to Slack'); - const postResult = HTTP.post('https://slack.com/api/reactions.remove', { params: data }); - if (postResult.statusCode === 200 && postResult.data && postResult.data.ok === true) { + const postResult = this.slackAPI.removeReaction(data); + if (postResult) { logger.slack.debug('Reaction removed from Slack'); } } @@ -617,8 +617,8 @@ export default class SlackAdapter { }; logger.slack.debug('Post Delete Message to Slack', data); - const postResult = HTTP.post('https://slack.com/api/chat.delete', { params: data }); - if (postResult.statusCode === 200 && postResult.data && postResult.data.ok === true) { + const postResult = this.slackAPI.removeMessage(data); + if (postResult) { logger.slack.debug('Message deleted on Slack'); } } @@ -640,7 +640,7 @@ export default class SlackAdapter { link_names: 1, }; logger.slack.debug('Post Message To Slack', data); - const postResult = HTTP.post('https://slack.com/api/chat.postMessage', { params: data }); + const postResult = this.slackAPI.sendMessage(data); if (postResult.statusCode === 200 && postResult.data && postResult.data.message && postResult.data.message.bot_id && postResult.data.message.ts) { Messages.setSlackBotIdAndSlackTs(rocketMessage._id, postResult.data.message.bot_id, postResult.data.message.ts); logger.slack.debug(`RocketMsgID=${ rocketMessage._id } SlackMsgID=${ postResult.data.message.ts } SlackBotID=${ postResult.data.message.bot_id }`); @@ -661,8 +661,8 @@ export default class SlackAdapter { as_user: true, }; logger.slack.debug('Post UpdateMessage To Slack', data); - const postResult = HTTP.post('https://slack.com/api/chat.update', { params: data }); - if (postResult.statusCode === 200 && postResult.data && postResult.data.ok === true) { + const postResult = this.slackAPI.updateMessage(data); + if (postResult) { logger.slack.debug('Message updated on Slack'); } } @@ -1040,10 +1040,10 @@ export default class SlackAdapter { importFromHistory(family, options) { logger.slack.debug('Importing messages history'); - const response = HTTP.get(`https://slack.com/api/${ family }.history`, { params: _.extend({ token: this.apiToken }, options) }); - if (response && response.data && _.isArray(response.data.messages) && response.data.messages.length > 0) { + const data = this.slackAPI.getHistory(family, options); + if (Array.isArray(data.messages) && data.messages.length) { let latest = 0; - for (const message of response.data.messages.reverse()) { + for (const message of data.messages.reverse()) { logger.slack.debug('MESSAGE: ', message); if (!latest || message.ts > latest) { latest = message.ts; @@ -1051,16 +1051,17 @@ export default class SlackAdapter { message.channel = options.channel; this.onMessage(message, true); } - return { has_more: response.data.has_more, ts: latest }; + return { has_more: data.has_more, ts: latest }; } } copyChannelInfo(rid, channelMap) { logger.slack.debug('Copying users from Slack channel to Rocket.Chat', channelMap.id, rid); - const response = HTTP.get(`https://slack.com/api/${ channelMap.family }.info`, { params: { token: this.apiToken, channel: channelMap.id } }); - if (response && response.data) { - const data = channelMap.family === 'channels' ? response.data.channel : response.data.group; - if (data && _.isArray(data.members) && data.members.length > 0) { + const channel = this.slackAPI.getRoomInfo(channelMap.id); + if (channel) { + const data = channel; + const members = this.slackAPI.getMembers(channelMap.id); + if (members && Array.isArray(members) && members.length) { for (const member of data.members) { const user = this.rocket.findUser(member) || this.rocket.addUser(member); if (user) { @@ -1100,9 +1101,9 @@ export default class SlackAdapter { } copyPins(rid, channelMap) { - const response = HTTP.get('https://slack.com/api/pins.list', { params: { token: this.apiToken, channel: channelMap.id } }); - if (response && response.data && _.isArray(response.data.items) && response.data.items.length > 0) { - for (const pin of response.data.items) { + const items = this.slackAPI.getPins(channelMap.id); + if (items && Array.isArray(items) && items.length) { + for (const pin of items) { if (pin.message) { const user = this.rocket.findUser(pin.message.user); const msgObj = { @@ -1131,7 +1132,7 @@ export default class SlackAdapter { logger.slack.info('importMessages: ', rid); const rocketchat_room = Rooms.findOneById(rid); if (rocketchat_room) { - if (this.getSlackChannel(rid) && false) { + if (this.getSlackChannel(rid)) { this.copyChannelInfo(rid, this.getSlackChannel(rid)); logger.slack.debug('Importing messages from Slack to Rocket.Chat', this.getSlackChannel(rid), rid); diff --git a/app/slackbridge/server/slackbridge.js b/app/slackbridge/server/slackbridge.js index f8757a1c234a..484b6f3135cc 100644 --- a/app/slackbridge/server/slackbridge.js +++ b/app/slackbridge/server/slackbridge.js @@ -33,6 +33,7 @@ class SlackBridgeClass { if (settings.get('SlackBridge_Out_Enabled')) { this.rocket.connect(); } + this.rocket.setSlackAPI(this.apiToken); this.connected = true; logger.connection.info('Enabled'); From 7b63b36f0b2d19293ed8cc0f3dc3681e81c9e28d Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Fri, 12 Apr 2019 17:20:28 -0300 Subject: [PATCH 06/15] Fix reactions to execute unsetReaction always when a reaction was removed --- app/reactions/server/setReaction.js | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/app/reactions/server/setReaction.js b/app/reactions/server/setReaction.js index 831d33fc8633..625ca44f58c2 100644 --- a/app/reactions/server/setReaction.js +++ b/app/reactions/server/setReaction.js @@ -46,22 +46,19 @@ export function setReaction(room, user, message, reaction, shouldReact) { } if (userAlreadyReacted) { removeUserReaction(message, reaction, user.username); - + callbacks.run('unsetReaction', message._id, reaction); + callbacks.run('afterUnsetReaction', message, { user, reaction, shouldReact }); if (_.isEmpty(message.reactions)) { delete message.reactions; if (isTheLastMessage(room, message)) { Rooms.unsetReactionsInLastMessage(room._id); } Messages.unsetReactions(message._id); - callbacks.run('unsetReaction', message._id, reaction); - callbacks.run('afterUnsetReaction', message, { user, reaction, shouldReact }); } else { Messages.setReactions(message._id, message.reactions); if (isTheLastMessage(room, message)) { Rooms.setReactionsInLastMessage(room._id, message); } - callbacks.run('setReaction', message._id, reaction); - callbacks.run('afterSetReaction', message, { user, reaction, shouldReact }); } } else { if (!message.reactions) { From df8d7e2f01b7a95498f9b18bb1d6c601bb3e574a Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 15 Apr 2019 14:27:41 -0300 Subject: [PATCH 07/15] Add function to retrieve all members of slack channel and remove old code --- app/slackbridge/server/RocketAdapter.js | 64 ------------------------- app/slackbridge/server/SlackAPI.js | 30 +++++++++--- app/slackbridge/server/SlackAdapter.js | 3 -- 3 files changed, 23 insertions(+), 74 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index f8bf096da4be..af02c57ff1f5 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -1,10 +1,8 @@ import _ from 'underscore'; import util from 'util'; - import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; -import { HTTP } from 'meteor/http'; import { callbacks } from '../../callbacks'; import { settings } from '../../settings'; import { Messages, Rooms, Users } from '../../models'; @@ -244,7 +242,6 @@ export default class RocketAdapter { addChannel(slackChannelID, hasRetried = false) { logger.rocket.debug('Adding Rocket.Chat channel from Slack', slackChannelID); - let slackResults = null; let members = null; const channel = this.slackAPI.getRoomInfo(slackChannelID); if (channel) { @@ -252,12 +249,6 @@ export default class RocketAdapter { if (!members) { logger.rocket.error('Could not fetch room members'); } - // if (slackMembers && slackMembers.data && slackMembers.data.ok === true) { - // slackResults.data.channel.members = slackMembers.data.members; - // } else { - // slackResults = null; - // logger.rocket.error('Could not fetch room members'); - // } } if (channel && members) { const rocketChannelData = channel; @@ -314,61 +305,6 @@ export default class RocketAdapter { this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); return Rooms.findOneById(rocketChannelData.rocketId); } - // if (slackResults && slackResults.data && slackResults.data.ok === true) { - // const rocketChannelData = slackResults.data.channel; - // const existingRocketRoom = Rooms.findOneByName(rocketChannelData.name); - // - // // If the room exists, make sure we have its id in importIds - // if (existingRocketRoom || rocketChannelData.is_general) { - // rocketChannelData.rocketId = rocketChannelData.is_general ? 'GENERAL' : existingRocketRoom._id; - // Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); - // } else { - // const rocketUsers = []; - // for (const member of rocketChannelData.members) { - // if (member !== rocketChannelData.creator) { - // const rocketUser = this.findUser(member) || this.addUser(member); - // if (rocketUser && rocketUser.username) { - // rocketUsers.push(rocketUser.username); - // } - // } - // } - // const rocketUserCreator = rocketChannelData.creator ? this.findUser(rocketChannelData.creator) || this.addUser(rocketChannelData.creator) : null; - // if (!rocketUserCreator) { - // logger.rocket.error('Could not fetch room creator information', rocketChannelData.creator); - // return; - // } - // - // try { - // const isPrivate = rocketChannelData.is_private; - // const rocketChannel = createRoom(isPrivate ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); - // rocketChannelData.rocketId = rocketChannel.rid; - // } catch (e) { - // if (!hasRetried) { - // logger.rocket.debug('Error adding channel from Slack. Will retry in 1s.', e.message); - // // If first time trying to create channel fails, could be because of multiple messages received at the same time. Try again once after 1s. - // Meteor._sleepForMs(1000); - // return this.findChannel(slackChannelID) || this.addChannel(slackChannelID, true); - // } else { - // console.log(e.message); - // } - // } - // - // const roomUpdate = { - // ts: new Date(rocketChannelData.created * 1000), - // }; - // let lastSetTopic = 0; - // if (!_.isEmpty(rocketChannelData.topic && rocketChannelData.topic.value)) { - // roomUpdate.topic = rocketChannelData.topic.value; - // lastSetTopic = rocketChannelData.topic.last_set; - // } - // if (!_.isEmpty(rocketChannelData.purpose && rocketChannelData.purpose.value) && rocketChannelData.purpose.last_set > lastSetTopic) { - // roomUpdate.topic = rocketChannelData.purpose.value; - // } - // Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); - // } - // this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); - // return Rooms.findOneById(rocketChannelData.rocketId); - // } logger.rocket.debug('Channel not added'); return; } diff --git a/app/slackbridge/server/SlackAPI.js b/app/slackbridge/server/SlackAPI.js index 812a76c2c964..a4825cfd05ae 100644 --- a/app/slackbridge/server/SlackAPI.js +++ b/app/slackbridge/server/SlackAPI.js @@ -35,19 +35,35 @@ export class SlackAPI { params: { token: this.apiToken, channel: roomId, + include_num_members: true, }, }); return response && response.data && response.statusCode === 200 && response.data.ok && response.data.channel; } getMembers(channelId) { - const response = HTTP.get('https://slack.com/api/conversations.members', { - params: { - token: this.apiToken, - channel: channelId, - }, - }); - return response && response.data && response.statusCode === 200 && response.data.ok && response.data.members; + const { num_members } = this.getRoomInfo(channelId); + const MAX_MEMBERS_PER_CALL = 100; + let members = []; + let currentCursor = ''; + for (let index = 0; index < num_members; index += MAX_MEMBERS_PER_CALL) { + const response = HTTP.get('https://slack.com/api/conversations.members', { + params: { + token: this.apiToken, + channel: channelId, + limit: MAX_MEMBERS_PER_CALL, + cursor: currentCursor, + }, + }); + if (response && response.data && response.statusCode === 200 && response.data.ok && Array.isArray(response.data.members)) { + members = members.concat(response.data.members); + const hasMoreItems = response.data.response_metadata && response.data.response_metadata.next_cursor; + if (hasMoreItems) { + currentCursor = response.data.response_metadata.next_cursor; + } + } + } + return members; } react(data) { diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 1c22a71db79d..f0c21bf90403 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -1,11 +1,8 @@ -import _ from 'underscore'; import url from 'url'; import http from 'http'; import https from 'https'; import { RTMClient } from '@slack/client'; - import { Meteor } from 'meteor/meteor'; -import { HTTP } from 'meteor/http'; import { getAvatarUrlFromUsername } from '../../utils'; import { Messages, Rooms, Users } from '../../models'; import { settings } from '../../settings'; From ae51bf0f5a28774789a092e0cdec99062e57389b Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 15 Apr 2019 14:27:41 -0300 Subject: [PATCH 08/15] Add function to retrieve all members of slack channel and remove old code --- app/slackbridge/server/RocketAdapter.js | 148 +++++++----------------- app/slackbridge/server/SlackAPI.js | 30 +++-- app/slackbridge/server/SlackAdapter.js | 3 - 3 files changed, 67 insertions(+), 114 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index f8bf096da4be..fe938e377528 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -1,10 +1,8 @@ import _ from 'underscore'; import util from 'util'; - import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Random } from 'meteor/random'; -import { HTTP } from 'meteor/http'; import { callbacks } from '../../callbacks'; import { settings } from '../../settings'; import { Messages, Rooms, Users } from '../../models'; @@ -189,23 +187,23 @@ export default class RocketAdapter { } processFileShare(rocketMessage) { - if (! settings.get('SlackBridge_FileUpload_Enabled')) { + if (!settings.get('SlackBridge_FileUpload_Enabled')) { return; } if (rocketMessage.file.name) { - let file_name = rocketMessage.file.name; + let fileName = rocketMessage.file.name; let text = rocketMessage.msg; const attachment = this.getMessageAttachment(rocketMessage); if (attachment) { - file_name = Meteor.absoluteUrl(attachment.title_link); + fileName = Meteor.absoluteUrl(attachment.title_link); if (!text) { text = attachment.description; } } - const message = `${ text } ${ file_name }`; + const message = `${ text } ${ fileName }`; rocketMessage.msg = message; this.slack.postMessage(this.slack.getSlackChannel(rocketMessage.rid), rocketMessage); @@ -242,51 +240,50 @@ export default class RocketAdapter { return Rooms.findOneByImportId(slackChannelId); } + getRocketUsers(members, slackChannel) { + const rocketUsers = []; + for (const member of members) { + if (member !== slackChannel.creator) { + const rocketUser = this.findUser(member) || this.addUser(member); + if (rocketUser && rocketUser.username) { + rocketUsers.push(rocketUser.username); + } + } + } + return rocketUsers; + } + + getRocketUserCreator(slackChannel) { + return slackChannel.creator ? this.findUser(slackChannel.creator) || this.addUser(slackChannel.creator) : null + } + addChannel(slackChannelID, hasRetried = false) { logger.rocket.debug('Adding Rocket.Chat channel from Slack', slackChannelID); - let slackResults = null; - let members = null; - const channel = this.slackAPI.getRoomInfo(slackChannelID); - if (channel) { - members = this.slackAPI.getMembers(slackChannelID); + const slackChannel = this.slackAPI.getRoomInfo(slackChannelID); + if (slackChannel) { + const members = this.slackAPI.getMembers(slackChannelID); if (!members) { logger.rocket.error('Could not fetch room members'); + return; } - // if (slackMembers && slackMembers.data && slackMembers.data.ok === true) { - // slackResults.data.channel.members = slackMembers.data.members; - // } else { - // slackResults = null; - // logger.rocket.error('Could not fetch room members'); - // } - } - if (channel && members) { - const rocketChannelData = channel; - const existingRocketRoom = Rooms.findOneByName(rocketChannelData.name); + const rocketRoom = Rooms.findOneByName(slackChannel.name); // If the room exists, make sure we have its id in importIds - if (existingRocketRoom || rocketChannelData.is_general) { - rocketChannelData.rocketId = rocketChannelData.is_general ? 'GENERAL' : existingRocketRoom._id; - Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); + if (rocketRoom || slackChannel.is_general) { + slackChannel.rocketId = slackChannel.is_general ? 'GENERAL' : rocketRoom._id; + Rooms.addImportIds(slackChannel.rocketId, slackChannel.id); } else { - const rocketUsers = []; - for (const member of members) { - if (member !== rocketChannelData.creator) { - const rocketUser = this.findUser(member) || this.addUser(member); - if (rocketUser && rocketUser.username) { - rocketUsers.push(rocketUser.username); - } - } - } - const rocketUserCreator = rocketChannelData.creator ? this.findUser(rocketChannelData.creator) || this.addUser(rocketChannelData.creator) : null; + const rocketUsers = this.getRocketUsers(members, slackChannel); + const rocketUserCreator = this.getRocketUserCreator(slackChannel); if (!rocketUserCreator) { - logger.rocket.error('Could not fetch room creator information', rocketChannelData.creator); + logger.rocket.error('Could not fetch room creator information', slackChannel.creator); return; } try { - const isPrivate = rocketChannelData.is_private; - const rocketChannel = createRoom(isPrivate ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); - rocketChannelData.rocketId = rocketChannel.rid; + const isPrivate = slackChannel.is_private; + const rocketChannel = createRoom(isPrivate ? 'p' : 'c', slackChannel.name, rocketUserCreator.username, rocketUsers); + slackChannel.rocketId = rocketChannel.rid; } catch (e) { if (!hasRetried) { logger.rocket.debug('Error adding channel from Slack. Will retry in 1s.', e.message); @@ -299,78 +296,22 @@ export default class RocketAdapter { } const roomUpdate = { - ts: new Date(rocketChannelData.created * 1000), + ts: new Date(slackChannel.created * 1000), }; let lastSetTopic = 0; - if (!_.isEmpty(rocketChannelData.topic && rocketChannelData.topic.value)) { - roomUpdate.topic = rocketChannelData.topic.value; - lastSetTopic = rocketChannelData.topic.last_set; + if (slackChannel.topic && slackChannel.topic.value) { + roomUpdate.topic = slackChannel.topic.value; + lastSetTopic = slackChannel.topic.last_set; } - if (!_.isEmpty(rocketChannelData.purpose && rocketChannelData.purpose.value) && rocketChannelData.purpose.last_set > lastSetTopic) { - roomUpdate.topic = rocketChannelData.purpose.value; + if (slackChannel.purpose && slackChannel.purpose.value && slackChannel.purpose.last_set > lastSetTopic) { + roomUpdate.topic = slackChannel.purpose.value; } - Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); + Rooms.addImportIds(slackChannel.rocketId, slackChannel.id); } - this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); - return Rooms.findOneById(rocketChannelData.rocketId); + this.slack.addSlackChannel(slackChannel.rocketId, slackChannelID); + return Rooms.findOneById(slackChannel.rocketId); } - // if (slackResults && slackResults.data && slackResults.data.ok === true) { - // const rocketChannelData = slackResults.data.channel; - // const existingRocketRoom = Rooms.findOneByName(rocketChannelData.name); - // - // // If the room exists, make sure we have its id in importIds - // if (existingRocketRoom || rocketChannelData.is_general) { - // rocketChannelData.rocketId = rocketChannelData.is_general ? 'GENERAL' : existingRocketRoom._id; - // Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); - // } else { - // const rocketUsers = []; - // for (const member of rocketChannelData.members) { - // if (member !== rocketChannelData.creator) { - // const rocketUser = this.findUser(member) || this.addUser(member); - // if (rocketUser && rocketUser.username) { - // rocketUsers.push(rocketUser.username); - // } - // } - // } - // const rocketUserCreator = rocketChannelData.creator ? this.findUser(rocketChannelData.creator) || this.addUser(rocketChannelData.creator) : null; - // if (!rocketUserCreator) { - // logger.rocket.error('Could not fetch room creator information', rocketChannelData.creator); - // return; - // } - // - // try { - // const isPrivate = rocketChannelData.is_private; - // const rocketChannel = createRoom(isPrivate ? 'p' : 'c', rocketChannelData.name, rocketUserCreator.username, rocketUsers); - // rocketChannelData.rocketId = rocketChannel.rid; - // } catch (e) { - // if (!hasRetried) { - // logger.rocket.debug('Error adding channel from Slack. Will retry in 1s.', e.message); - // // If first time trying to create channel fails, could be because of multiple messages received at the same time. Try again once after 1s. - // Meteor._sleepForMs(1000); - // return this.findChannel(slackChannelID) || this.addChannel(slackChannelID, true); - // } else { - // console.log(e.message); - // } - // } - // - // const roomUpdate = { - // ts: new Date(rocketChannelData.created * 1000), - // }; - // let lastSetTopic = 0; - // if (!_.isEmpty(rocketChannelData.topic && rocketChannelData.topic.value)) { - // roomUpdate.topic = rocketChannelData.topic.value; - // lastSetTopic = rocketChannelData.topic.last_set; - // } - // if (!_.isEmpty(rocketChannelData.purpose && rocketChannelData.purpose.value) && rocketChannelData.purpose.last_set > lastSetTopic) { - // roomUpdate.topic = rocketChannelData.purpose.value; - // } - // Rooms.addImportIds(rocketChannelData.rocketId, rocketChannelData.id); - // } - // this.slack.addSlackChannel(rocketChannelData.rocketId, slackChannelID); - // return Rooms.findOneById(rocketChannelData.rocketId); - // } logger.rocket.debug('Channel not added'); - return; } findUser(slackUserID) { @@ -459,7 +400,6 @@ export default class RocketAdapter { return Users.findOneById(rocketUserData.rocketId); } logger.rocket.debug('User not added'); - return; } addAliasToMsg(rocketUserName, rocketMsgObj) { diff --git a/app/slackbridge/server/SlackAPI.js b/app/slackbridge/server/SlackAPI.js index 812a76c2c964..a4825cfd05ae 100644 --- a/app/slackbridge/server/SlackAPI.js +++ b/app/slackbridge/server/SlackAPI.js @@ -35,19 +35,35 @@ export class SlackAPI { params: { token: this.apiToken, channel: roomId, + include_num_members: true, }, }); return response && response.data && response.statusCode === 200 && response.data.ok && response.data.channel; } getMembers(channelId) { - const response = HTTP.get('https://slack.com/api/conversations.members', { - params: { - token: this.apiToken, - channel: channelId, - }, - }); - return response && response.data && response.statusCode === 200 && response.data.ok && response.data.members; + const { num_members } = this.getRoomInfo(channelId); + const MAX_MEMBERS_PER_CALL = 100; + let members = []; + let currentCursor = ''; + for (let index = 0; index < num_members; index += MAX_MEMBERS_PER_CALL) { + const response = HTTP.get('https://slack.com/api/conversations.members', { + params: { + token: this.apiToken, + channel: channelId, + limit: MAX_MEMBERS_PER_CALL, + cursor: currentCursor, + }, + }); + if (response && response.data && response.statusCode === 200 && response.data.ok && Array.isArray(response.data.members)) { + members = members.concat(response.data.members); + const hasMoreItems = response.data.response_metadata && response.data.response_metadata.next_cursor; + if (hasMoreItems) { + currentCursor = response.data.response_metadata.next_cursor; + } + } + } + return members; } react(data) { diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 1c22a71db79d..f0c21bf90403 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -1,11 +1,8 @@ -import _ from 'underscore'; import url from 'url'; import http from 'http'; import https from 'https'; import { RTMClient } from '@slack/client'; - import { Meteor } from 'meteor/meteor'; -import { HTTP } from 'meteor/http'; import { getAvatarUrlFromUsername } from '../../utils'; import { Messages, Rooms, Users } from '../../models'; import { settings } from '../../settings'; From d1c8561080d583912e28d293fee91c2ed0ca5d99 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 15 Apr 2019 16:11:43 -0300 Subject: [PATCH 09/15] Fix send files from slack to rocket --- app/slackbridge/server/SlackAdapter.js | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index f0c21bf90403..27367e914758 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -419,11 +419,17 @@ export default class SlackAdapter { onChannelLeft(channelLeftMsg) { this.removeSlackChannel(channelLeftMsg.channel); } + /** * We have received a message from slack and we need to save/delete/update it into rocket * https://api.slack.com/events/message */ onMessage(slackMessage, isImporting) { + const isAFileShare = slackMessage && slackMessage.files && Array.isArray(slackMessage.files) && slackMessage.files.length; + if (isAFileShare) { + this.processFileShare(slackMessage); + return; + } if (slackMessage.subtype) { switch (slackMessage.subtype) { case 'message_deleted': @@ -435,9 +441,6 @@ export default class SlackAdapter { case 'channel_join': this.processChannelJoin(slackMessage); break; - case 'file_share': - this.processFileShare(slackMessage); - break; default: // Keeping backwards compatability for now, refactor later this.processNewMessage(slackMessage, isImporting); @@ -674,11 +677,12 @@ export default class SlackAdapter { } processFileShare(slackMessage) { - if (! settings.get('SlackBridge_FileUpload_Enabled')) { + if (!settings.get('SlackBridge_FileUpload_Enabled')) { return; } + const file = slackMessage.files[0]; - if (slackMessage.file && slackMessage.file.url_private_download !== undefined) { + if (file && file.url_private_download !== undefined) { const rocketChannel = this.rocket.getChannel(slackMessage); const rocketUser = this.rocket.getUser(slackMessage.user); @@ -688,8 +692,8 @@ export default class SlackAdapter { // If the text includes the file link, simply use the same text for the rocket message. // If the link was not included, then use it instead of the message. - if (slackMessage.text.indexOf(slackMessage.file.permalink) < 0) { - slackMessage.text = slackMessage.file.permalink; + if (slackMessage.text.indexOf(file.permalink) < 0) { + slackMessage.text = file.permalink; } const ts = new Date(parseInt(slackMessage.ts.split('.')[0]) * 1000); From 71f3ca84e551f717fc52c70334461db391dd28d4 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 15 Apr 2019 16:18:03 -0300 Subject: [PATCH 10/15] Fix lint and remove unused code --- app/slackbridge/server/RocketAdapter.js | 10 +--------- app/slackbridge/server/SlackAdapter.js | 7 +------ 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index fe938e377528..487acb306728 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -178,14 +178,6 @@ export default class RocketAdapter { return rocketMessage.attachments.find((attachment) => attachment.title_link && attachment.title_link.indexOf(`/${ fileId }/`) >= 0); } - getFileDownloadUrl(rocketMessage) { - const attachment = this.getMessageAttachment(rocketMessage); - - if (attachment) { - return attachment.title_link; - } - } - processFileShare(rocketMessage) { if (!settings.get('SlackBridge_FileUpload_Enabled')) { return; @@ -254,7 +246,7 @@ export default class RocketAdapter { } getRocketUserCreator(slackChannel) { - return slackChannel.creator ? this.findUser(slackChannel.creator) || this.addUser(slackChannel.creator) : null + return slackChannel.creator ? this.findUser(slackChannel.creator) || this.addUser(slackChannel.creator) : null; } addChannel(slackChannelID, hasRetried = false) { diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 27367e914758..79a36a536bca 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -61,7 +61,7 @@ export default class SlackAdapter { * Unregister for slack events and disconnect from Slack */ disconnect() { - this.rtm.disconnect && this.rtm.disconnect; + this.rtm.disconnect && this.rtm.disconnect(); } setRocket(rocket) { @@ -451,11 +451,6 @@ export default class SlackAdapter { } } - postGetChannelInfo(slackChID) { - logger.slack.debug('Getting slack channel info', slackChID); - return this.slackAPI.getRoomInfo(slackChID); - } - postFindChannel(rocketChannelName) { logger.slack.debug('Searching for Slack channel or group', rocketChannelName); const channels = this.slackAPI.getChannels(); From 7a91d79f8a01e3deedf7fa56f7ca20d35dc935c4 Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 15 Apr 2019 16:27:42 -0300 Subject: [PATCH 11/15] Fix error on slackbridge importer --- app/slackbridge/server/SlackAdapter.js | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/app/slackbridge/server/SlackAdapter.js b/app/slackbridge/server/SlackAdapter.js index 79a36a536bca..f8dcc6f36a6d 100644 --- a/app/slackbridge/server/SlackAdapter.js +++ b/app/slackbridge/server/SlackAdapter.js @@ -1055,10 +1055,9 @@ export default class SlackAdapter { logger.slack.debug('Copying users from Slack channel to Rocket.Chat', channelMap.id, rid); const channel = this.slackAPI.getRoomInfo(channelMap.id); if (channel) { - const data = channel; const members = this.slackAPI.getMembers(channelMap.id); if (members && Array.isArray(members) && members.length) { - for (const member of data.members) { + for (const member of members) { const user = this.rocket.findUser(member) || this.rocket.addUser(member); if (user) { logger.slack.debug('Adding user to room', user.username, rid); @@ -1070,21 +1069,21 @@ export default class SlackAdapter { let topic = ''; let topic_last_set = 0; let topic_creator = null; - if (data && data.topic && data.topic.value) { - topic = data.topic.value; - topic_last_set = data.topic.last_set; - topic_creator = data.topic.creator; + if (channel && channel.topic && channel.topic.value) { + topic = channel.topic.value; + topic_last_set = channel.topic.last_set; + topic_creator = channel.topic.creator; } - if (data && data.purpose && data.purpose.value) { + if (channel && channel.purpose && channel.purpose.value) { if (topic_last_set) { - if (topic_last_set < data.purpose.last_set) { - topic = data.purpose.topic; - topic_creator = data.purpose.creator; + if (topic_last_set < channel.purpose.last_set) { + topic = channel.purpose.topic; + topic_creator = channel.purpose.creator; } } else { - topic = data.purpose.topic; - topic_creator = data.purpose.creator; + topic = channel.purpose.topic; + topic_creator = channel.purpose.creator; } } From 73bf91efc2c0a6c68d12386f19aa51f2abfa39ea Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Mon, 15 Apr 2019 17:24:22 -0300 Subject: [PATCH 12/15] Fix roompick in admin page, related to choose room to publish in slackbridge --- app/ui-admin/client/admin.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/ui-admin/client/admin.js b/app/ui-admin/client/admin.js index 5914955a9bec..f2ad5770a400 100644 --- a/app/ui-admin/client/admin.js +++ b/app/ui-admin/client/admin.js @@ -588,7 +588,7 @@ Template.admin.events({ selectedRooms[this.id] = (selectedRooms[this.id] || []).concat(doc); instance.selectedRooms.set(selectedRooms); const value = selectedRooms[this.id]; - TempSettings.update({ _id: this.id }, { $set: { value } }); + TempSettings.update({ _id: this.id }, { $set: { value, changed: JSON.stringify(settings.collectionPrivate.findOne(this.id).value) !== JSON.stringify(value) } }); event.currentTarget.value = ''; event.currentTarget.focus(); }, @@ -604,6 +604,7 @@ Template.admin.events({ TempSettings.update({ _id: settingId }, { $set: { value, + changed: JSON.stringify(settings.collectionPrivate.findOne(settingId).value) !== JSON.stringify(value), }, }); }, From 288ad556ff756b27a20aaf7130dabc1dc31d8d6b Mon Sep 17 00:00:00 2001 From: Marcos Defendi Date: Thu, 18 Apr 2019 20:41:26 -0300 Subject: [PATCH 13/15] Fix callbacks order --- app/reactions/server/setReaction.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/reactions/server/setReaction.js b/app/reactions/server/setReaction.js index 625ca44f58c2..38cad11bc4bf 100644 --- a/app/reactions/server/setReaction.js +++ b/app/reactions/server/setReaction.js @@ -46,8 +46,6 @@ export function setReaction(room, user, message, reaction, shouldReact) { } if (userAlreadyReacted) { removeUserReaction(message, reaction, user.username); - callbacks.run('unsetReaction', message._id, reaction); - callbacks.run('afterUnsetReaction', message, { user, reaction, shouldReact }); if (_.isEmpty(message.reactions)) { delete message.reactions; if (isTheLastMessage(room, message)) { @@ -60,6 +58,8 @@ export function setReaction(room, user, message, reaction, shouldReact) { Rooms.setReactionsInLastMessage(room._id, message); } } + callbacks.run('unsetReaction', message._id, reaction); + callbacks.run('afterUnsetReaction', message, { user, reaction, shouldReact }); } else { if (!message.reactions) { message.reactions = {}; From cfcea5cba97af57ce9ec3b1c813609e1aeaf6d31 Mon Sep 17 00:00:00 2001 From: Pierre Lehnen Date: Sat, 27 Apr 2019 14:34:55 -0300 Subject: [PATCH 14/15] Fixed merge error --- app/slackbridge/server/RocketAdapter.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index 384bcd7c92e9..81a6aaa944d3 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -324,12 +324,11 @@ export default class RocketAdapter { addedRoom = Rooms.findOneById(slackChannel.rocketId); } - } + }); if (!addedRoom) { logger.rocket.debug('Channel not added'); } - return addedRoom; } From 3924556bc2900d9f9bcb92d4077b9f16279fdfbd Mon Sep 17 00:00:00 2001 From: Pierre Lehnen Date: Sat, 27 Apr 2019 15:02:24 -0300 Subject: [PATCH 15/15] Fixed file upload --- app/slackbridge/server/RocketAdapter.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/slackbridge/server/RocketAdapter.js b/app/slackbridge/server/RocketAdapter.js index 81a6aaa944d3..b51e2cf9f950 100644 --- a/app/slackbridge/server/RocketAdapter.js +++ b/app/slackbridge/server/RocketAdapter.js @@ -146,7 +146,7 @@ export default class RocketAdapter { } if (rocketMessage.file) { - return this.processFileShare(rocketMessage); + return this.processFileShare(rocketMessage, slack); } // A new message from Rocket.Chat @@ -187,7 +187,7 @@ export default class RocketAdapter { return rocketMessage.attachments.find((attachment) => attachment.title_link && attachment.title_link.indexOf(`/${ fileId }/`) >= 0); } - processFileShare(rocketMessage) { + processFileShare(rocketMessage, slack) { if (!settings.get('SlackBridge_FileUpload_Enabled')) { return; } @@ -207,7 +207,7 @@ export default class RocketAdapter { const message = `${ text } ${ fileName }`; rocketMessage.msg = message; - this.slack.postMessage(this.slack.getSlackChannel(rocketMessage.rid), rocketMessage); + slack.postMessage(slack.getSlackChannel(rocketMessage.rid), rocketMessage); } }