-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpotifyArduino.cpp
1262 lines (1086 loc) · 34.7 KB
/
SpotifyArduino.cpp
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
SpotifyArduino - An Arduino library to wrap the Spotify API
Copyright (c) 2021 Brian Lough.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SpotifyArduino.h"
/*
SpotifyArduino::SpotifyArduino(Client &client)
{
this->client = &client;
}
*/
SpotifyArduino::SpotifyArduino(Client &client, char *bearerToken)
{
this->client = &client;
sprintf(this->_bearerToken, "Bearer %s", bearerToken);
}
SpotifyArduino::SpotifyArduino(Client &client, const char *clientId, const char *clientSecret, const char *refreshToken)
{
this->client = &client;
this->_clientId = clientId;
this->_clientSecret = clientSecret;
setRefreshToken(refreshToken);
}
/*
SpotifyArduino::SpotifyArduino(WebSocketClient &client, const char *clientId, const char *clientSecret, const char *refreshToken)
{
this->client = &client;
this->_clientId = clientId;
this->_clientSecret = clientSecret;
setRefreshToken(refreshToken);
}
*/
int SpotifyArduino::makeRequestWithBody(const char *type, const char *command, const char *authorization, const char *body, const char *contentType, const char *host)
{
client->flush();
#ifdef SPOTIFY_DEBUG
Serial.println(host);
#endif
client->setTimeout(SPOTIFY_TIMEOUT);
if (!client->connect(host, portNumber))
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.println(F("Connection failed"));
#endif
return -1;
}
// give the esp a breather
yield();
// Send HTTP request
client->print(type);
client->print(command);
client->println(F(" HTTP/1.0"));
//Headers
client->print(F("Host: "));
client->println(host);
client->println(F("Accept: application/json"));
client->print(F("Content-Type: "));
client->println(contentType);
if (authorization != NULL)
{
client->print(F("Authorization: "));
client->println(authorization);
}
client->println(F("Cache-Control: no-cache"));
client->print(F("Content-Length: "));
client->println(strlen(body));
client->println();
client->print(body);
if (client->println() == 0)
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.println(F("Failed to send request"));
#endif
return -2;
}
int statusCode = getHttpStatusCode();
return statusCode;
}
int SpotifyArduino::makePutRequest(const char *command, const char *authorization, const char *body, const char *contentType, const char *host)
{
return makeRequestWithBody("PUT ", command, authorization, body, contentType);
}
int SpotifyArduino::makePostRequest(const char *command, const char *authorization, const char *body, const char *contentType, const char *host)
{
return makeRequestWithBody("POST ", command, authorization, body, contentType, host);
}
int SpotifyArduino::makeGetRequest(const char *command, const char *authorization, const char *accept, const char *host)
{
client->flush();
client->setTimeout(SPOTIFY_TIMEOUT);
if (!client->connect(host, portNumber))
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.println(F("Connection failed"));
#endif
return -1;
}
// give the esp a breather
yield();
// Send HTTP request
client->print(F("GET "));
client->print(command);
client->println(F(" HTTP/1.0"));
//Headers
client->print(F("Host: "));
client->println(host);
if (accept != NULL)
{
client->print(F("Accept: "));
client->println(accept);
}
if (authorization != NULL)
{
client->print(F("Authorization: "));
client->println(authorization);
}
client->println(F("Cache-Control: no-cache"));
if (client->println() == 0)
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.println(F("Failed to send request"));
#endif
return -2;
}
int statusCode = getHttpStatusCode();
return statusCode;
}
void SpotifyArduino::setRefreshToken(const char *refreshToken)
{
int newRefreshTokenLen = strlen(refreshToken);
if (_refreshToken == NULL || strlen(_refreshToken) < newRefreshTokenLen)
{
delete _refreshToken;
_refreshToken = new char[newRefreshTokenLen + 1]();
}
strncpy(_refreshToken, refreshToken, newRefreshTokenLen + 1);
}
bool SpotifyArduino::refreshAccessToken()
{
char body[300];
sprintf(body, refreshAccessTokensBody, _refreshToken, _clientId, _clientSecret);
#ifdef SPOTIFY_DEBUG
Serial.println(body);
printStack();
#endif
int statusCode = makePostRequest(SPOTIFY_TOKEN_ENDPOINT, NULL, body, "application/x-www-form-urlencoded", SPOTIFY_ACCOUNTS_HOST);
if (statusCode > 0)
{
skipHeaders();
}
unsigned long now = millis();
#ifdef SPOTIFY_DEBUG
Serial.print("status Code");
Serial.println(statusCode);
#endif
bool refreshed = false;
if (statusCode == 200)
{
StaticJsonDocument<48> filter;
filter["access_token"] = true;
filter["token_type"] = true;
filter["expires_in"] = true;
DynamicJsonDocument doc(512);
// Parse JSON object
#ifndef SPOTIFY_PRINT_JSON_PARSE
DeserializationError error = deserializeJson(doc, *client, DeserializationOption::Filter(filter));
#else
ReadLoggingStream loggingStream(*client, Serial);
DeserializationError error = deserializeJson(doc, loggingStream, DeserializationOption::Filter(filter));
#endif
if (!error)
{
#ifdef SPOTIFY_DEBUG
Serial.println(F("No JSON error, dealing with response"));
#endif
const char *accessToken = doc["access_token"].as<const char *>();
if (accessToken != NULL && (SPOTIFY_ACCESS_TOKEN_LENGTH >= strlen(accessToken)))
{
sprintf(this->_bearerToken, "Bearer %s", accessToken);
int tokenTtl = doc["expires_in"]; // Usually 3600 (1 hour)
tokenTimeToLiveMs = (tokenTtl * 1000) - 2000; // The 2000 is just to force the token expiry to check if its very close
timeTokenRefreshed = now;
refreshed = true;
}
else
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("Problem with access_token (too long or null): "));
Serial.println(accessToken);
#endif
}
}
else
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
#endif
}
}
else
{
parseError();
}
closeClient();
return refreshed;
}
bool SpotifyArduino::checkAndRefreshAccessToken()
{
unsigned long timeSinceLastRefresh = millis() - timeTokenRefreshed;
if (timeSinceLastRefresh >= tokenTimeToLiveMs)
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.println("Refresh of the Access token is due, doing that now.");
#endif
return refreshAccessToken();
}
// Token is still valid
return true;
}
const char *SpotifyArduino::requestAccessTokens(const char *code, const char *redirectUrl)
{
char body[500];
sprintf(body, requestAccessTokensBody, code, redirectUrl, _clientId, _clientSecret);
#ifdef SPOTIFY_DEBUG
Serial.println(body);
#endif
int statusCode = makePostRequest(SPOTIFY_TOKEN_ENDPOINT, NULL, body, "application/x-www-form-urlencoded", SPOTIFY_ACCOUNTS_HOST);
if (statusCode > 0)
{
skipHeaders();
}
unsigned long now = millis();
#ifdef SPOTIFY_DEBUG
Serial.print("status Code");
Serial.println(statusCode);
#endif
if (statusCode == 200)
{
DynamicJsonDocument doc(1000);
// Parse JSON object
#ifndef SPOTIFY_PRINT_JSON_PARSE
DeserializationError error = deserializeJson(doc, *client);
#else
ReadLoggingStream loggingStream(*client, Serial);
DeserializationError error = deserializeJson(doc, loggingStream);
#endif
if (!error)
{
sprintf(this->_bearerToken, "Bearer %s", doc["access_token"].as<const char *>());
setRefreshToken(doc["refresh_token"].as<const char *>());
int tokenTtl = doc["expires_in"]; // Usually 3600 (1 hour)
tokenTimeToLiveMs = (tokenTtl * 1000) - 2000; // The 2000 is just to force the token expiry to check if its very close
timeTokenRefreshed = now;
}
else
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
#endif
}
}
else
{
parseError();
}
closeClient();
return _refreshToken;
}
/*
bool SpotifyArduino::play(const char *deviceId)
{
char command[100] = SPOTIFY_PLAY_ENDPOINT;
return playerControl(command, deviceId);
}
bool SpotifyArduino::playAdvanced(char *body, const char *deviceId)
{
char command[100] = SPOTIFY_PLAY_ENDPOINT;
return playerControl(command, deviceId, body);
}
bool SpotifyArduino::pause(const char *deviceId)
{
char command[100] = SPOTIFY_PAUSE_ENDPOINT;
return playerControl(command, deviceId);
}
bool SpotifyArduino::setVolume(int volume, const char *deviceId)
{
char command[125];
sprintf(command, SPOTIFY_VOLUME_ENDPOINT, volume);
return playerControl(command, deviceId);
}
bool SpotifyArduino::toggleShuffle(bool shuffle, const char *deviceId)
{
char command[125];
char shuffleState[10];
if (shuffle)
{
strcpy(shuffleState, "true");
}
else
{
strcpy(shuffleState, "false");
}
sprintf(command, SPOTIFY_SHUFFLE_ENDPOINT, shuffleState);
return playerControl(command, deviceId);
}
bool SpotifyArduino::setRepeatMode(RepeatOptions repeat, const char *deviceId)
{
char command[125];
char repeatState[10];
switch (repeat)
{
case repeat_track:
strcpy(repeatState, "track");
break;
case repeat_context:
strcpy(repeatState, "context");
break;
case repeat_off:
strcpy(repeatState, "off");
break;
}
sprintf(command, SPOTIFY_REPEAT_ENDPOINT, repeatState);
return playerControl(command, deviceId);
}
bool SpotifyArduino::playerControl(char *command, const char *deviceId, const char *body)
{
if (deviceId[0] != 0)
{
char *questionMarkPointer;
questionMarkPointer = strchr(command, '?');
char deviceIdBuff[50];
if (questionMarkPointer == NULL)
{
sprintf(deviceIdBuff, "?device_id=%s", deviceId);
}
else
{
// params already started
sprintf(deviceIdBuff, "&device_id=%s", deviceId);
}
strcat(command, deviceIdBuff);
}
#ifdef SPOTIFY_DEBUG
Serial.println(command);
Serial.println(body);
#endif
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makePutRequest(command, _bearerToken, body);
closeClient();
//Will return 204 if all went well.
return statusCode == 204;
}
bool SpotifyArduino::playerNavigate(char *command, const char *deviceId)
{
if (deviceId[0] != 0)
{
char deviceIdBuff[50];
sprintf(deviceIdBuff, "?device_id=%s", deviceId);
strcat(command, deviceIdBuff);
}
#ifdef SPOTIFY_DEBUG
Serial.println(command);
#endif
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makePostRequest(command, _bearerToken);
closeClient();
//Will return 204 if all went well.
return statusCode == 204;
}
bool SpotifyArduino::nextTrack(const char *deviceId)
{
char command[100] = SPOTIFY_NEXT_TRACK_ENDPOINT;
return playerNavigate(command, deviceId);
}
bool SpotifyArduino::previousTrack(const char *deviceId)
{
char command[100] = SPOTIFY_PREVIOUS_TRACK_ENDPOINT;
return playerNavigate(command, deviceId);
}
bool SpotifyArduino::seek(int position, const char *deviceId)
{
char command[100] = SPOTIFY_SEEK_ENDPOINT;
char tempBuff[100];
sprintf(tempBuff, "?position_ms=%d", position);
strcat(command, tempBuff);
if (deviceId[0] != 0)
{
sprintf(tempBuff, "?device_id=%s", deviceId);
strcat(command, tempBuff);
}
#ifdef SPOTIFY_DEBUG
Serial.println(command);
printStack();
#endif
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makePutRequest(command, _bearerToken);
closeClient();
//Will return 204 if all went well.
return statusCode == 204;
}
bool SpotifyArduino::transferPlayback(const char *deviceId, bool play)
{
char body[100];
sprintf(body, "{\"device_ids\":[\"%s\"],\"play\":\"%s\"}", deviceId, (play ? "true" : "false"));
#ifdef SPOTIFY_DEBUG
Serial.println(SPOTIFY_PLAYER_ENDPOINT);
Serial.println(body);
printStack();
#endif
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makePutRequest(SPOTIFY_PLAYER_ENDPOINT, _bearerToken, body);
closeClient();
//Will return 204 if all went well.
return statusCode == 204;
}
*/
int SpotifyArduino::getCurrentlyPlaying(processCurrentlyPlaying currentlyPlayingCallback, const char *market)
{
char command[50] = SPOTIFY_CURRENTLY_PLAYING_ENDPOINT;
if (market[0] != 0)
{
char marketBuff[15];
sprintf(marketBuff, "?market=%s", market);
strcat(command, marketBuff);
}
/*
#ifdef SPOTIFY_DEBUG
Serial.println(command);
printStack();
#endif
*/
// Get from https://arduinojson.org/v6/assistant/
const size_t bufferSize = currentlyPlayingBufferSize;
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makeGetRequest(command, _bearerToken);
/*
#ifdef SPOTIFY_DEBUG
Serial.print("Status Code: ");
Serial.println(statusCode);
printStack();
#endif
*/
if (statusCode > 0)
{
skipHeaders();
}
if (statusCode == 200)
{
CurrentlyPlaying current;
//Apply Json Filter: https://arduinojson.org/v6/example/filter/
StaticJsonDocument<288> filter;
filter["is_playing"] = true;
filter["progress_ms"] = true;
JsonObject filter_item = filter.createNestedObject("item");
filter_item["duration_ms"] = true;
filter_item["name"] = true;
//filter_item["uri"] = true;
/*
JsonObject filter_item_artists_0 = filter_item["artists"].createNestedObject();
filter_item_artists_0["name"] = true;
filter_item_artists_0["uri"] = true;
JsonObject filter_item_album = filter_item.createNestedObject("album");
filter_item_album["name"] = true;
filter_item_album["uri"] = true;
JsonObject filter_item_album_images_0 = filter_item_album["images"].createNestedObject();
filter_item_album_images_0["height"] = true;
filter_item_album_images_0["width"] = true;
filter_item_album_images_0["url"] = true;
*/
// Allocate DynamicJsonDocument
DynamicJsonDocument doc(bufferSize);
// Parse JSON object
#ifndef SPOTIFY_PRINT_JSON_PARSE
DeserializationError error = deserializeJson(doc, *client, DeserializationOption::Filter(filter));
#else
ReadLoggingStream loggingStream(*client, Serial);
DeserializationError error = deserializeJson(doc, loggingStream, DeserializationOption::Filter(filter));
#endif
if (!error)
{
/*
#ifdef SPOTIFY_DEBUG
serializeJsonPretty(doc, Serial);
#endif
*/
JsonObject item = doc["item"];
//Serial.println("IMPORTANT I THINK");
//Serial.println(item);
/*
int numArtists = item["artists"].size();
if (numArtists > SPOTIFY_MAX_NUM_ARTISTS)
{
numArtists = SPOTIFY_MAX_NUM_ARTISTS;
}
current.numArtists = numArtists;
for (int i = 0; i < current.numArtists; i++)
{
current.artists[i].artistName = item["artists"][i]["name"].as<const char *>();
current.artists[i].artistUri = item["artists"][i]["uri"].as<const char *>();
}
current.albumName = item["album"]["name"].as<const char *>();
current.albumUri = item["album"]["uri"].as<const char *>();
*/
/*
JsonArray images = item["album"]["images"];
// Images are returned in order of width, so last should be smallest.
int numImages = images.size();
int startingIndex = 0;
if (numImages > SPOTIFY_NUM_ALBUM_IMAGES)
{
startingIndex = numImages - SPOTIFY_NUM_ALBUM_IMAGES;
current.numImages = SPOTIFY_NUM_ALBUM_IMAGES;
}
else
{
current.numImages = numImages;
}
#ifdef SPOTIFY_DEBUG
Serial.print(F("Num Images: "));
Serial.println(current.numImages);
Serial.println(numImages);
#endif
for (int i = 0; i < current.numImages; i++)
{
int adjustedIndex = startingIndex + i;
current.albumImages[i].height = images[adjustedIndex]["height"].as<int>();
current.albumImages[i].width = images[adjustedIndex]["width"].as<int>();
current.albumImages[i].url = images[adjustedIndex]["url"].as<const char *>();
}
*/
current.trackName = item["name"].as<const char *>();
//current.trackUri = item["uri"].as<const char *>();
current.isPlaying = doc["is_playing"].as<bool>();
current.progressMs = doc["progress_ms"].as<long>();
current.durationMs = item["duration_ms"].as<long>();
currentlyPlayingCallback(current);
}
else
{
/*
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
#endif
*/
statusCode = -1;
}
}
closeClient();
return statusCode;
}
/*
int SpotifyArduino::getPlayerDetails(processPlayerDetails playerDetailsCallback, const char *market)
{
char command[100] = SPOTIFY_PLAYER_ENDPOINT;
if (market[0] != 0)
{
char marketBuff[30];
sprintf(marketBuff, "?market=%s", market);
strcat(command, marketBuff);
}
#ifdef SPOTIFY_DEBUG
Serial.println(command);
printStack();
#endif
// Get from https://arduinojson.org/v6/assistant/
const size_t bufferSize = playerDetailsBufferSize;
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makeGetRequest(command, _bearerToken);
#ifdef SPOTIFY_DEBUG
Serial.print("Status Code: ");
Serial.println(statusCode);
#endif
if (statusCode > 0)
{
skipHeaders();
}
if (statusCode == 200)
{
StaticJsonDocument<192> filter;
JsonObject filter_device = filter.createNestedObject("device");
filter_device["id"] = true;
filter_device["name"] = true;
filter_device["type"] = true;
filter_device["is_active"] = true;
filter_device["is_private_session"] = true;
filter_device["is_restricted"] = true;
filter_device["volume_percent"] = true;
filter["progress_ms"] = true;
filter["is_playing"] = true;
filter["shuffle_state"] = true;
filter["repeat_state"] = true;
// Allocate DynamicJsonDocument
DynamicJsonDocument doc(bufferSize);
// Parse JSON object
#ifndef SPOTIFY_PRINT_JSON_PARSE
DeserializationError error = deserializeJson(doc, *client, DeserializationOption::Filter(filter));
#else
ReadLoggingStream loggingStream(*client, Serial);
DeserializationError error = deserializeJson(doc, loggingStream, DeserializationOption::Filter(filter));
#endif
if (!error)
{
PlayerDetails playerDetails;
JsonObject device = doc["device"];
// Copy into buffer and make the last character a null just incase we went over.
playerDetails.device.id = device["id"].as<const char *>();
playerDetails.device.name = device["name"].as<const char *>();
playerDetails.device.type = device["type"].as<const char *>();
playerDetails.device.isActive = device["is_active"].as<bool>();
playerDetails.device.isPrivateSession = device["is_private_session"].as<bool>();
playerDetails.device.isRestricted = device["is_restricted"].as<bool>();
playerDetails.device.volumePercent = device["volume_percent"].as<int>();
playerDetails.progressMs = doc["progress_ms"].as<long>();
playerDetails.isPlaying = doc["is_playing"].as<bool>();
playerDetails.shuffleState = doc["shuffle_state"].as<bool>();
const char *repeat_state = doc["repeat_state"];
if (strncmp(repeat_state, "track", 5) == 0)
{
playerDetails.repeateState = repeat_track;
}
else if (strncmp(repeat_state, "context", 7) == 0)
{
playerDetails.repeateState = repeat_context;
}
else
{
playerDetails.repeateState = repeat_off;
}
playerDetailsCallback(playerDetails);
}
else
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
#endif
statusCode = -1;
}
}
closeClient();
return statusCode;
}
int SpotifyArduino::getDevices(processDevices devicesCallback)
{
#ifdef SPOTIFY_DEBUG
Serial.println(SPOTIFY_DEVICES_ENDPOINT);
printStack();
#endif
// Get from https://arduinojson.org/v6/assistant/
const size_t bufferSize = getDevicesBufferSize;
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makeGetRequest(SPOTIFY_DEVICES_ENDPOINT, _bearerToken);
#ifdef SPOTIFY_DEBUG
Serial.print("Status Code: ");
Serial.println(statusCode);
#endif
if (statusCode > 0)
{
skipHeaders();
}
if (statusCode == 200)
{
// Allocate DynamicJsonDocument
DynamicJsonDocument doc(bufferSize);
// Parse JSON object
#ifndef SPOTIFY_PRINT_JSON_PARSE
DeserializationError error = deserializeJson(doc, *client);
#else
ReadLoggingStream loggingStream(*client, Serial);
DeserializationError error = deserializeJson(doc, loggingStream);
#endif
if (!error)
{
uint8_t totalDevices = doc["devices"].size();
SpotifyDevice spotifyDevice;
for (int i = 0; i < totalDevices; i++)
{
JsonObject device = doc["devices"][i];
spotifyDevice.id = device["id"].as<const char *>();
spotifyDevice.name = device["name"].as<const char *>();
spotifyDevice.type = device["type"].as<const char *>();
spotifyDevice.isActive = device["is_active"].as<bool>();
spotifyDevice.isPrivateSession = device["is_private_session"].as<bool>();
spotifyDevice.isRestricted = device["is_restricted"].as<bool>();
spotifyDevice.volumePercent = device["volume_percent"].as<int>();
if (!devicesCallback(spotifyDevice, i, totalDevices))
{
//User has indicated they are finished.
break;
}
}
}
else
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
#endif
statusCode = -1;
}
}
closeClient();
return statusCode;
}
int SpotifyArduino::searchForSong(String query, int limit, processSearch searchCallback, SearchResult results[])
{
#ifdef SPOTIFY_DEBUG
Serial.println(SPOTIFY_SEARCH_ENDPOINT);
printStack();
#endif
// Get from https://arduinojson.org/v6/assistant/
const size_t bufferSize = searchDetailsBufferSize;
if (autoTokenRefresh)
{
checkAndRefreshAccessToken();
}
int statusCode = makeGetRequest((SPOTIFY_SEARCH_ENDPOINT + query + "&limit=" + limit).c_str(), _bearerToken);
#ifdef SPOTIFY_DEBUG
Serial.print("Status Code: ");
Serial.println(statusCode);
#endif
if (statusCode > 0)
{
skipHeaders();
}
if (statusCode == 200)
{
// Allocate DynamicJsonDocument
DynamicJsonDocument doc(bufferSize);
// Parse JSON object
#ifndef SPOTIFY_PRINT_JSON_PARSE
DeserializationError error = deserializeJson(doc, *client);
#else
ReadLoggingStream loggingStream(*client, Serial);
DeserializationError error = deserializeJson(doc, loggingStream);
#endif
if (!error)
{
uint8_t totalResults = doc["tracks"]["items"].size();
Serial.print("Total Results: ");
Serial.println(totalResults);
SearchResult searchResult;
for (int i = 0; i < totalResults; i++)
{
//Polling track information
JsonObject result = doc["tracks"]["items"][i];
searchResult.trackUri = result["uri"].as<const char *>();
searchResult.trackName = result["name"].as<const char *>();
searchResult.albumUri = result["album"]["uri"].as<const char *>();
searchResult.albumName = result["album"]["name"].as<const char *>();
//Pull artist Information for the result
uint8_t totalArtists = result["artists"].size();
searchResult.numArtists = totalArtists;
SpotifyArtist artist;
for (int j = 0; j < totalArtists; j++)
{
JsonObject artistResult = result["artists"][j];
artist.artistName = artistResult["name"].as<const char *>();
artist.artistUri = artistResult["uri"].as<const char *>();
searchResult.artists[j] = artist;
}
uint8_t totalImages = result["album"]["images"].size();
searchResult.numImages = totalImages;
SpotifyImage image;
for (int j = 0; j < totalImages; j++)
{
JsonObject imageResult = result["album"]["images"][j];
image.height = imageResult["height"].as<int>();
image.width = imageResult["width"].as<int>();
image.url = imageResult["url"].as<const char *>();
searchResult.albumImages[j] = image;
}
//Serial.println(searchResult.trackName);
results[i] = searchResult;
if (i >= limit || !searchCallback(searchResult, i, totalResults))
{
//Break at the limit or when indicated
break;
}
}
}
else
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
#endif
statusCode = -1;
}
}
closeClient();
return statusCode;
}
*/
int SpotifyArduino::commonGetImage(char *imageUrl)
{
#ifdef SPOTIFY_DEBUG
Serial.print(F("Parsing image URL: "));
Serial.println(imageUrl);
#endif
uint8_t lengthOfString = strlen(imageUrl);
// We are going to just assume https, that's all I've
// seen and I can't imagine a company will go back
// to http
if (strncmp(imageUrl, "https://", 8) != 0)
{
#ifdef SPOTIFY_SERIAL_OUTPUT
Serial.print(F("Url not in expected format: "));
Serial.println(imageUrl);
Serial.println("(expected it to start with \"https://\")");
#endif
return false;
}
uint8_t protocolLength = 8;
char *pathStart = strchr(imageUrl + protocolLength, '/');
uint8_t pathIndex = pathStart - imageUrl;
uint8_t pathLength = lengthOfString - pathIndex;
char path[pathLength + 1];
strncpy(path, pathStart, pathLength);
path[pathLength] = '\0';
uint8_t hostLength = pathIndex - protocolLength;
char host[hostLength + 1];
strncpy(host, imageUrl + protocolLength, hostLength);
host[hostLength] = '\0';