-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyctrl_spotify.cpp
5572 lines (5236 loc) · 220 KB
/
myctrl_spotify.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
//
// Spotify settings/loaders
//
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <string.h>
#include <mysql.h>
#include <GL/glc.h>
#include <pthread.h> // multi thread support
#include <libxml/parser.h>
#include <sys/stat.h>
#include <time.h>
#include <curl/curl.h>
#include <unistd.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <string>
#include <fmt/format.h>
// json parser
#include "json-parser/json.h"
// global def
#include "myth_setup.h"
// web server stuf used to get token
#include "mongoose-master/mongoose.h"
#include "utility.h"
#include "myth_ttffont.h"
#include "utility.h"
// jpg/png file reader
#include "readjpg.h"
#include "loadpng.h"
// web file loader
#include "myctrl_readwebfile.h"
#include "myctrl_spotify.h"
#include "myctrl_glprint.h"
extern const char *dbname; // internal database name in mysql (music,movie,radio)
// web port
static const char *s_http_port = "8000";
static struct mg_serve_http_opts s_http_server_opts;
const int spotify_pathlength=80;
const int spotify_namelength=80;
const int spotify_desclength=2000;
const int feed_url=2000;
const char *spotify_json_path = "spotify_json/";
const char *spotify_gfx_path = "spotify_gfx/";
extern FILE *logfile;
size_t curl_writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
data->append((char*) ptr, size * nmemb);
return size * nmemb;
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) {
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
// flags
bool process_playinfo_tracks=false;
bool process_playinfo_playlist=false;
bool process_playinfo_songs=false;
bool process_playinfo_href=false;
bool process_playinfo_description=false;
bool process_playinfo_image=false;
bool process_playinfo_name=false;
bool process_playinfo_items=false;
bool process_playinfo_artist=false;
bool process_playinfo_track_nr=false;
bool process_playinfo_date=false;
bool process_playinfo_progress_ms=false;
bool process_playinfo_duration_ms=false;
bool playinfo_json_debug=false;
// ****************************************************************************************
//
// text render is glcRenderString for freetype font support
//
// ****************************************************************************************
extern bool global_use_spotify_local_player;
// extern int spotifyknapnr;
extern int spotify_select_iconnr;
extern spotify_class spotify_oversigt;
extern GLuint _texturemovieinfobox;
extern GLuint big_search_bar_playlist; // big search bar used by sporify search
extern GLuint big_search_bar_track; // big search bar used by sporify search
extern GLuint big_search_bar_albumm; // big search bar used by sporify search
extern GLuint big_search_bar_artist; // big search bar used by sporify search
extern char *keybuffer;
extern int keybufferindex;
extern bool do_select_device_to_play;
extern GLuint mobileplayer_icon;
extern GLuint pcplayer_icon;
extern GLuint unknownplayer_icon;
extern GLuint spotify_pil;
extern float configdefaultstreamfontsize;
extern int tema;
extern char configmysqluser[256]; //
extern char configmysqlpass[256]; //
extern char configmysqlhost[256]; //
extern char configmusicpath[256];
extern int configmythtvver;
extern int screen_size;
extern int screensizey;
extern int screeny;
extern GLuint spotify_askplay; // ask open icon
extern GLuint spotify_askopen; // ask play icon
extern GLuint setuprssback;
extern GLuint _textureclose;
extern GLuint setupkeysbar1;
extern int debugmode;
extern unsigned int musicoversigt_antal; //
extern int do_stream_icon_anim_icon_ofset; //
extern GLuint radiooptions,radiooptionsmask; //
extern GLuint _textureIdback; // back icon
extern GLuint newstuf_icon; //
extern int fonttype;
extern fontctrl aktivfont;
extern int orgwinsizey,orgwinsizex;
extern int _sangley;
extern int do_show_setup_select_linie;
extern GLuint _textureIdloading,_textureIdloading1;
extern GLuint spotify_icon_border;
// stream mask
extern GLuint onlinestreammask;
extern GLuint onlinestreammaskicon; // icon mask on web icon
extern spotify_class streamoversigt;
extern GLint cur_avail_mem_kb;
extern bool stream_loadergfx_started;
extern bool stream_loadergfx_started_done;
extern bool stream_loadergfx_started_break;
extern char localuserhomedir[4096]; // user homedir set in main
//extern bool spotify_oversigt_loaded_begin;
// ****************************************************************************************
//
// web server handler (internal function)
//
// ****************************************************************************************
static void spotify_server_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
const char *p;
const char *pspace;
int n=0;
char user_token[1024];
char sql[2048];
struct http_message *hm = (struct http_message *) ev_data;
struct mg_serve_http_opts opts;
int curl_error;
char* file_contents=NULL;
size_t len;
int error;
FILE *tokenfile;
char *base64_code;
char data[512];
char token_string[512];
char token_refresh[512];
unsigned int codel;
strcpy(data,spotify_oversigt.spotify_client_id);
strcat(data,":");
strcat(data,spotify_oversigt.spotify_secret_id);
char sed[]="cat spotify_access_token.txt | grep -Po '\"\\K[^:,\"}]*' | grep -Ev 'access_token|token_type|Bearer|expires_in|refresh_token|scope' > spotify_access_token2.txt";
//calc base64
base64_code=b64_encode((const unsigned char *) data, 65);
*(base64_code+88)='\0';
switch (ev) {
case MG_EV_HTTP_REQUEST:
// Invoked when the full HTTP request is in the buffer (including body).
// from spotify servers
// is callback call from by login page index.html or spotify_index.html (login/index.html have the callback url as callback from spotify )
if (mg_strncmp( hm->uri,mg_mk_str_n("/callback",9),9) == 0) {
// if (debugmode) fprintf(stdout,"Got reply server : %s \n", (mg_str) hm->uri);
// get code pointer ( uri.p = pointer to url )
p = strstr( hm->uri.p , "code="); // mg_mk_str_n("code=",5));
// get sptify code from server
if (p) {
pspace=strchr(p,' ');
if (pspace) {
codel=(pspace-p);
strncpy(user_token,p+5,pspace-p); // copy code from return url from server
*(user_token+(pspace-p))='\0';
}
user_token[codel-4]='\0';
}
// snprintf(sql,sizeof(sql),"curl -X POST -H 'Authorization: Basic %s' -d grant_type=authorization_code -d code=%s -d redirect_uri=http://localhost:8000/callback/ -d client_id=%s -d client_secret=%s -H 'Content-Type: application/x-www-form-urlencoded' https://accounts.spotify.com/api/token > spotify_access_token.txt",base64_code,user_token,spotify_oversigt.spotify_client_id,spotify_oversigt.spotify_secret_id);
std::string sql1;
sql1 = fmt::v8::format("curl -X POST -H 'Authorization: Basic {}' -d grant_type=authorization_code -d code={} -d redirect_uri=http://localhost:8000/callback/ -d client_id={} -d client_secret={} -H 'Content-Type: application/x-www-form-urlencoded' https://accounts.spotify.com/api/token > spotify_access_token.txt",base64_code,user_token,spotify_oversigt.spotify_client_id,spotify_oversigt.spotify_secret_id);
//printf("sql curl : %s \n ",sql);
curl_error=system(sql1.c_str());
if (curl_error==0) {
curl_error=system(sed);
if (curl_error==0) {
write_logfile(logfile,(char *) "******** Got spotify token ********");
} else {
write_logfile(logfile,(char *) "******** Error getting spotify token ********");
}
if (curl_error==0) {
tokenfile=fopen("spotify_access_token2.txt","r");
error=getline(&file_contents,&len,tokenfile);
strcpy(token_string,file_contents);
token_string[strlen(token_string)-1]='\0';
error=getline(&file_contents,&len,tokenfile);
strcpy(token_refresh,file_contents);
token_refresh[strlen(token_refresh)-1]='\0';
// save for later use
spotify_oversigt.spotify_set_token(token_string,token_refresh);
fclose(tokenfile);
free(file_contents);
if (strcmp(token_string,"")!=0) {
spotify_oversigt.spotify_get_user_id(); // get user id
spotify_oversigt.active_spotify_device=spotify_oversigt.spotify_get_available_devices(); // set users play device.
// set default spotify device if none
if (spotify_oversigt.active_spotify_device==-1) spotify_oversigt.active_spotify_device=0;
}
}
}
//c->flags |= MG_F_SEND_AND_CLOSE;
mg_serve_http(c, (struct http_message *) ev_data, s_http_server_opts); /* Serve static content */
} else {
// else show normal indhold
memset(&opts, 0, sizeof(opts));
opts.document_root = "."; // Serve files from the current directory
mg_serve_http(c, (struct http_message *) ev_data, s_http_server_opts);
}
// We have received an HTTP request. Parsed request is contained in `hm`.
// Send HTTP reply to the client which shows full original request.
//mg_send_head(c, 200, hm->message.len, "Content-Type: text/plain");
//mg_printf(c, "%.*s", (int)hm->message.len, hm->message.p);
break;
case MG_EV_HTTP_REPLY:
write_logfile(logfile,(char *) "Other CALL BACK server reply");
c->flags |= MG_F_CLOSE_IMMEDIATELY;
fwrite(hm->body.p, 1, hm->body.len, stdout);
putchar('\n');
break;
case MG_EV_CLOSE:
fprintf(stdout,"Server closed connection\n");
}
}
// ****************************************************************************************
//
// client handler
// get JSON return from spotify
//
// ****************************************************************************************
static int s_exit_flag = 0;
bool debug_json=false;
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
struct http_message *hm = (struct http_message *) ev_data;
int connect_status;
switch (ev) {
case MG_EV_CONNECT:
connect_status = *(int *) ev_data;
if (connect_status != 0) {
fprintf(stderr,"Error connecting %s\n", strerror(connect_status));
s_exit_flag = 1;
}
break;
case MG_EV_HTTP_REPLY:
fwrite(hm->message.p, 1, (int)hm->message.len, stdout);
fprintf(stdout,"Got reply client :\n%.*s\n", (int) hm->body.len, hm->body.p);
fprintf(stdout,"***************************************** CALL BACK **************************************************");
nc->flags |= MG_F_SEND_AND_CLOSE;
s_exit_flag = 1;
break;
case MG_EV_CLOSE:
if (s_exit_flag == 0) {
write_logfile(logfile,(char *) "Server closed connection.");
fprintf(stdout,"Server closed connection\n");
s_exit_flag = 1;
};
break;
default:
break;
}
}
// ****************************************************************************************
//
// Constructor spotify devices
//
// ****************************************************************************************
spotify_device_def::spotify_device_def() {
strcpy(id,"");
is_active=false;
is_private_session=false;
is_restricted=false;
strcpy(name,"");
strcpy(devtype,"");
devvolume=0;
}
// ****************************************************************************************
//
// Constructor spotify active player
//
// ****************************************************************************************
spotify_active_play_info_type::spotify_active_play_info_type() {
progress_ms=0;
duration_ms=0;
strcpy(song_name,"");
strcpy(artist_name,"");
strcpy(cover_image_url,"");
cover_image=0;
strcpy(album_name,"");
strcpy(release_date,"");
popularity=0;
is_playing=false;
};
// ****************************************************************************************
//
// Constructor spotify oversigt type
//
// ****************************************************************************************
spotify_oversigt_type::spotify_oversigt_type() {
strcpy(feed_showtxt,"");
strcpy(feed_name,"");
strcpy(feed_desc,"");
strcpy(feed_gfx_url,"");
strcpy(feed_release_date,"");
strcpy(playlistid,"");
strcpy(playlisturl,"");
feed_group_antal=0;
feed_path_antal=0;
nyt=false;
textureId=0;
type=0; // 0 = playlist / 1 = songs / 2 = search artist / 3 = artist records/albums
intnr=0;
};
// ****************************************************************************************
//
// constructor
//
// ****************************************************************************************
spotify_class::spotify_class() : antal(0) {
anim_viewer=true; // lav anim når view åbnes
anim_viewer_search=true;
for(int i=0;i<maxantal;i++) stack[i]=0;
stream_optionselect=0; // selected line in stream options
spotify_oversigt_loaded=false;
spotify_oversigt_loaded_nr=0;
antal=0;
type=0;
searchtype=0;
search_loaded=false; // load icobn gfx afload search is loaded done by thread.
spotify_aktiv_song_antal=0; //
gfx_loaded=false; // gfx loaded default false
spotify_is_playing=false; // is we playing any media
spotify_is_pause=false; // is player on pause
show_search_result=false; // are we showing search result in view
antalplaylists=0; // antal playlists
loaded_antal=0; // antal loaded
search_playlist_song=0;
int port_cnt, n;
int err = 0;
strcpy(spotify_aktiv_song[0].release_date,"");
// create web server
mg_mgr_init(&mgr, NULL); // Initialize event manager object
// start web server
write_logfile(logfile,(char *) "Starting web server on port 8000"); //
this->c = mg_bind(&mgr, s_http_port, spotify_server_ev_handler); // Create listening connection and add it to the event manager
mg_set_protocol_http_websocket(this->c); // make http protocol
//mg_connect_http(&mgr, ev_handler, "", NULL, NULL);
active_spotify_device=-1; // active spotify device -1 = no dev is active
active_default_play_device=active_spotify_device;
aktiv_song_spotify_icon=0; //
strcpy(spotify_client_id,""); //
strcpy(spotify_secret_id,""); //
strcpy(spotifytoken,""); //
strcpy(spotifytoken_refresh,""); //
strcpy(spotify_client_id,"05b40c70078a429fa40ab0f9ccb485de");
strcpy(spotify_secret_id,"e50c411d2d2f4faf85ddff16f587fea1");
strcpy(active_default_play_device_name,"");
strcpy(overview_show_band_name,""); //
strcpy(overview_show_cd_name,""); //
spotify_device_antal=0;
spotify_update_loaded_begin=false; // true then we are update the stack data
}
// ****************************************************************************************
//
// destructor
//
// ****************************************************************************************
spotify_class::~spotify_class() {
mg_mgr_free(&mgr); // delete web server again
mg_mgr_free(&client_mgr); // delete web client
clean_spotify_oversigt(); // clean spotify class
}
// ****************************************************************************************
//
// set loader flag
//
// ****************************************************************************************
void spotify_class::set_spotify_update_flag(bool flag) {
spotify_update_loaded_begin=flag;
}
// ****************************************************************************************
//
// get loader flag
//
// ****************************************************************************************
bool spotify_class::get_spotify_update_flag() {
return(spotify_update_loaded_begin);
}
// ****************************************************************************************
// file writer
// ****************************************************************************************
static size_t file_write_data(void *ptr, size_t size, size_t nmemb, void *stream) {
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
// ********************************************************************************************
//
// Refresh token
// return http code (normal 200)
//
// ********************************************************************************************
int spotify_class::spotify_refresh_token() {
std::size_t foundpos;
char auth_kode[1024];
std::string response_string;
std::string response_val;
int httpCode=0;
CURLcode res;
struct curl_slist *chunk = NULL;
char doget[2048];
char data[4096];
char call[4096];
CURL *curl;
FILE *tokenfil;
char *base64_code;
char newtoken[1024];
char post_playlist_data[1024];
char errbuf[CURL_ERROR_SIZE];
strcpy(newtoken,"");
curl = curl_easy_init();
if ((curl) && (strcmp(spotifytoken_refresh,"")!=0)) {
// add userinfo + basic auth
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERNAME, spotify_client_id);
curl_easy_setopt(curl, CURLOPT_PASSWORD, spotify_secret_id);
/* Add a custom header */
//chunk = curl_slist_append(chunk, "Accept: application/json");
//chunk = curl_slist_append(chunk, "Content-Type: application/json");
//
curl_easy_setopt(curl, CURLOPT_URL, "https://accounts.spotify.com/api/token");
// ask libcurl to use TLS version 1.3 or later
curl_easy_setopt(curl, CURLOPT_SSLVERSION, (long)CURL_SSLVERSION_TLSv1_3);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_writeFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (char *) &response_string);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
/* Add a custom header */
//chunk = curl_slist_append(chunk, "Accept: application/json");
//chunk = curl_slist_append(chunk, "Content-Type: application/json");
//chunk = curl_slist_append(chunk, base64_code);
errbuf[0] = 0;
// set type post
//curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
//sprintf(post_playlist_data,"{\"grant_type\":\"refresh_token\",\"refresh_token\":%s}",spotifytoken_refresh);
snprintf(post_playlist_data,sizeof(post_playlist_data),"grant_type=refresh_token&refresh_token=%s",spotifytoken_refresh);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_playlist_data);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(post_playlist_data));
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
size_t len = strlen(errbuf);
fprintf(stderr, "\nlibcurl: (%d) ", res);
if(len)
fprintf(stderr, "%s%s", errbuf,((errbuf[len - 1] != '\n') ? "\n" : ""));
else
fprintf(stderr, "%s\n", curl_easy_strerror(res));
}
// get respons code
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
}
if (httpCode == 200) {
write_logfile(logfile,(char *) "Spotify new token.");
//printf("%s \n", response_string.c_str());
//printf("resp length %d \n",response_string.length());
//value = json_parse((char *) response_string.c_str(),response_string.length()); // parser
//process_value_playinfo(value, 0,0); // fill play info
if ((response_string.size()>12) && (response_string.compare(2,12,"access_token")==0)) {
strncpy(newtoken,response_string.c_str()+17,180);
newtoken[181]='\0';
write_logfile(logfile,(char *) "Spotify token valid.");
strcpy(spotifytoken,newtoken); // update spotify token
}
} else {
fprintf(stderr,"Error code httpCode %d \n. ",httpCode);
fprintf(stderr,"Curl error: %s\n", curl_easy_strerror(res));
}
// always cleanup
curl_easy_cleanup(curl);
}
return(httpCode);
}
// *********************************************************************************************************************************
// Download image
// sample call
// download_image("https://i.scdn.co/image/ab67616d0000b2737bded29598acbe1e2f4b4437","/home/hans/file.jpg");
// ********************************************************************************************
int download_image(char *imgurl,char *filename) {
FILE *file;
std::string response_string;
CURLcode res;
CURL *curl;
char *base64_code;
char errbuf[CURL_ERROR_SIZE];
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, imgurl);
// send data to curl_writeFunction_file
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_VERBOSE,0L);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); // <-- ssl don't forget this
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); // <-- ssl and this
errbuf[0] = 0;
try {
file = fopen(filename, "wb");
if (file) {
curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
// get file
res = curl_easy_perform(curl);
fclose(file);
}
if(res != CURLE_OK) {
fprintf(stderr, "%s\n", curl_easy_strerror(res));
}
}
catch (...) {
printf("Error open file.\n");
}
curl_easy_cleanup(curl);
}
return(1);
}
// ****************************************************************************************
//
// save the refresh token in used
//
// ****************************************************************************************
void spotify_class::spotify_set_token(char *token,char *refresh) {
strcpy(spotifytoken,token);
strcpy(spotifytoken_refresh,refresh);
}
// ****************************************************************************************
// DEBUG code
// json parser used to parse the return files from spotify api
//
// ****************************************************************************************
void spotify_class::playlist_print_depth_shift(int depth) {
bool debug_json=false;
int j;
for (j=0; j < depth; j++) {
if (debug_json) printf(" ");
}
}
// * Default view ***********************************************************************************************************************************************
// ****************************************************************************************
//
// static void spotify_class::process_value(json_value* value, int depth);
//
// ****************************************************************************************
bool playlist_process_playlist=false;
bool playlist_process_songs=false;
bool playlist_process_url=false;
bool playlist_process_id=false;
bool playlist_process_image=false;
bool playlist_process_name=false;
bool playlist_process_items=false;
char playlistname[256];
char playlistid[256];
char playlistgfx[2048];
char playlistgfx_top[2048];
// ****************************************************************************************
// INTERNAL
// process types in file playlist
// parse user playlist
//
// Set process flags for playlist_process_value(json_value* value, int depth,int x,MYSQL *conn) function
//
// ****************************************************************************************
void spotify_class::playlist_process_object(json_value* value, int depth,MYSQL *conn) {
bool debug_json=false;
int length, x;
if (value == NULL) {
return;
}
length = value->u.object.length;
for (x = 0; x < length; x++) {
playlist_print_depth_shift(depth);
if (debug_json) printf("object[%d].name = %s\n", x, value->u.object.values[x].name);
if (strcmp(value->u.object.values[x].name , "url" )==0) {
playlist_process_url=true;
}
if (strcmp(value->u.object.values[x].name , "id" )==0) {
playlist_process_id=true;
}
if (strcmp(value->u.object.values[x].name , "images" )==0) {
playlist_process_image=true;
}
if (strcmp(value->u.object.values[x].name , "name" )==0) {
playlist_process_name=true;
}
if (strcmp(value->u.object.values[x].name , "items" )==0) {
playlist_process_items=true;
}
playlist_process_value(value->u.object.values[x].value, depth+1,x,conn);
}
}
// ****************************************************************************************
//
// parse user playlist
//
// ****************************************************************************************
void spotify_class::playlist_process_array(json_value* value, int depth,MYSQL *conn) {
bool debug_json=false;
int length, x;
if (value == NULL) {
return;
}
length = value->u.array.length;
if (debug_json) printf("array\n");
for (x = 0; x < length; x++) {
playlist_process_value(value->u.array.values[x], depth,x,conn);
}
}
// ****************************************************************************************
// INTERNAL lolevel func
// json parser start call function playlist db update
// parse user playlist
//
// ****************************************************************************************
void spotify_class::playlist_process_value(json_value* value, int depth,int x,MYSQL *conn) {
char filename[512];
char downloadfilenamelong[2048];
MYSQL_RES *res;
MYSQL_ROW row;
char tempstring[1024];
char sql[8192];
bool debug_json=false;
bool playlistexist=false;
int j;
if (value == NULL) return;
if (value->type != json_object) {
if (debug_json) playlist_print_depth_shift(depth);
}
switch (value->type) {
case json_none:
if (debug_json) printf("none\n");
break;
case json_object:
playlist_process_object(value, depth+1,conn);
break;
case json_array:
playlist_process_array(value, depth+1,conn);
break;
case json_integer:
if (debug_json) printf("int: %10" PRId64 "\n", value->u.integer);
break;
case json_double:
if (debug_json) printf("double: %f\n", value->u.dbl);
break;
case json_string:
if (debug_json) printf("string: %s\n", value->u.string.ptr);
if (( playlist_process_id ) && ( depth == 5 ) && ( x == 3 )) {
if (debug_json) printf("id found = %s \n", value->u.string.ptr);
strcpy(playlistid,value->u.string.ptr);
playlist_process_id=false;
}
if (playlist_process_items) {
// set start of items in list
playlist_process_items=false;
}
if ( playlist_process_image ) {
//printf(" Process_image song *************************depth=%d x=%d url = %s ********************************************** \n",depth,x,value->u.string.ptr);
if (( depth == 8 ) && ( x == 1 )) {
}
playlist_process_image=false;
}
// works for songs not playlist
if (playlist_process_url) {
//printf(" Process_image song *************************depth=%d x=%d url = %s ********************************************** \n",depth,x,value->u.string.ptr);
//printf("Song gfx icon found = %s \n", value->u.string.ptr);
strcpy(filename,"");
get_webfilenamelong(filename,value->u.string.ptr);
strcpy(downloadfilenamelong,value->u.string.ptr);
if (strcmp(filename,"")!=0) {
//getuserhomedir(downloadfilenamelong);
strcpy(downloadfilenamelong,localuserhomedir);
strcat(downloadfilenamelong,"/");
strcat(downloadfilenamelong,spotify_gfx_path);
strcat(downloadfilenamelong,filename);
strcat(downloadfilenamelong,".jpg");
}
strcpy(playlistgfx,downloadfilenamelong);
playlist_process_url=false;
}
// get playlist name
// and create datdabase record playlist info record
if ((playlist_process_name) && (depth==5) && (x==5)) {
//if (debug_json) printf("Name found = %s id %s \n", value->u.string.ptr,playlistid);
strcpy(playlistname,value->u.string.ptr);
playlistexist=false;
snprintf(sql,sizeof(sql),"select id from mythtvcontroller.spotifycontentplaylist where playlistname like '%s' limit 1", playlistname );
try {
mysql_query(conn,sql);
res = mysql_store_result(conn);
if (res) {
while ((row = mysql_fetch_row(res)) != NULL) {
playlistexist=true;
}
}
// if not exist create playlist
if (!(playlistexist)) {
//printf("Song name insert : %s \n", playlistname );
snprintf(sql,sizeof(sql),"insert into mythtvcontroller.spotifycontentplaylist values ('%s','%s','%s',0)",playlistname,playlistgfx,playlistid);
mysql_query(conn,sql);
res = mysql_store_result(conn);
}
playlist_process_name=false;
}
catch (...) {
write_logfile(logfile,(char *) "Error update mysql playlist db.");
}
}
break;
case json_boolean:
if (debug_json) printf("bool: %d\n", value->u.boolean);
break;
}
}
// ****************************************************************************************
//
// Get a List of Current User's Playlists (playlist NOT songs)
// IN use
// get users play lists
// write to spotify_users_playlist.json
//
//
// ****************************************************************************************
int spotify_class::download_user_playlist(char *spotifytoken,int startofset) {
std::size_t foundpos;
std::string response_string;
std::string response_val;
int httpCode;
CURLcode res;
struct curl_slist *chunk = NULL;
char doget[2048];
char data[4096];
char call[4096];
CURL *curl;
FILE *tokenfil;
FILE *outfile;
char *base64_code;
char post_playlist_data[1024];
char errbuf[CURL_ERROR_SIZE];
char auth_kode[2048];
curl = curl_easy_init();
strcpy(auth_kode,"Authorization: Bearer ");
strcat(auth_kode,spotifytoken);
if (curl) {
// add userinfo + basic auth
//curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_easy_setopt(curl, CURLOPT_XOAUTH2_BEARER,spotifytoken);
//curl_easy_setopt(curl, CURLOPT_USERNAME, spotify_client_id);
//curl_easy_setopt(curl, CURLOPT_PASSWORD, spotify_secret_id);
/* Add a custom header */
chunk = curl_slist_append(chunk, "Accept: application/json");
chunk = curl_slist_append(chunk, "Content-Type: application/json");
chunk = curl_slist_append(chunk, auth_kode);
//
curl_easy_setopt(curl, CURLOPT_URL, "https://api.spotify.com/v1/me/playlists");
// ask libcurl to use TLS version 1.3 or later
curl_easy_setopt(curl, CURLOPT_SSLVERSION, (long)CURL_SSLVERSION_TLSv1_3);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_writeFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (char *) &response_string);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_POST, 0);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
// set type post
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
/* Add a custom header */
errbuf[0] = 0;
// set type post
//curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
//sprintf(post_playlist_data,"{\"grant_type\":\"refresh_token\",\"refresh_token\":%s}",spotifytoken_refresh);
snprintf(post_playlist_data,sizeof(post_playlist_data),"limit=50&offset=%d",startofset);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_playlist_data);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(post_playlist_data));
outfile=fopen("spotify_users_playlist.json","wb");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, file_write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
size_t len = strlen(errbuf);
fprintf(stderr, "\nlibcurl: (%d) ", res);
if(len)
fprintf(stderr, "%s%s", errbuf,((errbuf[len - 1] != '\n') ? "\n" : ""));
else
fprintf(stderr, "%s\n", curl_easy_strerror(res));
}
// get respons code
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
}
if (httpCode == 200) {
write_logfile(logfile,(char *) "Download ok code 200");
//printf("%s \n", response_string.c_str());
//printf("resp length %d \n",response_string.length());
//value = json_parse((char *) response_string.c_str(),response_string.length()); // parser
//process_value_playinfo(value, 0,0); // fill play info
} else {
fprintf(stderr,"Error code httpCode %d \n. ",httpCode);
fprintf(stderr,"Curl error: %s\n", curl_easy_strerror(res));
}
// always cleanup
fclose(outfile);
curl_easy_cleanup(curl);
}
return(httpCode);
}
// ****************************************************************************************
//
// Check bout spotify have data in db.
// in use in main
//
// ****************************************************************************************
bool spotify_class::spotify_check_spotifydb_empty() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_RES *res1;
MYSQL_ROW row1;
char *database = (char *) dbname;
bool dbexist=false;
conn = mysql_init(NULL);
try {
if (conn) {
if (mysql_real_connect(conn, configmysqlhost,configmysqluser, configmysqlpass, database, 0, NULL, 0)) {
mysql_error(conn);
//exit(1);
}
mysql_query(conn,"set NAMES 'utf8'");
res = mysql_store_result(conn);
// test about rss table exist
mysql_query(conn,"SELECT playlistname from mythtvcontroller.spotifycontentplaylist limit 1");
res = mysql_store_result(conn);
if (res) {
while ((row = mysql_fetch_row(res)) != NULL) {
dbexist = true;
}
}
mysql_close(conn);
}
}
catch (...) {
write_logfile(logfile,(char *) "Error use mysql");
}
return(dbexist);
}
// ****************************************************************************************
//
// Get users playlist
// in use
// The default view
//
// ****************************************************************************************
int spotify_class::spotify_get_user_playlists(bool force,int startoffset) {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_RES *res1;
MYSQL_ROW row1;
char *database = (char *) dbname;
char sql[8192];
char doget[4096];
char filename[4096];
char temptxt[80];
char downloadfilenamelong[4096];
int curl_error;
FILE *json_file;
char *jons_string;
struct stat filestatus;
int file_size;
char* file_contents;
json_char* json;
json_value* value;
bool playlistexist;
bool dbexist=false;
loaded_antal=0;
unsigned int spotify_playlistantal=0;
unsigned int spotify_playlistantal_loaded=0;
bool spotifyplaylistloader_done=false;
try {
conn = mysql_init(NULL);
if (conn==NULL) {
fprintf(stderr,"Error opwn mysql connection.\n");
exit(1);
}
if (conn) {
if (!(mysql_real_connect(conn, configmysqlhost,configmysqluser, configmysqlpass, database, 0, NULL, 0))) {
if (mysql_error(conn)) {
printf("ERROR OPEN MYSQL.\n");
fprintf(stderr, "Error: %s\n", mysql_error(conn));
//exit(1);
}
}
mysql_query(conn,"set NAMES 'utf8'");
res = mysql_store_result(conn);
// test about rss table exist
mysql_query(conn,"SELECT feedtitle from mythtvcontroller.spotifycontentarticles limit 1");
res = mysql_store_result(conn);