2
2
package com.adamratzman.spotify.http
3
3
4
4
import com.adamratzman.spotify.SpotifyApi
5
- import com.adamratzman.spotify.SpotifyAppApi
5
+ import com.adamratzman.spotify.SpotifyClientApi
6
6
import com.adamratzman.spotify.SpotifyException
7
+ import com.adamratzman.spotify.SpotifyException.BadRequestException
7
8
import com.adamratzman.spotify.SpotifyRestAction
8
9
import com.adamratzman.spotify.SpotifyRestActionPaging
9
10
import com.adamratzman.spotify.base
@@ -44,9 +45,10 @@ abstract class SpotifyEndpoint(val api: SpotifyApi<*, *>) {
44
45
body : String? = null,
45
46
method : HttpRequestMethod = HttpRequestMethod .GET ,
46
47
retry202 : Boolean = true,
47
- contentType : String? = null
48
+ contentType : String? = null,
49
+ attemptedRefresh : Boolean = false
48
50
): String {
49
- if (api is SpotifyAppApi && getCurrentTimeMs() >= api.expireTime) {
51
+ if (api is SpotifyClientApi && getCurrentTimeMs() >= api.expireTime) {
50
52
if (! api.automaticRefresh) throw SpotifyException .AuthenticationException (" The access token has expired." )
51
53
else api.refreshToken()
52
54
}
@@ -59,19 +61,32 @@ abstract class SpotifyEndpoint(val api: SpotifyApi<*, *>) {
59
61
cache - = spotifyRequest
60
62
}
61
63
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
+ }
75
90
}
76
91
77
92
private fun handleResponse (
0 commit comments