-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.coffee
113 lines (88 loc) · 2.64 KB
/
app.coffee
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
phantom = require 'phantom'
uuid = require 'node-uuid'
express = require 'express'
bodyParser = require 'body-parser'
fs = require 'fs'
http = require 'http'
request = require 'request'
s3 = require 's3'
app = express()
config = require './config'
webhookUrl = config.webhookUrl
token = config.token
awsAccessKeyId = config.awsAccessKeyId
awsSecretKey = config.awsSecretKey
s3bucket = config.s3bucket
s3region = config.s3region
s3Url = "https://s3-#{s3region}.amazonaws.com/#{s3bucket}"
app.use bodyParser.urlencoded()
client = s3.createClient({
s3Options: {
accessKeyId: awsAccessKeyId.trim()
secretAccessKey: awsSecretKey.trim()
}
})
generateBravo = (to, msg, from, next) ->
phantom.create (ph) ->
ph.createPage (page) ->
pagePath = "#{__dirname}/public/bravo.html"
page.open pagePath, (status) ->
if (status != 'success')
console.log 'Unable to access page.'
else
page.evaluate (to, msg, from) ->
document.getElementsByClassName("js-to")[0].textContent = to
document.getElementsByClassName("js-msg")[0].textContent = msg
document.getElementsByClassName("js-from")[0].textContent = from
, (->), to, msg, from
setTimeout ->
id = uuid.v4()
filename = "bravos/#{id}.jpg"
page.render filename, format: "jpg", ->
next(filename)
ph.exit()
, 200
postBravoTos3 = (filename, next) ->
params = {
localFile: filename
s3Params: {
Bucket: s3bucket
Key: filename
ContentType: "image/jpeg"
}
}
uploader = client.uploadFile(params)
uploader.on 'error', (err) ->
console.error "unable to upload: ", err.stack
uploader.on 'end', (data) ->
imgUrl = [s3Url, filename].join("/")
next(imgUrl)
postToSlack = (channel, text, next) ->
opts = {channel, text}
opts.username = 'Bravo Bot'
opts.parse = 'full'
request.post webhookUrl, {form: {payload: JSON.stringify(opts) }}, (err, res, body) ->
next(err)
app.post "/", (req, res) ->
return if req.body.token != token
text = req.body.text
to = text.split(' ')[0]
toPrefix = ', @'
if /^\#/.test(to)
toPrefix = ", #"
to = to.replace /^(@|#)/, ''
if to == ""
toPrefix = ""
to = "!"
emptyTo = true
msg = text.split(' ')[1...].join(' ')
channel = '#' + req.body.channel_name
generateBravo "#{toPrefix}#{to}", msg, "@#{req.body.user_name}", (filename) ->
postBravoTos3 filename, (url) ->
if emptyTo
msg = "Bravo!"
else
msg = "Bravo#{toPrefix}#{to}!"
postToSlack channel, "#{msg} #{url}", ->
res.send("")
app.listen(10040)