Manga Ship extension, DataImageInterceptor (#3177)

* Manga Ship extension, DataImageInterceptor

* tweak regex
This commit is contained in:
Mike
2020-05-18 22:30:26 -04:00
committed by GitHub
parent af17930c45
commit 7e9bb52cbc
12 changed files with 224 additions and 0 deletions

View File

@ -0,0 +1,30 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 27
buildToolsVersion '29.0.3'
defaultConfig {
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName '1.0.0'
}
buildTypes {
release {
minifyEnabled false
}
}
}
repositories {
mavenCentral()
}
dependencies {
compileOnly "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compileOnly 'com.squareup.okhttp3:okhttp:3.10.0'
compileOnly 'org.jsoup:jsoup:1.13.1'
}

View File

@ -0,0 +1,2 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="eu.kanade.tachiyomi.lib.dataimage" />

View File

@ -0,0 +1,65 @@
package eu.kanade.tachiyomi.lib.dataimage
import android.util.Base64
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody
import org.jsoup.nodes.Element
/**
* If a source provides images via a data:image string instead of a URL, use these functions and interceptor
*/
/**
* Use if the attribute tag could have a data:image string or URL
* Transforms data:image in to a fake URL that OkHttp won't die on
*/
fun Element.dataImageAsUrl(attr: String): String {
return if (this.attr(attr).startsWith("data")) {
"https://127.0.0.1/?" + this.attr(attr).substringAfter(":")
} else {
this.attr("abs:$attr")
}
}
/**
* Use if the attribute tag has a data:image string but real URLs are on a different attribute
*/
fun Element.dataImageAsUrlOrNull(attr: String): String? {
return if (this.attr(attr).startsWith("data")) {
"https://127.0.0.1/?" + this.attr(attr).substringAfter(":")
} else {
null
}
}
/**
* Interceptor that detects the URLs we created with the above functions, base64 decodes the data if necessary,
* and builds a response with a valid image that Tachiyomi can display
*/
class DataImageInterceptor : Interceptor {
private val mediaTypePattern = Regex("""(^[^;,]*)[;,]""")
override fun intercept(chain: Interceptor.Chain): Response {
val url = chain.request().url().toString()
return if (url.startsWith("https://127.0.0.1/?image")) {
val dataString = url.substringAfter("?")
val byteArray = if (dataString.contains("base64")) {
Base64.decode(dataString.substringAfter("base64,"), Base64.DEFAULT)
} else {
dataString.substringAfter(",").toByteArray()
}
val mediaType = MediaType.parse(mediaTypePattern.find(dataString)!!.value)
Response.Builder().body(ResponseBody.create(mediaType, byteArray))
.request(chain.request())
.protocol(Protocol.HTTP_1_0)
.code(200)
.message("")
.build()
} else {
chain.proceed(chain.request())
}
}
}