summaryrefslogtreecommitdiffstats
path: root/MusicConverter/Model/Napster.swift
blob: b45e7db24c455d732356db278873818d63d4ddd7 (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
//
//  Napster.swift
//  MusicConverter
//
//  Created by Finn Behrens on 02.04.21.
//

import Foundation
import MediaPlayer

class Napster: ObservableObject {
    var id: String
    var api: AppleMusicApi
    @Published var cachedNapsterSource: NANapsterPlaylist?
    @Published var tracks: [NANapsterPlaylist.Track]?
    
    var appleChoices: [AppleChoice] = []
    var finischedConvertingChoices = false
    @Published var applePlaylist: MPMediaPlaylist?
    // ToDo: error handling
    var error: Error?
    
    var musicPlayer = MPMusicPlayerController.systemMusicPlayer
    
    var name: String {
        cachedNapsterSource?.name ?? id
    }
    
    /*var synced: Bool {
        self.appleChoices.count == self.cachedNapsterSource?.trackCount ?? -1
    }*/
    var synced = false
    
    init(id: String, api: AppleMusicApi) {
        self.id = id
        self.api = api
        
        if self.id.isEmpty {
            return
        }
        // TODO: apikey
    }
    
    init(demo: String, api: AppleMusicApi = AppleMusicApi()) {
        self.id = demo
        self.api = api
    }
    
    public func update(completion: @escaping (Error?) -> Void) {
        self.cachedNapsterSource = NANapsterPlaylist(id: id)
        self.appleChoices = []; // TODO: keep choices, but update
        self.cachedNapsterSource?.update { result in
            switch result {
            case .failure(let e):
                self.error = e
            case .success(_):
                self.updateTracks() { result in
                    guard (try? result.get()) != nil else {
                        print("wtf? what did guard do?")
                        return
                    }
                    
                    self.resolveTracks(completion: { e in
                        if e != nil {
                            self.error = e
                        }
                        completion(e)
                        self.finischedConvertingChoices = true
                        DispatchQueue.main.async {
                            self.objectWillChange.send()
                        }
                    })
                }
            }
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }
    }
    
    public func updateChoice(choice: Napster.AppleChoice, song: Int) {
        self.appleChoices[choice.id].choice = song
        DispatchQueue.main.async {
            self.objectWillChange.send()
        }
    }
    
    public func updateTracks(completion: @escaping (Result<[NANapsterPlaylist.Track], Error>) -> Void = {_ in}) {
        self.cachedNapsterSource?.getTracks { result in
            switch result {
            case .failure(let e):
                self.error = e
                completion(.failure(e))
            case .success(let d):
                DispatchQueue.main.sync {
                    self.tracks = d;
                }
                completion(.success(d))
            }
            // error also changes self
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }
    }
    
    // TODO: do not add songs without playbackParams
    public func resolveTracks(completion: @escaping (Error?) -> Void) {
        guard self.tracks != nil else {
            completion(NapsterError.TracksEmpty)
            return
        }
        api.convertPlaylist(playlist: self.tracks!, updateCallback: { (track, songs) in
            // FIXME: add unknown songs
            guard songs.count > 0 else {
                print("Did not find a song for \(track.name)")
                return
            }
            do {
                let choiceSongs = songs.filter { song in
                    //return true //song.attributes.playParams != nil
                    return song.attributes.playParams != nil
                }.map { song in
                    AppleMusicApi.SongInfo(song: song)
                }
                if choiceSongs.count > 0 {
                    try self.appleChoices.append(AppleChoice(id: self.appleChoices.count, songs: choiceSongs))
                } else {
                    print("did not found any playable songs for \(track.name)")
                }
            } catch {
                print("error adding to choices: \(error)")
            }
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }, completion: { error in
            if let error = error {
                print("error resolving: \(error)")
            } else {
                self.synced = true
                print("finisched syncing")
            }
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
            completion(error)
        })
    }
    
    public func updateId(_ id: String) {
        self.id = id
        // Invalidate caches
    }
    
    //public func createApplePlaylistAPI(completion: @escaping (Result<))
    
    public func createApplePlaylist(completion: @escaping (Result<MPMediaPlaylist, Error>) -> Void) {
        /*self.musicPlayer.setQueue(with: self.appleChoices.map({s in
            s.song.attributes.playParams.id
        }))
        self.musicPlayer.play()*/
        
        // TODO: check input variables
        guard self.cachedNapsterSource != nil else {
            completion(.failure(NANapsterError.NotCachedError))
            return
        }
        
        let playlistUUID = UUID()
        
        let playlistCreationMetadata = MPMediaPlaylistCreationMetadata(name: self.name)
        playlistCreationMetadata.descriptionText = self.cachedNapsterSource?.description ?? "" + "\n\nFrom napster"
        
        MPMediaLibrary.default().getPlaylist(with: playlistUUID, creationMetadata: playlistCreationMetadata, completionHandler: { (playlist, error) in
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            self.applePlaylist = playlist
            completion(.success(playlist!))
        })
    }
    
    public func convertToApplePlaylist(completion: @escaping (Result<(), Error>) -> Void) {
        guard let playlist = self.applePlaylist else {
            completion(.failure(NapsterError.NoPlaylistCreated))
            return
        }
        
        /*guard self.appleChoices.count > 0 else {
            completion(.failure(NapsterError.NotEnoughSongs))
            return
        }*/
        guard self.synced else {
            completion(.failure(NapsterError.NotEnoughSongs))
            return
        }
        
        var pos = 0
        
        // TODO: clear playlist
        
        var callback: (Error?) -> Void = {_ in}
        callback = { error in
            print("callback: adding song \(self.appleChoices[pos].song.name) to playlist")
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            if pos < self.appleChoices.count - 1 {
                pos += 1;
                while self.appleChoices[pos].song.attributes.playParams?.id == nil {
                    print("did not found a id for song \(self.appleChoices[pos].song.name)")
                    pos += 1;
                }
                playlist.addItem(withProductID: self.appleChoices[pos].song.attributes.playParams!.id, completionHandler: callback)
            } else {
                completion(.success(()))
            }
        }
        
        print("add first item")
        playlist.addItem(withProductID: self.appleChoices[pos].song.attributes.playParams!.id, completionHandler: callback)
    }
    
    public struct AppleChoice: Identifiable, CustomStringConvertible {
        init(id: Int, songs: [AppleMusicApi.SongInfo]) throws {
            guard songs.count > 0 else {
                throw NapsterError.NotEnoughSongs
            }
            
            self.id = id
            self.songs = songs
        }
        
        var id: Int
        var songs: [AppleMusicApi.SongInfo]
        var choice: Int = 0
        
        var song: AppleMusicApi.SongInfo {
            songs[choice]
        }
        
        var description: String {
            song.attributes.name
        }
    }
}

public enum NapsterError: Error {
    case TracksEmpty
    case NotEnoughSongs
    case NoPlaylistCreated
}