source: trunk/SapphireFrappliance/MetaDataImporting/SapphireMovieImporter.m @ 1320

Revision 1320, 23.2 KB checked in by gbooker, 4 years ago (diff)

Updated more enums with better names (no functionality change)

Line 
1/*
2 * SapphireMovieImporter.m
3 * Sapphire
4 *
5 * Created by Patrick Merrill on Sep. 10, 2007.
6 * Copyright 2007 Sapphire Development Team and/or www.nanopi.net
7 * All rights reserved.
8 *
9 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
10 * General Public License as published by the Free Software Foundation; either version 3 of the License,
11 * or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
14 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
15 * Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along with this program; if not,
18 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 */
20
21#import "SapphireMovieImporter.h"
22#import "SapphireFileMetaData.h"
23#import "NSFileManager-Extensions.h"
24#import "SapphireMovieChooser.h"
25#import "SapphirePosterChooser.h"
26#import "SapphireSettings.h"
27#import "SapphireMetaDataSupport.h"
28#import "SapphireMovie.h"
29#import "SapphireMovieTranslation.h"
30#import "SapphireMoviePoster.h"
31#import "SapphireApplianceController.h"
32#import "SapphireURLLoader.h"
33#import "SapphireScraper.h"
34#import "NSString-Extensions.h"
35
36@interface SapphireMovieImportStateData : SapphireImportStateData
37{
38@public
39        SapphireSiteMovieScraper        *siteScraper;
40        SapphireMovieTranslation        *translation;
41}
42- (id)initWithFile:(SapphireFileMetaData *)aFile atPath:(NSString *)aPath scraper:(SapphireSiteMovieScraper *)siteScaper;
43- (void)setTranslation:(SapphireMovieTranslation *)aTranslation;
44- (SapphireMovieTranslation *)createTranslationInContext:(NSManagedObjectContext *)moc;
45@end
46
47@implementation SapphireMovieImportStateData
48
49- (id)initWithFile:(SapphireFileMetaData *)aFile atPath:(NSString *)aPath scraper:(SapphireSiteMovieScraper *)aSiteScaper
50{
51        self = [super initWithFile:aFile atPath:aPath];
52        if(!self)
53                return self;
54       
55        siteScraper = [aSiteScaper retain];
56       
57        return self;
58}
59
60- (void)dealloc
61{
62        [siteScraper release];
63        [translation release];
64        [super dealloc];
65}
66
67- (void)setTranslation:(SapphireMovieTranslation *)aTranslation
68{
69        [translation autorelease];
70        translation = [aTranslation retain];
71}
72
73- (SapphireMovieTranslation *)createTranslationInContext:(NSManagedObjectContext *)moc
74{
75        SapphireMovieTranslation *tran = [SapphireMovieTranslation createMovieTranslationWithName:lookupName inContext:moc];
76        tran.importerID = [[siteScraper scraper] name];
77        [self setTranslation:tran];
78        return tran;
79}
80
81@end
82
83
84
85@interface SapphireMovieImporter ()
86- (void)getMovieResultsForState:(SapphireMovieImportStateData *)state;
87- (void)getMoviePostersForState:(SapphireMovieImportStateData *)state thumbElements:(NSArray *)thumbElements;
88- (void)saveMoviePosterAtURL:(NSString *)url forTranslation:(SapphireMovieTranslation *)tran;
89- (void)completeWithState:(SapphireMovieImportStateData *)state withStatus:(ImportState)status importComplete:(BOOL)importComplete;
90@end
91
92@implementation SapphireMovieImporter
93
94- (id)init
95{
96        self = [super init];
97        if(!self)
98                return self;
99       
100        scraper = [[SapphireScraper scrapperWithName:@"IMDb.com"] retain];
101       
102        return self;
103}
104
105- (void)dealloc
106{
107        [scraper release];
108        [super dealloc];
109}
110
111
112- (void)setDelegate:(id <SapphireImporterDelegate>)aDelegate
113{
114        delegate = aDelegate;
115}
116
117- (void)cancelImports
118{
119        cancelled = YES;
120}
121
122- (void)retrievedSearchResuls:(NSXMLDocument *)results forObject:(id)stateObj
123{
124        SapphireMovieImportStateData *state = (SapphireMovieImportStateData *)stateObj;
125        [state->siteScraper setObject:nil];     //Avoid retain loop
126        if(cancelled)
127                return;
128       
129        if(results == nil)
130        {
131                /*Failed to get data, network likely, don't mark this as imported*/
132                [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:NO];
133                return;
134        }
135        NSXMLElement *root = [results rootElement];
136        NSArray *entities = [root elementsForName:@"entity"];
137        NSMutableArray *movies = [[NSMutableArray alloc] initWithCapacity:[entities count]];
138        NSEnumerator *entityEnum = [entities objectEnumerator];
139        NSXMLElement *entity;
140        while((entity = [entityEnum nextObject]) != nil)
141        {
142                NSString *kind = stringValueOfChild(entity, @"kind");
143               
144                /*Skip video games and tv series*/
145                if([kind isEqualToString:@"VG"] || [kind isEqualToString:@"TV series"])
146                        continue;
147               
148                NSString *title = stringValueOfChild(entity, @"title");
149                NSString *itemID = stringValueOfChild(entity, @"id");
150                NSString *url = stringValueOfChild(entity, @"url");
151                NSString *year = stringValueOfChild(entity, @"year");
152                if([year length])
153                        title = [title stringByAppendingFormat:@" (%@)", year];
154               
155                if([title length] && [url length])
156                        [movies addObject:[NSDictionary dictionaryWithObjectsAndKeys:
157                                                           title, movieTranslationNameKey,
158                                                           url, movieTranslationLinkKey,
159                                                           itemID, movieTranslationIDKey,
160                                                           nil]];
161        }
162       
163        SapphireLog(SapphireLogTypeImport, SapphireLogLevelDetail, @"Found results: %@", movies);
164       
165        /* No need to prompt the user for an empty set */
166        if(![movies count])
167        {
168                /* We tried to import but found nothing - mark this file to be skipped on future imports */
169                [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:YES];
170        }
171        else if([[SapphireSettings sharedSettings] autoSelection])
172        {
173                SapphireFileMetaData *metaData = state->file;
174                NSManagedObjectContext *moc = [metaData managedObjectContext];
175                SapphireMovieTranslation *tran = [state createTranslationInContext:moc];
176                tran.url = [[movies objectAtIndex:0] objectForKey:movieTranslationLinkKey];
177                tran.itemID = [[movies objectAtIndex:0] objectForKey:movieTranslationIDKey];
178                [self getMovieResultsForState:state];
179        }
180        else
181        {
182                /*Bring up the prompt*/
183                SapphireMovieChooser *chooser = [[SapphireMovieChooser alloc] initWithScene:[delegate chooserScene]];
184                [chooser setMovies:movies];
185                [chooser setFileName:[NSString stringByCroppingDirectoryPath:state->path toLength:3]];
186                [chooser setListTitle:BRLocalizedString(@"Select Movie Title", @"Prompt the user for title of movie")];
187                /*And display prompt*/
188                [delegate displayChooser:chooser forImporter:self withContext:state];
189                [chooser release];
190        }
191        [movies release];
192}
193
194- (void)getMovieResultsForState:(SapphireMovieImportStateData *)state
195{
196        SapphireMovieTranslation *tran = state->translation;
197        NSString *link = tran.url;
198        SapphireSiteMovieScraper *siteScraper = state->siteScraper;
199        [siteScraper setObject:state];
200        [siteScraper getMovieDetailsAtURL:link forMovieID:tran.itemID];
201}
202
203- (void)retrievedMovieDetails:(NSXMLDocument *)details forObject:(id)stateObj
204{
205        SapphireMovieImportStateData *state = (SapphireMovieImportStateData *)stateObj;
206        [state->siteScraper setObject:nil];     //Avoid retain loop
207
208        if(cancelled)
209                return;
210       
211        if(details == nil)
212        {
213                /*Failed to get data, network likely, don't mark this as imported*/
214                [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:NO];
215                return;
216        }
217        NSXMLElement *root = [details rootElement];
218       
219        NSString        *movieTitleLink = stringValueOfChild(root, @"id");
220        NSNumber        *oscarsWon              = intValueOfChild(root, @"oscars");
221        NSDate          *releaseDate    = dateValueOfChild(root, @"releasedate");
222        NSString        *plot                   = stringValueOfChild(root, @"plot");
223        NSString        *mpaaStr                = stringValueOfChild(root, @"mpaa");
224        NSArray         *directors              = arrayStringValueOfChild(root, @"director");
225        NSArray         *genres                 = arrayStringValueOfChild(root, @"genre");
226        NSNumber        *top250                 = intValueOfChild(root, @"top250");
227        NSString        *usrRating              = stringValueOfChild(root, @"rating");
228        NSArray         *completeCast   = arrayStringValueOfXPath(root, @"actor/name");
229        NSString        *movieTitle             = stringValueOfChild(root, @"title");
230       
231        if([movieTitle rangeOfString:@"Request Limit Reached"].location != NSNotFound)
232        {
233                /*IMDB said we hit them too much; abort this data*/
234                [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:NO];
235                return;
236        }
237       
238        NSString *mpaaRating = nil;
239        if([mpaaStr hasPrefix:@"Rated"])
240        {
241                NSScanner *trimmer=[NSScanner scannerWithString:[mpaaStr substringFromIndex:6]] ;
242                [trimmer scanUpToString:@" " intoString:&mpaaRating];
243        }
244        else
245        {
246                NSArray *certifications = arrayStringValueOfXPath(root, @"certification");
247                NSString *certification;
248                NSEnumerator *certEnum = [certifications objectEnumerator];
249                while((certification = [certEnum nextObject]) != nil)
250                {
251                        if([certification hasPrefix:@"USA:"])
252                        {
253                                NSScanner *trimmer=[NSScanner scannerWithString:[certification substringFromIndex:4]];
254                                [trimmer scanUpToString:@" " intoString:&mpaaRating];
255                        }
256                }
257        }
258       
259       
260        NSMutableDictionary *infoIMDB = [NSMutableDictionary dictionary];
261        /* populate metadata to return */
262        [infoIMDB setObject:movieTitleLink forKey:META_MOVIE_IDENTIFIER_KEY];
263        if(oscarsWon)
264                [infoIMDB setObject:oscarsWon forKey:META_MOVIE_OSCAR_KEY];
265        else
266                [infoIMDB setObject:[NSNumber numberWithInt:0] forKey:META_MOVIE_OSCAR_KEY];
267        if(top250)
268                [infoIMDB setObject:top250 forKey:META_MOVIE_IMDB_250_KEY];
269        if([usrRating length]>0)
270                [infoIMDB setObject:[NSNumber numberWithFloat:[usrRating floatValue]] forKey:META_MOVIE_IMDB_RATING_KEY];
271        if(mpaaRating)
272                [infoIMDB setObject:mpaaRating forKey:META_MOVIE_MPAA_RATING_KEY];
273        else
274                [infoIMDB setObject:@"N/A" forKey:META_MOVIE_MPAA_RATING_KEY];
275        if(directors)
276                [infoIMDB setObject:directors forKey:META_MOVIE_DIRECTOR_KEY];
277        if(plot)
278                [infoIMDB setObject:plot forKey:META_MOVIE_PLOT_KEY];
279        if(releaseDate)
280                [infoIMDB setObject:releaseDate forKey:META_MOVIE_RELEASE_DATE_KEY];
281        if(genres)
282                [infoIMDB setObject:genres forKey:META_MOVIE_GENRES_KEY];
283        if(completeCast)
284                [infoIMDB setObject:completeCast forKey:META_MOVIE_CAST_KEY];
285        if(movieTitle)
286                [infoIMDB setObject:movieTitle forKey:META_MOVIE_TITLE_KEY];
287       
288        SapphireFileMetaData *metaData = state->file;
289        NSManagedObjectContext *moc = [metaData managedObjectContext];
290        SapphireMovie *movie = [SapphireMovie movieWithDictionary:infoIMDB inContext:moc];
291        if(movie == nil)
292        {
293                SapphireLog(SapphireLogTypeImport, SapphireLogLevelError, @"Failed to import movie for %@", state->path);
294                [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:NO];
295                return;
296        }
297        SapphireMovieTranslation *tran = state->translation;
298        [tran setMovie:movie];
299        [metaData setMovie:movie];
300       
301        SapphireMoviePoster *poster = [tran selectedPoster];
302        if(poster != nil)
303        {
304                [self saveMoviePosterAtURL:[poster link] forTranslation:tran];
305                [self completeWithState:state withStatus:ImportStateUpdated importComplete:YES];
306        }
307        else
308        {
309                NSArray *thumbs = [root elementsForName:@"thumb"];
310                NSXMLElement *fanart = [[root elementsForName:@"fanart"] lastObject];
311                if(fanart)
312                        thumbs = [thumbs arrayByAddingObjectsFromArray:[fanart elementsForName:@"thumb"]];
313               
314                BOOL canDisplay = [delegate canDisplayChooser];
315                if(canDisplay && [thumbs count])
316                        [self getMoviePostersForState:state thumbElements:thumbs];
317                else
318                        [self completeWithState:state withStatus:ImportStateUpdated importComplete:canDisplay];
319        }
320}
321
322- (void)getMoviePostersForState:(SapphireMovieImportStateData *)state thumbElements:(NSArray *)thumbElements;
323{
324        NSMutableArray *previews = [NSMutableArray arrayWithCapacity:[thumbElements count]];
325        SapphireMovieTranslation *tran = state->translation;
326        if([thumbElements count])
327        {
328                int index = 0;
329                NSManagedObjectContext *moc = [tran managedObjectContext];
330                //Redoing posters, get rid of old ones
331                [tran setSelectedPosterIndex:nil];
332                NSEnumerator *posterEnum = [[tran postersSet] objectEnumerator];
333                SapphireMoviePoster *poster;
334                while((poster = [posterEnum nextObject]) != nil)
335                        [moc deleteObject:poster];
336               
337                NSEnumerator *thumbEnum = [thumbElements objectEnumerator];
338                NSXMLElement *thumb;
339                NSMutableSet *posterSet = [NSMutableSet setWithCapacity:[thumbElements count]];
340                while((thumb = [thumbEnum nextObject]) != nil)
341                {
342                        NSString *preview = [[thumb attributeForName:@"preview"] stringValue];
343                        NSString *url = [thumb stringValue];
344                        if(![preview length])
345                                preview = url;
346                       
347                        [previews addObject:preview];
348                        [posterSet addObject:[SapphireMoviePoster createPosterWithLink:url index:index translation:tran inContext:moc]];
349                        index++;
350                }
351                [[tran postersSet] setSet:posterSet];
352        }
353        else
354        {
355                NSArray *posters = [tran orderedPosters];
356                NSEnumerator *posterEnum = [posters objectEnumerator];
357                SapphireMoviePoster *poster;
358                while((poster = [posterEnum nextObject]) != nil)
359                {
360                        NSString *link = [poster link];
361                        [previews addObject:link];
362                }
363        }
364        if([tran selectedPoster])
365        {
366                [self saveMoviePosterAtURL:[[tran selectedPoster] link] forTranslation:tran];
367                [self completeWithState:state withStatus:ImportStateUpdated importComplete:YES];
368        }
369        else if([previews count])
370        {
371                SapphirePosterChooser *posterChooser = [[SapphirePosterChooser alloc] initWithScene:[delegate chooserScene]];
372                if(![posterChooser okayToDisplay] || [[SapphireSettings sharedSettings] autoSelection])
373                {
374                        /* Auto Select the first poster */
375                        [self saveMoviePosterAtURL:[[tran posterAtIndex:0] link] forTranslation:tran];
376                        [posterChooser release];
377                }
378                else
379                {
380                        [posterChooser setPosters:previews];
381                        [posterChooser setFileName:[NSString stringByCroppingDirectoryPath:state->path toLength:3]];
382                        [posterChooser setFile:state->file];
383                        [posterChooser setListTitle:BRLocalizedString(@"Select Movie Poster", @"Prompt the user for poster selection")];
384                        [delegate displayChooser:posterChooser forImporter:self withContext:state];
385                        [posterChooser release];
386                }               
387        }
388        else
389                [self completeWithState:state withStatus:ImportStateUpdated importComplete:YES];
390}
391
392- (void)saveMoviePosterAtURL:(NSString *)url forTranslation:(SapphireMovieTranslation *)tran
393{
394        NSString *coverart = [[SapphireMetaDataSupport collectionArtPath] stringByAppendingPathComponent:@"@MOVIES"];
395        [[NSFileManager defaultManager] constructPath:coverart];
396        int imdbNumber = [SapphireMovie imdbNumberFromString:tran.itemID];
397        coverart = [coverart stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.jpg", imdbNumber]];
398        [[SapphireApplianceController urlLoader] saveDataAtURL:url toFile:coverart];   
399}
400
401- (void)completeWithState:(SapphireMovieImportStateData *)state withStatus:(ImportState)status importComplete:(BOOL)importComplete;
402{
403        SapphireFileMetaData *currentData = state->file;
404        if(importComplete)
405        {
406                [currentData didImportType:ImportTypeMaskMovie];
407                if (status == ImportStateNotUpdated && [currentData fileClassValue] != FileClassTVShow)
408                        [currentData setFileClassValue:FileClassUnknown];
409        }
410        [delegate backgroundImporter:self completedImportOnPath:state->path withState:status];
411}
412
413- (NSString *)movieURLFromNfoFilePath:(NSString *)filepath withID:(NSString * *)movieID
414{
415        NSString *nfoContent = [NSString stringWithContentsOfFile:filepath];
416       
417        if(![nfoContent length])
418                return nil;
419       
420        NSString *results = [scraper searchResultsForNfoContent:nfoContent];
421        if(![results length])
422                return nil;
423       
424        NSString *fullResults = [NSString stringWithFormat:@"<results>%@</results>", results];
425        NSError *error = nil;
426        NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:fullResults options:0 error:&error] autorelease];
427        if(!doc)
428                return nil;
429       
430        NSXMLElement *root = [doc rootElement];
431        NSString *urlStr = stringValueOfChild(root, @"url");
432        *movieID = stringValueOfChild(root, @"id");
433        return urlStr;
434}
435
436/*!
437* @brief verify file extention of a file
438 *
439 * @param metaData The file's metadata
440 * @return YES if candidate, NO otherwise
441 */
442- (BOOL)isMovieCandidate:(SapphireFileMetaData *)metaData;
443{
444        NSString *path = [metaData path];
445        BOOL ret = [[NSFileManager defaultManager] acceptFilePath:path];
446        if([metaData fileContainerType] == FileContainerTypeQTMovie)
447                ret &= [[NSFileManager videoExtensions] containsObject:[path pathExtension]];
448        if([metaData fileClassValue]==FileClassTVShow) /* File is a TV Show - skip it */
449                ret = NO;
450        return ret;
451}
452
453- (ImportState)importMetaData:(SapphireFileMetaData *)metaData path:(NSString *)path
454{
455        cancelled = NO;
456        /*Check to see if it is already imported*/
457        if([metaData importTypeValue] & ImportTypeMaskMovie)
458                return ImportStateNotUpdated;
459        /*Get path*/
460        if(![self isMovieCandidate:metaData])
461                return ImportStateNotUpdated;
462        SapphireLog(SapphireLogTypeImport, SapphireLogLevelDebug, @"Going to movie import %@", path);
463        NSString *extLessPath = path;
464        if([metaData fileContainerTypeValue] != FileContainerTypeVideoTS)
465                extLessPath = [extLessPath stringByDeletingPathExtension];
466       
467        /*choose between file or directory name for lookup */
468        NSString *lookupName;
469        if([[SapphireSettings sharedSettings] dirLookup])
470                lookupName = [[[path stringByDeletingLastPathComponent] lastPathComponent] lowercaseString];
471        else
472                lookupName = [[extLessPath lastPathComponent] lowercaseString];
473       
474        SapphireSiteMovieScraper *siteScraper = [[[SapphireSiteMovieScraper alloc] initWithMovieScraper:scraper delegate:self loader:[SapphireApplianceController urlLoader]] autorelease];
475        SapphireMovieImportStateData *state = [[[SapphireMovieImportStateData alloc] initWithFile:metaData atPath:path scraper:siteScraper] autorelease];
476        [state setLookupName:lookupName];
477        /*Check to see if we know this movie*/
478       
479        /*Look for a year in the title*/
480        NSScanner *titleYearScanner = [NSScanner scannerWithString:state->lookupName];
481        NSString *normalTitle = nil;
482        int year = 0;
483        BOOL success = YES;
484        success &= [titleYearScanner scanUpToString:@"(" intoString:&normalTitle];
485        success &= [titleYearScanner scanString:@"(" intoString:nil];
486        success &= [titleYearScanner scanInt:&year];
487        success &= [titleYearScanner scanString:@")" intoString:nil];
488       
489        NSString *yearStr = nil;
490        if(success)
491        {
492                yearStr = [NSString stringWithFormat:@"%d", year];
493                if([normalTitle hasSuffix:@" "])
494                   normalTitle = [normalTitle substringToIndex:[normalTitle length]-1];
495                [state setLookupName:normalTitle];
496        }
497       
498        SapphireLog(SapphireLogTypeImport, SapphireLogLevelDetail, @"Searching for movie \"%@\"", state->lookupName);
499        NSManagedObjectContext *moc = [metaData managedObjectContext];
500        SapphireMovieTranslation *tran = [SapphireMovieTranslation movieTranslationWithName:state->lookupName inContext:moc];
501        if(tran == nil)
502                //Check for translation with full title
503                tran = [SapphireMovieTranslation movieTranslationWithName:[titleYearScanner string] inContext:moc];
504        [state setTranslation:tran];
505        int searchIMDBNumber = [metaData searchIMDBNumber];
506        if(searchIMDBNumber > 0)
507        {
508                if(!tran)
509                        tran = [state createTranslationInContext:moc];
510                tran.url = [NSString stringWithFormat:@"http://%@/title/tt%d/", [[[siteScraper scraper] settings] objectForKey:@"url"], searchIMDBNumber];
511        }
512        if(tran.url == nil)
513        {
514                BOOL nfoPathIsDir = NO;
515                NSString *nfoFilePath=[extLessPath stringByAppendingPathExtension:@"nfo"];
516                NSString *movieURL = nil;
517                NSString *movieID = nil;
518                if([[NSFileManager defaultManager] fileExistsAtPath:nfoFilePath isDirectory:&nfoPathIsDir] && !nfoPathIsDir)
519                        movieURL = [self movieURLFromNfoFilePath:nfoFilePath withID:&movieID];
520               
521                if([movieURL length])
522                {
523                        if(tran == nil)
524                                tran = [state createTranslationInContext:moc];
525                        tran.url = movieURL;
526                        if([movieID length])
527                                [tran setItemID:movieID];
528                }
529                else
530                {
531                        if(![delegate canDisplayChooser])
532                        /*There is no data menu, background import. So we can't ask user, skip*/
533                                return ImportStateNotUpdated;
534                       
535                        SapphireLog(SapphireLogTypeImport, SapphireLogLevelDebug, @"Searching for %@ with year %@", state->lookupName, yearStr);
536                       
537                        /*Ask the user what movie this is*/
538                        [siteScraper setObject:state];
539                        [siteScraper searchForMovieName:state->lookupName year:yearStr];
540                        return ImportStateBackground;
541                }
542        }
543       
544        SapphireMovie *movie = [tran movie];
545        if(movie != nil)
546        {       
547                [metaData setMovie:movie];
548                if([tran selectedPoster] != nil)
549                        return ImportStateUpdated;
550                [self getMoviePostersForState:state thumbElements:[NSArray array]];
551                return ImportStateBackground;
552        }
553        [self getMovieResultsForState:state];
554        return ImportStateBackground;
555}
556
557
558- (NSString *)completionText
559{
560        return BRLocalizedString(@"All available Movie data has been imported", @"The Movie import is complete");
561}
562
563- (NSString *)initialText
564{
565        return BRLocalizedString(@"Fetch Movie Data", @"Title");
566}
567
568- (NSString *)informativeText
569{
570        return BRLocalizedString(@"This tool will attempt to fetch information about your Movie files from the Internet (IMDB/IMPAwards).  This procedure may take quite some time and could ask you questions.  You may cancel at any time.", @"Description of the movie import");
571}
572
573- (NSString *)buttonTitle
574{
575        return BRLocalizedString(@"Start Fetching Data", @"Button");
576}
577
578- (BOOL)stillNeedsDisplayOfChooser:(BRLayerController <SapphireChooser> *)chooser withContext:(id)context
579{
580        SapphireMovieImportStateData *state = (SapphireMovieImportStateData *)context;
581        if([chooser isKindOfClass:[SapphireMovieChooser class]])
582        {
583                NSManagedObjectContext *moc = [state->file managedObjectContext];
584                SapphireMovieTranslation *tran = [SapphireMovieTranslation movieTranslationWithName:state->lookupName inContext:moc];
585                if(tran)
586                        [state setTranslation:tran];
587                if(tran.url)
588                {
589                        [self getMovieResultsForState:state];
590                        return NO;
591                }
592        }
593        else if([chooser isKindOfClass:[SapphirePosterChooser class]])
594        {
595                SapphireMovieTranslation *tran = state->translation;
596                if([[tran selectedPoster] link])
597                {
598                        [self saveMoviePosterAtURL:[[tran selectedPoster] link] forTranslation:tran];
599                        [self completeWithState:state withStatus:ImportStateUpdated importComplete:YES];
600                        return NO;
601                }
602        }
603        return YES;
604}
605
606- (void)exhumedChooser:(BRLayerController <SapphireChooser> *)chooser withContext:(id)context
607{
608        SapphireMovieImportStateData *state = (SapphireMovieImportStateData *)context;
609        /*See if it was a movie chooser*/
610        if([chooser isKindOfClass:[SapphireMovieChooser class]])
611        {
612                /*Get the user's selection*/
613                SapphireMovieChooser *movieChooser = (SapphireMovieChooser *)chooser;
614                SapphireFileMetaData *currentData = state->file;
615                NSManagedObjectContext *moc = [currentData managedObjectContext];
616                int selection = [movieChooser selection];
617                if(selection == SapphireChooserChoiceCancel)
618                {
619                        /*They aborted, skip*/
620                        [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:NO];
621                }
622                else if(selection == SapphireChooserChoiceNotType)
623                {
624                        /*They said it is not a movie, so put in empty data so they are not asked again*/
625                        [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:YES];
626                }
627                else
628                {
629                        /*They selected a movie title, save the translation and write it*/
630                        NSDictionary *movie = [[movieChooser movies] objectAtIndex:selection];
631                        SapphireMovieTranslation *tran = [state createTranslationInContext:moc];
632                        tran.url = [movie objectForKey:movieTranslationLinkKey];
633                        tran.itemID = [movie objectForKey:movieTranslationIDKey];
634                        /*We can resume now*/
635                        [self getMovieResultsForState:state];
636                }
637                [SapphireMetaDataSupport save:moc];
638        }
639        else if([chooser isKindOfClass:[SapphirePosterChooser class]])
640        {
641                SapphirePosterChooser *posterChooser = (SapphirePosterChooser *)chooser;
642                SapphireFileMetaData *currentData = state->file;
643                NSManagedObjectContext *moc = [currentData managedObjectContext];
644                SapphireChooserChoice selectedPoster = [posterChooser selection];
645                if(selectedPoster == SapphireChooserChoiceCancel)
646                        /*They aborted, skip*/
647                        [self completeWithState:state withStatus:ImportStateNotUpdated importComplete:NO];
648                else
649                {
650                        SapphireMovieTranslation *tran = state->translation;
651                        [tran setSelectedPosterIndexValue:selectedPoster];
652                        [self saveMoviePosterAtURL:[[tran selectedPoster] link] forTranslation:tran];
653                        [self completeWithState:state withStatus:ImportStateUpdated importComplete:YES];
654                }
655                [SapphireMetaDataSupport save:moc];
656        }
657        else
658                return;
659}
660
661@end
Note: See TracBrowser for help on using the repository browser.