MLMediaLibrary.m 35.1 KB
Newer Older
1 2 3 4 5
/*****************************************************************************
 * MLMediaLibrary.m
 * MobileMediaLibraryKit
 *****************************************************************************
 * Copyright (C) 2010 Pierre d'Herbemont
6
 * Copyright (C) 2010-2015 VLC authors and VideoLAN
7 8 9 10
 * $Id$
 *
 * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
 *          Felix Paul Kühne <fkuehne # videolan.org>
11
 *          Tobias Conradi <videolan # tobias-conradi.de>
12
 *
13 14 15
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
16 17 18 19
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
22
 *
23 24 25
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26
 *****************************************************************************/
Pierre's avatar
Pierre committed
27 28

#import "MLMediaLibrary.h"
Pierre's avatar
Pierre committed
29
#import "MLTitleDecrapifier.h"
Pierre's avatar
Pierre committed
30 31 32 33
#import "MLFile.h"
#import "MLLabel.h"
#import "MLShowEpisode.h"
#import "MLShow.h"
34 35 36
#import "MLThumbnailerQueue.h"
#import "MLAlbumTrack.h"
#import "MLAlbum.h"
37
#import "MLFileParserQueue.h"
38
#import "MLCrashPreventer.h"
39
#import "MLMediaLibrary+Migration.h"
40
#import <sys/sysctl.h> // for sysctlbyname
Pierre's avatar
Pierre committed
41

42
#if TARGET_OS_IOS
43 44 45
#import <CoreSpotlight/CoreSpotlight.h>
#endif

Felix Paul Kühne's avatar
Felix Paul Kühne committed
46 47 48 49 50 51
#if HAVE_BLOCK
#import "MLMovieInfoGrabber.h"
#import "MLTVShowInfoGrabber.h"
#import "MLTVShowEpisodesInfoGrabber.h"
#endif

52 53
@interface MLMediaLibrary ()
{
54 55 56 57
    NSManagedObjectContext *_managedObjectContext;
    NSManagedObjectModel   *_managedObjectModel;

    BOOL _allowNetworkAccess;
58
    int _deviceSpeedCategory;
59

60 61
    NSString *_thumbnailFolderPath;
    NSString *_databaseFolderPath;
62
    NSString *_documentFolderPath;
63
    NSString *_libraryBasePath;
64 65 66
}
@end

Pierre's avatar
Pierre committed
67

Pierre's avatar
Pierre committed
68 69
// Pref key
static NSString *kLastTVDBUpdateServerTime = @"MLLastTVDBUpdateServerTime";
70
static NSString *kDecrapifyTitles = @"MLDecrapifyTitles";
Pierre's avatar
Pierre committed
71

Pierre's avatar
Pierre committed
72 73
#if HAVE_BLOCK
@interface MLMediaLibrary () <MLMovieInfoGrabberDelegate, MLTVShowEpisodesInfoGrabberDelegate, MLTVShowInfoGrabberDelegate>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
74 75
#else
@interface MLMediaLibrary ()
Pierre's avatar
Pierre committed
76
#endif
Pierre's avatar
Pierre committed
77
- (NSManagedObjectContext *)managedObjectContext;
Pierre's avatar
Pierre committed
78
- (NSString *)databaseFolderPath;
Pierre's avatar
Pierre committed
79 80
@end

Pierre's avatar
Pierre committed
81
@implementation MLMediaLibrary
82 83
+ (void)initialize
{
84
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
85
    [defaults registerDefaults:@{kDecrapifyTitles : @YES}];
86 87
}

Pierre's avatar
Pierre committed
88 89 90
+ (id)sharedMediaLibrary
{
    static id sharedMediaLibrary = nil;
Pierre's avatar
Pierre committed
91
    if (!sharedMediaLibrary) {
Pierre's avatar
Pierre committed
92
        sharedMediaLibrary = [[[self class] alloc] init];
93 94 95 96

        // Also force to init the crash preventer
        // Because it will correctly set up the parser and thumbnail queue
        [MLCrashPreventer sharedPreventer];
Pierre's avatar
Pierre committed
97
    }
Pierre's avatar
Pierre committed
98 99 100
    return sharedMediaLibrary;
}

101 102 103 104 105 106 107 108 109 110 111
- (instancetype)init
{
    self = [super init];
    if (self) {
        _applicationGroupIdentifier = @"group.org.videolan.vlc-ios";
        [self _setupLibraryPathPriorToMigration];
        APLog(@"Initializing db in %@", [self databaseFolderPath]);
    }
    return self;
}

112 113 114 115 116 117
- (void)dealloc
{
    if (_managedObjectContext)
        [_managedObjectContext removeObserver:self forKeyPath:@"hasChanges"];
}

Pierre's avatar
Pierre committed
118 119 120 121
- (NSFetchRequest *)fetchRequestForEntity:(NSString *)entity
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSManagedObjectContext *moc = [self managedObjectContext];
122 123 124
    if (!moc || moc.persistentStoreCoordinator == nil)
        return nil;

Pierre's avatar
Pierre committed
125
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entity inManagedObjectContext:moc];
Pierre's avatar
Pierre committed
126
    NSAssert(entityDescription, @"No entity");
Pierre's avatar
Pierre committed
127
    [request setEntity:entityDescription];
128
    return request;
Pierre's avatar
Pierre committed
129 130 131 132 133
}

- (id)createObjectForEntity:(NSString *)entity
{
    NSManagedObjectContext *moc = [self managedObjectContext];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
134
    if (!moc || moc.persistentStoreCoordinator == nil)
135 136
        return nil;

Pierre's avatar
Pierre committed
137 138 139
    return [NSEntityDescription insertNewObjectForEntityForName:entity inManagedObjectContext:moc];
}

