MLMediaLibrary.m 23.8 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"
Pierre's avatar
Pierre committed
20 21 22 23 24 25 26 27

#define DEBUG 1

#ifdef TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif

#define MLLog(...) NSLog(__VA_ARGS__)
Pierre's avatar
Pierre committed
28

Pierre's avatar
Pierre committed
29 30
// Pref key
static NSString *kLastTVDBUpdateServerTime = @"MLLastTVDBUpdateServerTime";
Pierre's avatar
Pierre committed
31

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

Pierre's avatar
Pierre committed
42 43 44 45
@implementation MLMediaLibrary
+ (id)sharedMediaLibrary
{
    static id sharedMediaLibrary = nil;
Pierre's avatar
Pierre committed
46
    if (!sharedMediaLibrary) {
Pierre's avatar
Pierre committed
47
        sharedMediaLibrary = [[[self class] alloc] init];
Pierre's avatar
Pierre committed
48
        NSLog(@"Initializing db in %@", [sharedMediaLibrary databaseFolderPath]);
Pierre's avatar
Pierre committed
49 50
        [sharedMediaLibrary startUpdateDB];
    }
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 85
    int directory = NSLibraryDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    NSString *directoryPath = [paths objectAtIndex:0];
    return directoryPath;
Pierre's avatar
Pierre committed
86 87 88 89 90 91 92
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext)
        return _managedObjectContext;

Pierre's avatar
Pierre committed
93
    NSString *databaseFolderPath = [self databaseFolderPath];
Pierre's avatar
Pierre committed
94

Pierre's avatar
Pierre committed
95 96
    NSString *path = [databaseFolderPath stringByAppendingPathComponent: @"MediaLibrary.sqlite"];
    NSURL *url = [NSURL fileURLWithPath:path];
Pierre's avatar
Pierre committed
97 98
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

Pierre's avatar
Pierre committed
99
    NSNumber *yes = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
100
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
Pierre's avatar
Pierre committed
101 102
                             yes, NSMigratePersistentStoresAutomaticallyOption,
                             yes, NSInferMappingModelAutomaticallyOption, nil];
Pierre's avatar
Pierre committed
103 104

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

    if (!persistentStore) {
Pierre's avatar
Pierre committed
108
#if! TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
109 110 111 112
        // 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
113
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
Pierre's avatar
Pierre committed
114
#else
Pierre's avatar
Pierre committed
115
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
Pierre's avatar
Pierre committed
116
#endif
Pierre's avatar
Pierre committed
117 118 119 120 121 122 123 124 125 126 127
        persistentStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:&error];
        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
128
    }
Pierre's avatar
Pierre committed
129 130 131

    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
Pierre's avatar
Pierre committed
132 133 134 135 136 137 138 139 140
    [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
141 142 143
    NSError *error = nil;
    BOOL success = [[self managedObjectContext] save:&error];
    NSAssert1(success, @"Can't save: %@", error);
Pierre's avatar
Pierre committed
144
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
145 146 147 148 149 150
    NSProcessInfo *process = [NSProcessInfo processInfo];
    if ([process respondsToSelector:@selector(enableSuddenTermination)])
        [process enableSuddenTermination];
#endif
}

