-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathplex_client.cpp
More file actions
1824 lines (1573 loc) · 73.6 KB
/
Copy pathplex_client.cpp
File metadata and controls
1824 lines (1573 loc) · 73.6 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
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
#include "plex_client.h"
#include <iostream>
#include "audio_decoder.h"
#include "plex_xml.h"
#include <curl/curl.h>
#include <random>
#include <cmath>
#include <sstream>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <mutex>
#include <thread>
#include <queue>
#include <map>
#include <condition_variable>
#include <cstdio>
#include <memory>
#include <array>
#include <ctime>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <errno.h>
#include <cstring>
#ifdef __APPLE__
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#elif __linux__
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#endif
namespace PlexTUI {
// Respect config enable_debug_logging (set from PlexClient ctor). No logging when false.
static std::atomic<bool> g_lyrics_debug_logging{false};
// Global log file path (set from main.cpp via config)
static std::string g_debug_log_file_path;
void PlexClient::set_debug_log_file_path(const std::string& path) {
g_debug_log_file_path = path;
}
static void log_lyrics_fetch(const std::string& message) {
if (!g_lyrics_debug_logging.load()) return;
// Determine log file path (use global if set, otherwise default)
std::string log_file;
if (!g_debug_log_file_path.empty()) {
log_file = g_debug_log_file_path;
} else {
// Default: next to config.ini
const char* home = getenv("HOME");
if (home) {
log_file = std::string(home) + "/.config/plex-tui/debug.log";
} else {
log_file = "debug.log"; // Fallback to current directory
}
}
std::ofstream log(log_file, std::ios::app);
if (log.is_open()) {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
char time_str[64];
std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", std::localtime(&time_t));
log << "[" << time_str << "] [LYRICS] " << message << std::endl;
}
std::cerr << "[LYRICS] " << message << std::endl;
}
// Lyrics request structure for async fetching
struct LyricsRequest {
std::string track_id;
std::string artist;
std::string title;
std::string album;
uint32_t duration_seconds; // Duration in seconds for LRCLIB API
LyricsRequest(const std::string& id, const std::string& art, const std::string& tit,
const std::string& alb = "", uint32_t dur_sec = 0)
: track_id(id), artist(art), title(tit), album(alb), duration_seconds(dur_sec) {}
};
// Pimpl for hiding CURL implementation details
struct PlexClient::Impl {
CURL* curl = nullptr;
std::string response_buffer;
AudioLevels audio_levels;
// Mutex to protect playback state from concurrent access
mutable std::mutex playback_mutex;
// Simulated playback state for demo
bool is_playing = false;
uint32_t position = 0;
Track current_track;
std::chrono::steady_clock::time_point playback_start_time;
// Async lyrics fetching infrastructure
std::thread lyrics_thread;
std::mutex lyrics_mutex;
std::condition_variable lyrics_cv;
std::queue<LyricsRequest> lyrics_queue;
std::map<std::string, std::string> lyrics_results; // track_id -> lyrics
std::map<std::string, std::vector<LyricLine>> synced_lyrics_results; // track_id -> time-synced lyrics
std::map<std::string, bool> lyrics_in_progress; // track_id -> fetching status
bool lyrics_thread_running = false;
// No curl handle needed - we use subprocess (popen) for thread-safe lyrics fetching
static size_t write_callback(void* contents, size_t size, size_t nmemb, void* userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// Static write callback for lyrics thread (thread-safe)
// This must be a plain C function pointer - no lambda captures
static size_t lyrics_write_callback(void* contents, size_t size, size_t nmemb, void* userp) {
// Validate all inputs
if (!userp || !contents) {
return 0;
}
if (size == 0 || nmemb == 0) {
return 0; // Nothing to write
}
// Cast user pointer to string pointer
std::string* data = static_cast<std::string*>(userp);
if (!data) {
return 0;
}
// Validate size to prevent overflow
size_t total_size = size * nmemb;
if (total_size == 0 || total_size > 10 * 1024 * 1024) {
return 0; // Too large or invalid
}
// Check current size to prevent excessive growth
if (data->length() > 10 * 1024 * 1024) {
return 0; // Already too large
}
// Append data with exception handling
try {
const char* src = static_cast<const char*>(contents);
data->append(src, total_size);
return total_size;
} catch (const std::bad_alloc&) {
// Out of memory - stop transfer
return 0;
} catch (...) {
// Any other exception - stop transfer
return 0;
}
}
// Lyrics fetching thread function
void lyrics_thread_func() {
// No curl handle needed - we use subprocess (popen) for lyrics fetching
// This avoids all thread-safety issues with libcurl
while (lyrics_thread_running) {
bool has_request = false;
LyricsRequest request("", "", "", "");
// Wait for a request (with timeout for responsive shutdown)
{
std::unique_lock<std::mutex> lock(lyrics_mutex);
// Use timeout so we can check thread_running more frequently for smooth quit
lyrics_cv.wait_for(lock, std::chrono::milliseconds(100), [this] {
return !lyrics_queue.empty() || !lyrics_thread_running;
});
if (!lyrics_thread_running) {
log_lyrics_fetch("Thread shutdown signal received, exiting loop");
break;
}
if (!lyrics_queue.empty()) {
request = lyrics_queue.front();
lyrics_queue.pop();
has_request = true;
// Mark as in progress
lyrics_in_progress[request.track_id] = true;
}
}
if (has_request) {
// Check again before processing (in case shutdown happened while we had the lock)
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
log_lyrics_fetch("Thread shutdown detected before processing request");
break;
}
}
// First, try LRCLIB API (time-synced lyrics)
std::vector<LyricLine> synced_lyrics;
std::string lyrics;
std::string lrclib_result = fetch_lrclib_lyrics(request);
if (!lrclib_result.empty()) {
// Parse LRC format from LRCLIB response
log_lyrics_fetch("Calling parse_lrc_format with " + std::to_string(lrclib_result.length()) + " chars");
synced_lyrics = parse_lrc_format(lrclib_result);
if (!synced_lyrics.empty()) {
log_lyrics_fetch("SOURCE: LRCLIB API (time-synced) - " + request.title + " by " + request.artist + " (" + std::to_string(synced_lyrics.size()) + " lines)");
} else {
// LRCLIB returned something but couldn't parse - treat as plain text fallback
lyrics = lrclib_result;
log_lyrics_fetch("LRCLIB returned lyrics but not in parseable LRC format, using as plain text");
}
} else {
// LRCLIB failed, fallback to lyrics.ovh (non-time-synced, manual scrolling)
lyrics = fetch_lyrics_for_request(request);
}
// Store result (even if empty - indicates fetch completed)
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
// Only store if thread is still running (avoid race condition)
if (lyrics_thread_running) {
lyrics_results[request.track_id] = lyrics;
synced_lyrics_results[request.track_id] = synced_lyrics;
lyrics_in_progress[request.track_id] = false;
}
// Note: If lyrics is empty, it means no lyrics were found
// This is different from "still fetching" (which would be in_progress = true)
}
}
}
// Thread is shutting down
log_lyrics_fetch("Lyrics thread shutting down cleanly");
}
// Parse LRC format lyrics (from LRCLIB API)
// Returns vector of time-synced lyric lines
std::vector<LyricLine> parse_lrc_format(const std::string& lyrics_text) {
std::vector<LyricLine> lines;
if (lyrics_text.empty()) {
log_lyrics_fetch("parse_lrc_format: Empty lyrics text");
return lines;
}
// Check if it looks like LRC format (contains timestamp patterns like [mm:ss.xx])
if (lyrics_text.find('[') == std::string::npos || lyrics_text.find(':') == std::string::npos) {
log_lyrics_fetch("parse_lrc_format: Doesn't look like LRC format (no [ or :)");
return lines;
}
// Log first 200 chars for debugging
std::string preview = lyrics_text.substr(0, std::min(lyrics_text.length(), size_t(200)));
log_lyrics_fetch("parse_lrc_format: Parsing LRC format (" + std::to_string(lyrics_text.length()) + " chars), preview: " + preview);
// Parse as LRC format - handle both actual newlines and escaped \n
std::string text = lyrics_text;
// Replace escaped newlines with actual newlines if present
size_t pos = 0;
while ((pos = text.find("\\n", pos)) != std::string::npos) {
text.replace(pos, 2, "\n");
pos += 1;
}
std::istringstream stream(text);
std::string line;
int line_count = 0;
while (std::getline(stream, line)) {
line_count++;
// Skip empty lines
if (line.empty()) continue;
// Skip metadata tags like [ar:Artist], [ti:Title], etc.
// But NOT timestamps like [00:06.40] - timestamps have digits before the colon
if (line.length() > 2 && line[0] == '[') {
size_t colon_pos = line.find(':');
size_t bracket_pos = line.find(']');
if (colon_pos != std::string::npos && colon_pos < bracket_pos) {
// Check if it's a metadata tag (has letters before colon) vs timestamp (has digits)
// Metadata: [ar:Artist], [ti:Title] - has letters before colon
// Timestamp: [00:06.40] - has digits before colon
bool is_metadata = false;
if (colon_pos > 1) {
// Check characters between [ and : - if any are letters, it's metadata
for (size_t i = 1; i < colon_pos; ++i) {
if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {
is_metadata = true;
break;
}
}
}
if (is_metadata) {
continue; // Skip metadata tags
}
// Otherwise it's a timestamp, continue parsing
}
}
// Parse timestamp: [mm:ss.xx] or [mm:ss.xx][mm:ss.xx] (multiple timestamps)
size_t pos = 0;
while (pos < line.length() && line[pos] == '[') {
pos++; // Skip '['
size_t timestamp_end = line.find(']', pos);
if (timestamp_end == std::string::npos) break;
std::string timestamp_str = line.substr(pos, timestamp_end - pos);
pos = timestamp_end + 1; // Skip ']'
// Parse mm:ss.xx format (also handles mm:ss format without centiseconds)
// Format can be: 00:17.12 (minutes:seconds.centiseconds) or 0:17.12
int minutes = 0, seconds = 0, centiseconds = 0;
int parsed = sscanf(timestamp_str.c_str(), "%d:%d.%d", &minutes, &seconds, ¢iseconds);
if (parsed >= 2) {
// If no centiseconds parsed, default to 0
if (parsed == 2) {
centiseconds = 0;
}
// Convert to milliseconds: minutes*60*1000 + seconds*1000 + centiseconds*10
// Example: 00:17.12 = 0*60000 + 17*1000 + 12*10 = 17120 ms
uint32_t timestamp_ms = (minutes * 60 + seconds) * 1000 + centiseconds * 10;
// Get the lyric text (everything after the last timestamp)
std::string lyric_text;
if (pos < line.length()) {
lyric_text = line.substr(pos);
// Trim whitespace
while (!lyric_text.empty() && (lyric_text.front() == ' ' || lyric_text.front() == '\t')) {
lyric_text.erase(lyric_text.begin());
}
}
if (!lyric_text.empty()) {
lines.push_back(LyricLine(timestamp_ms, lyric_text));
}
}
}
}
// Sort by timestamp
std::sort(lines.begin(), lines.end(), [](const LyricLine& a, const LyricLine& b) {
return a.timestamp_ms < b.timestamp_ms;
});
log_lyrics_fetch("parse_lrc_format: Parsed " + std::to_string(lines.size()) + " time-synced lines from " + std::to_string(line_count) + " input lines");
return lines;
}
// Note: LRC file loading removed - server-side file paths are not accessible from client
// Time-synced lyrics are now fetched from LRCLIB API instead
// Fetch time-synced lyrics from LRCLIB API
// Returns LRC format string that can be parsed
std::string fetch_lrclib_lyrics(const LyricsRequest& request) {
if (request.artist.empty() || request.title.empty() || request.duration_seconds == 0) {
log_lyrics_fetch("Skipping LRCLIB fetch - missing artist, title, or duration");
return "";
}
log_lyrics_fetch("Fetching from LRCLIB: \"" + request.title + "\" by \"" + request.artist + "\" (duration: " + std::to_string(request.duration_seconds) + "s)");
// Check if thread is being shut down
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
log_lyrics_fetch("Thread shutting down, skipping LRCLIB fetch");
return "";
}
}
try {
// URL encode parameters for curl
std::string encoded_artist = url_encode(request.artist);
std::string encoded_title = url_encode(request.title);
std::string encoded_album = url_encode(request.album);
// Build LRCLIB API URL: /api/get?track_name=...&artist_name=...&album_name=...&duration=...
std::string lrclib_url = "https://lrclib.net/api/get?track_name=" + encoded_title +
"&artist_name=" + encoded_artist +
"&album_name=" + encoded_album +
"&duration=" + std::to_string(request.duration_seconds);
log_lyrics_fetch("LRCLIB URL: " + lrclib_url);
// Build curl command (use curl command-line tool via subprocess)
// Don't use --fail so we can check the response content even on HTTP errors
std::string curl_cmd = "curl -s -m 10 --silent --show-error \"";
curl_cmd += lrclib_url;
curl_cmd += "\"";
log_lyrics_fetch("Executing curl command for LRCLIB (subprocess)");
FILE* pipe = popen(curl_cmd.c_str(), "r");
if (!pipe) {
log_lyrics_fetch("ERROR: Failed to open pipe for LRCLIB curl command");
return "";
}
// Check for shutdown while reading
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
pclose(pipe);
log_lyrics_fetch("Thread shutdown detected during LRCLIB fetch");
return "";
}
}
// Read response (read all data, not just one line)
std::array<char, 8192> buffer;
std::string response;
size_t total_read = 0;
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
// Check for shutdown periodically
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
pclose(pipe);
log_lyrics_fetch("Thread shutdown detected while reading LRCLIB response");
return "";
}
}
size_t len = strlen(buffer.data());
response += buffer.data();
total_read += len;
// Safety limit: max 1MB response
if (total_read > 1024 * 1024) {
log_lyrics_fetch("WARNING: LRCLIB response exceeds 1MB, truncating");
break;
}
}
// Remove trailing newline if present
while (!response.empty() && (response.back() == '\n' || response.back() == '\r')) {
response.pop_back();
}
pclose(pipe); // Don't check status - check response content instead
if (response.empty()) {
log_lyrics_fetch("LRCLIB API returned empty response");
return "";
}
log_lyrics_fetch("Received LRCLIB response: " + std::to_string(response.length()) + " bytes");
// Log response preview for debugging (first 200 chars)
if (response.length() > 0) {
std::string preview = response.substr(0, std::min(response.length(), size_t(200)));
log_lyrics_fetch("LRCLIB response preview: " + preview + (response.length() > 200 ? "..." : ""));
}
// Check for error response (404 Not Found)
// Error responses have: {"code": 404, "name": "TrackNotFound", "message": "..."}
// Successful responses also have "name" field, so check for the error structure specifically
if (response.find("\"code\":") != std::string::npos &&
(response.find("TrackNotFound") != std::string::npos ||
response.find("\"message\":") != std::string::npos)) {
// Log the actual error for debugging
std::string error_code = parse_json_field(response, "code");
std::string error_name = parse_json_field(response, "name");
std::string error_msg = parse_json_field(response, "message");
log_lyrics_fetch("LRCLIB API returned error: code=" + error_code + ", name=" + error_name + ", message=" + error_msg);
return "";
}
// Parse JSON response to extract syncedLyrics
// Simple JSON parsing for "syncedLyrics" field
log_lyrics_fetch("Attempting to parse syncedLyrics from response...");
std::string synced_lyrics = parse_json_field(response, "syncedLyrics");
if (!synced_lyrics.empty()) {
// Log first 300 chars to see the actual format
std::string preview = synced_lyrics.substr(0, std::min(synced_lyrics.length(), size_t(300)));
log_lyrics_fetch("Extracted syncedLyrics (" + std::to_string(synced_lyrics.length()) + " chars), preview: " + preview);
log_lyrics_fetch("SOURCE: LRCLIB API (time-synced) - " + request.title + " by " + request.artist + " (" + std::to_string(synced_lyrics.length()) + " chars)");
return synced_lyrics;
} else {
log_lyrics_fetch("syncedLyrics field not found or empty in response");
}
// Fallback to plainLyrics if syncedLyrics not available
log_lyrics_fetch("Attempting to parse plainLyrics from response...");
std::string plain_lyrics = parse_json_field(response, "plainLyrics");
if (!plain_lyrics.empty()) {
log_lyrics_fetch("SOURCE: LRCLIB API (plain text, not time-synced) - " + request.title + " by " + request.artist);
return plain_lyrics;
} else {
log_lyrics_fetch("plainLyrics field not found or empty in response");
}
// Check if response contains the field name at all
if (response.find("syncedLyrics") == std::string::npos && response.find("plainLyrics") == std::string::npos) {
log_lyrics_fetch("ERROR: Response does not contain syncedLyrics or plainLyrics fields at all");
}
log_lyrics_fetch("LRCLIB API returned no lyrics (no syncedLyrics or plainLyrics field)");
return "";
} catch (const std::exception& e) {
log_lyrics_fetch("ERROR: Exception in LRCLIB fetch: " + std::string(e.what()));
return "";
} catch (...) {
log_lyrics_fetch("ERROR: Unknown exception in LRCLIB fetch");
return "";
}
}
// Simple URL encoding helper
std::string url_encode(const std::string& str) {
std::string encoded;
encoded.reserve(str.length() * 3); // Worst case: all chars need encoding
for (char c : str) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
} else if (c == ' ') {
encoded += "%20";
} else {
// URL encode special characters
char hex[4];
snprintf(hex, sizeof(hex), "%%%02X", static_cast<unsigned char>(c));
encoded += hex;
}
}
return encoded;
}
// Simple JSON field parser (extracts value from "fieldName":"value")
// Handles multi-line strings with escaped characters
// Note: This function properly unescapes \n, \r, \t, etc. from JSON strings
std::string parse_json_field(const std::string& json, const std::string& field_name) {
std::string search_pattern = "\"" + field_name + "\"";
size_t pos = json.find(search_pattern);
if (pos == std::string::npos) {
return "";
}
// Find the colon after the field name
pos = json.find(':', pos);
if (pos == std::string::npos) {
return "";
}
pos++; // Move past colon
// Skip whitespace
while (pos < json.length() && (json[pos] == ' ' || json[pos] == '\t' || json[pos] == '\n' || json[pos] == '\r')) {
pos++;
}
if (pos >= json.length()) {
return "";
}
// Check if value is null
if (pos + 4 <= json.length() && json.substr(pos, 4) == "null") {
return "";
}
// Check if value is a string (starts with ")
if (json[pos] != '"') {
return ""; // Not a string value
}
pos++; // Skip opening quote
// Find the closing quote, handling escaped quotes and newlines
std::string value;
value.reserve(json.length()); // Pre-allocate
bool in_escape = false;
for (size_t i = pos; i < json.length(); ++i) {
if (in_escape) {
// Handle escape sequences
if (json[i] == 'n') {
value += '\n';
} else if (json[i] == 'r') {
value += '\r';
} else if (json[i] == 't') {
value += '\t';
} else if (json[i] == '\\') {
value += '\\';
} else if (json[i] == '"') {
value += '"'; // Escaped quote
} else {
value += '\\'; // Unknown escape, keep backslash
value += json[i];
}
in_escape = false;
} else if (json[i] == '\\') {
in_escape = true;
} else if (json[i] == '"') {
// Unescaped quote - end of string
break;
} else {
value += json[i];
}
}
return value;
}
// Fetch lyrics from lyrics.ovh API (fallback, non-time-synced, manual scrolling)
// Uses subprocess (curl command-line) to avoid thread-safety issues with libcurl
std::string fetch_lyrics_for_request(const LyricsRequest& request) {
// Fetch from lyrics.ovh API (fallback for non-time-synced lyrics)
if (request.artist.empty() || request.title.empty()) {
log_lyrics_fetch("Skipping lyrics fetch - empty artist or title");
return "";
}
// Check if thread is being shut down - exit early
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
log_lyrics_fetch("Thread shutting down, skipping fetch for: " + request.title);
return "";
}
}
log_lyrics_fetch("Starting lyrics fetch for: \"" + request.title + "\" by \"" + request.artist + "\"");
try {
// URL encode artist and title for curl command
std::string encoded_artist;
std::string encoded_title;
// URL encode artist and title (curl will handle it, but we need proper encoding)
// Use curl's built-in URL encoding via curl_easy_escape if available, or manual encoding
for (char c : request.artist) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') {
encoded_artist += c;
} else if (c == ' ') {
encoded_artist += "%20";
} else {
// URL encode special characters
char hex[4];
snprintf(hex, sizeof(hex), "%%%02X", static_cast<unsigned char>(c));
encoded_artist += hex;
}
}
for (char c : request.title) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') {
encoded_title += c;
} else if (c == ' ') {
encoded_title += "%20";
} else {
// URL encode special characters
char hex[4];
snprintf(hex, sizeof(hex), "%%%02X", static_cast<unsigned char>(c));
encoded_title += hex;
}
}
std::string lyrics_url = "https://api.lyrics.ovh/v1/" + encoded_artist + "/" + encoded_title;
log_lyrics_fetch("URL: " + lyrics_url);
// Build curl command (use curl command-line tool via subprocess)
// Escape single quotes in URL for shell safety
std::string escaped_url = lyrics_url;
size_t pos = 0;
while ((pos = escaped_url.find("'", pos)) != std::string::npos) {
escaped_url.replace(pos, 1, "'\\''");
pos += 4;
}
std::string curl_cmd = "curl -s -S --max-time 5 --connect-timeout 3 --location '";
curl_cmd += escaped_url;
curl_cmd += "' 2>/dev/null";
log_lyrics_fetch("Executing curl command (subprocess)");
// Use popen to execute curl command and read output
// This is thread-safe - each subprocess runs independently
FILE* pipe = popen(curl_cmd.c_str(), "r");
if (!pipe) {
log_lyrics_fetch("ERROR: Failed to start curl subprocess");
return ""; // Failed to start subprocess
}
// Check if thread is being shut down before reading (for smooth quit)
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
log_lyrics_fetch("Thread shutdown detected, closing pipe");
pclose(pipe); // Close pipe if shutting down
return "";
}
}
// Read response from subprocess (thread-safe - each pipe is independent)
std::string response;
response.reserve(8192); // Pre-allocate
char buffer[4096];
size_t bytes_read = 0;
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
// Check if shutting down during read
{
std::lock_guard<std::mutex> lock(lyrics_mutex);
if (!lyrics_thread_running) {
log_lyrics_fetch("Thread shutdown detected during read, closing pipe");
pclose(pipe);
return "";
}
}
size_t len = strlen(buffer);
if (len > 0) {
response.append(buffer, len);
bytes_read += len;
// Safety limit: max 1MB response
if (bytes_read > 1024 * 1024) {
break;
}
}
}
pclose(pipe); // Close pipe (status not needed - we check response content)
log_lyrics_fetch("Received response: " + std::to_string(response.length()) + " bytes");
if (response.length() > 0 && response.length() < 200) {
log_lyrics_fetch("Response preview: " + response.substr(0, std::min(response.length(), size_t(100))));
}
// Check if we got a response
// Note: curl might return non-zero status for some errors, but still have partial data
// So we check response content first, then status
if (response.empty()) {
log_lyrics_fetch("ERROR: Empty response from API");
return "";
}
// Remove any trailing newlines/whitespace
while (!response.empty() && (response.back() == '\n' || response.back() == '\r' || response.back() == ' ')) {
response.pop_back();
}
if (response.empty()) {
log_lyrics_fetch("ERROR: Response contains only whitespace");
return ""; // Only whitespace
}
// Parse JSON response from lyrics.ovh API
// Format: {"lyrics":"...lyrics text with escaped newlines..."}
// Handle both success and error responses
if (response.find("\"lyrics\"") == std::string::npos) {
// No lyrics key - might be error like {"error":"Not found"}
// Check if it's an error response
if (response.find("\"error\"") != std::string::npos) {
log_lyrics_fetch("API returned error: lyrics not found");
return "";
}
log_lyrics_fetch("ERROR: Unknown response format (no 'lyrics' key found)");
return "";
}
// Find "lyrics" key and extract value
size_t lyrics_key_pos = response.find("\"lyrics\"");
if (lyrics_key_pos == std::string::npos) {
return "";
}
// Find the colon after "lyrics"
size_t colon_pos = response.find(':', lyrics_key_pos);
if (colon_pos == std::string::npos || colon_pos >= response.length() - 1) {
return "";
}
// Skip whitespace after colon
size_t value_start = colon_pos + 1;
while (value_start < response.length() &&
(response[value_start] == ' ' || response[value_start] == '\t' || response[value_start] == '\n' || response[value_start] == '\r')) {
value_start++;
}
if (value_start >= response.length()) {
return "";
}
// Check if value is a string (starts with ")
if (response[value_start] != '"') {
return ""; // Not a string value (might be null)
}
value_start++; // Skip opening quote
// Find the closing quote, handling escaped quotes and newlines
std::string lyrics;
lyrics.reserve(response.length()); // Pre-allocate
bool in_escape = false;
for (size_t i = value_start; i < response.length(); ++i) {
if (in_escape) {
// Handle escape sequences
if (response[i] == 'n') {
lyrics += '\n';
} else if (response[i] == 'r') {
lyrics += '\r';
} else if (response[i] == 't') {
lyrics += '\t';
} else if (response[i] == '\\') {
lyrics += '\\';
} else if (response[i] == '"') {
lyrics += '"'; // Escaped quote
} else {
lyrics += '\\'; // Unknown escape, keep backslash
lyrics += response[i];
}
in_escape = false;
} else if (response[i] == '\\') {
in_escape = true;
} else if (response[i] == '"') {
// Unescaped quote - end of string
break;
} else {
lyrics += response[i];
}
}
// Return lyrics if we found any (trim whitespace)
if (!lyrics.empty()) {
// Trim leading/trailing whitespace
while (!lyrics.empty() && (lyrics.front() == ' ' || lyrics.front() == '\n' || lyrics.front() == '\r' || lyrics.front() == '\t')) {
lyrics.erase(lyrics.begin());
}
while (!lyrics.empty() && (lyrics.back() == ' ' || lyrics.back() == '\n' || lyrics.back() == '\r' || lyrics.back() == '\t')) {
lyrics.pop_back();
}
if (!lyrics.empty()) {
log_lyrics_fetch("SOURCE: lyrics.ovh API (NOT time-synced) - SUCCESS: Extracted lyrics (" + std::to_string(lyrics.length()) + " chars, " +
std::to_string(std::count(lyrics.begin(), lyrics.end(), '\n') + 1) + " lines)");
return lyrics;
}
}
log_lyrics_fetch("WARNING: Parsed lyrics but result is empty after trimming");
} catch (const std::exception& e) {
// Subprocess or parsing failed
log_lyrics_fetch("EXCEPTION during lyrics fetch: " + std::string(e.what()));
return "";
} catch (...) {
log_lyrics_fetch("UNKNOWN EXCEPTION during lyrics fetch");
return "";
}
log_lyrics_fetch("No lyrics found for: " + request.title + " by " + request.artist);
return ""; // No lyrics found
}
};
PlexClient::PlexClient(const std::string& server_url, const std::string& token, bool enable_debug_logging)
: server_url(server_url), token(token), pimpl(std::make_unique<Impl>()) {
g_lyrics_debug_logging.store(enable_debug_logging);
curl_global_init(CURL_GLOBAL_DEFAULT);
pimpl->curl = curl_easy_init();
// Initialize audio decoder and album art
audio_decoder = std::make_unique<AudioDecoder>();
album_art = std::make_unique<AlbumArt>();
// Start lyrics fetching thread
pimpl->lyrics_thread_running = true;
pimpl->lyrics_thread = std::thread(&Impl::lyrics_thread_func, pimpl.get());
}
PlexClient::~PlexClient() {
stop_audio_capture();
// Stop lyrics thread cleanly
if (pimpl) {
log_lyrics_fetch("Shutting down lyrics thread...");
{
std::lock_guard<std::mutex> lock(pimpl->lyrics_mutex);
pimpl->lyrics_thread_running = false;
}
pimpl->lyrics_cv.notify_all();
if (pimpl->lyrics_thread.joinable()) {
// Wait for thread to finish (with timeout would be better, but join is simpler)
pimpl->lyrics_thread.join();
log_lyrics_fetch("Lyrics thread joined successfully");
}
}
if (pimpl && pimpl->curl) {
curl_easy_cleanup(pimpl->curl);
}
curl_global_cleanup();
}
bool PlexClient::connect() {
if (server_url.empty() || token.empty()) {
return false;
}
if (!pimpl || !pimpl->curl) {
return false; // Curl not initialized
}
// Test connection with a simple request
std::string response = make_request("/");
if (response.empty() || response.length() < 10) {
// Connection failed, but don't crash
connected = false;
return false;
}
// Check if we got valid XML response
if (response.find("<?xml") == std::string::npos &&
response.find("<MediaContainer") == std::string::npos) {
connected = false;
return false;
}
connected = true;
return true;
}
std::string PlexClient::make_request(const std::string& endpoint, const std::string& method) {
if (!pimpl || !pimpl->curl) return "";
pimpl->response_buffer.clear();
std::string url = server_url + endpoint;
// Add token to URL if not already present
if (url.find("X-Plex-Token") == std::string::npos) {
url += (url.find('?') != std::string::npos ? "&" : "?");
url += "X-Plex-Token=" + token;
}
// Reset curl options
curl_easy_reset(pimpl->curl);
curl_easy_setopt(pimpl->curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(pimpl->curl, CURLOPT_WRITEFUNCTION, Impl::write_callback);
curl_easy_setopt(pimpl->curl, CURLOPT_WRITEDATA, &pimpl->response_buffer);
curl_easy_setopt(pimpl->curl, CURLOPT_TIMEOUT, 5L); // 5 second timeout
curl_easy_setopt(pimpl->curl, CURLOPT_CONNECTTIMEOUT, 3L); // 3 second connect timeout
// SSL options for HTTPS
curl_easy_setopt(pimpl->curl, CURLOPT_SSL_VERIFYPEER, 0L); // Allow self-signed certs
curl_easy_setopt(pimpl->curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(pimpl->curl, CURLOPT_FOLLOWLOCATION, 1L); // Follow redirects
// Add Plex token header
struct curl_slist* headers = nullptr;
std::string token_header = "X-Plex-Token: " + token;
headers = curl_slist_append(headers, token_header.c_str());
headers = curl_slist_append(headers, "Accept: application/xml");
curl_easy_setopt(pimpl->curl, CURLOPT_HTTPHEADER, headers);
if (method == "POST") {
curl_easy_setopt(pimpl->curl, CURLOPT_POST, 1L);
} else if (method == "PUT") {
curl_easy_setopt(pimpl->curl, CURLOPT_CUSTOMREQUEST, "PUT");
}
CURLcode res = curl_easy_perform(pimpl->curl);
curl_slist_free_all(headers);
if (res != CURLE_OK) {
return "";
}
return pimpl->response_buffer;
}
// Real Plex API implementations
int PlexClient::get_music_library_id() {
if (!connected) return -1;
std::string response = make_request("/library/sections");
if (response.empty() || response.length() < 10) return -1;
try {
PlexXML::Node root = PlexXML::parse(response);
auto directories = root.find_all("Directory");
for (const auto& dir : directories) {
std::string type = dir.get_attr("type");
if (type == "artist") {
std::string key = dir.get_attr("key", "-1");
if (key != "-1" && !key.empty()) {
return std::stoi(key);
}
}
}
} catch (...) {