summaryrefslogtreecommitdiffstats
path: root/MusicConverter/helpers/MusicKITApi.swift
blob: e47241a56dfc02e1c32513e69811f072f28b6bd9 (plain)
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
//
//  MusicKITApi.swift
//  MusicConverter
//
//  Created by Finn Behrens on 02.04.21.
//

import Foundation
import StoreKit
import MediaPlayer

class AppleMusicApi: ObservableObject {
    static let token = Bundle.main.infoDictionary?["MUSIC_KIT_API_KEY"] as! String
    var userToken: String?
    var storeFront: StoreFront?
    var songLoader: URLSession = URLSession(configuration: .default)
    
    func updateUserToken(completion: @escaping (Result<String, Error>) -> Void) {
        var err: Error?
        //let semaphore = DispatchSemaphore(value: 0)
        SKCloudServiceController().requestCapabilities(completionHandler: { (cloudServiceCapability, error) in
            guard error == nil else {
                completion(.failure(error!))
                err = error
                return
            }
            
            if !cloudServiceCapability.contains(.addToCloudMusicLibrary) {
                print("error: cannot add items to music library")
                // TODO: error handling
            }
            
            if !cloudServiceCapability.contains(.musicCatalogPlayback) {
                print("error: cannot play music from catalog")
            }
            
            print("got capabilitties")
            //semaphore.signal()
        })
        //semaphore.wait()
        /*guard err == nil else {
            print("got error")
           return
        }*/
        SKCloudServiceController().requestUserToken(forDeveloperToken: Self.token) { (recievedToken, error) in
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            self.userToken = recievedToken
            completion(.success(recievedToken!))
        }
    }
    
    func updateStoreFrontID(completion: @escaping(Result<String, Error>) -> Void) {
        guard userToken != nil else {
            completion(.failure(MusicKitError.NoUserTokenError))
            return
        }
        let musicURL = URL(string: "https://api.music.apple.com/v1/me/storefront")!
        var musicRequest = URLRequest(url: musicURL)
        musicRequest.httpMethod = "GET"
        musicRequest.addValue("Bearer \(Self.token)", forHTTPHeaderField: "Authorization")
        musicRequest.addValue(self.userToken!, forHTTPHeaderField: "Music-User-Token")
        
        URLSession.shared.dataTask(with: musicRequest) { (data, response, error) in
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            do {
                let decodedData = try JSONDecoder().decode(musicData<StoreFront>.self, from: data!)
                self.storeFront = decodedData.data!.first
                guard self.storeFront != nil else {
                    completion(.failure(MusicKitError.NoStoreFront))
                    return
                }
                completion(.success(self.storeFront!.id))
            } catch {
                print("data: \(String(decoding: data!, as: UTF8.self))")
                print("error decoding: \(error)")
                completion(.failure(error))
                return
            }
        }
        .resume()
    }
    
    public func fetchForIsrc(isrc: String, completion: @escaping (Result<[Song], Error>) -> Void) {
        guard userToken != nil else {
            completion(.failure(MusicKitError.NoUserTokenError))
            return
        }
        guard storeFront != nil else {
            completion(.failure(MusicKitError.NoStoreFront))
            return
        }
        
        guard let musicURL = URL(string: "https://api.music.apple.com/v1/catalog/\(self.storeFront!.id)/songs?filter[isrc]=\(isrc)") else {
            completion(.failure(MusicKitError.InvalidUrl))
            return
        }
        
        let musicRequest = self.buildRequest(url: musicURL)
        
        self.songLoader.dataTask(with: musicRequest) { (data, response, error) in
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            do {
                let decodedData = try JSONDecoder().decode(musicData<Song>.self, from: data!)
                completion(.success(decodedData.data!))
            } catch {
                print("data: \(String(decoding: data!, as: UTF8.self))")
                print("error song: \(error)")
                completion(.failure(error))
                return
            }
        }
        .resume()
    }
    
    public func getPicture(song: Song, x: Int = 0, y: Int = 0, dataCompletion: @escaping (Result<Data, Error>) -> Void) {
        let artwork = song.attributes.artwork
        guard x < artwork.height && y < artwork.height else {
            dataCompletion(.failure(MusicKitError.InvalidImageResulotion))
            return
        }
        var x = x
        var y = y
        if x == 0 {
            x = artwork.height
        }
        if y == 0 {
            y = artwork.width
        }
        
        var url = artwork.url
        url = url.replacingOccurrences(of: "{h}", with: x.description)
        url = url.replacingOccurrences(of: "{w}", with: y.description)
        
        guard let url = URL(string: url) else {
            dataCompletion(.failure(MusicKitError.InvalidUrl))
            return
        }
        
        let imageRequest = self.buildRequest(url: url)
        
        URLSession.shared.dataTask(with: imageRequest) { (data, response, error) in
            guard error == nil else {
                dataCompletion(.failure(error!))
                return
            }
            
            dataCompletion(.success(data!))
        }
        .resume()
    }
    
