AquaStream/app/src/main/java/com/lagradost/cloudstream3/network/DdosGuardKiller.kt

59 lines
2.1 KiB
Kotlin
Raw Normal View History

2021-12-16 19:33:14 +00:00
package com.lagradost.cloudstream3.network
2021-12-16 20:18:47 +00:00
import androidx.annotation.AnyThread
import com.lagradost.cloudstream3.USER_AGENT
2021-12-16 19:33:14 +00:00
import com.lagradost.cloudstream3.app
import com.lagradost.nicehttp.Requests.Companion.await
import com.lagradost.nicehttp.getCookies
import kotlinx.coroutines.runBlocking
import okhttp3.Headers
import okhttp3.Headers.Companion.toHeaders
2021-12-16 19:33:14 +00:00
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
/**
* @param alwaysBypass will pre-emptively fetch ddos guard cookies if true.
* If false it will only try to get cookies when a request returns 403
* */
2021-12-16 20:18:47 +00:00
// As seen in https://github.com/anime-dl/anime-downloader/blob/master/anime_downloader/sites/erairaws.py
@AnyThread
2021-12-16 19:33:14 +00:00
class DdosGuardKiller(private val alwaysBypass: Boolean) : Interceptor {
val savedCookiesMap = mutableMapOf<String, Map<String, String>>()
2021-12-16 20:18:47 +00:00
private var ddosBypassPath: String? = null
2021-12-16 19:33:14 +00:00
override fun intercept(chain: Interceptor.Chain): Response = runBlocking {
2021-12-16 19:33:14 +00:00
val request = chain.request()
if (alwaysBypass) return@runBlocking bypassDdosGuard(request)
2021-12-16 19:33:14 +00:00
val response = chain.proceed(request)
return@runBlocking if (response.code == 403) {
2021-12-16 19:33:14 +00:00
bypassDdosGuard(request)
} else response
}
private suspend fun bypassDdosGuard(request: Request): Response {
2021-12-16 20:18:47 +00:00
ddosBypassPath = ddosBypassPath ?: Regex("'(.*?)'").find(
app.get(
"https://check.ddos-guard.net/check.js"
).text
)?.groupValues?.get(1)
2021-12-16 19:33:14 +00:00
val cookies =
savedCookiesMap[request.url.host]
// If no cookies are found fetch and save em.
?: (request.url.scheme + "://" + request.url.host + (ddosBypassPath ?: "")).let {
app.get(it, cacheTime = 0).cookies.also { cookies ->
savedCookiesMap[request.url.host] = cookies
}
2021-12-19 14:00:09 +00:00
}
2021-12-16 19:33:14 +00:00
val headers = getHeaders(request.headers.toMap(), cookies + request.cookies)
2021-12-16 19:33:14 +00:00
return app.baseClient.newCall(
request.newBuilder()
.headers(headers)
.build()
).await()
2021-12-16 19:33:14 +00:00
}
}