1 | Configuration = require './configuration'
|
2 | _ = require('underscore')._
|
3 |
|
4 | Async = require 'async'
|
5 | Moment = require 'moment'
|
6 |
|
7 | Hipchat = Configuration.Hipchat
|
8 | Winston = Configuration.Winston
|
9 | Commands = require './commands'
|
10 | Cache = require './cache'
|
11 | Utils = require './utils'
|
12 |
|
13 |
|
14 | pattern = new RegExp "^#{Configuration.Nickname} ([a-zA-Z0-9]+)
|
15 | ( ([a-zA-Z0-9\-\+\/\.\:\_]+))?
|
16 | ( ([a-zA-Z0-9\-\+\/\.\:\_]+))?
|
17 | ( ([a-zA-Z0-9\-\+\/\.\:\_]+))?
|
18 | ( ([a-zA-Z0-9\-\+\/\.\:\_]+))?
|
19 | ( ([a-zA-Z0-9\-\+\/\.\:\_]+))?
|
20 | ( ([a-zA-Z0-9\-\+\/\.\:\_]+))?$"
|
21 |
|
22 | dispatch = (message, from) ->
|
23 | if (not from? or from.name != Configuration.Nickname)
|
24 |
|
25 | if (not message.match(new RegExp "#{Configuration.Nickname}"))
|
26 |
|
27 | if (require('./gh_helpers').githubPRUrlMatching(message))
|
28 | cmd = Commands.pulls
|
29 | if (cmd)
|
30 | cmd.args = []
|
31 | cmd.args.push message
|
32 | cmd
|
33 | else
|
34 | request = message.match(pattern)
|
35 | if (request and request.length > 1)
|
36 | cmd = Commands[request[1]]
|
37 | if (cmd)
|
38 | cmd.args = []
|
39 | cmd.args.push request[3]
|
40 | cmd.args.push request[5]
|
41 | cmd.args.push request[7]
|
42 | cmd.args.push request[9]
|
43 | cmd.args.push request[11]
|
44 | cmd
|
45 |
|
46 | server = (frequency, testCallback) ->
|
47 | freq = if frequency? then frequency else Hipchat.Frequency
|
48 |
|
49 | Hipchat.Rooms.history Hipchat.Channel, (error, lines) ->
|
50 | if (error?) then Winston.logger.error("An error occured while fetching history: #{JSON.stringify(error)}")
|
51 | else if(lines)
|
52 | Cache.store(lines.messages)
|
53 |
|
54 | intervalId = setInterval () ->
|
55 | Hipchat.Rooms.history Hipchat.Channel, (error, lines) ->
|
56 | if (error?) then Winston.logger.error("An error occured while fetching history: #{JSON.stringify(error)}")
|
57 | else if (lines)
|
58 | Async.each lines.messages, (line, cb) ->
|
59 | if (not Cache.cached(line))
|
60 | command = dispatch(line.message, line.from)
|
61 |
|
62 | if (command)
|
63 | if testCallback? and _.isFunction(testCallback)
|
64 | testCallback(intervalId, command)
|
65 | else
|
66 | Winston.logger.info "Command #{command.name} detected #{Moment().format()}"
|
67 | Winston.logger.verbose "With arguments: #{JSON.stringify(command.args)}"
|
68 |
|
69 | _.partial(command.action, Utils.render).apply null, command.args
|
70 | cb(null)
|
71 | , (err) ->
|
72 | Cache.store lines.messages
|
73 | , freq
|
74 |
|
75 | if (not _.isFunction(testCallback))
|
76 | Winston.logger.info "Bot listening to Hipchat channel: #{Hipchat.Channel}"
|
77 | Winston.logger.verbose "Verbose mode activated"
|
78 |
|
79 | module.exports = {
|
80 | dispatch: dispatch,
|
81 | action: server
|
82 | }
|