UNPKG

2.74 kBtext/coffeescriptView Raw
1Configuration = require './configuration'
2_ = require('underscore')._
3
4Async = require 'async'
5Moment = require 'moment'
6
7Hipchat = Configuration.Hipchat
8Winston = Configuration.Winston
9Commands = require './commands'
10Cache = require './cache'
11Utils = require './utils'
12
13# TODO: Loop or XRegExp
14pattern = 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
22dispatch = (message, from) ->
23 if (not from? or from.name != Configuration.Nickname)
24
25 if (not message.match(new RegExp "#{Configuration.Nickname}"))
26 #TODO: This definitively need NOT to be a special case hard coded
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
46server = (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
79module.exports = {
80 dispatch: dispatch,
81 action: server
82}