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
- (NSString *)databaseFolderPath;
Pierre's avatar
Pierre committed
39 40
@end

Pierre's avatar
Pierre committed
41 42 43 44
@implementation MLMediaLibrary
+ (id)sharedMediaLibrary
{
    static id sharedMediaLibrary = nil;
Pierre's avatar
Pierre committed
45
    if (!sharedMediaLibrary) {
Pierre's avatar
Pierre committed
46
        sharedMediaLibrary = [[[self class] alloc] init];
Pierre's avatar
Pierre committed
47
        NSLog(@"Initializing db in %@", [sharedMediaLibrary databaseFolderPath]);
48
        [sharedMediaLibrary updateDatabase];
Pierre's avatar
Pierre committed
49
    }
Pierre's avatar
Pierre committed
50 51 52 53 54 55 56 57
    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
58
    NSAssert(entityDescription, @"No entity");
Pierre's avatar
Pierre committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    [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
79
- (NSString *)databaseFolderPath
Pierre's avatar
Pierre committed
80
{
Pierre's avatar
Pierre committed
81 82 83 84
    int directory = NSLibraryDirectory;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    NSString *directoryPath = [paths objectAtIndex:0];
    return directoryPath;
Pierre's avatar
Pierre committed
85 86 87 88 89 90 91
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#pragma mark -
#pragma mark Online meta data grabbing

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // First fetch the MLShow ID
        MLTVShowInfoGrabber *grabber = [[[MLTVShowInfoGrabber alloc] init] autorelease];
Pierre's avatar
Pierre committed
323 324 325 326 327 328 329 330 331 332 333
        [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
334 335
                MLLog(@"Fetching show episode information on %@", showId);

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

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

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

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


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

Pierre's avatar
Pierre committed
410

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

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

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

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

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

443
    [[MLFileParserQueue sharedFileParserQueue] addFile:file];
444

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

    // Go online and fetch info.
Pierre's avatar
Pierre committed
452 453 454

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

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

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

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

Pierre's avatar
Pierre committed
486 487 488
#pragma mark -
#pragma mark Adding file to the DB

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

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

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

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

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

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

    [self fetchMetaDataForFile:file];
}

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

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

Pierre's avatar
Pierre committed
546 547 548 549 550 551
    }

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

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

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

Pierre's avatar
Pierre committed
556
    NSMutableArray *filePathsToAdd = [NSMutableArray arrayWithArray:filepaths];
Pierre's avatar
Pierre committed
557

Pierre's avatar
Pierre committed
558

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

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

Pierre's avatar
Pierre committed
570 571 572 573

#pragma mark -
#pragma mark DB Updates

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

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

600 601 602 603 604 605 606
    // 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
607 608 609 610 611 612 613 614 615 616 617 618
    // 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
619 620
        [self fetchMetaDataForFile:file];

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

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

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

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