-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
235 lines (208 loc) · 5.85 KB
/
index.js
File metadata and controls
235 lines (208 loc) · 5.85 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
'use strict';
const googleAuth = require('./lib/google-auth');
const db = require('./lib/dynamo-access');
const Promise = require('bluebird');
const _ = require('lodash');
const slackApi = require('./lib/slack-api');
const sayings = require('./lib/sayings');
const formatters = require('./lib/formatters');
const keywords = ['to', 'subject', 'body'];
const json = JSON.stringify;
function assembleBot(team, channel) {
let bot = {
team: team,
api: slackApi(team)
};
bot.say = message => {
if (typeof message === 'string') {
return bot.api.send(channel, {text: message});
} else {
return bot.api.send(channel, message);
}
};
for (let saying in sayings) {
bot[saying] = bot.say.bind(bot, sayings[saying]);
}
return bot;
}
function checkKeywords(word) {
let regex;
for (let j = 0; j < keywords.length; j++) {
regex = new RegExp(`^${keywords[j]}:`);
if (regex.test(word)) {
return keywords[j];
}
}
return null;
}
function parseMessage(text) {
const regex = /(to:|subject:|body:)/;
const body = {};
const arr = text.split(regex).map(w => w.trim()).filter(w => w !== '');
arr.forEach((e, i) => {
let word = checkKeywords(e);
if (word) {
let phrase = arr[i + 1];
if (word === 'to' && phrase.indexOf('|') !== -1) {
phrase = phrase.slice(0, phrase.indexOf('|'));
}
body[word] = phrase.trim();
}
});
console.log('parsed message:', body);
return body;
}
/*function authorizeNewUser(userId, cb) {
googleAuth.authorizeUser(function(err, auth) {
if (err) return cb(err);
const userData = {
id: userId,
dateAccessed: new Date(),
googleAuth: auth,
accessed: 100
};
console.log('inserting new user');
db.insertSlackUser(userData, function(err, data) {
db.getUser(userId, cb);
});
});
}*/
const saveUserToken = Promise.coroutine(function* (event, code, bot, done) {
try {
let token = yield googleAuth.applyNewToken(code);
const saveUser = Promise.promisify(db.saveUserToken, db);
const user = yield saveUser(event.user_id, event.team_id, token);
const text = sayings.authorized;
if (event.command) {
yield bot.api.commandResponse(sayings.authorized, event.response_url);
return done(null, {text: ':email:'});
} else{
yield bot.authorized();
}
} catch(e) {
if (event.command) {
yield bot.api.commandResponse(sayings.tokenCommandError, event.response_url);
} else {
yield bot.tokenError();
}
}
return done();
});
const lookupUser = function(userId, teamId) {
return new Promise(function(resolve, reject) {
db.getUser(userId, teamId, function(err, user) {
if (err) return reject(err);
if (!user || !user.Item) {
console.log('USER NOT FOUND', user)
return resolve(null);
}
return resolve(user.Item);
});
});
};
const lookupTeam = function(teamId) {
return new Promise(function(resolve, reject) {
db.getTeam(teamId, function(err, team) {
if (err) return reject(err); // don't reject
if (!team || !team.Item) {
console.log('TEAM NOT FOUND', team)
return resolve(null);
}
return resolve(team.Item);
});
});
};
const handleNewUser = function(event, bot) {
return new Promise(function(resolve, reject) {
db.insertSlackUser(event.user_id, event.team_id, function(err) {
if (err) {
return reject(err);
}
const url = googleAuth.getAuthUrl();
bot.introduce();
bot.help();
resolve();
});
});
}
// Lambda entry point
exports.handler = Promise.coroutine(function* (event, context, cb) {
context.callbackWaitsForEmptyEventLoop = false;
const done = (err, data) => {
event = null;
context = null;
cb(err, data);
};
// transform event from API Gateway
if (event['body-json']) {
event = event['body-json'];
}
// Handle Slack's endpoint verification
if (event.challenge) {
console.log('recieved challenge', event);
return done(null, {challenge: event.challenge});
}
if (event.type === 'event_callback') {
let _event = event.event;
delete event.event;
_.assign(event, _event);
event.user_id = event.user;
}
console.log('event post transformation:', event);
let team = yield lookupTeam(event.team_id);
if (!team) {
return console.error('no team found for ', event.team_id);
}
// If this event was originated from us (the bot user), return
if (event.user_id === team.bot_user_id) {
return context.done();
}
let bot = assembleBot(team, event.channel);
if (/^help/.test(event.text)) {
yield bot.help();
return done();
} else if (/^instructions/.test(event.text)) {
yield bot.instructions();
return done();
}
let user = yield lookupUser(event.user_id, event.team_id);
if (!user) {
try {
yield handleNewUser(event, bot);
} catch(e) {
console.error(e);
yield bot.error();
}
return done();
}
let token, isSlashCommand;
if (/^token=/.test(event.text)) {
token = event.text.slice('token='.length).trim();
return saveUserToken(event, token, bot, done);
} else if (!token && event.command && event.command === '/anfon-token') {
token = event.text;
return saveUserToken(event, token, bot, done);
}
if (!user.googleAuth.access_token) {
yield bot.unauthorized();
return done();
}
const body = parseMessage(event.text);
if (!body.to) {
return bot.missingTo().then(() => done());
}
if (!body.subject && !body.body) {
yield bot.missingMessage();
return done();
}
try {
yield googleAuth.sendEmail(user.googleAuth, body);
} catch(e) {
console.error(e);
yield bot.say(':slightly_frowning_face: There was a problem with sending that email:\n_' + e.errors[0].message + '_');
return done();
}
yield bot.say(formatters.email(body));
yield bot.sent();
done();
});