Skip to content

Commit

Permalink
Imgur upload reliability improved
Browse files Browse the repository at this point in the history
  • Loading branch information
QuantumBadger committed Jul 4, 2021
1 parent 86e7060 commit 3009221
Show file tree
Hide file tree
Showing 17 changed files with 486 additions and 147 deletions.
3 changes: 3 additions & 0 deletions assets/changelog-alpha.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/Alpha 285 (2021-07-04)
Imgur upload reliability improved

/Alpha 284 (2021-07-03)
Show parent comment after submitting reply
Better error message when failing to create cache directories
Expand Down
1 change: 1 addition & 0 deletions assets/changelog.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
100/1.18
Imgur upload reliability improved
Show parent comment after submitting reply
More detail in errors for failed API requests

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Base64OutputStream;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
Expand All @@ -48,7 +47,8 @@
import org.quantumbadger.redreader.common.Priority;
import org.quantumbadger.redreader.common.RRError;
import org.quantumbadger.redreader.common.StringUtils;
import org.quantumbadger.redreader.http.HTTPBackend;
import org.quantumbadger.redreader.http.body.HTTPRequestBodyMultipart;
import org.quantumbadger.redreader.http.body.multipart.PartFormDataBinary;
import org.quantumbadger.redreader.image.ThumbnailScaler;
import org.quantumbadger.redreader.jsonwrap.JsonObject;
import org.quantumbadger.redreader.jsonwrap.JsonValue;
Expand All @@ -57,7 +57,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

