Add useragent interceptor

This commit is contained in:
Mikołaj Pich 2018-12-16 16:15:57 +01:00
parent c30b213ce4
commit c0b9181b80
No known key found for this signature in database
GPG key ID: F62B26E36D4C4BAA
3 changed files with 45 additions and 5 deletions

View file

@ -2,6 +2,7 @@ package io.github.wulkanowy.api
import io.github.wulkanowy.api.interceptor.ErrorInterceptor
import io.github.wulkanowy.api.interceptor.NotLoggedInErrorInterceptor
import io.github.wulkanowy.api.interceptor.UserAgentInterceptor
import io.github.wulkanowy.api.messages.Folder
import io.github.wulkanowy.api.messages.Folder.*
import io.github.wulkanowy.api.messages.Message
@ -79,6 +80,13 @@ class Api {
var useNewStudent: Boolean = false
/**
* @see <a href="https://deviceatlas.com/blog/most-popular-android-smartphones#poland">The most popular Android phones - 2018</a>
* @see <a href="http://www.tera-wurfl.com/explore/?action=wurfl_id&id=samsung_sm_j500h_ver1">Tera-WURFL Explorer - Samsung SM-J500H (Galaxy J5)</a>
*/
var androidVersion: String = "5.1"
var buildTag: String = "SM-J500H Build/LMY48B"
enum class LoginType {
AUTO,
STANDARD,
@ -87,11 +95,14 @@ class Api {
ADFSLight
}
private val interceptors: HashMap<Interceptor, Boolean> = hashMapOf(
ErrorInterceptor() to false,
NotLoggedInErrorInterceptor(loginType) to false,
HttpLoggingInterceptor().setLevel(logLevel) to true
)
private val interceptors by lazy {
hashMapOf(
UserAgentInterceptor(androidVersion, buildTag) to false,
ErrorInterceptor() to false,
NotLoggedInErrorInterceptor(loginType) to false,
HttpLoggingInterceptor().setLevel(logLevel) to true
)
}
fun setInterceptor(interceptor: Interceptor, network: Boolean = false) {
interceptors[interceptor] = network

View file

@ -0,0 +1,27 @@
package io.github.wulkanowy.api.interceptor
import okhttp3.Interceptor
import okhttp3.Response
/**
* @see <a href="https://github.com/jhy/jsoup/blob/220b77140bce70dcf9c767f8f04758b09097db14/src/main/java/org/jsoup/helper/HttpConnection.java#L59">JSoup default user agent</a>
* @see <a href="https://developer.chrome.com/multidevice/user-agent#chrome_for_android_user_agent">User Agent Strings - Google Chrome</a>
*/
class UserAgentInterceptor(
private val androidVersion: String,
private val buildTag: String,
private val webKitRev: String = "537.36",
private val chromeRev: String = "71.0.3578.98"
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return chain.proceed(chain.request().newBuilder()
.addHeader("User-Agent",
"Mozilla/5.0 (Linux; $androidVersion; $buildTag) " +
"AppleWebKit/$webKitRev (KHTML, like Gecko) " +
"Chrome/$chromeRev Mobile " +
"Safari/$webKitRev")
.build()
)
}
}

View file

@ -49,6 +49,8 @@ class ApiRemoteTest : BaseTest() {
studentId = 1
diaryId = 101
useNewStudent = false
androidVersion = "7.1.1"
buildTag = "PIXEL"
setInterceptor(Interceptor {
println("Request event ${it.request().url().host()}")
it.proceed(it.request())