140 141
- (void)removeObject:(NSManagedObject *)object
{
142 143 144 145
    NSManagedObjectContext *moc = [self managedObjectContext];

    if (moc)
        [[self managedObjectContext] deleteObject:object];
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
#pragma mark - helper
- (int)deviceSpeedCategory
{
    if (_deviceSpeedCategory > 0)
        return _deviceSpeedCategory;

    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);

    char *answer = malloc(size);
    sysctlbyname("hw.machine", answer, &size, NULL, 0);

    NSString *currentMachine = @(answer);
    free(answer);

    if ([currentMachine hasPrefix:@"iPhone2"] || [currentMachine hasPrefix:@"iPhone3"] || [currentMachine hasPrefix:@"iPhone4"] || [currentMachine hasPrefix:@"iPod3"] || [currentMachine hasPrefix:@"iPod4"] || [currentMachine hasPrefix:@"iPad2"]) {
        // iPhone 3GS, iPhone 4, 3rd and 4th generation iPod touch, iPad 2, iPad mini (1st gen)
        _deviceSpeedCategory = 1;
    } else if ([currentMachine hasPrefix:@"iPad3,1"] || [currentMachine hasPrefix:@"iPad3,2"] || [currentMachine hasPrefix:@"iPad3,3"] || [currentMachine hasPrefix:@"iPod5"]) {
        // iPod 5, iPad 3
        _deviceSpeedCategory = 2;
    } else if ([currentMachine hasPrefix:@"iPhone5"] || [currentMachine hasPrefix:@"iPhone6"] || [currentMachine hasPrefix:@"iPad4"]) {
        // iPhone 5 + 5S, iPad 4, iPad Air, iPad mini 2G
        _deviceSpeedCategory = 3;
    } else
        // iPhone 6, 2014 iPads
        _deviceSpeedCategory = 4;

    return _deviceSpeedCategory;
}

Pierre's avatar
Pierre committed
179 180 181 182 183 184
#pragma mark -
#pragma mark Media Library
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel)
        return _managedObjectModel;
185

186
    NSString *path = [[NSBundle bundleForClass:self.class] pathForResource:@"MediaLibrary" ofType:@"momd"];
187 188 189
    NSURL *momURL = [NSURL fileURLWithPath:path];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

Pierre's avatar
Pierre committed
190 191 192
    return _managedObjectModel;
}

193
#pragma mark - Path handling
194 195 196 197 198 199 200 201
- (void)setLibraryBasePath:(NSString *)libraryBasePath
{
    _libraryBasePath = [libraryBasePath copy];
    _databaseFolderPath = nil;
    _thumbnailFolderPath = nil;
    _persistentStoreURL = nil;
}

202 203 204 205 206
- (NSString *)databaseFolderPath
{
    if (_databaseFolderPath.length == 0) {
        _databaseFolderPath = self.libraryBasePath;
    }
207
    return _databaseFolderPath;
Pierre's avatar
Pierre committed
208 209
}

210 211
- (NSString *)thumbnailFolderPath
{
212 213
    if (_thumbnailFolderPath.length == 0) {
        _thumbnailFolderPath = [self.libraryBasePath stringByAppendingPathComponent:@"Thumbnails"];
214 215
    }
    return _thumbnailFolderPath;
216 217
}

218 219 220 221 222 223 224 225
- (NSString *)documentFolderPath
{
    if (_documentFolderPath) {
        if (_documentFolderPath.length > 0)
            return _documentFolderPath;
    }
    int directory = NSDocumentDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
226
    _documentFolderPath = paths.firstObject;
227 228 229
    return _documentFolderPath;
}

230 231 232 233 234 235 236 237
- (NSURL *)persistentStoreURL
{
    if (_persistentStoreURL == nil) {
        NSString *databaseFolderPath = [self databaseFolderPath];
        NSString *path = [databaseFolderPath stringByAppendingPathComponent: @"MediaLibrary.sqlite"];
        _persistentStoreURL = [NSURL fileURLWithPath:path];
    }
    return _persistentStoreURL;
238 239
}

240 241 242 243 244 245 246 247 248 249
- (NSString *)pathRelativeToDocumentsFolderFromAbsolutPath:(NSString *)absolutPath
{
    return [absolutPath stringByReplacingOccurrencesOfString:self.documentFolderPath withString:@""];
}
- (NSString *)absolutPathFromPathRelativeToDocumentsFolder:(NSString *)relativePath
{
    return [self.documentFolderPath stringByAppendingPathComponent:relativePath];
}

#pragma mark -
250

251 252 253 254 255
- (NSPersistentStore *)addDefaultLibraryStoreToCoordinator:(NSPersistentStoreCoordinator *)coordinator withError:(NSError **)error {

    NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption : @YES,
                              NSInferMappingModelAutomaticallyOption : @YES,
                              NSSQLitePragmasOption : @{@"journal_mode": @"DELETE"}};
Pierre's avatar
Pierre committed
256

257 258 259 260 261
    if (self.additionalPersitentStoreOptions.count > 0) {
        NSMutableDictionary *mutableOptions = options.mutableCopy;
        [mutableOptions addEntriesFromDictionary:self.additionalPersitentStoreOptions];
        options = mutableOptions;
    }
262 263 264 265 266 267 268 269 270 271
    return [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.persistentStoreURL options:options error:error];
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator) {
        return _persistentStoreCoordinator;
    }

    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
Pierre's avatar
Pierre committed
272

273 274 275 276 277 278 279
    if ([[self.additionalPersitentStoreOptions objectForKey:NSReadOnlyPersistentStoreOption] boolValue] == YES) {
        if (![[NSFileManager defaultManager] fileExistsAtPath:self.persistentStoreURL.path]) {
            APLog(@"no library was found in read-only mode, hence no functionality will be available in this session");
            return nil;
        }
    }

Pierre's avatar
Pierre committed
280
    NSError *error;
281
    NSPersistentStore *persistentStore = [self addDefaultLibraryStoreToCoordinator:coordinator withError:&error];
