-
Notifications
You must be signed in to change notification settings - Fork 95
/
twitter.js
357 lines (312 loc) · 10.5 KB
/
twitter.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
const crypto = require('crypto');
const OAuth = require('oauth-1.0a');
const Fetch = require('cross-fetch');
const querystring = require('querystring');
const Stream = require('./stream');
const getUrl = (subdomain, endpoint = '1.1') =>
`https://${subdomain}.twitter.com/${endpoint}`;
const createOauthClient = ({ key, secret }) => {
const client = OAuth({
consumer: { key, secret },
signature_method: 'HMAC-SHA1',
hash_function(baseString, key) {
return crypto
.createHmac('sha1', key)
.update(baseString)
.digest('base64');
},
});
return client;
};
const defaults = {
subdomain: 'api',
consumer_key: null,
consumer_secret: null,
access_token_key: null,
access_token_secret: null,
bearer_token: null,
version: '1.1',
extension: true,
};
// Twitter expects POST body parameters to be URL-encoded: https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature
// However, some endpoints expect a JSON payload - https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event
// It appears that JSON payloads don't need to be included in the signature,
// because sending DMs works without signing the POST body
const JSON_ENDPOINTS = [
'direct_messages/events/new',
'direct_messages/welcome_messages/new',
'direct_messages/welcome_messages/rules/new',
'media/metadata/create',
'collections/entries/curate',
];
const baseHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
function percentEncode(string) {
// From OAuth.prototype.percentEncode
return string
.replace(/!/g, '%21')
.replace(/\*/g, '%2A')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29');
}
class Twitter {
constructor(options) {
const config = Object.assign({}, defaults, options);
this.authType = config.bearer_token ? 'App' : 'User';
this.client = createOauthClient({
key: config.consumer_key,
secret: config.consumer_secret,
});
this.token = {
key: config.access_token_key,
secret: config.access_token_secret,
};
this.url = getUrl(config.subdomain, config.version);
this.oauth = getUrl(config.subdomain, 'oauth');
this.config = config;
}
/**
* Parse the JSON from a Response object and add the Headers under `_headers`
* @param {Response} response - the Response object returned by Fetch
* @return {Promise<object>}
* @private
*/
static async _handleResponse(response) {
const headers = response.headers; // TODO: see #44
if (response.ok) {
// Return empty response on 204 "No content", or Content-Length=0
if (response.status === 204 || response.headers.get('content-length') === '0')
return {
_headers: headers,
};
// Otherwise, parse JSON response
return response.json().then(res => {
res._headers = headers; // TODO: this creates an array-like object when it adds _headers to an array response
return res;
});
} else {
throw {
_headers: headers,
...await response.json(),
};
}
}
/**
* Resolve the TEXT parsed from the successful response or reject the JSON from the error
* @param {Response} response - the Response object returned by Fetch
* @return {Promise<object>}
* @throws {Promise<object>}
* @private
*/
static async _handleResponseTextOrJson(response) {
let body = await response.text();
if (response.ok) {
return querystring.parse(body);
} else {
let error;
try {
// convert to object if it is a json
error = JSON.parse(body);
} catch (e) {
// it is not a json
error = body;
}
return Promise.reject(error);
}
}
async getBearerToken() {
const headers = {
Authorization:
'Basic ' +
Buffer.from(
this.config.consumer_key + ':' + this.config.consumer_secret,
).toString('base64'),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
};
const results = await Fetch('https://api.twitter.com/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials',
headers,
}).then(Twitter._handleResponse);
return results;
}
async getRequestToken(twitterCallbackUrl) {
const requestData = {
url: `${this.oauth}/request_token`,
method: 'POST',
};
let parameters = {};
if (twitterCallbackUrl) parameters = { oauth_callback: twitterCallbackUrl };
if (parameters) requestData.url += '?' + querystring.stringify(parameters);
const headers = this.client.toHeader(
this.client.authorize(requestData, {}),
);
const results = await Fetch(requestData.url, {
method: 'POST',
headers: Object.assign({}, baseHeaders, headers),
})
.then(Twitter._handleResponseTextOrJson);
return results;
}
async getAccessToken(options) {
const requestData = {
url: `${this.oauth}/access_token`,
method: 'POST',
};
let parameters = { oauth_verifier: options.oauth_verifier, oauth_token: options.oauth_token };
if (parameters.oauth_verifier && parameters.oauth_token) requestData.url += '?' + querystring.stringify(parameters);
const headers = this.client.toHeader( this.client.authorize(requestData) );
const results = await Fetch(requestData.url, {
method: 'POST',
headers: Object.assign({}, baseHeaders, headers),
})
.then(Twitter._handleResponseTextOrJson);
return results;
}
/**
* Construct the data and headers for an authenticated HTTP request to the Twitter API
* @param {string} method - 'GET' or 'POST'
* @param {string} resource - the API endpoint
* @param {object} parameters
* @return {{requestData: {url: string, method: string}, headers: ({Authorization: string}|OAuth.Header)}}
* @private
*/
_makeRequest(method, resource, parameters) {
const requestData = {
url: `${this.url}/${resource}${this.config.extension ? '.json' : ''}`,
method,
};
if (parameters)
if (method === 'POST') requestData.data = parameters;
else requestData.url += '?' + querystring.stringify(parameters);
let headers = {};
if (this.authType === 'User') {
headers = this.client.toHeader(
this.client.authorize(requestData, this.token),
);
} else {
headers = {
Authorization: `Bearer ${this.config.bearer_token}`,
};
}
return {
requestData,
headers,
};
}
/**
* Send a GET request
* @param {string} resource - endpoint, e.g. `followers/ids`
* @param {object} [parameters] - optional parameters
* @returns {Promise<object>} Promise resolving to the response from the Twitter API.
* The `_header` property will be set to the Response headers (useful for checking rate limits)
*/
get(resource, parameters) {
const { requestData, headers } = this._makeRequest(
'GET',
resource,
parameters,
);
return Fetch(requestData.url, { headers })
.then(Twitter._handleResponse);
}
/**
* Send a POST request
* @param {string} resource - endpoint, e.g. `users/lookup`
* @param {object} body - POST parameters object.
* Will be encoded appropriately (JSON or urlencoded) based on the resource
* @returns {Promise<object>} Promise resolving to the response from the Twitter API.
* The `_header` property will be set to the Response headers (useful for checking rate limits)
*/
post(resource, body) {
const { requestData, headers } = this._makeRequest(
'POST',
resource,
JSON_ENDPOINTS.includes(resource) ? null : body, // don't sign JSON bodies; only parameters
);
const postHeaders = Object.assign({}, baseHeaders, headers);
if (JSON_ENDPOINTS.includes(resource)) {
body = JSON.stringify(body);
} else {
body = percentEncode(querystring.stringify(body));
postHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
return Fetch(requestData.url, {
method: 'POST',
headers: postHeaders,
body,
})
.then(Twitter._handleResponse);
}
/**
* Send a PUT request
* @param {string} resource - endpoint e.g. `direct_messages/welcome_messages/update`
* @param {object} parameters - required or optional query parameters
* @param {object} body - PUT request body
* @returns {Promise<object>} Promise resolving to the response from the Twitter API.
*/
put(resource, parameters, body) {
const { requestData, headers } = this._makeRequest(
'PUT',
resource,
parameters,
);
const putHeaders = Object.assign({}, baseHeaders, headers);
body = JSON.stringify(body);
return Fetch(requestData.url, {
method: 'PUT',
headers: putHeaders,
body,
})
.then(Twitter._handleResponse);
}
/**
*
* @param {string} resource - endpoint, e.g. `statuses/filter`
* @param {object} parameters
* @returns {Stream}
*/
stream(resource, parameters) {
if (this.authType !== 'User')
throw new Error('Streams require user context authentication');
const stream = new Stream();
// POST the request, in order to accommodate long parameter lists, e.g.
// up to 5000 ids for statuses/filter - https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter
const requestData = {
url: `${getUrl('stream')}/${resource}${this.config.extension ? '.json' : ''}`,
method: 'POST',
};
if (parameters) requestData.data = parameters;
const headers = this.client.toHeader(
this.client.authorize(requestData, this.token),
);
const request = Fetch(requestData.url, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: percentEncode(querystring.stringify(parameters)),
});
request
.then(response => {
stream.destroy = this.stream.destroy = () => response.body.destroy();
if (response.ok) {
stream.emit('start', response);
} else {
response._headers = response.headers; // TODO: see #44 - could omit the line
stream.emit('error', response);
}
response.body
.on('data', chunk => stream.parse(chunk))
.on('error', error => stream.emit('error', error)) // no point in adding the original response headers
.on('end', () => stream.emit('end', response));
})
.catch(error => stream.emit('error', error));
return stream;
}
}
module.exports = Twitter;