Merge Mihon 0.21.2 updates and use BookOasis updater
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
Build & Test / Build & Test App (push) Has been cancelled
Release / Extract tag name (push) Has been cancelled
Update website / update_website (release) Has been cancelled
Release / Build (push) Has been cancelled
Release / Build (FOSS) (push) Has been cancelled
Release / Create GitHub Release (push) Has been cancelled
This commit is contained in:
@@ -33,6 +33,8 @@ dependencies {
|
||||
api(libs.okhttp.dnsOverHttps)
|
||||
api(libs.okio)
|
||||
|
||||
api(libs.apollo)
|
||||
|
||||
implementation(libs.image.decoder)
|
||||
|
||||
implementation(libs.unifile)
|
||||
|
||||
@@ -7,7 +7,7 @@ import okhttp3.HttpUrl
|
||||
|
||||
class AndroidCookieJar : CookieJar {
|
||||
|
||||
private val manager = CookieManager.getInstance()
|
||||
private val manager by lazy { CookieManager.getInstance() }
|
||||
|
||||
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
|
||||
val urlString = url.toString()
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package eu.kanade.tachiyomi.network
|
||||
|
||||
import com.apollographql.apollo.api.ApolloResponse
|
||||
import com.apollographql.apollo.api.Operation
|
||||
import com.apollographql.apollo.exception.ApolloHttpException
|
||||
import com.apollographql.apollo.exception.ApolloNetworkException
|
||||
import logcat.LogPriority
|
||||
import tachiyomi.core.common.util.system.logcat
|
||||
|
||||
/**
|
||||
* Returns the result of calling [transform] with [data] if the GraphQL response had data present without errors,
|
||||
* otherwise logs the failure under [errorLog] and falls back to [default].
|
||||
*
|
||||
* Any [ApolloHttpException] is re-thrown as [HttpException] after logging the response body.
|
||||
* This behavior can be replaced with a custom handler by providing a non-null value to [onException]. Such a lambda
|
||||
* MUST close the [ApolloHttpException.body] properly to avoid sockets and other resources leaking.
|
||||
*
|
||||
* Other failures are logged and the result of calling [default] is returned.
|
||||
*
|
||||
* @param errorLog A log message which will be included with any exceptions or errors being logged.
|
||||
* @param default A lambda which provides a default value to be returned in place of the expected value when an
|
||||
* exception or error is found.
|
||||
* @param onException A handler for [ApolloHttpException]s. It MUST handle closing the response body to avoid resource
|
||||
* leaks. Defaults to throwing a [HttpException] with the same status code.
|
||||
* @param transform A transforming lambda for the GraphQL data received.
|
||||
*/
|
||||
fun <D : Operation.Data, R> ApolloResponse<D>.dataOrElse(
|
||||
errorLog: String,
|
||||
default: () -> R,
|
||||
onException: ((ApolloHttpException) -> Unit)? = null,
|
||||
transform: (D) -> R,
|
||||
): R {
|
||||
if (exception != null) {
|
||||
val e = exception!!
|
||||
if (e is ApolloHttpException) {
|
||||
val body = e.body?.use { it.readUtf8() }
|
||||
logcat(LogPriority.ERROR, throwable = e) { "$errorLog: $body" }
|
||||
if (onException != null) {
|
||||
onException(e)
|
||||
} else {
|
||||
throw HttpException(e.statusCode).apply { stackTrace = e.stackTrace }
|
||||
}
|
||||
}
|
||||
logcat(LogPriority.ERROR, throwable = e) { errorLog }
|
||||
// Don't mask connection/IO-related issues
|
||||
if (e is ApolloNetworkException && e.cause != null) {
|
||||
throw e.cause!!
|
||||
}
|
||||
} else if (!errors.isNullOrEmpty()) {
|
||||
val errorMessages = errors!!.joinToString(separator = "\n ", prefix = "\n ") { it.message }
|
||||
logcat(LogPriority.ERROR) { "$errorLog: $errorMessages" }
|
||||
} else if (data != null) {
|
||||
return transform(data!!)
|
||||
}
|
||||
return default()
|
||||
}
|
||||
@@ -5,7 +5,8 @@ import app.cash.quickjs.QuickJs
|
||||
import dev.zacsweers.metro.AppScope
|
||||
import dev.zacsweers.metro.Inject
|
||||
import dev.zacsweers.metro.SingleIn
|
||||
import tachiyomi.core.common.util.lang.withIOContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Util for evaluating JavaScript in sources.
|
||||
@@ -23,7 +24,7 @@ class JavaScriptEngine(context: Context) {
|
||||
* @param script JavaScript to execute.
|
||||
* @return Result of JavaScript code as a primitive type.
|
||||
*/
|
||||
suspend fun <T> evaluate(script: String): T = withIOContext {
|
||||
suspend fun <T> evaluate(script: String): T = withContext(Dispatchers.Default) {
|
||||
QuickJs.create().use {
|
||||
it.evaluate(script) as T
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import dev.zacsweers.metro.SingleIn
|
||||
import eu.kanade.tachiyomi.network.interceptor.CloudflareInterceptor
|
||||
import eu.kanade.tachiyomi.network.interceptor.UncaughtExceptionInterceptor
|
||||
import eu.kanade.tachiyomi.network.interceptor.UserAgentInterceptor
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import mihon.core.metro.AppCoroutineScope
|
||||
import okhttp3.Cache
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
@@ -17,13 +19,14 @@ import kotlin.time.Duration.Companion.seconds
|
||||
@Inject
|
||||
@SingleIn(AppScope::class)
|
||||
class NetworkHelper(
|
||||
@AppCoroutineScope private val scope: CoroutineScope,
|
||||
private val context: Context,
|
||||
private val preferences: NetworkPreferences,
|
||||
) {
|
||||
|
||||
val cookieJar = AndroidCookieJar()
|
||||
|
||||
private val clientBuilder: OkHttpClient.Builder = run {
|
||||
private fun clientBuilder(): OkHttpClient.Builder = run {
|
||||
val builder = OkHttpClient.Builder()
|
||||
.cookieJar(cookieJar)
|
||||
.connectTimeout(30.seconds)
|
||||
@@ -62,18 +65,20 @@ class NetworkHelper(
|
||||
}
|
||||
}
|
||||
|
||||
val client = clientBuilder
|
||||
.addInterceptor(
|
||||
CloudflareInterceptor(context, cookieJar, ::defaultUserAgentProvider),
|
||||
)
|
||||
.build()
|
||||
val client: OkHttpClient by lazy {
|
||||
clientBuilder()
|
||||
.addInterceptor(
|
||||
CloudflareInterceptor(context, cookieJar, scope, ::defaultUserAgentProvider),
|
||||
)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Since extension-lib 1.5
|
||||
*/
|
||||
@Deprecated("The regular client handles Cloudflare by default")
|
||||
@Suppress("UNUSED")
|
||||
val cloudflareClient: OkHttpClient = client
|
||||
val cloudflareClient: OkHttpClient get() = client
|
||||
|
||||
fun defaultUserAgentProvider() = preferences.defaultUserAgent.get().trim()
|
||||
}
|
||||
|
||||
+151
-46
@@ -3,33 +3,56 @@ package eu.kanade.tachiyomi.network.interceptor
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.RenderProcessGoneDetail
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import android.widget.Toast
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.webkit.ScriptHandler
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import eu.kanade.tachiyomi.network.AndroidCookieJar
|
||||
import eu.kanade.tachiyomi.util.system.isOutdated
|
||||
import eu.kanade.tachiyomi.util.system.toast
|
||||
import okhttp3.Cookie
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import logcat.LogPriority
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import tachiyomi.core.common.i18n.stringResource
|
||||
import tachiyomi.core.common.util.system.logcat
|
||||
import tachiyomi.i18n.MR
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock
|
||||
import kotlin.concurrent.read
|
||||
import kotlin.concurrent.write
|
||||
|
||||
class CloudflareInterceptor(
|
||||
private val context: Context,
|
||||
private val cookieManager: AndroidCookieJar,
|
||||
scope: CoroutineScope,
|
||||
defaultUserAgentProvider: () -> String,
|
||||
) : WebViewInterceptor(context, defaultUserAgentProvider) {
|
||||
) : WebViewInterceptor(context, scope, defaultUserAgentProvider) {
|
||||
|
||||
private val executor = ContextCompat.getMainExecutor(context)
|
||||
|
||||
// Requests to a host share its lock while a challenge is solved under it alone, so concurrent requests wait for
|
||||
// one WebView instead of each opening their own
|
||||
private val hostLocks = ConcurrentHashMap<String, ReentrantReadWriteLock>()
|
||||
|
||||
private val listenerScript = """
|
||||
addEventListener("message", ({data}) => {
|
||||
if (data?.source === "cloudflare-challenge") {
|
||||
mihon?.postMessage(data.event);
|
||||
}
|
||||
})
|
||||
""".trimIndent()
|
||||
|
||||
override fun shouldIntercept(response: Response): Boolean {
|
||||
// Check if Cloudflare anti-bot is on
|
||||
// Checking the cf-mitigated header is the official way to detect a Cloudflare challenge:
|
||||
@@ -37,19 +60,50 @@ class CloudflareInterceptor(
|
||||
return response.header("cf-mitigated") == "challenge" && response.header("Server") in SERVER_CHECK
|
||||
}
|
||||
|
||||
override fun intercept(
|
||||
chain: Interceptor.Chain,
|
||||
request: Request,
|
||||
response: Response,
|
||||
): Response {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request()
|
||||
val lock = hostLocks.computeIfAbsent(request.url.host) { ReentrantReadWriteLock() }
|
||||
|
||||
val (response, clearance) = lock.read {
|
||||
val response = chain.proceed(request)
|
||||
if (!shouldIntercept(response)) return response
|
||||
response to clearance(request.url)
|
||||
}
|
||||
|
||||
// write releases the read hold of a request made from within another to the same host, like an extension
|
||||
// refreshing a token, which would otherwise wait on itself
|
||||
lock.write {
|
||||
// Another request may have solved the challenge while this one waited
|
||||
if (isCleared(request.url, clearance)) {
|
||||
response.close()
|
||||
} else {
|
||||
if (!prepareWebView()) return response
|
||||
solve(request, response, clearance)
|
||||
}
|
||||
}
|
||||
|
||||
return chain.proceed(request)
|
||||
}
|
||||
|
||||
override fun intercept(chain: Interceptor.Chain, request: Request, response: Response): Response {
|
||||
solve(request, response, clearance(request.url))
|
||||
return chain.proceed(request)
|
||||
}
|
||||
|
||||
private fun clearance(url: HttpUrl): String? {
|
||||
return cookieManager.get(url).firstOrNull { it.name == "cf_clearance" }?.value
|
||||
}
|
||||
|
||||
private fun isCleared(url: HttpUrl, previousClearance: String?): Boolean {
|
||||
val clearance = clearance(url)
|
||||
return !clearance.isNullOrBlank() && clearance != previousClearance
|
||||
}
|
||||
|
||||
private fun solve(request: Request, response: Response, clearance: String?) {
|
||||
try {
|
||||
response.close()
|
||||
cookieManager.remove(request.url, COOKIE_NAMES, 0)
|
||||
val oldCookie = cookieManager.get(request.url)
|
||||
.firstOrNull { it.name == "cf_clearance" }
|
||||
resolveWithWebView(request, oldCookie)
|
||||
|
||||
return chain.proceed(request)
|
||||
resolveWithWebView(request, clearance)
|
||||
}
|
||||
// Because OkHttp's enqueue only handles IOExceptions, wrap the exception so that
|
||||
// we don't crash the entire app
|
||||
@@ -61,64 +115,84 @@ class CloudflareInterceptor(
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
private fun resolveWithWebView(originalRequest: Request, oldCookie: Cookie?) {
|
||||
private fun resolveWithWebView(originalRequest: Request, originalClearance: String?) {
|
||||
// We need to lock this thread until the WebView finds the challenge solution url, because
|
||||
// OkHttp doesn't support asynchronous interceptors.
|
||||
val latch = CountDownLatch(1)
|
||||
|
||||
var webview: WebView? = null
|
||||
var listenerScriptHandler: ScriptHandler? = null
|
||||
val useIsolatedWorld = WebViewFeature.isFeatureSupported(WebViewFeature.JS_INJECTION_IN_FRAME_AND_WORLD)
|
||||
|
||||
var challengeFound = false
|
||||
var cloudflareBypassed = false
|
||||
var challengeFailed = false
|
||||
var isWebViewOutdated = false
|
||||
var isRenderProcessGone = false
|
||||
|
||||
val origRequestUrl = originalRequest.url.toString()
|
||||
// A WebView can only load a page with GET, and loading the url of another method usually reaches an
|
||||
// endpoint that answers GET without a challenge to solve. The clearance covers the whole site, so it's
|
||||
// earned on the site's root page instead.
|
||||
val challengeUrl = if (originalRequest.method == "GET") {
|
||||
origRequestUrl
|
||||
} else {
|
||||
originalRequest.url.newBuilder().encodedPath("/").query(null).fragment(null).build().toString()
|
||||
}
|
||||
val headers = parseHeaders(originalRequest.headers)
|
||||
|
||||
executor.execute {
|
||||
webview = createWebView(originalRequest)
|
||||
|
||||
webview.addJavascriptInterface(
|
||||
object {
|
||||
@Suppress("unused")
|
||||
@JavascriptInterface
|
||||
fun interactiveDetected() {
|
||||
// The challenge cannot be solved non-interactively, abort.
|
||||
fun onChallengeEvent(event: String) {
|
||||
when (event) {
|
||||
// The challenge cannot be solved non-interactively, abort.
|
||||
"interactiveBegin" -> latch.countDown()
|
||||
"fail" -> {
|
||||
challengeFailed = true
|
||||
latch.countDown()
|
||||
}
|
||||
},
|
||||
"mihon",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (useIsolatedWorld) {
|
||||
// An isolated world keeps the bridge out of the page's reach
|
||||
val world = WebViewCompat.getExecutionWorld(webview, "mihon")
|
||||
val origins = setOf(originalRequest.url.origin())
|
||||
WebViewCompat.addWebMessageListener(webview, "mihon", origins, world) { _, message, _, isMainFrame, _ ->
|
||||
if (isMainFrame) message.data?.let(::onChallengeEvent)
|
||||
}
|
||||
listenerScriptHandler = WebViewCompat.addJavaScriptOnEvent(
|
||||
webview,
|
||||
listenerScript,
|
||||
WebViewCompat.INJECTION_EVENT_DOCUMENT_START,
|
||||
origins,
|
||||
world,
|
||||
)
|
||||
} else {
|
||||
webview.addJavascriptInterface(
|
||||
object {
|
||||
@Suppress("unused")
|
||||
@JavascriptInterface
|
||||
fun postMessage(event: String) = onChallengeEvent(event)
|
||||
},
|
||||
"mihon",
|
||||
)
|
||||
}
|
||||
|
||||
webview.webViewClient = object : WebViewClient() {
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
fun isCloudFlareBypassed(): Boolean {
|
||||
return cookieManager.get(origRequestUrl.toHttpUrl())
|
||||
.firstOrNull { it.name == "cf_clearance" }
|
||||
.let { it != null && it != oldCookie }
|
||||
}
|
||||
|
||||
if (isCloudFlareBypassed()) {
|
||||
if (!challengeFailed && isCleared(originalRequest.url, originalClearance)) {
|
||||
cloudflareBypassed = true
|
||||
latch.countDown()
|
||||
}
|
||||
|
||||
if (url == origRequestUrl) {
|
||||
if (url == challengeUrl) {
|
||||
if (!challengeFound) {
|
||||
// The first request didn't return the challenge, abort.
|
||||
latch.countDown()
|
||||
} else {
|
||||
// Listen for an interactiveBegin event
|
||||
view.evaluateJavascript(
|
||||
"""
|
||||
addEventListener("message", ({data}) => {
|
||||
if (data?.source === "cloudflare-challenge" && data?.event === "interactiveBegin") {
|
||||
mihon.interactiveDetected();
|
||||
}
|
||||
})
|
||||
""".trimIndent(),
|
||||
null,
|
||||
)
|
||||
} else if (!useIsolatedWorld) {
|
||||
view.evaluateJavascript(listenerScript, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,26 +212,52 @@ class CloudflareInterceptor(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
||||
// Not handling it kills the app, failing the bypass is enough
|
||||
logcat(LogPriority.ERROR) {
|
||||
"WebView renderer gone during Cloudflare bypass: crashed=${detail.didCrash()}, " +
|
||||
"priority=${detail.rendererPriorityAtExit()}, url=$origRequestUrl"
|
||||
}
|
||||
isRenderProcessGone = true
|
||||
latch.countDown()
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
webview.loadUrl(origRequestUrl, headers)
|
||||
webview.loadUrl(challengeUrl, headers)
|
||||
}
|
||||
|
||||
latch.awaitFor30Seconds()
|
||||
|
||||
executor.execute {
|
||||
if (!cloudflareBypassed) {
|
||||
// Only destroy can be called on a WebView whose renderer is gone
|
||||
if (!cloudflareBypassed && !isRenderProcessGone) {
|
||||
isWebViewOutdated = webview?.isOutdated() == true
|
||||
}
|
||||
|
||||
webview?.run {
|
||||
stopLoading()
|
||||
if (!isRenderProcessGone) {
|
||||
if (useIsolatedWorld) {
|
||||
WebViewCompat.removeWebMessageListener(
|
||||
this,
|
||||
WebViewCompat.getExecutionWorld(this, "mihon"),
|
||||
"mihon",
|
||||
)
|
||||
} else {
|
||||
removeJavascriptInterface("mihon")
|
||||
}
|
||||
listenerScriptHandler?.remove()
|
||||
stopLoading()
|
||||
}
|
||||
destroy()
|
||||
}
|
||||
}
|
||||
|
||||
// Throw exception if we failed to bypass Cloudflare
|
||||
if (!cloudflareBypassed) {
|
||||
// A clearance from a failed challenge would only be rejected again
|
||||
cookieManager.remove(originalRequest.url, COOKIE_NAMES, 0)
|
||||
// Prompt user to update WebView if it seems too outdated
|
||||
if (isWebViewOutdated) {
|
||||
context.toast(MR.strings.information_webview_outdated, Toast.LENGTH_LONG)
|
||||
@@ -168,6 +268,11 @@ class CloudflareInterceptor(
|
||||
}
|
||||
}
|
||||
|
||||
// An origin rule without a port only matches the scheme's default one
|
||||
private fun HttpUrl.origin(): String {
|
||||
return if (port == HttpUrl.defaultPort(scheme)) "$scheme://$host" else "$scheme://$host:$port"
|
||||
}
|
||||
|
||||
private val SERVER_CHECK = arrayOf("cloudflare-nginx", "cloudflare")
|
||||
private val COOKIE_NAMES = listOf("cf_clearance")
|
||||
|
||||
|
||||
+19
-8
@@ -10,11 +10,13 @@ import eu.kanade.tachiyomi.util.system.WebViewUtil
|
||||
import eu.kanade.tachiyomi.util.system.setDefaultSettings
|
||||
import eu.kanade.tachiyomi.util.system.setUserAgent
|
||||
import eu.kanade.tachiyomi.util.system.toast
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.Headers
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import tachiyomi.core.common.util.lang.launchUI
|
||||
import tachiyomi.i18n.MR
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.CountDownLatch
|
||||
@@ -22,6 +24,7 @@ import java.util.concurrent.TimeUnit
|
||||
|
||||
abstract class WebViewInterceptor(
|
||||
private val context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
private val defaultUserAgentProvider: () -> String,
|
||||
) : Interceptor {
|
||||
|
||||
@@ -56,17 +59,25 @@ abstract class WebViewInterceptor(
|
||||
return response
|
||||
}
|
||||
|
||||
if (!WebViewUtil.supportsWebView(context)) {
|
||||
launchUI {
|
||||
context.toast(MR.strings.information_webview_required, Toast.LENGTH_LONG)
|
||||
}
|
||||
return response
|
||||
}
|
||||
initWebView
|
||||
if (!prepareWebView()) return response
|
||||
|
||||
return intercept(chain, request, response)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a WebView can be used, initializing it if so.
|
||||
*/
|
||||
protected fun prepareWebView(): Boolean {
|
||||
if (!WebViewUtil.supportsWebView(context)) {
|
||||
scope.launch(Dispatchers.Main) {
|
||||
context.toast(MR.strings.information_webview_required, Toast.LENGTH_LONG)
|
||||
}
|
||||
return false
|
||||
}
|
||||
initWebView
|
||||
return true
|
||||
}
|
||||
|
||||
fun parseHeaders(headers: Headers): Map<String, String> {
|
||||
return headers
|
||||
// Keeping unsafe header makes webview throw [net::ERR_INVALID_ARGUMENT]
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package mihon.core.common.extensions
|
||||
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Reads epoch milliseconds from a format that writes 0 for a time it doesn't know, such as the source API, a tracker
|
||||
* or a backup.
|
||||
*/
|
||||
fun Long.toInstantOrNull(): Instant? = takeIf { it != 0L }?.let(Instant::fromEpochMilliseconds)
|
||||
|
||||
/**
|
||||
* Writes epoch milliseconds to a format that takes 0 for a time it doesn't know.
|
||||
*/
|
||||
fun Instant?.toEpochMillisOrZero(): Long = this?.toEpochMilliseconds() ?: 0L
|
||||
@@ -1,5 +1,6 @@
|
||||
package mihon.core.common.extensions
|
||||
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
val JsonObjectEmpty = JsonObject(emptyMap())
|
||||
@@ -8,3 +9,7 @@ val JsonObjectEmptyBytes = byteArrayOf(0x7B, 0x7D)
|
||||
|
||||
val JsonObject.Companion.EMPTY: JsonObject
|
||||
inline get() = JsonObjectEmpty
|
||||
|
||||
fun JsonObject.toByteArray(): ByteArray = toString().encodeToByteArray()
|
||||
|
||||
fun ByteArray.toJsonObject(): JsonObject = Json.decodeFromString<JsonObject>(decodeToString())
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package tachiyomi.core.common.util.lang
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Think twice before using this. This is a delicate API. It is easy to accidentally create resource or memory leaks when GlobalScope is used.
|
||||
*
|
||||
* **Possible replacements**
|
||||
* - suspend function
|
||||
* - custom scope like view or presenter scope
|
||||
*/
|
||||
@DelicateCoroutinesApi
|
||||
fun launchUI(block: suspend CoroutineScope.() -> Unit): Job =
|
||||
GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT, block)
|
||||
|
||||
/**
|
||||
* Think twice before using this. This is a delicate API. It is easy to accidentally create resource or memory leaks when GlobalScope is used.
|
||||
*
|
||||
* **Possible replacements**
|
||||
* - suspend function
|
||||
* - custom scope like view or presenter scope
|
||||
*/
|
||||
@DelicateCoroutinesApi
|
||||
fun launchIO(block: suspend CoroutineScope.() -> Unit): Job =
|
||||
GlobalScope.launch(Dispatchers.IO, CoroutineStart.DEFAULT, block)
|
||||
|
||||
/**
|
||||
* Think twice before using this. This is a delicate API. It is easy to accidentally create resource or memory leaks when GlobalScope is used.
|
||||
*
|
||||
* **Possible replacements**
|
||||
* - suspend function
|
||||
* - custom scope like view or presenter scope
|
||||
*/
|
||||
@DelicateCoroutinesApi
|
||||
fun launchNow(block: suspend CoroutineScope.() -> Unit): Job =
|
||||
GlobalScope.launch(Dispatchers.Main, CoroutineStart.UNDISPATCHED, block)
|
||||
|
||||
fun CoroutineScope.launchUI(block: suspend CoroutineScope.() -> Unit): Job =
|
||||
launch(Dispatchers.Main, block = block)
|
||||
|
||||
fun CoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit): Job =
|
||||
launch(Dispatchers.IO, block = block)
|
||||
|
||||
fun CoroutineScope.launchNonCancellable(block: suspend CoroutineScope.() -> Unit): Job =
|
||||
launchIO { withContext(NonCancellable, block) }
|
||||
|
||||
suspend fun <T> withUIContext(block: suspend CoroutineScope.() -> T) = withContext(
|
||||
Dispatchers.Main,
|
||||
block,
|
||||
)
|
||||
|
||||
suspend fun <T> withIOContext(block: suspend CoroutineScope.() -> T) = withContext(
|
||||
Dispatchers.IO,
|
||||
block,
|
||||
)
|
||||
|
||||
suspend fun <T> withNonCancellableContext(block: suspend CoroutineScope.() -> T) =
|
||||
withContext(NonCancellable, block)
|
||||
@@ -0,0 +1,60 @@
|
||||
package tachiyomi.core.common.util.lang
|
||||
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingCommand
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.conflate
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.emitAll
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlin.coroutines.AbstractCoroutineContextElement
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlin.time.Duration
|
||||
|
||||
/**
|
||||
* Keeps a view model's flows running while its screen is hidden, but holds back database and other frequent
|
||||
* updates until the screen is visible again, so returning to it shows the last state instead of re-running
|
||||
* everything. Flows collected without a gate in their context are unaffected.
|
||||
*/
|
||||
class SubscriberGate : AbstractCoroutineContextElement(SubscriberGate) {
|
||||
|
||||
companion object Key : CoroutineContext.Key<SubscriberGate>
|
||||
|
||||
private val open = MutableStateFlow(true)
|
||||
|
||||
fun whileSubscribed(stopTimeout: Duration): SharingStarted = object : SharingStarted {
|
||||
override fun command(subscriptionCount: StateFlow<Int>): Flow<SharingCommand> = flow {
|
||||
emit(SharingCommand.START)
|
||||
subscriptionCount
|
||||
.map { it > 0 }
|
||||
.distinctUntilChanged()
|
||||
.collectLatest { subscribed ->
|
||||
if (!subscribed) delay(stopTimeout)
|
||||
open.value = subscribed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun awaitOpen() {
|
||||
open.first { it }
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> Flow<T>.pausedWhileUnsubscribed(): Flow<T> = flow {
|
||||
val gate = currentCoroutineContext()[SubscriberGate]
|
||||
if (gate == null) {
|
||||
emitAll(this@pausedWhileUnsubscribed)
|
||||
} else {
|
||||
this@pausedWhileUnsubscribed.conflate().collect {
|
||||
gate.awaitOpen()
|
||||
emit(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,15 +47,16 @@ object ImageUtil {
|
||||
|
||||
fun findImageType(stream: InputStream): ImageType? {
|
||||
return try {
|
||||
val format = ImageDecoder.new(stream).use { dec -> dec.format }
|
||||
val format = ImageDecoder.open(stream).use { dec -> dec.format }
|
||||
when (format) {
|
||||
"jpeg" -> ImageType.JPEG
|
||||
"png" -> ImageType.PNG
|
||||
"webp" -> ImageType.WEBP
|
||||
"gif" -> ImageType.GIF
|
||||
"heif" -> ImageType.HEIF
|
||||
"jxl" -> ImageType.JXL
|
||||
"jp2" -> ImageType.JP2
|
||||
ImageDecoder.Format.JPEG -> ImageType.JPEG
|
||||
ImageDecoder.Format.PNG -> ImageType.PNG
|
||||
ImageDecoder.Format.WEBP -> ImageType.WEBP
|
||||
ImageDecoder.Format.GIF -> ImageType.GIF
|
||||
ImageDecoder.Format.AVIF -> ImageType.AVIF
|
||||
ImageDecoder.Format.HEIF -> ImageType.HEIF
|
||||
ImageDecoder.Format.JXL -> ImageType.JXL
|
||||
ImageDecoder.Format.JP2 -> ImageType.JP2
|
||||
else -> null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
@@ -76,7 +77,7 @@ object ImageUtil {
|
||||
ImageType.GIF -> true
|
||||
ImageType.WEBP, ImageType.HEIF -> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return false
|
||||
ImageDecoder.new(source.peek().inputStream()).use { dec -> dec.pages > 1 }
|
||||
ImageDecoder.open(source.peek().inputStream()).use { dec -> dec.pages > 1 }
|
||||
}
|
||||
|
||||
else -> false
|
||||
@@ -303,10 +304,13 @@ object ImageUtil {
|
||||
*/
|
||||
fun chooseBackground(context: Context, imageStream: InputStream): Drawable {
|
||||
val image = try {
|
||||
ImageDecoder.new(imageStream).use { it.decode() }.let { res ->
|
||||
createBitmap(res.width, res.height).also { bitmap ->
|
||||
res.image.rewind()
|
||||
bitmap.copyPixelsFromBuffer(res.image)
|
||||
ImageDecoder.open(imageStream).use { it.decodeNext() to it.isHdr }.let { (res, hdr) ->
|
||||
res.use {
|
||||
val config = if (hdr) Bitmap.Config.RGBA_F16 else Bitmap.Config.ARGB_8888
|
||||
createBitmap(res.width, res.height, config).also { bitmap ->
|
||||
res.image.rewind()
|
||||
bitmap.copyPixelsFromBuffer(res.image)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
@@ -314,8 +318,16 @@ object ImageUtil {
|
||||
null
|
||||
}
|
||||
|
||||
if (image == null) return Color.WHITE.toDrawable()
|
||||
return try {
|
||||
chooseBackground(context, image)
|
||||
} finally {
|
||||
image.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun chooseBackground(context: Context, image: Bitmap): Drawable {
|
||||
val whiteColor = Color.WHITE
|
||||
if (image == null) return whiteColor.toDrawable()
|
||||
if (image.width < 50 || image.height < 50) {
|
||||
return whiteColor.toDrawable()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package mihon.core.metro
|
||||
|
||||
import dev.zacsweers.metro.Qualifier
|
||||
|
||||
/**
|
||||
* Qualifies the single application wide [kotlinx.coroutines.CoroutineScope].
|
||||
*
|
||||
* It lives for as long as the process does and is backed by a [kotlinx.coroutines.SupervisorJob] on
|
||||
* [kotlinx.coroutines.Dispatchers.IO], so a failure in one child never takes the others down. Use it for work that is
|
||||
* owned by an application scoped component and must outlive any screen. Work that belongs to a screen, a view model or
|
||||
* another cancellable lifecycle keeps its own scope.
|
||||
*
|
||||
* A child that fails with an uncaught exception is logged and reported instead of crashing the app, except in debug
|
||||
* builds, since by the time it fails the screen that started it may be long gone.
|
||||
*/
|
||||
@Qualifier
|
||||
@Target(
|
||||
AnnotationTarget.VALUE_PARAMETER,
|
||||
AnnotationTarget.FUNCTION,
|
||||
AnnotationTarget.PROPERTY,
|
||||
AnnotationTarget.PROPERTY_GETTER,
|
||||
)
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class AppCoroutineScope
|
||||
Reference in New Issue
Block a user