This repository has been archived by the owner on Aug 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
94 lines (85 loc) · 2.58 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
var twitter = require('ntwitter');
var mongoose = require('mongoose');
var twitter_conf = require('./config_twitter.js');
var config = require('./config.js');
// mapped 1-1 to Twitter object
var twschema = new mongoose.Schema(config.tw_harvest_schema_11, {autoindex: true});
var t = new twitter({
consumer_key: twitter_conf.twit_consumer_key,
consumer_secret: twitter_conf.twit_consumer_secret,
access_token_key: twitter_conf.twit_access_token,
access_token_secret: twitter_conf.twit_token_secret
});
// connect to dataabse
var db = mongoose.createConnection(config.db_host, config.db_name);
db.on('error', console.error.bind(console, 'connection error:'));
// Tweet Model object
var TweetElement = db.model(config.db_collection_twitter, twschema);
// Twitter object
var Twit = {
'save' : function(tweet, callback) {
TwitStore.save(tweet, callback);
}
}
// Twitter Store Model
var TwitStore = {
'getLastTweet' : function(callback) {
// http://mongoosejs.com/docs/api.html#query_Query-sort
// http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html
var q = TweetElement.findOne().limit(1);
q.sort({ created_at: 'desc' });
q.execFind(function(err, tweet) {
if (err) {
console.log('No tweet found');
process.exit(0);
}
if (tweet.length === 0) {
callback(false);
}
// callback last tweet
callback(tweet[0]);
});
},
'save' : function(tweet, callback) {
twit = new TweetElement(tweet);
twit.save(function(err, type) {
callback(err, type);
});
}
}
TwitStore.getLastTweet(function(item) {
var query = {};
if (item) {
query.since_id = item.id_str;
}
// https://dev.twitter.com/docs/api/1/get/search
// maximum number
query.count = twitter_conf.twitter_query_count;
query.q = twitter_conf.twitter_harvest_search;
query.result_type = twitter_conf.twitter_result_type;
var url = twitter_conf.twitter_search_url;
t.get(url, query, function(err, data) {
if (typeof(data) != 'undefined' && data.statuses.length) {
res = data.statuses;
counter = 0;
res.forEach(function (item) {
Twit.save(item, function(err, type) {
counter++;
if (err) {
console.log('Fatal error on saving tweet.');
console.log(err);
process.exit(0);
}
if (counter == res.length) {
console.log('Imported: ' + counter + ' tweets.');
process.exit(1);
}
});
});
}
else {
console.log('No fresh data available.');
process.exit(1);
}
});
});