Skip to content

Commit

Permalink
Sync downloaded status with Realm database
Browse files Browse the repository at this point in the history
  • Loading branch information
insidegui committed Dec 23, 2015
1 parent 80441e6 commit 0345919
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 7 deletions.
35 changes: 32 additions & 3 deletions WWDC/VideoStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class VideoStore : NSObject, NSURLSessionDownloadDelegate {
}

func download(url: String) {
if isDownloading(url) {
if isDownloading(url) || hasVideo(url) {
return
}

Expand Down Expand Up @@ -144,6 +144,7 @@ class VideoStore : NSObject, NSURLSessionDownloadDelegate {

do {
try fileManager.moveItemAtURL(location, toURL: localURL)
WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithURL(originalAbsoluteURLString, downloaded: true)
} catch _ {
print("VideoStore was unable to move \(location) to \(localURL)")
}
Expand All @@ -162,20 +163,48 @@ class VideoStore : NSObject, NSURLSessionDownloadDelegate {

// MARK: File observation

var folderMonitor: DTFolderMonitor!
private var folderMonitor: DTFolderMonitor!
private var existingVideoFiles = [String]()

func monitorDownloadsFolder() {
if folderMonitor != nil {
folderMonitor.stopMonitoring()
folderMonitor = nil
}

folderMonitor = DTFolderMonitor(forURL: NSURL(fileURLWithPath: Preferences.SharedPreferences().localVideoStoragePath)) {
let videosPath = Preferences.SharedPreferences().localVideoStoragePath
enumerateVideoFiles(videosPath)

folderMonitor = DTFolderMonitor(forURL: NSURL(fileURLWithPath: videosPath)) {
self.enumerateVideoFiles(videosPath)

NSNotificationCenter.defaultCenter().postNotificationName(VideoStoreDownloadedFilesChangedNotification, object: nil)
}
folderMonitor.startMonitoring()
}

/// Updates the downloaded status for the sessions on the database based on the existence of the downloaded video file
private func enumerateVideoFiles(path: String) {
guard let enumerator = NSFileManager.defaultManager().enumeratorAtPath(path) else { return }
guard let files = enumerator.allObjects as? [String] else { return }

// existing/added files
for file in files {
WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: true)
}

if existingVideoFiles.count == 0 {
existingVideoFiles = files
return
}

// removed files
let removedFiles = existingVideoFiles.filter { !files.contains($0) }
for file in removedFiles {
WWDCDatabase.sharedDatabase.updateDownloadedStatusForSessionWithLocalFileName(file, downloaded: false)
}
}

// MARK: Teardown

deinit {
Expand Down
42 changes: 38 additions & 4 deletions WWDC/WWDCDatabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ typealias SessionsUpdatedCallback = () -> Void
}

private let bgThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
private var transcriptIndexingQueue = NSOperationQueue()
private var backgroundOperationQueue = NSOperationQueue()

private var config: AppConfig! {
didSet {
Expand Down Expand Up @@ -165,6 +165,7 @@ typealias SessionsUpdatedCallback = () -> Void
// create and store/update each video
for jsonSession in sessionsArray {
var session = Session(json: jsonSession)

if backgroundRealm.objectForPrimaryKey(Session.self, key: session.uniqueId) == nil {
newSessionKeys.append(session.uniqueId)
}
Expand All @@ -191,8 +192,8 @@ typealias SessionsUpdatedCallback = () -> Void
guard sessionKeys.count > 0 else { return }

transcriptIndexingProgress = NSProgress(totalUnitCount: Int64(sessionKeys.count))
transcriptIndexingQueue.underlyingQueue = bgThread
transcriptIndexingQueue.name = "Transcript indexing"
backgroundOperationQueue.underlyingQueue = bgThread
backgroundOperationQueue.name = "WWDCDatabase background"

let backgroundRealm = try! Realm()

Expand All @@ -215,7 +216,7 @@ typealias SessionsUpdatedCallback = () -> Void
return
}

self.transcriptIndexingQueue.addOperationWithBlock {
self.backgroundOperationQueue.addOperationWithBlock {
let bgRealm = try! Realm()
guard let session = bgRealm.objectForPrimaryKey(Session.self, key: sessionKey) else { return }
let transcript = Transcript(json: JSON(data: jsonData), session: session)
Expand All @@ -228,6 +229,39 @@ typealias SessionsUpdatedCallback = () -> Void
}
}

/// Update downloaded flag on the database for the session with the specified URL
func updateDownloadedStatusForSessionWithURL(url: String, downloaded: Bool) {
backgroundOperationQueue.addOperationWithBlock {
do {
let bgRealm = try Realm()
if let session = bgRealm.objects(Session.self).filter("hdVideoURL = %@", url).first {
do {
try bgRealm.write {
session.downloaded = downloaded
}
} catch _ {
print("Error updating downloaded flag for session with url \(url)")
}
}
} catch let error {
print("Realm error \(error)")
}
}
}

/// Update downloaded flag on the database for the session with the specified filename
func updateDownloadedStatusForSessionWithLocalFileName(filename: String, downloaded: Bool) {
mainQ {
guard let session = self.realm.objects(Session.self).filter("hdVideoURL contains %@", filename).first else {
print("Session not found with local filename \(filename)")
return
}
guard let url = session.hd_url else { return }

self.updateDownloadedStatusForSessionWithURL(url, downloaded: downloaded)
}
}

}

// MARK: - Data migration
Expand Down

0 comments on commit 0345919

Please sign in to comment.