Pierre's avatar
Pierre committed
151
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
Pierre's avatar
Pierre committed
152 153
{
    if ([keyPath isEqualToString:@"hasChanges"] && object == _managedObjectContext) {
Pierre's avatar
Pierre committed
154
#if !TARGET_OS_IPHONE && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Pierre's avatar
Pierre committed
155 156 157 158 159
        NSProcessInfo *process = [NSProcessInfo processInfo];
        if ([process respondsToSelector:@selector(disableSuddenTermination)])
            [process disableSuddenTermination];
#endif

Pierre's avatar
Pierre committed
160 161 162 163
        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
164 165 166 167 168
        return;
    }
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

Pierre's avatar
Pierre committed
169 170
#pragma mark -
#pragma mark No meta data fallbacks
Pierre's avatar
Pierre committed
171

Pierre's avatar
Pierre committed
172
- (void)computeThumbnailForFile:(MLFile *)file
Pierre's avatar
Pierre committed
173
{
Pierre's avatar
Pierre committed
174 175 176 177
    if (!file.computedThumbnail) {
        MLLog(@"Computing thumbnail for %@", file.title);
        [[MLThumbnailerQueue sharedThumbnailerQueue] addFile:file];
    }
Pierre's avatar
Pierre committed
178
}
Pierre's avatar
Pierre committed
179
- (void)errorWhenFetchingMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
180
{
Pierre's avatar
Pierre committed
181
    MLLog(@"Error when fetching for '%@'", file.title);
Pierre's avatar
Pierre committed
182

Pierre's avatar
Pierre committed
183 184
    [self computeThumbnailForFile:file];
}
Pierre's avatar
Pierre committed
185

Pierre's avatar
Pierre committed
186 187 188 189 190 191 192
- (void)errorWhenFetchingMetaDataForShow:(MLShow *)show
{
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self errorWhenFetchingMetaDataForFile:file];
    }
}
Pierre's avatar
Pierre committed
193

Pierre's avatar
Pierre committed
194 195 196 197
- (void)noMetaDataInRemoteDBForFile:(MLFile *)file
{
    file.noOnlineMetaData = [NSNumber numberWithBool:YES];
    [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
198 199
}

Pierre's avatar
Pierre committed
200
- (void)noMetaDataInRemoteDBForShow:(MLShow *)show
Pierre's avatar
Pierre committed
201
{
Pierre's avatar
Pierre committed
202 203 204
    for (MLShowEpisode *episode in show.episodes) {
        for (MLFile *file in episode.files)
            [self noMetaDataInRemoteDBForFile:file];
Pierre's avatar
Pierre committed
205 206 207
    }
}

Pierre's avatar
Pierre committed
208 209 210 211
#pragma mark -
#pragma mark Getter

- (void)addNewLabelWithName:(NSString *)name
Pierre's avatar
Pierre committed
212
{
Pierre's avatar
Pierre committed
213 214
    MLLabel *label = [self createObjectForEntity:@"Label"];
    label.name = name;
Pierre's avatar
Pierre committed
215 216
}

Pierre's avatar
Pierre committed
217 218 219 220 221 222 223
/**
 * TV MLShow Episodes
 */

#pragma mark -
#pragma mark Online meta data grabbing

Pierre's avatar
Pierre committed
224 225 226
#if !HAVE_BLOCK
- (void)tvShowEpisodesInfoGrabberDidFinishGrabbing:(MLTVShowEpisodesInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
227
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
228 229 230 231 232 233 234

    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
235
        MLShowEpisode *showEpisode = [MLShowEpisode episodeWithShow:show episodeNumber:[result objectForKey:@"episodeNumber"] seasonNumber:[result objectForKey:@"seasonNumber"] createIfNeeded:YES];
Pierre's avatar
Pierre committed
236 237 238 239
        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
240 241 242 243 244
        if (!showEpisode.artworkURL) {
            for (MLFile *file in showEpisode.files)
                [self computeThumbnailForFile:file];
        }

Pierre's avatar
Pierre committed
245 246 247 248 249
        showEpisode.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
    show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
}

Pierre's avatar
Pierre committed
250 251 252 253 254 255 256 257 258 259 260
- (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
261 262
- (void)tvShowInfoGrabberDidFinishGrabbing:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
263
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    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
282
        [self noMetaDataInRemoteDBForShow:show];
Pierre's avatar
Pierre committed
283 284 285 286
        show.lastSyncDate = [MLTVShowInfoGrabber serverTime];
    }
}

