Yokan / rebuild
Course 1 8624561

OkHttpExtensions.kt

vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/OkHttpExtensions.kt

implementation174 lines
1package eu.kanade.tachiyomi.network23import kotlinx.coroutines.ExperimentalCoroutinesApi4import kotlinx.coroutines.suspendCancellableCoroutine5import okhttp3.Call6import okhttp3.Callback7import okhttp3.Cookie8import okhttp3.HttpUrl9import okhttp3.OkHttpClient10import okhttp3.Request11import okhttp3.Response12import rx.Observable13import rx.Producer14import rx.Subscription15import java.io.IOException16import java.net.HttpCookie17import java.util.concurrent.atomic.AtomicBoolean18import kotlin.coroutines.resumeWithException1920// Based on https://github.com/gildor/kotlin-coroutines-okhttp21@OptIn(ExperimentalCoroutinesApi::class)22private suspend fun Call.await(callStack: Array<StackTraceElement>): Response {23    return suspendCancellableCoroutine { continuation ->24        val callback =25            object : Callback {26                override fun onResponse(27                    call: Call,28                    response: Response,29                ) {30                    continuation.resume(response) { cause, value, context ->31                        value.body.close()32                    }33                }3435                override fun onFailure(36                    call: Call,37                    e: IOException,38                ) {39                    // Don't bother with resuming the continuation if it is already cancelled.40                    if (continuation.isCancelled) return41                    val exception = IOException(e.message, e).apply { stackTrace = callStack }42                    continuation.resumeWithException(exception)43                }44            }4546        enqueue(callback)4748        continuation.invokeOnCancellation {49            try {50                cancel()51            } catch (ex: Throwable) {52                // Ignore cancel exception53            }54        }55    }56}5758suspend fun Call.await(): Response {59    val callStack = Exception().stackTrace.run { copyOfRange(1, size) }60    return await(callStack)61}6263/**64 * @since extensions-lib 1565 */66suspend fun Call.awaitSuccess(): Response {67    val callStack = Exception().stackTrace.run { copyOfRange(1, size) }68    val response = await(callStack)69    if (!response.isSuccessful) {70        response.close()71        throw HttpException(response.code).apply { stackTrace = callStack }72    }73    return response74}7576@Suppress("unused_parameter", "UnusedParameter")77fun OkHttpClient.newCachelessCallWithProgress(78    request: Request,79    listener: ProgressListener,80): Call {81    val progressClient =82        newBuilder()83            .cache(null)84            .build()8586    return progressClient.newCall(request)87}8889fun Call.asObservable(): Observable<Response> {90    return Observable.unsafeCreate { subscriber ->91        // Since Call is a one-shot type, clone it for each new subscriber.92        val call = clone()9394        // Wrap the call in a helper which handles both unsubscription and backpressure.95        val requestArbiter =96            object : AtomicBoolean(), Producer, Subscription {97                override fun request(n: Long) {98                    if (n == 0L || !compareAndSet(false, true)) return99100                    try {101                        val response = call.execute()102                        if (!subscriber.isUnsubscribed) {103                            subscriber.onNext(response)104                            subscriber.onCompleted()105                        }106                    } catch (e: Exception) {107                        if (!subscriber.isUnsubscribed) {108                            subscriber.onError(e)109                        }110                    }111                }112113                override fun unsubscribe() {114                    call.cancel()115                }116117                override fun isUnsubscribed(): Boolean = call.isCanceled()118            }119120        subscriber.add(requestArbiter)121        subscriber.setProducer(requestArbiter)122    }123}124125fun Call.asObservableSuccess(): Observable<Response> =126    asObservable().doOnNext { response ->127        if (!response.isSuccessful) {128            response.close()129            throw HttpException(response.code)130        }131    }132133fun OkHttpClient.newCallWithProgress(134    request: Request,135    listener: ProgressListener,136): Call {137    val progressClient =138        newBuilder()139            .build()140141    return progressClient.newCall(request)142}143144class HttpException(145    val code: Int,146) : IllegalStateException("HTTP error $code")147148fun Cookie.toHttpCookie(url: HttpUrl): HttpCookie {149    val httpCookie = HttpCookie(name, value)150    httpCookie.domain = domain151    httpCookie.path = path152    httpCookie.secure = secure153    // httpCookie.httpOnly = httpOnly // private field154    if (expiresAt != Long.MAX_VALUE) {155        httpCookie.maxAge = (expiresAt - System.currentTimeMillis()) / 1000156    }157    return httpCookie158}159160fun HttpCookie.toCookie(url: HttpUrl): Cookie {161    val builder =162        Cookie163            .Builder()164            .name(name)165            .value(value)166    if (domain != null) builder.domain(domain)167    if (path != null) builder.path(path)168    if (secure) builder.secure()169    // if (httpOnly) builder.httpOnly() // private field170    if (maxAge > 0) {171        builder.expiresAt(System.currentTimeMillis() + maxAge * 1000)172    }173    return builder.build()174}175

Search chapters, reference and source filenames.