MLMediaLibrary.m 35.6 KB
Newer Older
1 2 3 4 5
/*****************************************************************************
 * MLMediaLibrary.m
 * MobileMediaLibraryKit
 *****************************************************************************
 * Copyright (C) 2010 Pierre d'Herbemont
6
 * Copyright (C) 2010-2014 VLC authors and VideoLAN
7 8 9 10 11
 * $Id$
 *
 * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
 *          Felix Paul Kühne <fkuehne # videolan.org>
 *
12 13 14
 * 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
15 16 17 18
 * (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
19 20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
21
 *
22 23 24
 * 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.
25
 *****************************************************************************/
Pierre's avatar
Pierre committed
26 27

#import "MLMediaLibrary.h"
Pierre's avatar
Pierre committed
28 29
#import "MLTitleDecrapifier.h"
#import "MLMovieInfoGrabber.h"
Pierre's avatar
Pierre committed
30 31
#import "MLTVShowInfoGrabber.h"
#import "MLTVShowEpisodesInfoGrabber.h"
Pierre's avatar
Pierre committed
32 33 34 35
#import "MLFile.h"
#import "MLLabel.h"
#import "MLShowEpisode.h"
#import "MLShow.h"
36 37 38
#import "MLThumbnailerQueue.h"
#import "MLAlbumTrack.h"
#import "MLAlbum.h"
39
#import "MLFileParserQueue.h"
40
#import "MLCrashPreventer.h"
Pierre's avatar
Pierre committed
41

42 43
@interface MLMediaLibrary ()
{
44 45 46 47 48
    NSManagedObjectContext *_managedObjectContext;
    NSManagedObjectModel   *_managedObjectModel;

    BOOL _allowNetworkAccess;

49 50
    NSString *_thumbnailFolderPath;
    NSString *_databaseFolderPath;
51
    NSString *_documentFolderPath;
52 53 54
}
@end

Pierre's avatar
Pierre committed
55
#define DEBUG 1
56 57
// To debug
#define DELETE_LIBRARY_ON_EACH_LAUNCH 0
Pierre's avatar
Pierre committed
58

Pierre's avatar
Pierre committed
59 60
// Pref key
static NSString *kLastTVDBUpdateServerTime = @"MLLastTVDBUpdateServerTime";
61
static NSString *kUpdatedToTheGreatSharkHuntDatabaseFormat = @"upgradedToDatabaseFormat 2.3";
62
static NSString *kDecrapifyTitles = @"MLDecrapifyTitles";
Pierre's avatar
Pierre committed
63

Pierre's avatar
Pierre committed
64
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
65
@interface MLMediaLibrary ()
Pierre's avatar
Pierre committed
66 67 68
#else
@interface MLMediaLibrary () <MLMovieInfoGrabberDelegate, MLTVShowEpisodesInfoGrabberDelegate, MLTVShowInfoGrabberDelegate>
#endif
Pierre's avatar
Pierre committed
69
- (NSManagedObjectContext *)managedObjectContext;
Pierre's avatar
Pierre committed
70
- (NSString *)databaseFolderPath;
Pierre's avatar
Pierre committed
71 72
@end

Pierre's avatar
Pierre committed
73
@implementation MLMediaLibrary
74 75
+ (void)initialize
{
76
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
77
    [defaults registerDefaults:@{kUpdatedToTheGreatSharkHuntDatabaseFormat : @NO, kDecrapifyTitles : @YES}];
78 79
}

Pierre's avatar
Pierre committed
80 81 82
+ (id)sharedMediaLibrary
{
    static id sharedMediaLibrary = nil;
Pierre's avatar
Pierre committed
83
    if (!sharedMediaLibrary) {
Pierre's avatar
Pierre committed
84
        sharedMediaLibrary = [[[self class] alloc] init];
85
        APLog(@"Initializing db in %@", [sharedMediaLibrary databaseFolderPath]);
86 87 88 89

        // 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
90
    }
Pierre's avatar
Pierre committed
91 92 93
    return sharedMediaLibrary;
}

94 95 96 97 98 99
- (void)dealloc
{
    if (_managedObjectContext)
        [_managedObjectContext removeObserver:self forKeyPath:@"hasChanges"];
}

Pierre's avatar
Pierre committed
100 101 102 103 104
- (NSFetchRequest *)fetchRequestForEntity:(NSString *)entity
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSManagedObjectContext *moc = [self managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entity inManagedObjectContext:moc];
Pierre's avatar
Pierre committed
105
    NSAssert(entityDescription, @"No entity");
Pierre's avatar
Pierre committed
106
    [request setEntity:entityDescription];
107
    return request;
Pierre's avatar
Pierre committed
108 109 110 111 112 113 114 115
}

- (id)createObjectForEntity:(NSString *)entity
{
    NSManagedObjectContext *moc = [self managedObjectContext];
    return [NSEntityDescription insertNewObjectForEntityForName:entity inManagedObjectContext:moc];
}

116 117 118 119 120
- (void)removeObject:(NSManagedObject *)object
{
    [[self managedObjectContext] deleteObject:object];
}

