-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
96 lines (81 loc) · 2.37 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
"use latest";
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var waterfall = require('async').waterfall;
/* Tools */
const fail = (err) => (
console.log(err)
);
const existy = (input) => (
input != null
);
module.exports = (ctx, cb) => {
const MONGO_URL = ctx.data.MONGO_URL;
if (!MONGO_URL) return cb(new Error('MONGO_URL secret is missing'));
/* Parse a string to check if it has 'http' or 'https' in it */
const hasHttp = (str) => (
/(https?:\/\/)/.test(str)
);
/* Search for messages that contain links and return them */
const getUrlsFromObject = (obj) => {
if (!obj.hasOwnProperty('messages')) {
return fail('This object does not have a messages prop');
}
if (obj['messages'].length === 0) {
return fail('No new messages in the last 5 minutes');
}
if (obj.hasOwnProperty('messages')) {
return obj['messages'].filter(msg => (
hasHttp(msg.text)
))
}
};
/* Check if obj has urls */
const hasUrls = (obj) => {
if (obj.length === 0) {
return fail('This channel does not have any URL');
}
return obj;
};
/* Connect to db */
const mongoConnection = (cb) => {
MongoClient.connect(MONGO_URL, function (err, db) {
if (err) return cb(err);
cb(null, db);
})
};
/* Make a request to Slack for messages in history of the last five minutes */
const slackRequest = (db, cb) => {
const token = ctx.data.SLACK_TOKEN;
const channel = ctx.data.SLACK_CHANNEL;
const oldest = (Date.now() - 5 * 60 * 1000) / 1000;
request.get(`https://slack.com/api/channels.history?token=${token}&channel=${channel}&oldest=${oldest}&pretty=1`, (err, res, body) => {
if (err) return cb(err);
cb(null, db, getUrlsFromObject(JSON.parse(body)));
});
};
/* Save the result to Mongo */
const saveToMongo = (db, obj, cb) => {
if (!existy(obj)) {
return fail('No new object');
}
if (!hasUrls(obj)) {
return fail('Nothing to save');
}
db
.collection('links')
.insert(obj, function (err, result) {
if(err) return cb(err);
cb(null, result);
});
};
/* Save result to db */
waterfall([
mongoConnection,
slackRequest,
saveToMongo
], (err, res) => {
if (err) return fail(err);
console.log(`Mongo saved correctly ${res.ops.length} entries`)
}, cb);
};