Pierre's avatar
Pierre committed
282 283

    if (!persistentStore) {
Pierre's avatar
Pierre committed
284
#if! TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
285 286 287 288
        // FIXME: Deal with versioning
        NSInteger ret = NSRunAlertPanel(@"Error", @"The Media Library you have on your disk is not compatible with the one Lunettes can read. Do you want to create a new one?", @"No", @"Yes", nil);
        if (ret == NSOKButton)
            [NSApp terminate:nil];
289
        [[NSFileManager defaultManager] removeItemAtPath:self.persistentStoreURL.path error:nil];
Pierre's avatar
Pierre committed
290
#else
291
        [[NSFileManager defaultManager] removeItemAtPath:self.persistentStoreURL.path error:nil];
Pierre's avatar
Pierre committed
292
#endif
293
        persistentStore = [self addDefaultLibraryStoreToCoordinator:coordinator withError:&error];
Pierre's avatar
Pierre committed
294 295 296 297
        if (!persistentStore) {
#if! TARGET_OS_IPHONE
            NSRunInformationalAlertPanel(@"Corrupted Media Library", @"There is nothing we can apparently do about it...", @"OK", nil, nil);
#else
Felix Paul Kühne's avatar
Felix Paul Kühne committed
298
#ifndef TARGET_OS_WATCH
Pierre's avatar
Pierre committed
299 300
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Corrupted Media Library" message:@"There is nothing we can apparently do about it..." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
301
#endif
Pierre's avatar
Pierre committed
302 303 304 305
#endif
            // Probably assert instead.
            return nil;
        }
Pierre's avatar
Pierre committed
306
    }
Tobias's avatar
Tobias committed
307 308

    _persistentStoreCoordinator = coordinator;
309 310 311
    return coordinator;
}

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

- (void)overrideLibraryWithLibraryFromURL:(NSURL *)replacementURL {

    NSError *error;

    NSPersistentStoreCoordinator *psc = self.persistentStoreCoordinator;
    NSPersistentStore *store = [psc persistentStoreForURL:self.persistentStoreURL];
    if (store) {
        if(![psc removePersistentStore:store error:&error]) {
            NSLog(@"%s failed to remove persistent store with error %@",__PRETTY_FUNCTION__,error);
            error = nil;
        }
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager replaceItemAtURL:self.persistentStoreURL
                                   withItemAtURL:replacementURL
                                  backupItemName:nil
                                         options:0
                                resultingItemURL:nil
                                           error:&error];
    if (!success) {
        NSLog(@"%s failed to replace store with error %@",__PRETTY_FUNCTION__,error);
        error = nil;
    }

    if(![self addDefaultLibraryStoreToCoordinator:psc withError:&error]) {
        NSLog(@"%s failed to add store with error %@",__PRETTY_FUNCTION__,error);
    }
}

343 344 345 346
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext)
        return _managedObjectContext;
Pierre's avatar
Pierre committed
347

348 349 350 351
    NSPersistentStoreCoordinator *coodinator = self.persistentStoreCoordinator;
    if (!coodinator) {
        return nil;
    }
352
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
353
    [_managedObjectContext setPersistentStoreCoordinator:coodinator];
Tobias's avatar
Tobias committed
354 355
    if (_managedObjectContext.persistentStoreCoordinator == nil) {
        _managedObjectContext = nil;
356
        return nil;
Tobias's avatar
Tobias committed
357
    }
Pierre's avatar
Pierre committed
358 359 360 361 362 363 364 365
    [_managedObjectContext setUndoManager:nil];
    [_managedObjectContext addObserver:self forKeyPath:@"hasChanges" options:NSKeyValueObservingOptionInitial context:nil];
    return _managedObjectContext;
}

- (void)savePendingChanges
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(savePendingChanges) object:nil];
Pierre's avatar
Pierre committed
366
    NSError *error = nil;
367 368 369 370
    NSManagedObjectContext *moc = [self managedObjectContext];
    if (!moc)
        return;

Pierre's avatar
Pierre committed
371 372
    BOOL success = [[self managedObjectContext] save:&error];
    NSAssert1(success, @"Can't save: %@", error);
Pierre's avatar
Pierre committed
373
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
374 375 376 377 378 379
    NSProcessInfo *process = [NSProcessInfo processInfo];
    if ([process respondsToSelector:@selector(enableSuddenTermination)])
        [process enableSuddenTermination];
#endif
}

380 381 382
- (void)save
{
    NSError *error = nil;
383 384 385 386 387
    NSManagedObjectContext *moc = [self managedObjectContext];
    if (!moc)
        return;

    BOOL success = [moc save:&error];
388 389 390
    NSAssert1(success, @"Can't save: %@", error);
}

Pierre's avatar
Pierre committed
391
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Pierre's avatar
Pierre committed
392 393
{
    if ([keyPath isEqualToString:@"hasChanges"] && object == _managedObjectContext) {
Pierre's avatar
Pierre committed
394
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
395 396 397 398 399
        NSProcessInfo *process = [NSProcessInfo processInfo];
        if ([process respondsToSelector:@selector(disableSuddenTermination)])
            [process disableSuddenTermination];
#endif

Pierre's avatar
Pierre committed
400 401 402 403
        if ([[self managedObjectContext] hasChanges]) {
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(savePendingChanges) object:nil];
            [self performSelector:@selector(savePendingChanges) withObject:nil afterDelay:1.];
        }
Pierre's avatar
Pierre committed
404 405 406 407 408
        return;
    }
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

409 410 411 412 413
- (NSManagedObject *)objectForURIRepresentation:(NSURL *)uriRepresenation {
    if (uriRepresenation == nil) {
        return nil;
    }
    NSManagedObjectID *objectID = [self.persistentStoreCoordinator managedObjectIDForURIRepresentation:uriRepresenation];
Tobias's avatar
Tobias committed
414 415 416 417
    if (objectID) {
        return [self.managedObjectContext objectWithID:objectID];
    }
    return nil;
418 419
}

