MLMediaLibrary.m 25.5 KB
Newer Older
Pierre's avatar
Pierre committed
1 2 3 4 5 6 7 8 9
//
//  MLMediaLibrary.m
//  MobileMediaLibraryKit
//
//  Created by Pierre d'Herbemont on 7/14/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "MLMediaLibrary.h"
Pierre's avatar
Pierre committed
10 11
#import "MLTitleDecrapifier.h"
#import "MLMovieInfoGrabber.h"
Pierre's avatar
Pierre committed
12 13
#import "MLTVShowInfoGrabber.h"
#import "MLTVShowEpisodesInfoGrabber.h"
Pierre's avatar
Pierre committed
14 15 16 17 18
#import "MLFile.h"
#import "MLLabel.h"
#import "MLShowEpisode.h"
#import "MLThumbnailerQueue.h"
#import "MLShow.h"
19
#import "MLFileParserQueue.h"
20
#import "MLCrashPreventer.h"
Pierre's avatar
Pierre committed
21 22

#define DEBUG 1
23 24
// To debug
#define DELETE_LIBRARY_ON_EACH_LAUNCH 0
Pierre's avatar
Pierre committed
25

Pierre's avatar
Pierre committed
26 27
// Pref key
static NSString *kLastTVDBUpdateServerTime = @"MLLastTVDBUpdateServerTime";
Pierre's avatar
Pierre committed
28

Pierre's avatar
Pierre committed
29
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
30
@interface MLMediaLibrary ()
Pierre's avatar
Pierre committed
31 32 33
#else
@interface MLMediaLibrary () <MLMovieInfoGrabberDelegate, MLTVShowEpisodesInfoGrabberDelegate, MLTVShowInfoGrabberDelegate>
#endif
Pierre's avatar
Pierre committed
34
- (NSManagedObjectContext *)managedObjectContext;
35
- (void)startUpdateDB;
Pierre's avatar
Pierre committed
36
- (NSString *)databaseFolderPath;
Pierre's avatar
Pierre committed
37 38
@end

Pierre's avatar
Pierre committed
39 40 41 42
@implementation MLMediaLibrary
+ (id)sharedMediaLibrary
{
    static id sharedMediaLibrary = nil;
Pierre's avatar
Pierre committed
43
    if (!sharedMediaLibrary) {
Pierre's avatar
Pierre committed
44
        sharedMediaLibrary = [[[self class] alloc] init];
45
        APLog(@"Initializing db in %@", [sharedMediaLibrary databaseFolderPath]);
46 47 48 49

        // 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
50
    }
Pierre's avatar
Pierre committed
51 52 53 54 55 56 57 58
    return sharedMediaLibrary;
}

- (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
59
    NSAssert(entityDescription, @"No entity");
Pierre's avatar
Pierre committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    [request setEntity:entityDescription];
    return [request autorelease];
}

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

#pragma mark -
#pragma mark Media Library
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel)
        return _managedObjectModel;
    _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
    return _managedObjectModel;
}

