3 var debug = require('debug')('gitter:app:twitter:service');
4 var Promise = require('bluebird');
5 var request = Promise.promisify(require('request'));
6 var querystring = require('querystring');
7 var StatusError = require('statuserror');
9 function escapeTweet(str) {
10 return encodeURIComponent(str).replace(/[!'()*]/g, escape);
13 var FOLLOWER_API_ENDPOINT = 'https://api.twitter.com/1.1/followers/list.json';
14 var FAVORITES_API_ENDPOINT = 'https://api.twitter.com/1.1/favorites/list.json';
15 var TWEET_API_ENDPOINT = 'https://api.twitter.com/1.1/statuses/update.json';
17 function TwitterService(consumerKey, consumerSecret, accessToken, accessTokenSecret) {
18 this.consumerKey = consumerKey;
19 this.consumerSecret = consumerSecret;
20 this.accessToken = accessToken;
21 this.accessTokenSecret = accessTokenSecret;
24 TwitterService.prototype.findFollowers = function(username) {
26 url: FOLLOWER_API_ENDPOINT,
29 consumer_key: this.consumerKey,
30 consumer_secret: this.consumerSecret,
31 token: this.accessToken,
32 token_secret: this.accessTokenSecret
37 }).then(function(results) {
38 debug('Twitter API results: %j', results && results.body);
39 if (!results.body || !results.body.users) {
43 return results.body.users;
47 TwitterService.prototype.findFavorites = function() {
49 url: FAVORITES_API_ENDPOINT,
52 consumer_key: this.consumerKey,
53 consumer_secret: this.consumerSecret,
54 token: this.accessToken,
55 token_secret: this.accessTokenSecret
60 TwitterService.prototype.sendTweet = function(status) {
63 url: TWEET_API_ENDPOINT,
66 consumer_key: this.consumerKey,
67 consumer_secret: this.consumerSecret,
68 token: this.accessToken,
69 token_secret: this.accessTokenSecret
73 'content-type': 'application/x-www-form-urlencoded'
75 body: querystring.stringify(
82 encodeURIComponent: escapeTweet
85 }).then(function(res) {
86 if (res.statusCode === 200) {
90 var errorMessage = res.body;
91 if (res.body.errors) {
92 errorMessage = (res.body.errors || []).reduce(function(errorString, error) {
94 errorString + (errorString.length > 0 ? ' -- ' : '') + error.code + ' ' + error.message
98 var errorString = 'Status: ' + res.statusCode + ' -- ' + errorMessage;
100 throw new StatusError(400, errorString);
104 module.exports = TwitterService;