Pierre's avatar
Pierre committed
420 421
#pragma mark -
#pragma mark No meta data fallbacks
Pierre's avatar
Pierre committed
422

Pierre's avatar
Pierre committed
423
- (void)computeThumbnailForFile:(MLFile *)file
Pierre's avatar
Pierre committed
424
{
425
    if (!file.computedThumbnail && ![file isKindOfType:kMLFileTypeAudio]) {
426
        APLog(@"Computing thumbnail for %@", file.title);
Pierre's avatar
Pierre committed
427 428
        [[MLThumbnailerQueue sharedThumbnailerQueue] addFile:file];
    }
Pierre's avatar
Pierre committed
429
}
430

Pierre's avatar
Pierre committed
431
- (void)errorWhenFetchingMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
432
{
433
    APLog(@"Error when fetching for '%@'", file.title);
Pierre's avatar
Pierre committed
434

Pierre's avatar
Pierre committed
435 436
    [self computeThumbnailForFile:file];
}
Pierre's avatar
Pierre committed
437

Pierre's avatar
Pierre committed
438 439 440 441 442 443 444
- (void)errorWhenFetchingMetaDataForShow:(MLShow *)show
{
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self errorWhenFetchingMetaDataForFile:file];
    }
}
Pierre's avatar
Pierre committed
445

Pierre's avatar
Pierre committed
446 447
- (void)noMetaDataInRemoteDBForFile:(MLFile *)file
{
448
    file.noOnlineMetaData = @YES;
Pierre's avatar
Pierre committed
449
    [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
450 451
}

Pierre's avatar
Pierre committed
452
- (void)noMetaDataInRemoteDBForShow:(MLShow *)show
Pierre's avatar
Pierre committed
453
{
Pierre's avatar
Pierre committed
454 455 456
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self noMetaDataInRemoteDBForFile:file];
Pierre's avatar
Pierre committed
457 458 459
    }
}

Pierre's avatar
Pierre committed
460 461 462 463
#pragma mark -
#pragma mark Getter

- (void)addNewLabelWithName:(NSString *)name
Pierre's avatar
Pierre committed
464
{
Pierre's avatar
Pierre committed
465 466
    MLLabel *label = [self createObjectForEntity:@"Label"];
    label.name = name;
Pierre's avatar
Pierre committed
467 468
}

Pierre's avatar
Pierre committed
469 470 471 472 473 474 475
/**
 * TV MLShow Episodes
 */

#pragma mark -
#pragma mark Online meta data grabbing