Pierre's avatar
Pierre committed
80
- (NSString *)databaseFolderPath
Pierre's avatar
Pierre committed
81
{
Pierre's avatar
Pierre committed
82 83 84
    int directory = NSLibraryDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    NSString *directoryPath = [paths objectAtIndex:0];
85
#if DELETE_LIBRARY_ON_EACH_LAUNCH
Pierre's avatar
Pierre committed
86
    [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
87
#endif
Pierre's avatar
Pierre committed
88
    return directoryPath;
Pierre's avatar
Pierre committed
89 90
}

Pierre's avatar
Pierre committed
91 92 93 94 95 96 97 98 99 100 101 102

- (NSString *)thumbnailFolderPath
{
    int directory = NSLibraryDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    NSString *directoryPath = [paths objectAtIndex:0];
#if DELETE_LIBRARY_ON_EACH_LAUNCH
    [[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
#endif
    return [directoryPath stringByAppendingPathComponent:@"Thumbnails"];
}

Pierre's avatar
Pierre committed
103 104 105 106 107
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext)
        return _managedObjectContext;

Pierre's avatar
Pierre committed
108
    NSString *databaseFolderPath = [self databaseFolderPath];
Pierre's avatar
Pierre committed
109

Pierre's avatar
Pierre committed
110 111
    NSString *path = [databaseFolderPath stringByAppendingPathComponent: @"MediaLibrary.sqlite"];
    NSURL *url = [NSURL fileURLWithPath:path];
Pierre's avatar
Pierre committed
112 113
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

Pierre's avatar
Pierre committed
114
    NSNumber *yes = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
115
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
Pierre's avatar
Pierre committed
116 117
                             yes, NSMigratePersistentStoresAutomaticallyOption,
                             yes, NSInferMappingModelAutomaticallyOption, nil];
Pierre's avatar
Pierre committed
118 119

    NSError *error;
Pierre's avatar
Pierre committed
120 121 122
    NSPersistentStore *persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:&error];

    if (!persistentStore) {
Pierre's avatar
Pierre committed
123
#if! TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
124 125 126 127
        // 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];
Pierre's avatar
Pierre committed
128
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
Pierre's avatar
Pierre committed
129
#else
Pierre's avatar
Pierre committed
130
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
Pierre's avatar
Pierre committed
131
#endif
Pierre's avatar
Pierre committed
132 133
        persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:&error];
        if (!persistentStore) {
134 135
            if (coordinator)
                [coordinator release];
Pierre's avatar
Pierre committed
136 137 138 139 140
#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];
141
            [alert autorelease];
Pierre's avatar
Pierre committed
142 143 144 145
#endif
            // Probably assert instead.
            return nil;
        }
Pierre's avatar
Pierre committed
146
    }
Pierre's avatar
Pierre committed
147 148 149

    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
Pierre's avatar
Pierre committed
150 151 152 153 154 155 156 157 158
    [coordinator release];
    [_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
159 160 161
    NSError *error = nil;
    BOOL success = [[self managedObjectContext] save:&error];
    NSAssert1(success, @"Can't save: %@", error);
Pierre's avatar
Pierre committed
162
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
163 164 165 166 167 168
    NSProcessInfo *process = [NSProcessInfo processInfo];
    if ([process respondsToSelector:@selector(enableSuddenTermination)])
        [process enableSuddenTermination];
#endif
}

Pierre's avatar
Pierre committed
169
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Pierre's avatar
Pierre committed
170 171
{
    if ([keyPath isEqualToString:@"hasChanges"] && object == _managedObjectContext) {
Pierre's avatar
Pierre committed
172
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
173 174 175 176 177
        NSProcessInfo *process = [NSProcessInfo processInfo];
        if ([process respondsToSelector:@selector(disableSuddenTermination)])
            [process disableSuddenTermination];
#endif

Pierre's avatar
Pierre committed
178 179 180 181
        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
182 183 184 185 186
        return;
    }
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

Pierre's avatar
Pierre committed
187 188
#pragma mark -
#pragma mark No meta data fallbacks
Pierre's avatar
Pierre committed
189

Pierre's avatar
Pierre committed
190
- (void)computeThumbnailForFile:(MLFile *)file
Pierre's avatar
Pierre committed
191
{
Pierre's avatar
Pierre committed
192
    if (!file.computedThumbnail) {
193
        APLog(@"Computing thumbnail for %@", file.title);
Pierre's avatar
Pierre committed
194 195
        [[MLThumbnailerQueue sharedThumbnailerQueue] addFile:file];
    }
Pierre's avatar
Pierre committed
196
}
Pierre's avatar
Pierre committed
197
- (void)errorWhenFetchingMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
198
{
199
    APLog(@"Error when fetching for '%@'", file.title);
Pierre's avatar
Pierre committed
200

Pierre's avatar
Pierre committed
201 202
    [self computeThumbnailForFile:file];
}
Pierre's avatar
Pierre committed
203

Pierre's avatar
Pierre committed
204 205 206 207 208 209 210
- (void)errorWhenFetchingMetaDataForShow:(MLShow *)show
{
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self errorWhenFetchingMetaDataForFile:file];
    }
}
Pierre's avatar
Pierre committed
211

Pierre's avatar
Pierre committed
212 213 214 215
- (void)noMetaDataInRemoteDBForFile:(MLFile *)file
{
    file.noOnlineMetaData = [NSNumber numberWithBool:YES];
    [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
216 217
}

Pierre's avatar
Pierre committed
218
- (void)noMetaDataInRemoteDBForShow:(MLShow *)show
Pierre's avatar
Pierre committed
219
{
Pierre's avatar
Pierre committed
220 221 222
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self noMetaDataInRemoteDBForFile:file];
Pierre's avatar
Pierre committed
223 224 225
    }
}