Pierre's avatar
Pierre committed
121 122 123 124 125 126
#pragma mark -
#pragma mark Media Library
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel)
        return _managedObjectModel;
127 128 129 130 131

    NSString *path = [[NSBundle mainBundle] pathForResource:@"MediaLibrary-2.5" ofType:@"mom"];
    NSURL *momURL = [NSURL fileURLWithPath:path];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momURL];

Pierre's avatar
Pierre committed
132 133 134
    return _managedObjectModel;
}

Pierre's avatar
Pierre committed
135
- (NSString *)databaseFolderPath
Pierre's avatar
Pierre committed
136
{
137 138 139 140
    if (_databaseFolderPath) {
        if (_databaseFolderPath.length > 0)
            return _databaseFolderPath;
    }
Pierre's avatar
Pierre committed
141 142
    int directory = NSLibraryDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
143
    NSString *directoryPath = paths[0];
144
#if DELETE_LIBRARY_ON_EACH_LAUNCH
Pierre's avatar
Pierre committed
145
    [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
146
#endif
147 148
    _databaseFolderPath = directoryPath;
    return _databaseFolderPath;
Pierre's avatar
Pierre committed
149 150
}

151 152
- (NSString *)thumbnailFolderPath
{
153 154 155 156
    if (_thumbnailFolderPath) {
        if (_thumbnailFolderPath.length > 0)
            return _thumbnailFolderPath;
    }
157 158
    int directory = NSLibraryDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
159
    NSString *directoryPath = paths[0];
160 161 162
#if DELETE_LIBRARY_ON_EACH_LAUNCH
    [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
#endif
163 164
    _thumbnailFolderPath = [directoryPath stringByAppendingPathComponent:@"Thumbnails"];
    return _thumbnailFolderPath;
165 166
}

167 168 169 170 171 172 173 174 175
- (NSString *)documentFolderPath
{
    if (_documentFolderPath) {
        if (_documentFolderPath.length > 0)
            return _documentFolderPath;
    }
    int directory = NSDocumentDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);

176
    _documentFolderPath = [NSString stringWithFormat:@"file://%@", paths[0]];
177 178 179
    return _documentFolderPath;
}

180
- (NSURL *)persistentStoreURL {
Pierre's avatar
Pierre committed
181
    NSString *databaseFolderPath = [self databaseFolderPath];
Pierre's avatar
Pierre committed
182
    NSString *path = [databaseFolderPath stringByAppendingPathComponent: @"MediaLibrary.sqlite"];
183 184 185 186 187
    return [NSURL fileURLWithPath:path];
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

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

190
    NSNumber *yes = @YES;
191
    NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption : yes,
192
                              NSInferMappingModelAutomaticallyOption : yes};
Pierre's avatar
Pierre committed
193 194

    NSError *error;
195
    NSPersistentStore *persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.persistentStoreURL options:options error:&error];
Pierre's avatar
Pierre committed
196 197

    if (!persistentStore) {
Pierre's avatar
Pierre committed
198
#if! TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
199 200 201 202
        // 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];
203
        [[NSFileManager defaultManager] removeItemAtPath:self.persistentStoreURL.path error:nil];
Pierre's avatar
Pierre committed
204
#else
205
        [[NSFileManager defaultManager] removeItemAtPath:self.persistentStoreURL.path error:nil];
Pierre's avatar
Pierre committed
206
#endif
207
        persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.persistentStoreURL options:options error:&error];
Pierre's avatar
Pierre committed
208 209 210 211 212 213 214 215 216 217
        if (!persistentStore) {
#if! TARGET_OS_IPHONE
            NSRunInformationalAlertPanel(@"Corrupted Media Library", @"There is nothing we can apparently do about it...", @"OK", nil, nil);
#else
            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];
#endif
            // Probably assert instead.
            return nil;
        }
Pierre's avatar
Pierre committed
218
    }
219 220 221 222 223 224 225
    return coordinator;
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext)
        return _managedObjectContext;
Pierre's avatar
Pierre committed
226 227

    _managedObjectContext = [[NSManagedObjectContext alloc] init];
