forked from reddit/node-api-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.es6.js
More file actions
executable file
·263 lines (216 loc) · 7 KB
/
index.es6.js
File metadata and controls
executable file
·263 lines (216 loc) · 7 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
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
import Cache from '@r/rest-cache';
import { EventEmitter } from 'events';
import superagent from 'superagent';
import url from 'url';
import activities from './apis/activities';
import hidden from './apis/hidden';
import saves from './apis/saves';
import search from './apis/search';
import stylesheets from './apis/stylesheets';
import subreddits from './apis/subreddits';
import subscriptions from './apis/subscriptions';
import trophies from './apis/trophies';
import accounts from './apis/accounts';
import votes from './apis/votes';
import links from './apis/links';
import comments from './apis/comments';
import captcha from './apis/captcha';
import reports from './apis/reports';
import messages from './apis/messages';
import modListing from './apis/modListing';
import preferences from './apis/preferences';
import subredditRelationships from './apis/subredditRelationships';
import rules from './apis/rules';
import wiki from './apis/wiki';
import multis from './apis/multis';
import multiSubscriptions from './apis/multiSubscriptions';
import NotImplementedError from './errors/notImplementedError';
import { v1 as _v1, errors as _errors, models as _models } from './old-src/api';
_errors.NotImplementedError = NotImplementedError;
const APIs = {
activities,
captcha,
hidden,
saves,
search,
stylesheets,
subreddits,
subscriptions,
trophies,
accounts,
votes,
links,
comments,
reports,
messages,
modListing,
preferences,
subredditRelationships,
rules,
wiki,
multis,
multiSubscriptions,
};
const DEFAULT_API_ORIGIN = 'https://www.reddit.com';
const AUTHED_API_ORIGIN = 'https://oauth.reddit.com';
const SCOPES = 'history,identity,mysubreddits,read,subscribe,vote,submit,' +
'save,edit,account,creddits,flair,livemanage,modconfig,' +
'modcontributors,modflair,modlog,modothers,modposts,modself,' +
'modwiki,privatemessages,report,wikiedit,wikiread';
class Snoode {
constructor(config={}) {
this.config = {
origin: DEFAULT_API_ORIGIN,
event: new EventEmitter(),
userAgent: 'snoodev2',
...config,
};
this.event = this.config.event;
this.cache = new Cache(this.buildCacheConfig());
for (let a in APIs) {
this[a] = new APIs[a](this);
}
}
buildCacheConfig() {
let dataTypes = {};
for (let a in APIs) {
let API = APIs[a];
let apiName = (new API({})).api;
dataTypes[apiName] = API.dataCacheConfig;
}
return {
dataTypes,
};
}
withAuth (token) {
return new Snoode({...this.config, token});
}
withConfig (config) {
// Merge the new config onto the old and return a new instance
return new Snoode({...this.config, ...config});
}
login (username, pass) {
return new Promise((r, x) => {
if (!this.config.oauthAppOrigin) {
x('Please set up a Reddit Oauth App, and pass in its URL as oauthAppOrigin to config.');
}
if (!this.config.clientId) {
x('Please set up a Reddit Oauth App, and pass in its id as clientId to config.');
}
if (!this.config.clientSecret) {
x('Please set up a Reddit Oauth App, and pass in its secret as clientSecret to config.');
}
superagent
.post(`${this.config.origin}/api/login/${username}`)
.type('form')
.send({ user: username, passwd: pass, api_type: 'json' })
.end((err, res) => {
if (err || !res.ok) {
return x(err || res);
}
const cookies = (res.header['set-cookie'] || []).map(c => {
return c.split(';')[0];
});
if (res.header['set-cookie'].join('').indexOf('reddit_session')) {
return this.convertCookiesToAuthToken(cookies).then(r,x);
}
x('Invalid login information.');
});
});
}
loginAndSave(username, pass) {
this.login(username, pass).then((token) => {
this.config.token = token.access_token;
this.config.refreshToken = token.refresh_token;
this.config.origin = this.config.authedOrigin || AUTHED_API_ORIGIN;
for (let a in APIs) {
this[a] = new APIs[a](this);
}
}, err => { throw err; });
}
convertCookiesToAuthToken (cookies) {
return new Promise((resolve, reject) => {
if (!cookies) { reject('No cookies passed in'); }
const endpoint = `${this.config.origin}/api/me.json`;
const headers = {
'User-Agent': this.config.userAgent,
cookie: cookies.join('; '),
...this.config.defaultHeaders,
};
superagent
.get(endpoint)
.set(headers)
.end((err, res) => {
if (err || !res.ok) {
if (err.timeout) { err.status = 504; }
return reject(err || res);
}
if (res.body.error || !res.body.data) {
return reject(401);
}
const modhash = res.body.data.modhash;
const endpoint = `${this.config.origin}/api/v1/authorize`;
const redirect_uri = `${this.config.oauthAppOrigin}/oauth2/token`;
let clientId = this.config.clientId;
let clientSecret = this.config.clientSecret;
const postParams = {
client_id: clientId,
redirect_uri,
scope: SCOPES,
state: modhash,
duration: 'permanent',
authorize: 'yes',
};
headers['x-modhash'] = modhash;
superagent
.post(endpoint)
.set(headers)
.type('form')
.send(postParams)
.redirects(0)
.end((err, res) => {
if (res.status !== 302) {
return resolve(res.status || 500);
}
if (res.body.error) {
return resolve(401);
}
const location = url.parse(res.headers.location, true);
const code = location.query.code;
const endpoint = `${this.config.origin}/api/v1/access_token`;
const postData = {
grant_type: 'authorization_code',
code,
redirect_uri,
};
const b = new Buffer(
`${clientId}:${clientSecret}`
);
const s = b.toString('base64');
const basicAuth = `Basic ${s}`;
const headers = {
'User-Agent': this.config.userAgent,
'Authorization': basicAuth,
...this.config.defaultHeaders,
};
superagent
.post(endpoint)
.set(headers)
.send(postData)
.type('form')
.end(function(err, res) {
if (err || !res.ok) {
if (err.timeout) { err.status = 504; }
reject(err);
}
return resolve(res.body);
});
});
});
});
}
}
export default Snoode;
export const v1 = _v1;
export const models = _models;
export const errors = _errors;