-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathYTMusicClient.swift
More file actions
1279 lines (1028 loc) · 50.9 KB
/
YTMusicClient.swift
File metadata and controls
1279 lines (1028 loc) · 50.9 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
// swiftlint:disable file_length
import CryptoKit
import Foundation
import os
// MARK: - PaginatedContentType
/// Identifies content types that support pagination via continuation tokens.
/// Used internally by YTMusicClient to manage pagination state generically.
enum PaginatedContentType: String, Hashable, Sendable {
case home = "FEmusic_home"
case explore = "FEmusic_explore"
case charts = "FEmusic_charts"
case moodsAndGenres = "FEmusic_moods_and_genres"
case newReleases = "FEmusic_new_releases"
case podcasts = "FEmusic_podcasts"
/// Display name for logging.
var displayName: String {
switch self {
case .home: "home"
case .explore: "explore"
case .charts: "charts"
case .moodsAndGenres: "moods and genres"
case .newReleases: "new releases"
case .podcasts: "podcasts"
}
}
}
// MARK: - YTMusicClient
/// Client for making authenticated requests to YouTube Music's internal API.
@MainActor
// swiftlint:disable:next type_body_length
final class YTMusicClient: YTMusicClientProtocol {
private let authService: AuthService
private let webKitManager: WebKitManager
private let session: URLSession
private let logger = DiagnosticsLogger.api
/// YouTube Music API base URL.
private static let baseURL = "https://music.youtube.com/youtubei/v1"
/// API key used in requests (extracted from YouTube Music web client).
private static let apiKey = "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX30"
/// Client version for WEB_REMIX.
private static let clientVersion = "1.20231204.01.00"
/// Centralized storage for continuation tokens keyed by content type.
private var continuationTokens: [PaginatedContentType: String] = [:]
init(authService: AuthService, webKitManager: WebKitManager = .shared) {
self.authService = authService
self.webKitManager = webKitManager
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = [
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
"Accept-Encoding": "gzip, deflate, br",
]
// Enable HTTP pipelining for faster sequential requests
configuration.httpShouldUsePipelining = true
// Increase connection pool for parallel requests
configuration.httpMaximumConnectionsPerHost = 6
// Use shared URL cache for transport-level caching
configuration.urlCache = URLCache.shared
configuration.requestCachePolicy = .useProtocolCachePolicy
// Reduce timeout for faster failure detection
configuration.timeoutIntervalForRequest = 15
configuration.timeoutIntervalForResource = 30
self.session = URLSession(configuration: configuration)
}
// MARK: - Generic Pagination Methods
/// Fetches paginated content for the given content type.
/// Stores the continuation token for subsequent calls to `getContinuation`.
private func fetchPaginatedContent(type: PaginatedContentType) async throws -> HomeResponse {
self.logger.info("Fetching \(type.displayName) page")
let body: [String: Any] = [
"browseId": type.rawValue,
]
let data = try await request("browse", body: body, ttl: APICache.TTL.home)
let response = HomeResponseParser.parse(data)
// Store continuation token for progressive loading
let token = HomeResponseParser.extractContinuationToken(from: data)
self.continuationTokens[type] = token
let hasMore = token != nil
self.logger.info("\(type.displayName.capitalized) page loaded: \(response.sections.count) initial sections, hasMore: \(hasMore)")
return response
}
/// Fetches the next batch of sections for the given content type via continuation.
/// Returns nil if no more sections are available.
private func fetchContinuation(type: PaginatedContentType) async throws -> [HomeSection]? {
guard let token = continuationTokens[type] else {
self.logger.debug("No \(type.displayName) continuation token available")
return nil
}
self.logger.info("Fetching \(type.displayName) continuation")
do {
let continuationData = try await requestContinuation(token)
let additionalSections = HomeResponseParser.parseContinuation(continuationData)
self.continuationTokens[type] = HomeResponseParser.extractContinuationTokenFromContinuation(continuationData)
let hasMore = self.continuationTokens[type] != nil
self.logger.info("\(type.displayName.capitalized) continuation loaded: \(additionalSections.count) sections, hasMore: \(hasMore)")
return additionalSections
} catch {
self.logger.warning("Failed to fetch \(type.displayName) continuation: \(error.localizedDescription)")
self.continuationTokens[type] = nil
throw error
}
}
/// Checks whether more sections are available for the given content type.
private func hasMoreSections(for type: PaginatedContentType) -> Bool {
self.continuationTokens[type] != nil
}
// MARK: - Public API Methods (Protocol Conformance)
/// Fetches the home page content (initial sections only for fast display).
/// Call `getHomeContinuation` to load additional sections progressively.
func getHome() async throws -> HomeResponse {
try await self.fetchPaginatedContent(type: .home)
}
/// Fetches the next batch of home sections via continuation.
/// Returns nil if no more sections are available.
func getHomeContinuation() async throws -> [HomeSection]? {
try await self.fetchContinuation(type: .home)
}
/// Whether more home sections are available to load.
var hasMoreHomeSections: Bool {
self.hasMoreSections(for: .home)
}
/// Fetches the explore page content (initial sections only for fast display).
func getExplore() async throws -> HomeResponse {
try await self.fetchPaginatedContent(type: .explore)
}
/// Fetches the next batch of explore sections via continuation.
func getExploreContinuation() async throws -> [HomeSection]? {
try await self.fetchContinuation(type: .explore)
}
/// Whether more explore sections are available to load.
var hasMoreExploreSections: Bool {
self.hasMoreSections(for: .explore)
}
/// Fetches the charts page content (initial sections only for fast display).
func getCharts() async throws -> HomeResponse {
try await self.fetchPaginatedContent(type: .charts)
}
/// Fetches the next batch of charts sections via continuation.
func getChartsContinuation() async throws -> [HomeSection]? {
try await self.fetchContinuation(type: .charts)
}
/// Whether more charts sections are available to load.
var hasMoreChartsSections: Bool {
self.hasMoreSections(for: .charts)
}
/// Fetches the moods and genres page content (initial sections only for fast display).
func getMoodsAndGenres() async throws -> HomeResponse {
try await self.fetchPaginatedContent(type: .moodsAndGenres)
}
/// Fetches the next batch of moods and genres sections via continuation.
func getMoodsAndGenresContinuation() async throws -> [HomeSection]? {
try await self.fetchContinuation(type: .moodsAndGenres)
}
/// Whether more moods and genres sections are available to load.
var hasMoreMoodsAndGenresSections: Bool {
self.hasMoreSections(for: .moodsAndGenres)
}
/// Fetches the new releases page content (initial sections only for fast display).
func getNewReleases() async throws -> HomeResponse {
try await self.fetchPaginatedContent(type: .newReleases)
}
/// Fetches the next batch of new releases sections via continuation.
func getNewReleasesContinuation() async throws -> [HomeSection]? {
try await self.fetchContinuation(type: .newReleases)
}
/// Whether more new releases sections are available to load.
var hasMoreNewReleasesSections: Bool {
self.hasMoreSections(for: .newReleases)
}
/// Fetches the podcasts page content (initial sections only for fast display).
func getPodcasts() async throws -> [PodcastSection] {
self.logger.info("Fetching podcasts page")
let body: [String: Any] = [
"browseId": PaginatedContentType.podcasts.rawValue,
]
let data = try await request("browse", body: body, ttl: APICache.TTL.home)
let sections = PodcastParser.parseDiscovery(data)
// Store continuation token for progressive loading
let token = HomeResponseParser.extractContinuationToken(from: data)
self.continuationTokens[.podcasts] = token
let hasMore = token != nil
self.logger.info("Podcasts page loaded: \(sections.count) initial sections, hasMore: \(hasMore)")
return sections
}
/// Fetches the next batch of podcasts sections via continuation.
func getPodcastsContinuation() async throws -> [PodcastSection]? {
guard let token = continuationTokens[.podcasts] else {
self.logger.debug("No podcasts continuation token available")
return nil
}
self.logger.info("Fetching podcasts continuation")
do {
let continuationData = try await requestContinuation(token)
let additionalSections = PodcastParser.parseContinuation(continuationData)
self.continuationTokens[.podcasts] = HomeResponseParser.extractContinuationTokenFromContinuation(continuationData)
let hasMore = self.continuationTokens[.podcasts] != nil
self.logger.info("Podcasts continuation loaded: \(additionalSections.count) sections, hasMore: \(hasMore)")
return additionalSections
} catch {
self.logger.warning("Failed to fetch podcasts continuation: \(error.localizedDescription)")
self.continuationTokens[.podcasts] = nil
throw error
}
}
/// Whether more podcasts sections are available to load.
var hasMorePodcastsSections: Bool {
self.hasMoreSections(for: .podcasts)
}
/// Fetches details for a podcast show including its episodes.
func getPodcastShow(browseId: String) async throws -> PodcastShowDetail {
self.logger.info("Fetching podcast show: \(browseId)")
let body: [String: Any] = [
"browseId": browseId,
]
let data = try await request("browse", body: body, ttl: APICache.TTL.playlist)
let showDetail = PodcastParser.parseShowDetail(data, showId: browseId)
self.logger.info("Parsed podcast show '\(showDetail.show.title)' with \(showDetail.episodes.count) episodes")
return showDetail
}
/// Fetches more episodes for a podcast show via continuation.
func getPodcastEpisodesContinuation(token: String) async throws -> PodcastEpisodesContinuation {
self.logger.info("Fetching more podcast episodes via continuation")
let data = try await requestContinuation(token, ttl: APICache.TTL.playlist)
let continuation = PodcastParser.parseEpisodesContinuation(data)
self.logger.info("Parsed \(continuation.episodes.count) more episodes")
return continuation
}
/// Makes a continuation request for browse endpoints.
private func requestContinuation(_ token: String, ttl: TimeInterval? = APICache.TTL.home) async throws -> [String: Any] {
let body: [String: Any] = [
"continuation": token,
]
return try await self.request("browse", body: body, ttl: ttl)
}
/// Makes a continuation request for next/queue endpoints.
private func requestContinuation(_ token: String, body additionalBody: [String: Any]) async throws -> [String: Any] {
var body = additionalBody
body["continuation"] = token
return try await self.request("next", body: body)
}
/// Searches for content.
func search(query: String) async throws -> SearchResponse {
self.logger.info("Searching for: \(query)")
let body: [String: Any] = [
"query": query,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let response = SearchResponseParser.parse(data)
self.logger.info("Search found \(response.songs.count) songs, \(response.albums.count) albums, \(response.artists.count) artists, \(response.playlists.count) playlists")
return response
}
/// Searches for songs only (filtered search).
func searchSongs(query: String) async throws -> [Song] {
self.logger.info("Searching songs only for: \(query)")
// YouTube Music API params for songs filter
// Derived from: EgWKAQ (filtered) + II (songs) + AWoMEA4QChADEAQQCRAF (no spelling correction)
let songsFilterParams = "EgWKAQIIAWoMEA4QChADEAQQCRAF"
let body: [String: Any] = [
"query": query,
"params": songsFilterParams,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let songs = SearchResponseParser.parseSongsOnly(data)
self.logger.info("Songs search found \(songs.count) songs")
return songs
}
// MARK: - Filtered Search with Pagination
/// Filter params for YouTube Music search.
/// Pattern: EgWKAQ (base) + filter code + AWoMEA4QChADEAQQCRAF (no spelling correction)
private enum SearchFilterParams {
static let songs = "EgWKAQIIAWoMEA4QChADEAQQCRAF"
static let albums = "EgWKAQIYAWoMEA4QChADEAQQCRAF"
static let artists = "EgWKAQIgAWoMEA4QChADEAQQCRAF"
static let playlists = "EgWKAQIoAWoMEA4QChADEAQQCRAF"
/// Featured playlists (first-party YouTube Music curated playlists)
static let featuredPlaylists = "EgeKAQQoADgBagwQDhAKEAMQBBAJEAU="
/// Community playlists (user-created playlists)
static let communityPlaylists = "EgeKAQQoAEABagwQDhAKEAMQBBAJEAU="
/// Podcasts (podcast shows)
static let podcasts = "EgWKAQJQAWoQEBAQCRAEEAMQBRAKEBUQEQ%3D%3D"
}
/// Continuation token for filtered search pagination.
private var searchContinuationToken: String?
/// Whether more search results are available to load.
var hasMoreSearchResults: Bool {
self.searchContinuationToken != nil
}
/// Searches for albums only (filtered search with pagination).
func searchAlbums(query: String) async throws -> SearchResponse {
self.logger.info("Searching albums only for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.albums,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (albums, token) = SearchResponseParser.parseAlbumsOnly(data)
self.searchContinuationToken = token
self.logger.info("Albums search found \(albums.count) albums, hasMore: \(token != nil)")
return SearchResponse(songs: [], albums: albums, artists: [], playlists: [], continuationToken: token)
}
/// Searches for artists only (filtered search with pagination).
func searchArtists(query: String) async throws -> SearchResponse {
self.logger.info("Searching artists only for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.artists,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (artists, token) = SearchResponseParser.parseArtistsOnly(data)
self.searchContinuationToken = token
self.logger.info("Artists search found \(artists.count) artists, hasMore: \(token != nil)")
return SearchResponse(songs: [], albums: [], artists: artists, playlists: [], continuationToken: token)
}
/// Searches for playlists only (filtered search with pagination).
func searchPlaylists(query: String) async throws -> SearchResponse {
self.logger.info("Searching playlists only for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.playlists,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (playlists, token) = SearchResponseParser.parsePlaylistsOnly(data)
self.searchContinuationToken = token
self.logger.info("Playlists search found \(playlists.count) playlists, hasMore: \(token != nil)")
return SearchResponse(songs: [], albums: [], artists: [], playlists: playlists, continuationToken: token)
}
/// Searches for featured playlists only (YouTube Music curated playlists).
func searchFeaturedPlaylists(query: String) async throws -> SearchResponse {
self.logger.info("Searching featured playlists only for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.featuredPlaylists,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (playlists, token) = SearchResponseParser.parsePlaylistsOnly(data)
self.searchContinuationToken = token
self.logger.info("Featured playlists search found \(playlists.count) playlists, hasMore: \(token != nil)")
return SearchResponse(songs: [], albums: [], artists: [], playlists: playlists, continuationToken: token)
}
/// Searches for community playlists only (user-created playlists).
func searchCommunityPlaylists(query: String) async throws -> SearchResponse {
self.logger.info("Searching community playlists only for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.communityPlaylists,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (playlists, token) = SearchResponseParser.parsePlaylistsOnly(data)
self.searchContinuationToken = token
self.logger.info("Community playlists search found \(playlists.count) playlists, hasMore: \(token != nil)")
return SearchResponse(songs: [], albums: [], artists: [], playlists: playlists, continuationToken: token)
}
/// Searches for podcasts only (podcast shows).
func searchPodcasts(query: String) async throws -> SearchResponse {
self.logger.info("Searching podcasts only for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.podcasts,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (podcastShows, token) = SearchResponseParser.parsePodcastsOnly(data)
self.searchContinuationToken = token
self.logger.info("Podcasts search found \(podcastShows.count) shows, hasMore: \(token != nil)")
return SearchResponse(
songs: [],
albums: [],
artists: [],
playlists: [],
podcastShows: podcastShows,
continuationToken: token
)
}
/// Searches for songs only with pagination support.
func searchSongsWithPagination(query: String) async throws -> SearchResponse {
self.logger.info("Searching songs with pagination for: \(query)")
let body: [String: Any] = [
"query": query,
"params": SearchFilterParams.songs,
]
let data = try await request("search", body: body, ttl: APICache.TTL.search)
let (songs, token) = SearchResponseParser.parseSongsWithContinuation(data)
self.searchContinuationToken = token
self.logger.info("Songs search found \(songs.count) songs, hasMore: \(token != nil)")
return SearchResponse(songs: songs, albums: [], artists: [], playlists: [], continuationToken: token)
}
/// Fetches the next batch of search results via continuation.
/// Returns nil if no more results are available.
func getSearchContinuation() async throws -> SearchResponse? {
guard let token = searchContinuationToken else {
self.logger.debug("No search continuation token available")
return nil
}
self.logger.info("Fetching search continuation")
do {
let continuationData = try await requestContinuation(token, ttl: APICache.TTL.search)
let response = SearchResponseParser.parseContinuation(continuationData)
self.searchContinuationToken = response.continuationToken
self.logger.info("Search continuation loaded: \(response.allItems.count) items, hasMore: \(response.hasMore)")
return response
} catch {
self.logger.warning("Failed to fetch search continuation: \(error.localizedDescription)")
self.searchContinuationToken = nil
throw error
}
}
/// Clears the search continuation token.
func clearSearchContinuation() {
self.searchContinuationToken = nil
}
/// Fetches search suggestions for autocomplete.
func getSearchSuggestions(query: String) async throws -> [SearchSuggestion] {
guard !query.isEmpty else {
return []
}
self.logger.debug("Fetching search suggestions for: \(query)")
let body: [String: Any] = [
"input": query,
]
// No caching for suggestions - they're ephemeral
let data = try await request("music/get_search_suggestions", body: body)
let suggestions = SearchSuggestionsParser.parse(data)
self.logger.debug("Found \(suggestions.count) suggestions")
return suggestions
}
/// Fetches the user's library playlists.
func getLibraryPlaylists() async throws -> [Playlist] {
self.logger.info("Fetching library playlists")
let body: [String: Any] = [
"browseId": "FEmusic_liked_playlists",
]
let data = try await request("browse", body: body, ttl: APICache.TTL.library)
let playlists = PlaylistParser.parseLibraryPlaylists(data)
self.logger.info("Parsed \(playlists.count) library playlists")
return playlists
}
/// Fetches the user's library content including playlists and podcast shows.
func getLibraryContent() async throws -> PlaylistParser.LibraryContent {
self.logger.info("Fetching library content (playlists + podcasts)")
// Use library_landing to get all content types including podcasts
let body: [String: Any] = [
"browseId": "FEmusic_library_landing",
]
let data = try await request("browse", body: body, ttl: APICache.TTL.library)
return PlaylistParser.parseLibraryContent(data)
}
// MARK: - Liked Songs with Pagination
/// Continuation token for liked songs pagination.
private var likedSongsContinuationToken: String?
/// Whether more liked songs are available to load.
var hasMoreLikedSongs: Bool {
self.likedSongsContinuationToken != nil
}
/// Fetches the user's liked songs with pagination support.
/// Uses VLLM (Liked Music playlist) which returns all songs with proper pagination,
/// unlike FEmusic_liked_videos which is limited to ~13 songs.
func getLikedSongs() async throws -> LikedSongsResponse {
self.logger.info("Fetching liked songs via VLLM playlist")
let body: [String: Any] = [
"browseId": "VLLM",
]
let data = try await request("browse", body: body, ttl: APICache.TTL.library)
// Use playlist parser since VLLM returns playlist format
let playlistResponse = PlaylistParser.parsePlaylistWithContinuation(data, playlistId: "LM")
// Store continuation token for pagination
self.likedSongsContinuationToken = playlistResponse.continuationToken
let hasMore = playlistResponse.hasMore
// Convert to LikedSongsResponse format
let response = LikedSongsResponse(
songs: playlistResponse.detail.tracks,
continuationToken: playlistResponse.continuationToken
)
self.logger.info("Parsed \(response.songs.count) liked songs, hasMore: \(hasMore)")
return response
}
/// Fetches the next batch of liked songs via continuation.
/// Returns nil if no more songs are available.
func getLikedSongsContinuation() async throws -> LikedSongsResponse? {
guard let token = likedSongsContinuationToken else {
self.logger.debug("No liked songs continuation token available")
return nil
}
self.logger.info("Fetching liked songs continuation")
do {
let continuationData = try await requestContinuation(token)
// Use playlist continuation parser since VLLM returns playlist format
let playlistResponse = PlaylistParser.parsePlaylistContinuation(continuationData)
self.likedSongsContinuationToken = playlistResponse.continuationToken
let hasMore = playlistResponse.hasMore
// Convert to LikedSongsResponse format
let response = LikedSongsResponse(
songs: playlistResponse.tracks,
continuationToken: playlistResponse.continuationToken
)
self.logger.info("Liked songs continuation loaded: \(response.songs.count) songs, hasMore: \(hasMore)")
return response
} catch {
self.logger.warning("Failed to fetch liked songs continuation: \(error.localizedDescription)")
self.likedSongsContinuationToken = nil
throw error
}
}
// MARK: - Playlist with Pagination
/// Continuation token for playlist tracks pagination.
private var playlistContinuationToken: String?
/// Whether more playlist tracks are available to load.
var hasMorePlaylistTracks: Bool {
self.playlistContinuationToken != nil
}
/// Fetches playlist details including tracks with pagination support.
func getPlaylist(id: String) async throws -> PlaylistTracksResponse {
self.logger.info("Fetching playlist: \(id)")
// Handle different ID formats:
// - VL... = playlist (already has prefix)
// - PL... = playlist (needs VL prefix)
// - RD... = radio/mix (use as-is)
// - OLAK... = album (use as-is)
// - MPRE... = album (use as-is)
let browseId: String = if id.hasPrefix("VL") || id.hasPrefix("RD") || id.hasPrefix("OLAK") || id.hasPrefix("MPRE") || id.hasPrefix("UC") {
id
} else if id.hasPrefix("PL") {
"VL\(id)"
} else {
"VL\(id)"
}
let body: [String: Any] = [
"browseId": browseId,
]
let data = try await request("browse", body: body, ttl: APICache.TTL.playlist)
let response = PlaylistParser.parsePlaylistWithContinuation(data, playlistId: id)
// Store continuation token for pagination
self.playlistContinuationToken = response.continuationToken
let hasMore = response.hasMore
self.logger.info("Parsed playlist '\(response.detail.title)' with \(response.detail.tracks.count) tracks, hasMore: \(hasMore)")
return response
}
/// Fetches all tracks for a playlist using the queue endpoint.
/// This returns all tracks in a single request without pagination.
/// More reliable for radio playlists (RDCLAK prefix) where continuation doesn't work correctly.
func getPlaylistAllTracks(playlistId: String) async throws -> [Song] {
// Strip VL prefix if present since get_queue uses raw playlist ID
let rawPlaylistId: String = if playlistId.hasPrefix("VL") {
String(playlistId.dropFirst(2))
} else {
playlistId
}
self.logger.info("Fetching all playlist tracks via queue: \(rawPlaylistId)")
let body: [String: Any] = [
"playlistId": rawPlaylistId,
]
// No caching for queue endpoint - we want fresh results each time
let data = try await request("music/get_queue", body: body, ttl: nil)
let tracks = PlaylistParser.parseQueueTracks(data)
self.logger.info("Fetched \(tracks.count) tracks from queue endpoint")
return tracks
}
/// Fetches the next batch of playlist tracks via continuation.
/// Returns nil if no more tracks are available.
func getPlaylistContinuation() async throws -> PlaylistContinuationResponse? {
guard let token = playlistContinuationToken else {
self.logger.debug("No playlist continuation token available")
return nil
}
self.logger.info("Fetching playlist continuation")
do {
let continuationData = try await requestContinuation(token)
let response = PlaylistParser.parsePlaylistContinuation(continuationData)
self.playlistContinuationToken = response.continuationToken
let hasMore = response.hasMore
self.logger.info("Playlist continuation loaded: \(response.tracks.count) tracks, hasMore: \(hasMore)")
return response
} catch {
self.logger.warning("Failed to fetch playlist continuation: \(error.localizedDescription)")
self.playlistContinuationToken = nil
throw error
}
}
/// Fetches artist details including their songs and albums.
func getArtist(id: String) async throws -> ArtistDetail {
self.logger.info("Fetching artist: \(id)")
let body: [String: Any] = [
"browseId": id,
]
let data = try await request("browse", body: body, ttl: APICache.TTL.artist)
let topKeys = Array(data.keys)
self.logger.debug("Artist response top-level keys: \(topKeys)")
let detail = ArtistParser.parseArtistDetail(data, artistId: id)
self.logger.info("Parsed artist '\(detail.artist.name)' with \(detail.songs.count) songs and \(detail.albums.count) albums")
return detail
}
/// Fetches all songs for an artist using the songs browse endpoint.
func getArtistSongs(browseId: String, params: String?) async throws -> [Song] {
self.logger.info("Fetching artist songs: \(browseId)")
var body: [String: Any] = [
"browseId": browseId,
]
if let params {
body["params"] = params
}
let data = try await request("browse", body: body, ttl: APICache.TTL.artist)
let songs = ArtistParser.parseArtistSongs(data)
self.logger.info("Parsed \(songs.count) artist songs")
return songs
}
// MARK: - Lyrics
/// Fetches lyrics for a song by video ID.
/// - Parameter videoId: The video ID of the song
/// - Returns: Lyrics if available, or Lyrics.unavailable if not
func getLyrics(videoId: String) async throws -> Lyrics {
self.logger.info("Fetching lyrics for: \(videoId)")
// Step 1: Get the lyrics browse ID from the "next" endpoint
let nextBody: [String: Any] = [
"videoId": videoId,
"enablePersistentPlaylistPanel": true,
"isAudioOnly": true,
"tunerSettingValue": "AUTOMIX_SETTING_NORMAL",
]
let nextData = try await request("next", body: nextBody)
guard let lyricsBrowseId = LyricsParser.extractLyricsBrowseId(from: nextData) else {
self.logger.info("No lyrics available for: \(videoId)")
return .unavailable
}
// Step 2: Fetch the actual lyrics using the browse ID
let browseBody: [String: Any] = [
"browseId": lyricsBrowseId,
]
let browseData = try await request("browse", body: browseBody, ttl: APICache.TTL.lyrics)
let lyrics = LyricsParser.parse(from: browseData)
self.logger.info("Fetched lyrics for \(videoId): \(lyrics.isAvailable ? "available" : "unavailable")")
return lyrics
}
// MARK: - Radio Queue
/// Fetches a radio queue (similar songs) based on a video ID.
/// Uses the "next" endpoint with a radio playlist ID (RDAMVM prefix).
/// - Parameter videoId: The seed video ID to base the radio on
/// - Returns: An array of songs forming the radio queue
func getRadioQueue(videoId: String) async throws -> [Song] {
self.logger.info("Fetching radio queue for: \(videoId)")
// Use RDAMVM prefix to request a radio mix based on the song
let body: [String: Any] = [
"videoId": videoId,
"playlistId": "RDAMVM\(videoId)",
"enablePersistentPlaylistPanel": true,
"isAudioOnly": true,
"tunerSettingValue": "AUTOMIX_SETTING_NORMAL",
]
let data = try await request("next", body: body)
let result = RadioQueueParser.parse(from: data)
self.logger.info("Fetched radio queue with \(result.songs.count) songs")
return result.songs
}
/// Fetches a mix queue from a playlist ID (e.g., artist mix "RDEM...").
/// Uses the "next" endpoint with the provided playlist ID.
/// - Parameters:
/// - playlistId: The mix playlist ID (e.g., "RDEM..." for artist mix)
/// - startVideoId: Optional starting video ID
/// - Returns: RadioQueueResult with songs and continuation token for infinite mix
func getMixQueue(playlistId: String, startVideoId: String?) async throws -> RadioQueueResult {
self.logger.info("Fetching mix queue for playlist: \(playlistId)")
var body: [String: Any] = [
"playlistId": playlistId,
"enablePersistentPlaylistPanel": true,
"isAudioOnly": true,
"tunerSettingValue": "AUTOMIX_SETTING_NORMAL",
]
// Add video ID if provided to start at a specific track
if let videoId = startVideoId {
body["videoId"] = videoId
}
let data = try await request("next", body: body)
let result = RadioQueueParser.parse(from: data)
self.logger.info("Fetched mix queue with \(result.songs.count) songs, hasContinuation: \(result.continuationToken != nil)")
return result
}
/// Fetches more songs for a mix queue using a continuation token.
/// - Parameter continuationToken: The continuation token from a previous getMixQueue call
/// - Returns: RadioQueueResult with additional songs and next continuation token
func getMixQueueContinuation(continuationToken: String) async throws -> RadioQueueResult {
self.logger.info("Fetching mix queue continuation")
let body: [String: Any] = [
"enablePersistentPlaylistPanel": true,
"isAudioOnly": true,
]
let data = try await requestContinuation(continuationToken, body: body)
let result = RadioQueueParser.parseContinuation(from: data)
self.logger.info("Fetched \(result.songs.count) more songs, hasContinuation: \(result.continuationToken != nil)")
return result
}
// MARK: - Song Metadata
/// Fetches full song metadata including feedbackTokens for library management.
/// Uses the `next` endpoint to get track details with library status.
/// - Parameter videoId: The video ID of the song
/// - Returns: A Song with full metadata including feedbackTokens and inLibrary status
func getSong(videoId: String) async throws -> Song {
self.logger.info("Fetching song metadata: \(videoId)")
// Use the "next" endpoint which returns track info with feedbackTokens
let body: [String: Any] = [
"videoId": videoId,
"enablePersistentPlaylistPanel": true,
"isAudioOnly": true,
"tunerSettingValue": "AUTOMIX_SETTING_NORMAL",
]
let data = try await request("next", body: body, ttl: APICache.TTL.songMetadata)
let song = try SongMetadataParser.parse(data, videoId: videoId)
self.logger.info("Parsed song '\(song.title)' - inLibrary: \(song.isInLibrary ?? false), hasTokens: \(song.feedbackTokens != nil)")
return song
}
// MARK: - Mood/Genre Category
/// Fetches content for a moods/genres category page.
/// These are browse pages that return sections of songs/playlists, not playlist tracks.
/// - Parameters:
/// - browseId: The browse ID (e.g., "FEmusic_moods_and_genres_category")
/// - params: Optional params for the category (extracted from navigation button)
/// - Returns: HomeResponse with sections for the category
func getMoodCategory(browseId: String, params: String?) async throws -> HomeResponse {
self.logger.info("Fetching mood category: \(browseId)")
var body: [String: Any] = [
"browseId": browseId,
]
if let params {
body["params"] = params
}
let data = try await request("browse", body: body, ttl: APICache.TTL.home)
let response = HomeResponseParser.parse(data)
self.logger.info("Mood category loaded: \(response.sections.count) sections")
return response
}
// MARK: - Like/Library Actions
/// Rates a song (like/dislike/indifferent).
/// - Parameters:
/// - videoId: The video ID of the song to rate
/// - rating: The rating to apply (like, dislike, or indifferent to remove rating)
func rateSong(videoId: String, rating: LikeStatus) async throws {
self.logger.info("Rating song \(videoId) with \(rating.rawValue)")
let body: [String: Any] = [
"target": ["videoId": videoId],
]
// Endpoint varies by rating type
let endpoint = switch rating {
case .like:
"like/like"
case .dislike:
"like/dislike"
case .indifferent:
"like/removelike"
}
_ = try await self.request(endpoint, body: body)
self.logger.info("Successfully rated song \(videoId)")
// Invalidate mutation-affected caches in a single pass
APICache.shared.invalidateMutationCaches()
}
/// Adds or removes a song from the user's library.
/// - Parameter feedbackTokens: Tokens obtained from song metadata (use add token to add, remove token to remove)
func editSongLibraryStatus(feedbackTokens: [String]) async throws {
guard !feedbackTokens.isEmpty else {
self.logger.warning("No feedback tokens provided for library edit")
return
}
self.logger.info("Editing song library status with \(feedbackTokens.count) tokens")
let body: [String: Any] = [
"feedbackTokens": feedbackTokens,
]
_ = try await self.request("feedback", body: body)
self.logger.info("Successfully edited library status")
// Invalidate mutation-affected caches in a single pass
APICache.shared.invalidateMutationCaches()
}
/// Adds a playlist to the user's library using the like/like endpoint.
/// This is equivalent to the "Add to Library" action in YouTube Music.
/// - Parameter playlistId: The playlist ID to add to library
func subscribeToPlaylist(playlistId: String) async throws {
self.logger.info("Adding playlist to library: \(playlistId)")
// Remove VL prefix if present for the API call
let cleanId = playlistId.hasPrefix("VL") ? String(playlistId.dropFirst(2)) : playlistId
let body: [String: Any] = [
"target": ["playlistId": cleanId],
]
_ = try await self.request("like/like", body: body)
self.logger.info("Successfully added playlist \(playlistId) to library")
// Invalidate library cache so UI updates
APICache.shared.invalidate(matching: "browse:")
}
/// Removes a playlist from the user's library using the like/removelike endpoint.
/// This is equivalent to the "Remove from Library" action in YouTube Music.
/// - Parameter playlistId: The playlist ID to remove from library
func unsubscribeFromPlaylist(playlistId: String) async throws {
self.logger.info("Removing playlist from library: \(playlistId)")
// Remove VL prefix if present for the API call
let cleanId = playlistId.hasPrefix("VL") ? String(playlistId.dropFirst(2)) : playlistId
let body: [String: Any] = [
"target": ["playlistId": cleanId],
]
_ = try await self.request("like/removelike", body: body)
self.logger.info("Successfully removed playlist \(playlistId) from library")
// Invalidate library cache so UI updates
APICache.shared.invalidate(matching: "browse:")
}