1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
|
<?php
declare(strict_types=1);
namespace TCB;
use TCB\Credentials;
use TCB\HttpServer;
use TCB\Request;
use TCB\Response;
use TCB\TokenStorage;
final class TokenManager
{
private string $authorisationCode;
public function __construct(
private readonly Credentials $credentials,
private readonly HttpServer $httpServer,
private readonly TokenStorage $storage,
) {}
public function getAccessToken(): string
{
if ($this->storage->accessToken === '' || $this->storage->refreshToken === '') {
$this->authorise();
$this->requestAccessToken();
}
if ($this->storage->expiresOn < time()) {
$this->refreshAccessToken();
}
return $this->storage->accessToken;
}
private function authorise(): void
{
$this->authorisationCode = '';
$this->httpServer->get(
'/callback',
function (Request $request, HttpServer $server): Response {
$server->closeAfterResponse();
if (
!array_key_exists('state', $request->params)
|| $request->params['state'] !== $this->credentials->state
) {
$body = 'State mismatch.';
} elseif (array_key_exists('error', $request->params)) {
$body = "Error from Spotify: {$request->params['error']}";
} elseif (!array_key_exists('code', $request->params)) {
$body = "Missing authorisation code from Spotify.";
} else {
$this->authorisationCode = $request->params['code'];
$body = 'Authorisation code received from Spotify. You can close this page and go back to the terminal.';
}
return new Response(
statusCode: 200,
contentType: 'text/plain; charset=UTF-8',
body: htmlspecialchars($body, ENT_QUOTES),
);
},
);
$query = http_build_query([
'response_type' => 'code',
'client_id' => $this->credentials->clientID,
'redirect_uri' => $this->credentials->redirectURI,
'state' => $this->credentials->state,
'scope' => 'playlist-read-private',
'show_dialog' => false,
]);
echo "Visit the below URL in your browser to authorise access to Spotify.\n";
echo "https://accounts.spotify.com/authorize?$query\n";
echo "Waiting for authorisation from Spotify...\n";
$this->httpServer->run();
if ($this->authorisationCode === '') {
echo "Failed to get authorisation code from Spotify.\n";
exit(1);
}
}
private function requestAccessToken(): void
{
echo "Requesting an access token from Spotify.\n";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://accounts.spotify.com/api/token',
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode($this->credentials->clientID . ':' . $this->credentials->clientSecret),
'Content-Type: application/x-www-form-urlencoded',
],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'authorization_code',
'code' => $this->authorisationCode,
'redirect_uri' => $this->credentials->redirectURI,
]),
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($statusCode !== 200) {
echo "Non 200 response from Spotify: $statusCode $response\n";
exit(1);
}
$data = json_decode($response, true) ?? [];
$accessToken = $data['access_token'] ?? '';
$refreshToken = $data['refresh_token'] ?? '';
$expiresIn = $data['expires_in'] ?? 0;
if ($accessToken === '' || $refreshToken === '') {
echo "Failed to get access token from Spotify.\n";
exit(1);
}
$this->storage->accessToken = $accessToken;
$this->storage->refreshToken = $refreshToken;
$this->storage->expiresOn = time() + $expiresIn;
$this->storage->save();
}
private function refreshAccessToken(): void
{
echo "Refreshing the Spotify access token.\n";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://accounts.spotify.com/api/token',
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Basic ' . base64_encode($this->credentials->clientID . ':' . $this->credentials->clientSecret),
'Content-Type: application/x-www-form-urlencoded',
],
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'refresh_token',
'refresh_token' => $this->storage->refreshToken,
]),
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($statusCode !== 200) {
echo "Non 200 response from Spotify: $statusCode $response\n";
exit(1);
}
$data = json_decode($response, true) ?? [];
$accessToken = $data['access_token'] ?? '';
$refreshToken = $data['refresh_token'] ?? $this->storage->refreshToken;
$expiresIn = $data['expires_in'] ?? 0;
if ($accessToken === '' || $refreshToken === '') {
echo "Failed to refresh the Spotify access token.\n";
exit(1);
}
$this->storage->accessToken = $accessToken;
$this->storage->refreshToken = $refreshToken;
$this->storage->expiresOn = time() + $expiresIn;
$this->storage->save();
}
}
|