Pierre's avatar
Pierre committed
226 227 228 229
#pragma mark -
#pragma mark Getter

- (void)addNewLabelWithName:(NSString *)name
Pierre's avatar
Pierre committed
230
{
Pierre's avatar
Pierre committed
231 232
    MLLabel *label = [self createObjectForEntity:@"Label"];
    label.name = name;
Pierre's avatar
Pierre committed
233 234
}

Pierre's avatar
Pierre committed
235 236 237 238 239 240 241
/**
 * TV MLShow Episodes
 */

#pragma mark -
#pragma mark Online meta data grabbing

Pierre's avatar
Pierre committed
242 243 244
#if !HAVE_BLOCK
- (void)tvShowEpisodesInfoGrabberDidFinishGrabbing:(MLTVShowEpisodesInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
245
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
246 247 248 249 250 251 252

    NSArray *results = grabber.episodesResults;
    [show setValue:[grabber.results objectForKey:@"serieArtworkURL"] forKey:@"artworkURL"];
    for (id result in results) {
        if ([[result objectForKey:@"serie"] boolValue]) {
            continue;
        }
Pierre's avatar
Pierre committed
253
        MLShowEpisode *showEpisode = [MLShowEpisode episodeWithShow:show episodeNumber:[result objectForKey:@"episodeNumber"] seasonNumber:[result objectForKey:@"seasonNumber"] createIfNeeded:YES];
Pierre's avatar
Pierre committed
254 255 256 257
        showEpisode.name = [result objectForKey:@"title"];
        showEpisode.theTVDBID = [result objectForKey:@"id"];
        showEpisode.shortSummary = [result objectForKey:@"shortSummary"];
        showEpisode.artworkURL = [result objectForKey:@"artworkURL"];
Pierre's avatar
Pierre committed
258 259 260 261 262
        if (!showEpisode.artworkURL) {
            for (MLFile *file in showEpisode.files)
                [self computeThumbnailForFile:file];
        }

Pierre's avatar
Pierre committed
263 264 265 266 267
        showEpisode.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
    show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
}

Pierre's avatar
Pierre committed
268 269 270 271 272 273 274 275 276 277 278
- (void)save
{
    [[self managedObjectContext] save:nil];
}

- (void)tvShowEpisodesInfoGrabber:(MLTVShowEpisodesInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
279 280
- (void)tvShowInfoGrabberDidFinishGrabbing:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
281
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    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"];

        // Fetch episodes info
        MLTVShowEpisodesInfoGrabber *grabber = [[[MLTVShowEpisodesInfoGrabber alloc] init] autorelease];
        grabber.delegate = self;
        grabber.userData = show;
        [grabber lookUpForShowID:showId];
    }
    else {
        // Not found.
Pierre's avatar
Pierre committed
300
        [self noMetaDataInRemoteDBForShow:show];
Pierre's avatar
Pierre committed
301 302 303 304
        show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
}

Pierre's avatar
Pierre committed
305 306 307 308 309 310
- (void)tvShowInfoGrabber:(MLTVShowInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
311 312
- (void)tvShowInfoGrabberDidFetchServerTime:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
313
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
314 315 316

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

Pierre's avatar
Pierre committed
317
    // First fetch the MLShow ID
Pierre's avatar
Pierre committed
318 319 320 321
    MLTVShowInfoGrabber *showInfoGrabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
    showInfoGrabber.delegate = self;
    showInfoGrabber.userData = show;

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

Pierre's avatar
Pierre committed
324 325 326 327
    [showInfoGrabber lookUpForTitle:show.name];
}
#endif

Pierre's avatar
Pierre committed
328
- (void)fetchMetaDataForShow:(MLShow *)show
Pierre's avatar
Pierre committed
329
{
Pierre's avatar
Pierre committed
330 331
    if (!_allowNetworkAccess)
        return;
332
    APLog(@"Fetching show server time");
Pierre's avatar
Pierre committed
333

Pierre's avatar
Pierre committed
334
    // First fetch the serverTime, so that we can update each entry.
Pierre's avatar
Pierre committed
335 336
#if HAVE_BLOCK
    [MLTVShowInfoGrabber fetchServerTimeAndExecuteBlock:^(NSNumber *serverDate) {
Pierre's avatar
Pierre committed
337 338 339

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

340
        APLog(@"Fetching show information on %@", show.name);
Pierre's avatar
Pierre committed
341 342 343

        // First fetch the MLShow ID
        MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
344 345 346 347 348 349 350 351 352 353 354
        [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"];

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

Pierre's avatar
Pierre committed
357
                // Fetch episode info
Pierre's avatar
Pierre committed
358
                MLTVShowEpisodesInfoGrabber *grabber = [[[MLTVShowEpisodesInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
359 360 361 362 363 364 365
                [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;
                        }
Pierre's avatar
Pierre committed
366
                        MLShowEpisode *showEpisode = [self showEpisodeWithShow:show episodeNumber:[result objectForKey:@"episodeNumber"] seasonNumber:[result objectForKey:@"seasonNumber"]];
Pierre's avatar
Pierre committed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
                        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
383
#else
Pierre's avatar
Pierre committed
384 385 386 387
    MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
    grabber.delegate = self;
    grabber.userData = show;
    [grabber fetchServerTime];
Pierre's avatar
Pierre committed
388
#endif
Pierre's avatar
Pierre committed
389 390
}

Pierre's avatar
Pierre committed
391
- (void)addTVShowEpisodeWithInfo:(NSDictionary *)tvShowEpisodeInfo andFile:(MLFile *)file
Pierre's avatar
Pierre committed
392
{
Pierre's avatar
Pierre committed
393
    file.type = kMLFileTypeTVShowEpisode;
Pierre's avatar
Pierre committed
394 395 396 397 398 399

    NSNumber *seasonNumber = [tvShowEpisodeInfo objectForKey:@"season"];
    NSNumber *episodeNumber = [tvShowEpisodeInfo objectForKey:@"episode"];
    NSString *tvShowName = [tvShowEpisodeInfo objectForKey:@"tvShowName"];
    BOOL hasNoTvShow = NO;
    if (!tvShowName) {
Pierre's avatar
Pierre committed
400
        tvShowName = @"Untitled TV MLShow";
Pierre's avatar
Pierre committed
401 402 403
        hasNoTvShow = YES;
    }
    BOOL wasInserted = NO;
Pierre's avatar
Pierre committed
404 405 406 407
    MLShow *show = nil;
    MLShowEpisode *episode = [MLShowEpisode episodeWithShowName:tvShowName episodeNumber:episodeNumber seasonNumber:seasonNumber createIfNeeded:YES wasCreated:&wasInserted];
    if (episode)
        show = episode.show;
Pierre's avatar
Pierre committed
408 409 410 411 412 413 414 415 416 417 418 419
    if (wasInserted && !hasNoTvShow) {
        show.name = tvShowName;
        [self fetchMetaDataForShow:show];
    }

    if (hasNoTvShow)
        episode.name = file.title;
    file.seasonNumber = seasonNumber;
    file.episodeNumber = episodeNumber;
    episode.shouldBeDisplayed = [NSNumber numberWithBool:YES];

    [episode addFilesObject:file];
Pierre's avatar
Pierre committed
420
    file.showEpisode = episode;
Pierre's avatar
Pierre committed
421

Pierre's avatar
Pierre committed
422
    // The rest of the meta data will be fetched using the MLShow
Pierre's avatar
Pierre committed
423
    file.hasFetchedInfo = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
424 425 426 427
}


/**
Pierre's avatar
Pierre committed
428
 * MLFile auto detection
Pierre's avatar
Pierre committed
429 430
 */

Pierre's avatar
Pierre committed
431

Pierre's avatar
Pierre committed
432
#if !HAVE_BLOCK
Pierre's avatar
Pierre committed
433 434 435 436 437 438
- (void)movieInfoGrabber:(MLMovieInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLFile *file = grabber.userData;
    [self errorWhenFetchingMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
439 440 441 442 443
- (void)movieInfoGrabberDidFinishGrabbing:(MLMovieInfoGrabber *)grabber
{
    NSNumber *yes = [NSNumber numberWithBool:YES];

    NSArray *results = grabber.results;
Pierre's avatar
Pierre committed
444
    MLFile *file = grabber.userData;
Pierre's avatar
Pierre committed
445 446 447 448 449 450 451
    if ([results count] > 0) {
        NSDictionary *result = [results objectAtIndex:0];
        file.artworkURL = [result objectForKey:@"artworkURL"];
        file.title = [result objectForKey:@"title"];
        file.shortSummary = [result objectForKey:@"shortSummary"];
        file.releaseYear = [result objectForKey:@"releaseYear"];
    }
Pierre's avatar
Pierre committed
452 453 454 455
    else {
        [self noMetaDataInRemoteDBForFile:file];
    }

Pierre's avatar
Pierre committed
456 457 458 459
    file.hasFetchedInfo = yes;
}
#endif

Pierre's avatar
Pierre committed
460
- (void)fetchMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
461
{
462
    APLog(@"Fetching meta data for %@", file.title);
Pierre's avatar
Pierre committed
463

464
    [[MLFileParserQueue sharedFileParserQueue] addFile:file];
465

Pierre's avatar
Pierre committed
466 467 468 469 470
    if (!_allowNetworkAccess) {
        // Automatically compute the thumbnail
        [self computeThumbnailForFile:file];
    }

Pierre's avatar
Pierre committed
471
    NSDictionary *tvShowEpisodeInfo = [MLTitleDecrapifier tvShowEpisodeInfoFromString:file.title];
Pierre's avatar
Pierre committed
472 473 474 475 476
    if (tvShowEpisodeInfo) {
        [self addTVShowEpisodeWithInfo:tvShowEpisodeInfo andFile:file];
        return;
    }

Pierre's avatar
Pierre committed
477 478 479
    if (!_allowNetworkAccess)
        return;

Pierre's avatar
Pierre committed
480
    // Go online and fetch info.
Pierre's avatar
Pierre committed
481 482 483

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

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

Pierre's avatar
Pierre committed
488
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
489
    [grabber lookUpForTitle:file.title andExecuteBlock:^(NSError *err){
Pierre's avatar
Pierre committed
490 491
        if (err) {
            [self errorWhenFetchingMetaDataForFile:file];
Pierre's avatar
Pierre committed
492
            return;
Pierre's avatar
Pierre committed
493
        }
Pierre's avatar
Pierre committed
494 495 496 497 498

        NSArray *results = grabber.results;
        if ([results count] > 0) {
            NSDictionary *result = [results objectAtIndex:0];
            file.artworkURL = [result objectForKey:@"artworkURL"];
Pierre's avatar
Pierre committed
499 500
            if (!file.artworkURL)
                [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
501 502 503
            file.title = [result objectForKey:@"title"];
            file.shortSummary = [result objectForKey:@"shortSummary"];
            file.releaseYear = [result objectForKey:@"releaseYear"];
Pierre's avatar
Pierre committed
504 505 506
        } else
            [self noMetaDataInRemoteDBForFile:file];
        file.hasFetchedInfo = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
507
    }];
Pierre's avatar
Pierre committed
508
#else
Pierre's avatar
Pierre committed
509 510 511
    grabber.userData = file;
    grabber.delegate = self;
    [grabber lookUpForTitle:file.title];
Pierre's avatar
Pierre committed
512
#endif
Pierre's avatar
Pierre committed
513 514
}

Pierre's avatar
Pierre committed
515 516 517
#pragma mark -
#pragma mark Adding file to the DB

Pierre's avatar
Pierre committed
518
- (void)addFilePath:(NSString *)filePath
Pierre's avatar
Pierre committed
519
{
520
    APLog(@"Adding Path %@", filePath);
Pierre's avatar
Pierre committed
521

Pierre's avatar
Pierre committed
522
    NSURL *url = [NSURL fileURLWithPath:filePath];
Pierre's avatar
Pierre committed
523 524
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSString *title = [filePath lastPathComponent];
Pierre's avatar
Pierre committed
525
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
526 527
    NSDate *openedDate = nil; // FIXME kMDItemLastUsedDate
    NSDate *modifiedDate = nil; // FIXME [result valueForAttribute:@"kMDItemFSContentChangeDate"];
Pierre's avatar
Pierre committed
528
#endif
Pierre's avatar
Pierre committed
529
    NSNumber *size = [attributes objectForKey:NSFileSize]; // FIXME [result valueForAttribute:@"kMDItemFSSize"];
Pierre's avatar
Pierre committed
530

Pierre's avatar
Pierre committed
531
    MLFile *file = [self createObjectForEntity:@"File"];
Pierre's avatar
Pierre committed
532
    file.url = [url absoluteString];
Pierre's avatar
Pierre committed
533 534 535 536 537 538 539 540 541 542 543 544

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

    NSNumber *no = [NSNumber numberWithBool:NO];
    NSNumber *yes = [NSNumber numberWithBool:YES];

    file.currentlyWatching = no;
    file.lastPosition = [NSNumber numberWithDouble:0];
    file.remainingTime = [NSNumber numberWithDouble:0];
    file.unread = yes;

Pierre's avatar
Pierre committed
545
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
546 547 548 549
    if ([openedDate isGreaterThan:modifiedDate]) {
        file.playCount = [NSNumber numberWithDouble:1];
        file.unread = no;
    }
Pierre's avatar
Pierre committed
550 551
#endif

Pierre's avatar
Pierre committed
552
    file.title = [MLTitleDecrapifier decrapify:[title stringByDeletingPathExtension]];
Pierre's avatar
Pierre committed
553 554

    if ([size longLongValue] < 150000000) /* 150 MB */
Pierre's avatar
Pierre committed
555
        file.type = kMLFileTypeClip;
Pierre's avatar
Pierre committed
556
    else
Pierre's avatar
Pierre committed
557
        file.type = kMLFileTypeMovie;
Pierre's avatar
Pierre committed
558 559 560 561

    [self fetchMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
562
- (void)addFilePaths:(NSArray *)filepaths
Pierre's avatar
Pierre committed
563
{
Pierre's avatar
Pierre committed
564
    NSUInteger count = [filepaths count];
Pierre's avatar
Pierre committed
565 566 567 568
    NSMutableArray *fetchPredicates = [NSMutableArray arrayWithCapacity:count];
    NSMutableDictionary *urlToObject = [NSMutableDictionary dictionaryWithCapacity:count];

    // Prepare a fetch request for all items
Pierre's avatar
Pierre committed
569
    for (NSString *path in filepaths) {
Pierre's avatar
Pierre committed
570
        NSURL *url = [NSURL fileURLWithPath:path];
Pierre's avatar
Pierre committed
571 572 573 574
        NSString *urlString = [url absoluteString];
        [fetchPredicates addObject:[NSPredicate predicateWithFormat:@"url == %@", urlString]];
        [urlToObject setObject:path forKey:urlString];

Pierre's avatar
Pierre committed
575 576 577 578 579 580
    }

    NSFetchRequest *request = [self fetchRequestForEntity:@"File"];

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

581
    APLog(@"Fetching");
Pierre's avatar
Pierre committed
582
    NSArray *dbResults = [[self managedObjectContext] executeFetchRequest:request error:nil];
583
    APLog(@"Done");
Pierre's avatar
Pierre committed
584

Pierre's avatar
Pierre committed
585
    NSMutableArray *filePathsToAdd = [NSMutableArray arrayWithArray:filepaths];
Pierre's avatar
Pierre committed
586

Pierre's avatar
Pierre committed
587

Pierre's avatar
Pierre committed
588
    // Remove objects that are already in db.
Pierre's avatar
Pierre committed
589 590
    for (MLFile *dbResult in dbResults) {
        NSString *urlString = dbResult.url;
Pierre's avatar
Pierre committed
591
        [filePathsToAdd removeObject:[urlToObject objectForKey:urlString]];
Pierre's avatar
Pierre committed
592 593 594
    }

    // Add only the newly added items
Pierre's avatar
Pierre committed
595 596
    for (NSString* path in filePathsToAdd)
        [self addFilePath:path];
Pierre's avatar
Pierre committed
597 598
}

Pierre's avatar
Pierre committed
599 600 601 602

#pragma mark -
#pragma mark DB Updates

Pierre's avatar
Pierre committed
603 604 605 606 607 608
#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
609
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
610 611 612 613
        [self fetchMetaDataForShow:show];
}
#endif

614 615 616 617 618
- (void)updateMediaDatabase
{
    [self startUpdateDB];
}

619
- (void)startUpdateDB
Pierre's avatar
Pierre committed
620
{
Pierre's avatar
Pierre committed
621
    // Remove no more present files
Pierre's avatar
Pierre committed
622 623
    NSFetchRequest *request = [self fetchRequestForEntity:@"File"];
    NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
624
    NSFileManager *fileManager = [NSFileManager defaultManager];
625

Pierre's avatar
Pierre committed
626 627 628
    for (MLFile *file in results) {
        NSString *urlString = [file url];
        NSURL *fileURL = [NSURL URLWithString:urlString];
629
        BOOL exists = [fileManager fileExistsAtPath:[fileURL path]];
630
        if (!exists) {
631
            APLog(@"Marking - %@", [fileURL absoluteString]);
632 633
            file.isSafe = YES; // It doesn't exists, it's safe.
        }
Pierre's avatar
Pierre committed
634 635
        file.isOnDisk = [NSNumber numberWithBool:exists];
    }
Pierre's avatar
Pierre committed
636

637 638 639 640 641 642 643
    // 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];

Pierre's avatar
Pierre committed
644 645 646
    if (!_allowNetworkAccess) {
        // Always attempt to fetch
        request = [self fetchRequestForEntity:@"File"];
Pierre's avatar
Pierre committed
647
        [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES"]];
Pierre's avatar
Pierre committed
648
        results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
649 650 651 652
        for (MLFile *file in results) {
            if (!file.computedThumbnail)
                [self computeThumbnailForFile:file];
        }
Pierre's avatar
Pierre committed
653 654 655
        return;
    }

Pierre's avatar
Pierre committed
656 657
    // Get the thumbnails to compute
    request = [self fetchRequestForEntity:@"File"];
Pierre's avatar
Pierre committed
658
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && hasFetchedInfo == 1 && artworkURL == nil"]];
Pierre's avatar
Pierre committed
659 660
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
    for (MLFile *file in results)
Pierre's avatar
Pierre committed
661 662
        if (!file.computedThumbnail)
            [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
663

Pierre's avatar
Pierre committed
664

Pierre's avatar
Pierre committed
665 666 667 668 669
    // 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
670 671
        [self fetchMetaDataForFile:file];

Pierre's avatar
Pierre committed
672
    // Get to fetch show info
Pierre's avatar
Pierre committed
673 674 675
    request = [self fetchRequestForEntity:@"Show"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"lastSyncDate == 0"]];
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
676
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
677 678
        [self fetchMetaDataForShow:show];

Pierre's avatar
Pierre committed
679
    // Get updated TV Shows
Pierre's avatar
Pierre committed
680
    NSNumber *lastServerTime = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:kLastTVDBUpdateServerTime]];
Pierre's avatar
Pierre committed
681
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
682
    [MLTVShowInfoGrabber fetchUpdatesSinceServerTime:lastServerTime andExecuteBlock:^(NSArray *updates){
Pierre's avatar
Pierre committed
683 684 685
        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
686
        for (MLShow *show in results)
Pierre's avatar
Pierre committed
687 688
            [self fetchMetaDataForShow:show];
    }];
Pierre's avatar
Pierre committed
689 690 691 692
#else
    MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
    grabber.delegate = self;
    [grabber fetchUpdatesSinceServerTime:lastServerTime];
Pierre's avatar
Pierre committed
693
#endif
Pierre's avatar
Pierre committed
694
    /* Update every hour - FIXME: Preferences key */
695
    [self performSelector:@selector(startUpdateDB) withObject:nil afterDelay:60 * 60];
Pierre's avatar
Pierre committed
696
}
Pierre's avatar
Pierre committed
697

698 699 700 701 702
- (void)applicationWillExit
{
    [[MLCrashPreventer sharedPreventer] cancelAllFileParse];
}

Pierre's avatar
Pierre committed
703 704 705 706 707
- (void)applicationWillStart
{
    [[MLCrashPreventer sharedPreventer] markCrasherFiles];
}

Pierre's avatar
Pierre committed
708 709 710 711 712 713 714 715 716 717 718
- (void)libraryDidDisappear
{
    // Stop expansive work
    [[MLThumbnailerQueue sharedThumbnailerQueue] stop];
}

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