From e0c0f24b00449272f8a5faf167a30d3f11306172 Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Sat, 30 Nov 2024 13:49:46 -0700 Subject: [PATCH 1/7] Refactor to make request type an argument for CacheRequest --- .../activities/ImageViewActivity.java | 2 + .../activities/ImgurUploadActivity.java | 1 + .../activities/InboxListingActivity.java | 1 + .../redreader/cache/CacheDownload.java | 1 + .../redreader/cache/CacheRequest.java | 14 ++++ .../redreader/common/FileUtils.java | 2 + .../redreader/compose/net/NetWrapper.kt | 1 + .../fragments/PostListingFragment.java | 3 + .../redreader/fragments/UserProfileDialog.kt | 1 + .../redreader/http/HTTPBackend.kt | 7 +- .../redreader/http/okhttp/OKHTTPBackend.kt | 67 ++++++++++--------- .../redreader/image/DeviantArtAPI.java | 1 + .../redreader/image/GfycatAPI.java | 1 + .../redreader/image/ImgurAPI.java | 2 + .../redreader/image/ImgurAPIV3.java | 2 + .../redreader/image/RedditGalleryAPI.kt | 1 + .../redreader/image/RedditVideosAPI.kt | 1 + .../redreader/image/RedgifsAPI.java | 1 + .../redreader/image/RedgifsAPIV2.java | 2 + .../redreader/image/StreamableAPI.java | 1 + .../receivers/NewMessageChecker.java | 1 + .../announcements/AnnouncementDownloader.java | 1 + .../reddit/CommentListingRequest.java | 1 + .../redreader/reddit/RedditAPI.java | 2 + ...itAPIIndividualSubredditDataRequester.java | 1 + ...itAPIIndividualSubredditListRequester.java | 1 + .../RedditAPIMultiredditListRequester.java | 1 + .../redreader/reddit/api/RedditOAuth.kt | 8 ++- .../reddit/prepared/RedditPreparedPost.java | 1 + .../prepared/html/HtmlRawElementImg.java | 1 + .../redreader/views/RedditPostView.java | 1 + 31 files changed, 97 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java b/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java index 69085d8a3..7c05b14c4 100644 --- a/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java +++ b/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java @@ -889,6 +889,7 @@ private void makeCacheRequest( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, this, new CacheRequestCallbacks() { @@ -979,6 +980,7 @@ public void onDataStreamAvailable( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, this, new CacheRequestCallbacks() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java b/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java index 5fb7224fe..c4e04201d 100644 --- a/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java +++ b/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java @@ -285,6 +285,7 @@ private void uploadImage() { DownloadStrategyAlways.INSTANCE, Constants.FileType.NOCACHE, CacheRequest.DownloadQueueType.IMGUR_API, + CacheRequest.RequestMethod.POST, new HTTPRequestBody.Multipart() .addPart(new Part.FormDataBinary("image", mImageData)), this, diff --git a/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java b/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java index 06a1ed38a..7b7cbf315 100644 --- a/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java +++ b/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java @@ -262,6 +262,7 @@ private void makeFirstRequest(final Context context) { DownloadStrategyAlways.INSTANCE, Constants.FileType.INBOX_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, false, context, new CacheRequestCallbacks() { diff --git a/src/main/java/org/quantumbadger/redreader/cache/CacheDownload.java b/src/main/java/org/quantumbadger/redreader/cache/CacheDownload.java index 8660bcba3..0507192df 100644 --- a/src/main/java/org/quantumbadger/redreader/cache/CacheDownload.java +++ b/src/main/java/org/quantumbadger/redreader/cache/CacheDownload.java @@ -75,6 +75,7 @@ public CacheDownload( initiator.context, new HTTPBackend.RequestDetails( mInitiator.url, + mInitiator.requestMethod, mInitiator.requestBody.asNullable())); } diff --git a/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java b/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java index a5a66e41a..d3fe3bef4 100644 --- a/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java +++ b/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java @@ -64,6 +64,11 @@ public enum RequestFailureType { CACHE_DIR_DOES_NOT_EXIST } + public enum RequestMethod { + GET, + POST + } + public final UriString url; public final RedditAccount user; public final UUID requestSession; @@ -75,6 +80,7 @@ public enum RequestFailureType { public final int fileType; public final DownloadQueueType queueType; + public final RequestMethod requestMethod; @NonNull public final Optional requestBody; public final boolean cache; @@ -114,6 +120,7 @@ public CacheRequest( @NonNull final DownloadStrategy downloadStrategy, final int fileType, final DownloadQueueType queueType, + final RequestMethod requestMethod, final boolean cache, @NonNull final Context context, @NonNull final CacheRequestCallbacks callbacks) { @@ -126,6 +133,7 @@ public CacheRequest( downloadStrategy, fileType, queueType, + requestMethod, null, cache, context, @@ -140,6 +148,7 @@ public CacheRequest( @NonNull final DownloadStrategy downloadStrategy, final int fileType, final DownloadQueueType queueType, + final RequestMethod requestMethod, @NonNull final Context context, @NonNull final CacheRequestCallbacks callbacks) { @@ -151,6 +160,7 @@ public CacheRequest( downloadStrategy, fileType, queueType, + requestMethod, true, context, callbacks); @@ -164,6 +174,7 @@ public CacheRequest( @NonNull final DownloadStrategy downloadStrategy, final int fileType, final DownloadQueueType queueType, + final RequestMethod requestMethod, @Nullable final HTTPRequestBody requestBody, @NonNull final Context context, @NonNull final CacheRequestCallbacks callbacks) { @@ -176,6 +187,7 @@ public CacheRequest( downloadStrategy, fileType, queueType, + requestMethod, requestBody, false, context, @@ -191,6 +203,7 @@ private CacheRequest( @NonNull final DownloadStrategy downloadStrategy, final int fileType, final DownloadQueueType queueType, + final RequestMethod requestMethod, @Nullable final HTTPRequestBody requestBody, final boolean cache, @NonNull final Context context, @@ -216,6 +229,7 @@ private CacheRequest( this.downloadStrategy = downloadStrategy; this.fileType = fileType; this.queueType = queueType; + this.requestMethod = requestMethod; this.requestBody = Optional.ofNullable(requestBody); this.cache = (requestBody == null) && cache; diff --git a/src/main/java/org/quantumbadger/redreader/common/FileUtils.java b/src/main/java/org/quantumbadger/redreader/common/FileUtils.java index 7e3b69878..58207b6e4 100644 --- a/src/main/java/org/quantumbadger/redreader/common/FileUtils.java +++ b/src/main/java/org/quantumbadger/redreader/common/FileUtils.java @@ -487,6 +487,7 @@ private static void internalDownloadImageToSaveAudio( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, activity, new CacheRequestCallbacks() { @@ -604,6 +605,7 @@ public void onSuccess(final ImageInfo info) { DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, activity, new CacheRequestCallbacks() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt b/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt index 123c8bd49..3363d98e3 100644 --- a/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt +++ b/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt @@ -315,6 +315,7 @@ private fun fetchFile( downloadStrategy, fileType, queueType, + CacheRequest.RequestMethod.GET, cache, context, object : CacheRequestCallbacks { diff --git a/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java b/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java index 573aebabd..0fa4423b0 100644 --- a/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java +++ b/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java @@ -665,6 +665,7 @@ private CacheRequest createPostListingRequest( downloadStrategy, Constants.FileType.POST_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, activity, new CacheRequestCallbacks() { @Override @@ -1018,6 +1019,7 @@ private void precacheComments( TimestampBound.notOlderThan(TimeDuration.minutes(15))), Constants.FileType.COMMENT_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, // Don't parse the JSON activity, new CacheRequestCallbacks() { @@ -1133,6 +1135,7 @@ private void precacheImage( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DownloadQueueType.IMAGE_PRECACHE, + CacheRequest.RequestMethod.GET, activity, new CacheRequestCallbacks() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt b/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt index d27a74fb8..e3d57914d 100644 --- a/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt +++ b/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt @@ -437,6 +437,7 @@ object UserProfileDialog { DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.INLINE_IMAGE_PREVIEW, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, object : CacheRequestCallbacks { override fun onDataStreamComplete( diff --git a/src/main/java/org/quantumbadger/redreader/http/HTTPBackend.kt b/src/main/java/org/quantumbadger/redreader/http/HTTPBackend.kt index bbad86973..42a1c765a 100644 --- a/src/main/java/org/quantumbadger/redreader/http/HTTPBackend.kt +++ b/src/main/java/org/quantumbadger/redreader/http/HTTPBackend.kt @@ -18,6 +18,7 @@ package org.quantumbadger.redreader.http import android.content.Context +import org.quantumbadger.redreader.cache.CacheRequest.RequestMethod import org.quantumbadger.redreader.cache.CacheRequest.RequestFailureType import org.quantumbadger.redreader.common.Result import org.quantumbadger.redreader.common.UriString @@ -26,9 +27,11 @@ import org.quantumbadger.redreader.http.okhttp.OKHTTPBackend import java.io.InputStream abstract class HTTPBackend { + data class RequestDetails( - val url: UriString, - val requestBody: HTTPRequestBody? + val url: UriString, + val requestMethod: RequestMethod, + val requestBody: HTTPRequestBody? ) interface Request { diff --git a/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt b/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt index cd05b5d4c..ee9f0a9de 100644 --- a/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt +++ b/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt @@ -28,7 +28,9 @@ import okhttp3.HttpUrl import okhttp3.MediaType.Companion.toMediaType import okhttp3.MultipartBody import okhttp3.OkHttpClient +import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.internal.EMPTY_REQUEST import org.quantumbadger.redreader.cache.CacheRequest import org.quantumbadger.redreader.common.Constants import org.quantumbadger.redreader.common.General.getGeneralErrorForFailure @@ -174,37 +176,9 @@ class OKHTTPBackend private constructor() : HTTPBackend() { val requestBody = details.requestBody - if (requestBody != null) { - reqBuilder.post( - when (requestBody) { - is HTTPRequestBody.Multipart -> { - val builder = MultipartBody.Builder().setType(MultipartBody.FORM) - - requestBody.forEachPart { part: Part -> - when (part) { - is Part.FormData -> { - builder.addFormDataPart(part.name, part.value) - } - - is Part.FormDataBinary -> { - builder.addFormDataPart( - name = part.name, - filename = null, - body = part.value.toRequestBody("application/octet-stream".toMediaType()) - ) - } - } - } - - builder.build() - } - - is HTTPRequestBody.PostFields -> requestBody.encodeFields() - .toRequestBody("application/x-www-form-urlencoded".toMediaType()) - } - ) - } else { - reqBuilder.get() + when(details.requestMethod) { + CacheRequest.RequestMethod.GET -> reqBuilder.get() + CacheRequest.RequestMethod.POST -> reqBuilder.post(prepareRequestBody(requestBody)) } reqBuilder.url(details.url.value) @@ -313,6 +287,37 @@ class OKHTTPBackend private constructor() : HTTPBackend() { } } + private fun prepareRequestBody(requestBody: HTTPRequestBody?): RequestBody { + return when (requestBody) { + is HTTPRequestBody.Multipart -> { + val builder = MultipartBody.Builder().setType(MultipartBody.FORM) + + requestBody.forEachPart { part: Part -> + when (part) { + is Part.FormData -> { + builder.addFormDataPart(part.name, part.value) + } + + is Part.FormDataBinary -> { + builder.addFormDataPart( + name = part.name, + filename = null, + body = part.value.toRequestBody("application/octet-stream".toMediaType()) + ) + } + } + } + + builder.build() + } + + is HTTPRequestBody.PostFields -> requestBody.encodeFields() + .toRequestBody("application/x-www-form-urlencoded".toMediaType()) + + null -> EMPTY_REQUEST + } + } + companion object { private const val TAG = "OKHTTPBackend" diff --git a/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java b/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java index e3064eb0b..133c0a763 100644 --- a/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java @@ -66,6 +66,7 @@ public static void getImageInfo( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java b/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java index 1da3f6908..95571d500 100644 --- a/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java @@ -57,6 +57,7 @@ public static void getImageInfo( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java b/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java index 2e706bf74..07e542d47 100644 --- a/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java @@ -59,6 +59,7 @@ public static void getAlbumInfo( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser( context, @@ -110,6 +111,7 @@ public static void getImageInfo( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java b/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java index 40625d55e..2ac0b4758 100644 --- a/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java +++ b/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java @@ -61,6 +61,7 @@ public static void getAlbumInfo( withAuth ? CacheRequest.DownloadQueueType.IMGUR_API : CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override @@ -112,6 +113,7 @@ public static void getImageInfo( withAuth ? CacheRequest.DownloadQueueType.IMGUR_API : CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt b/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt index c36f17aad..869551860 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt +++ b/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt @@ -94,6 +94,7 @@ class RedditGalleryAPI { DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, context, object : CacheRequestCallbacks { diff --git a/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt b/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt index 8a7ec0b7f..2ab226f65 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt +++ b/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt @@ -73,6 +73,7 @@ object RedditVideosAPI { DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, object : CacheRequestCallbacks { private val mNotifiedFailure = AtomicBoolean(false) diff --git a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java index d32bfd469..35f1ce5f5 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java @@ -61,6 +61,7 @@ public static void getImageInfo( TimestampBound.notOlderThan(TimeDuration.minutes(10))), Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java index fa4a38d1f..32f857b1f 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java +++ b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java @@ -95,6 +95,7 @@ private static void requestMetadata( TimestampBound.notOlderThan(TimeDuration.minutes(10))), Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.REDGIFS_API_V2, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override @@ -154,6 +155,7 @@ public static void getImageInfo( DownloadStrategyAlways.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.POST, new HTTPRequestBody.PostFields( new PostField("grant_type", "client_credentials"), new PostField( diff --git a/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java b/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java index 7a23a3944..02ed0aff6 100644 --- a/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java @@ -57,6 +57,7 @@ public static void getImageInfo( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE_INFO, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java b/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java index 07a904aa0..09f64d281 100644 --- a/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java +++ b/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java @@ -116,6 +116,7 @@ public static void checkForNewMessages(final Context context) { DownloadStrategyAlways.INSTANCE, Constants.FileType.INBOX_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, false, context, new CacheRequestCallbacks() { diff --git a/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java b/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java index cb951d282..f0476f261 100644 --- a/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java +++ b/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java @@ -68,6 +68,7 @@ public static void performDownload(@NonNull final Context context) { DownloadStrategyAlways.INSTANCE, Constants.FileType.POST_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, false, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { diff --git a/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java b/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java index 05f25eb8e..86f81bc52 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java @@ -246,6 +246,7 @@ private CacheRequest createCommentListingCacheRequest() { mDownloadStrategy, Constants.FileType.COMMENT_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, mContext, new CacheRequestCallbacks() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java index 0fdbd5e96..1ffabfa36 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java @@ -1091,6 +1091,7 @@ private static CacheRequest createPostRequestUnprocessedResponse( DownloadStrategyAlways.INSTANCE, Constants.FileType.NOCACHE, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.POST, new HTTPRequestBody.PostFields(postFields), context, callbacks); @@ -1114,6 +1115,7 @@ private static CacheRequest createGetRequest( downloadStrategy, fileType, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, null, context, new CacheRequestJSONParser(context, handler)); diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java index 4320e68dd..56b02a9a0 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java @@ -84,6 +84,7 @@ public void performRequest( DownloadStrategyAlways.INSTANCE, Constants.FileType.SUBREDDIT_ABOUT, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java index 68a0bff55..ee6ca6900 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java @@ -189,6 +189,7 @@ private void doSubredditListRequest( DownloadStrategyAlways.INSTANCE, Constants.FileType.SUBREDDIT_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java index 1517176df..f7df50042 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java @@ -99,6 +99,7 @@ private void doRequest( DownloadStrategyAlways.INSTANCE, Constants.FileType.MULTIREDDIT_LIST, CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.GET, context, new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { @Override diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditOAuth.kt b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditOAuth.kt index 68a11a5fe..c00911df2 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditOAuth.kt +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditOAuth.kt @@ -30,6 +30,7 @@ import okhttp3.internal.closeQuietly import org.quantumbadger.redreader.R import org.quantumbadger.redreader.account.RedditAccount import org.quantumbadger.redreader.account.RedditAccountManager +import org.quantumbadger.redreader.cache.CacheRequest.RequestMethod import org.quantumbadger.redreader.cache.CacheRequest.RequestFailureType import org.quantumbadger.redreader.common.AndroidCommon import org.quantumbadger.redreader.common.CachedStringHash @@ -292,6 +293,7 @@ object RedditOAuth { context, RequestDetails( uri, + RequestMethod.POST, HTTPRequestBody.PostFields(postFields) ) ) @@ -384,7 +386,9 @@ object RedditOAuth { val uri = Constants.Reddit.getUri(Constants.Reddit.PATH_ME) return try { val request = HTTPBackend.backend - .prepareRequest(context, RequestDetails(uri, null)) + .prepareRequest( + context, RequestDetails(uri, RequestMethod.GET, null) + ) request.addHeader("Authorization", "bearer " + accessToken!!.token) val result = AtomicReference() request.executeInThisThread(object : HTTPBackend.Listener { @@ -573,6 +577,7 @@ object RedditOAuth { context, RequestDetails( uri, + RequestMethod.POST, HTTPRequestBody.PostFields(postFields) ) ) @@ -684,6 +689,7 @@ object RedditOAuth { context, RequestDetails( uri, + RequestMethod.POST, HTTPRequestBody.PostFields(postFields) ) ) diff --git a/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java b/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java index ae0c90f1a..a45f4091c 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java @@ -713,6 +713,7 @@ private void downloadThumbnail( DownloadStrategyIfNotCached.INSTANCE, fileType, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, context, new CacheRequestCallbacks() { diff --git a/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java b/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java index 71db9f635..2f53d392c 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java @@ -86,6 +86,7 @@ public final synchronized void writeTo( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.IMAGE, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, activity, new CacheRequestCallbacks() { Bitmap image = null; diff --git a/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java b/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java index 6bce3e40d..9120dffc0 100644 --- a/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java +++ b/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java @@ -534,6 +534,7 @@ private void downloadInlinePreview( DownloadStrategyIfNotCached.INSTANCE, Constants.FileType.INLINE_IMAGE_PREVIEW, CacheRequest.DownloadQueueType.IMMEDIATE, + CacheRequest.RequestMethod.GET, mActivity, new CacheRequestCallbacks() { @Override From fb62939331f311b9fed86775779d7ddb4a16474b Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Sat, 30 Nov 2024 13:50:05 -0700 Subject: [PATCH 2/7] Support PUT requests --- .../redreader/cache/CacheRequest.java | 3 ++- .../redreader/http/okhttp/OKHTTPBackend.kt | 1 + .../redreader/reddit/RedditAPI.java | 22 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java b/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java index d3fe3bef4..ffcc49d6f 100644 --- a/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java +++ b/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java @@ -66,7 +66,8 @@ public enum RequestFailureType { public enum RequestMethod { GET, - POST + POST, + PUT } public final UriString url; diff --git a/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt b/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt index ee9f0a9de..69797b093 100644 --- a/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt +++ b/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt @@ -178,6 +178,7 @@ class OKHTTPBackend private constructor() : HTTPBackend() { when(details.requestMethod) { CacheRequest.RequestMethod.GET -> reqBuilder.get() + CacheRequest.RequestMethod.PUT -> reqBuilder.put(prepareRequestBody(requestBody)); CacheRequest.RequestMethod.POST -> reqBuilder.post(prepareRequestBody(requestBody)) } diff --git a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java index 1ffabfa36..fad71a7d4 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java @@ -1120,4 +1120,26 @@ private static CacheRequest createGetRequest( context, new CacheRequestJSONParser(context, handler)); } + + @NonNull + private static CacheRequest createPutRequest( + @NonNull final UriString url, + @NonNull final RedditAccount user, + @NonNull final List postFields, + @NonNull final Context context, + @NonNull final CacheRequestJSONParser.Listener handler) { + + return new CacheRequest( + url, + user, + null, + new Priority(Constants.Priority.API_ACTION), + DownloadStrategyAlways.INSTANCE, + Constants.FileType.NOCACHE, + CacheRequest.DownloadQueueType.REDDIT_API, + CacheRequest.RequestMethod.PUT, + new HTTPRequestBody.PostFields(postFields), + context, + new CacheRequestJSONParser(context, handler)); + } } From afd8212b6c93ae6cf12e5548c9d59a7ab33c4c12 Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Sun, 24 Nov 2024 21:32:42 -0700 Subject: [PATCH 3/7] Handle 404, 403, 401, and 400 errors separately --- .../java/org/quantumbadger/redreader/common/General.kt | 8 +++++++- src/main/res/values/strings.xml | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/quantumbadger/redreader/common/General.kt b/src/main/java/org/quantumbadger/redreader/common/General.kt index 7aef2d017..c5942c827 100644 --- a/src/main/java/org/quantumbadger/redreader/common/General.kt +++ b/src/main/java/org/quantumbadger/redreader/common/General.kt @@ -308,9 +308,15 @@ object General { if(status == 404) { title = R.string.error_404_title message = R.string.error_404_message - } else { + } else if (status == 403) { title = R.string.error_403_title message = R.string.error_403_message + } else if (status == 401) { + title = R.string.error_401_title + message = R.string.error_401_message + } else { + title = R.string.error_400_title + message = R.string.error_400_message } } } diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml index 4d1f752c7..fce1e1d34 100644 --- a/src/main/res/values/strings.xml +++ b/src/main/res/values/strings.xml @@ -1902,4 +1902,10 @@ Horizontal padding Compact title + + + Unauthorized + Reddit says that you are not logged in or have provided invalid credentials. + Bad Request + Reddit says that you have submitted something invalid. From 68993be7cac698e9b05dd997d714386cc726550d Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Sun, 24 Nov 2024 21:34:51 -0700 Subject: [PATCH 4/7] Handle any 2xx response as a success --- .../org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt b/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt index 69797b093..db5ab2ad9 100644 --- a/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt +++ b/src/main/java/org/quantumbadger/redreader/http/okhttp/OKHTTPBackend.kt @@ -217,7 +217,7 @@ class OKHTTPBackend private constructor() : HTTPBackend() { val status = response.code val body = response.body - if (status == 200 || status == 202) { + if (status in 200..299) { val bodyStream: InputStream? val bodyLength: Long? From 57b5f1ab0ece99ffb183d24e9d7b3e458da97194 Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Wed, 27 Nov 2024 01:19:12 -0700 Subject: [PATCH 5/7] Refactor to use builder for CacheRequest --- .../activities/ImageViewActivity.java | 272 +++++++++--------- .../activities/ImgurUploadActivity.java | 142 ++++----- .../activities/InboxListingActivity.java | 42 ++- .../redreader/cache/CacheRequest.java | 254 ++++++++-------- .../redreader/common/FileUtils.java | 51 ++-- .../redreader/compose/net/NetWrapper.kt | 119 ++++---- .../fragments/PostListingFragment.java | 132 +++++---- .../redreader/fragments/UserProfileDialog.kt | 27 +- .../redreader/image/DeviantArtAPI.java | 71 ++--- .../redreader/image/GfycatAPI.java | 70 ++--- .../redreader/image/ImgurAPI.java | 154 +++++----- .../redreader/image/ImgurAPIV3.java | 162 ++++++----- .../redreader/image/RedditGalleryAPI.kt | 99 +++---- .../redreader/image/RedditVideosAPI.kt | 238 +++++++-------- .../redreader/image/RedgifsAPI.java | 72 ++--- .../redreader/image/RedgifsAPIV2.java | 178 ++++++------ .../redreader/image/StreamableAPI.java | 72 ++--- .../receivers/NewMessageChecker.java | 28 +- .../announcements/AnnouncementDownloader.java | 63 ++-- .../reddit/CommentListingRequest.java | 28 +- .../redreader/reddit/RedditAPI.java | 71 +++-- ...itAPIIndividualSubredditDataRequester.java | 86 +++--- ...itAPIIndividualSubredditListRequester.java | 235 +++++++-------- .../RedditAPIMultiredditListRequester.java | 100 +++---- .../reddit/prepared/RedditPreparedPost.java | 25 +- .../prepared/html/HtmlRawElementImg.java | 26 +- .../redreader/views/RedditPostView.java | 26 +- 27 files changed, 1446 insertions(+), 1397 deletions(-) diff --git a/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java b/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java index 7c05b14c4..4be2bf4be 100644 --- a/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java +++ b/src/main/java/org/quantumbadger/redreader/activities/ImageViewActivity.java @@ -881,152 +881,156 @@ private void makeCacheRequest( = new AtomicReference<>(); final AtomicReference videoMimetype = new AtomicReference<>(); - CacheManager.getInstance(this).makeRequest(mImageOrVideoRequest = new CacheRequest( - uri, - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.IMAGE_VIEW), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - this, - new CacheRequestCallbacks() { - - private boolean mProgressTextSet = false; - - @Override - public void onFailure(@NonNull final RRError error) { + CacheManager.getInstance(this).makeRequest( + mImageOrVideoRequest = new CacheRequest.Builder() + .setUrl(uri) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.IMAGE_VIEW)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(true) + .setContext(this) + .setCallbacks(new CacheRequestCallbacks() { + private boolean mProgressTextSet = false; + + @Override + public void onFailure(@NonNull final RRError error) { + + synchronized(resultLock) { + + if(!failed.getAndSet(true)) { + AndroidCommon.UI_THREAD_HANDLER.post(() -> { + final LinearLayout layout + = new LinearLayout( + ImageViewActivity.this); + final ErrorView errorView = new ErrorView( + ImageViewActivity.this, + error); + layout.addView(errorView); + General.setLayoutMatchWidthWrapHeight(errorView); + setMainView(layout); + }); + } + } + } - synchronized(resultLock) { - - if(!failed.getAndSet(true)) { - AndroidCommon.UI_THREAD_HANDLER.post(() -> { - final LinearLayout layout - = new LinearLayout(ImageViewActivity.this); - final ErrorView errorView = new ErrorView( - ImageViewActivity.this, - error); - layout.addView(errorView); - General.setLayoutMatchWidthWrapHeight(errorView); - setMainView(layout); + @Override + public void onDownloadNecessary() { + AndroidCommon.runOnUiThread(() -> { + progressBar.setVisibility(View.VISIBLE); + progressBar.setIndeterminate(true); + manageAspectRatioIndicator(progressBar); }); } - } - } - @Override - public void onDownloadNecessary() { - AndroidCommon.runOnUiThread(() -> { - progressBar.setVisibility(View.VISIBLE); - progressBar.setIndeterminate(true); - manageAspectRatioIndicator(progressBar); - }); - } - - @Override - public void onProgress( - final boolean authorizationInProgress, - final long bytesRead, - final long totalBytes) { - - AndroidCommon.runOnUiThread(() -> { - progressBar.setVisibility(View.VISIBLE); - progressBar.setIndeterminate(authorizationInProgress); - progressBar.setProgress( - ((float)((1000 * bytesRead) / totalBytes)) / 1000); - manageAspectRatioIndicator(progressBar); - - if(!mProgressTextSet) { - mProgressText.setText(General.bytesToMegabytes(totalBytes)); - mProgressTextSet = true; + @Override + public void onProgress( + final boolean authorizationInProgress, + final long bytesRead, + final long totalBytes) { + + AndroidCommon.runOnUiThread(() -> { + progressBar.setVisibility(View.VISIBLE); + progressBar.setIndeterminate(authorizationInProgress); + progressBar.setProgress( + ((float)((1000 * bytesRead) / totalBytes)) / 1000); + manageAspectRatioIndicator(progressBar); + + if(!mProgressTextSet) { + mProgressText.setText(General.bytesToMegabytes(totalBytes)); + mProgressTextSet = true; + } + }); } - }); - } - - @Override - public void onDataStreamAvailable( - @NonNull final GenericFactory - streamFactory, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache, - @Nullable final String mimetype) { - - synchronized(resultLock) { - - if(audio.get() != null || audioUri == null) { - onImageStreamReady( - !fromCache, - streamFactory, - audio.get(), - mimetype, - Uri.parse(uri.toString())); - } else { - video.set(streamFactory); - videoMimetype.set(mimetype); + @Override + public void onDataStreamAvailable( + @NonNull final GenericFactory + streamFactory, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache, + @Nullable final String mimetype) { + + synchronized(resultLock) { + + if(audio.get() != null || audioUri == null) { + onImageStreamReady( + !fromCache, + streamFactory, + audio.get(), + mimetype, + Uri.parse(uri.toString())); + + } else { + video.set(streamFactory); + videoMimetype.set(mimetype); + } + } } - } - } - })); + }) + .build()); if(audioUri != null) { - CacheManager.getInstance(this).makeRequest(mAudioRequest = new CacheRequest( - audioUri, - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.IMAGE_VIEW), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - this, - new CacheRequestCallbacks() { - @Override - public void onFailure(@NonNull final RRError error) { - - synchronized(resultLock) { - - if(!failed.getAndSet(true)) { - - AndroidCommon.runOnUiThread(() -> { - final LinearLayout layout - = new LinearLayout(ImageViewActivity.this); - final ErrorView errorView = new ErrorView( - ImageViewActivity.this, - error); - layout.addView(errorView); - General.setLayoutMatchWidthWrapHeight(errorView); - setMainView(layout); - }); + CacheManager.getInstance(this) + .makeRequest(mAudioRequest = new CacheRequest.Builder() + .setUrl(audioUri) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.IMAGE_VIEW)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(true) + .setContext(this) + .setCallbacks(new CacheRequestCallbacks() { + @Override + public void onFailure(@NonNull final RRError error) { + + synchronized (resultLock) { + + if (!failed.getAndSet(true)) { + + AndroidCommon.runOnUiThread(() -> { + final LinearLayout layout + = new LinearLayout(ImageViewActivity.this); + final ErrorView errorView = new ErrorView( + ImageViewActivity.this, + error); + layout.addView(errorView); + General.setLayoutMatchWidthWrapHeight(errorView); + setMainView(layout); + }); + } + } } - } - } - @Override - public void onDataStreamAvailable( - @NonNull final GenericFactory< - SeekableInputStream, IOException> streamFactory, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache, - @Nullable final String mimetype) { - - synchronized(resultLock) { - if(video.get() != null) { - onImageStreamReady( - !fromCache, - video.get(), - streamFactory, - videoMimetype.get(), - Uri.parse(uri.toString())); - } else { - audio.set(streamFactory); + @Override + public void onDataStreamAvailable( + @NonNull final GenericFactory< + SeekableInputStream, IOException> streamFactory, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache, + @Nullable final String mimetype) { + + synchronized (resultLock) { + if (video.get() != null) { + onImageStreamReady( + !fromCache, + video.get(), + streamFactory, + videoMimetype.get(), + Uri.parse(uri.toString())); + } else { + audio.set(streamFactory); + } + } } - } - } - })); + }) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java b/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java index c4e04201d..7ee924378 100644 --- a/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java +++ b/src/main/java/org/quantumbadger/redreader/activities/ImgurUploadActivity.java @@ -277,81 +277,83 @@ private void uploadImage() { final UriString apiUrl = new UriString("https://api.imgur.com/3/image"); - CacheManager.getInstance(this).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getInstance(this).getDefaultAccount(), - null, - new Priority(Constants.Priority.API_ACTION), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.NOCACHE, - CacheRequest.DownloadQueueType.IMGUR_API, - CacheRequest.RequestMethod.POST, - new HTTPRequestBody.Multipart() - .addPart(new Part.FormDataBinary("image", mImageData)), - this, - new CacheRequestJSONParser(this, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - final Uri imageUri; - - try { - final JsonObject root = result.asObject(); - - if(root == null) { - throw new RuntimeException("Response root object is null"); + CacheManager.getInstance(this).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getInstance(this).getDefaultAccount()) + .setPriority(new Priority(Constants.Priority.API_ACTION)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.NOCACHE) + .setQueueType(CacheRequest.DownloadQueueType.IMGUR_API) + .setRequestMethod(CacheRequest.RequestMethod.POST) + .setRequestBody(new HTTPRequestBody.Multipart() + .addPart(new Part.FormDataBinary("image", mImageData))) + .setContext(this) + .setCallbacks(new CacheRequestJSONParser( + this, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + final Uri imageUri; + + try { + final JsonObject root = result.asObject(); + + if(root == null) { + throw new RuntimeException("Response root object is null"); + } + + final Boolean success = root.getBoolean("success"); + + if(!Boolean.TRUE.equals(success)) { + onFailure(General.getGeneralErrorForFailure( + ImgurUploadActivity.this, + CacheRequest.RequestFailureType.UPLOAD_FAIL_IMGUR, + null, + null, + null, + Optional.of(new FailedRequestBody(result)))); + return; + } + + final String id = root.getObject("data").getString("id"); + imageUri = Uri.parse("https://imgur.com/" + id); + + } catch(final Throwable t) { + onFailure(General.getGeneralErrorForFailure( + ImgurUploadActivity.this, + CacheRequest.RequestFailureType.PARSE_IMGUR, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + return; + } + + AndroidCommon.runOnUiThread(() -> { + + final Intent resultIntent = new Intent(); + resultIntent.setData(imageUri); + setResult(0, resultIntent); + finish(); + }); } - final Boolean success = root.getBoolean("success"); + @Override + public void onFailure(@NonNull final RRError error) { - if(!Boolean.TRUE.equals(success)) { - onFailure(General.getGeneralErrorForFailure( + General.showResultDialog( ImgurUploadActivity.this, - CacheRequest.RequestFailureType.UPLOAD_FAIL_IMGUR, - null, - null, - null, - Optional.of(new FailedRequestBody(result)))); - return; - } - - final String id = root.getObject("data").getString("id"); - imageUri = Uri.parse("https://imgur.com/" + id); - - } catch(final Throwable t) { - onFailure(General.getGeneralErrorForFailure( - ImgurUploadActivity.this, - CacheRequest.RequestFailureType.PARSE_IMGUR, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - return; - } - - AndroidCommon.runOnUiThread(() -> { + error); - final Intent resultIntent = new Intent(); - resultIntent.setData(imageUri); - setResult(0, resultIntent); - finish(); - }); - } - - @Override - public void onFailure(@NonNull final RRError error) { - - General.showResultDialog( - ImgurUploadActivity.this, - error); - - AndroidCommon.runOnUiThread(ImgurUploadActivity.this::hideLoadingOverlay); - } - }))); + AndroidCommon.runOnUiThread( + ImgurUploadActivity.this::hideLoadingOverlay); + } + })) + .build()); } @Override diff --git a/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java b/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java index 7b7cbf315..398d040b6 100644 --- a/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java +++ b/src/main/java/org/quantumbadger/redreader/activities/InboxListingActivity.java @@ -253,20 +253,17 @@ private void makeFirstRequest(final Context context) { } } - // TODO parameterise limit - request = new CacheRequest( - url, - user, - null, - new Priority(Constants.Priority.API_INBOX_LIST), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.INBOX_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - false, - context, - new CacheRequestCallbacks() { - + request = new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_INBOX_LIST)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.INBOX_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(false) + .setContext(context) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onDataStreamComplete( @NonNull final GenericFactory @@ -348,8 +345,8 @@ public void onDataStreamComplete( final RedditPreparedMessage message = new RedditPreparedMessage( - InboxListingActivity.this, - ((RedditThing.Message) thing).getData(), + InboxListingActivity.this, + ((RedditThing.Message) thing).getData(), inboxType); itemHandler.sendMessage(General.handlerMessage( @@ -364,20 +361,20 @@ public void onDataStreamComplete( final ArrayList> replies = ((RedditThing.Listing)((RedditFieldReplies.Some) - message.src.getReplies()).getValue()) - .getData().getChildren(); + message.src.getReplies()).getValue()) + .getData().getChildren(); for(final MaybeParseError childMsgValue : replies) { final RedditMessage childMsgRaw = ((RedditThing.Message)childMsgValue.ok()) - .getData(); + .getData(); final RedditPreparedMessage childMsg = new RedditPreparedMessage( - InboxListingActivity.this, - childMsgRaw, + InboxListingActivity.this, + childMsgRaw, inboxType); itemHandler.sendMessage(General.handlerMessage( @@ -420,7 +417,8 @@ public void onFailure(@NonNull final RRError error) { AndroidCommon.runOnUiThread(() -> notifications.addView( new ErrorView(InboxListingActivity.this, error))); } - }); + }) + .build(); cm.makeRequest(request); } diff --git a/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java b/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java index ffcc49d6f..61bc0a51a 100644 --- a/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java +++ b/src/main/java/org/quantumbadger/redreader/cache/CacheRequest.java @@ -67,7 +67,11 @@ public enum RequestFailureType { public enum RequestMethod { GET, POST, - PUT + PUT; + + public boolean isGetRequest() { + return this == GET; + } } public final UriString url; @@ -113,126 +117,20 @@ public synchronized void cancel() { } } - public CacheRequest( - @NonNull final UriString url, - @NonNull final RedditAccount user, - @Nullable final UUID requestSession, - @NonNull final Priority priority, - @NonNull final DownloadStrategy downloadStrategy, - final int fileType, - final DownloadQueueType queueType, - final RequestMethod requestMethod, - final boolean cache, - @NonNull final Context context, - @NonNull final CacheRequestCallbacks callbacks) { - - this( - url, - user, - requestSession, - priority, - downloadStrategy, - fileType, - queueType, - requestMethod, - null, - cache, - context, - callbacks); - } - - public CacheRequest( - @NonNull final UriString url, - @NonNull final RedditAccount user, - @Nullable final UUID requestSession, - @NonNull final Priority priority, - @NonNull final DownloadStrategy downloadStrategy, - final int fileType, - final DownloadQueueType queueType, - final RequestMethod requestMethod, - @NonNull final Context context, - @NonNull final CacheRequestCallbacks callbacks) { - - this( - url, - user, - requestSession, - priority, - downloadStrategy, - fileType, - queueType, - requestMethod, - true, - context, - callbacks); - } - - public CacheRequest( - @NonNull final UriString url, - @NonNull final RedditAccount user, - @Nullable final UUID requestSession, - @NonNull final Priority priority, - @NonNull final DownloadStrategy downloadStrategy, - final int fileType, - final DownloadQueueType queueType, - final RequestMethod requestMethod, - @Nullable final HTTPRequestBody requestBody, - @NonNull final Context context, - @NonNull final CacheRequestCallbacks callbacks) { - - this( - url, - user, - requestSession, - priority, - downloadStrategy, - fileType, - queueType, - requestMethod, - requestBody, - false, - context, - callbacks); - } - - // TODO remove this huge constructor, make mutable - private CacheRequest( - @NonNull final UriString url, - @NonNull final RedditAccount user, - @Nullable final UUID requestSession, - @NonNull final Priority priority, - @NonNull final DownloadStrategy downloadStrategy, - final int fileType, - final DownloadQueueType queueType, - final RequestMethod requestMethod, - @Nullable final HTTPRequestBody requestBody, - final boolean cache, - @NonNull final Context context, - @NonNull final CacheRequestCallbacks callbacks) { - - this.context = context.getApplicationContext(); - mCallbacks = callbacks; - - if(user == null) { - throw new NullPointerException( - "User was null - set to empty string for anonymous"); - } - - if(!downloadStrategy.shouldDownloadWithoutCheckingCache() && requestBody != null) { - throw new IllegalArgumentException( - "Should not perform cache lookup for POST requests"); - } - - this.url = url; - this.user = user; - this.requestSession = requestSession; - this.priority = priority; - this.downloadStrategy = downloadStrategy; - this.fileType = fileType; - this.queueType = queueType; - this.requestMethod = requestMethod; - this.requestBody = Optional.ofNullable(requestBody); - this.cache = (requestBody == null) && cache; + private CacheRequest(final CacheRequest.Builder builder) { + + this.context = builder.context.getApplicationContext(); + this.mCallbacks = builder.callbacks; + this.url = builder.url; + this.user = builder.user; + this.requestSession = builder.requestSession; + this.priority = builder.priority; + this.downloadStrategy = builder.downloadStrategy; + this.fileType = builder.fileType; + this.queueType = builder.queueType; + this.requestMethod = builder.requestMethod; + this.requestBody = Optional.ofNullable(builder.requestBody); + this.cache = (builder.requestBody == null) && builder.cache; if(url == null) { notifyFailure(General.getGeneralErrorForFailure( @@ -349,4 +247,118 @@ public void notifyDownloadStarted() { } } } + + public static class Builder { + private UriString url; + private RedditAccount user; + @Nullable private UUID requestSession; + private Priority priority; + + private DownloadStrategy downloadStrategy; + + private Integer fileType; + + private DownloadQueueType queueType; + private RequestMethod requestMethod; + @Nullable private HTTPRequestBody requestBody; + private boolean cache; + private Context context; + private CacheRequestCallbacks callbacks; + + public Builder setUrl(final UriString url) { + this.url = url; + return this; + } + + public Builder setUser(final RedditAccount user) { + this.user = user; + return this; + } + + public Builder setRequestSession(final UUID requestSession) { + this.requestSession = requestSession; + return this; + } + + public Builder setPriority(final @NonNull Priority priority) { + this.priority = priority; + return this; + } + + public Builder setDownloadStrategy(final @NonNull DownloadStrategy downloadStrategy) { + this.downloadStrategy = downloadStrategy; + return this; + } + + public Builder setFileType(final int fileType) { + this.fileType = fileType; + return this; + } + + public Builder setQueueType(final DownloadQueueType queueType) { + this.queueType = queueType; + return this; + } + + public Builder setRequestMethod(final RequestMethod requestMethod) { + this.requestMethod = requestMethod; + return this; + } + + public Builder setRequestBody(final HTTPRequestBody requestBody) { + this.requestBody = requestBody; + return this; + } + + public Builder setCache(final boolean cache) { + this.cache = cache; + return this; + } + + public Builder setContext(final Context context) { + this.context = context; + return this; + } + + public Builder setCallbacks(final CacheRequestCallbacks callbacks) { + this.callbacks = callbacks; + return this; + } + + public CacheRequest build() { + validate(); + return new CacheRequest(this); + } + + private void validate() { + if (user == null) { + throw new IllegalArgumentException("The user field must be set for CacheReqest."); + } + if (context == null) { + throw new IllegalArgumentException( + "The context field must be set for CacheReqest."); + } + if(priority == null) { + throw new IllegalArgumentException( + "The priority field must be set for CacheReqest."); + } + if(fileType == null) { + throw new IllegalArgumentException( + "The fileType field must be set for CacheReqest."); + } + if(downloadStrategy == null) { + throw new IllegalArgumentException( + "The downloadStrategy field must be set for CacheReqest."); + } + if(requestMethod == null) { + throw new IllegalArgumentException( + "The requestMethod field must be set for CacheReqest."); + } + if(!downloadStrategy.shouldDownloadWithoutCheckingCache() + && !requestMethod.isGetRequest()) { + throw new IllegalArgumentException( + "Should not perform cache lookup for POST or PUT requests"); + } + } + } } diff --git a/src/main/java/org/quantumbadger/redreader/common/FileUtils.java b/src/main/java/org/quantumbadger/redreader/common/FileUtils.java index 58207b6e4..7ef703ec1 100644 --- a/src/main/java/org/quantumbadger/redreader/common/FileUtils.java +++ b/src/main/java/org/quantumbadger/redreader/common/FileUtils.java @@ -479,17 +479,17 @@ private static void internalDownloadImageToSaveAudio( final CacheManager cacheManager = CacheManager.getInstance(activity); - cacheManager.makeRequest(new CacheRequest( - info.urlAudioStream, - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.IMAGE_VIEW), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - activity, - new CacheRequestCallbacks() { + cacheManager.makeRequest(new CacheRequest.Builder() + .setUrl(info.urlAudioStream) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.IMAGE_VIEW)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(true) + .setContext(activity) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onFailure(@NonNull final RRError error) { @@ -575,7 +575,8 @@ public void onCacheFileWritten( Optional.empty())); } } - })); + }) + .build()); } public static void downloadImageToSave( @@ -597,17 +598,17 @@ public void onFailure(@NonNull final RRError error) { @Override public void onSuccess(final ImageInfo info) { - CacheManager.getInstance(activity).makeRequest(new CacheRequest( - info.original.url, - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.IMAGE_VIEW), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - activity, - new CacheRequestCallbacks() { + CacheManager.getInstance(activity).makeRequest(new CacheRequest.Builder() + .setUrl(info.original.url) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.IMAGE_VIEW)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(true) + .setContext(activity) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onDownloadNecessary() { General.quickToast( @@ -642,8 +643,8 @@ public void onCacheFileWritten( callback.onSuccess(info, cacheFile, mimetype); } } - })); - + }) + .build()); } @Override diff --git a/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt b/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt index 3363d98e3..288ddb7ce 100644 --- a/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt +++ b/src/main/java/org/quantumbadger/redreader/compose/net/NetWrapper.kt @@ -307,75 +307,76 @@ private fun fetchFile( val thisRequest = ++currentRequest.intValue - val req = CacheRequest( - uri, - account, - null, - priority, - downloadStrategy, - fileType, - queueType, - CacheRequest.RequestMethod.GET, - cache, - context, - object : CacheRequestCallbacks { - - var done = false - - val active - get() = !done && thisRequest == currentRequest.intValue - - override fun onFailure(error: RRError) { - AndroidCommon.runOnUiThread { - if (active) { - state.value = - NetRequestStatus.Failed(error.invokeIf(error.resolution == null) { - error.copy(resolution = RRError.Resolution.RETRY) - }) - done = true + val req = CacheRequest.Builder() + .setUrl(uri) + .setUser(account) + .setPriority(priority) + .setDownloadStrategy(downloadStrategy) + .setFileType(fileType) + .setQueueType(queueType) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(cache) + .setContext(context) + .setCallbacks( + object : CacheRequestCallbacks { + + var done = false + + val active + get() = !done && thisRequest == currentRequest.intValue + + override fun onFailure(error: RRError) { + AndroidCommon.runOnUiThread { + if (active) { + state.value = + NetRequestStatus.Failed(error.invokeIf(error.resolution == null) { + error.copy(resolution = RRError.Resolution.RETRY) + }) + done = true + } } } - } - override fun onDataStreamComplete( - streamFactory: GenericFactory, - timestamp: TimestampUTC?, - session: UUID, - fromCache: Boolean, - mimetype: String? - ) { - val result = filter( - FileRequestMetadata( - streamFactory, - timestamp, - session, - fromCache, - mimetype + override fun onDataStreamComplete( + streamFactory: GenericFactory, + timestamp: TimestampUTC?, + session: UUID, + fromCache: Boolean, + mimetype: String? + ) { + val result = filter( + FileRequestMetadata( + streamFactory, + timestamp, + session, + fromCache, + mimetype + ) ) - ) - AndroidCommon.runOnUiThread { - if (active) { - state.value = result - done = true + AndroidCommon.runOnUiThread { + if (active) { + state.value = result + done = true + } } } - } - override fun onProgress( - authorizationInProgress: Boolean, - bytesRead: Long, - totalBytes: Long - ) { - AndroidCommon.runOnUiThread { - if (active && totalBytes > 0) { - state.value = - NetRequestStatus.Downloading(bytesRead.toFloat() / totalBytes.toFloat()) + override fun onProgress( + authorizationInProgress: Boolean, + bytesRead: Long, + totalBytes: Long + ) { + AndroidCommon.runOnUiThread { + if (active && totalBytes > 0) { + state.value = + NetRequestStatus.Downloading( + bytesRead.toFloat() / totalBytes.toFloat()) + } } } - } - } - ) + }) + .build() CacheManager.getInstance(context).makeRequest(req) diff --git a/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java b/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java index 0fa4423b0..5563413ce 100644 --- a/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java +++ b/src/main/java/org/quantumbadger/redreader/fragments/PostListingFragment.java @@ -657,17 +657,18 @@ private CacheRequest createPostListingRequest( final AppCompatActivity activity = getActivity(); - return new CacheRequest( - url, - user, - requestSession, - new Priority(Constants.Priority.API_POST_LIST), - downloadStrategy, - Constants.FileType.POST_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - activity, - new CacheRequestCallbacks() { + return new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setRequestSession(requestSession) + .setPriority(new Priority(Constants.Priority.API_POST_LIST)) + .setDownloadStrategy(downloadStrategy) + .setFileType(Constants.FileType.POST_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(activity) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onDataStreamComplete( @NonNull final GenericFactory @@ -825,7 +826,7 @@ public void onDataStreamComplete( final RedditThing postThing = ((MaybeParseError.Ok)postThingValue) - .getValue(); + .getValue(); if(!(postThing instanceof RedditThing.Post)) { continue; @@ -994,7 +995,8 @@ public void onFailure(@NonNull final RRError error) { error)); }); } - }); + }) + .build(); } private void precacheComments( @@ -1007,47 +1009,44 @@ private void precacheComments( final UriString url = UriString.from(controller.getUri()); - CacheManager.getInstance(activity) - .makeRequest(new CacheRequest( - url, - RedditAccountManager.getInstance(activity).getDefaultAccount(), - null, - new Priority( - Constants.Priority.COMMENT_PRECACHE, - positionInList), - new DownloadStrategyIfTimestampOutsideBounds( - TimestampBound.notOlderThan(TimeDuration.minutes(15))), - Constants.FileType.COMMENT_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - // Don't parse the JSON - activity, - new CacheRequestCallbacks() { - @Override - public void onFailure(@NonNull final RRError error) { - - if(General.isSensitiveDebugLoggingEnabled()) { - Log.e( - TAG, - "Failed to precache " - + url - + " (" - + error - + ")"); - } - } + CacheManager.getInstance(activity).makeRequest(new CacheRequest.Builder() + .setUrl(url) + .setUser(RedditAccountManager.getInstance(activity).getDefaultAccount()) + .setPriority(new Priority(Constants.Priority.COMMENT_PRECACHE, positionInList)) + .setDownloadStrategy(new DownloadStrategyIfTimestampOutsideBounds( + TimestampBound.notOlderThan(TimeDuration.minutes(15)))) + .setFileType(Constants.FileType.COMMENT_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(activity) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { + @Override + public void onFailure(@NonNull final RRError error) { - @Override - public void onCacheFileWritten( - @NonNull final CacheManager.ReadableCacheFile cacheFile, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache, - @Nullable final String mimetype) { - - // Successfully precached - } - })); + if(General.isSensitiveDebugLoggingEnabled()) { + Log.e( + TAG, + "Failed to precache " + + url + + " (" + + error + + ")"); + } + } + + @Override + public void onCacheFileWritten( + @NonNull final CacheManager.ReadableCacheFile cacheFile, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache, + @Nullable final String mimetype) { + + // Successfully precached + } + }) + .build()); } private void precacheImage( @@ -1125,19 +1124,17 @@ private void precacheImage( final UriString url, final int positionInList) { - CacheManager.getInstance(activity).makeRequest(new CacheRequest( - url, - RedditAccountManager.getAnon(), - null, - new Priority( - Constants.Priority.IMAGE_PRECACHE, - positionInList), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE, - CacheRequest.DownloadQueueType.IMAGE_PRECACHE, - CacheRequest.RequestMethod.GET, - activity, - new CacheRequestCallbacks() { + CacheManager.getInstance(activity).makeRequest(new CacheRequest.Builder() + .setUrl(url) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.IMAGE_PRECACHE, positionInList)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE) + .setQueueType(CacheRequest.DownloadQueueType.IMAGE_PRECACHE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(activity) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onFailure(@NonNull final RRError error) { @@ -1160,6 +1157,7 @@ public void onCacheFileWritten( // Successfully precached } - })); + }) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt b/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt index e3d57914d..70915ee0e 100644 --- a/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt +++ b/src/main/java/org/quantumbadger/redreader/fragments/UserProfileDialog.kt @@ -429,17 +429,17 @@ object UserProfileDialog { imageOutput: ImageView, context: AppCompatActivity ) { - CacheManager.getInstance(context).makeRequest(CacheRequest( - url, - RedditAccountManager.getAnon(), - null, - Priority(Constants.Priority.INLINE_IMAGE_PREVIEW), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.INLINE_IMAGE_PREVIEW, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - object : CacheRequestCallbacks { + CacheManager.getInstance(context).makeRequest(CacheRequest.Builder() + .setUrl(url) + .setUser(RedditAccountManager.getAnon()) + .setPriority(Priority(Constants.Priority.INLINE_IMAGE_PREVIEW)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.INLINE_IMAGE_PREVIEW) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks(object : CacheRequestCallbacks { override fun onDataStreamComplete( streamFactory: GenericFactory, timestamp: TimestampUTC, @@ -481,7 +481,8 @@ object UserProfileDialog { "Failed to download user avatar: $error" ) } - } - )) + }) + .build() + ); } } diff --git a/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java b/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java index 133c0a763..1df727bb1 100644 --- a/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/DeviantArtAPI.java @@ -58,42 +58,45 @@ public static void getImageInfo( throw new RuntimeException(e); } - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, final boolean fromCache) { + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { - try { - final JsonObject outer = result.asObject(); - listener.onSuccess(ImageInfo.parseDeviantArt(outer)); + try { + final JsonObject outer = result.asObject(); + listener.onSuccess(ImageInfo.parseDeviantArt(outer)); - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - } - } + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } + } - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java b/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java index 95571d500..5efe5db1d 100644 --- a/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/GfycatAPI.java @@ -49,42 +49,44 @@ public static void getImageInfo( final UriString apiUrl = new UriString("https://api.gfycat.com/v1/gfycats/" + imageId); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, final boolean fromCache) { + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, final boolean fromCache) { - try { - final JsonObject outer = result.asObject().getObject("gfyItem"); - listener.onSuccess(ImageInfo.parseGfycat(outer)); + try { + final JsonObject outer = result.asObject() + .getObject("gfyItem"); + listener.onSuccess(ImageInfo.parseGfycat(outer)); - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - } - } + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } + } - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + }})) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java b/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java index 07e542d47..392a2e778 100644 --- a/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/ImgurAPI.java @@ -51,47 +51,47 @@ public static void getAlbumInfo( final UriString apiUrl = new UriString("https://api.imgur.com/2/album/" + albumId + ".json"); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser( + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks(new CacheRequestJSONParser( context, - new CacheRequestJSONParser.Listener() { - - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - final JsonObject outer = result.asObject().getObject("album"); - listener.onSuccess(AlbumInfo.parseImgur(albumUrl, outer)); - - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); + new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + final JsonObject outer = result.asObject().getObject("album"); + listener.onSuccess(AlbumInfo.parseImgur(albumUrl, outer)); + + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } } - } - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } public static void getImageInfo( @@ -103,43 +103,45 @@ public static void getImageInfo( final UriString apiUrl = new UriString("https://api.imgur.com/2/image/" + imageId + ".json"); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - final JsonObject outer = result.asObject().getObject("image"); - listener.onSuccess(ImageInfo.parseImgur(outer)); - - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - } - } - - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + final JsonObject outer = result.asObject().getObject("image"); + listener.onSuccess(ImageInfo.parseImgur(outer)); + + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } + } + + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java b/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java index 2ac0b4758..358ab99de 100644 --- a/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java +++ b/src/main/java/org/quantumbadger/redreader/image/ImgurAPIV3.java @@ -51,47 +51,49 @@ public static void getAlbumInfo( final UriString apiUrl = new UriString("https://api.imgur.com/3/album/" + albumId); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - withAuth + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(withAuth ? CacheRequest.DownloadQueueType.IMGUR_API - : CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - final JsonObject outer = result.asObject().getObject("data"); - final AlbumInfo album = AlbumInfo.parseImgurV3(albumUrl, outer); - listener.onSuccess(album); - - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - } - } - - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + : CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + final JsonObject outer = result.asObject().getObject("data"); + final AlbumInfo album = AlbumInfo.parseImgurV3(albumUrl, outer); + listener.onSuccess(album); + + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } + } + + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } public static void getImageInfo( @@ -103,45 +105,47 @@ public static void getImageInfo( final UriString apiUrl = new UriString("https://api.imgur.com/3/image/" + imageId); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - withAuth + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(withAuth ? CacheRequest.DownloadQueueType.IMGUR_API - : CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - final JsonObject outer = result.asObject().getObject("data"); - listener.onSuccess(ImageInfo.parseImgurV3(outer)); - - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - } - } - - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + : CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + final JsonObject outer = result.asObject().getObject("data"); + listener.onSuccess(ImageInfo.parseImgurV3(outer)); + + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } + } + + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt b/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt index 869551860..ef9ff1ba2 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt +++ b/src/main/java/org/quantumbadger/redreader/image/RedditGalleryAPI.kt @@ -86,68 +86,69 @@ class RedditGalleryAPI { ).generateJsonUri() CacheManager.getInstance(context).makeRequest( - CacheRequest( - UriString.from(apiUrl), - RedditAccountManager.getInstance(context).defaultAccount, - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - context, - object : CacheRequestCallbacks { - - override fun onDataStreamComplete( - streamFactory: GenericFactory, - timestamp: TimestampUTC?, - session: UUID, - fromCache: Boolean, - mimetype: String? - ) { - try { - val thingResponse = JsonUtils.decodeRedditThingResponseFromStream(streamFactory.create()) - - val responseMultiple = (thingResponse as? RedditThingResponse.Multiple) ?: + CacheRequest.Builder() + .setUrl(UriString.from(apiUrl)) + .setUser(RedditAccountManager.getInstance(context).defaultAccount) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + object : CacheRequestCallbacks { + + override fun onDataStreamComplete( + streamFactory: GenericFactory, + timestamp: TimestampUTC?, + session: UUID, + fromCache: Boolean, + mimetype: String? + ) { + try { + val thingResponse = JsonUtils.decodeRedditThingResponseFromStream(streamFactory.create()) + + val responseMultiple = (thingResponse as? RedditThingResponse.Multiple) ?: throw RuntimeException("Expecting RedditThingResponse.Multiple") - val listing = (responseMultiple.things.firstOrNull() as? RedditThing.Listing)?.data ?: + val listing = (responseMultiple.things.firstOrNull() as? RedditThing.Listing)?.data ?: throw RuntimeException("No listing in response") - val firstItem = listing.children.firstOrNull()?.ok() + val firstItem = listing.children.firstOrNull()?.ok() - val post = (firstItem as? RedditThing.Post)?.data ?: + val post = (firstItem as? RedditThing.Post)?.data ?: throw RuntimeException("No post found in response") - val album = AlbumInfo.parseRedditGallery(post) + val album = AlbumInfo.parseRedditGallery(post) - if (album == null) { - if (post.removed_by_category != null) { - listener.onGalleryRemoved() + if (album == null) { + if (post.removed_by_category != null) { + listener.onGalleryRemoved() + } else { + listener.onGalleryDataNotPresent() + } } else { - listener.onGalleryDataNotPresent() + listener.onSuccess(album) } - } else { - listener.onSuccess(album) + + } catch(t: Throwable) { + onFailure(getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + albumUrl, + FailedRequestBody.from(streamFactory))); } + } - } catch(t: Throwable) { - onFailure(getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - albumUrl, - FailedRequestBody.from(streamFactory))); + override fun onFailure(error: RRError) { + listener.onFailure(error) } - } - - override fun onFailure(error: RRError) { - listener.onFailure(error) - } - } - ) - ) + }) + .build() + ); } } } diff --git a/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt b/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt index 2ab226f65..1ccb8d0b0 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt +++ b/src/main/java/org/quantumbadger/redreader/image/RedditVideosAPI.kt @@ -64,127 +64,127 @@ object RedditVideosAPI { ) { val apiUrl = UriString("https://v.redd.it/$imageId/DASHPlaylist.mpd") - CacheManager.getInstance(context).makeRequest( - CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - object : CacheRequestCallbacks { - private val mNotifiedFailure = AtomicBoolean(false) - - override fun onDataStreamComplete( - stream: GenericFactory, - timestamp: TimestampUTC, - session: UUID, - fromCache: Boolean, - mimetype: String? - ) { - val mpd = try { - stream.create().use(::readWholeStreamAsUTF8) - } catch (e: IOException) { - Log.e(TAG, "Got exception", e) - - if (!mNotifiedFailure.getAndSet(true)) { - listener.onFailure( - getGeneralErrorForFailure( - context, + CacheManager.getInstance(context).makeRequest(CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + object : CacheRequestCallbacks { + private val mNotifiedFailure = AtomicBoolean(false) + + override fun onDataStreamComplete( + stream: GenericFactory, + timestamp: TimestampUTC, + session: UUID, + fromCache: Boolean, + mimetype: String? + ) { + val mpd = try { + stream.create().use(::readWholeStreamAsUTF8) + } catch (e: IOException) { + Log.e(TAG, "Got exception", e) + + if (!mNotifiedFailure.getAndSet(true)) { + listener.onFailure( + getGeneralErrorForFailure( + context, CacheRequest.RequestFailureType.STORAGE, - e, - null, - apiUrl, - FailedRequestBody.from(stream) - ) - ) - } - - return - } - - try { - var videoUrl: UriString? = null - var audioUrl: UriString? = null - - // Hacky workaround -- we should parse the MPD - val possibleFiles = arrayOf( - "DASH_AUDIO_128.mp4", - "DASH_AUDIO_64.mp4", - "DASH_AUDIO.mp4", - "DASH_audio_128.mp4", - "DASH_audio_64.mp4", - "DASH_audio.mp4", - "audio" - ) - - for (file in possibleFiles) { - if (mpd.contains(file)) { - audioUrl = UriString("https://v.redd.it/$imageId/$file") - break - } - } - - for (format in PREFERRED_VIDEO_FORMATS) { - if (mpd.contains("$format.mp4")) { - videoUrl = UriString("https://v.redd.it/$imageId/$format.mp4") - break - } - - if (mpd.contains(format)) { - videoUrl = UriString("https://v.redd.it/$imageId/$format") - break - } - } - - if (videoUrl == null) { - // Fallback - videoUrl = UriString("https://v.redd.it/$imageId/DASH_480.mp4") - } - - val result = if (audioUrl != null) { - ImageInfo( - original = ImageUrlInfo(videoUrl), - urlAudioStream = audioUrl, - mediaType = ImageInfo.MediaType.VIDEO, - hasAudio = ImageInfo.HasAudio.HAS_AUDIO - ) - } else { - ImageInfo( + e, + null, + apiUrl, + FailedRequestBody.from(stream) + ) + ) + } + + return + } + + try { + var videoUrl: UriString? = null + var audioUrl: UriString? = null + + // Hacky workaround -- we should parse the MPD + val possibleFiles = arrayOf( + "DASH_AUDIO_128.mp4", + "DASH_AUDIO_64.mp4", + "DASH_AUDIO.mp4", + "DASH_audio_128.mp4", + "DASH_audio_64.mp4", + "DASH_audio.mp4", + "audio" + ) + + for (file in possibleFiles) { + if (mpd.contains(file)) { + audioUrl = UriString("https://v.redd.it/$imageId/$file") + break + } + } + + for (format in PREFERRED_VIDEO_FORMATS) { + if (mpd.contains("$format.mp4")) { + videoUrl = UriString("https://v.redd.it/$imageId/$format.mp4") + break + } + + if (mpd.contains(format)) { + videoUrl = UriString("https://v.redd.it/$imageId/$format") + break + } + } + + if (videoUrl == null) { + // Fallback + videoUrl = UriString("https://v.redd.it/$imageId/DASH_480.mp4") + } + + val result = if (audioUrl != null) { + ImageInfo( original = ImageUrlInfo(videoUrl), - mediaType = ImageInfo.MediaType.VIDEO, - hasAudio = ImageInfo.HasAudio.NO_AUDIO - ) - } - - listener.onSuccess(result) - } catch (e: Exception) { - Log.e(TAG, "Got exception", e) - - if (!mNotifiedFailure.getAndSet(true)) { - listener.onFailure( - getGeneralErrorForFailure( - context, + urlAudioStream = audioUrl, + mediaType = ImageInfo.MediaType.VIDEO, + hasAudio = ImageInfo.HasAudio.HAS_AUDIO + ) + } else { + ImageInfo( + original = ImageUrlInfo(videoUrl), + mediaType = ImageInfo.MediaType.VIDEO, + hasAudio = ImageInfo.HasAudio.NO_AUDIO + ) + } + + listener.onSuccess(result) + } catch (e: Exception) { + Log.e(TAG, "Got exception", e) + + if (!mNotifiedFailure.getAndSet(true)) { + listener.onFailure( + getGeneralErrorForFailure( + context, CacheRequest.RequestFailureType.STORAGE, - e, - null, - apiUrl, - Optional.of(FailedRequestBody(mpd)) - ) - ) - } - } - } - - override fun onFailure(error: RRError) { - if (!mNotifiedFailure.getAndSet(true)) { - listener.onFailure(error) - } - } - }) - ) + e, + null, + apiUrl, + Optional.of(FailedRequestBody(mpd)) + ) + ) + } + } + } + + override fun onFailure(error: RRError) { + if (!mNotifiedFailure.getAndSet(true)) { + listener.onFailure(error) + } + } + }) + .build()) } } diff --git a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java index 35f1ce5f5..399acbbea 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPI.java @@ -51,45 +51,47 @@ public static void getImageInfo( final UriString apiUrl = new UriString("https://api.redgifs.com/v1/gfycats/" + imageId); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) // RedGifs links expire after an undocumented period of time - new DownloadStrategyIfTimestampOutsideBounds( - TimestampBound.notOlderThan(TimeDuration.minutes(10))), - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { + .setDownloadStrategy(new DownloadStrategyIfTimestampOutsideBounds( + TimestampBound.notOlderThan(TimeDuration.minutes(10)))) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { - try { - final JsonObject outer = result.asObject().getObject("gfyItem"); - listener.onSuccess(ImageInfo.parseGfycat(outer)); + try { + final JsonObject outer = result.asObject().getObject("gfyItem"); + listener.onSuccess(ImageInfo.parseGfycat(outer)); - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } } - } - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java index 32f857b1f..a305dff72 100644 --- a/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java +++ b/src/main/java/org/quantumbadger/redreader/image/RedgifsAPIV2.java @@ -85,49 +85,51 @@ private static void requestMetadata( final UriString apiUrl = new UriString("https://api.redgifs.com/v2/gifs/" + StringUtils.asciiLowercase(imageId)); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) // RedGifs V2 links expire after an undocumented period of time - new DownloadStrategyIfTimestampOutsideBounds( - TimestampBound.notOlderThan(TimeDuration.minutes(10))), - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.REDGIFS_API_V2, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - listener.onSuccess(ImageInfo.parseRedgifsV2(result - .getObjectAtPath("gif") - .orThrow(() -> new RuntimeException("No element 'gif'")))); - - Log.i(TAG, "Got RedGifs v2 metadata"); - - } catch(final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); + .setDownloadStrategy(new DownloadStrategyIfTimestampOutsideBounds( + TimestampBound.notOlderThan(TimeDuration.minutes(10)))) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.REDGIFS_API_V2) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + listener.onSuccess(ImageInfo.parseRedgifsV2(result + .getObjectAtPath("gif") + .orThrow(() -> new RuntimeException("No element 'gif'")))); + + Log.i(TAG, "Got RedGifs v2 metadata"); + + } catch(final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } } - } - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } @@ -147,64 +149,62 @@ public static void getImageInfo( final UriString apiUrl = new UriString("https://api.redgifs.com/v2/oauth/client"); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyAlways.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.POST, - new HTTPRequestBody.PostFields( + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.POST) + .setRequestBody(new HTTPRequestBody.PostFields( new PostField("grant_type", "client_credentials"), new PostField( Constants.OA_CI, "1828d09da4e-1011-a880-0005-d2ecbe8daab3"), new PostField( Constants.OA_CS, - "yCarP8TUpIr6J2W8YW+vgSRb8HuBd9koW/nkPtsQaP8=") - ), - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - final Optional accessToken - = result.getStringAtPath("access_token"); - - if(accessToken.isEmpty()) { - Log.i(TAG, "Failed to get RedGifs v2 token: result not present"); - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.REQUEST, - null, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - return; + "yCarP8TUpIr6J2W8YW+vgSRb8HuBd9koW/nkPtsQaP8="))) + .setContext(context) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + final Optional accessToken + = result.getStringAtPath("access_token"); + + if(accessToken.isEmpty()) { + Log.i(TAG, "Failed to get RedGifs v2 token: result not present"); + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.REQUEST, + null, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + return; + } + + Log.i(TAG, "Got RedGifs v2 token"); + + TOKEN.set(AuthToken.expireIn10Mins(accessToken.get())); + + requestMetadata(context, imageId, priority, listener); } - Log.i(TAG, "Got RedGifs v2 token"); - - TOKEN.set(AuthToken.expireIn10Mins(accessToken.get())); - - requestMetadata(context, imageId, priority, listener); - } + @Override + public void onFailure(@NonNull final RRError error) { - @Override - public void onFailure(@NonNull final RRError error) { - - Log.i(TAG, "Failed to get RedGifs v2 token"); - listener.onFailure(error); - } - }) - - )); + Log.i(TAG, "Failed to get RedGifs v2 token"); + listener.onFailure(error); + } + })) + .build()); } diff --git a/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java b/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java index 02ed0aff6..99357abd1 100644 --- a/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java +++ b/src/main/java/org/quantumbadger/redreader/image/StreamableAPI.java @@ -49,43 +49,45 @@ public static void getImageInfo( final UriString apiUrl = new UriString("https://api.streamable.com/videos/" + imageId); - CacheManager.getInstance(context).makeRequest(new CacheRequest( - apiUrl, - RedditAccountManager.getAnon(), - null, - priority, - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE_INFO, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(apiUrl) + .setUser(RedditAccountManager.getAnon()) + .setPriority(priority) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE_INFO) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks( + new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { - try { - final JsonObject outer = result.asObject(); - listener.onSuccess(ImageInfo.parseStreamable(outer)); + try { + final JsonObject outer = result.asObject(); + listener.onSuccess(ImageInfo.parseStreamable(outer)); - } catch (final Throwable t) { - listener.onFailure(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - t, - null, - apiUrl, - Optional.of(new FailedRequestBody(result)))); - } - } + } catch (final Throwable t) { + listener.onFailure(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + t, + null, + apiUrl, + Optional.of(new FailedRequestBody(result)))); + } + } - @Override - public void onFailure(@NonNull final RRError error) { - listener.onFailure(error); - } - }))); + @Override + public void onFailure(@NonNull final RRError error) { + listener.onFailure(error); + } + })) + .build()); } } diff --git a/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java b/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java index 09f64d281..3fdddcd14 100644 --- a/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java +++ b/src/main/java/org/quantumbadger/redreader/receivers/NewMessageChecker.java @@ -108,18 +108,17 @@ public static void checkForNewMessages(final Context context) { final UriString url = Constants.Reddit.getUri("/message/unread.json?limit=2"); - final CacheRequest request = new CacheRequest( - url, - user, - null, - new Priority(Constants.Priority.API_INBOX_LIST), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.INBOX_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - false, - context, - new CacheRequestCallbacks() { + final CacheRequest request = new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_INBOX_LIST)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.INBOX_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(false) + .setContext(context) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onFailure(@NonNull final RRError error) { @@ -216,7 +215,7 @@ public void onDataStreamComplete( if(oldMessageId == null || (!messageID.getValue().equals(oldMessageId) && oldMessageTimestamp - <= messageTimestamp.toUtcSecs())) { + <= messageTimestamp.toUtcSecs())) { Log.e(TAG, "New messages detected. Showing notification."); @@ -248,7 +247,8 @@ public void onDataStreamComplete( FailedRequestBody.from(streamFactory))); } } - }); + }) + .build(); cm.makeRequest(request); } diff --git a/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java b/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java index f0476f261..ee6b3346b 100644 --- a/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java +++ b/src/main/java/org/quantumbadger/redreader/receivers/announcements/AnnouncementDownloader.java @@ -60,37 +60,38 @@ public static void performDownload(@NonNull final Context context) { return; } - CacheManager.getInstance(context).makeRequest(new CacheRequest( - Constants.Reddit.getUri("/r/rr_announcements/new.json?limit=1"), - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.DEV_ANNOUNCEMENTS), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.POST_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - false, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - onJsonRetrieved(context, result); - } - - @Override - public void onFailure(@NonNull final RRError error) { - - Log.e( - TAG, - "Error downloading announcements: " + error, - error.t); - } - }))); + CacheManager.getInstance(context).makeRequest(new CacheRequest.Builder() + .setUrl(Constants.Reddit.getUri("/r/rr_announcements/new.json?limit=1")) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.DEV_ANNOUNCEMENTS)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.POST_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setCache(false) + .setContext(context) + .setCallbacks(new CacheRequestJSONParser( + context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + onJsonRetrieved(context, result); + } + + @Override + public void onFailure(@NonNull final RRError error) { + + Log.e( + TAG, + "Error downloading announcements: " + error, + error.t); + } + })) + .build()); } private static void onJsonRetrieved( diff --git a/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java b/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java index 86f81bc52..88fdcef94 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/CommentListingRequest.java @@ -238,17 +238,18 @@ private CacheRequest createCommentListingCacheRequest() { final UriString url = UriString.from(mUrl.generateJsonUri()); - return new CacheRequest( - url, - mUser, - mSession, - new Priority(Constants.Priority.API_COMMENT_LIST), - mDownloadStrategy, - Constants.FileType.COMMENT_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - mContext, - new CacheRequestCallbacks() { + return new CacheRequest.Builder() + .setUrl(url) + .setUser(mUser) + .setRequestSession(mSession) + .setPriority(new Priority(Constants.Priority.API_COMMENT_LIST)) + .setDownloadStrategy(mDownloadStrategy) + .setFileType(Constants.FileType.COMMENT_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(mContext) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onFailure(@NonNull final RRError error) { AndroidCommon.runOnUiThread(() @@ -274,7 +275,7 @@ public void onDataStreamAvailable( try { final RedditThingResponse thingResponse = JsonUtils.INSTANCE.decodeRedditThingResponseFromStream( - streamFactory.create()); + streamFactory.create()); onThingDownloaded(thingResponse, session, timestamp, fromCache); @@ -289,7 +290,8 @@ public void onDataStreamAvailable( } }, "Comment parsing", 1_000_000).start(); } - }); + }) + .build(); } private void buildCommentTree( diff --git a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java index fad71a7d4..51199ddce 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java @@ -1083,18 +1083,18 @@ private static CacheRequest createPostRequestUnprocessedResponse( @NonNull final Context context, @NonNull final CacheRequestCallbacks callbacks) { - return new CacheRequest( - url, - user, - null, - new Priority(Constants.Priority.API_ACTION), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.NOCACHE, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.POST, - new HTTPRequestBody.PostFields(postFields), - context, - callbacks); + return new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_ACTION)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.NOCACHE) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.POST) + .setRequestBody(new HTTPRequestBody.PostFields(postFields)) + .setContext(context) + .setCallbacks(callbacks) + .build(); } @NonNull @@ -1107,18 +1107,17 @@ private static CacheRequest createGetRequest( @NonNull final Context context, @NonNull final CacheRequestJSONParser.Listener handler) { - return new CacheRequest( - url, - user, - null, - priority, - downloadStrategy, - fileType, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - null, - context, - new CacheRequestJSONParser(context, handler)); + return new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setPriority(priority) + .setDownloadStrategy(downloadStrategy) + .setFileType(fileType) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCallbacks(new CacheRequestJSONParser(context, handler)) + .build(); } @NonNull @@ -1129,17 +1128,17 @@ private static CacheRequest createPutRequest( @NonNull final Context context, @NonNull final CacheRequestJSONParser.Listener handler) { - return new CacheRequest( - url, - user, - null, - new Priority(Constants.Priority.API_ACTION), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.NOCACHE, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.PUT, - new HTTPRequestBody.PostFields(postFields), - context, - new CacheRequestJSONParser(context, handler)); + return new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_ACTION)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.NOCACHE) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.PUT) + .setRequestBody(new HTTPRequestBody.PostFields(postFields)) + .setContext(context) + .setCallbacks(new CacheRequestJSONParser(context, handler)) + .build(); } } diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java index 56b02a9a0..d94c1e614 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditDataRequester.java @@ -76,48 +76,52 @@ public void performRequest( final UriString url = Constants.Reddit.getUri(subredditCanonicalId.toString() + "/about.json"); - final CacheRequest aboutSubredditCacheRequest = new CacheRequest( - url, - user, - null, - new Priority(Constants.Priority.API_SUBREDDIT_INVIDIVUAL), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.SUBREDDIT_ABOUT, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - final RedditThing subredditThing = result.asObject(RedditThing.class); - final RedditSubreddit subreddit = subredditThing.asSubreddit(); - subreddit.downloadTime = timestamp.toUtcMs(); - handler.onRequestSuccess(subreddit, timestamp); - - RedditSubredditHistory.addSubreddit(user, subredditCanonicalId); - - } catch(final Exception e) { - handler.onRequestFailed(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - e, - null, - url, - Optional.of(new FailedRequestBody(result)))); - } - } + final CacheRequest aboutSubredditCacheRequest = new CacheRequest.Builder() + .setUrl(url) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_SUBREDDIT_INVIDIVUAL)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.SUBREDDIT_ABOUT) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks(new CacheRequestJSONParser( + context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + final RedditThing subredditThing + = result.asObject(RedditThing.class); + final RedditSubreddit subreddit = subredditThing.asSubreddit(); + subreddit.downloadTime = timestamp.toUtcMs(); + handler.onRequestSuccess(subreddit, timestamp); + + RedditSubredditHistory.addSubreddit( + user, subredditCanonicalId); + + } catch(final Exception e) { + handler.onRequestFailed(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + e, + null, + url, + Optional.of(new FailedRequestBody(result)))); + } + } - @Override - public void onFailure(@NonNull final RRError error) { - handler.onRequestFailed(error); - } - })); + @Override + public void onFailure(@NonNull final RRError error) { + handler.onRequestFailed(error); + } + })) + .build(); CacheManager.getInstance(context).makeRequest(aboutSubredditCacheRequest); } diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java index ee6ca6900..ea0959f0c 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIIndividualSubredditListRequester.java @@ -181,126 +181,133 @@ private void doSubredditListRequest( } } - final CacheRequest aboutSubredditCacheRequest = new CacheRequest( - uri, - user, - null, - new Priority(Constants.Priority.API_SUBREDDIT_INVIDIVUAL), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.SUBREDDIT_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, final boolean fromCache) { - - try { - - final HashSet output = new HashSet<>(); - final ArrayList toWrite = new ArrayList<>(); - - final JsonObject redditListing = - result.asObject().getObject("data"); - - final JsonArray subreddits = - redditListing.getArray("children"); - - if(type == RedditSubredditManager.SubredditListType.SUBSCRIBED - && subreddits.size() == 0 - && after == null) { - performRequest( - RedditSubredditManager.SubredditListType.DEFAULTS, - TimestampBound.ANY, - handler); - return; - } - - for(final JsonValue v : subreddits) { - final RedditThing thing = v.asObject(RedditThing.class); - final RedditSubreddit subreddit = thing.asSubreddit(); - - subreddit.downloadTime = timestamp.toUtcMs(); + final CacheRequest aboutSubredditCacheRequest = new CacheRequest.Builder() + .setUrl(uri) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_SUBREDDIT_INVIDIVUAL)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.SUBREDDIT_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks(new CacheRequestJSONParser( + context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, final boolean fromCache) { try { - output.add(subreddit.getCanonicalId().toString()); - toWrite.add(subreddit); - } catch(final InvalidSubredditNameException e) { - Log.e( - "SubredditListRequester", - "Ignoring invalid subreddit", - e); - } - } - - RedditSubredditManager.getInstance(context, user) - .offerRawSubredditData(toWrite, timestamp); - final String receivedAfter = redditListing.getString("after"); - if(receivedAfter != null && type != - RedditSubredditManager.SubredditListType.MOST_POPULAR) { - - doSubredditListRequest( - type, - new RequestResponseHandler< - WritableHashSet, - RRError>() { - @Override - public void onRequestFailed( - final RRError failureReason) { - handler.onRequestFailed(failureReason); - } - - @Override - public void onRequestSuccess( - final WritableHashSet result, - final TimestampUTC timeCached) { - output.addAll(result.toHashset()); - handler.onRequestSuccess(new WritableHashSet( - output, - timeCached, - type.name()), timeCached); - - if(after == null) { - Log.i("SubredditListRequester", "Got " - + output.size() - + " subreddits in multiple requests"); - } - } - }, - receivedAfter); - - } else { - handler.onRequestSuccess(new WritableHashSet( - output, - timestamp, - type.name()), timestamp); - - if(after == null) { - Log.i("SubredditListRequester", "Got " - + output.size() + " subreddits in 1 request"); + final HashSet output = new HashSet<>(); + final ArrayList toWrite = new ArrayList<>(); + + final JsonObject redditListing = + result.asObject().getObject("data"); + + final JsonArray subreddits = + redditListing.getArray("children"); + + if(type == RedditSubredditManager.SubredditListType.SUBSCRIBED + && subreddits.size() == 0 + && after == null) { + performRequest( + RedditSubredditManager.SubredditListType.DEFAULTS, + TimestampBound.ANY, + handler); + return; + } + + for(final JsonValue v : subreddits) { + final RedditThing thing = v.asObject(RedditThing.class); + final RedditSubreddit subreddit = thing.asSubreddit(); + + subreddit.downloadTime = timestamp.toUtcMs(); + + try { + output.add(subreddit.getCanonicalId().toString()); + toWrite.add(subreddit); + } catch(final InvalidSubredditNameException e) { + Log.e( + "SubredditListRequester", + "Ignoring invalid subreddit", + e); + } + + } + + RedditSubredditManager.getInstance(context, user) + .offerRawSubredditData(toWrite, timestamp); + final String receivedAfter = redditListing + .getString("after"); + if(receivedAfter != null && type != RedditSubredditManager + .SubredditListType.MOST_POPULAR) { + + doSubredditListRequest( + type, + new RequestResponseHandler< + WritableHashSet, + RRError>() { + @Override + public void onRequestFailed( + final RRError failureReason) { + handler.onRequestFailed(failureReason); + } + + @Override + public void onRequestSuccess( + final WritableHashSet result, + final TimestampUTC timeCached) { + output.addAll(result.toHashset()); + handler.onRequestSuccess( + new WritableHashSet( + output, + timeCached, + type.name()), + timeCached); + + if(after == null) { + Log.i( + "SubredditListRequester", + "Got " + output.size() + + " subreddits in " + + "multiple requests"); + } + } + }, + receivedAfter); + + } else { + handler.onRequestSuccess(new WritableHashSet( + output, + timestamp, + type.name()), timestamp); + + if(after == null) { + Log.i("SubredditListRequester", "Got " + + output.size() + " subreddits in 1 request"); + } + } + + } catch(final Exception e) { + handler.onRequestFailed(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + e, + null, + uri, + Optional.of(new FailedRequestBody(result)))); } } - } catch(final Exception e) { - handler.onRequestFailed(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - e, - null, - uri, - Optional.of(new FailedRequestBody(result)))); - } - } - - @Override - public void onFailure(@NonNull final RRError error) { - handler.onRequestFailed(error); - } - })); + @Override + public void onFailure(@NonNull final RRError error) { + handler.onRequestFailed(error); + } + })) + .build(); CacheManager.getInstance(context).makeRequest(aboutSubredditCacheRequest); } diff --git a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java index f7df50042..3c6c1a902 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/api/RedditAPIMultiredditListRequester.java @@ -91,57 +91,59 @@ private void doRequest( final UriString uri = Constants.Reddit.getUri(Constants.Reddit.PATH_MULTIREDDITS_MINE); - final CacheRequest request = new CacheRequest( - uri, - user, - null, - new Priority(Constants.Priority.API_SUBREDDIT_LIST), - DownloadStrategyAlways.INSTANCE, - Constants.FileType.MULTIREDDIT_LIST, - CacheRequest.DownloadQueueType.REDDIT_API, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestJSONParser(context, new CacheRequestJSONParser.Listener() { - @Override - public void onJsonParsed( - @NonNull final JsonValue result, - final TimestampUTC timestamp, - @NonNull final UUID session, - final boolean fromCache) { - - try { - final HashSet output = new HashSet<>(); - - final JsonArray multiredditList = result.asArray(); - - for(final JsonValue multireddit : multiredditList) { - final String name = multireddit.asObject() - .getObject("data") - .getString("name"); - output.add(name); + final CacheRequest request = new CacheRequest.Builder() + .setUrl(uri) + .setUser(user) + .setPriority(new Priority(Constants.Priority.API_SUBREDDIT_LIST)) + .setDownloadStrategy(DownloadStrategyAlways.INSTANCE) + .setFileType(Constants.FileType.MULTIREDDIT_LIST) + .setQueueType(CacheRequest.DownloadQueueType.REDDIT_API) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks(new CacheRequestJSONParser( + context, new CacheRequestJSONParser.Listener() { + @Override + public void onJsonParsed( + @NonNull final JsonValue result, + final TimestampUTC timestamp, + @NonNull final UUID session, + final boolean fromCache) { + + try { + final HashSet output = new HashSet<>(); + + final JsonArray multiredditList = result.asArray(); + + for(final JsonValue multireddit : multiredditList) { + final String name = multireddit.asObject() + .getObject("data") + .getString("name"); + output.add(name); + } + + handler.onRequestSuccess(new WritableHashSet( + output, + timestamp, + user.getCanonicalUsername()), timestamp); + + } catch(final Exception e) { + handler.onRequestFailed(General.getGeneralErrorForFailure( + context, + CacheRequest.RequestFailureType.PARSE, + e, + null, + uri, + Optional.of(new FailedRequestBody(result)))); + } } - handler.onRequestSuccess(new WritableHashSet( - output, - timestamp, - user.getCanonicalUsername()), timestamp); - - } catch(final Exception e) { - handler.onRequestFailed(General.getGeneralErrorForFailure( - context, - CacheRequest.RequestFailureType.PARSE, - e, - null, - uri, - Optional.of(new FailedRequestBody(result)))); - } - } - - @Override - public void onFailure(@NonNull final RRError error) { - handler.onRequestFailed(error); - } - })); + @Override + public void onFailure(@NonNull final RRError error) { + handler.onRequestFailed(error); + } + })) + .build(); CacheManager.getInstance(context).makeRequest(request); } diff --git a/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java b/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java index a45f4091c..fa854d4ca 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/prepared/RedditPreparedPost.java @@ -705,17 +705,17 @@ private void downloadThumbnail( final RedditAccount anon = RedditAccountManager.getAnon(); - cm.makeRequest(new CacheRequest( - uri, - anon, - null, - new Priority(priority, listId), - DownloadStrategyIfNotCached.INSTANCE, - fileType, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - context, - new CacheRequestCallbacks() { + cm.makeRequest(new CacheRequest.Builder() + .setUrl(uri) + .setUser(anon) + .setPriority(new Priority(priority, listId)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(fileType) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(context) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onDataStreamComplete( @@ -741,7 +741,8 @@ public void onFailure(@NonNull final RRError error) { error.t); } } - })); + }) + .build()); } // These operations are ordered so as to avoid race conditions diff --git a/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java b/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java index 2f53d392c..719f5768c 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/prepared/html/HtmlRawElementImg.java @@ -78,17 +78,17 @@ public final synchronized void writeTo( ssb.append(mTitle); - CacheManager.getInstance(activity).makeRequest(new CacheRequest( - mSrc, - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.API_COMMENT_LIST), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.IMAGE, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - activity, - new CacheRequestCallbacks() { + CacheManager.getInstance(activity).makeRequest(new CacheRequest.Builder() + .setUrl(mSrc) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.API_COMMENT_LIST)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.IMAGE) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(activity) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { Bitmap image = null; @Override @@ -129,8 +129,8 @@ public void onDataStreamComplete( @Override public void onFailure(@NonNull final RRError error) { } - } - )); + }) + .build()); } @Override diff --git a/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java b/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java index 9120dffc0..f98795af0 100644 --- a/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java +++ b/src/main/java/org/quantumbadger/redreader/views/RedditPostView.java @@ -526,17 +526,17 @@ private void downloadInlinePreview( mImagePreviewLoadingSpinner.setVisibility(VISIBLE); setBottomMargin(true); - CacheManager.getInstance(mActivity).makeRequest(new CacheRequest( - preview.url, - RedditAccountManager.getAnon(), - null, - new Priority(Constants.Priority.INLINE_IMAGE_PREVIEW), - DownloadStrategyIfNotCached.INSTANCE, - Constants.FileType.INLINE_IMAGE_PREVIEW, - CacheRequest.DownloadQueueType.IMMEDIATE, - CacheRequest.RequestMethod.GET, - mActivity, - new CacheRequestCallbacks() { + CacheManager.getInstance(mActivity).makeRequest(new CacheRequest.Builder() + .setUrl(preview.url) + .setUser(RedditAccountManager.getAnon()) + .setPriority(new Priority(Constants.Priority.INLINE_IMAGE_PREVIEW)) + .setDownloadStrategy(DownloadStrategyIfNotCached.INSTANCE) + .setFileType(Constants.FileType.INLINE_IMAGE_PREVIEW) + .setQueueType(CacheRequest.DownloadQueueType.IMMEDIATE) + .setRequestMethod(CacheRequest.RequestMethod.GET) + .setContext(mActivity) + .setCache(true) + .setCallbacks(new CacheRequestCallbacks() { @Override public void onDataStreamComplete( @NonNull final GenericFactory stream, @@ -624,8 +624,8 @@ public void onFailure(@NonNull final RRError error) { General.setLayoutMatchWidthWrapHeight(errorView); }); } - } - )); + }) + .build()); } private void showPrefPrompt() { From f8da9707689055b429e1bcba0246a56e656c3413 Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Wed, 27 Nov 2024 19:39:19 -0700 Subject: [PATCH 6/7] Add support for add subreddit to multireddit api method --- .../redreader/common/Constants.java | 1 + .../redreader/reddit/RedditAPI.java | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/main/java/org/quantumbadger/redreader/common/Constants.java b/src/main/java/org/quantumbadger/redreader/common/Constants.java index 8b5d1d629..e8046ace7 100644 --- a/src/main/java/org/quantumbadger/redreader/common/Constants.java +++ b/src/main/java/org/quantumbadger/redreader/common/Constants.java @@ -147,6 +147,7 @@ public static final class Reddit { = "/subreddits/mine/moderator.json?limit=100"; public static final String PATH_SUBREDDITS_POPULAR = "/subreddits/popular.json"; public static final String PATH_MULTIREDDITS_MINE = "/api/multi/mine.json"; + public static final String PATH_MULTIREDDIT = "/api/multi"; public static final String PATH_COMMENTS = "/comments/"; public static final String PATH_ME = "/api/v1/me"; diff --git a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java index 51199ddce..94ea0bf46 100644 --- a/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java +++ b/src/main/java/org/quantumbadger/redreader/reddit/RedditAPI.java @@ -25,6 +25,7 @@ import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; +import org.json.JSONObject; import org.quantumbadger.redreader.account.RedditAccount; import org.quantumbadger.redreader.activities.BugReportActivity; import org.quantumbadger.redreader.cache.CacheManager; @@ -65,6 +66,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -959,6 +961,35 @@ public void onFailure(@NonNull final RRError error) { )); } + public static void addSubredditToMultireddit( + final CacheManager cm, + final APIResponseHandler.ActionResponseHandler handler, + final RedditAccount user, + final String multiredditName, + final String subredditName, + final Context context) { + + final Uri.Builder builder = Constants.Reddit.getUriBuilder( + Constants.Reddit.PATH_MULTIREDDIT) + .appendPath("user") + .appendPath(user.username) + .appendPath("m") + .appendPath(multiredditName) + .appendPath("r") + .appendPath(subredditName); + + final Map jsonData = new HashMap<>(); + jsonData.put("name", subredditName); + + cm.makeRequest(createPutRequest( + UriString.from(builder.build()), + user, + new ArrayList<>(Collections.singleton( + new PostField("model", new JSONObject(jsonData).toString()))), + context, + new GenericResponseHandler(handler))); + } + @Nullable private static APIResponseHandler.APIFailureType findFailureType(final JsonValue response) { From 6d812ac976f2d60d9678a98feb5cde7147399a24 Mon Sep 17 00:00:00 2001 From: Michael Boisvert Date: Wed, 27 Nov 2024 21:01:12 -0700 Subject: [PATCH 7/7] Create 'Add to Multireddit' action for subreddits --- .../adapters/MainMenuListingManager.java | 16 +- .../fragments/AddToMultiredditDialog.java | 162 ++++++++++++++++++ src/main/res/layout/add_to_multireddit.xml | 53 ++++++ src/main/res/values/arrays.xml | 2 + src/main/res/values/strings.xml | 2 + 5 files changed, 234 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/quantumbadger/redreader/fragments/AddToMultiredditDialog.java create mode 100644 src/main/res/layout/add_to_multireddit.xml diff --git a/src/main/java/org/quantumbadger/redreader/adapters/MainMenuListingManager.java b/src/main/java/org/quantumbadger/redreader/adapters/MainMenuListingManager.java index c2fa94d1d..fbe364bac 100644 --- a/src/main/java/org/quantumbadger/redreader/adapters/MainMenuListingManager.java +++ b/src/main/java/org/quantumbadger/redreader/adapters/MainMenuListingManager.java @@ -48,6 +48,7 @@ import org.quantumbadger.redreader.common.ScreenreaderPronunciation; import org.quantumbadger.redreader.common.SharedPrefsWrapper; import org.quantumbadger.redreader.common.UriString; +import org.quantumbadger.redreader.fragments.AddToMultiredditDialog; import org.quantumbadger.redreader.fragments.MainMenuFragment; import org.quantumbadger.redreader.receivers.announcements.Announcement; import org.quantumbadger.redreader.receivers.announcements.AnnouncementDownloader; @@ -117,7 +118,8 @@ public enum SubredditAction { UNPIN(R.string.unpin_subreddit), SUBSCRIBE(R.string.options_subscribe), UNSUBSCRIBE(R.string.options_unsubscribe), - EXTERNAL(R.string.action_external); + EXTERNAL(R.string.action_external), + ADD_TO_MULTIREDDIT(R.string.add_subreddit_to_multireddit); public final int descriptionResId; @@ -820,6 +822,13 @@ public static void showActionMenu( } } } + + if(itemPref.contains(SubredditAction.ADD_TO_MULTIREDDIT)) { + menu.add(new SubredditMenuItem( + activity, + R.string.add_subreddit_to_multireddit, + SubredditAction.ADD_TO_MULTIREDDIT)); + } } final String[] menuText = new String[menu.size()]; @@ -941,6 +950,11 @@ private static void onSubredditActionMenuItemSelected( Toast.LENGTH_SHORT).show(); } break; + + case ADD_TO_MULTIREDDIT: + + AddToMultiredditDialog.show(activity, subredditCanonicalId); + break; } } diff --git a/src/main/java/org/quantumbadger/redreader/fragments/AddToMultiredditDialog.java b/src/main/java/org/quantumbadger/redreader/fragments/AddToMultiredditDialog.java new file mode 100644 index 000000000..004c136a5 --- /dev/null +++ b/src/main/java/org/quantumbadger/redreader/fragments/AddToMultiredditDialog.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * This file is part of RedReader. + * + * RedReader is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * RedReader is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with RedReader. If not, see . + ******************************************************************************/ + +package org.quantumbadger.redreader.fragments; + +import android.util.Log; +import android.view.KeyEvent; +import android.view.View; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.widget.ArrayAdapter; +import android.widget.AutoCompleteTextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; + +import com.google.android.material.dialog.MaterialAlertDialogBuilder; + +import org.quantumbadger.redreader.R; +import org.quantumbadger.redreader.account.RedditAccountManager; +import org.quantumbadger.redreader.cache.CacheManager; +import org.quantumbadger.redreader.common.RRError; +import org.quantumbadger.redreader.common.TimestampBound; +import org.quantumbadger.redreader.reddit.APIResponseHandler; +import org.quantumbadger.redreader.reddit.RedditAPI; +import org.quantumbadger.redreader.reddit.api.RedditMultiredditSubscriptionManager; +import org.quantumbadger.redreader.reddit.things.SubredditCanonicalId; +import org.quantumbadger.redreader.views.liststatus.ErrorView; + +import java.util.ArrayList; +import java.util.Collections; + +public class AddToMultiredditDialog { + + private final static String TAG = "AddToMultiredditDialog"; + + public static void show( + final AppCompatActivity activity, + final SubredditCanonicalId subredditCanonicalId) { + + final MaterialAlertDialogBuilder alertBuilder + = new MaterialAlertDialogBuilder(activity); + + final View root = activity.getLayoutInflater().inflate( + R.layout.add_to_multireddit, + null); + + final RedditMultiredditSubscriptionManager multiredditManager + = RedditMultiredditSubscriptionManager.getSingleton( + activity, + RedditAccountManager.getInstance(activity).getDefaultAccount()); + + final ArrayList multireddits = multiredditManager.getSubscriptionList(); + Collections.sort(multireddits); + + final ArrayAdapter autocompleteAdapter = new ArrayAdapter<>( + activity, + android.R.layout.simple_dropdown_item_1line, + multireddits); + + final AutoCompleteTextView editText + = root.findViewById(R.id.selected_multireddit); + editText.setAdapter(autocompleteAdapter); + + alertBuilder.setView(root); + + alertBuilder.setNegativeButton(R.string.dialog_cancel, null); + + alertBuilder.setPositiveButton( + R.string.dialog_go, + (dialog, which) -> addToMultireddit(activity, editText, subredditCanonicalId)); + + final AlertDialog alertDialog = alertBuilder.create(); + + editText.setOnEditorActionListener((v, actionId, event) -> { + if(actionId == EditorInfo.IME_ACTION_GO + || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { + addToMultireddit(activity, editText, subredditCanonicalId); + alertDialog.dismiss(); + } + return false; + }); + + alertDialog.getWindow() + .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); + alertDialog.show(); + } + + private static void addToMultireddit( + final AppCompatActivity activity, + final AutoCompleteTextView editText, + final SubredditCanonicalId subredditCanonicalId) { + + final String multiredditName = editText.getText() + .toString() + .trim() + .replace(" ", ""); + final String subredditName = subredditCanonicalId.getDisplayNameLowercase(); + + RedditAPI.addSubredditToMultireddit( + CacheManager.getInstance(activity), + new APIResponseHandler.ActionResponseHandler(activity) { + + @Override + protected void onCallbackException(final Throwable t) { + Log.e( + TAG, "Error while adding subreddit to multireddit", t); + throw new RuntimeException(t); + } + + @Override + protected void onFailure(@NonNull final RRError error) { + activity.runOnUiThread(() -> { + final MaterialAlertDialogBuilder builder + = new MaterialAlertDialogBuilder(activity); + builder.setView(new ErrorView(activity, error)); + builder.create().show(); + }); + } + + @Override + protected void onSuccess() { + activity.runOnUiThread(() -> Toast.makeText( + activity, + String.format("Added %s to %s", subredditName, multiredditName), + Toast.LENGTH_SHORT).show()); + RedditMultiredditSubscriptionManager.getSingleton( + activity, + RedditAccountManager + .getInstance(activity).getDefaultAccount()) + .triggerUpdate(null, TimestampBound.NONE); + } + }, + RedditAccountManager.getInstance(activity).getDefaultAccount(), + multiredditName, + subredditName, + activity + ); + + Toast.makeText( + activity, + String.format("Adding %s to %s", subredditName, multiredditName), + Toast.LENGTH_SHORT).show(); + } +} diff --git a/src/main/res/layout/add_to_multireddit.xml b/src/main/res/layout/add_to_multireddit.xml new file mode 100644 index 000000000..00f516367 --- /dev/null +++ b/src/main/res/layout/add_to_multireddit.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + diff --git a/src/main/res/values/arrays.xml b/src/main/res/values/arrays.xml index 9d3502316..96b5fc1e5 100644 --- a/src/main/res/values/arrays.xml +++ b/src/main/res/values/arrays.xml @@ -495,6 +495,7 @@ @string/pin_subreddit @string/options_subscribe @string/block_subreddit + @string/add_subreddit_to_multireddit @@ -505,6 +506,7 @@ pin subscribe block + add_to_multireddit diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml index fce1e1d34..7e8918616 100644 --- a/src/main/res/values/strings.xml +++ b/src/main/res/values/strings.xml @@ -1908,4 +1908,6 @@ Reddit says that you are not logged in or have provided invalid credentials. Bad Request Reddit says that you have submitted something invalid. + + Add to New or Existing Multireddit