1 | 'use strict'
|
2 |
|
3 | const EventEmitter = require('events').EventEmitter
|
4 | const fs = require('fs')
|
5 | const path = require('path')
|
6 |
|
7 | const async = require('async')
|
8 | const Log = require('log')
|
9 | const HttpClient = require('scoped-http-client')
|
10 |
|
11 | const Brain = require('./brain')
|
12 | const Response = require('./response')
|
13 | const Listener = require('./listener')
|
14 | const Message = require('./message')
|
15 | const Middleware = require('./middleware')
|
16 |
|
17 | const HUBOT_DEFAULT_ADAPTERS = ['campfire', 'shell']
|
18 | const HUBOT_DOCUMENTATION_SECTIONS = ['description', 'dependencies', 'configuration', 'commands', 'notes', 'author', 'authors', 'examples', 'tags', 'urls']
|
19 |
|
20 | class Robot {
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | constructor (adapterPath, adapter, httpd, name, alias) {
|
29 | if (name == null) {
|
30 | name = 'Hubot'
|
31 | }
|
32 | if (alias == null) {
|
33 | alias = false
|
34 | }
|
35 | this.adapterPath = path.join(__dirname, 'adapters')
|
36 |
|
37 | this.name = name
|
38 | this.events = new EventEmitter()
|
39 | this.brain = new Brain(this)
|
40 | this.alias = alias
|
41 | this.adapter = null
|
42 | this.Response = Response
|
43 | this.commands = []
|
44 | this.listeners = []
|
45 | this.middleware = {
|
46 | listener: new Middleware(this),
|
47 | response: new Middleware(this),
|
48 | receive: new Middleware(this)
|
49 | }
|
50 | this.logger = new Log(process.env.HUBOT_LOG_LEVEL || 'info')
|
51 | this.pingIntervalId = null
|
52 | this.globalHttpOptions = {}
|
53 |
|
54 | this.parseVersion()
|
55 | if (httpd) {
|
56 | this.setupExpress()
|
57 | } else {
|
58 | this.setupNullRouter()
|
59 | }
|
60 |
|
61 | this.loadAdapter(adapter)
|
62 |
|
63 | this.adapterName = adapter
|
64 | this.errorHandlers = []
|
65 |
|
66 | this.on('error', (err, res) => {
|
67 | return this.invokeErrorHandlers(err, res)
|
68 | })
|
69 | this.onUncaughtException = err => {
|
70 | return this.emit('error', err)
|
71 | }
|
72 | process.on('uncaughtException', this.onUncaughtException)
|
73 | }
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | listen (matcher, options, callback) {
|
88 | this.listeners.push(new Listener.Listener(this, matcher, options, callback))
|
89 | }
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 | hear (regex, options, callback) {
|
101 | this.listeners.push(new Listener.TextListener(this, regex, options, callback))
|
102 | }
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 | respond (regex, options, callback) {
|
115 | this.hear(this.respondPattern(regex), options, callback)
|
116 | }
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 | respondPattern (regex) {
|
125 | const regexWithoutModifiers = regex.toString().split('/')
|
126 | regexWithoutModifiers.shift()
|
127 | const modifiers = regexWithoutModifiers.pop()
|
128 | const regexStartsWithAnchor = regexWithoutModifiers[0] && regexWithoutModifiers[0][0] === '^'
|
129 | const pattern = regexWithoutModifiers.join('/')
|
130 | const name = this.name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
|
131 |
|
132 | if (regexStartsWithAnchor) {
|
133 | this.logger.warning(`Anchors don’t work well with respond, perhaps you want to use 'hear'`)
|
134 | this.logger.warning(`The regex in question was ${regex.toString()}`)
|
135 | }
|
136 |
|
137 | if (!this.alias) {
|
138 | return new RegExp('^\\s*[@]?' + name + '[:,]?\\s*(?:' + pattern + ')', modifiers)
|
139 | }
|
140 |
|
141 | const alias = this.alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
|
142 |
|
143 |
|
144 | if (name.length > alias.length) {
|
145 | return new RegExp('^\\s*[@]?(?:' + name + '[:,]?|' + alias + '[:,]?)\\s*(?:' + pattern + ')', modifiers)
|
146 | }
|
147 |
|
148 |
|
149 | return new RegExp('^\\s*[@]?(?:' + alias + '[:,]?|' + name + '[:,]?)\\s*(?:' + pattern + ')', modifiers)
|
150 | }
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 | enter (options, callback) {
|
160 | this.listen(msg => msg instanceof Message.EnterMessage, options, callback)
|
161 | }
|
162 |
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 | leave (options, callback) {
|
171 | this.listen(msg => msg instanceof Message.LeaveMessage, options, callback)
|
172 | }
|
173 |
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 |
|
181 | topic (options, callback) {
|
182 | this.listen(msg => msg instanceof Message.TopicMessage, options, callback)
|
183 | }
|
184 |
|
185 |
|
186 |
|
187 |
|
188 |
|
189 |
|
190 |
|
191 | error (callback) {
|
192 | this.errorHandlers.push(callback)
|
193 | }
|
194 |
|
195 |
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 | invokeErrorHandlers (error, res) {
|
203 | this.logger.error(error.stack)
|
204 |
|
205 | this.errorHandlers.map((errorHandler) => {
|
206 | try {
|
207 | errorHandler(error, res)
|
208 | } catch (errorHandlerError) {
|
209 | this.logger.error(`while invoking error handler: ${errorHandlerError}\n${errorHandlerError.stack}`)
|
210 | }
|
211 | })
|
212 | }
|
213 |
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 | catchAll (options, callback) {
|
222 |
|
223 |
|
224 | if (callback == null) {
|
225 | callback = options
|
226 | options = {}
|
227 | }
|
228 |
|
229 | this.listen(isCatchAllMessage, options, function listenCallback (msg) {
|
230 | msg.message = msg.message.message
|
231 | callback(msg)
|
232 | })
|
233 | }
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 |
|
241 |
|
242 |
|
243 |
|
244 |
|
245 |
|
246 |
|
247 | listenerMiddleware (middleware) {
|
248 | this.middleware.listener.register(middleware)
|
249 | }
|
250 |
|
251 |
|
252 |
|
253 |
|
254 |
|
255 |
|
256 |
|
257 |
|
258 |
|
259 |
|
260 |
|
261 |
|
262 | responseMiddleware (middleware) {
|
263 | this.middleware.response.register(middleware)
|
264 | }
|
265 |
|
266 |
|
267 |
|
268 |
|
269 |
|
270 |
|
271 |
|
272 |
|
273 |
|
274 |
|
275 |
|
276 | receiveMiddleware (middleware) {
|
277 | this.middleware.receive.register(middleware)
|
278 | }
|
279 |
|
280 |
|
281 |
|
282 |
|
283 |
|
284 |
|
285 |
|
286 |
|
287 |
|
288 |
|
289 |
|
290 | receive (message, cb) {
|
291 |
|
292 |
|
293 | this.middleware.receive.execute({ response: new Response(this, message) }, this.processListeners.bind(this), cb)
|
294 | }
|
295 |
|
296 |
|
297 |
|
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 | processListeners (context, done) {
|
306 |
|
307 |
|
308 | let anyListenersExecuted = false
|
309 |
|
310 | async.detectSeries(this.listeners, (listener, done) => {
|
311 | try {
|
312 | listener.call(context.response.message, this.middleware.listener, function (listenerExecuted) {
|
313 | anyListenersExecuted = anyListenersExecuted || listenerExecuted
|
314 |
|
315 |
|
316 | process.nextTick(() =>
|
317 |
|
318 | done(context.response.message.done)
|
319 | )
|
320 | })
|
321 | } catch (err) {
|
322 | this.emit('error', err, new this.Response(this, context.response.message, []))
|
323 |
|
324 | done(false)
|
325 | }
|
326 | },
|
327 |
|
328 | _ => {
|
329 |
|
330 |
|
331 | if (!(context.response.message instanceof Message.CatchAllMessage) && !anyListenersExecuted) {
|
332 | this.logger.debug('No listeners executed; falling back to catch-all')
|
333 | this.receive(new Message.CatchAllMessage(context.response.message), done)
|
334 | } else {
|
335 | if (done != null) {
|
336 | process.nextTick(done)
|
337 | }
|
338 | }
|
339 | })
|
340 | }
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 | loadFile (filepath, filename) {
|
349 | const ext = path.extname(filename)
|
350 | const full = path.join(filepath, path.basename(filename, ext))
|
351 |
|
352 |
|
353 | if (!require.extensions[ext]) {
|
354 | return
|
355 | }
|
356 |
|
357 | try {
|
358 | const script = require(full)
|
359 |
|
360 | if (typeof script === 'function') {
|
361 | script(this)
|
362 | this.parseHelp(path.join(filepath, filename))
|
363 | } else {
|
364 | this.logger.warning(`Expected ${full} to assign a function to module.exports, got ${typeof script}`)
|
365 | }
|
366 | } catch (error) {
|
367 | this.logger.error(`Unable to load ${full}: ${error.stack}`)
|
368 | process.exit(1)
|
369 | }
|
370 | }
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 | load (path) {
|
378 | this.logger.debug(`Loading scripts from ${path}`)
|
379 |
|
380 | if (fs.existsSync(path)) {
|
381 | fs.readdirSync(path).sort().map(file => this.loadFile(path, file))
|
382 | }
|
383 | }
|
384 |
|
385 |
|
386 |
|
387 |
|
388 |
|
389 |
|
390 |
|
391 | loadHubotScripts (path, scripts) {
|
392 | this.logger.debug(`Loading hubot-scripts from ${path}`)
|
393 | Array.from(scripts).map(script => this.loadFile(path, script))
|
394 | }
|
395 |
|
396 |
|
397 |
|
398 |
|
399 |
|
400 |
|
401 |
|
402 | loadExternalScripts (packages) {
|
403 | this.logger.debug('Loading external-scripts from npm packages')
|
404 |
|
405 | try {
|
406 | if (Array.isArray(packages)) {
|
407 | return packages.forEach(pkg => require(pkg)(this))
|
408 | }
|
409 |
|
410 | Object.keys(packages).forEach(key => require(key)(this, packages[key]))
|
411 | } catch (error) {
|
412 | this.logger.error(`Error loading scripts from npm package - ${error.stack}`)
|
413 | process.exit(1)
|
414 | }
|
415 | }
|
416 |
|
417 |
|
418 |
|
419 |
|
420 | setupExpress () {
|
421 | const user = process.env.EXPRESS_USER
|
422 | const pass = process.env.EXPRESS_PASSWORD
|
423 | const stat = process.env.EXPRESS_STATIC
|
424 | const port = process.env.EXPRESS_PORT || process.env.PORT || 8080
|
425 | const address = process.env.EXPRESS_BIND_ADDRESS || process.env.BIND_ADDRESS || '0.0.0.0'
|
426 | const limit = process.env.EXPRESS_LIMIT || '100kb'
|
427 | const paramLimit = parseInt(process.env.EXPRESS_PARAMETER_LIMIT) || 1000
|
428 |
|
429 | const express = require('express')
|
430 | const multipart = require('connect-multiparty')
|
431 |
|
432 | const app = express()
|
433 |
|
434 | app.use((req, res, next) => {
|
435 | res.setHeader('X-Powered-By', `hubot/${this.name}`)
|
436 | return next()
|
437 | })
|
438 |
|
439 | if (user && pass) {
|
440 | app.use(express.basicAuth(user, pass))
|
441 | }
|
442 | app.use(express.query())
|
443 |
|
444 | app.use(express.json())
|
445 | app.use(express.urlencoded({ limit, parameterLimit: paramLimit }))
|
446 |
|
447 |
|
448 | app.use(multipart({ maxFilesSize: 100 * 1024 * 1024 }))
|
449 |
|
450 | if (stat) {
|
451 | app.use(express.static(stat))
|
452 | }
|
453 |
|
454 | try {
|
455 | this.server = app.listen(port, address)
|
456 | this.router = app
|
457 | } catch (error) {
|
458 | const err = error
|
459 | this.logger.error(`Error trying to start HTTP server: ${err}\n${err.stack}`)
|
460 | process.exit(1)
|
461 | }
|
462 |
|
463 | let herokuUrl = process.env.HEROKU_URL
|
464 |
|
465 | if (herokuUrl) {
|
466 | if (!/\/$/.test(herokuUrl)) {
|
467 | herokuUrl += '/'
|
468 | }
|
469 | this.pingIntervalId = setInterval(() => {
|
470 | HttpClient.create(`${herokuUrl}hubot/ping`).post()((_err, res, body) => {
|
471 | this.logger.info('keep alive ping!')
|
472 | })
|
473 | }, 5 * 60 * 1000)
|
474 | }
|
475 | }
|
476 |
|
477 |
|
478 |
|
479 |
|
480 | setupNullRouter () {
|
481 | const msg = 'A script has tried registering a HTTP route while the HTTP server is disabled with --disabled-httpd.'
|
482 |
|
483 | this.router = {
|
484 | get: () => this.logger.warning(msg),
|
485 | post: () => this.logger.warning(msg),
|
486 | put: () => this.logger.warning(msg),
|
487 | delete: () => this.logger.warning(msg)
|
488 | }
|
489 | }
|
490 |
|
491 | // Load the adapter Hubot is going to use.
|
492 | //
|
493 | // path - A String of the path to adapter if local.
|
494 | // adapter - A String of the adapter name to use.
|
495 | //
|
496 | // Returns nothing.
|
497 | loadAdapter (adapter) {
|
498 | this.logger.debug(`Loading adapter ${adapter}`)
|
499 |
|
500 | try {
|
501 | const path = Array.from(HUBOT_DEFAULT_ADAPTERS).indexOf(adapter) !== -1 ? `${this.adapterPath}/${adapter}` : `hubot-${adapter}`
|
502 |
|
503 | this.adapter = require(path).use(this)
|
504 | } catch (err) {
|
505 | this.logger.error(`Cannot load adapter ${adapter} - ${err}`)
|
506 | process.exit(1)
|
507 | }
|
508 | }
|
509 |
|
510 |
|
511 |
|
512 |
|
513 | helpCommands () {
|
514 | return this.commands.sort()
|
515 | }
|
516 |
|
517 |
|
518 |
|
519 |
|
520 |
|
521 |
|
522 | parseHelp (path) {
|
523 | const scriptDocumentation = {}
|
524 | const body = fs.readFileSync(require.resolve(path), 'utf-8')
|
525 |
|
526 | const useStrictHeaderRegex = /^["']use strict['"];?\s+/
|
527 | const lines = body.replace(useStrictHeaderRegex, '').split('\n')
|
528 | .reduce(toHeaderCommentBlock, {lines: [], isHeader: true}).lines
|
529 | .filter(Boolean)
|
530 | let currentSection = null
|
531 | let nextSection
|
532 |
|
533 | this.logger.debug(`Parsing help for ${path}`)
|
534 |
|
535 | for (let i = 0, line; i < lines.length; i++) {
|
536 | line = lines[i]
|
537 |
|
538 | if (line.toLowerCase() === 'none') {
|
539 | continue
|
540 | }
|
541 |
|
542 | nextSection = line.toLowerCase().replace(':', '')
|
543 | if (Array.from(HUBOT_DOCUMENTATION_SECTIONS).indexOf(nextSection) !== -1) {
|
544 | currentSection = nextSection
|
545 | scriptDocumentation[currentSection] = []
|
546 | } else {
|
547 | if (currentSection) {
|
548 | scriptDocumentation[currentSection].push(line)
|
549 | if (currentSection === 'commands') {
|
550 | this.commands.push(line)
|
551 | }
|
552 | }
|
553 | }
|
554 | }
|
555 |
|
556 | if (currentSection === null) {
|
557 | this.logger.info(`${path} is using deprecated documentation syntax`)
|
558 | scriptDocumentation.commands = []
|
559 | for (let i = 0, line, cleanedLine; i < lines.length; i++) {
|
560 | line = lines[i]
|
561 | if (line.match('-')) {
|
562 | continue
|
563 | }
|
564 |
|
565 | cleanedLine = line.slice(2, +line.length + 1 || 9e9).replace(/^hubot/i, this.name).trim()
|
566 | scriptDocumentation.commands.push(cleanedLine)
|
567 | this.commands.push(cleanedLine)
|
568 | }
|
569 | }
|
570 | }
|
571 |
|
572 |
|
573 |
|
574 |
|
575 |
|
576 |
|
577 |
|
578 |
|
579 | send (envelope) {
|
580 | const strings = [].slice.call(arguments, 1)
|
581 |
|
582 | this.adapter.send.apply(this.adapter, [envelope].concat(strings))
|
583 | }
|
584 |
|
585 |
|
586 |
|
587 |
|
588 |
|
589 |
|
590 |
|
591 |
|
592 | reply (envelope) {
|
593 | const strings = [].slice.call(arguments, 1)
|
594 |
|
595 | this.adapter.reply.apply(this.adapter, [envelope].concat(strings))
|
596 | }
|
597 |
|
598 |
|
599 |
|
600 |
|
601 |
|
602 |
|
603 |
|
604 | messageRoom (room) {
|
605 | const strings = [].slice.call(arguments, 1)
|
606 | const envelope = { room }
|
607 |
|
608 | this.adapter.send.apply(this.adapter, [envelope].concat(strings))
|
609 | }
|
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 |
|
616 |
|
617 |
|
618 |
|
619 | on (event) {
|
620 | const args = [].slice.call(arguments, 1)
|
621 |
|
622 | this.events.on.apply(this.events, [event].concat(args))
|
623 | }
|
624 |
|
625 |
|
626 |
|
627 |
|
628 |
|
629 |
|
630 |
|
631 |
|
632 | emit (event) {
|
633 | const args = [].slice.call(arguments, 1)
|
634 |
|
635 | this.events.emit.apply(this.events, [event].concat(args))
|
636 | }
|
637 |
|
638 |
|
639 |
|
640 |
|
641 | run () {
|
642 | this.emit('running')
|
643 |
|
644 | this.adapter.run()
|
645 | }
|
646 |
|
647 |
|
648 |
|
649 |
|
650 | shutdown () {
|
651 | if (this.pingIntervalId != null) {
|
652 | clearInterval(this.pingIntervalId)
|
653 | }
|
654 | process.removeListener('uncaughtException', this.onUncaughtException)
|
655 | this.adapter.close()
|
656 | if (this.server) {
|
657 | this.server.close()
|
658 | }
|
659 |
|
660 | this.brain.close()
|
661 | }
|
662 |
|
663 |
|
664 |
|
665 |
|
666 | parseVersion () {
|
667 | const pkg = require(path.join(__dirname, '..', 'package.json'))
|
668 | this.version = pkg.version
|
669 |
|
670 | return this.version
|
671 | }
|
672 |
|
673 |
|
674 |
|
675 |
|
676 |
|
677 |
|
678 |
|
679 |
|
680 |
|
681 |
|
682 |
|
683 |
|
684 |
|
685 |
|
686 |
|
687 |
|
688 |
|
689 |
|
690 |
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 |
|
697 |
|
698 |
|
699 |
|
700 |
|
701 |
|
702 |
|
703 |
|
704 |
|
705 | http (url, options) {
|
706 | const httpOptions = extend({}, this.globalHttpOptions, options)
|
707 |
|
708 | return HttpClient.create(url, httpOptions).header('User-Agent', `Hubot/${this.version}`)
|
709 | }
|
710 | }
|
711 |
|
712 | module.exports = Robot
|
713 |
|
714 | function isCatchAllMessage (message) {
|
715 | return message instanceof Message.CatchAllMessage
|
716 | }
|
717 |
|
718 | function toHeaderCommentBlock (block, currentLine) {
|
719 | if (!block.isHeader) {
|
720 | return block
|
721 | }
|
722 |
|
723 | if (isCommentLine(currentLine)) {
|
724 | block.lines.push(removeCommentPrefix(currentLine))
|
725 | } else {
|
726 | block.isHeader = false
|
727 | }
|
728 |
|
729 | return block
|
730 | }
|
731 |
|
732 | function isCommentLine (line) {
|
733 | return /^(#|\/\/)/.test(line)
|
734 | }
|
735 |
|
736 | function removeCommentPrefix (line) {
|
737 | return line.replace(/^[#/]+\s*/, '')
|
738 | }
|
739 |
|
740 | function extend (obj/* , ...sources */) {
|
741 | const sources = [].slice.call(arguments, 1)
|
742 |
|
743 | sources.forEach((source) => {
|
744 | if (typeof source !== 'object') {
|
745 | return
|
746 | }
|
747 |
|
748 | Object.keys(source).forEach((key) => {
|
749 | obj[key] = source[key]
|
750 | })
|
751 | })
|
752 |
|
753 | return obj
|
754 | }
|