forked from Kenshin/simpread
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstapaper.js
More file actions
238 lines (216 loc) · 7.44 KB
/
instapaper.js
File metadata and controls
238 lines (216 loc) · 7.44 KB
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
// Instapaper xAuth API for client side JS. Depends on cross-domain requests.
// Reference: <http://www.instapaper.com/api/full>
// xAuth documentation from Twitter: <https://dev.twitter.com/docs/oauth/xauth>
// With help from <https://gist.github.com/447636>
var jsSHA = require("./sha1");
var Instapaper, fixedEncodeURIComponent, qline2object;
Instapaper = (function() {
class Instapaper {
// ## Class Methods
// ### Creates Nonce
// > "The oauth_nonce parameter is a unique token your application should
// generate for each unique request. Twitter will use this value to determine
// whether a request has been submitted multiple times."
// > <https://dev.twitter.com/docs/auth/authorizing-request>
generateNonce() {
var length, nonce;
nonce = [];
length = 5; // arbitrary - looks like a good length
while (length > 0) {
nonce.push((((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1));
length--;
}
return nonce.join("");
}
// UTC timestamp.
getUTCtimestamp() {
return (new Date((new Date).toUTCString())).getTime() / 1000;
}
// ### Creates 'header string' for 'Authorization' in HTTP header
// cf. <https://dev.twitter.com/docs/auth/authorizing-request>
authTemplate(req) {
var auth;
auth = `OAuth oauth_consumer_key="${fixedEncodeURIComponent(req.consumer_key)}", `;
if (req.token != null) {
auth += `oauth_token="${fixedEncodeURIComponent(req.token)}", `;
}
auth += `oauth_signature_method="HMAC-SHA1", oauth_signature="${fixedEncodeURIComponent(req.signature)}", oauth_timestamp="${fixedEncodeURIComponent(req.timestamp)}", oauth_nonce="${fixedEncodeURIComponent(req.nonce)}", oauth_version="1.0"`.trim();
return auth;
}
// ### Creates 'Signature base string'
// cf. <https://dev.twitter.com/docs/auth/creating-signature>
sigBaseTemplate(req) {
var i, j, len, param_helper, param_string, params, ref, sig;
params = {
oauth_consumer_key: req.consumer_key,
oauth_nonce: req.nonce,
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: req.timestamp,
oauth_version: '1.0'
};
if (req.token != null) {
params.oauth_token = req.token;
}
if (req.data != null) {
params = $.extend(params, req.data);
}
// Params string: sort object by key, then make querystring
param_helper = [];
ref = Object.keys(params).sort();
for (j = 0, len = ref.length; j < len; j++) {
i = ref[j];
param_helper.push(`${fixedEncodeURIComponent(i)}=${fixedEncodeURIComponent(params[i])}`);
}
param_string = param_helper.join('&');
sig = `POST&${fixedEncodeURIComponent(this.baseUrl + req.url)}&${fixedEncodeURIComponent(param_string)}`;
return sig;
}
// ## General Methods
makeSigningKey() {
var key;
key = this.consumer_secret + '&';
if (this.token_secret != null) {
key += this.token_secret;
}
return key;
}
// ### Create Signature for `authTemplate()`
// Depends on HMAC-SHA1 from <http://caligatio.github.com/jsSHA/>
makeSignature(req) {
var hmacGen;
hmacGen = new jsSHA(this.sigBaseTemplate(req), "TEXT");
var hmac = hmacGen.getHMAC(this.makeSigningKey(), "TEXT", "SHA-1", "B64")
return hmac;
}
// ### Creates `req`, an object with data specific for each request
makeRequestObject(options) {
var req;
req = $.extend({
consumer_key: this.consumer_key,
consumer_secret: this.consumer_secret,
nonce: this.generateNonce(),
timestamp: this.getUTCtimestamp(),
token: this.token,
token_secret: this.token_secret,
method: 'POST'
}, options);
// Add signature, depends on req data so far
req.signature = this.makeSignature(req);
return req;
}
// Creates new Ajax request
// Always uses POST
request(options) {
var auth, req;
req = options.req || (options.req = this.makeRequestObject({
url: options.url,
data: options.data
}));
auth = this.authTemplate(options.req);
return $.ajax({
url: `${this.baseUrl}${options.url}`,
dataType: (function() {
return options.dataType || "json";
})(),
type: 'POST',
data: options.data,
headers: {
Authorization: auth
}
});
}
// ## Specific API Methods
// ### Gets an OAuth access token for a user.
// * Requires username and password
// * Also needs HTTPS
requestToken(user, password) {
var data, tokening, url;
if (!((user != null) && (password != null))) {
throw 'Please provide username and password.';
}
this.user = user;
url = "oauth/access_token";
data = {
x_auth_username: user,
x_auth_password: password,
x_auth_mode: "client_auth"
};
// Make Ajax request
tokening = this.request({
url: url,
req: this.makeRequestObject({
url: url,
data: data
}),
data: data,
dataType: 'text'
});
// Sucessful response looks like:
// `oauth_token=aabbccdd&oauth_token_secret=efgh1234`
tokening.done((response) => {
// Uses `jline2object` (see below) to retrieve data from query string
data = qline2object(response);
// Save oauth tokens to instance variables
this.token = data.oauth_token;
return this.token_secret = data.oauth_token_secret;
});
// Please can for a failure case yourself!
// `tokening.fail (jqXHR, textStatus, errorThrown) => ...`
return tokening;
}
// ### Returns the currently logged in user.
// `[{"type":"user","user_id":54321,"username":"TestUserOMGLOL"}]`
verifyCredentials() {
return this.request({
url: "account/verify_credentials"
});
}
// Example method
// I won't add all the API stuff here, just do something like:
// insta = new Instapaper()
// insta.requestToken(username, password)
// insta.request(url: "bookmarks/list")
bookmarkList() {
return this.request({
url: "bookmarks/list"
});
}
add( url, title, description ) {
return this.request({
url: "bookmarks/add",
data: {
url,
title,
description
}
});
}
};
// Always uses HTTPS
Instapaper.prototype.baseUrl = "https://www.instapaper.com/api/1/";
// Application keys for this application
Instapaper.prototype.consumer_key = 'SECRET';
Instapaper.prototype.consumer_secret = 'TOPSECRET';
return Instapaper;
})();
if (typeof module !== "undefined" && module !== null) {
module.exports = Instapaper;
}
// Helper function to transform querystring/qline to JS object
// Insanely fast: <http://jsperf.com/query-str-parsing-regex-vs-split/5>
qline2object = function(query = "") {
var item, j, len, parts, result;
result = {};
parts = query.split("&");
for (j = 0, len = parts.length; j < len; j++) {
item = parts[j];
item = item.split("=");
result[item[0]] = item[1];
}
return result;
};
// native encodeURIComponent isn't sufficient here
// from <https://gist.github.com/447636>
fixedEncodeURIComponent = function(str) {
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
};