-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.js
110 lines (79 loc) · 2.6 KB
/
tracker.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
// Export the function trackBlog to be used in other files.
// OBS: Other files should evoke require('./tracker.js'); (if in the same dir)
module.exports.trackBlog = trackBlog;
module.exports.postBlog = postBlog;
module.exports.reTrackBlog = reTrackBlog;
function postBlog(req, res){
var hostname = req.body.blog;
//console.info("POST received: ", hostname);
trackBlog(hostname, function(s){
res.send(s);
});
}
function trackBlog(hostname, cb){
var https = require('https');
var db = require('./dbManager.js');
// Insert the hostname into the URL
var url = 'https://api.tumblr.com/v2/blog/' + hostname + '/likes?\
api_key=ZtJYLO0HI9tPYsC2pqCy6ciItK3XxWL9KgQErmo2TsknKtNtEp';
// do the GET request
var get_request = https.get(url, function(res) {
// Callback function to send the statusCode to the POST request
cb(res.statusCode);
// If blog not found, return error;
if(res.statusCode == 404)
return;
// Create a variable to accumulate data.
// It is necessary because the data could be to long.
// Otherwise it could only be possible to receive two posts.
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
// After all data is accumulated
res.on('end', function () {
// Create the JSON only if the hostname is valid.
// Parse the data to JSON Object
var j = JSON.parse(data);
//console.info(j);
db.saveBlog(hostname, j.response.liked_count, j.response.liked_posts);
});
});
// Catch any errors
get_request.end();
get_request.on('error', function(e) {
console.error(e);
});
}
function reTrackBlog(hostname){
var https = require('https');
var db = require('./dbManager.js');
// Insert the hostname into the URL
var url = 'https://api.tumblr.com/v2/blog/' + hostname + '/likes?\
api_key=ZtJYLO0HI9tPYsC2pqCy6ciItK3XxWL9KgQErmo2TsknKtNtEp';
// do the GET request
var get_request = https.get(url, function(res) {
// Create a variable to accumulate data.
// It is necessary because the data could be to long.
// Otherwise it could only be possible to receive two posts.
var data = '';
// If blog not found, return error;
if(res.statusCode == 404)
return;
res.on('data', function (chunk) {
data += chunk;
});
// After all data is accumulated
res.on('end', function () {
// Create the JSON only if the hostname is valid.
// Parse the data to JSON Object
var j = JSON.parse(data);
db.updateBlog(hostname, j.response.liked_count, j.response.liked_posts);
});
});
// Catch any errors
get_request.end();
get_request.on('error', function(e) {
console.error(e);
});
}