Skip to content

Commit 9ea3f68

Browse files
committed
fix automatic token refresh for SpotifyClientApi, including with 401
1 parent 7f74495 commit 9ea3f68

File tree

1 file changed

+31
-16
lines changed
  • src/commonMain/kotlin/com.adamratzman.spotify/http

1 file changed

+31
-16
lines changed

src/commonMain/kotlin/com.adamratzman.spotify/http/Endpoints.kt

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
package com.adamratzman.spotify.http
33

44
import com.adamratzman.spotify.SpotifyApi
5-
import com.adamratzman.spotify.SpotifyAppApi
5+
import com.adamratzman.spotify.SpotifyClientApi
66
import com.adamratzman.spotify.SpotifyException
7+
import com.adamratzman.spotify.SpotifyException.BadRequestException
78
import com.adamratzman.spotify.SpotifyRestAction
89
import com.adamratzman.spotify.SpotifyRestActionPaging
910
import com.adamratzman.spotify.base
@@ -44,9 +45,10 @@ abstract class SpotifyEndpoint(val api: SpotifyApi<*, *>) {
4445
body: String? = null,
4546
method: HttpRequestMethod = HttpRequestMethod.GET,
4647
retry202: Boolean = true,
47-
contentType: String? = null
48+
contentType: String? = null,
49+
attemptedRefresh: Boolean = false
4850
): String {
49-
if (api is SpotifyAppApi && getCurrentTimeMs() >= api.expireTime) {
51+
if (api is SpotifyClientApi && getCurrentTimeMs() >= api.expireTime) {
5052
if (!api.automaticRefresh) throw SpotifyException.AuthenticationException("The access token has expired.")
5153
else api.refreshToken()
5254
}
@@ -59,19 +61,32 @@ abstract class SpotifyEndpoint(val api: SpotifyApi<*, *>) {
5961
cache -= spotifyRequest
6062
}
6163

62-
val document = createConnection(url, body, method, contentType).execute(
63-
cacheState?.eTag?.let {
64-
listOf(HttpHeader("If-None-Match", it))
65-
}
66-
)
67-
68-
return handleResponse(document, cacheState, spotifyRequest, retry202) ?: execute(
69-
url,
70-
body,
71-
method,
72-
false,
73-
contentType
74-
)
64+
return try {
65+
val document = createConnection(url, body, method, contentType).execute(
66+
cacheState?.eTag?.let {
67+
listOf(HttpHeader("If-None-Match", it))
68+
}
69+
)
70+
71+
handleResponse(document, cacheState, spotifyRequest, retry202) ?: execute(
72+
url,
73+
body,
74+
method,
75+
false,
76+
contentType
77+
)
78+
} catch (e: BadRequestException) {
79+
if (e.statusCode?.equals(401) == true && !attemptedRefresh) {
80+
execute(
81+
url,
82+
body,
83+
method,
84+
retry202,
85+
contentType,
86+
true
87+
)
88+
} else throw e
89+
}
7590
}
7691

7792
private fun handleResponse(

0 commit comments

Comments
 (0)