summaryrefslogtreecommitdiffstats
path: root/MusicConverter/helpers/MusicKITApi.swift
blob: 0b394a3fc9e78064b4699c7271b38ed77c34932a (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
//
//  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))")
                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))")
                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)
                }
            }
        }
        
        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)
    }

    struct musicData<T: Decodable>: Decodable {
        var data: [T]
    }
    
    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
}