    public func getPicture(song: Song, x: Int = 0, y: Int = 0, completion: @escaping (Result<UIImage?, Error>) -> Void) {
        getPicture(song: song, x: x, y: y, dataCompletion: {result in
            switch result {
            case .failure(let e):
                completion(.failure(e))
            case .success(let d):
                completion(.success(UIImage(data: d)))
            }
        })
    }

    
    //private func buildRequest(urlString: String) -> URLRequest
    private func buildRequest(url: URL) -> URLRequest {
        var musicRequest = URLRequest(url: url)
        musicRequest.httpMethod = "GET"
        musicRequest.addValue("Bearer \(Self.token)", forHTTPHeaderField: "Authorization")
        musicRequest.addValue(self.userToken!, forHTTPHeaderField: "Music-User-Token")
        
        return musicRequest
    }
    
    public func convertPlaylist(playlist: [NATrack], updateCallback: @escaping (NATrack, [Song]) -> Void, completion: @escaping (Error?) -> Void) {
        var pos = 0;
        
        var callback: (Result<[Song], Error>) -> Void = {_ in}
        callback = { result in
            switch result {
            case .failure(let e):
                completion(e)
                return
            case .success(let d):
                print("found \(d.count) songs for \(playlist[pos-1].name)")
                updateCallback(playlist[pos-1], d)
                if pos < playlist.count {
                    var curr = playlist[pos]
                    var isrc = curr.isrc
                    if isrc == nil {
                        print("\(curr.name): isrc empty, skipping...")
                        // TODO: more error handling?
                        while isrc == nil {
                            pos += 1;
                            isrc = playlist[pos].isrc
                        }
                        curr = playlist[pos]
                    }
                    pos += 1;
                    self.fetchForIsrc(isrc: isrc!, completion: callback)
                } else {
                    completion(nil)
                }
            }
        }
        
        var curr = playlist[pos]
        var isrc = curr.isrc
        if isrc == nil {
            print("\(curr.name): isrc empty, skipping...")
            // TODO: more error handling?
            while isrc == nil {
                pos += 1;
                isrc = playlist[pos].isrc
            }
            curr = playlist[pos]
        }
        pos += 1;
        self.fetchForIsrc(isrc: isrc!, completion: callback)
    }

    public func createPlaylistAPI(name: String, tracks: [LibraryPlaylistRequestTrack]? = nil, description: String? = nil, completion: @escaping (Result<[LibraryPlaylist], Error>) -> Void) {
        let request = LibraryPlaylistCreationRequest(name: name, tracks: tracks, description: description)
        createPlaylistAPI(creationRequest: request, completion: completion)
    }
    
    public func createPlaylistAPI(creationRequest: LibraryPlaylistCreationRequest, completion: @escaping (Result<[LibraryPlaylist], Error>) -> Void) {
        
        
        guard let url = URL(string: "https://api.music.apple.com/v1/me/library/playlists") else {
            completion(.failure(MusicKitError.InvalidUrl))
            return
        }
        var playlistRequest = self.buildRequest(url: url)
        playlistRequest.httpMethod = "POST"
        playlistRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
        do {
            playlistRequest.httpBody = try JSONEncoder().encode(creationRequest)
            let str = String(data: playlistRequest.httpBody!, encoding: .utf8)
            print("request: \(str!)")
        } catch {
            completion(.failure(error))
            return
        }
        
        URLSession.shared.dataTask(with: playlistRequest) { (data, response, error) in
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            do {
                let decodedData = try JSONDecoder().decode(musicData<LibraryPlaylist>.self, from: data!)
                if decodedData.hasError {
                    decodedData.printErrors()
                    completion(.failure(decodedData.errors!.first!))
                    return
                }
                completion(.success(decodedData.data!))
            } catch {
                print("error playlistCreationRequest: \(error)")
                print("json response: \(String(data: data!, encoding: .utf8) ?? "error")")
                completion(.failure(error))
                return
            }
            //completion(.success())
        }
        .resume()
    }
    
    // TODO: https://developer.apple.com/documentation/applemusicapi/responseroot
    struct musicData<T: Decodable>: Decodable {
        var data: [T]?
        var errors: [ResposeError]?
        
        var hasError: Bool {
            return errors != nil && errors?.count ?? 0 > 0
        }
        
