-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
203 lines (185 loc) · 8.82 KB
/
app.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//var createError = require('http-errors');
var express = require('express');
var path = require('path');
//var cookieParser = require('cookie-parser');
//var logger = require('morgan');
const
crypto = require('crypto'),
bodyParser = require('body-parser'),
request = require('request');
// Use dotenv to allow local running with environment variables
require('dotenv').load();
const
VERIFY_TOKEN = process.env.VERIFY_TOKEN,
ACCESS_TOKEN = process.env.ACCESS_TOKEN,
APP_SECRET = process.env.APP_SECRET;
if (!(APP_SECRET && VERIFY_TOKEN && ACCESS_TOKEN)) {
console.error('Missing environment values.');
//process.exit(1);
}
//pg.defaults.ssl = false;
var graphapi = request.defaults({
baseUrl: 'https://graph.facebook.com',
json: true,
auth: {
'bearer': ACCESS_TOKEN
}
});
function verifyRequestSignature(req, res, buf) {
var signature = req.headers['x-hub-signature'];
if (!signature) {
// For testing, let's log an error. In production, you should throw an error.
console.error('Couldn\'t validate the signature.');
} else {
var elements = signature.split('=');
var signatureHash = elements[1];
var expectedHash = crypto.createHmac('sha1', APP_SECRET)
.update(buf)
.digest('hex');
if (signatureHash != expectedHash) {
throw new Error('Couldn\'t validate the request signature.');
}
}
}
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json({ verify: verifyRequestSignature }));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// List out all the thanks recorded in the database
app.get('/', function(request, response) {
response.render('pages/thanks', { results: 'ok' });
});
// Handle the webhook subscription request from Facebook
app.get('/webhook', function(request, response) {
if (request.query['hub.mode'] === 'subscribe' &&
request.query['hub.verify_token'] === VERIFY_TOKEN) {
console.log('Validated webhook');
response.status(200).send(request.query['hub.challenge']);
} else {
console.error('Failed validation. Make sure the validation tokens match.');
response.sendStatus(403);
}
});
// Handle webhook payloads from Facebook
app.post('/webhook', function(request, response) {
if (request.body && request.body.entry) {
request.body.entry.forEach(function(entry) {
entry.changes.forEach(function(change) {
if (change.field === 'mention') {
let mention_id = (change.value.item === 'comment') ?
change.value.comment_id : change.value.post_id;
// Like the post or comment to indicate acknowledgement
graphapi({
url: '/' + mention_id + '/likes',
method: 'POST'
}, function(error, res, body) {
console.log('Like', mention_id);
});
let message = change.value.message,
message_tags = change.value.message_tags,
sender = change.value.from.id,
permalink_url = change.value.permalink_url,
recipients = [],
managers = [],
query_inserts = [];
/*
message_tags.forEach(function(message_tag) {
// Ignore page / group mentions
if(message_tag.type !== 'user') return;
// Add the recipient to a list, for later retrieving their manager
recipients.push(message_tag.id);
});
// Get recipients' managers in bulk using the ?ids= batch fetching method
graphapi({
url: '/',
qs: {
ids: recipients.join(','),
fields: 'managers'
}
}, function(error,res,body) {
// Add a data row for the insert query
recipients.forEach(function(recipient) {
// Check if we found their manager
let manager = '';
if(body
&& body[recipient]
&& body[recipient].managers
&& body[recipient].managers.data[0])
manager = body[recipient].managers.data[0].id;
managers[recipient] = manager;
query_inserts.push(`(now(),'${permalink_url}','${recipient}','${manager}','${sender}','${message}')`);
});*/
/* var interval = '1 week';
let query = 'INSERT INTO thanks VALUES '
+ query_inserts.join(',')
+ `; SELECT * FROM thanks WHERE create_date > now() - INTERVAL '${interval}';`;
pg.connect(DATABASE_URL, function(err, client, done) {
client.query(query, function(err, result) {
done();
if (err) {
console.error(err);
} else if (result) {
var summary = 'Thanks received!\n';
// iterate through result rows, count number of thanks sent
var sender_thanks_sent = 0;
result.rows.forEach(function(row) {
if(row.sender == sender) sender_thanks_sent++;
});
summary += `@[${sender}] has sent ${sender_thanks_sent} thanks in the last ${interval}\n`;
// Iterate through recipients, count number of thanks received
recipients.forEach(function(recipient) {
let recipient_thanks_received = 0;
result.rows.forEach(function(row) {
if(row.recipient == recipient) recipient_thanks_received++;
});
if(managers[recipient]) {
summary += `@[${recipient}] has received ${recipient_thanks_received} thanks in the last ${interval}. Heads up to @[${managers[recipient]}].\n`;
} else {
summary += `@[${recipient}] has received ${recipient_thanks_received} thanks in the last ${interval}. I don't know their manager.\n`;
}
});*/
// Comment reply with thanks stat summary
var summary = 'Muchas Gracias por tu comentario' + message + '\n';
graphapi({
url: '/' + mention_id + '/comments',
method: 'POST',
qs: {
message: summary
}
}, function(error, res, body) {
console.log('Comment reply', mention_id);
});
//}
response.sendStatus(200);
//});
//});
//});
}
});
});
}
});
module.exports = app;