-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
189 lines (148 loc) · 5.59 KB
/
server.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// server.js
// Node.js implementation of slackline – https://github.com/ernesto-jimenez/slackline
// BASE SETUP
// ========================================================================================
// required modules
var settings = require ('./settings');
var express = require('express');
var bodyParser = require('body-parser');
var http = require('http');
var https = require('https');
var querystring = require('querystring');
var request = require('request');
var crypto = require('crypto');
// create an instance of express
var app = express();
// configure the app to use bodyParser()
// this will allow us to interpret the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// ROUTES
// ========================================================================================
var router = express.Router();
// test route to make sure everything is working
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to slackline!' });
});
router.all('/bridge', function(req, res) {
var username = req.body.user_name;
var userid = req.body.user_id;
var text = req.body.text;
var target_domain = req.query.domain;
var target_hook_token = req.query.token;
// to avoid infinite loops, don't post messages generated by slackbot
if (username == "slackbot") {
console.log("don't reflect this message; it's from the other channel!")
res.end('Message forwarded!');
return
} else {
getHash(userid, target_domain, function(err, email_hash){
fixMentions(text, target_domain, function(err, cleanText){
sendPost(email_hash, username, cleanText, target_domain, target_hook_token);
});
});
// TO DO: only fire success message when sendPost actually finishes (via a callback)
res.end('Message forwarded!');
};
});
app.use(router);
// START THE SERVER
// ========================================================================================
app.listen(port);
console.log('slackline is running on port ' + port);
// FUNCTIONS
// ========================================================================================
var mentionMap = {}
// takes a raw Slack message as an input, returns a cleaned string with any @ mentions converted to the relevant usernames
function fixMentions(text, target_domain, next){
var strText = text;
var userPattern = /<@([^>]+)>/igm;
var userArray = strText.match(userPattern);
if (userArray) {
var counter = 0;
userArray.forEach(function(strUseridRaw){
if (mentionMap[strUseridRaw]) {
strText = strText.replace(strUseridRaw, '@' + mentionMap[strUseridRaw]);
counter += 1;
if (counter == (userArray.length)) {
next(null, strText);
}
} else {
var strUserid = strUseridRaw.substring(2, strUseridRaw.length -1);
// get the sender's domain from settings.js
var referrer_domain = settings.domainReferrer[target_domain];
// use the sender's domain and userid to grab their user info from the Slack API
var url = 'https://slack.com/api/users.info?token=' + settings.tokens[referrer_domain] + '&user=' + strUserid;
https.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var userResponse = JSON.parse(body);
var username = userResponse.user.name;
mentionMap[strUseridRaw] = username;
strText = strText.replace(strUseridRaw, '@' + username);
counter += 1;
if (counter == (userArray.length)) {
next(null, strText);
}
});
}).on('error', function(e) {
console.log('Got error: ' + e);
});
}
});
} else {
next(null, text);
};
};
// cache of hashed email addresses, used for Gravatar URLs
var emailMap = {};
// calculate a hash of a user's email address based on userid. if that userid already exists in the cache, use the cached value.
// pass hash to the callback
function getHash(userid, target_domain, next) {
if (emailMap[userid]) {
var email_hash = emailMap[userid];
next(null, email_hash);
} else {
// get the sender's domain from settings.js
var referrer_domain = settings.domainReferrer[target_domain];
// use the sender's domain and userid to grab their user info from the Slack API
var url = 'https://slack.com/api/users.info?token=' + settings.tokens[referrer_domain] + '&user=' + userid;
https.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var userResponse = JSON.parse(body);
var email_hash = crypto.createHash('md5').update(userResponse.user.profile.email).digest('hex');
emailMap[userid] = email_hash;
next(null, email_hash);
});
}).on('error', function(e) {
console.log('Got error: ' + e);
});
};
};
// Send the forwarded message as a POST to the target Slack instance
function sendPost(email_hash, username, text, target_domain, target_hook_token) {
var options = {
uri: 'https://' + target_domain + settings.postUrl + target_hook_token,
method: 'POST',
json: {
'username' : username,
'text' : text,
'icon_url' : 'http://www.gravatar.com/avatar/' + email_hash
}
};
request(options, function(error, response, body) {
if(!error && response.statusCode == 200) {
console.log('Success!');
} else {
console.log(response);
}
});
};