        func printErrors() {
            for error in errors ?? [] {
                print("error: \(error)")
            }
        }
        
        public struct ResposeError: Codable, Error {
            var code: String
            var detail: String?
            var id: String
            // var source
            var status: String
            var title: String
        }
    }
    
    public struct LibraryPlaylistCreationRequest: Codable {
        var attributes: Attributes
        var relationships: Relationships?
        
        init(name: String, tracks: [LibraryPlaylistRequestTrack]? = nil, description: String? = nil) {
            self.attributes = Attributes(name: name, description: description)
            
            if let tracks = tracks {
                self.relationships = Relationships(tracks: Relationships.TracksData(data: tracks))
            }
        }
        
        public struct Attributes: Codable {
            var name: String
            var description: String?
        }
        
        public struct Relationships: Codable {
            var tracks: TracksData
            
            public struct TracksData: Codable {
                var data: [LibraryPlaylistRequestTrack]
            }
        }
    }
    
    public struct LibraryPlaylistRequestTrack: Codable, Identifiable {
        var id: String
        var type: TrackType = .songs
        
        public enum TrackType: String, Codable {
            case songs = "songs"
            case music_videos = "music-videos"
            case library_songs = "library-songs"
            case library_music_videos = "library-music-videos"
        }
    }
    
    public struct LibraryPlaylist: Decodable {
        var attributes: Attributes?
        //var relationships: Relationships?
        var type: String
        var id: String
        
        /*var id: String? {
            attributes?.playParams?.id
        }*/
        
        var name: String? {
            attributes?.name
        }
        
        public struct Attributes: Decodable {
            var artwork: Song.Attributes.Artwork?
            //var description: String?
            var name: String
            var playParams: Song.Attributes.PlayParameters?
            var canEdit: Bool
        }
        
        // TODO
        public struct Relationships: Decodable {
            
        }
    }
    
    public struct StoreFront: Decodable {
        var attributes: Attributes
        var href: String
        var id: String
        var type: String
        
        public struct Attributes: Decodable {
            var defaultLanguageTag: String
            var name: String
            var supportedLanguageTags: [String]
        }
    }
    
    public class SongInfo {
        var song: Song
        var mediaItem: MPMediaItem?
        
        init (song: Song) {
            self.song = song
        }
        
        var attributes: Song.Attributes {
            song.attributes
        }
        
        var name: String {
            attributes.name
        }
        
        var isrc: String {
            attributes.isrc
        }
        
        var artistName: String {
            attributes.artistName
        }
        
        var albumName: String {
            attributes.albumName
        }
    }
    
    public struct Song: Decodable {
        var attributes: Attributes
                
        
        
        public struct Attributes: Decodable {
            var albumName: String
            var artistName: String
            var artwork: Artwork
            var composerName: String?
            var contentRating: String?
            var discNumber: Int
            var durationInMillis: Int?
            // var editorialNotes
            var genreNames: [String]
            var isrc: String
            var name: String
            var playParams: PlayParameters?
            // var previews: [Preview] (required)
            var releaseDate: String
            /// (Required) The number of the song in the album’s track list.
            var trackNumber: Int
            /// (Required) The URL for sharing a song in the iTunes Store
            var url: String
            
            var isExplicit: Bool? {
                guard let contentRating = contentRating else {
                    return nil
                }
                return contentRating == "explicit"
            }
            
            var playbackSeconds: Int? {
                guard let durationInMillis = durationInMillis else {
                    return nil
                }
                return durationInMillis / 1000
            }
            
            public struct Artwork: Decodable {
                /// The average background color of the image.
                var bgColor: String?
                /// (Required) The maximum height available for the image.
                var height: Int
                /// (Required) The maximum width available for the image.
                var width: Int
                /// The primary text color that may be used if the background color is displayed.
                var textColor1: String?
                /// The secondary text color that may be used if the background color is displayed.
                var textColor2: String?
                /// The tertiary text color that may be used if the background color is displayed.
                var textColor3: String?
                /// The final post-tertiary text color that may be used if the background color is displayed.
                var textColor4: String?
                /// (Required) The URL to request the image asset. The image filename must be preceded by {w}x{h}, as placeholders for the width and height values as described above (for example, {w}x{h}bb.jpeg).
                var url: String
            }
            
            public struct PlayParameters: Decodable, Identifiable {
                /// (Required) The ID of the content to use for playback.
                var id: String
                /// (Required) The kind of the content to use for playback.
                var kind: String
            }
        }
    }
}

enum MusicKitError: Error {
    case NoUserTokenError
    case NoStoreFront
    case InvalidUrl
    case InvalidImageResulotion
}