228
    [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
Pierre's avatar
Pierre committed
229 230 231 232 233 234 235 236
    [_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
237 238 239
    NSError *error = nil;
    BOOL success = [[self managedObjectContext] save:&error];
    NSAssert1(success, @"Can't save: %@", error);
Pierre's avatar
Pierre committed
240
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
241 242 243 244 245 246
    NSProcessInfo *process = [NSProcessInfo processInfo];
    if ([process respondsToSelector:@selector(enableSuddenTermination)])
        [process enableSuddenTermination];
#endif
}

247 248 249 250 251 252 253
- (void)save
{
    NSError *error = nil;
    BOOL success = [[self managedObjectContext] save:&error];
    NSAssert1(success, @"Can't save: %@", error);
}

Pierre's avatar
Pierre committed
254
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Pierre's avatar
Pierre committed
255 256
{
    if ([keyPath isEqualToString:@"hasChanges"] && object == _managedObjectContext) {
Pierre's avatar
Pierre committed
257
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
258 259 260 261 262
        NSProcessInfo *process = [NSProcessInfo processInfo];
        if ([process respondsToSelector:@selector(disableSuddenTermination)])
            [process disableSuddenTermination];
#endif

Pierre's avatar
Pierre committed
263 264 265 266
        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
267 268 269 270 271
        return;
    }
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

Pierre's avatar
Pierre committed
272 273
#pragma mark -
#pragma mark No meta data fallbacks
Pierre's avatar
Pierre committed
274

Pierre's avatar
Pierre committed
275
- (void)computeThumbnailForFile:(MLFile *)file
Pierre's avatar
Pierre committed
276
{
Pierre's avatar
Pierre committed
277
    if (!file.computedThumbnail) {
278
        APLog(@"Computing thumbnail for %@", file.title);
Pierre's avatar
Pierre committed
279 280
        [[MLThumbnailerQueue sharedThumbnailerQueue] addFile:file];
    }
Pierre's avatar
Pierre committed
281
}
Pierre's avatar
Pierre committed
282
- (void)errorWhenFetchingMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
283
{
284
    APLog(@"Error when fetching for '%@'", file.title);
Pierre's avatar
Pierre committed
285

Pierre's avatar
Pierre committed
286 287
    [self computeThumbnailForFile:file];
}
Pierre's avatar
Pierre committed
288

Pierre's avatar
Pierre committed
289 290 291 292 293 294 295
- (void)errorWhenFetchingMetaDataForShow:(MLShow *)show
{
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self errorWhenFetchingMetaDataForFile:file];
    }
}
Pierre's avatar
Pierre committed
296

Pierre's avatar
Pierre committed
297 298
- (void)noMetaDataInRemoteDBForFile:(MLFile *)file
{
299
    file.noOnlineMetaData = @YES;
Pierre's avatar
Pierre committed
300
    [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
301 302
}

Pierre's avatar
Pierre committed
303
- (void)noMetaDataInRemoteDBForShow:(MLShow *)show
Pierre's avatar
Pierre committed
304
{
Pierre's avatar
Pierre committed
305 306 307
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self noMetaDataInRemoteDBForFile:file];
Pierre's avatar
Pierre committed
308 309 310
    }
}

Pierre's avatar
Pierre committed
311 312 313 314
#pragma mark -
#pragma mark Getter

- (void)addNewLabelWithName:(NSString *)name
Pierre's avatar
Pierre committed
315
{
Pierre's avatar
Pierre committed
316 317
    MLLabel *label = [self createObjectForEntity:@"Label"];
    label.name = name;
Pierre's avatar
Pierre committed
318 319
}

Pierre's avatar
Pierre committed
320 321 322 323 324 325 326
/**
 * TV MLShow Episodes
 */

#pragma mark -
#pragma mark Online meta data grabbing