Pierre's avatar
Pierre committed
287 288 289 290 291 292
- (void)tvShowInfoGrabber:(MLTVShowInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLShow *show = grabber.userData;
    [self errorWhenFetchingMetaDataForShow:show];
}

Pierre's avatar
Pierre committed
293 294
- (void)tvShowInfoGrabberDidFetchServerTime:(MLTVShowInfoGrabber *)grabber
{
Pierre's avatar
Pierre committed
295
    MLShow *show = grabber.userData;
Pierre's avatar
Pierre committed
296 297 298

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

Pierre's avatar
Pierre committed
299
    // First fetch the MLShow ID
Pierre's avatar
Pierre committed
300 301 302 303
    MLTVShowInfoGrabber *showInfoGrabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
    showInfoGrabber.delegate = self;
    showInfoGrabber.userData = show;

Pierre's avatar
Pierre committed
304 305
    MLLog(@"Fetching show information on %@", show.name);

Pierre's avatar
Pierre committed
306 307 308 309
    [showInfoGrabber lookUpForTitle:show.name];
}
#endif

Pierre's avatar
Pierre committed
310
- (void)fetchMetaDataForShow:(MLShow *)show
Pierre's avatar
Pierre committed
311
{
Pierre's avatar
Pierre committed
312 313
    MLLog(@"Fetching show server time");

Pierre's avatar
Pierre committed
314
    // First fetch the serverTime, so that we can update each entry.
Pierre's avatar
Pierre committed
315 316
#if HAVE_BLOCK
    [MLTVShowInfoGrabber fetchServerTimeAndExecuteBlock:^(NSNumber *serverDate) {
Pierre's avatar
Pierre committed
317 318 319

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

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

        // First fetch the MLShow ID
        MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
324 325 326 327 328 329 330 331 332 333 334
        [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"];

Pierre's avatar
Pierre committed
335 336
                MLLog(@"Fetching show episode information on %@", showId);

Pierre's avatar
Pierre committed
337
                // Fetch episode info
Pierre's avatar
Pierre committed
338
                MLTVShowEpisodesInfoGrabber *grabber = [[[MLTVShowEpisodesInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
339 340 341 342 343 344 345
                [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
346
                        MLShowEpisode *showEpisode = [self showEpisodeWithShow:show episodeNumber:[result objectForKey:@"episodeNumber"] seasonNumber:[result objectForKey:@"seasonNumber"]];
Pierre's avatar
Pierre committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
                        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
363
#else
Pierre's avatar
Pierre committed
364 365 366 367
    MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
    grabber.delegate = self;
    grabber.userData = show;
    [grabber fetchServerTime];
Pierre's avatar
Pierre committed
368
#endif
Pierre's avatar
Pierre committed
369 370
}

Pierre's avatar
Pierre committed
371
- (void)addTVShowEpisodeWithInfo:(NSDictionary *)tvShowEpisodeInfo andFile:(MLFile *)file
Pierre's avatar
Pierre committed
372
{
Pierre's avatar
Pierre committed
373
    file.type = kMLFileTypeTVShowEpisode;
Pierre's avatar
Pierre committed
374 375 376 377 378 379

    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
380
        tvShowName = @"Untitled TV MLShow";
Pierre's avatar
Pierre committed
381 382 383
        hasNoTvShow = YES;
    }
    BOOL wasInserted = NO;
Pierre's avatar
Pierre committed
384 385 386 387
    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
388 389 390 391 392 393 394 395 396 397 398 399
    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
400
    file.showEpisode = episode;
Pierre's avatar
Pierre committed
401

Pierre's avatar
Pierre committed
402
    // The rest of the meta data will be fetched using the MLShow
Pierre's avatar
Pierre committed
403
    file.hasFetchedInfo = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
404 405 406 407
}


/**
Pierre's avatar
Pierre committed
408
 * MLFile auto detection
Pierre's avatar
Pierre committed
409 410
 */

Pierre's avatar
Pierre committed
411

Pierre's avatar
Pierre committed
412
#if !HAVE_BLOCK
Pierre's avatar
Pierre committed
413 414 415 416 417 418
- (void)movieInfoGrabber:(MLMovieInfoGrabber *)grabber didFailWithError:(NSError *)error
{
    MLFile *file = grabber.userData;
    [self errorWhenFetchingMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
419 420 421 422 423
- (void)movieInfoGrabberDidFinishGrabbing:(MLMovieInfoGrabber *)grabber
{
    NSNumber *yes = [NSNumber numberWithBool:YES];

    NSArray *results = grabber.results;
Pierre's avatar
Pierre committed
424
    MLFile *file = grabber.userData;
Pierre's avatar
Pierre committed
425 426 427 428 429 430 431
    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
432 433 434 435
    else {
        [self noMetaDataInRemoteDBForFile:file];
    }

Pierre's avatar
Pierre committed
436 437 438 439
    file.hasFetchedInfo = yes;
}
#endif

Pierre's avatar
Pierre committed
440
- (void)fetchMetaDataForFile:(MLFile *)file
Pierre's avatar
Pierre committed
441
{
Pierre's avatar
Pierre committed
442 443
    MLLog(@"Fetching meta data for %@", file.title);

444 445 446
    if (!file.tracks)
        [[MLFileParserQueue sharedFileParserQueue] addFile:file];

Pierre's avatar
Pierre committed
447
    NSDictionary *tvShowEpisodeInfo = [MLTitleDecrapifier tvShowEpisodeInfoFromString:file.title];
Pierre's avatar
Pierre committed
448 449 450 451 452 453
    if (tvShowEpisodeInfo) {
        [self addTVShowEpisodeWithInfo:tvShowEpisodeInfo andFile:file];
        return;
    }

    // Go online and fetch info.
Pierre's avatar
Pierre committed
454 455 456

    // 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
457
    MLMovieInfoGrabber *grabber = [[[MLMovieInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
458

Pierre's avatar
Pierre committed
459 460
    MLLog(@"Looking up for Movie '%@'", file.title);

Pierre's avatar
Pierre committed
461
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
462
    [grabber lookUpForTitle:file.title andExecuteBlock:^(NSError *err){
Pierre's avatar
Pierre committed
463 464
        if (err) {
            [self errorWhenFetchingMetaDataForFile:file];
Pierre's avatar
Pierre committed
465
            return;
Pierre's avatar
Pierre committed
466
        }
Pierre's avatar
Pierre committed
467 468 469 470 471

        NSArray *results = grabber.results;
        if ([results count] > 0) {
            NSDictionary *result = [results objectAtIndex:0];
            file.artworkURL = [result objectForKey:@"artworkURL"];
Pierre's avatar
Pierre committed
472 473
            if (!file.artworkURL)
                [self computeThumbnailForFile:file];
Pierre's avatar
Pierre committed
474 475 476
            file.title = [result objectForKey:@"title"];
            file.shortSummary = [result objectForKey:@"shortSummary"];
            file.releaseYear = [result objectForKey:@"releaseYear"];
Pierre's avatar
Pierre committed
477 478 479
        } else
            [self noMetaDataInRemoteDBForFile:file];
        file.hasFetchedInfo = [NSNumber numberWithBool:YES];
Pierre's avatar
Pierre committed
480
    }];
Pierre's avatar
Pierre committed
481
#else
Pierre's avatar
Pierre committed
482 483 484
    grabber.userData = file;
    grabber.delegate = self;
    [grabber lookUpForTitle:file.title];
Pierre's avatar
Pierre committed
485
#endif
Pierre's avatar
Pierre committed
486 487
}

Pierre's avatar
Pierre committed
488 489 490
#pragma mark -
#pragma mark Adding file to the DB

Pierre's avatar
Pierre committed
491
- (void)addFilePath:(NSString *)filePath
Pierre's avatar
Pierre committed
492
{
Pierre's avatar
Pierre committed
493 494
    MLLog(@"Adding Path %@", filePath);

Pierre's avatar
Pierre committed
495
    NSURL *url = [NSURL fileURLWithPath:filePath];
Pierre's avatar
Pierre committed
496 497
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSString *title = [filePath lastPathComponent];
Pierre's avatar
Pierre committed
498
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
499 500
    NSDate *openedDate = nil; // FIXME kMDItemLastUsedDate
    NSDate *modifiedDate = nil; // FIXME [result valueForAttribute:@"kMDItemFSContentChangeDate"];
Pierre's avatar
Pierre committed
501
#endif
Pierre's avatar
Pierre committed
502
    NSNumber *size = [attributes objectForKey:NSFileSize]; // FIXME [result valueForAttribute:@"kMDItemFSSize"];
Pierre's avatar
Pierre committed
503

Pierre's avatar
Pierre committed
504
    MLFile *file = [self createObjectForEntity:@"File"];
Pierre's avatar
Pierre committed
505
    file.url = [url absoluteString];
Pierre's avatar
Pierre committed
506 507 508 509 510 511 512 513 514 515 516 517

    // 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
518
#if !TARGET_OS_IPHONE
Pierre's avatar
Pierre committed
519 520 521 522
    if ([openedDate isGreaterThan:modifiedDate]) {
        file.playCount = [NSNumber numberWithDouble:1];
        file.unread = no;
    }
Pierre's avatar
Pierre committed
523 524
#endif

Pierre's avatar
Pierre committed
525
    file.title = [MLTitleDecrapifier decrapify:[title stringByDeletingPathExtension]];
Pierre's avatar
Pierre committed
526 527

    if ([size longLongValue] < 150000000) /* 150 MB */
Pierre's avatar
Pierre committed
528
        file.type = kMLFileTypeClip;
Pierre's avatar
Pierre committed
529
    else
Pierre's avatar
Pierre committed
530
        file.type = kMLFileTypeMovie;
Pierre's avatar
Pierre committed
531 532 533 534

    [self fetchMetaDataForFile:file];
}

Pierre's avatar
Pierre committed
535
- (void)addFilePaths:(NSArray *)filepaths
Pierre's avatar
Pierre committed
536
{
Pierre's avatar
Pierre committed
537
    NSUInteger count = [filepaths count];
Pierre's avatar
Pierre committed
538 539 540 541
    NSMutableArray *fetchPredicates = [NSMutableArray arrayWithCapacity:count];
    NSMutableDictionary *urlToObject = [NSMutableDictionary dictionaryWithCapacity:count];

    // Prepare a fetch request for all items
Pierre's avatar
Pierre committed
542
    for (NSString *path in filepaths) {
Pierre's avatar
Pierre committed
543
        NSURL *url = [NSURL fileURLWithPath:path];
Pierre's avatar
Pierre committed
544 545 546 547
        NSString *urlString = [url absoluteString];
        [fetchPredicates addObject:[NSPredicate predicateWithFormat:@"url == %@", urlString]];
        [urlToObject setObject:path forKey:urlString];

Pierre's avatar
Pierre committed
548 549 550 551 552 553
    }

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

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

Pierre's avatar
Pierre committed
554
    MLLog(@"Fetching");
Pierre's avatar
Pierre committed
555
    NSArray *dbResults = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
556
    MLLog(@"Done");
Pierre's avatar
Pierre committed
557

Pierre's avatar
Pierre committed
558
    NSMutableArray *filePathsToAdd = [NSMutableArray arrayWithArray:filepaths];
Pierre's avatar
Pierre committed
559

Pierre's avatar
Pierre committed
560

Pierre's avatar
Pierre committed
561
    // Remove objects that are already in db.
Pierre's avatar
Pierre committed
562 563
    for (MLFile *dbResult in dbResults) {
        NSString *urlString = dbResult.url;
Pierre's avatar
Pierre committed
564
        [filePathsToAdd removeObject:[urlToObject objectForKey:urlString]];
Pierre's avatar
Pierre committed
565 566 567
    }

    // Add only the newly added items
Pierre's avatar
Pierre committed
568 569
    for (NSString* path in filePathsToAdd)
        [self addFilePath:path];
Pierre's avatar
Pierre committed
570 571
}

Pierre's avatar
Pierre committed
572 573 574 575

#pragma mark -
#pragma mark DB Updates

Pierre's avatar
Pierre committed
576 577 578 579 580 581
#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
582
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
583 584 585 586
        [self fetchMetaDataForShow:show];
}
#endif

Pierre's avatar
Pierre committed
587 588
- (void)startUpdateDB
{
Pierre's avatar
Pierre committed
589
    // Remove no more present files
Pierre's avatar
Pierre committed
590 591
    NSFetchRequest *request = [self fetchRequestForEntity:@"File"];
    NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
592 593 594 595
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (MLFile *file in results) {
        NSString *urlString = [file url];
        NSURL *fileURL = [NSURL URLWithString:urlString];
596 597 598
        BOOL exists = [fileManager fileExistsAtPath:[fileURL path]];
        if (!exists)
            NSLog(@"Marking - %@", [fileURL absoluteString]);
Pierre's avatar
Pierre committed
599 600
        file.isOnDisk = [NSNumber numberWithBool:exists];
    }
Pierre's avatar
Pierre committed
601

602 603 604 605 606 607 608
    // 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
609 610 611 612 613 614 615 616 617 618 619 620
    // Get the thumbnails to compute
    request = [self fetchRequestForEntity:@"File"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES && hasFetchedInfo == 1 && artworkURL == nil && computedThumbnail == nil"]];
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
    for (MLFile *file in results)
        [self computeThumbnailForFile:file];

    // 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
621 622
        [self fetchMetaDataForFile:file];

Pierre's avatar
Pierre committed
623
    // Get to fetch show info
Pierre's avatar
Pierre committed
624 625 626
    request = [self fetchRequestForEntity:@"Show"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"lastSyncDate == 0"]];
    results = [[self managedObjectContext] executeFetchRequest:request error:nil];
Pierre's avatar
Pierre committed
627
    for (MLShow *show in results)
Pierre's avatar
Pierre committed
628 629
        [self fetchMetaDataForShow:show];

Pierre's avatar
Pierre committed
630
    // Get updated TV Shows
Pierre's avatar
Pierre committed
631
    NSNumber *lastServerTime = [NSNumber numberWithInteger:[[NSUserDefaults standardUserDefaults] integerForKey:kLastTVDBUpdateServerTime]];
Pierre's avatar
Pierre committed
632
#if HAVE_BLOCK
Pierre's avatar
Pierre committed
633
    [MLTVShowInfoGrabber fetchUpdatesSinceServerTime:lastServerTime andExecuteBlock:^(NSArray *updates){
Pierre's avatar
Pierre committed
634 635 636
        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
637
        for (MLShow *show in results)
Pierre's avatar
Pierre committed
638 639
            [self fetchMetaDataForShow:show];
    }];
Pierre's avatar
Pierre committed
640 641 642 643
#else
    MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
    grabber.delegate = self;
    [grabber fetchUpdatesSinceServerTime:lastServerTime];
Pierre's avatar
Pierre committed
644
#endif
Pierre's avatar
Pierre committed
645 646 647
    /* Update every hour - FIXME: Preferences key */
    [self performSelector:@selector(startUpdateDB) withObject:nil afterDelay:60 * 60];
}
Pierre's avatar
Pierre committed
648 649 650 651 652 653 654 655 656 657 658 659

- (void)libraryDidDisappear
{
    // Stop expansive work
    [[MLThumbnailerQueue sharedThumbnailerQueue] stop];
}

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