summaryrefslogtreecommitdiffstats
path: root/MusicConverter/Model/Napster.swift
blob: 21d89197826398741aafb63dd662bb140aefeb04 (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
//
//  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
    }
    
    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.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))
            }
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }
    }
    
    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 {
                try self.appleChoices.append(AppleChoice(id: self.appleChoices.count, songs: songs.map({s in AppleMusicApi.SongInfo(song: s)})))
            } catch {
                print("error adding to choices: \(error)")
            }
            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }, completion: completion) // TODO: do I need the completion?
    }
    
    public func updateId(_ id: String) {
        self.id = id
        // Invalidate caches
    }
    
    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
        }
        
        var pos = 0
        
        // TODO: clear playlist
        
        var callback: (Error?) -> Void = {_ in}
        callback = { error in
            guard error == nil else {
                completion(.failure(error!))
                return
            }
            
            if pos < self.appleChoices.count {
                pos += 1;
                playlist.addItem(withProductID: self.appleChoices[pos].song.attributes.playParams.id, completionHandler: callback)
            } else {
                completion(.success(()))
            }
        }
        
        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
}