VLCMediaLibraryManager.swift 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/*****************************************************************************
 * VLCMediaLibraryManager.swift
 * VLC for iOS
 *****************************************************************************
 * Copyright © 2018 VideoLAN. All rights reserved.
 * Copyright © 2018 Videolabs
 *
 * Authors: Soomin Lee <bubu # mikan.io>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/

13 14 15 16 17 18 19 20 21
extension Notification.Name {
    static let VLCNewFileAddedNotification = Notification.Name("NewFileAddedNotification")
}

// For objc
extension NSNotification {
    @objc static let VLCNewFileAddedNotification = Notification.Name.VLCNewFileAddedNotification
}

22
@objc protocol MediaLibraryObserver: class {
23
    // Video
24
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
25
                                     didUpdateVideo video: [VLCMLMedia])
26 27

    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
28
                                     didDeleteMediaWithIds ids: [NSNumber])
29

30
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
31
                                     didAddVideos videos: [VLCMLMedia])
32

33
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
34
                                     didAddShowEpisodes showEpisodes: [VLCMLMedia])
35 36 37

    // Audio
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
38
                                     didAddAudios audios: [VLCMLMedia])
39 40

    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
41
                                     didAddArtists artists: [VLCMLArtist])
Soomin Lee's avatar
Soomin Lee committed
42 43

    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
44
                                     didDeleteArtistsWithIds artistsIds: [NSNumber])
Soomin Lee's avatar
Soomin Lee committed
45

Soomin Lee's avatar
Soomin Lee committed
46
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
47
                                     didAddAlbums albums: [VLCMLAlbum])
Soomin Lee's avatar
Soomin Lee committed
48

49 50 51 52 53 54
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
                                     didDeleteAlbumsWithIds albumsIds: [NSNumber])

    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
                                     didAddAlbumTracks albumTracks: [VLCMLMedia])

Soomin Lee's avatar
Soomin Lee committed
55
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
56
                                     didAddGenres genres: [VLCMLGenre])
57 58 59 60

    // Playlist
    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
                                     didAddPlaylists playlists: [VLCMLPlaylist])
61 62 63

    @objc optional func medialibrary(_ medialibrary: VLCMediaLibraryManager,
                                     didDeletePlaylistsWithIds playlistsIds: [NSNumber])
64 65
}

66 67 68 69 70
class VLCMediaLibraryManager: NSObject {
    private static let databaseName: String = "medialibrary.db"
    private var databasePath: String!
    private var thumbnailPath: String!

71 72 73 74
    // Using ObjectIdentifier to avoid duplication and facilitate
    // identification of observing object
    private var observers = [ObjectIdentifier: Observer]()

75
    private lazy var medialib: VLCMediaLibrary = {
76 77 78 79 80 81 82 83
        let medialibrary = VLCMediaLibrary()
        medialibrary.delegate = self
        return medialibrary
    }()

    override init() {
        super.init()
        setupMediaLibrary()
84 85
        NotificationCenter.default.addObserver(self, selector: #selector(reload),
                                               name: .VLCNewFileAddedNotification, object: nil)
86 87 88 89 90 91 92 93 94 95 96 97
    }

    // MARK: Private
    private func setupMediaLibrary() {
        guard let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
            let dbPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first else {
                preconditionFailure("VLCMediaLibraryManager: Unable to init medialibrary.")
        }

        databasePath = dbPath + "/" + VLCMediaLibraryManager.databaseName
        thumbnailPath = documentPath

98 99
        let medialibraryStatus = medialib.setupMediaLibrary(databasePath: databasePath,
                                                            thumbnailPath: thumbnailPath)
100 101 102

        switch medialibraryStatus {
        case .success:
103
            guard medialib.start() else {
104 105 106
                assertionFailure("VLCMediaLibraryManager: Medialibrary failed to start.")
                return
            }
107 108
            medialib.reload()
            medialib.discover(onEntryPoint: "file://" + documentPath)
109 110 111 112 113 114 115 116 117 118 119 120
        case .alreadyInitialized:
            assertionFailure("VLCMediaLibraryManager: Medialibrary already initialized.")
        case .failed:
            preconditionFailure("VLCMediaLibraryManager: Failed to setup medialibrary.")
        case .dbReset:
            // should still start and discover but warn the user that the db has been wipped
            assertionFailure("VLCMediaLibraryManager: The database was resetted, please re-configure.")
        }
    }

    // MARK: Internal

121
    @objc func reload() {
122 123 124
        medialib.reload()
    }

125 126
    /// Returns number of *ALL* files(audio and video) present in the medialibrary database
    func numberOfFiles() -> Int {
127
        var media = medialib.audioFiles(with: .filename, desc: false)
128

129
        media += medialib.videoFiles(with: .filename, desc: false)
130 131 132 133 134 135 136 137
        return media.count
    }


    /// Returns *ALL* file found for a specified VLCMLMediaType
    ///
    /// - Parameter type: Type of the media
    /// - Returns: Array of VLCMLMedia
138 139
    func media(ofType type: VLCMLMediaType, sortingCriteria sort: VLCMLSortingCriteria = .filename, desc: Bool = false) -> [VLCMLMedia] {
        return type == .video ? medialib.videoFiles(with: sort, desc: desc) : medialib.audioFiles(with: sort, desc: desc)
140 141
    }

Soomin Lee's avatar
Soomin Lee committed
142 143 144
    func genre(sortingCriteria sort: VLCMLSortingCriteria = .default, desc: Bool = false) -> [VLCMLGenre] {
        return medialib.genres(with: sort, desc: desc)
    }
145 146
}

147
// MARK: - Observer
148

149 150 151 152 153
private extension VLCMediaLibraryManager {
    struct Observer {
        weak var observer: MediaLibraryObserver?
    }
}
154 155

extension VLCMediaLibraryManager {
156 157
    func addObserver(_ observer: MediaLibraryObserver) {
        let identifier = ObjectIdentifier(observer)
158
        observers[identifier] = Observer(observer: observer)
159 160 161 162 163 164
    }

    func removeObserver(_ observer: MediaLibraryObserver) {
        let identifier = ObjectIdentifier(observer)
        observers.removeValue(forKey: identifier)
    }
165 166
}

167
// MARK: MediaLibrary - Audio methods
168 169

extension VLCMediaLibraryManager {
170 171
    func getArtists(sortingCriteria sort: VLCMLSortingCriteria = .artist, desc: Bool = false) -> [VLCMLArtist] {
        return medialib.artists(with: sort, desc: desc, all: true)
172 173
    }

174 175
    func getAlbums(sortingCriteria sort: VLCMLSortingCriteria = .album, desc: Bool = false) -> [VLCMLAlbum] {
        return medialib.albums(with: sort, desc: desc)
176 177 178
    }
}

179
// MARK: MediaLibrary - Video methods
180 181 182 183

extension VLCMediaLibraryManager {
}

184 185 186
// MARK: MediaLibrary - Playlist methods

extension VLCMediaLibraryManager {
187 188 189 190 191 192 193 194 195

    func createPlaylist(with name: String) -> VLCMLPlaylist {
        return medialib.createPlaylist(withName: name)
    }

    func deletePlaylist(with identifier: VLCMLIdentifier) -> Bool {
        return medialib.deletePlaylist(withIdentifier: identifier)
    }

196 197 198 199 200
    func getPlaylists(sortingCriteria sort: VLCMLSortingCriteria = .default, desc: Bool = false) -> [VLCMLPlaylist] {
        return medialib.playlists(with: sort, desc: desc)
    }
}

201 202
// MARK: - VLCMediaLibraryDelegate - Media

203 204
extension VLCMediaLibraryManager: VLCMediaLibraryDelegate {
    func medialibrary(_ medialibrary: VLCMediaLibrary, didAddMedia media: [VLCMLMedia]) {
205
        let videos = media.filter {( $0.type() == .video )}
206 207
        let audio = media.filter {( $0.type() == .audio )}

208
        for observer in observers {
209 210
            observer.value.observer?.medialibrary?(self, didAddVideos: videos)
            observer.value.observer?.medialibrary?(self, didAddAudios: audio)
211 212 213 214 215 216 217 218
        }
    }

    func medialibrary(_ medialibrary: VLCMediaLibrary, didUpdateMedia media: [VLCMLMedia]) {
        let showEpisodes = media.filter {( $0.subtype() == .showEpisode )}
        let albumTrack = media.filter {( $0.subtype() == .albumTrack )}

        for observer in observers {
219 220
            observer.value.observer?.medialibrary?(self, didAddShowEpisodes: showEpisodes)
            observer.value.observer?.medialibrary?(self, didAddAlbumTracks: albumTrack)
221
        }
222 223
    }

224 225 226 227 228
    func medialibrary(_ medialibrary: VLCMediaLibrary, didDeleteMediaWithIds mediaIds: [NSNumber]) {
        for observer in observers {
            observer.value.observer?.medialibrary?(self, didDeleteMediaWithIds: mediaIds)
        }
    }
229 230 231
}

// MARK: - VLCMediaLibraryDelegate - Artists
232

233
extension VLCMediaLibraryManager {
Soomin Lee's avatar
Soomin Lee committed
234 235
    func medialibrary(_ medialibrary: VLCMediaLibrary, didAdd artists: [VLCMLArtist]) {
        for observer in observers {
236
            observer.value.observer?.medialibrary?(self, didAddArtists: artists)
Soomin Lee's avatar
Soomin Lee committed
237 238
        }
    }
239 240 241 242 243 244

    func medialibrary(_ medialibrary: VLCMediaLibrary, didDeleteArtistsWithIds artistsIds: [NSNumber]) {
        for observer in observers {
            observer.value.observer?.medialibrary?(self, didDeleteArtistsWithIds: artistsIds)
        }
    }
245
}
Soomin Lee's avatar
Soomin Lee committed
246

247 248 249
// MARK: - VLCMediaLibraryDelegate - Albums

extension VLCMediaLibraryManager {
Soomin Lee's avatar
Soomin Lee committed
250 251
    func medialibrary(_ medialibrary: VLCMediaLibrary, didAdd albums: [VLCMLAlbum]) {
        for observer in observers {
252
            observer.value.observer?.medialibrary?(self, didAddAlbums: albums)
Soomin Lee's avatar
Soomin Lee committed
253 254
        }
    }
255 256 257 258 259 260

    func medialibrary(_ medialibrary: VLCMediaLibrary, didDeleteAlbumsWithIds albumsIds: [NSNumber]) {
        for observer in observers {
            observer.value.observer?.medialibrary?(self, didDeleteAlbumsWithIds: albumsIds)
        }
    }
261
}
Soomin Lee's avatar
Soomin Lee committed
262

263 264 265 266 267 268 269 270
// MARK: - VLCMediaLibraryDelegate - Playlists

extension VLCMediaLibraryManager {
    func medialibrary(_ medialibrary: VLCMediaLibrary, didAdd playlists: [VLCMLPlaylist]) {
        for observer in observers {
            observer.value.observer?.medialibrary?(self, didAddPlaylists: playlists)
        }
    }
271 272 273 274 275 276

    func medialibrary(_ medialibrary: VLCMediaLibrary, didDeletePlaylistsWithIds playlistsIds: [NSNumber]) {
        for observer in observers {
            observer.value.observer?.medialibrary?(self, didDeletePlaylistsWithIds: playlistsIds)
        }
    }
277 278
}

279 280 281
// MARK: - VLCMediaLibraryDelegate - Discovery

extension VLCMediaLibraryManager {
282 283 284 285 286 287 288 289 290 291 292 293
    func medialibrary(_ medialibrary: VLCMediaLibrary, didStartDiscovery entryPoint: String) {
    }

    func medialibrary(_ medialibrary: VLCMediaLibrary, didCompleteDiscovery entryPoint: String) {
    }

    func medialibrary(_ medialibrary: VLCMediaLibrary, didProgressDiscovery entryPoint: String) {
    }

    func medialibrary(_ medialibrary: VLCMediaLibrary, didUpdateParsingStatsWithPercent percent: UInt32) {
    }
}