Felix Paul Kühne's avatar
Felix Paul Kühne committed
476
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
477 478
- (void)tvShowEpisodesInfoGrabberDidFinishGrabbing:(MLTVShowEpisodesInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
479
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
480 481

    NSArray *results = grabber.episodesResults;
482
    [show setValue:(grabber.results)[@"serieArtworkURL"] forKey:@"artworkURL"];
Pierre's avatar
Pierre committed
483
    for (id result in results) {
484
        if ([result[@"serie"] boolValue]) {
Pierre's avatar
Pierre committed
485 486
            continue;
        }
487 488 489 490 491
        MLShowEpisode *showEpisode = [MLShowEpisode episodeWithShow:show episodeNumber:result[@"episodeNumber"] seasonNumber:result[@"seasonNumber"] createIfNeeded:YES];
        showEpisode.name = result[@"title"];
        showEpisode.theTVDBID = result[@"id"];
        showEpisode.shortSummary = result[@"shortSummary"];
        showEpisode.artworkURL = result[@"artworkURL"];
Pierre's avatar
Pierre committed
492 493 494 495 496
        if (!showEpisode.artworkURL) {
            for (MLFile *file in showEpisode.files)
                [self computeThumbnailForFile:file];
        }

Pierre's avatar
Pierre committed
497 498 499 500 501
        showEpisode.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
    show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
}

Pierre's avatar
Pierre committed
502 503 504 505 506 507
- (void)tvShowEpisodesInfoGrabber:(MLTVShowEpisodesInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
508 509
- (void)tvShowInfoGrabberDidFinishGrabbing:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
510
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
511 512
    NSArray *results = grabber.results;
    if ([results count] > 0) {
513 514
        NSDictionary *result = results[0];
        NSString *showId = result[@"id"];
Pierre's avatar
Pierre committed
515 516

        show.theTVDBID = showId;
517 518 519
        show.name = result[@"title"];
        show.shortSummary = result[@"shortSummary"];
        show.releaseYear = result[@"releaseYear"];
Pierre's avatar
Pierre committed
520 521

        // Fetch episodes info
522
        MLTVShowEpisodesInfoGrabber *grabber = [[MLTVShowEpisodesInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
523 524 525 526 527 528
        grabber.delegate = self;
        grabber.userData = show;
        [grabber lookUpForShowID:showId];
    }
    else {
        // Not found.
Pierre's avatar
Pierre committed
529
        [self noMetaDataInRemoteDBForShow:show];
Pierre's avatar
Pierre committed
530 531 532 533
        show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
}

Pierre's avatar
Pierre committed
534 535 536 537 538 539
- (void)tvShowInfoGrabber:(MLTVShowInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
540 541
- (void)tvShowInfoGrabberDidFetchServerTime:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
542
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
543 544 545

    [[NSUserDefaults standardUserDefaults] setInteger:[[MLTVShowInfoGrabber serverTime] integerValue] forKey:kLastTVDBUpdateServerTime];

Pierre's avatar
Pierre committed
546
    // First fetch the MLShow ID
547
    MLTVShowInfoGrabber *showInfoGrabber = [[MLTVShowInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
548 549 550
    showInfoGrabber.delegate = self;
    showInfoGrabber.userData = show;

551
    APLog(@"Fetching show information on %@", show.name);
Pierre's avatar
Pierre committed
552

Pierre's avatar
Pierre committed
553 554 555 556
    [showInfoGrabber lookUpForTitle:show.name];
}
#endif

Pierre's avatar
Pierre committed
557
- (void)fetchMetaDataForShow:(MLShow *)show
Pierre's avatar
Pierre committed
558
{
559 560
    if (!_allowNetworkAccess)
        return;
561
    APLog(@"Fetching show server time");
Pierre's avatar
Pierre committed
562

Pierre's avatar
Pierre committed
563
    // First fetch the serverTime, so that we can update each entry.
Pierre's avatar
Pierre committed
564 565
#if HAVE_BLOCK
    [MLTVShowInfoGrabber fetchServerTimeAndExecuteBlock:^(NSNumber *serverDate) {
Pierre's avatar
Pierre committed
566 567 568

        [[NSUserDefaults standardUserDefaults] setInteger:[serverDate integerValue] forKey:kLastTVDBUpdateServerTime];

569
        APLog(@"Fetching show information on %@", show.name);
Pierre's avatar
Pierre committed
570 571 572

        // First fetch the MLShow ID
        MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
573 574 575 576 577 578 579 580 581 582 583
        [grabber lookUpForTitle:show.name andExecuteBlock:^{
            NSArray *results = grabber.results;
            if ([results count] > 0) {
                NSDictionary *result = [results objectAtIndex:0];
                NSString *showId = [result objectForKey:@"id"];

                show.theTVDBID = showId;
                show.name = [result objectForKey:@"title"];
                show.shortSummary = [result objectForKey:@"shortSummary"];
                show.releaseYear = [result objectForKey:@"releaseYear"];

584
                APLog(@"Fetching show episode information on %@", showId);
Pierre's avatar
Pierre committed
585

Pierre's avatar
Pierre committed
586
                // Fetch episode info
Pierre's avatar
Pierre committed
587
                MLTVShowEpisodesInfoGrabber *grabber = [[[MLTVShowEpisodesInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
588 589 590 591 592 593 594
                [grabber lookUpForShowID:showId andExecuteBlock:^{
                    NSArray *results = grabber.episodesResults;
                    [show setValue:[grabber.results objectForKey:@"serieArtworkURL"] forKey:@"artworkURL"];
                    for (id result in results) {
                        if ([[result objectForKey:@"serie"] boolValue]) {
                            continue;
                        }
595
                        MLShowEpisode *showEpisode = [MLShowEpisode episodeWithShow:show episodeNumber:[result objectForKey:@"episodeNumber"] seasonNumber:[result objectForKey:@"seasonNumber"] createIfNeeded:YES];
Pierre's avatar
Pierre committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
                        showEpisode.name = [result objectForKey:@"title"];
                        showEpisode.theTVDBID = [result objectForKey:@"id"];
                        showEpisode.shortSummary = [result objectForKey:@"shortSummary"];
                        showEpisode.artworkURL = [result objectForKey:@"artworkURL"];
                        showEpisode.lastSyncDate = serverDate;
                    }
                    show.lastSyncDate = serverDate;
                }];
            }
            else {
                // Not found.
                show.lastSyncDate = serverDate;
            }

        }];
    }];
Pierre's avatar
Pierre committed
612
#endif
Pierre's avatar
Pierre committed
613 614
}

Pierre's avatar
Pierre committed
615
- (void)addTVShowEpisodeWithInfo:(NSDictionary *)tvShowEpisodeInfo andFile:(MLFile *)file
Pierre's avatar
Pierre committed
616
{
Pierre's avatar
Pierre committed
617
    file.type = kMLFileTypeTVShowEpisode;
Pierre's avatar
Pierre committed
618

619 620 621
    NSNumber *seasonNumber = tvShowEpisodeInfo[@"season"];
    NSNumber *episodeNumber = tvShowEpisodeInfo[@"episode"];
    NSString *tvShowName = tvShowEpisodeInfo[@"tvShowName"];
622
    NSString *tvEpisodeName = tvShowEpisodeInfo[@"tvEpisodeName"];
Pierre's avatar
Pierre committed
623 624
    BOOL hasNoTvShow = NO;
    if (!tvShowName) {
625
        tvShowName = @"";
Pierre's avatar
Pierre committed
626 627 628
        hasNoTvShow = YES;
    }
    BOOL wasInserted = NO;
Pierre's avatar
Pierre committed
629 630
    MLShow *show = nil;
    MLShowEpisode *episode = [MLShowEpisode episodeWithShowName:tvShowName episodeNumber:episodeNumber seasonNumber:seasonNumber createIfNeeded:YES wasCreated:&wasInserted];
631 632

    if (episode) {
Pierre's avatar
Pierre committed
633
        show = episode.show;
634 635
        [show addEpisode:episode];
    }
Pierre's avatar
Pierre committed
636 637 638 639
    if (wasInserted && !hasNoTvShow) {
        show.name = tvShowName;
        [self fetchMetaDataForShow:show];
    }
640
    episode.name = tvEpisodeName;
Pierre's avatar
Pierre committed
641

642
    if (episode.name.length < 1)
Pierre's avatar
Pierre committed
643 644 645
        episode.name = file.title;
    file.seasonNumber = seasonNumber;
    file.episodeNumber = episodeNumber;
646
    episode.shouldBeDisplayed = @YES;
Pierre's avatar
Pierre committed
647 648

    [episode addFilesObject:file];
Pierre's avatar
Pierre committed
649
    file.showEpisode = episode;
Pierre's avatar
Pierre committed
650

Pierre's avatar
Pierre committed
651
    // The rest of the meta data will be fetched using the MLShow
652
    file.hasFetchedInfo = @YES;
Pierre's avatar
Pierre committed
653 654 655
}

/**
Pierre's avatar
Pierre committed
656
 * MLFile auto detection
Pierre's avatar
Pierre committed
657 658
 */

Felix Paul Kühne's avatar
Felix Paul Kühne committed
659
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
660 661 662 663 664 665
- (void)movieInfoGrabber:(MLMovieInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLFile *file = grabber.userData;
    [self errorWhenFetchingMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
666 667
- (void)movieInfoGrabberDidFinishGrabbing:(MLMovieInfoGrabber *)grabber
{
668
    NSNumber *yes = @YES;
Pierre's avatar
Pierre committed
669 670

    NSArray *results = grabber.results;
Pierre's avatar
Pierre committed
671
    MLFile *file = grabber.userData;
Pierre's avatar
Pierre committed
672
    if ([results count] > 0) {
673 674 675 676 677
        NSDictionary *result = results[0];
        file.artworkURL = result[@"artworkURL"];
        file.title = result[@"title"];
        file.shortSummary = result[@"shortSummary"];
        file.releaseYear = result[@"releaseYear"];
Pierre's avatar
Pierre committed
678
    }
Pierre's avatar
Pierre committed
679 680 681 682
    else {
        [self noMetaDataInRemoteDBForFile:file];
    }

Pierre's avatar
Pierre committed
683 684 685 686
    file.hasFetchedInfo = yes;
}
#endif

Pierre's avatar
Pierre committed
687
- (void)fetchMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
688
{
689
    APLog(@"Fetching meta data for %@", file.title);
Pierre's avatar
Pierre committed
690

Pierre's avatar
Pierre committed
691
    NSDictionary *tvShowEpisodeInfo = [MLTitleDecrapifier tvShowEpisodeInfoFromString:file.title];
Pierre's avatar
Pierre committed
692
    if (tvShowEpisodeInfo) {
693
        file.type = kMLFileTypeTVShowEpisode;
Pierre's avatar
Pierre committed
694 695 696 697
        [self addTVShowEpisodeWithInfo:tvShowEpisodeInfo andFile:file];
        return;
    }

698 699
    if (!_allowNetworkAccess)
        return;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
700
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
701
    // Go online and fetch info.
Pierre's avatar
Pierre committed
702 703 704

    // We don't care about keeping a reference to track the item during its life span
    // because we are a singleton
705
    MLMovieInfoGrabber *grabber = [[MLMovieInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
706

707
    APLog(@"Looking up for Movie '%@'", file.title);
Pierre's avatar
Pierre committed
708

Felix Paul Kühne's avatar
Felix Paul Kühne committed
709

Pierre's avatar
Pierre committed
710
    [grabber lookUpForTitle:file.title andExecuteBlock:^(NSError *err){
Pierre's avatar
Pierre committed
711 712
        if (err) {
            [self errorWhenFetchingMetaDataForFile:file];
Pierre's avatar
Pierre committed
713
            return;
Pierre's avatar
Pierre committed
714
        }
Pierre's avatar
Pierre committed
715 716 717 718 719

        NSArray *results = grabber.results;
        if ([results count] > 0) {
            NSDictionary *result = [results objectAtIndex:0];
            file.artworkURL = [result objectForKey:@"artworkURL"];
Pierre's avatar
Pierre committed
720 721
            if (!file.artworkURL)
                [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
722 723 724
            file.title = [result objectForKey:@"title"];
            file.shortSummary = [result objectForKey:@"shortSummary"];
            file.releaseYear = [result objectForKey:@"releaseYear"];
Pierre's avatar
Pierre committed
725 726 727
        } else
            [self noMetaDataInRemoteDBForFile:file];
        file.hasFetchedInfo = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
728
    }];
Pierre's avatar
Pierre committed
729
#endif
Pierre's avatar
Pierre committed
730 731
}

Pierre's avatar
Pierre committed
732 733 734
#pragma mark -
#pragma mark Adding file to the DB

735 736 737 738 739 740 741 742
#ifdef MLKIT_READONLY_TARGET

- (void)addFilePaths:(NSArray *)filepaths
{
}

#else

Pierre's avatar
Pierre committed
743
- (void)addFilePath:(NSString *)filePath
Pierre's avatar
Pierre committed
744
{
745
    APLog(@"Adding Path %@", filePath);
Pierre's avatar
Pierre committed
746

Pierre's avatar
Pierre committed
747
    NSURL *url = [NSURL fileURLWithPath:filePath];
Pierre's avatar
Pierre committed
748
    NSString *title = [filePath lastPathComponent];
Pierre's avatar
Pierre committed
749
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
750 751
    NSDate *openedDate = nil; // FIXME kMDItemLastUsedDate
    NSDate *modifiedDate = nil; // FIXME [result valueForAttribute:@"kMDItemFSContentChangeDate"];
Pierre's avatar
Pierre committed
752
#endif
Pierre's avatar
Pierre committed
753

Pierre's avatar
Pierre committed
754
    MLFile *file = [self createObjectForEntity:@"File"];
755
    file.url = url;
Pierre's avatar
Pierre committed
756 757 758 759

    // Yes, this is a negative number. VLCTime nicely display negative time
    // with "XX minutes remaining". And we are using this facility.

760 761
    NSNumber *no = @NO;
    NSNumber *yes = @YES;
Pierre's avatar
Pierre committed
762 763

    file.currentlyWatching = no;
764 765
    file.lastPosition = @0.0;
    file.remainingTime = @0.0;
Pierre's avatar
Pierre committed
766 767
    file.unread = yes;

Pierre's avatar
Pierre committed
768
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
769 770 771 772
    if ([openedDate isGreaterThan:modifiedDate]) {
        file.playCount = [NSNumber numberWithDouble:1];
        file.unread = no;
    }
Pierre's avatar
Pierre committed
773 774
#endif

775 776 777 778
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:kDecrapifyTitles] boolValue] == YES)
        file.title = [MLTitleDecrapifier decrapify:[title stringByDeletingPathExtension]];
    else
        file.title = [title stringByDeletingPathExtension];
Pierre's avatar
Pierre committed
779

780
    [[MLFileParserQueue sharedFileParserQueue] addFile:file];
Pierre's avatar
Pierre committed
781 782
}

Pierre's avatar
Pierre committed
783
- (void)addFilePaths:(NSArray *)filepaths
Pierre's avatar
Pierre committed
784
{
Pierre's avatar
Pierre committed
785
    NSUInteger count = [filepaths count];
Pierre's avatar
Pierre committed
786 787 788 789
    NSMutableArray *fetchPredicates = [NSMutableArray arrayWithCapacity:count];
    NSMutableDictionary *urlToObject = [NSMutableDictionary dictionaryWithCapacity:count];

    // Prepare a fetch request for all items
Pierre's avatar
Pierre committed
790
    for (NSString *path in filepaths) {
791
        NSString *relativePath = path;
792
#if TARGET_OS_IPHONE
793 794
        // on iPhone we only save relative paths ins the DB
        relativePath = [self pathRelativeToDocumentsFolderFromAbsolutPath:path];
795
#endif
796 797
        [urlToObject setObject:path forKey:relativePath];
        [fetchPredicates addObject:[NSPredicate predicateWithFormat:@"path == %@", relativePath]];
Pierre's avatar
Pierre committed
798 799
    }
    NSFetchRequest *request = [self fetchRequestForEntity:@"File"];
800 801
    if (!request)
        return;
Pierre's avatar
Pierre committed
802 803
    [request setPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:fetchPredicates]];

804
    APLog(@"Fetching");
805 806 807 808
    NSManagedObjectContext *moc = [self managedObjectContext];
    if (!moc)
        return;
    NSArray *dbResults = [moc executeFetchRequest:request error:nil];
809
    APLog(@"Done");
Pierre's avatar
Pierre committed
810

Pierre's avatar
Pierre committed
811
    NSMutableArray *filePathsToAdd = [NSMutableArray arrayWithArray:filepaths];
Pierre's avatar
Pierre committed
812 813

    // Remove objects that are already in db.
Pierre's avatar
Pierre committed
814
    for (MLFile *dbResult in dbResults) {
815 816
        NSString *path = dbResult.path;
        [filePathsToAdd removeObject:[urlToObject objectForKey:path]];
Pierre's avatar
Pierre committed
817 818 819
    }

    // Add only the newly added items
Pierre's avatar
Pierre committed
820 821
    for (NSString* path in filePathsToAdd)
        [self addFilePath:path];
Pierre's avatar
Pierre committed
822
}
823
#endif
Pierre's avatar
Pierre committed
824 825 826 827

#pragma mark -
#pragma mark DB Updates

Felix Paul Kühne's avatar
Felix Paul Kühne committed
828
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
829 830 831
- (void)tvShowInfoGrabber:(MLTVShowInfoGrabber *)grabber didFetchUpdates:(NSArray *)updates
{
    NSFetchRequest *request = [self fetchRequestForEntity:@"Show"];
832 833 834
    if (!request)
        return;

Pierre's avatar
Pierre committed
835 836
    [request setPredicate:[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"theTVDBID"] rightExpression:[NSExpression expressionForConstantValue:updates] modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:0]];
    NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
837
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
838 839 840 841
        [self fetchMetaDataForShow:show];
}
#endif

842 843 844 845 846 847 848 849
#ifdef MLKIT_READONLY_TARGET

- (void)updateMediaDatabase
{
}

#else

850
- (void)updateMediaDatabase
Pierre's avatar
Pierre committed
851
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
852
    [self libraryDidDisappear];
Pierre's avatar
Pierre committed
853
    // Remove no more present files
Pierre's avatar
Pierre committed
854
    NSFetchRequest *request = [self fetchRequestForEntity:@"File"];
855 856
    if (!request)
        return;
857 858 859 860
    NSManagedObjectContext *moc = [self managedObjectContext];
    if (!moc)
        return;
    NSArray *results = [moc executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
861
    NSFileManager *fileManager = [NSFileManager defaultManager];
862

863
    unsigned int count = (unsigned int)results.count;
864 865
    for (unsigned int x = 0; x < count; x++) {
        MLFile *file = results[x];
866
       NSURL *fileURL = file.url;
867
        BOOL exists = [fileManager fileExistsAtPath:[fileURL path]];
868
        if (!exists) {
869
            APLog(@"Marking - %@", [fileURL absoluteString]);
870
            file.isSafe = YES; // It doesn't exist, it's safe.
871 872
            if (file.isAlbumTrack) {
                MLAlbum *album = file.albumTrack.album;
873 874 875 876 877 878 879 880 881 882 883
                if (album != nil) {
                    if (album.tracks.count <= 1) {
                        @try {
                            [moc deleteObject:album];
                        }
                        @catch (NSException *exception) {
                            APLog(@"failed to nuke object because it disappeared in front of us");
                        }
                    } else
                        [album removeTrack:file.albumTrack];
                }
884 885 886
            }
            if (file.isShowEpisode) {
                MLShow *show = file.showEpisode.show;
887 888 889 890 891 892 893 894 895 896 897
                if (show != nil) {
                    if (show.episodes.count <= 1) {
                        @try {
                            [moc deleteObject:show];
                        }
                        @catch (NSException *exception) {
                            APLog(@"failed to nuke object because it disappeared in front of us");
                        }
                    } else
                        [show removeEpisode:file.showEpisode];
                }
898
            }
899
#if TARGET_OS_IOS
900
            NSString *thumbPath = [file thumbnailPath];
901 902
            bool thumbExists = [fileManager fileExistsAtPath:thumbPath];
            if (thumbExists)
903
                [fileManager removeItemAtPath:thumbPath error:nil];
904 905 906 907 908 909 910 911 912

            if (SYSTEM_RUNS_IOS9) {
            /* remove file from CoreSpotlight */
                [[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:@[file.objectID.URIRepresentation.absoluteString]
                                                                               completionHandler:^(NSError * __nullable error) {
                                                                                   NSLog(@"Removed %@ from index", file.objectID.URIRepresentation);
                                                                               }];
            }

913
            [moc deleteObject:file];
914
#endif
915
        }
916 917 918
#if !TARGET_OS_IPHONE
    file.isOnDisk = @(exists);
#endif
Pierre's avatar
Pierre committed
919
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
920
    [self libraryDidAppear];
Pierre's avatar
Pierre committed
921

922 923
    // Get the file to parse
    request = [self fetchRequestForEntity:@"File"];
924 925
    if (!request)
        return;
926
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && tracks.@count == 0"]];
927
    results = [moc executeFetchRequest:request error:nil];
928 929 930
    for (MLFile *file in results)
        [[MLFileParserQueue sharedFileParserQueue] addFile:file];

931 932 933
    if (!_allowNetworkAccess) {
        // Always attempt to fetch
        request = [self fetchRequestForEntity:@"File"];
934 935
        if (!request)
            return;
936
        [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES"]];
937
        results = [moc executeFetchRequest:request error:nil];
938
        for (MLFile *file in results) {
939
            if (!file.computedThumbnail && ![file isKindOfType:kMLFileTypeAudio])
940 941
                [self computeThumbnailForFile:file];
        }
942 943 944
        return;
    }

Pierre's avatar
Pierre committed
945 946
    // Get the thumbnails to compute
    request = [self fetchRequestForEntity:@"File"];
947 948
    if (!request)
        return;
949
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && hasFetchedInfo == 1 && artworkURL == nil"]];
950
    results = [moc executeFetchRequest:request error:nil];
951 952 953 954 955 956
    for (MLFile *file in results) {
        if (!file.computedThumbnail) {
            if (!file.albumTrack && ![file isKindOfType:kMLFileTypeAudio])
                [self computeThumbnailForFile:file];
        }
    }
Pierre's avatar
Pierre committed
957 958 959

    // Get to fetch meta data
    request = [self fetchRequestForEntity:@"File"];
960 961
    if (!request)
        return;
Pierre's avatar
Pierre committed
962
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && hasFetchedInfo == 0"]];
963
    results = [moc executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
964
    for (MLFile *file in results)
965
        [[MLFileParserQueue sharedFileParserQueue] addFile:file];
Pierre's avatar
Pierre committed
966

Pierre's avatar
Pierre committed
967
    // Get to fetch show info
Pierre's avatar
Pierre committed
968
    request = [self fetchRequestForEntity:@"Show"];
969 970
    if (!request)
        return;
Pierre's avatar
Pierre committed
971
    [request setPredicate:[NSPredicate predicateWithFormat:@"lastSyncDate == 0"]];
972
    results = [moc executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
973
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
974 975
        [self fetchMetaDataForShow:show];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
976
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
977
    // Get updated TV Shows
978
    NSNumber *lastServerTime = @([[NSUserDefaults standardUserDefaults] integerForKey:kLastTVDBUpdateServerTime]);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
979

Pierre's avatar
Pierre committed
980
    [MLTVShowInfoGrabber fetchUpdatesSinceServerTime:lastServerTime andExecuteBlock:^(NSArray *updates){
Pierre's avatar
Pierre committed
981
        NSFetchRequest *request = [self fetchRequestForEntity:@"Show"];
982 983
        if (!request)
            return;
Pierre's avatar
Pierre committed
984
        [request setPredicate:[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"theTVDBID"] rightExpression:[NSExpression expressionForConstantValue:updates] modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:0]];
985
        NSArray *results = [moc executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
986
        for (MLShow *show in results)
Pierre's avatar
Pierre committed
987 988
            [self fetchMetaDataForShow:show];
    }];
Pierre's avatar
Pierre committed
989
#endif
Pierre's avatar
Pierre committed
990
    /* Update every hour - FIXME: Preferences key */
991
    [self performSelector:@selector(updateMediaDatabase) withObject:nil afterDelay:60 * 60];
Pierre's avatar
Pierre committed
992
}
993
#endif
Pierre's avatar
Pierre committed
994

995 996
- (void)applicationWillExit
{
997
    [[MLFileParserQueue sharedFileParserQueue] stop];
998 999 1000
    [[MLCrashPreventer sharedPreventer] cancelAllFileParse];
}

Pierre's avatar
Pierre committed
1001 1002 1003
- (void)applicationWillStart
{
    [[MLCrashPreventer sharedPreventer] markCrasherFiles];
1004
    [[MLFileParserQueue sharedFileParserQueue] resume];
Pierre's avatar
Pierre committed
1005 1006
}

Pierre's avatar
Pierre committed
1007 1008 1009 1010
- (void)libraryDidDisappear
{
    // Stop expansive work
    [[MLThumbnailerQueue sharedThumbnailerQueue] stop];
1011
    [[MLFileParserQueue sharedFileParserQueue] stop];
Pierre's avatar
Pierre committed
1012 1013 1014 1015 1016 1017
}

- (void)libraryDidAppear
{
    // Resume our work
    [[MLThumbnailerQueue sharedThumbnailerQueue] resume];
1018
    [[MLFileParserQueue sharedFileParserQueue] resume];
Pierre's avatar
Pierre committed
1019
}
1020

1021
#pragma mark - migrations
1022

1023 1024 1025 1026 1027 1028 1029
- (BOOL)libraryMigrationNeeded
{
    return [self _libraryMigrationNeeded];
}
- (void)migrateLibrary
{
    [self _migrateLibrary];
1030 1031
}

Pierre's avatar
Pierre committed
1032
@end