MemoryCookieJar.kt
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/MemoryCookieJar.kt
1package eu.kanade.tachiyomi.network23import okhttp3.Cookie4import okhttp3.CookieJar5import okhttp3.HttpUrl67class MemoryCookieJar : CookieJar {8 private val cache = mutableSetOf<WrappedCookie>()910 @Synchronized11 override fun loadForRequest(url: HttpUrl): List<Cookie> {12 val cookiesToRemove = mutableSetOf<WrappedCookie>()13 val validCookies = mutableSetOf<WrappedCookie>()1415 cache.forEach { cookie ->16 if (cookie.isExpired()) {17 cookiesToRemove.add(cookie)18 } else if (cookie.matches(url)) {19 validCookies.add(cookie)20 }21 }2223 cache.removeAll(cookiesToRemove)2425 return validCookies.toList().map(WrappedCookie::unwrap)26 }2728 @Synchronized29 override fun saveFromResponse(30 url: HttpUrl,31 cookies: List<Cookie>,32 ) {33 val cookiesToAdd = cookies.map { WrappedCookie.wrap(it) }3435 cache.removeAll(cookiesToAdd)36 cache.addAll(cookiesToAdd)37 }3839 @Synchronized40 fun clear() {41 cache.clear()42 }4344 @Synchronized45 fun addCookie(cookie: Cookie) {46 val wrapped = WrappedCookie.wrap(cookie)47 cache.remove(wrapped)48 cache.add(wrapped)49 }5051 @Synchronized52 fun addAll(53 url: HttpUrl,54 cookies: List<Cookie>,55 ) {56 cookies.forEach { addCookie(it) }57 }58}5960class WrappedCookie private constructor(61 val cookie: Cookie,62) {63 fun unwrap() = cookie6465 fun isExpired() = cookie.expiresAt < System.currentTimeMillis()6667 fun matches(url: HttpUrl) = cookie.matches(url)6869 override fun equals(other: Any?): Boolean {70 if (other !is WrappedCookie) return false7172 return other.cookie.name == cookie.name &&73 other.cookie.domain == cookie.domain &&74 other.cookie.path == cookie.path &&75 other.cookie.secure == cookie.secure &&76 other.cookie.hostOnly == cookie.hostOnly77 }7879 override fun hashCode(): Int {80 var hash = 1781 hash = 31 * hash + cookie.name.hashCode()82 hash = 31 * hash + cookie.domain.hashCode()83 hash = 31 * hash + cookie.path.hashCode()84 hash = 31 * hash + if (cookie.secure) 0 else 185 hash = 31 * hash + if (cookie.hostOnly) 0 else 186 return hash87 }8889 companion object {90 fun wrap(cookie: Cookie) = WrappedCookie(cookie)91 }92}93