Skip to content

Commit

Permalink
Fix: Handle HTTP Range Not Satisfiable in WebDAV getRange()
Browse files Browse the repository at this point in the history
The POSIX read() API also returns 0 when file offset is at or past end
of file.
  • Loading branch information
zhanghai committed Mar 2, 2024
1 parent 60da95b commit a9bcff4
Showing 1 changed file with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down Expand Up @@ -79,4 +89,8 @@ class FileByteChannel(
override fun onClose() {
sequentialWriteOutputStream?.close()
}

companion object {
private const val HTTP_RANGE_NOT_SATISFIABLE = 416
}
}

0 comments on commit a9bcff4

Please sign in to comment.