Maybe better handle MAL token expiration
This commit is contained in:
parent
b485e1d657
commit
08a6db7d6e
@ -11,9 +11,6 @@ class MyAnimeListInterceptor(private val myanimelist: MyAnimeList, private var t
|
|||||||
private val json: Json by injectLazy()
|
private val json: Json by injectLazy()
|
||||||
|
|
||||||
private var oauth: OAuth? = null
|
private var oauth: OAuth? = null
|
||||||
set(value) {
|
|
||||||
field = value?.copy(expires_in = System.currentTimeMillis() + (value.expires_in * 1000))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val originalRequest = chain.request()
|
val originalRequest = chain.request()
|
||||||
@ -24,21 +21,19 @@ class MyAnimeListInterceptor(private val myanimelist: MyAnimeList, private var t
|
|||||||
if (oauth == null) {
|
if (oauth == null) {
|
||||||
oauth = myanimelist.loadOAuth()
|
oauth = myanimelist.loadOAuth()
|
||||||
}
|
}
|
||||||
// Refresh access token if null or expired.
|
// Refresh access token if expired
|
||||||
if (oauth!!.isExpired()) {
|
if (oauth != null && oauth!!.isExpired()) {
|
||||||
chain.proceed(MyAnimeListApi.refreshTokenRequest(oauth!!.refresh_token)).use {
|
chain.proceed(MyAnimeListApi.refreshTokenRequest(oauth!!.refresh_token)).use {
|
||||||
if (it.isSuccessful) {
|
if (it.isSuccessful) {
|
||||||
setAuth(json.decodeFromString(it.body!!.string()))
|
setAuth(json.decodeFromString(it.body!!.string()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Throw on null auth.
|
|
||||||
if (oauth == null) {
|
if (oauth == null) {
|
||||||
throw Exception("No authentication token")
|
throw Exception("No authentication token")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add the authorization header to the original request.
|
// Add the authorization header to the original request
|
||||||
val authRequest = originalRequest.newBuilder()
|
val authRequest = originalRequest.newBuilder()
|
||||||
.addHeader("Authorization", "Bearer ${oauth!!.access_token}")
|
.addHeader("Authorization", "Bearer ${oauth!!.access_token}")
|
||||||
.build()
|
.build()
|
||||||
|
@ -7,8 +7,9 @@ data class OAuth(
|
|||||||
val refresh_token: String,
|
val refresh_token: String,
|
||||||
val access_token: String,
|
val access_token: String,
|
||||||
val token_type: String,
|
val token_type: String,
|
||||||
|
val created_at: Long = System.currentTimeMillis(),
|
||||||
val expires_in: Long
|
val expires_in: Long
|
||||||
) {
|
) {
|
||||||
|
|
||||||
fun isExpired() = System.currentTimeMillis() > expires_in
|
fun isExpired() = System.currentTimeMillis() > created_at + (expires_in * 1000)
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user