-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
272 lines (240 loc) · 8.39 KB
/
index.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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
console.log('Loading function');
var Promise = require('bluebird');
var Twitter = require('twitter');
var AWS = require('aws-sdk');
var dynamoDbDoc = new AWS.DynamoDB.DocumentClient();
var config = require('./config.json').production;
var client = new Twitter({
consumer_key: config.consumer_key,
consumer_secret: config.consumer_secret,
access_token_key: config.access_token_key,
access_token_secret: config.access_token_secret
});
/**
* Provide an event that contains the following key:
*
* - operation: one of the operations in the switch statement below
*/
exports.handler = function(event, context) {
console.log('Received event:', JSON.stringify(event, null, 2));
var operation = event.operation;
switch (operation) {
case 'create':
var status = event.status;
if (!status) {
return context.fail(new Error('Invalid or missing "status" parameter.'));
}
client.post('statuses/update', {status: status}, function(error, tweet/*, response*/){
if(error) {
console.error('Error posting tweet');
console.error(error);
return context.fail(new Error('Error posting tweet: ' + error));
}
console.info('Tweet posted');
console.info(tweet); // Tweet body.
return context.succeed(tweet);
});
break;
case 'ping':
return context.succeed('pong');
default:
context.fail(new Error('Unrecognized operation "' + operation + '"'));
}
};
/**
* Schedule a tweet to be posted at a later time
*
* - date: The time at which to post the tweet (in milliseconds since Jan 1 1970 UTC)
* - status: The tweet text
*/
exports.scheduledTweetPost = function(event, context) {
var twoMinutes = 2*60*1000;
/* GET PARAMETERS */
var date = parseInt(event.date);
var status = event.status;
/* VALIDATE PARAMETERS */
if (!status) { return context.fail(new Error('Invalid or missing "status" parameter.')); }
if (!date) { return context.fail(new Error('Invalid or missing "date" parameter.')); }
if (date < (new Date() - twoMinutes)) { return context.fail(new Error('Invalid date. Cannot post tweet in the past.')); }
/* CONSTRUCT DYNAMODB ENTRY */
var params = {
TableName: 'scheduledTweets',
Item: {
// FIXME: Don't hard-code twitterAccount value
'twitterAccount': 'crc',
'postedDate': date,
'modifiedDate': new Date().valueOf(),
'statusText': status,
'isPosted': false
},
ReturnValues: 'ALL_OLD'
};
/* PUT ITEM IN DYNAMODB */
dynamoDbDoc.put(params, function(err, data) {
if (err) {
console.error(err);
return context.fail(new Error('Error scheduling tweet.'));
}
if (data && data.hasOwnProperty('Attributes')) {
console.info('Tweet replaced.');
console.info('Previous tweet: ');
console.info(JSON.stringify(data, null, 2));
} else {
console.info('New tweet scheduled.');
}
return context.succeed(data);
});
};
/**
* Updates a previously scheduled but not posted tweet.
*
* - oldDate: The previously scheduled time at which the tweet was to be posted (milliseconds since Jan 1 1970)
* - newDate: The updated time at which to post the tweet (milliseconds since Jan 1 1970 UTC)
* - status: The updated tweet text
*/
exports.scheduledTweetPut = function(/*event, context*/) {
};
/**
* Deletes a previously scheduled but not posted tweet.
*
* - date: The time at which the tweet was to be posted (milliseconds since Jan 1 1970)
*/
exports.scheduledTweetDelete = function(/*event, context*/) {
};
/**
* Returns all scheduled tweets to post with a specified time range
*
* Required:
* - account: Handle for the twitter account (without @)
*
* Optional:
* - fromDate: The post date after which to return scheduled tweets (milliseconds since Jan 1 1970)
* - toDate: The post date before which to return scheduled tweets (milliseconds since Jan 1 1970)
*/
exports.scheduledTweetList = function(event, context) {
/* GET PARAMETERS */
var account = event.account;
var fromDate = parseInt(event.fromDate) || null;
var toDate = parseInt(event.toDate) || null;
/* VALIDATE PARAMETERS */
if (fromDate && toDate && toDate < fromDate) { return context.fail(new Error('"toDate" cannot be before "fromDate".')); }
if (!account) { return context.fail(new Error('Invalid or missing "account" parameter.')); }
/* CONSTRUCT DATE RANGE QUERY */
var dateRangeQuery = '';
var expAttrVals = { ':account': account, ':true': true };
if (fromDate && toDate) {
dateRangeQuery = ' AND postedDate BETWEEN :from AND :to';
expAttrVals[':from'] = fromDate;
expAttrVals[':to'] = toDate;
} else if (fromDate) {
dateRangeQuery = ' AND postedDate GT :from';
expAttrVals[':from'] = fromDate;
} else if (toDate) {
dateRangeQuery = ' AND postedDate LT :to';
expAttrVals[':to'] = toDate;
}
/* CONSTRUCT DYNAMODB QUERY */
var params = {
TableName: 'scheduledTweets',
KeyConditionExpression: 'twitterAccount = :account' + dateRangeQuery,
FilterExpression: 'isPosted <> :true',
ExpressionAttributeValues: expAttrVals
};
/* EXECUTE DYNAMODB QUERY */
dynamoDbDoc.query(params, function(err, data) {
if (err) {
console.error(err);
return context.fail(new Error('Error getting scheduled tweets.'));
}
console.info('Got ' + data.Count + ' scheduled tweets from DynamoDB.');
return context.succeed(data);
});
};
/**
* Checks DynamoDB for any tweets that are scheduled to be posted now and posts them to Twitter!
* This is setup to be run every 5 minutes. It looks for tweets to be posted from the past
* 7 minutes to the next 1 minute. It filters out tweets with `posted` set to true.
*/
exports.scheduledTweetWorker = function(event, context) {
/* DEFINE DYNAMODB QUERY */
var twitterAccount = 'crc';
var now = new Date();
var fromDate = +now - (7*60*1000); // now minus 7 minutes
var toDate = +now + (1*60*1000); // now plus 1 minute
var params = {
TableName: 'scheduledTweets',
KeyConditionExpression: 'twitterAccount = :account AND postedDate BETWEEN :from AND :to',
FilterExpression: 'isPosted <> :true',
ExpressionAttributeValues: {
':account': twitterAccount,
':from': fromDate,
':to': toDate,
':true': true
}
};
/* EXECUTE DYNAMODB QUERY */
dynamoDbDoc.query(params, function(err, data) {
if (err) {
console.error(err);
return context.fail(new Error('Error getting scheduled tweets.'));
}
console.info('Worker got ' + data.Count + ' scheduled tweets from DynamoDB.');
console.info(data);
Promise.each(data.Items, function(scheduledTweet) {
if (!scheduledTweet.isPosted) {
return postAsync(scheduledTweet.statusText)
.then(function(tweet) {
console.log('Posted tweet: ' + scheduledTweet.statusText);
return setTweetAsPosted(scheduledTweet, tweet.id_str);
})
.catch(function(error) {
console.error('Error posting tweet: ' + scheduledTweet.statusText);
console.error(error);
});
}
})
.then(function() {
return context.succeed('Finished posting tweets. No errors.');
})
.catch(function(/*error*/) {
return context.fail('Finished posting tweets. See error(s) above.');
});
});
};
function postAsync(tweetText) {
return new Promise(function(resolve, reject) {
client.post('statuses/update', {status: tweetText}, function(error, tweet/*, response*/) {
if (error) {
console.error('Error posting tweet.');
reject(error);
} else {
console.log('Tweet posted.');
resolve(tweet);
}
});
});
}
function setTweetAsPosted(scheduledTweet, twitterId) {
/* DEFINE DYNAMODB QUERY */
var params = {
TableName: 'scheduledTweets',
Key: { 'twitterAccount': scheduledTweet.twitterAccount,
'postedDate': scheduledTweet.postedDate },
UpdateExpression: 'set #a = :boolVal, #b = :twitterId',
ExpressionAttributeNames: { '#a': 'isPosted',
'#b': 'twitterId' },
ExpressionAttributeValues: { ':boolVal': true,
':twitterId': twitterId }
};
/* EXECUTE DYNAMODB QUERY */
return new Promise(function(resolve, reject) {
dynamoDbDoc.update(params, function(err, data) {
if (err) {
console.error('Error setting tweet as posted (' + scheduledTweet.statusText + ')');
reject(err);
} else {
resolve(data);
}
});
});
}