forked from WCOMAB/KuduPostDeploymentSlackHook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.js
94 lines (84 loc) · 2.41 KB
/
slack.js
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
var https = require('https');
var url = require('url');
var slackHookRequestOptions = getSlackHookRequestOptions();
module.exports.sendToSlack = sendToSlack;
function getSlackHookRequestOptions()
{
var hookUri = url.parse(process.env.slackhookuri);
return {
host: hookUri.hostname,
port: hookUri.port,
path: hookUri.path,
method: 'POST',
headers: { 'Content-Type': 'application/json' }
};
}
function sendToSlack(parsedRequest, callback)
{
if (!parsedRequest || (parsedRequest.body||'').trim()=='') {
callback(true);
return;
}
var error = false;
var slackMessage = convertToSlackMessage(parsedRequest.body, parsedRequest.channel);
var req = https.request(slackHookRequestOptions);
req.on('error', function(e) {
console.error(e);
error = true;
});
req.on('close', function() { callback(error); } );
req.write(slackMessage);
req.end();
}
function convertToSlackMessage(body, channel)
{
var parsedBody = trParseBody(body);
var success = (parsedBody.status=='success' && parsedBody.complete);
return JSON.stringify({
username: getSlackUserName(parsedBody, success),
icon_emoji: success ? ':shipit:' : ':warning:',
text: getSlackText(parsedBody),
channel: channel || process.env.slackchannel
});
}
function trParseBody(body)
{
try
{
return JSON.parse(body) || {
status: 'failed',
complete: false
};
} catch(err) {
console.error(err);
return {
status: err,
complete: false
};
}
}
function getSlackUserName(parsedBody, success)
{
return (
(success ? 'Published:': 'Failed:') +
' ' +
(parsedBody.siteName || 'unknown')
);
}
function getSlackText(parsedBody)
{
var hostName = parsedBody.hostName
var id = parsedBody.id
return (
'Initiated by: ' +
(parsedBody.author || 'unknown') +
' ' +
(parsedBody.endTime || '') +
'\r\n' +
(hostName ? '<https://' + hostName + '|' + hostName + '> ' : '') +
(id ? 'Id: ' + parsedBody.id + '\r\n' : '') +
'```' +
(parsedBody.message || 'null message') +
'```'
);
}