import android.content.Context
import android.os.Handler
import android.os.Looper
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.CountDownLatch

interface AntiDDOSCookiesStorage {
    fun saveCookie(cookie: String)
    fun loadCookie(): String?
}

class AntiDdosInterceptor(private val context: Context, private val cookiesStorage: AntiDDOSCookiesStorage) : Interceptor {
    companion object {
        const val TARGET_STRING = "SomeLongString"
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        var savedCookies = cookiesStorage.loadCookie()

        if (savedCookies == null) {
            loadPageWithWebView(originalRequest.url.toString())
            savedCookies = cookiesStorage.loadCookie()
        }

        val requestWithCookies = originalRequest.newBuilder()
            .header("Cookie", savedCookies ?: "")
            .build()

        var response = chain.proceed(requestWithCookies)

        if (!response.body?.string()?.contains(TARGET_STRING) == true) {
            // If TARGET_STRING is not found, repeat the process
            response.close()
            loadPageWithWebView(originalRequest.url.toString())
            savedCookies = cookiesStorage.loadCookie()
            val newRequestWithCookies = originalRequest.newBuilder()
                .header("Cookie", savedCookies ?: "")
                .build()
            response = chain.proceed(newRequestWithCookies)
        }

        return response
    }

    private fun loadPageWithWebView(url: String) {
        val latch = CountDownLatch(1)

        Handler(Looper.getMainLooper()).post {
            val webView = WebView(context)
            val webSettings: WebSettings = webView.settings
            webSettings.javaScriptEnabled = true
            webView.webViewClient = object : WebViewClient() {
                override fun onPageFinished(view: WebView?, url: String?) {
                    val cookieManager = CookieManager.getInstance()
                    val cookies = cookieManager.getCookie(url)
                    cookiesStorage.saveCookie(cookies)
                    latch.countDown()
                }
            }

            webView.loadUrl(url)
        }

        try {
            latch.await()
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }
}

Изменить пасту