mattbdean / JRAW

The Java Reddit API Wrapper
https://mattbdean.gitbooks.io/jraw
MIT License
356 stars 125 forks source link

Script application expiry #276

Open andehr opened 6 years ago

andehr commented 6 years ago

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!

Fischer96 commented 5 years ago

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

andehr commented 5 years ago

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()

Fischer96 commented 5 years ago

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?

andehr commented 5 years ago

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);
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.

Fischer96 commented 5 years ago

Will check it out, thank you!

Mikusch commented 4 years ago

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