Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WebView Asset PathHandler that returns contents of a zip archive.
// Licensed under CC-0 terms. https://creativecommons.org/share-your-work/public-domain/cc0/
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.zip.ZipInputStream
import android.webkit.WebResourceResponse
import androidx.webkit.WebViewAssetLoader
// WebView Asset PathHandler that returns contents of a zip archive.
class ZipArchivePathHandler(private val zipArchiveBytes: ByteArray) : WebViewAssetLoader.PathHandler {
override fun handle(path: String): WebResourceResponse? {
val bs = ByteArrayInputStream(zipArchiveBytes)
val zs = ZipInputStream(bs)
while(true) {
val entry = zs.nextEntry ?: break
if (entry.name == path) {
if (entry.size > Int.MAX_VALUE)
return WebResourceResponse("text/html", "utf-8", 500, "Internal Error", mapOf(), ByteArrayInputStream("Internal Error: compressed zip entry ${entry.name} has bloated size: ${entry.size}".toByteArray()))
// huh, entry.size is not really available??
val os = ByteArrayOutputStream(4096)
val bytes = ByteArray(4096)
while (true) {
val size = zs.read(bytes, 0, bytes.size)
if (size < 0)
break
os.write(bytes, 0, size)
}
return WebResourceResponse(
MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)),
"utf-8",
ByteArrayInputStream(os.toByteArray()))
}
}
return WebResourceResponse("text/html", "utf-8", 404, "Not Found", mapOf(), ByteArrayInputStream("Not found".toByteArray()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment