mattbdean/JRAW

Script application expiry

Opened this issue · 6 comments

Hi,

Am I right in saying that according to https://mattbdean.gitbooks.io/jraw/oauth2.html, a reddit script should have its access token automatically renewed when it expires?

Because after initialising the RedditClient as below using my script app, and using client.submission(submissionID).comments(); for 1 hour, I get a 401 code.

Credentials credentials = Credentials.script(apiKey.username, apiKey.password, apiKey.clientID, apiKey.clientSecret);
NetworkAdapter adapter = new OkHttpNetworkAdapter(getUserAgent());
RedditClient reddit = OAuthHelper.automatic(adapter, credentials);
reddit.setAutoRenew(true);

Should I just re-call client.submission(submissionID).comments();, or is this a sign of a problem?

Thanks for any help!

Have the exact same problem. After one hour the auth dies and it does not renew. Manually renewing doesn't work either sadly

The work around I mention above was the only way I could get it to work. Just amounts to catching the 401s and re-calling client.submission(submissionID).comments()

So you just do all of this

Credentials credentials = Credentials.script(apiKey.username, apiKey.password, apiKey.clientID, apiKey.clientSecret);
NetworkAdapter adapter = new OkHttpNetworkAdapter(getUserAgent());
RedditClient reddit = OAuthHelper.automatic(adapter, credentials);
reddit.setAutoRenew(true);

And then you call your function again?

Yeah, you only need to do those 4 lines once:

Credentials credentials = Credentials.script(apiKey.username, apiKey.password, apiKey.clientID, apiKey.clientSecret);
NetworkAdapter adapter = new OkHttpNetworkAdapter(getUserAgent());
RedditClient reddit = OAuthHelper.automatic(adapter, credentials);
reddit.setAutoRenew(true);

Then you use the client object (here reddit) to, say, collect all comments:

RootCommentNode rootNode = reddit.submission(submissionID).comments();
rootNode.loadFully(reddit);
  • Wrap those 2 calls in a try-catch statement.
  • Catch ApiException.
  • Check whether it is caused by a 401, and re-call the comment endpoint:
int httpCode = ((NetworkException) exception.getCause()).getRes().getCode();
if (httpCode == 401) {
    RootCommentNode rootNode = reddit.submission(submissionID).comments();
    rootNode.loadFully(reddit);
}

I don't know if it's necessary, but I tend to add a Thread.sleep(1000) before re-trying, because I treat all APIs like temperamental babies :)

So you just gotta wrap that up nicely, so that whenever you call your "get comments" function it knows to retry as much as it needs.

Will check it out, thank you!

This is still an issue, and even catching 401's then re-trying will not work anymore after a while.