This repository has been archived by the owner on Mar 17, 2024. It is now read-only.
/
snoowrap.js
1981 lines (1879 loc) · 86.5 KB
/
snoowrap.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {defaults, forOwn, includes, isEmpty, map, mapValues, omit, omitBy, snakeCase, values} from 'lodash';
import Promise from './Promise.js';
import promiseWrap from 'promise-chains';
import util from 'util';
import * as requestHandler from './request_handler.js';
import {HTTP_VERBS, KINDS, MAX_LISTING_ITEMS, MODULE_NAME, USER_KEYS, SUBREDDIT_KEYS, VERSION} from './constants.js';
import * as errors from './errors.js';
import {
addEmptyRepliesListing,
addFullnamePrefix,
addSnakeCaseShadowProps,
defineInspectFunc,
handleJsonErrors,
isBrowser,
requiredArg
} from './helpers.js';
import createConfig from './create_config.js';
import * as objects from './objects/index.js';
const api_type = 'json';
/** The class for a snoowrap requester.
* A requester is the base object that is used to fetch content from reddit. Each requester contains a single set of OAuth
tokens.
If constructed with a refresh token, a requester will be able to repeatedly generate access tokens as necessary, without any
further user intervention. After making at least one request, a requester will have the `access_token` property, which specifies
the access token currently in use. It will also have a few additional properties such as `scope` (an array of scope strings)
and `ratelimitRemaining` (the number of requests remaining for the current 10-minute interval, in compliance with reddit's
[API rules](https://github.com/reddit/reddit/wiki/API).) These properties primarily exist for internal use, but they are
exposed since they are useful externally as well.
*/
const snoowrap = class snoowrap {
/**
* @summary Constructs a new requester.
* @desc You should use the snoowrap constructor if you are able to authorize a reddit account in advance (e.g. for a Node.js
script that always uses the same account). If you aren't able to authorize in advance (e.g. acting through an arbitrary user's
account while running snoowrap in a browser), then you should use {@link snoowrap.getAuthUrl} and
{@link snoowrap.fromAuthCode} instead.
*
* To edit snoowrap specific settings, see {@link snoowrap#config}.
*
* snoowrap supports several different options for pre-existing authentication:
* 1. *Refresh token*: To authenticate with a refresh token, pass an object with the properties `userAgent`, `clientId`,
`clientSecret`, and `refreshToken` to the snoowrap constructor. You will need to get the refresh token from reddit
beforehand. A script to automatically generate refresh tokens for you can be found
[here](https://github.com/not-an-aardvark/reddit-oauth-helper).
* 1. *Username/password*: To authenticate with a username and password, pass an object with the properties `userAgent`,
`clientId`, `clientSecret`, `username`, and `password` to the snoowrap constructor. Note that username/password
authentication is only possible for `script`-type apps.
* 1. *Access token*: To authenticate with an access token, pass an object with the properties `userAgent` and `accessToken`
to the snoowrap constructor. Note that all access tokens expire one hour after being generated, so this method is
not recommended for long-term use.
* @param {object} options An object containing authentication options. This should always have the property `userAgent`. It
must also contain some combination of credentials (see above)
* @param {string} options.userAgent A unique description of what your app does. This argument is not necessary when snoowrap
is running in a browser.
* @param {string} [options.clientId] The client ID of your app (assigned by reddit)
* @param {string} [options.clientSecret] The client secret of your app (assigned by reddit). If you are using a refresh token
with an installed app (which does not have a client secret), pass an empty string as your `clientSecret`.
* @param {string} [options.username] The username of the account to access
* @param {string} [options.password] The password of the account to access
* @param {string} [options.refreshToken] A refresh token for your app
* @param {string} [options.accessToken] An access token for your app
*/
constructor ({
// The function signature for the constructor is a bit large due to the snake_case aliases. Essentially, it accepts an
// object with properties {userAgent, clientId, clientSecret, refreshToken, accessToken, username, password}.
// Additionally, if snake_case properties are provided and camelCase properties are not (e.g. `user_agent` is provided but
// `userAgent` is not), then the `userAgent` identifier gets set to the provided `user_agent` property. This is needed for
// backwards compatibility; snoowrap previously only accepted snake_case props, but now it also accepts camelCase props.
user_agent, userAgent = user_agent,
client_id, clientId = client_id,
client_secret, clientSecret = client_secret,
refresh_token, refreshToken = refresh_token,
access_token, accessToken = access_token,
username,
password
} = {}) {
if (!userAgent && !isBrowser) {
return requiredArg('userAgent');
}
if ((!accessToken || typeof accessToken !== 'string') &&
(clientId === undefined || clientSecret === undefined || typeof refreshToken !== 'string') &&
(clientId === undefined || clientSecret === undefined || username === undefined || password === undefined)
) {
throw new errors.NoCredentialsError();
}
if (isBrowser) {
this.userAgent = global.navigator.userAgent;
}
defaults(this, {userAgent, clientId, clientSecret, refreshToken, accessToken, username, password}, {
clientId: null,
clientSecret: null,
refreshToken: null,
accessToken: null,
username: null,
password: null,
ratelimitRemaining: null,
ratelimitExpiration: null,
tokenExpiration: null,
scope: null,
_config: createConfig(),
_nextRequestTimestamp: -Infinity
});
addSnakeCaseShadowProps(this);
}
/**
* @summary Gets an authorization URL, which allows a user to authorize access to their account
* @desc This create a URL where a user can authorize an app to act through their account. If the user visits the returned URL
in a web browser, they will see a page that looks like [this](https://i.gyazo.com/0325534f38b78c1dbd4c84d690dda6c2.png). If
the user clicks "Allow", they will be redirected to your `redirectUri`, with a `code` querystring parameter containing an
* *authorization code*. If this code is passed to {@link snoowrap.fromAuthCode}, you can create a requester to make
requests on behalf of the user.
*
* The main use-case here is for running snoowrap in a browser. You can generate a URL, send the user there, and then continue
after the user authenticates on reddit and is redirected back.
*
* @param {object} options
* @param {string} options.clientId The client ID of your app (assigned by reddit). If your code is running clientside in a
browser, using an "Installed" app type is recommended.
* @param {string[]} options.scope An array of scopes (permissions on the user's account) to request on the authentication
page. A list of possible scopes can be found [here](https://www.reddit.com/api/v1/scopes). You can also get them on-the-fly
with {@link snoowrap#getOauthScopeList}.
* @param {string} options.redirectUri The URL where the user should be redirected after authenticating. This **must** be the
same as the redirect URI that is configured for the reddit app. (If there is a mismatch, the returned URL will display an
error page instead of an authentication form.)
* @param {boolean} [options.permanent=true] If `true`, the app will have indefinite access to the user's account. If `false`,
access to the user's account will expire after 1 hour.
* @param {string} [options.state] A string that can be used to verify a user after they are redirected back to the site. When
the user is redirected from reddit, to the redirect URI after authenticating, the resulting URI will have this same `state`
value in the querystring. (See [here](http://www.twobotechnologies.com/blog/2014/02/importance-of-state-in-oauth2.html) for
more information on how to use the `state` value.)
* @param {string} [options.endpointDomain='reddit.com'] The endpoint domain for the URL. If the user is authenticating on
reddit.com (as opposed to some other site with a reddit-like API), you can omit this value.
* @returns {string} A URL where the user can authenticate with the given options
* @example
*
* var authenticationUrl = snoowrap.getAuthUrl({
* clientId: 'foobarbazquuux',
* scope: ['identity', 'wikiread', 'wikiedit'],
* redirectUri: 'https://example.com/reddit_callback',
* permanent: false,
* state: 'fe211bebc52eb3da9bef8db6e63104d3' // a random string, this could be validated when the user is redirected back
* });
* // --> 'https://www.reddit.com/api/v1/authorize?client_id=foobarbaz&response_type=code&state= ...'
*
* window.location.href = authenticationUrl; // send the user to the authentication url
*/
static getAuthUrl ({
clientId = requiredArg('clientId'),
scope = requiredArg('scope'),
redirectUri = requiredArg('redirectUri'),
permanent = true,
state = '_',
endpointDomain = 'reddit.com'
}) {
if (!(Array.isArray(scope) && scope.length && scope.every(scopeValue => scopeValue && typeof scopeValue === 'string'))) {
throw new TypeError('Missing `scope` argument; a non-empty list of OAuth scopes must be provided');
}
return `
https://www.${endpointDomain}/api/v1/authorize?
client_id=${encodeURIComponent(clientId)}
&response_type=code
&state=${encodeURIComponent(state)}
&redirect_uri=${encodeURIComponent(redirectUri)}
&duration=${permanent ? 'permanent' : 'temporary'}
&scope=${encodeURIComponent(scope.join(' '))}
`.replace(/\s/g, '');
}
/**
* @summary Creates a snoowrap requester from an authorization code.
* @desc An authorization code is the `code` value that appears in the querystring after a user authenticates with reddit and
is redirected. For more information, see {@link snoowrap.getAuthUrl}.
*
* The main use-case for this function is for running snoowrap in a browser. You can generate a URL with
{@link snoowrap.getAuthUrl} and send the user to that URL, and then use this function to create a requester when
the user is redirected back with an authorization code.
* @param {object} options
* @param {string} options.code The authorization code
* @param {string} options.userAgent A unique description of what your app does. This argument is not necessary when snoowrap
is running in a browser.
* @param {string} options.clientId The client ID of your app (assigned by reddit). If your code is running clientside in a
browser, using an "Installed" app type is recommended.
* @param {string} [options.clientSecret] The client secret of your app. If your app has the "Installed" app type, omit
this parameter.
* @param {string} options.redirectUri The redirect URI that is configured for the reddit app.
* @param {string} [options.endpointDomain='reddit.com'] The endpoint domain that the returned requester should be configured
to use. If the user is authenticating on reddit.com (as opposed to some other site with a reddit-like API), you can omit this
value.
* @returns {Promise<snoowrap>} A Promise that fulfills with a `snoowrap` instance
* @example
*
* // Get the `code` querystring param (assuming the user was redirected from reddit)
* var code = new URL(window.location.href).searchParams.get('code');
*
* snoowrap.fromAuthCode({
* code: code,
* userAgent: 'My app',
* clientId: 'foobarbazquuux',
* redirectUri: 'example.com'
* }).then(r => {
* // Now we have a requester that can access reddit through the user's account
* return r.getHot().then(posts => {
* // do something with posts from the front page
* });
* })
*/
static fromAuthCode ({
code = requiredArg('code'),
userAgent = isBrowser ? global.navigator.userAgent : requiredArg('userAgent'),
clientId = requiredArg('clientId'),
clientSecret,
redirectUri = requiredArg('redirectUri'),
endpointDomain = 'reddit.com'
}) {
return this.prototype.credentialedClientRequest.call({
userAgent,
clientId,
clientSecret,
// Use `this.prototype.rawRequest` function to allow for custom `rawRequest` method usage in subclasses.
rawRequest: this.prototype.rawRequest
}, {
method: 'post',
baseUrl: `https://www.${endpointDomain}/`,
uri: 'api/v1/access_token',
form: {grant_type: 'authorization_code', code, redirect_uri: redirectUri}
}).then(response => {
if (response.error) {
throw new errors.RequestError(`API Error: ${response.error} - ${response.error_description}`);
}
// Use `new this` instead of `new snoowrap` to ensure that subclass instances can be returned
const requester = new this({userAgent, clientId, clientSecret, ...response});
requester.config({endpointDomain});
return requester;
});
}
/**
* @summary Returns the grant types available for app-only authentication
* @desc Per the Reddit API OAuth docs, there are two different grant types depending on whether the app is an installed client
* or a confidential client such as a web app or string. This getter returns the possible values for the "grant_type" field
* in application-only auth.
* @returns {object} The enumeration of possible grant_type values
*/
static get grantType () {
return {
CLIENT_CREDENTIALS: 'client_credentials',
INSTALLED_CLIENT: 'https://oauth.reddit.com/grants/installed_client'
};
}
/**
* @summary Creates a snoowrap requester from a "user-less" Authorization token
* @desc In some cases, 3rd party app clients may wish to make API requests without a user context. App clients can request
* a "user-less" Authorization token via either the standard client_credentials grant, or the reddit specific
* extension to this grant, https://oauth.reddit.com/grants/installed_client. Which grant type an app uses depends on
* the app-type and its use case.
* @param {object} options
* @param {string} options.userAgent A unique description of what your app does. This argument is not necessary when snoowrap
is running in a browser.
* @param {string} options.clientId The client ID of your app (assigned by reddit). If your code is running clientside in a
* browser, using an "Installed" app type is recommended.
* @param {string} [options.clientSecret] The client secret of your app. Only required for "client_credentials" grant type.
* @param {string} [options.deviceId] A unique, per-device ID generated by your client. Only required
* for "Installed" grant type, needs to be between 20-30 characters long. From the reddit docs: "reddit *may* choose to use
* this ID to generate aggregate data about user counts. Clients that wish to remain anonymous should use the value
* DO_NOT_TRACK_THIS_DEVICE."
* @param {string} [options.grantType=snoowrap.grantType.INSTALLED_CLIENT] The type of "user-less"
* token to use {@link snoowrap.grantType}
* @param {boolean} [options.permanent=true] If `true`, the app will have indefinite access. If `false`,
access will expire after 1 hour.
* @param {string} [options.endpointDomain='reddit.com'] The endpoint domain that the returned requester should be configured
to use. If the user is authenticating on reddit.com (as opposed to some other site with a reddit-like API), you can omit this
value.
* @returns {Promise<snoowrap>} A Promise that fulfills with a `snoowrap` instance
* @example
*
* snoowrap.fromApplicationOnlyAuth({
* userAgent: 'My app',
* clientId: 'foobarbazquuux',
* deviceId: 'unique id between 20-30 chars',
* grantType: snoowrap.grantType.INSTALLED_CLIENT
* }).then(r => {
* // Now we have a requester that can access reddit through a "user-less" Auth token
* return r.getHot().then(posts => {
* // do something with posts from the front page
* });
* })
*
* snoowrap.fromApplicationOnlyAuth({
* userAgent: 'My app',
* clientId: 'foobarbazquuux',
* clientSecret: 'your web app secret',
* grantType: snoowrap.grantType.CLIENT_CREDENTIALS
* }).then(r => {
* // Now we have a requester that can access reddit through a "user-less" Auth token
* return r.getHot().then(posts => {
* // do something with posts from the front page
* });
* })
*/
static fromApplicationOnlyAuth ({
userAgent = isBrowser ? global.navigator.userAgent : requiredArg('userAgent'),
clientId = requiredArg('clientId'),
clientSecret,
deviceId,
grantType = snoowrap.grantType.INSTALLED_CLIENT,
permanent = true,
endpointDomain = 'reddit.com'
}) {
return this.prototype.credentialedClientRequest.call({
clientId,
clientSecret,
// Use `this.prototype.rawRequest` function to allow for custom `rawRequest` method usage in subclasses.
rawRequest: this.prototype.rawRequest
}, {
method: 'post',
baseUrl: `https://www.${endpointDomain}/`,
uri: 'api/v1/access_token',
form: {grant_type: grantType, device_id: deviceId, duration: permanent ? 'permanent' : 'temporary'}
}).then(response => {
if (response.error) {
throw new errors.RequestError(`API Error: ${response.error} - ${response.error_description}`);
}
// Use `new this` instead of `new snoowrap` to ensure that subclass instances can be returned
const requester = new this({userAgent, clientId, clientSecret, ...response});
requester.config({endpointDomain});
return requester;
});
}
_newObject (objectType, content, _hasFetched = false) {
return Array.isArray(content) ? content : new snoowrap.objects[objectType](content, this, _hasFetched);
}
/**
* @summary Retrieves or modifies the configuration options for this snoowrap instance.
* @param {object} [options] A map of `{[config property name]: value}`. Note that any omitted config properties will simply
retain whatever value they had previously. (In other words, if you only want to change one property, you only need to put
that one property in this parameter. To get the current configuration without modifying anything, simply omit this
parameter.)
* @param {string} [options.endpointDomain='reddit.com'] The endpoint where requests should be sent
* @param {Number} [options.requestDelay=0] A minimum delay, in milliseconds, to enforce between API calls. If multiple
api calls are requested during this timespan, they will be queued and sent one at a time. Setting this to more than 1000 will
ensure that reddit's ratelimit is never reached, but it will make things run slower than necessary if only a few requests
are being sent. If this is set to zero, snoowrap will not enforce any delay between individual requests. However, it will
still refuse to continue if reddit's enforced ratelimit (600 requests per 10 minutes) is exceeded.
* @param {Number} [options.requestTimeout=30000] A timeout for all OAuth requests, in milliseconds. If the reddit server
fails to return a response within this amount of time, the Promise will be rejected with a timeout error.
* @param {boolean} [options.continueAfterRatelimitError=false] Determines whether snoowrap should queue API calls if
reddit's ratelimit is exceeded. If set to `true` when the ratelimit is exceeded, snoowrap will queue all further requests,
and will attempt to send them again after the current ratelimit period expires (which happens every 10 minutes). If set
to `false`, snoowrap will simply throw an error when reddit's ratelimit is exceeded.
* @param {Number[]} [options.retryErrorCodes=[502, 503, 504, 522]] If reddit responds to an idempotent request with one of
these error codes, snoowrap will retry the request, up to a maximum of `max_retry_attempts` requests in total. (These
errors usually indicate that there was an temporary issue on reddit's end, and retrying the request has a decent chance of
success.) This behavior can be disabled by simply setting this property to an empty array.
* @param {Number} [options.maxRetryAttempts=3] See `retryErrorCodes`.
* @param {boolean} [options.warnings=true] snoowrap may occasionally log warnings, such as deprecation notices, to the
console. These can be disabled by setting this to `false`.
* @param {boolean} [options.debug=false] If set to true, snoowrap will print out potentially-useful information for debugging
purposes as it runs.
* @param {object} [options.logger=console] By default, snoowrap will log any warnings and debug output to the console.
A custom logger object may be supplied via this option; it must expose `warn`, `info`, `debug`, and `trace` functions.
* @param {boolean} [options.proxies=true] Setting this to `false` disables snoowrap's method-chaining feature. This causes
the syntax for using snoowrap to become a bit heavier, but allows for consistency between environments that support the ES6
`Proxy` object and environments that don't. This option is a no-op in environments that don't support the `Proxy` object,
since method chaining is always disabled in those environments. Note, changing this setting must be done before making
any requests.
* @returns {object} An updated Object containing all of the configuration values
* @example
*
* r.config({requestDelay: 1000, warnings: false});
* // sets the request delay to 1000 milliseconds, and suppresses warnings.
*/
config (options = {}) {
const invalidKey = Object.keys(options).find(key => !(key in this._config));
if (invalidKey) {
throw new TypeError(`Invalid config option '${invalidKey}'`);
}
return Object.assign(this._config, options);
}
_warn (...args) {
if (this._config.warnings) {
this._config.logger.warn(...args);
}
}
_debug (...args) {
if (this._config.debug) {
this._config.logger.debug(...args);
}
}
get _promiseWrap () {
return this._config.proxies ? promiseWrap : identity;
}
/**
* @summary Gets information on a reddit user with a given name.
* @param {string} name - The user's username
* @returns {RedditUser} An unfetched RedditUser object for the requested user
* @example
*
* r.getUser('not_an_aardvark')
* // => RedditUser { name: 'not_an_aardvark' }
* r.getUser('not_an_aardvark').link_karma.then(console.log)
* // => 6
*/
getUser (name) {
return this._newObject('RedditUser', {name: (name + '').replace(/^\/?u\//, '')});
}
/**
* @summary Gets information on a comment with a given id.
* @param {string} commentId - The base36 id of the comment
* @returns {Comment} An unfetched Comment object for the requested comment
* @example
*
* r.getComment('c0b6xx0')
* // => Comment { name: 't1_c0b6xx0' }
* r.getComment('c0b6xx0').author.name.then(console.log)
* // => 'Kharos'
*/
getComment (commentId) {
return this._newObject('Comment', {name: addFullnamePrefix(commentId, 't1_')});
}
/**
* @summary Gets information on a given subreddit.
* @param {string} displayName - The name of the subreddit (e.g. 'AskReddit')
* @returns {Subreddit} An unfetched Subreddit object for the requested subreddit
* @example
*
* r.getSubreddit('AskReddit')
* // => Subreddit { display_name: 'AskReddit' }
* r.getSubreddit('AskReddit').created_utc.then(console.log)
* // => 1201233135
*/
getSubreddit (displayName) {
return this._newObject('Subreddit', {display_name: displayName.replace(/^\/?r\//, '')});
}
/**
* @summary Gets information on a given submission.
* @param {string} submissionId - The base36 id of the submission
* @returns {Submission} An unfetched Submission object for the requested submission
* @example
*
* r.getSubmission('2np694')
* // => Submission { name: 't3_2np694' }
* r.getSubmission('2np694').title.then(console.log)
* // => 'What tasty food would be distusting if eaten over rice?'
*/
getSubmission (submissionId) {
return this._newObject('Submission', {name: addFullnamePrefix(submissionId, 't3_')});
}
/**
* @summary Gets a private message by ID.
* @param {string} messageId The base36 ID of the message
* @returns {PrivateMessage} An unfetched PrivateMessage object for the requested message
* @example
*
* r.getMessage('51shnw')
* // => PrivateMessage { name: 't4_51shnw' }
* r.getMessage('51shnw').subject.then(console.log)
* // => 'Example'
* // See here for a screenshot of the PM in question https://i.gyazo.com/24f3b97e55b6ff8e3a74cb026a58b167.png
*/
getMessage (messageId) {
return this._newObject('PrivateMessage', {name: addFullnamePrefix(messageId, 't4_')});
}
/**
* Gets a livethread by ID.
* @param {string} threadId The base36 ID of the livethread
* @returns {LiveThread} An unfetched LiveThread object
* @example
*
* r.getLivethread('whrdxo8dg9n0')
* // => LiveThread { id: 'whrdxo8dg9n0' }
* r.getLivethread('whrdxo8dg9n0').nsfw.then(console.log)
* // => false
*/
getLivethread (threadId) {
return this._newObject('LiveThread', {id: addFullnamePrefix(threadId, 'LiveUpdateEvent_').slice(16)});
}
/**
* @summary Gets information on the requester's own user profile.
* @returns {RedditUser} A RedditUser object corresponding to the requester's profile
* @example
*
* r.getMe().then(console.log);
* // => RedditUser { is_employee: false, has_mail: false, name: 'snoowrap_testing', ... }
*/
getMe () {
return this._get({uri: 'api/v1/me'}).then(result => {
this._ownUserInfo = this._newObject('RedditUser', result, true);
return this._ownUserInfo;
});
}
_getMyName () {
return Promise.resolve(this._ownUserInfo ? this._ownUserInfo.name : this.getMe().get('name'));
}
/**
* @summary Gets a distribution of the requester's own karma distribution by subreddit.
* @returns {Promise} A Promise for an object with karma information
* @example
*
* r.getKarma().then(console.log)
* // => [
* // { sr: Subreddit { display_name: 'redditdev' }, comment_karma: 16, link_karma: 1 },
* // { sr: Subreddit { display_name: 'programming' }, comment_karma: 2, link_karma: 1 },
* // ...
* // ]
*/
getKarma () {
return this._get({uri: 'api/v1/me/karma'});
}
/**
* @summary Gets information on the user's current preferences.
* @returns {Promise} A promise for an object containing the user's current preferences
* @example
*
* r.getPreferences().then(console.log)
* // => { default_theme_sr: null, threaded_messages: true, hide_downs: false, ... }
*/
getPreferences () {
return this._get({uri: 'api/v1/me/prefs'});
}
/**
* @summary Updates the user's current preferences.
* @param {object} updatedPreferences An object of the form {[some preference name]: 'some value', ...}. Any preference
* not included in this object will simply retain its current value.
* @returns {Promise} A Promise that fulfills when the request is complete
* @example
*
* r.updatePreferences({threaded_messages: false, hide_downs: true})
* // => { default_theme_sr: null, threaded_messages: false,hide_downs: true, ... }
* // (preferences updated on reddit)
*/
updatePreferences (updatedPreferences) {
return this._patch({uri: 'api/v1/me/prefs', body: updatedPreferences});
}
/**
* @summary Gets the currently-authenticated user's trophies.
* @returns {Promise} A TrophyList containing the user's trophies
* @example
*
* r.getMyTrophies().then(console.log)
* // => TrophyList { trophies: [
* // Trophy { icon_70: 'https://s3.amazonaws.com/redditstatic/award/verified_email-70.png',
* // description: null,
* // url: null,
* // icon_40: 'https://s3.amazonaws.com/redditstatic/award/verified_email-40.png',
* // award_id: 'o',
* // id: '16fn29',
* // name: 'Verified Email'
* // }
* // ] }
*/
getMyTrophies () {
return this._get({uri: 'api/v1/me/trophies'});
}
/**
* @summary Gets the list of the currently-authenticated user's friends.
* @returns {Promise} A Promise that resolves with a list of friends
* @example
*
* r.getFriends().then(console.log)
* // => [ [ RedditUser { date: 1457927963, name: 'not_an_aardvark', id: 't2_k83md' } ], [] ]
*/
getFriends () {
return this._get({uri: 'prefs/friends'});
}
/**
* @summary Gets the list of people that the currently-authenticated user has blocked.
* @returns {Promise} A Promise that resolves with a list of blocked users
* @example
*
* r.getBlockedUsers().then(console.log)
* // => [ RedditUser { date: 1457928120, name: 'actually_an_aardvark', id: 't2_q3519' } ]
*/
getBlockedUsers () {
return this._get({uri: 'prefs/blocked'});
}
/**
* @summary Determines whether the currently-authenticated user needs to fill out a captcha in order to submit content.
* @returns {Promise} A Promise that resolves with a boolean value
* @example
*
* r.checkCaptchaRequirement().then(console.log)
* // => false
*/
checkCaptchaRequirement () {
return this._get({uri: 'api/needs_captcha'});
}
/**
* @summary Gets the identifier (a hex string) for a new captcha image.
* @returns {Promise} A Promise that resolves with a string
* @example
*
* r.getNewCaptchaIdentifier().then(console.log)
* // => 'o5M18uy4mk0IW4hs0fu2GNPdXb1Dxe9d'
*/
getNewCaptchaIdentifier () {
return this._post({uri: 'api/new_captcha', form: {api_type}}).then(res => res.json.data.iden);
}
/**
* @summary Gets an image for a given captcha identifier.
* @param {string} identifier The captcha identifier.
* @returns {Promise} A string containing raw image data in PNG format
* @example
*
* r.getCaptchaImage('o5M18uy4mk0IW4hs0fu2GNPdXb1Dxe9d').then(console.log)
// => (A long, incoherent string representing the image in PNG format)
*/
getCaptchaImage (identifier) {
return this._get({uri: `captcha/${identifier}`});
}
/**
* @summary Gets an array of categories that items can be saved in. (Requires reddit gold)
* @returns {Promise} An array of categories
* @example
*
* r.getSavedCategories().then(console.log)
* // => [ { category: 'cute cat pictures' }, { category: 'interesting articles' } ]
*/
getSavedCategories () {
return this._get({uri: 'api/saved_categories'}).get('categories');
}
/**
* @summary Marks a list of submissions as 'visited'.
* @desc **Note**: This endpoint only works if the authenticated user is subscribed to reddit gold.
* @param {Submission[]} links A list of Submission objects to mark
* @returns {Promise} A Promise that fulfills when the request is complete
* @example
*
* var submissions = [r.getSubmission('4a9u54'), r.getSubmission('4a95nb')]
* r.markAsVisited(submissions)
* // (the links will now appear purple on reddit)
*/
markAsVisited (links) {
return this._post({uri: 'api/store_visits', links: map(links, 'name').join(',')});
}
_submit ({
captcha_response, captchaResponse = captcha_response,
captcha_iden, captchaIden = captcha_iden,
kind,
resubmit = true,
send_replies = true, sendReplies = send_replies,
crosspost_fullname,
text,
title,
url,
subreddit_name, subredditName = subreddit_name,
nsfw,
spoiler,
flairId,
flairText,
...options
}) {
return this._post({
uri: 'api/submit', form: {
api_type, captcha: captchaResponse, iden: captchaIden, sendreplies: sendReplies, sr: subredditName, kind, resubmit,
crosspost_fullname, text, title, url, spoiler, nsfw, flair_id: flairId, flair_text: flairText, ...options
}
}).tap(handleJsonErrors(this)).then(result => this.getSubmission(result.json.data.id));
}
/**
* @summary Creates a new selfpost on the given subreddit.
* @param {object} options An object containing details about the submission
* @param {string} options.subredditName The name of the subreddit that the post should be submitted to
* @param {string} options.title The title of the submission
* @param {string} [options.text] The selftext of the submission
* @param {boolean} [options.sendReplies=true] Determines whether inbox replies should be enabled for this submission
* @param {string} [options.captchaIden] A captcha identifier. This is only necessary if the authenticated account
requires a captcha to submit posts and comments.
* @param {string} [options.captchaResponse] The response to the captcha with the given identifier
* @returns {Promise} The newly-created Submission object
* @example
*
* r.submitSelfpost({
* subredditName: 'snoowrap_testing',
* title: 'This is a selfpost',
* text: 'This is the text body of the selfpost'
* }).then(console.log)
* // => Submission { name: 't3_4abmsz' }
* // (new selfpost created on reddit)
*/
submitSelfpost (options) {
return this._submit({...options, kind: 'self'});
}
/**
* @summary Creates a new link submission on the given subreddit.
* @param {object} options An object containing details about the submission
* @param {string} options.subredditName The name of the subreddit that the post should be submitted to
* @param {string} options.title The title of the submission
* @param {string} options.url The url that the link submission should point to
* @param {boolean} [options.sendReplies=true] Determines whether inbox replies should be enabled for this submission
* @param {boolean} [options.resubmit=true] If this is false and same link has already been submitted to this subreddit in
the past, reddit will return an error. This could be used to avoid accidental reposts.
* @param {string} [options.captchaIden] A captcha identifier. This is only necessary if the authenticated account
requires a captcha to submit posts and comments.
* @param {string} [options.captchaResponse] The response to the captcha with the given identifier
* @returns {Promise} The newly-created Submission object
* @example
*
* r.submitLink({
* subredditName: 'snoowrap_testing',
* title: 'I found a cool website!',
* url: 'https://google.com'
* }).then(console.log)
* // => Submission { name: 't3_4abnfe' }
* // (new linkpost created on reddit)
*/
submitLink (options) {
return this._submit({...options, kind: 'link'});
}
/**
* @summary Creates a new crosspost submission on the given subreddit
* @desc **NOTE**: To create a crosspost, the authenticated account must be subscribed to the subreddit where
* the crosspost is being submitted, and that subreddit be configured to allow crossposts.
* @param {object} options An object containing details about the submission
* @param {string} options.subredditName The name of the subreddit that the crosspost should be submitted to
* @param {string} options.title The title of the crosspost
* @param {(string|Submission)} options.originalPost A Submission object or a post ID for the original post which
is being crossposted
* @param {boolean} [options.sendReplies=true] Determines whether inbox replies should be enabled for this submission
* @param {boolean} [options.resubmit=true] If this is false and same link has already been submitted to this subreddit in
the past, reddit will return an error. This could be used to avoid accidental reposts.
* @returns {Promise} The newly-created Submission object
* @example
*
* await r.submitCrosspost({ title: 'I found an interesting post', originalPost: '6vths0', subredditName: 'snoowrap' })
*/
submitCrosspost (options) {
return this._submit({
...options,
kind: 'crosspost',
crosspost_fullname: options.originalPost instanceof snoowrap.objects.Submission
? options.originalPost.name
: addFullnamePrefix(options.originalPost, 't3_')
});
}
_getSortedFrontpage (sortType, subredditName, options = {}) {
// Handle things properly if only a time parameter is provided but not the subreddit name
let opts = options;
let subName = subredditName;
if (typeof subredditName === 'object' && isEmpty(omitBy(opts, option => option === undefined))) {
/* In this case, "subredditName" ends up referring to the second argument, which is not actually a name since the user
decided to omit that parameter. */
opts = subredditName;
subName = undefined;
}
const parsedOptions = omit({...opts, t: opts.time || opts.t}, 'time');
return this._getListing({uri: (subName ? `r/${subName}/` : '') + sortType, qs: parsedOptions});
}
/**
* @summary Gets a Listing of hot posts.
* @param {string} [subredditName] The subreddit to get posts from. If not provided, posts are fetched from
the front page of reddit.
* @param {object} [options={}] Options for the resulting Listing
* @returns {Promise} A Listing containing the retrieved submissions
* @example
*
* r.getHot().then(console.log)
* // => Listing [
* // Submission { domain: 'imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'pics' }, ... },
* // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'funny' }, ... },
* // ...
* // ]
*
* r.getHot('gifs').then(console.log)
* // => Listing [
* // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'gifs' }, ... },
* // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'gifs' }, ... },
* // ...
* // ]
*
* r.getHot('redditdev', {limit: 1}).then(console.log)
* // => Listing [
// Submission { domain: 'self.redditdev', banned_by: null, subreddit: Subreddit { display_name: 'redditdev' }, ...}
* // ]
*/
getHot (subredditName, options) {
return this._getSortedFrontpage('hot', subredditName, options);
}
/**
* @summary Gets a Listing of best posts.
* @param {object} [options={}] Options for the resulting Listing
* @returns {Promise<Listing>} A Listing containing the retrieved submissions
* @example
*
* r.getBest().then(console.log)
* // => Listing [
* // Submission { domain: 'imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'pics' }, ... },
* // Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'funny' }, ... },
* // ...
* // ]
*
* r.getBest({limit: 1}).then(console.log)
* // => Listing [
// Submission { domain: 'self.redditdev', banned_by: null, subreddit: Subreddit { display_name: 'redditdev' }, ...}
* // ]
*/
getBest (options) {
return this._getSortedFrontpage('best', undefined, options);
}
/**
* @summary Gets a Listing of new posts.
* @param {string} [subredditName] The subreddit to get posts from. If not provided, posts are fetched from
the front page of reddit.
* @param {object} [options={}] Options for the resulting Listing
* @returns {Promise} A Listing containing the retrieved submissions
* @example
*
* r.getNew().then(console.log)
* // => Listing [
* // Submission { domain: 'self.Jokes', banned_by: null, subreddit: Subreddit { display_name: 'Jokes' }, ... },
* // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... },
* // ...
* // ]
*
*/
getNew (subredditName, options) {
return this._getSortedFrontpage('new', subredditName, options);
}
/**
* @summary Gets a Listing of new comments.
* @param {string} [subredditName] The subreddit to get comments from. If not provided, posts are fetched from
the front page of reddit.
* @param {object} [options={}] Options for the resulting Listing
* @returns {Promise} A Listing containing the retrieved comments
* @example
*
* r.getNewComments().then(console.log)
* // => Listing [
* // Comment { link_title: 'What amazing book should be made into a movie, but hasn\'t been yet?', ... }
* // Comment { link_title: 'How far back in time could you go and still understand English?', ... }
* // ]
*/
getNewComments (subredditName, options) {
return this._getSortedFrontpage('comments', subredditName, options);
}
/**
* @summary Get list of content by IDs. Returns a listing of the requested content.
* @param {Array<string|Submission|Comment>} ids An array of content IDs. Can include the id itself, or a Submission or Comment object.
can get a post and a comment * @returns {Promise<Listing<Submission|Comment>>} A listing of content requested, can be any class fetchable by API. e.g. Comment, Submission
* @example
*
* r.getContentByIds(['t3_9l9vof','t3_9la341']).then(console.log);
* // => Listing [
* // Submission { approved_at_utc: null, ... }
* // Submission { approved_at_utc: null, ... }
* // ]
*
* r.getContentByIds([r.getSubmission('9l9vof'), r.getSubmission('9la341')]).then(console.log);
* // => Listing [
* // Submission { approved_at_utc: null, ... }
* // Submission { approved_at_utc: null, ... }
* // ]
*/
getContentByIds (ids) {
if (!Array.isArray(ids)) {
throw new TypeError('Invalid argument: Argument needs to be an array.');
}
const prefixedIds = ids.map(id => {
if (id instanceof snoowrap.objects.Submission || id instanceof snoowrap.objects.Comment) {
return id.name;
} else if (typeof id === 'string') {
if (!/t(1|3)_/g.test(ids)) {
throw new TypeError('Invalid argument: Ids need to include Submission or Comment prefix, e.g. t1_, t3_.');
}
return id;
}
throw new TypeError('Id must be either a string, Submission, or Comment.');
});
return this._get({uri: '/api/info', method: 'get', qs: {id: prefixedIds.join(',')}});
}
/**
* @summary Gets a single random Submission.
* @desc **Note**: This function will not work when snoowrap is running in a browser, because the reddit server sends a
redirect which cannot be followed by a CORS request.
* @param {string} [subredditName] The subreddit to get the random submission. If not provided, the post is fetched from
the front page of reddit.
* @returns {Promise} The retrieved Submission object
* @example
*
* r.getRandomSubmission('aww').then(console.log)
* // => Submission { domain: 'i.imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'aww' }, ... }
*/
getRandomSubmission (subredditName) {
return this._get({uri: `${subredditName ? `r/${subredditName}/` : ''}random`});
}
/**
* @summary Gets a Listing of top posts.
* @param {string} [subredditName] The subreddit to get posts from. If not provided, posts are fetched from
the front page of reddit.
* @param {object} [options={}] Options for the resulting Listing
* @param {string} [options.time] Describes the timespan that posts should be retrieved from. Should be one of
`hour, day, week, month, year, all`
* @returns {Promise} A Listing containing the retrieved submissions
* @example
*
* r.getTop({time: 'all', limit: 2}).then(console.log)
* // => Listing [
* // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... },
* // Submission { domain: 'imgur.com', banned_by: null, subreddit: Subreddit { display_name: 'funny' }, ... }
* // ]
*
* r.getTop('AskReddit').then(console.log)
* // => Listing [
* // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... },
* // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... },
* // Submission { domain: 'self.AskReddit', banned_by: null, subreddit: Subreddit { display_name: 'AskReddit' }, ... },
* // ...
* // ]
*/
getTop (subredditName, options) {
return this._getSortedFrontpage('top', subredditName, options);
}
/**
* @summary Gets a Listing of controversial posts.
* @param {string} [subredditName] The subreddit to get posts from. If not provided, posts are fetched from
the front page of reddit.
* @param {object} [options={}] Options for the resulting Listing
* @param {string} [options.time] Describes the timespan that posts should be retrieved from. Should be one of
`hour, day, week, month, year, all`
* @returns {Promise} A Listing containing the retrieved submissions
* @example
*
* r.getControversial('technology').then(console.log)
* // => Listing [
* // Submission { domain: 'thenextweb.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... },
* // Submission { domain: 'pcmag.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... }
* // ]
*/
getControversial (subredditName, options) {
return this._getSortedFrontpage('controversial', subredditName, options);
}
/**
* @summary Gets a Listing of controversial posts.
* @param {string} [subredditName] The subreddit to get posts from. If not provided, posts are fetched from
the front page of reddit.
* @param {object} [options] Options for the resulting Listing
* @returns {Promise} A Listing containing the retrieved submissions
* @example
*
* r.getRising('technology').then(console.log)
* // => Listing [
* // Submission { domain: 'thenextweb.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... },
* // Submission { domain: 'pcmag.com', banned_by: null, subreddit: Subreddit { display_name: 'technology' }, ... }
* // ]
*/
getRising (subredditName, options) {
return this._getSortedFrontpage('rising', subredditName, options);
}
/**
* @summary Gets the authenticated user's unread messages.
* @param {object} [options={}] Options for the resulting Listing
* @returns {Promise} A Listing containing unread items in the user's inbox
* @example
*
* r.getUnreadMessages().then(console.log)
* // => Listing [
* // PrivateMessage { body: 'hi!', was_comment: false, first_message: null, ... },