-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc.php
More file actions
492 lines (399 loc) · 13.7 KB
/
Copy pathfunc.php
File metadata and controls
492 lines (399 loc) · 13.7 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
<?php
/**
* Model of Access Token delivered by Spotify API
*/
readonly class AccessToken
{
public function __construct(
public string $value,
public string $type,
public string $expires_in,
public string $refresh_token,
) {}
}
/**
* Module containing all functions.
*/
require_once 'config.php';
/**
* Debugging function : var_dump $data only in DEBUG_MODE
*
* @param [type] ...$data
* @return void
*/
function dump(mixed ...$data): void
{
if (!defined('DEBUG_MODE') || DEBUG_MODE !== true) {
return;
}
foreach ($data as $value) {
var_dump($value);
}
}
/**
* Debugging function : var_dump $data and die script, only in DEBUG_MODE
*
* @param [type] ...$data
* @return void
*/
function ddump(mixed ...$data): void
{
if (!defined('DEBUG_MODE') || DEBUG_MODE !== true) {
return;
}
foreach ($data as $value) {
var_dump($value);
}
die;
}
/**
* Authenticates the user with Spotify and returns a valid access token.
* If a refresh token is available locally, it is used to obtain a new
* access token without user interaction. Otherwise, the OAuth
* authorization flow is triggered and the resulting refresh token
* is stored for future use.
*
* @return AccessToken
*/
function connect(): AccessToken
{
$access_token = null;
//if no available refresh token, ask first auth from Spotify user
if (!file_exists('refresh_token')) {
//Obtain authorization : requires web form validation
$code = ask_for_auth();
$access_token = request_access_token($code);
//Store refresh token to store authorization and reuse it next time.
save_refresh_token($access_token);
} else {
//Ask new access token from refresh token (skip auth.)
$refresh_token = file_get_contents('refresh_token');
$access_token = refresh_access_token($refresh_token);
}
if ($access_token === null) {
throw new RuntimeException("Impossible de se connecter au compte utilisateur. Réessayer.");
}
return $access_token;
}
/**
* Ask user for auth (OAuth 2 flow) to impersonate him
*
* @return string authorization code
*/
function ask_for_auth(): string
{
/*@see https://developer.spotify.com/documentation/web-api/concepts/scopes*/
$scopes = ['playlist-read-private', 'user-top-read', 'user-library-read'];
$query_params = array(
'client_id' => CLIENT_ID,
'redirect_uri' => REDIRECT_URI,
/*@see https://developer.spotify.com/documentation/web-api/tutorials/code-flow/ */
'response_type' => 'code',
'scope' => implode(' ', $scopes)
);
$auth_url = sprintf("%s?%s", AUTHORIZE_URL, http_build_query($query_params));
//Redirection vers la page d'authentification user de Spotify (web form)
//Remarque : je ne pense pas que cette instruction soit portable...
exec("xdg-open '$auth_url' >/dev/null 2>&1");
//Handle redirect URI from the browser by opening a socket
$socket_addr = str_replace(['http://', 'https://'], '', REDIRECT_URI);
$socket = stream_socket_server('tcp://' . $socket_addr, $errno, $errstr);
$connexion = stream_socket_accept($socket);
if(false === $connexion){
throw new RuntimeException('Connection not accepted');
}
$request = fread($connexion, 1024);
//Extract 'code' from the URL(request arg URL ?code=XXXXxxxx)
preg_match('#GET /\?([^ ]+)#', $request, $matches);
parse_str($matches[1] ?? '', $query_string);
$code = $query_string['code'] ?? null;
if ($code != null) {
fwrite($connexion, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n <p>Autorization granted</p>");
} else {
fwrite($connexion, "HTTP/1.1 400 OK\r\nContent-Type: text/plain\r\n\r\n <p>Autorization code missing. Please try again</p>");
throw new RuntimeException('Authorization code missing');
}
fclose($connexion);
fclose($socket);
return $code;
}
/**
* Return the Spotify access token once the user has authenticated and granted authorization
*
* @param string $code Token obtained after Spotify user has granted authorization to this client app
* @return AccessToken Necessary for any further requests
*/
function request_access_token(string $code): AccessToken
{
/*@see https://developer.spotify.com/documentation/web-api/tutorials/code-flow (section Request an access token)*/
$data = [
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => REDIRECT_URI,
];
$token = base64_encode(sprintf("%s:%s", CLIENT_ID, CLIENT_SECRET));
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => ACCESS_TOKEN_URL_SPOTIFY,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => http_build_query($data, '', '&', PHP_QUERY_RFC3986),
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . $token
]
]);
$response = curl_exec($ch);
if ($response == false) {
dump(curl_errno($ch), curl_error($ch));
throw new RuntimeException("Impossible d'obtenir l'access token. Vérifier les credentials et réessayer.");
}
$response = json_decode($response, true);
return new AccessToken(
$response['access_token'],
$response['token_type'],
$response['expires_in'],
$response['refresh_token'],
);
}
/**
* Save refresh token for later use
*
* @param AccessToken $token
* @return void
*/
function save_refresh_token(AccessToken $token): void
{
$file_refresh_token = fopen('refresh_token', 'w');
fwrite($file_refresh_token, $token->refresh_token);
fclose($file_refresh_token);
}
/**
* Renew access token from previously stored refresh token
*
* @param string $refresh_token
* @return AccessToken
*/
function refresh_access_token(string $refresh_token): AccessToken
{
/*@see https://developer.spotify.com/documentation/web-api/tutorials/refreshing-tokens */
$data = [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token,
];
$token = base64_encode(sprintf("%s:%s", CLIENT_ID, CLIENT_SECRET));
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => ACCESS_TOKEN_URL_SPOTIFY,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => http_build_query($data, '', '&', PHP_QUERY_RFC3986),
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . $token
]
]);
$response = curl_exec($ch);
if ($response == false) {
dump(curl_errno($ch), curl_error($ch));
throw new RuntimeException("Impossible d'obtenir l'access token. Vérifier les credentials et réessayer.");
}
$response = json_decode($response, true);
return new AccessToken(
$response['access_token'],
$response['token_type'],
$response['expires_in'],
//If no refresh token, reuse the previous one
//(@see https://developer.spotify.com/documentation/web-api/tutorials/refreshing-tokens, section Response )
$response['refresh_token'] ?? $refresh_token,
);
}
/**
* Send an HTTP request
*
* @param string $ressource
* @param AccessToken $access_token
* @param string $method. Default : GET
* @param string $format. Default : ARRAY (call json_decode)
* @return mixed
*/
function request(string $ressource, AccessToken $access_token, string $method = 'GET', string $format = 'ARRAY'): mixed
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => BASE_URL . $ressource,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $access_token->value
]
]);
$response = curl_exec($ch);
if ($response == false) {
dump(curl_errno($ch), curl_error($ch));
throw new RuntimeException("Une erreur est survenue.");
}
if ($format === 'ARRAY') {
$response = json_decode($response, true);
}
return $response;
}
/**
* Print the playlist information on a single line
*
* @param array $playlist
* @return void
*/
function printf_playlist_data(array $playlist): void
{
if (!is_array($playlist) || !isset($playlist['name'])) {
return;
}
$width = 33;
$pad = $width - mb_strwidth($playlist['name'], 'UTF-8');
printf(
"- Playlist: %s%s (%3d tracks), owned by %s\n",
$playlist['name'],
str_repeat(' ', max(0, $pad)),
intval($playlist['tracks']['total']),
$playlist['owner']['display_name']
);
}
/**
* Save all of the user's playlists locally as JSON.
*
* @param AccessToken $access_token
* @param string $which_one Which playlists to save ? Default: ALL. Possible values : 'OWNED_ONLY', 'ALL'
* @return void
*/
function backup_playlists(AccessToken $access_token, string $current_user_id, string $which_one = 'ALL')
{
$playlists = request('/me/playlists', $access_token);
printf("== INFORMATIONS ==\n");
printf("Total number of playlists (%d)\n", intval($playlists['total']));
printf("Playlists to save: \n");
$playlist_to_save = [];
foreach ($playlists['items'] as $playlist) {
$SAVE = false;
switch ($which_one) {
case 'ALL':
$playlist_to_save[] = $playlist;
$SAVE = true;
break;
case 'OWNED_ONLY':
if ($playlist['owner']['id'] === $current_user_id) {
$playlist_to_save[] = $playlist;
$SAVE = true;
}
break;
}
if ($SAVE) {
printf_playlist_data($playlist);
}
}
printf("Number of playlists to save (%s): %d\n", $which_one, count($playlist_to_save));
printf("\n== PROCESSING ==\n");
$position = 0;
foreach ($playlist_to_save as $playlist) {
printf(
"- Saving playlist %-25s (n°%2d/%2d, id: %s) ... ",
$playlist['name'],
$position + 1,
count($playlist_to_save),
$playlist['id']
);
$ressource = sprintf("/playlists/%s/tracks", $playlist['id']);
$tracks = query_paginated_tracks($ressource, $access_token, 100);
save_playlist_locally($playlist, json_encode($tracks));
$position++;
}
}
/**
* Save locally the special playlist 'Your music' (Liked tracks)
*
* @param AccessToken $access_token
* @return void
*/
function backup_liked_tracks(AccessToken $access_token)
{
printf("- Saving playlist 'Your Music' (liked tracks)\n");
printf("Collecting saved tracks data :\n");
$tracks = query_paginated_tracks("/me/tracks", $access_token, 50, show_progress: true);
$playlist = [
'name' => 'saved_tracks'
];
save_playlist_locally($playlist, json_encode($tracks));
}
function query_paginated_tracks(string $resource, AccessToken $access_token, int $limit = 50, bool $show_progress = false)
{
//Liked tracks list ('Your music') is paginated, max 50 per page. Normal playlist is max 100 per page.
//@see https://developer.spotify.com/documentation/web-api/reference/get-users-saved-tracks
$tracks = [];
$offset = 0;
do {
$query_params = http_build_query([
'offset' => $offset,
'limit' => $limit,
//Keep only track metadata i'm interested in
//@see https://developer.spotify.com/documentation/web-api/reference/get-playlists-tracks
'fields' => 'next,total,items(added_at,track(name,href,uri,duration_ms,external_ids,external_urls,album(name,href),artists(name)))'
]);
$response = request(sprintf("%s?%s", $resource, $query_params), $access_token);
if (isset($response['items'])) {
$tracks = array_merge($tracks, $response['items']);
}
if ($show_progress) {
printf("%d/%d (%02.1f%%)\n", count($tracks), $response['total'], count($tracks) / $response['total'] * 100);
}
$offset += $limit;
} while (isset($response['next'])); //next page
return $tracks;
}
/**
* Sanitize the playlist name to produce a valid, safe filename
*
* @param string $name Le nom de la playlist
* @return string
*/
function format_2_filename(string $name): string
{
$name = trim($name);
$name = str_replace(" ", "-", $name);
$name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $name);
$name = strtolower($name);
return $name;
}
/**
* Save a copy of the playlist tracks in JSON format to a text file named after the playlist
*
* @param array $playlist Playlist to save. Key 'name' required
* @param string $tracks List of tracks (JSON format)
* @return integer|boolean
*/
function save_playlist_locally(array $playlist, string $tracks): int|bool
{
if (!defined('BACKUP_DIR')) {
throw new RuntimeException("La valeur BACKUP_DIR (PATH où sauver les playlists) n'est pas défini. Le définir puis relancer le programme.");
}
$dir = BACKUP_DIR;
if (!is_dir($dir) && !mkdir($dir, 0775, true)) {
throw new RuntimeException("Impossible de créer $dir. Revoir les permissions sur le path concerné et relancer le programme.");
}
/*
Les playlists ont un historique de versions (snapshot),
on enregistre donc seulement les playlists dans leur dernier état.
*/
$file_playlist = sprintf("$dir/%s.json", format_2_filename($playlist['name']));
$file = fopen($file_playlist, 'w');
$res = fwrite($file, $tracks);
fclose($file);
if ($res != false) {
printf("Playlist %s saved.\n", $playlist['name']);
}
return $res;
}
function ascii_bar(float $frac, int $width = 80): string
{
$size = floor($frac * $width);
$bar = str_repeat("\u{2588}", $size);
return $bar;
}