From a9bcff4a793718f0ebc12c96eb830b71324148b7 Mon Sep 17 00:00:00 2001 From: Hai Zhang Date: Fri, 1 Mar 2024 17:41:23 -0800 Subject: [PATCH] Fix: Handle HTTP Range Not Satisfiable in WebDAV getRange() The POSIX read() API also returns 0 when file offset is at or past end of file. --- .../provider/webdav/client/FileByteChannel.kt | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/me/zhanghai/android/files/provider/webdav/client/FileByteChannel.kt b/app/src/main/java/me/zhanghai/android/files/provider/webdav/client/FileByteChannel.kt index fca3185ed..c77fd372b 100644 --- a/app/src/main/java/me/zhanghai/android/files/provider/webdav/client/FileByteChannel.kt +++ b/app/src/main/java/me/zhanghai/android/files/provider/webdav/client/FileByteChannel.kt @@ -6,8 +6,10 @@ package me.zhanghai.android.files.provider.webdav.client import at.bitfire.dav4jvm.DavResource +import at.bitfire.dav4jvm.exception.HttpException import at.bitfire.dav4jvm.property.webdav.GetContentLength import me.zhanghai.android.files.provider.common.AbstractFileByteChannel +import me.zhanghai.android.files.provider.common.EMPTY import me.zhanghai.android.files.provider.common.readFully import okhttp3.RequestBody.Companion.toRequestBody import java.io.IOException @@ -25,8 +27,16 @@ class FileByteChannel( @Throws(IOException::class) override fun onRead(position: Long, size: Int): ByteBuffer { + val inputStream = try { + resource.getRangeCompat("*/*", position, size, null) + } catch (e: HttpException) { + if (e.code == HTTP_RANGE_NOT_SATISFIABLE) { + // We were reading at/past end of file + return ByteBuffer::class.EMPTY + } + throw e + } val destination = ByteBuffer.allocate(size) - val inputStream = resource.getRangeCompat("*/*", position, size, null) val limit = inputStream.use { it.readFully(destination.array(), destination.arrayOffset(), size) } @@ -79,4 +89,8 @@ class FileByteChannel( override fun onClose() { sequentialWriteOutputStream?.close() } + + companion object { + private const val HTTP_RANGE_NOT_SATISFIABLE = 416 + } }