Pierre's avatar
Pierre committed
327 328 329
#if !HAVE_BLOCK
- (void)tvShowEpisodesInfoGrabberDidFinishGrabbing:(MLTVShowEpisodesInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
330
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
331 332

    NSArray *results = grabber.episodesResults;
333
    [show setValue:(grabber.results)[@"serieArtworkURL"] forKey:@"artworkURL"];
Pierre's avatar
Pierre committed
334
    for (id result in results) {
335
        if ([result[@"serie"] boolValue]) {
Pierre's avatar
Pierre committed
336 337
            continue;
        }
338 339 340 341 342
        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
343 344 345 346 347
        if (!showEpisode.artworkURL) {
            for (MLFile *file in showEpisode.files)
                [self computeThumbnailForFile:file];
        }

Pierre's avatar
Pierre committed
348 349 350 351 352
        showEpisode.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
    show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
}

Pierre's avatar
Pierre committed
353 354 355 356 357 358
- (void)tvShowEpisodesInfoGrabber:(MLTVShowEpisodesInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
359 360
- (void)tvShowInfoGrabberDidFinishGrabbing:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
361
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
362 363
    NSArray *results = grabber.results;
    if ([results count] > 0) {
364 365
        NSDictionary *result = results[0];
        NSString *showId = result[@"id"];
Pierre's avatar
Pierre committed
366 367

        show.theTVDBID = showId;
368 369 370
        show.name = result[@"title"];
        show.shortSummary = result[@"shortSummary"];
        show.releaseYear = result[@"releaseYear"];
Pierre's avatar
Pierre committed
371 372

        // Fetch episodes info
373
        MLTVShowEpisodesInfoGrabber *grabber = [[MLTVShowEpisodesInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
374 375 376 377 378 379
        grabber.delegate = self;
        grabber.userData = show;
        [grabber lookUpForShowID:showId];
    }
    else {
        // Not found.
Pierre's avatar
Pierre committed
380
        [self noMetaDataInRemoteDBForShow:show];
Pierre's avatar
Pierre committed
381 382 383 384
        show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
}

Pierre's avatar
Pierre committed
385 386 387 388 389 390
- (void)tvShowInfoGrabber:(MLTVShowInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
391 392
- (void)tvShowInfoGrabberDidFetchServerTime:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
393
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
394 395 396

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

Pierre's avatar
Pierre committed
397
    // First fetch the MLShow ID
398
    MLTVShowInfoGrabber *showInfoGrabber = [[MLTVShowInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
399 400 401
    showInfoGrabber.delegate = self;
    showInfoGrabber.userData = show;

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

Pierre's avatar
Pierre committed
404 405 406 407
    [showInfoGrabber lookUpForTitle:show.name];
}
#endif

Pierre's avatar
Pierre committed
408
- (void)fetchMetaDataForShow:(MLShow *)show
Pierre's avatar
Pierre committed
409
{
410 411
    if (!_allowNetworkAccess)
        return;
412
    APLog(@"Fetching show server time");
Pierre's avatar
Pierre committed
413

Pierre's avatar
Pierre committed
414
    // First fetch the serverTime, so that we can update each entry.
Pierre's avatar
Pierre committed
415 416
#if HAVE_BLOCK
    [MLTVShowInfoGrabber fetchServerTimeAndExecuteBlock:^(NSNumber *serverDate) {
Pierre's avatar
Pierre committed
417 418 419

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

420
        APLog(@"Fetching show information on %@", show.name);
Pierre's avatar
Pierre committed
421 422 423

        // First fetch the MLShow ID
        MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
424 425 426 427 428 429 430 431 432 433 434
        [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"];

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

Pierre's avatar
Pierre committed
437
                // Fetch episode info
Pierre's avatar
Pierre committed
438
                MLTVShowEpisodesInfoGrabber *grabber = [[[MLTVShowEpisodesInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
439 440 441 442 443 444 445
                [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;
                        }
446
                        MLShowEpisode *showEpisode = [MLShowEpisode episodeWithShow:show episodeNumber:[result objectForKey:@"episodeNumber"] seasonNumber:[result objectForKey:@"seasonNumber"] createIfNeeded:YES];
Pierre's avatar
Pierre committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                        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
463
#else
464
    MLTVShowInfoGrabber *grabber = [[MLTVShowInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
465 466 467
    grabber.delegate = self;
    grabber.userData = show;
    [grabber fetchServerTime];
Pierre's avatar
Pierre committed
468
#endif
Pierre's avatar
Pierre committed
469 470
}

Pierre's avatar
Pierre committed
471
- (void)addTVShowEpisodeWithInfo:(NSDictionary *)tvShowEpisodeInfo andFile:(MLFile *)file
Pierre's avatar
Pierre committed
472
{
Pierre's avatar
Pierre committed
473
    file.type = kMLFileTypeTVShowEpisode;
Pierre's avatar
Pierre committed
474

475 476 477
    NSNumber *seasonNumber = tvShowEpisodeInfo[@"season"];
    NSNumber *episodeNumber = tvShowEpisodeInfo[@"episode"];
    NSString *tvShowName = tvShowEpisodeInfo[@"tvShowName"];
478
    NSString *tvEpisodeName = tvShowEpisodeInfo[@"tvEpisodeName"];
Pierre's avatar
Pierre committed
479 480
    BOOL hasNoTvShow = NO;
    if (!tvShowName) {
481
        tvShowName = @"";
Pierre's avatar
Pierre committed
482 483 484
        hasNoTvShow = YES;
    }
    BOOL wasInserted = NO;
Pierre's avatar
Pierre committed
485 486
    MLShow *show = nil;
    MLShowEpisode *episode = [MLShowEpisode episodeWithShowName:tvShowName episodeNumber:episodeNumber seasonNumber:seasonNumber createIfNeeded:YES wasCreated:&wasInserted];
487 488

    if (episode) {
Pierre's avatar
Pierre committed
489
        show = episode.show;
490 491
        [show addEpisode:episode];
    }
Pierre's avatar
Pierre committed
492 493 494 495
    if (wasInserted && !hasNoTvShow) {
        show.name = tvShowName;
        [self fetchMetaDataForShow:show];
    }
496
    episode.name = tvEpisodeName;
Pierre's avatar
Pierre committed
497

498
    if (episode.name.length < 1)
Pierre's avatar
Pierre committed
499 500 501
        episode.name = file.title;
    file.seasonNumber = seasonNumber;
    file.episodeNumber = episodeNumber;
502
    episode.shouldBeDisplayed = @YES;
Pierre's avatar
Pierre committed
503 504

    [episode addFilesObject:file];
Pierre's avatar
Pierre committed
505
    file.showEpisode = episode;
Pierre's avatar
Pierre committed
506

Pierre's avatar
Pierre committed
507
    // The rest of the meta data will be fetched using the MLShow
508
    file.hasFetchedInfo = @YES;
Pierre's avatar
Pierre committed
509 510
}

511 512 513 514
- (void)addAudioContentWithInfo:(NSDictionary *)audioContentInfo andFile:(MLFile *)file
{
    file.type = kMLFileTypeAudio;

515 516 517
    file.title = audioContentInfo[VLCMetaInformationTitle];

    /* all further meta data is set by the FileParserQueue */
518 519 520 521

    file.hasFetchedInfo = @YES;
}

Pierre's avatar
Pierre committed
522
/**
Pierre's avatar
Pierre committed
523
 * MLFile auto detection
Pierre's avatar
Pierre committed
524 525
 */

Pierre's avatar
Pierre committed
526
#if !HAVE_BLOCK
Pierre's avatar
Pierre committed
527 528 529 530 531 532
- (void)movieInfoGrabber:(MLMovieInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLFile *file = grabber.userData;
    [self errorWhenFetchingMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
533 534
- (void)movieInfoGrabberDidFinishGrabbing:(MLMovieInfoGrabber *)grabber
{
535
    NSNumber *yes = @YES;
Pierre's avatar
Pierre committed
536 537

    NSArray *results = grabber.results;
Pierre's avatar
Pierre committed
538
    MLFile *file = grabber.userData;
Pierre's avatar
Pierre committed
539
    if ([results count] > 0) {
540 541 542 543 544
        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
545
    }
Pierre's avatar
Pierre committed
546 547 548 549
    else {
        [self noMetaDataInRemoteDBForFile:file];
    }

Pierre's avatar
Pierre committed
550 551 552 553
    file.hasFetchedInfo = yes;
}
#endif

Pierre's avatar
Pierre committed
554
- (void)fetchMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
555
{
556
    APLog(@"Fetching meta data for %@", file.title);
Pierre's avatar
Pierre committed
557

558
    [[MLFileParserQueue sharedFileParserQueue] addFile:file];
559

560 561 562 563 564
    if (!_allowNetworkAccess) {
        // Automatically compute the thumbnail
        [self computeThumbnailForFile:file];
    }

Pierre's avatar
Pierre committed
565
    NSDictionary *tvShowEpisodeInfo = [MLTitleDecrapifier tvShowEpisodeInfoFromString:file.title];
Pierre's avatar
Pierre committed
566 567 568 569 570
    if (tvShowEpisodeInfo) {
        [self addTVShowEpisodeWithInfo:tvShowEpisodeInfo andFile:file];
        return;
    }

571 572 573 574 575 576 577 578
    if ([file isSupportedAudioFile]) {
        NSDictionary *audioContentInfo = [MLTitleDecrapifier audioContentInfoFromFile:file];
        if (audioContentInfo && ![file videoTrack]) {
            [self addAudioContentWithInfo:audioContentInfo andFile:file];
            return;
        }
    }

579 580 581
    if (!_allowNetworkAccess)
        return;

Pierre's avatar
Pierre committed
582
    // Go online and fetch info.
Pierre's avatar
Pierre committed
583 584 585

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

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

Pierre's avatar
Pierre committed
590
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
591
    [grabber lookUpForTitle:file.title andExecuteBlock:^(NSError *err){
Pierre's avatar
Pierre committed
592 593
        if (err) {
            [self errorWhenFetchingMetaDataForFile:file];
Pierre's avatar
Pierre committed
594
            return;
Pierre's avatar
Pierre committed
595
        }
Pierre's avatar
Pierre committed
596 597 598 599 600

        NSArray *results = grabber.results;
        if ([results count] > 0) {
            NSDictionary *result = [results objectAtIndex:0];
            file.artworkURL = [result objectForKey:@"artworkURL"];
Pierre's avatar
Pierre committed
601 602
            if (!file.artworkURL)
                [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
603 604 605
            file.title = [result objectForKey:@"title"];
            file.shortSummary = [result objectForKey:@"shortSummary"];
            file.releaseYear = [result objectForKey:@"releaseYear"];
Pierre's avatar
Pierre committed
606 607 608
        } else
            [self noMetaDataInRemoteDBForFile:file];
        file.hasFetchedInfo = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
609
    }];
Pierre's avatar
Pierre committed
610
#else
Pierre's avatar
Pierre committed
611 612 613
    grabber.userData = file;
    grabber.delegate = self;
    [grabber lookUpForTitle:file.title];
Pierre's avatar
Pierre committed
614
#endif
Pierre's avatar
Pierre committed
615 616
}

Pierre's avatar
Pierre committed
617 618 619
#pragma mark -
#pragma mark Adding file to the DB

Pierre's avatar
Pierre committed
620
- (void)addFilePath:(NSString *)filePath
Pierre's avatar
Pierre committed
621
{
622
    APLog(@"Adding Path %@", filePath);
Pierre's avatar
Pierre committed
623

Pierre's avatar
Pierre committed
624
    NSURL *url = [NSURL fileURLWithPath:filePath];
Pierre's avatar
Pierre committed
625 626
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSString *title = [filePath lastPathComponent];
Pierre's avatar
Pierre committed
627
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
628 629
    NSDate *openedDate = nil; // FIXME kMDItemLastUsedDate
    NSDate *modifiedDate = nil; // FIXME [result valueForAttribute:@"kMDItemFSContentChangeDate"];
Pierre's avatar
Pierre committed
630
#endif
631
    NSNumber *size = attributes[NSFileSize]; // FIXME [result valueForAttribute:@"kMDItemFSSize"];
Pierre's avatar
Pierre committed
632

Pierre's avatar
Pierre committed
633
    MLFile *file = [self createObjectForEntity:@"File"];
Pierre's avatar
Pierre committed
634
    file.url = [url absoluteString];
Pierre's avatar
Pierre committed
635 636 637 638

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

639 640
    NSNumber *no = @NO;
    NSNumber *yes = @YES;
Pierre's avatar
Pierre committed
641 642

    file.currentlyWatching = no;
643 644
    file.lastPosition = @0.0;
    file.remainingTime = @0.0;
Pierre's avatar
Pierre committed
645 646
    file.unread = yes;

Pierre's avatar
Pierre committed
647
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
648 649 650 651
    if ([openedDate isGreaterThan:modifiedDate]) {
        file.playCount = [NSNumber numberWithDouble:1];
        file.unread = no;
    }
Pierre's avatar
Pierre committed
652 653
#endif

654 655 656 657
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:kDecrapifyTitles] boolValue] == YES)
        file.title = [MLTitleDecrapifier decrapify:[title stringByDeletingPathExtension]];
    else
        file.title = [title stringByDeletingPathExtension];
Pierre's avatar
Pierre committed
658 659

    if ([size longLongValue] < 150000000) /* 150 MB */
Pierre's avatar
Pierre committed
660
        file.type = kMLFileTypeClip;
Pierre's avatar
Pierre committed
661
    else
Pierre's avatar
Pierre committed
662
        file.type = kMLFileTypeMovie;
Pierre's avatar
Pierre committed
663 664 665 666

    [self fetchMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
667
- (void)addFilePaths:(NSArray *)filepaths
Pierre's avatar
Pierre committed
668
{
Pierre's avatar
Pierre committed
669
    NSUInteger count = [filepaths count];
Pierre's avatar
Pierre committed
670 671
    NSMutableArray *fetchPredicates = [NSMutableArray arrayWithCapacity:count];
    NSMutableDictionary *urlToObject = [NSMutableDictionary dictionaryWithCapacity:count];
672
    NSString *documentFolderPath = [[MLMediaLibrary sharedMediaLibrary] documentFolderPath];
Pierre's avatar
Pierre committed
673 674

    // Prepare a fetch request for all items
675 676 677
    NSArray *pathComponents;
    NSUInteger componentCount;

Pierre's avatar
Pierre committed
678
    for (NSString *path in filepaths) {
679
#if TARGET_OS_IPHONE
680
        NSString *urlString;
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
        NSString *componentString = @"";

        pathComponents = [path componentsSeparatedByString:@"/"];
        componentCount = pathComponents.count;
        if ([pathComponents[componentCount - 2] isEqualToString:@"Documents"])
            componentString = [path lastPathComponent];
        else {
            NSUInteger firstElement = [pathComponents indexOfObject:@"Documents"] + 1;
            for (NSUInteger x = 0; x < componentCount - firstElement; x++) {
                if (x == 0)
                    componentString = [componentString stringByAppendingFormat:@"%@", pathComponents[firstElement + x]];
                else
                    componentString = [componentString stringByAppendingFormat:@"/%@", pathComponents[firstElement + x]];
            }
        }
696

697 698 699 700 701 702
        /* compose and escape string */
        urlString = [[NSString stringWithFormat:@"%@/%@", documentFolderPath, componentString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        /* check for the end of the paths */
        [fetchPredicates addObject:[NSPredicate predicateWithFormat:@"url CONTAINS %@", [urlString lastPathComponent]]];
        [urlToObject setObject:path forKey:urlString];
703
#else
704
        [fetchPredicates addObject:[NSPredicate predicateWithFormat:@"url == %@", path]];
705
#endif
Pierre's avatar
Pierre committed
706 707 708 709 710
    }
    NSFetchRequest *request = [self fetchRequestForEntity:@"File"];

    [request setPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:fetchPredicates]];

711
    APLog(@"Fetching");
Pierre's avatar
Pierre committed
712
    NSArray *dbResults = [[self managedObjectContext] executeFetchRequest:request error:nil];
713
    APLog(@"Done");
Pierre's avatar
Pierre committed
714

Pierre's avatar
Pierre committed
715
    NSMutableArray *filePathsToAdd = [NSMutableArray arrayWithArray:filepaths];
Pierre's avatar
Pierre committed
716 717

    // Remove objects that are already in db.
Pierre's avatar
Pierre committed
718 719
    for (MLFile *dbResult in dbResults) {
        NSString *urlString = dbResult.url;
720
        [filePathsToAdd removeObject:[urlToObject objectForKey:urlString]];
Pierre's avatar
Pierre committed
721 722 723
    }

    // Add only the newly added items
Pierre's avatar
Pierre committed
724 725
    for (NSString* path in filePathsToAdd)
        [self addFilePath:path];
Pierre's avatar
Pierre committed
726 727
}

Pierre's avatar
Pierre committed
728 729 730 731

#pragma mark -
#pragma mark DB Updates

Pierre's avatar
Pierre committed
732 733 734 735 736 737
#if !HAVE_BLOCK
- (void)tvShowInfoGrabber:(MLTVShowInfoGrabber *)grabber didFetchUpdates:(NSArray *)updates
{
    NSFetchRequest *request = [self fetchRequestForEntity:@"Show"];
    [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
738
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
739 740 741 742
        [self fetchMetaDataForShow:show];
}
#endif

743 744
- (BOOL)libraryNeedsUpgrade
{
745
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:kUpdatedToTheGreatSharkHuntDatabaseFormat] boolValue])
746 747 748 749 750
        return YES;
    return NO;
}

- (void)upgradeLibrary
Felix Paul Kühne's avatar
Felix Paul Kühne committed
751 752 753 754 755 756
{
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:kUpdatedToTheGreatSharkHuntDatabaseFormat] boolValue])
        [self _upgradeLibraryToGreatSharkHuntDatabaseFormat];
}

- (void)_upgradeLibraryToGreatSharkHuntDatabaseFormat
757
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
758
    [self libraryDidDisappear];
759 760 761
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSFileManager *fileManager = [NSFileManager defaultManager];

762
    /* remove potential empty albums left over by previous releases */
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    NSArray *collection = [MLAlbum allAlbums];
    NSUInteger count = collection.count;
    MLAlbum *album;
    MLAlbumTrack *track;
    NSArray *secondaryCollection;
    NSURL *fileURL;
    NSUInteger secondaryCount = 0;
    NSArray *tertiaryCollection;
    NSUInteger tertiaryCount = 0;
    NSUInteger emptyAlbumCounter = 0;
    for (NSUInteger x = 0; x < count; x++) {
        album = collection[x];
        if (album.tracks.count < 1)
            [[self managedObjectContext] deleteObject:album];
        else {
            secondaryCollection = album.tracks.allObjects;
            secondaryCount = secondaryCollection.count;
            emptyAlbumCounter = 0;
            for (NSUInteger y = 0; y < secondaryCount; y++) {
                track = secondaryCollection[y];
                tertiaryCollection = track.files.allObjects;
                tertiaryCount = tertiaryCollection.count;
                for (NSUInteger z = 0; z < tertiaryCount; z++) {
                    fileURL = [NSURL URLWithString:[(MLFile *)tertiaryCollection[z] url]];
                    BOOL exists = [fileManager fileExistsAtPath:[fileURL path]];
                    if (exists)
                        emptyAlbumCounter++;
790 791
                    else
                        [album removeTrack:track];
792 793 794 795 796 797 798
                }
            }
            if (emptyAlbumCounter == 0)
                [[self managedObjectContext] deleteObject:album];
        }
    }
    album = nil;
799 800

    /* remove potential empty shows left over by previous releases */
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
    collection = [MLShow allShows];
    MLShow *show;
    MLShowEpisode *showEpisode;
    count = collection.count;
    for (NSUInteger x = 0; x < count; x++) {
        show = collection[x];
        if (show.episodes.count < 1)
            [[self managedObjectContext] deleteObject:show];
        else {
            secondaryCollection = show.episodes.allObjects;
            secondaryCount = secondaryCollection.count;
            emptyAlbumCounter = 0;
            for (NSUInteger y = 0; y < secondaryCount; y++) {
                showEpisode = secondaryCollection[y];
                tertiaryCollection = showEpisode.files.allObjects;
                tertiaryCount = tertiaryCollection.count;
                for (NSUInteger z = 0; z < tertiaryCount; z++) {
                    fileURL = [NSURL URLWithString:[(MLFile *)tertiaryCollection[z] url]];
                    BOOL exists = [fileManager fileExistsAtPath:[fileURL path]];
                    if (exists)
                        emptyAlbumCounter++;
822 823
                    else
                        [show removeEpisode:showEpisode];
824 825 826 827 828 829 830
                }
            }
            if (emptyAlbumCounter == 0)
                [[self managedObjectContext] deleteObject:show];
        }
    }

831 832 833 834 835
    /* remove duplicates */
    NSArray *allFiles = [MLFile allFiles];
    NSUInteger allFilesCount = allFiles.count;
    NSMutableArray *seenFiles = [[NSMutableArray alloc] initWithCapacity:allFilesCount];
    MLFile *currentFile;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
836 837
    NSString *currentFilePath;
    for (NSUInteger x = 0; x < allFilesCount; x++) {
838
        currentFile = allFiles[x];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
839 840
        currentFilePath = [currentFile.url stringByReplacingOccurrencesOfString:@"/localhost/" withString:@"//"];
        if ([seenFiles containsObject:currentFilePath])
841 842
            [[self managedObjectContext] deleteObject:currentFile];
        else
Felix Paul Kühne's avatar
Felix Paul Kühne committed
843
            [seenFiles addObject:currentFilePath];
844 845
    }

846
    [defaults setBool:YES forKey:kUpdatedToTheGreatSharkHuntDatabaseFormat];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
847 848 849
    [defaults synchronize];

    [self libraryDidAppear];
850 851 852 853
    if ([self.delegate respondsToSelector:@selector(libraryUpgradeComplete)])
        [self.delegate libraryUpgradeComplete];
}

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

862
    unsigned int count = (unsigned int)results.count;
863 864
    for (unsigned int x = 0; x < count; x++) {
        MLFile *file = results[x];
Pierre's avatar
Pierre committed
865 866
        NSString *urlString = [file url];
        NSURL *fileURL = [NSURL URLWithString:urlString];
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
                if (album.tracks.count <= 1) {
                    @try {
                        [[self managedObjectContext] deleteObject:album];
                    }
                    @catch (NSException *exception) {
                        APLog(@"failed to nuke object because it disappeared in front of us");
                    }
880
                } else
881
                    [album removeTrack:file.albumTrack];
882 883 884
            }
            if (file.isShowEpisode) {
                MLShow *show = file.showEpisode.show;
885 886 887 888 889 890 891
                if (show.episodes.count <= 1) {
                    @try {
                        [[self managedObjectContext] deleteObject:show];
                    }
                    @catch (NSException *exception) {
                        APLog(@"failed to nuke object because it disappeared in front of us");
                    }
892 893
                } else
                    [show removeEpisode:file.showEpisode];
894
            }
895
#if TARGET_OS_IPHONE
896
            NSString *thumbPath = [file thumbnailPath];
897 898
            bool thumbExists = [fileManager fileExistsAtPath:thumbPath];
            if (thumbExists)
899
                [fileManager removeItemAtPath:thumbPath error:nil];
900 901
            [[self managedObjectContext] deleteObject:file];
#endif
902
        }
903 904 905
#if !TARGET_OS_IPHONE
    file.isOnDisk = @(exists);
#endif
Pierre's avatar
Pierre committed
906
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
907
    [self libraryDidAppear];
Pierre's avatar
Pierre committed
908

909 910 911 912 913 914 915
    // Get the file to parse
    request = [self fetchRequestForEntity:@"File"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && tracks.@count == 0"]];
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
    for (MLFile *file in results)
        [[MLFileParserQueue sharedFileParserQueue] addFile:file];

916 917 918
    if (!_allowNetworkAccess) {
        // Always attempt to fetch
        request = [self fetchRequestForEntity:@"File"];
919
        [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES"]];
920
        results = [[self managedObjectContext] executeFetchRequest:request error:nil];
921 922 923 924
        for (MLFile *file in results) {
            if (!file.computedThumbnail)
                [self computeThumbnailForFile:file];
        }
925 926 927
        return;
    }

Pierre's avatar
Pierre committed
928 929
    // Get the thumbnails to compute
    request = [self fetchRequestForEntity:@"File"];
930
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && hasFetchedInfo == 1 && artworkURL == nil"]];
Pierre's avatar
Pierre committed
931 932
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
    for (MLFile *file in results)
933
        if (!file.computedThumbnail && ![file isAlbumTrack])
934
            [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
935 936 937 938 939 940

    // Get to fetch meta data
    request = [self fetchRequestForEntity:@"File"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && hasFetchedInfo == 0"]];
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
    for (MLFile *file in results)
Pierre's avatar
Pierre committed
941 942
        [self fetchMetaDataForFile:file];

Pierre's avatar
Pierre committed
943
    // Get to fetch show info
Pierre's avatar
Pierre committed
944 945 946
    request = [self fetchRequestForEntity:@"Show"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"lastSyncDate == 0"]];
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
947
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
948 949
        [self fetchMetaDataForShow:show];

Pierre's avatar
Pierre committed
950
    // Get updated TV Shows
951
    NSNumber *lastServerTime = @([[NSUserDefaults standardUserDefaults] integerForKey:kLastTVDBUpdateServerTime]);
Pierre's avatar
Pierre committed
952
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
953
    [MLTVShowInfoGrabber fetchUpdatesSinceServerTime:lastServerTime andExecuteBlock:^(NSArray *updates){
Pierre's avatar
Pierre committed
954 955 956
        NSFetchRequest *request = [self fetchRequestForEntity:@"Show"];
        [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
957
        for (MLShow *show in results)
Pierre's avatar
Pierre committed
958 959
            [self fetchMetaDataForShow:show];
    }];
Pierre's avatar
Pierre committed
960
#else
961
    MLTVShowInfoGrabber *grabber = [[MLTVShowInfoGrabber alloc] init];
Pierre's avatar
Pierre committed
962 963
    grabber.delegate = self;
    [grabber fetchUpdatesSinceServerTime:lastServerTime];
Pierre's avatar
Pierre committed
964
#endif
Pierre's avatar
Pierre committed
965
    /* Update every hour - FIXME: Preferences key */
966
    [self performSelector:@selector(updateMediaDatabase) withObject:nil afterDelay:60 * 60];
Pierre's avatar
Pierre committed
967
}
Pierre's avatar
Pierre committed
968

969 970 971 972 973
- (void)applicationWillExit
{
    [[MLCrashPreventer sharedPreventer] cancelAllFileParse];
}

Pierre's avatar
Pierre committed
974 975 976 977 978
- (void)applicationWillStart
{
    [[MLCrashPreventer sharedPreventer] markCrasherFiles];
}

Pierre's avatar
Pierre committed
979 980 981 982 983 984 985 986 987 988 989
- (void)libraryDidDisappear
{
    // Stop expansive work
    [[MLThumbnailerQueue sharedThumbnailerQueue] stop];
}

- (void)libraryDidAppear
{
    // Resume our work
    [[MLThumbnailerQueue sharedThumbnailerQueue] resume];
}
Pierre's avatar
Pierre committed
990
@end