public class ImgurUploadActivity extends BaseActivity {
Expand All @@ -66,7 +65,7 @@ public class ImgurUploadActivity extends BaseActivity {

private ImageView mThumbnailView;

private String mBase64Data;
private byte[] mImageData;

private Button mUploadButton;

Expand Down Expand Up @@ -124,7 +123,7 @@ protected void onCreate(final Bundle savedInstanceState) {
});

mUploadButton.setOnClickListener(v -> {
if(mBase64Data != null) {
if(mImageData != null) {
uploadImage();
} else {
General.quickToast(this, R.string.no_file_selected);
Expand Down Expand Up @@ -164,7 +163,7 @@ private void hideLoadingOverlay() {

private void updateUploadButtonVisibility() {
mUploadButton.setVisibility(
mBase64Data != null
mImageData != null
? View.VISIBLE
: View.GONE);
}
Expand Down Expand Up @@ -206,22 +205,19 @@ public void run() {
rawBitmap.recycle();

final ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
final Base64OutputStream output = new Base64OutputStream(
byteOutput,
0);

try(InputStream inputStream = getContentResolver().openInputStream(uri)) {
General.copyStream(inputStream, output);
output.flush();
General.copyStream(inputStream, byteOutput);
byteOutput.flush();

} catch(final IOException e) {
throw new RuntimeException(e);
}

final String base64String = new String(byteOutput.toByteArray());
final byte[] imageData = byteOutput.toByteArray();

AndroidCommon.UI_THREAD_HANDLER.post(() -> {
mBase64Data = base64String;
mImageData = imageData;
mUploadButton.setEnabled(true);
mThumbnailView.setImageBitmap(thumbnailBitmap);
mTextView.setText(getString(
Expand All @@ -243,7 +239,7 @@ public void run() {
e));

AndroidCommon.UI_THREAD_HANDLER.post(() -> {
mBase64Data = null;
mImageData = null;
mUploadButton.setEnabled(false);
mThumbnailView.setImageBitmap(null);
mTextView.setText(R.string.no_file_selected);
Expand All @@ -259,9 +255,6 @@ private void uploadImage() {

showLoadingOverlay();

final ArrayList<HTTPBackend.PostField> postFields = new ArrayList<>(1);
postFields.add(new HTTPBackend.PostField("image", mBase64Data));

CacheManager.getInstance(this).makeRequest(new CacheRequest(
General.uriFromString("https://api.imgur.com/3/image"),
RedditAccountManager.getInstance(this).getDefaultAccount(),
Expand All @@ -270,14 +263,16 @@ private void uploadImage() {
DownloadStrategyAlways.INSTANCE,
Constants.FileType.NOCACHE,
CacheRequest.DOWNLOAD_QUEUE_IMGUR_API,
postFields,
new HTTPRequestBodyMultipart()
.addPart(new PartFormDataBinary("image", mImageData)),
this,
new CacheRequestJSONParser(this, new CacheRequestJSONParser.Listener() {
@Override
public void onJsonParsed(
@NonNull final JsonValue result,
final long timestamp,
@NonNull final UUID session, final boolean fromCache) {
@NonNull final UUID session,
final boolean fromCache) {

final Uri imageUri;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public CacheDownload(

mRequest = HTTPBackend.getBackend().prepareRequest(
initiator.context,
new HTTPBackend.RequestDetails(mInitiator.url, mInitiator.postFields));
new HTTPBackend.RequestDetails(mInitiator.url, mInitiator.requestBody));
}

public synchronized void cancel() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,12 @@
import org.quantumbadger.redreader.common.Priority;
import org.quantumbadger.redreader.common.RRError;
import org.quantumbadger.redreader.common.datastream.SeekableInputStream;
import org.quantumbadger.redreader.http.HTTPBackend;
import org.quantumbadger.redreader.http.body.HTTPRequestBody;

import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URI;
import java.util.List;
import java.util.UUID;

public final class CacheRequest implements Comparable<CacheRequest> {
Expand Down Expand Up @@ -94,7 +93,7 @@ public final class CacheRequest implements Comparable<CacheRequest> {
public final int fileType;

public final @DownloadQueueType int queueType;
public final List<HTTPBackend.PostField> postFields;
@NonNull public final Optional<HTTPRequestBody> requestBody;

public final boolean cache;

Expand Down Expand Up @@ -183,7 +182,7 @@ public CacheRequest(
@NonNull final DownloadStrategy downloadStrategy,
final int fileType,
final @DownloadQueueType int queueType,
final List<HTTPBackend.PostField> postFields,
@Nullable final HTTPRequestBody requestBody,
final Context context,
final CacheRequestCallbacks callbacks) {

Expand All @@ -195,7 +194,7 @@ public CacheRequest(
downloadStrategy,
fileType,
queueType,
postFields,
requestBody,
false,
context,
callbacks);
Expand All @@ -210,7 +209,7 @@ private CacheRequest(
@NonNull final DownloadStrategy downloadStrategy,
final int fileType,
final @DownloadQueueType int queueType,
final List<HTTPBackend.PostField> postFields,
@Nullable final HTTPRequestBody requestBody,
final boolean cache,
final Context context,
final CacheRequestCallbacks callbacks) {
Expand All @@ -223,7 +222,7 @@ private CacheRequest(
"User was null - set to empty string for anonymous");
}

if(!downloadStrategy.shouldDownloadWithoutCheckingCache() && postFields != null) {
if(!downloadStrategy.shouldDownloadWithoutCheckingCache() && requestBody != null) {
throw new IllegalArgumentException(
"Should not perform cache lookup for POST requests");
}
Expand All @@ -235,8 +234,8 @@ private CacheRequest(
this.downloadStrategy = downloadStrategy;
this.fileType = fileType;
this.queueType = queueType;
this.postFields = postFields;
this.cache = (postFields == null) && cache;
this.requestBody = Optional.ofNullable(requestBody);
this.cache = (requestBody == null) && cache;

if(url == null) {
notifyFailure(
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/org/quantumbadger/redreader/common/Void.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*******************************************************************************
* 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 <http://www.gnu.org/licenses/>.
******************************************************************************/

package org.quantumbadger.redreader.common;

import androidx.annotation.NonNull;

public final class Void {

@SuppressWarnings("InstantiationOfUtilityClass")
@NonNull public static final Void INSTANCE = new Void();

private Void() {}
}
64 changes: 9 additions & 55 deletions src/main/java/org/quantumbadger/redreader/http/HTTPBackend.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,13 @@

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.quantumbadger.redreader.cache.CacheRequest;
import org.quantumbadger.redreader.common.Optional;
import org.quantumbadger.redreader.http.body.HTTPRequestBody;
import org.quantumbadger.redreader.http.okhttp.OKHTTPBackend;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.List;

public abstract class HTTPBackend {
/**
Expand All @@ -41,79 +38,36 @@ public static HTTPBackend getBackend() {
public static class RequestDetails {

@NonNull private final URI mUrl;
@Nullable private final List<PostField> mPostFields;
@NonNull private final Optional<HTTPRequestBody> mRequestBody;

public RequestDetails(
@NonNull final URI url,
@Nullable final List<PostField> postFields) {
@NonNull final Optional<HTTPRequestBody> requestBody) {
mUrl = url;
mPostFields = postFields;
mRequestBody = requestBody;
}

@NonNull
public URI getUrl() {
return mUrl;
}

@Nullable
public List<PostField> getPostFields() {
return mPostFields;
@NonNull
public Optional<HTTPRequestBody> getRequestBody() {
return mRequestBody;
}

@NonNull
@Override
public String toString() {
return "RequestDetails("
+ mUrl.toString()
+ mUrl
+ ", "
+ (mPostFields != null ? mPostFields.toString() : null)
+ mRequestBody
+ ")";
}
}

public static class PostField {

public final String name;
public final String value;

public PostField(final String name, final String value) {
this.name = name;
this.value = value;
}

public String encode() {
try {
return URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(
value,
"UTF-8");
} catch(final UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}

public static String encodeList(final List<PostField> fields) {

final StringBuilder result = new StringBuilder();

for(final PostField field : fields) {

if(result.length() > 0) {
result.append('&');
}

result.append(field.encode());
}

return result.toString();
}

@NonNull
@Override
public String toString() {
return "PostField(name=" + name + ")";
}
}

public interface Request {
void executeInThisThread(final Listener listener);

Expand Down

0 comments on commit 3009221

Please sign in to comment.