All files / lib WebexBot.js

2.07% Statements 5/242
0% Branches 0/116
0% Functions 0/48
2.11% Lines 5/237
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 5781x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1x  
var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var url = require('url');
var crypto = require('crypto');
 
function WebexBot(configuration) {
 
    // Create a core botkit bot
    var controller = Botkit(configuration || {});
 
    // [COMPAT] Webex rebrand, see https://github.com/howdyai/botkit/issues/1346
    if (controller.config.ciscospark_access_token) {
        console.warn('DEPRECATED: please switch your configuration property from "ciscospark_access_token" to "access_token"');
        controller.config.access_token = controller.config.ciscospark_access_token;
    }
 
    if (!controller.config.access_token) {
        throw new Error('access_token required to create controller');
    } else {
        controller.api = require('ciscospark').init({
            credentials: {
                authorization: {
                    access_token: controller.config.access_token
                }
            }
        });
 
        if (!controller.api) {
            throw new Error('Could not create the Webex Teams API client');
        }
 
        controller.api.people.get('me').then(function(identity) {
            console.log('Webex: My identity is', identity);
            controller.identity = identity;
        }).catch(function(err) {
            throw new Error(err);
        });
    }
 
    if (!controller.config.public_address) {
        throw new Error('public_address parameter required to receive webhooks');
    } else {
 
        var endpoint = url.parse(controller.config.public_address);
        if (!endpoint.hostname) {
            throw new Error('Could not determine hostname of public address: ' + controller.config.public_address);
        } else {
            controller.config.public_address = endpoint.hostname + (endpoint.port ? ':' + endpoint.port : '');
        }
 
    }
 
    if (!controller.config.secret) {
        console.warn('WARNING: No secret specified. Source of incoming webhooks will not be validated. https://developer.webex.com/webhooks-explained.html#auth');
        // throw new Error('secret parameter required to secure webhooks');
    }
 
 
    controller.resetWebhookSubscriptions = function() {
        controller.api.webhooks.list().then(function(list) {
            for (var i = 0; i < list.items.length; i++) {
                controller.api.webhooks.remove(list.items[i]).then(function() {
                    // console.log('Removed subscription: ' + list.items[i].name);
                }).catch(function(err) {
                    console.error('Error removing subscription:', err);
                });
            }
        });
    };
 
    // set up a web route for receiving outgoing webhooks and/or slash commands
    controller.createWebhookEndpoints = function(webserver, bot, cb) {
 
 
        var webhook_name = controller.config.webhook_name || 'Botkit Firehose';
 
        var webhook_path = '/webex/receive';
 
        // [COMPAT] Webex rebrand, see https://github.com/howdyai/botkit/issues/1346
        if (controller.config.ciscospark_access_token) {
            compat_path = '/ciscospark/receive';
            var lines = [
                'COMPATIBILITY: because we detected the "ciscospark_access_token" configuration property, ',
                'the "' + compat_path +  '" path is used instead of "' + webhook_path + '"'
            ];
            console.warn(lines.join(' '));
            webhook_path = compat_path;
        }
 
        controller.log(
            '** Serving webhook endpoints for Webex Platform at: ' +
            'http://' + controller.config.hostname + ':' + controller.config.port + webhook_path);
        webserver.post(webhook_path, function(req, res) {
            res.sendStatus(200);
            controller.handleWebhookPayload(req, res, bot);
 
        });
 
 
        controller.api.webhooks.list().then(function(list) {
            var hook_id = null;
 
            for (var i = 0; i < list.items.length; i++) {
                if (list.items[i].name == webhook_name) {
                    hook_id = list.items[i].id;
                }
            }
 
            var hook_url = 'https://' + controller.config.public_address + webhook_path;
 
            console.log('Webex: incoming webhook url is ', hook_url);
 
            if (hook_id) {
                controller.api.webhooks.update({
                    id: hook_id,
                    resource: 'all',
                    targetUrl: hook_url,
                    event: 'all',
                    secret: controller.config.secret,
                    name: webhook_name,
                }).then(function() {
                    console.log('Webex: SUCCESSFULLY UPDATED WEBEX WEBHOOKS');
                    if (cb) cb();
                }).catch(function(err) {
                    console.error('FAILED TO REGISTER WEBHOOK', err);
                    throw new Error(err);
                });
 
            } else {
                controller.api.webhooks.create({
                    resource: 'all',
                    targetUrl: hook_url,
                    event: 'all',
                    secret: controller.config.secret,
                    name: webhook_name,
                }).then(function() {
                    console.log('Webex: SUCCESSFULLY REGISTERED WEBEX WEBHOOKS');
                    if (cb) cb();
                }).catch(function(err) {
                    console.error('FAILED TO REGISTER WEBHOOK', err);
                    throw new Error(err);
                });
 
            }
        }).catch(function(err) {
            throw new Error(err);
        });
    };
 
    controller.middleware.spawn.use(function(worker, next) {
 
        /*
         * copy the identity that we get when the app initially boots up
         * into the specific bot instance
         */
        worker.identity = controller.identity;
        next();
 
    });
 
 
    controller.middleware.ingest.use(function limitUsers(bot, message, res, next) {
 
        if (controller.config.limit_to_org) {
            if (!message.raw_message.orgId || message.raw_message.orgId != controller.config.limit_to_org) {
                // this message is from a user outside of the proscribed org
                console.warn('WARNING: this message is from a user outside of the proscribed org', controller.config.limit_to_org);
                return false;
            }
        }
 
        if (controller.config.limit_to_domain) {
            var domains = [];
            if (typeof(controller.config.limit_to_domain) == 'string') {
                domains = [controller.config.limit_to_domain];
            } else {
                domains = controller.config.limit_to_domain;
            }
 
            var addressParser = require('email-addresses');
            var a = addressParser.parseOneAddress(message.raw_message.data.personEmail);
 
            var allowed = false;
            for (var d = 0; d < domains.length; d++) {
                if (a.domain.toLowerCase() == domains[d]) {
                    allowed = true;
                }
            }
 
            if (!allowed) {
                console.warn('WARNING: this message came from a domain that is outside of the allowed list', controller.config.limit_to_domain);
                // this message came from a domain that is outside of the allowed list.
                return false;
            }
        }
 
        next();
    });
 
    controller.middleware.normalize.use(function getDecryptedMessage(bot, message, next) {
 
        if (message.resource == 'messages' && message.event == 'created') {
 
            controller.api.messages.get(message.data).then(function(decrypted_message) {
 
                message.userId = decrypted_message.personId;
                message.user = decrypted_message.personEmail;
                message.channel = decrypted_message.roomId;
                message.text = decrypted_message.text;
                message.html = decrypted_message.html;
                message.id = decrypted_message.id;
 
                // remove @mentions of the bot from the source text before we ingest it
                if (message.html) {
 
                    // strip the mention & HTML from the message
                    var pattern = new RegExp('^(\<p\>)?\<spark\-mention .*?data\-object\-id\=\"' + controller.identity.id + '\".*?\>.*?\<\/spark\-mention\>', 'im');
                    if (!message.html.match(pattern)) {
                        var encoded_id = controller.identity.id;
                        var decoded = new Buffer(encoded_id, 'base64').toString('ascii');
 
                        // this should look like ciscospark://us/PEOPLE/<id string>
                        var matches;
                        if (matches = decoded.match(/ciscospark\:\/\/.*\/(.*)/im)) {
                            pattern = new RegExp('^(\<p\>)?\<spark\-mention .*?data\-object\-id\=\"' + matches[1] + '\".*?\>.*?\<\/spark\-mention\>', 'im');
                        }
                    }
                    var action = message.html.replace(pattern, '');
 
 
                    // strip the remaining HTML tags
                    action = action.replace(/\<.*?\>/img, '');
 
                    // strip remaining whitespace
                    action = action.trim();
 
                    // replace the message text with the the HTML version
                    message.text = action;
 
                } else {
                    var pattern = new RegExp('^' + controller.identity.displayName + '\\s+', 'i');
                    if (message.text) {
                        message.text = message.text.replace(pattern, '');
                    }
                }
 
                next();
 
            }).catch(function(err) {
                console.error('Could not get message', err);
            });
        } else {
            next();
        }
 
 
    });
 
    controller.middleware.normalize.use(function handleEvents(bot, message, next) {
 
        if (message.resource != 'messages' || message.event != 'created') {
 
            var event = message.resource + '.' + message.event;
            message.userId = message.data.personId;
            message.user = message.data.personEmail;
            message.channel = message.data.roomId;
            message.id = message.data.id;
            message.type = event;
 
            switch (event) {
                case 'memberships.deleted':
                    if (message.userId === controller.identity.id) {
                        message.type = 'bot_space_leave';
                    } else {
                        message.type = 'user_space_leave';
                    }
                    break;
                case 'memberships.created':
                    if (message.userId === controller.identity.id) {
                        message.type = 'bot_space_join';
                    } else {
                        message.type = 'user_space_join';
                    }
                    break;
            }
        }
        next();
 
    });
 
    controller.middleware.categorize.use(function(bot, message, next) {
 
        // further categorize messages
        if (message.type == 'message_received') {
            if (message.userId === controller.identity.id) {
                message.type = 'self_message';
            } else if (message.raw_message.data.roomType == 'direct') {
                message.type = 'direct_message';
            } else {
                message.type = 'direct_mention';
            }
        }
 
        next();
 
    });
 
 
    controller.middleware.format.use(function(bot, message, platform_message, next) {
 
        // clone the incoming message
        for (var k in message) {
            platform_message[k] = message[k];
        }
 
        // mutate the message into proper Webex Teams format
        platform_message.roomId = message.channel;
        delete platform_message.channel;
 
        // delete reference to recipient
        delete platform_message.to;
 
        // default the markdown field to be the same as tex.
        if (platform_message.text && !platform_message.markdown) {
            platform_message.markdown = message.text;
        }
 
        next();
 
    });
 
 
    controller.handleWebhookPayload = function(req, res, bot) {
 
        var payload = req.body;
        if (controller.config.secret) {
            var signature = req.headers['x-spark-signature'];
            var hash = crypto.createHmac('sha1', controller.config.secret).update(JSON.stringify(payload)).digest('hex');
            if (signature != hash) {
                console.error('WARNING: Webhook received message with invalid signature. Potential malicious behavior!');
                return false;
            }
        }
 
        controller.ingest(bot, req.body, res);
 
    };
 
    /*
     * customize the bot definition, which will be used when new connections
     * spawn!
     */
    controller.defineBot(function(botkit, config) {
 
        var bot = {
            type: 'webex',
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };
 
        /**
         * Convenience method for creating a DM convo.
         */
        bot.startPrivateConversation = function(message, cb) {
 
            var message_options = {};
 
            message_options.toPersonEmail = message.user;
 
            botkit.startTask(bot, message_options, function(task, convo) {
                convo.on('sent', function(sent_message) {
                    /*
                     * update this convo so that future messages will match
                     * since the source message did not have this info in it.
                     */
                    convo.source_message.user = message_options.toPersonEmail;
                    convo.source_message.channel = sent_message.roomId;
 
                    convo.context.user = convo.source_message.user;
                    convo.context.channel = convo.source_message.channel;
 
                });
                cb(null, convo);
            });
        };
 
 
        /**
         * Convenience method for creating a DM based on a personId instead of email
         */
        bot.startPrivateConversationWithPersonId = function(personId, cb) {
 
            controller.api.people.get(personId).then(function(identity) {
                bot.startPrivateConversation({user: identity.emails[0]}, cb);
            }).catch(function(err) {
                cb(err);
            });
        };
 
 
        /**
         * Convenience method for creating a DM convo with the `actor`, not the sender
         * this applies to events like channel joins, where the actor may be the user who sent the invite
         */
        bot.startPrivateConversationWithActor = function(message, cb) {
            bot.startPrivateConversationWithPersonId(message.raw_message.actorId, cb);
        };
 
 
        bot.send = function(message, cb) {
 
            controller.api.messages.create(message).then(function(message) {
                if (cb) cb(null, message);
            }).catch(function(err) {
                if (cb) cb(err);
            });
 
        };
 
        bot.reply = function(src, resp, cb) {
            var msg = {};
 
            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }
 
            if (src.channel) {
                msg.channel = src.channel;
            } else if (src.toPersonEmail) {
                msg.toPersonEmail = src.toPersonEmail;
            } else if (src.toPersonId) {
                msg.toPersonId = src.toPersonId;
            }
 
            msg.to = src.user;
 
            bot.say(msg, cb);
        };
 
        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user &&
                        botkit.tasks[t].convos[c].source_message.channel == message.channel &&
                        botkit.excludedEvents.indexOf(message.type) == -1 // this type of message should not be included
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }
 
            cb();
        };
 
        bot.retrieveFileInfo = function(url, cb) {
            request.head({
                url: url,
                headers: {
                    'Authorization': 'Bearer ' + controller.config.access_token
                },
            }, function(err, response) {
 
                if (!err) {
                    var obj = response.headers;
                    if (obj['content-disposition']) {
                        obj.filename = obj['content-disposition'].replace(/.*filename=\"(.*)\".*/gi, '$1');
                    }
                    cb(null, obj);
                } else {
                    cb(err);
                }
 
            });
        };
 
        bot.retrieveFile = function(url, cb) {
 
            request({
                url: url,
                headers: {
                    'Authorization': 'Bearer ' + controller.config.access_token
                },
                encoding: 'binary',
            }, function(err, response, body) {
 
                cb(err, body);
 
            });
 
        };
 
 
        /*
         * return info about the specific instance of this bot
         * including identity information, and any other info that is relevant
         */
        bot.getInstanceInfo = function(cb) {
            return new Promise(function(resolve, reject) {
                var instance = {
                    identity: {},
                    team: {},
                };
 
                controller.api.people.get('me').then(function(identity) {
 
                    instance.identity.name = identity.displayName;
                    instance.identity.id = identity.id;
                    instance.team.id = identity.orgId;
 
                    if (cb) cb(null, instance);
                    resolve(instance);
 
                }).catch(reject);
            });
        };
        bot.getMessageUser = function(message, cb) {
            return new Promise(function(resolve, reject) {
 
                controller.api.people.list({email: message.user}).then(function(identity) {
                    if (identity.length) {
                        identity = identity.items[0];
                    } else {
                        if (cb) {
                            cb('User not found');
                        }
 
                        return reject('User not found');
                    }
 
                    // normalize this into what botkit wants to see
                    var profile = {
                        id: identity.id,
                        username: identity.displayName,
                        first_name: identity.firstName,
                        last_name: identity.lastName,
                        full_name: (identity.firstName && identity.lastName) ? identity.firstName + ' ' + identity.lastName : '',
                        email: identity.emails[0],
                        gender: null, // no source for this info
                        timezone_offset: null, // no source for this info
                        timezone: identity.timezone, // this MAY be set depending on user settings
                    };
 
                    if (cb) {
                        cb(null, profile);
                    }
                    resolve(profile);
 
                }).catch(function(err) {
                    if (cb) {
                        cb(err);
                    }
                    reject(err);
                });
            });
 
        };
 
        return bot;
 
    });
 
    controller.startTicking();
 
    return controller;
 
}
 
 
module.exports = WebexBot;