From 1cb5fe33be14f79aab48fac136bb45bfb05de98f Mon Sep 17 00:00:00 2001 From: adb Date: Sun, 31 Jan 2021 13:24:27 +0100 Subject: [PATCH] refresh api token if necessary --- .../java/sh/adb/RandomRedditMemesAPI/RedditAPI.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/sh/adb/RandomRedditMemesAPI/RedditAPI.java b/src/main/java/sh/adb/RandomRedditMemesAPI/RedditAPI.java index c81d135..11f38c4 100644 --- a/src/main/java/sh/adb/RandomRedditMemesAPI/RedditAPI.java +++ b/src/main/java/sh/adb/RandomRedditMemesAPI/RedditAPI.java @@ -39,7 +39,10 @@ public class RedditAPI { client = new RedditHttpClient(userAgent, HttpClientBuilder.create().build()); // Create token (will be valid for 1 hour) - token = agent.tokenAppOnly(false); + newToken(); + } + public void newToken() throws RedditOAuthException { + this.token = this.agent.tokenAppOnly(false); System.out.println("Access Token: " + token.getAccessToken()); System.out.println("Token Type: " + token.getTokenType()); System.out.println("Refreshable: " + token.isRefreshable()); @@ -48,10 +51,8 @@ public class RedditAPI { System.out.println("Will expire in 61 minutes: " + token.willExpireIn((long) 3660)); System.out.println("Will expire in 59 minutes: " + token.willExpireIn((long) 3540)); } - public void newToken() throws RedditOAuthException { - this.token = this.agent.tokenAppOnly(false); - } - public List getSub(String subreddit) throws RedditParseException { + public List getSub(String subreddit) throws RedditParseException, RedditOAuthException { + if (token.willExpireIn((long) 120)) newToken(); SubmissionsListingParser parser = new SubmissionsListingParser(); SubmissionsOfSubredditRequest request = (SubmissionsOfSubredditRequest) new SubmissionsOfSubredditRequest(subreddit, SubmissionSort.HOT).setLimit(100); List submissions = parser.parse(client.get(token, request));