Source: messaging/connectors/slack/SlackConnector.js

/**
 * Licensed Materials - Property of IBM
 * IBM Cognos Products: Collaboration
 * (C) Copyright IBM Corp. 2017, 2019
 *
 * US Government Users Restricted Rights - Use, duplication or disclosure
 * restricted by GSA ADP Schedule Contract with IBM Corp.
 */

define([
	'../ConnectorBase',
	'./SlackClient',
	'../../../nls/StringResources'
], function (ConnectorBase, SlackClient, StringMessages) {
	'use strict';

	/**
	 * Maximum number of recipient users for direct messages.
	 */
	var MAX_RECIPIENT_USERS = 8;
	var USERS_PAGE_SIZE = 15;

	var SlackConnector = ConnectorBase.extend( /** @lends SlackConnector */ {

		/**
		 * @desc Constructor for SlackConnector.
		 * @constructs SlackConnector
		 * @extends ConnectorBase
		 * @public
		 * @param options {Object} Options
		 * @param options.glassContext {Object} The glass context
		 */
		init: function (options) {
			// base class is keeping for us the glassContext and logger
			SlackConnector.inherited('init', this, arguments);
			this.client = new SlackClient(options.glassContext);
		},

		/**
		 * Configure this connector with some meta info.
		 * @instance
		 * @param {object} meta meta data specific to this connector type.
		 */
		configure: function (meta) {
			SlackConnector.inherited('configure', this, arguments);
			if (!(meta.features &&
				meta.features.messaging && meta.features.messaging.endpoint &&
				meta.features.me && meta.features.me.endpoint &&
				meta.features.conversations && meta.features.conversations.endpoint)) {
				throw new Error(StringMessages.get('error_invalid_configuration'));
			}
		},

		/**
		 * Authenticate to Slack.
		 * @instance
		 * @param {object} options options are not used at the moment.
		 * @returns {promise}
		 */
		authenticate: function (options) {
			void (options);
			return this.client
				.signIn()
				.catch(this.errorHandler);
		},

		/**
		 * Send a message to Slack.
		 * @instance
		 * @param {object} data Options
		 * @param {string} data.channel Channel name
		 * @param {string} data.message Message text
		 * @param {string} data.url URL to CA asset
		 * @returns {Promise}
		 */
		send: function (data) {
			let promise;
			// some validations...
			if (!Array.isArray(data.recipients) || data.recipients.length === 0 || !data.recipients[0]) {
				promise = Promise
					.reject(new Error(StringMessages.get('error_missing_recipient')));
			} else if (!data.message && !data.url) {
				promise = Promise
					.reject(new Error(StringMessages.get('error_missing_message')));
			} else {
				promise = this.client.sendMessage({
					url: this.meta.features.messaging.endpoint,
					data: {
						channel: data.recipients.join(','),
						dataUrl: data['dataUrl'],
						filename: StringMessages.get(data.assetTitle && 'ca_image' || 'ca_image_short', data),
						comment: data.assetSubTitle,
						message: {
							text: data.message,
							as_user: true,
							attachments: data.url ? [{
								color: '#36a64f',
								title: StringMessages.get(data.assetTitle && 'ca_link' || 'ca_link_short', data),
								title_link: data.url,
								footer: StringMessages.get('product')
							}] : []
						}
					}
				});
			}
			return promise.catch(this.errorHandler);
		},

		/**
		 * Retrieve all users from Slack.
		 * @instance
		 * @returns {promise}
		 */
		getUsers: function (query) {
			return this.loadFeatures().then(this._getUsers.bind(this, query));
		},

		_getUsers: function (query) {
			var payloadToSend = {
				searchTerm: query,
				pageSize: USERS_PAGE_SIZE
			};
			return this.client
				.doGet({
					url: this.meta.features.users.endpoint,
					data: payloadToSend
				})
				.then(function (result) {
					var users = result.data.members;
					return users;
				})
				.catch(this.errorHandler);
		},

		/**
		 * Retrieve all conversations from Slack.
		 * @instance
		 * @returns {promise}
		 */
		getConversations: function () {
			return this.loadFeatures().then(this._getConversations.bind(this));
		},

		_getConversations: function () {
			return this.client
				.doGet({
					url: this.meta.features.conversations.endpoint
				})
				.then(function (result) {
					var conversations = result.data.conversations;

					// make sure we have a valid array
					conversations.ims = conversations.ims || [];
					conversations.mpims = conversations.mpims || [];
					conversations.channels = conversations.channels || [];
					conversations.pvtchannels = conversations.pvtchannels || [];

					return conversations;
				})
				.catch(this.errorHandler);
		},

		/**
		 * Retrieve the workspaces the user belongs to from Slack.
		 *
		 * @instance
		 * @return Promise
		 */
		getWorkspace: function () {
			return this.client
				.doGet({
					url: this.meta.features.me.endpoint
				}).then(function (workspace) {
					return workspace.data.team;
				});
		},

		/**
		 * Returns the maximum number of recipient users.
		 * @instance
		 * @returns {number}
		 */
		getMaxRecipientUsers: function () {
			return MAX_RECIPIENT_USERS;
		},

		/**
		 * Calls feature 'me' to check if the provider is ready for use.
		 * @override
		 */
		check: function () {
			return this.loadFeatures()
				.then(function () {
					return this.client
						.doGet({
							url: this.meta.features.me.endpoint
						})
						.then(function (response) {
							this.me = response.data || {};
						}.bind(this))
						.catch(this.errorHandler);
				}.bind(this));
		}
	});
	return SlackConnector;
});