|
| 1 | +package com.zulip.android.networking; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import okhttp3.MediaType; |
| 6 | +import okhttp3.ResponseBody; |
| 7 | +import okio.Buffer; |
| 8 | +import okio.BufferedSource; |
| 9 | +import okio.ForwardingSource; |
| 10 | +import okio.Okio; |
| 11 | +import okio.Source; |
| 12 | + |
| 13 | +/** |
| 14 | + * TODO: add description |
| 15 | + */ |
| 16 | + |
| 17 | +public class UploadProgressResponse extends ResponseBody { |
| 18 | + private final ResponseBody responseBody; |
| 19 | + private final ProgressListener progressListener; |
| 20 | + private BufferedSource bufferedSource; |
| 21 | + private int mNotificationId; |
| 22 | + |
| 23 | + public UploadProgressResponse(ResponseBody responseBody, ProgressListener progressListener, |
| 24 | + int notificationId) { |
| 25 | + this.responseBody = responseBody; |
| 26 | + this.progressListener = progressListener; |
| 27 | + this.mNotificationId = notificationId; |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public MediaType contentType() { |
| 32 | + return responseBody.contentType(); |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public long contentLength() { |
| 37 | + return responseBody.contentLength(); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public BufferedSource source() { |
| 42 | + if (bufferedSource == null) { |
| 43 | + bufferedSource = Okio.buffer(source(responseBody.source())); |
| 44 | + } |
| 45 | + return bufferedSource; |
| 46 | + } |
| 47 | + |
| 48 | + private Source source(Source source) { |
| 49 | + return new ForwardingSource(source) { |
| 50 | + long totalBytesRead = 0L; |
| 51 | + |
| 52 | + @Override |
| 53 | + public long read(Buffer sink, long byteCount) throws IOException { |
| 54 | + long bytesRead = super.read(sink, byteCount); |
| 55 | + // read() returns the number of bytes read, or -1 if this source is exhausted. |
| 56 | + totalBytesRead += bytesRead != -1 ? bytesRead : 0; |
| 57 | + progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1, mNotificationId); |
| 58 | + return bytesRead; |
| 59 | + } |
| 60 | + }; |
| 61 | + } |
| 62 | + |
| 63 | + public interface ProgressListener { |
| 64 | + void update(long bytesRead, long contentLength, boolean done, int notificationId); |
| 65 | + } |
| 66 | +} |
0 commit comments