From f71f056c22d2f77eddd42002f8677171d5eb6ba0 Mon Sep 17 00:00:00 2001 From: casey langen Date: Sat, 3 Jun 2017 20:39:21 -0700 Subject: [PATCH] Fixed a bug where range request (offset) was getting ignored if the server responds with with an HTTP 200 (not 206), and the response has not yet been cached. --- .../com/danikula/videocache/HttpProxyCache.java | 15 +++++++++++++++ .../com/danikula/videocache/HttpUrlSource.java | 10 +++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/library/src/main/java/com/danikula/videocache/HttpProxyCache.java b/library/src/main/java/com/danikula/videocache/HttpProxyCache.java index 010354f..b7a1eb6 100644 --- a/library/src/main/java/com/danikula/videocache/HttpProxyCache.java +++ b/library/src/main/java/com/danikula/videocache/HttpProxyCache.java @@ -87,12 +87,27 @@ private void responseWithoutCache(OutputStream out, long offset) throws ProxyCac HttpUrlSource newSourceNoCache = new HttpUrlSource(this.source); try { newSourceNoCache.open((int) offset); + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int readBytes; + + /* manually advance to the offset if the server ignored the + range request and returned the entire body. */ + if (offset > 0 && newSourceNoCache.getResponseCode() == 200) { + int readCount; + long remaining = offset; + while (remaining > 0) { + readCount = (int) Math.min(DEFAULT_BUFFER_SIZE, offset); + remaining -= newSourceNoCache.read(buffer, readCount); + } + } + + /* return data after the offset */ while ((readBytes = newSourceNoCache.read(buffer)) != -1) { out.write(buffer, 0, readBytes); offset += readBytes; } + out.flush(); } finally { newSourceNoCache.close(); diff --git a/library/src/main/java/com/danikula/videocache/HttpUrlSource.java b/library/src/main/java/com/danikula/videocache/HttpUrlSource.java index c7fb8ad..f10ed6b 100644 --- a/library/src/main/java/com/danikula/videocache/HttpUrlSource.java +++ b/library/src/main/java/com/danikula/videocache/HttpUrlSource.java @@ -118,11 +118,15 @@ public void close() throws ProxyCacheException { @Override public int read(byte[] buffer) throws ProxyCacheException { + return read(buffer, buffer.length); + } + + public int read(byte[] buffer, int length) throws ProxyCacheException { if (inputStream == null) { throw new ProxyCacheException("Error reading data from " + sourceInfo.url + ": connection is absent!"); } try { - return inputStream.read(buffer, 0, buffer.length); + return inputStream.read(buffer, 0, length); } catch (InterruptedIOException e) { throw new InterruptedProxyCacheException("Reading source " + sourceInfo.url + " is interrupted", e); } catch (IOException e) { @@ -200,6 +204,10 @@ public String getUrl() { return sourceInfo.url; } + public int getResponseCode() throws IOException { + return connection.getResponseCode(); + } + @Override public String toString() { return "HttpUrlSource{sourceInfo='" + sourceInfo + "}";