Handle CloudFlare protection #13

This commit is contained in:
Koitharu
2020-11-07 17:50:08 +02:00
parent e2b65f6fb6
commit 17c20b2bf9
5 changed files with 34 additions and 3 deletions

View File

@@ -0,0 +1,5 @@
package org.koitharu.kotatsu.core.exceptions
import okio.IOException
class CloudFlareProtectedException(val url: String) : IOException("Protected by CloudFlare")

View File

@@ -0,0 +1,26 @@
package org.koitharu.kotatsu.core.network
import okhttp3.Interceptor
import okhttp3.Response
import org.koitharu.kotatsu.core.exceptions.CloudFlareProtectedException
import java.net.HttpURLConnection.HTTP_FORBIDDEN
import java.net.HttpURLConnection.HTTP_UNAVAILABLE
class CloudFlareInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
if (response.code == HTTP_FORBIDDEN || response.code == HTTP_UNAVAILABLE) {
if (response.header(HEADER_SERVER)?.startsWith(SERVER_CLOUDFLARE) == true) {
throw CloudFlareProtectedException(chain.request().url.toString())
}
}
return response
}
private companion object {
private const val HEADER_SERVER = "Server"
private const val SERVER_CLOUDFLARE = "cloudflare"
}
}

View File

@@ -7,7 +7,6 @@ import org.koin.dsl.module
import org.koitharu.kotatsu.core.network.cookies.PersistentCookieJar
import org.koitharu.kotatsu.core.network.cookies.cache.SetCookieCache
import org.koitharu.kotatsu.core.network.cookies.persistence.SharedPrefsCookiePersistor
import org.koitharu.kotatsu.core.parser.UserAgentInterceptor
import org.koitharu.kotatsu.utils.CacheUtils
import java.util.concurrent.TimeUnit
@@ -27,6 +26,7 @@ val networkModule
cookieJar(get())
cache(CacheUtils.createHttpCache(androidContext()))
addInterceptor(UserAgentInterceptor())
addInterceptor(CloudFlareInterceptor())
}.build()
}
}

View File

@@ -1,4 +1,4 @@
package org.koitharu.kotatsu.core.parser
package org.koitharu.kotatsu.core.network
import android.os.Build
import okhttp3.Interceptor

View File

@@ -12,7 +12,7 @@ import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.get
import org.koitharu.kotatsu.core.model.MangaSource
import org.koitharu.kotatsu.core.parser.UserAgentInterceptor
import org.koitharu.kotatsu.core.network.UserAgentInterceptor
import org.koitharu.kotatsu.core.prefs.SourceSettings
import org.koitharu.kotatsu.domain.MangaLoaderContext
import org.koitharu.kotatsu.utils.AssertX