From 23ae0015907278c8d2d3363f9824ef93b8d3b23b Mon Sep 17 00:00:00 2001 From: Matthias Neeracher Date: Thu, 18 Aug 2011 19:15:32 +0200 Subject: [PATCH] Eliminate duplicate media --- Medianno/MADocument.mm | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/Medianno/MADocument.mm b/Medianno/MADocument.mm index 3e16378..ce7d7be 100644 --- a/Medianno/MADocument.mm +++ b/Medianno/MADocument.mm @@ -42,17 +42,35 @@ - (void)addMediaURL:(NSURL *)url name:(NSString *)name date:(NSDate *)date { - NSManagedObjectContext *moc = [self managedObjectContext]; - MAMedia * media = [NSEntityDescription insertNewObjectForEntityForName:@"MAMedia" inManagedObjectContext:moc]; - NSString * path = [url path]; - NSNumber * size; + NSString * path = [url path]; + NSNumber * size; [url getResourceValue:&size forKey:NSURLFileSizeKey error:nil]; - + int64_t fileSize = [size longLongValue]; + NSTimeInterval fileDate = [date timeIntervalSinceReferenceDate]; + + NSManagedObjectContext *moc = [self managedObjectContext]; + MAMedia * media = nil; + // + // Look for existing file with same name, file size, and (preferably) date first. + // Since the date may be parsed from the file name (and subject to a later fix), + // we tolerate mismatches. + // + NSFetchRequest * fetch = [NSFetchRequest fetchRequestWithEntityName:@"MAMedia"]; + [fetch setPredicate:[NSPredicate predicateWithFormat:@"name == %@", name]]; + for (MAMedia * m in [moc executeFetchRequest:fetch error:nil]) + if (m.size == fileSize) { + media = m; + if (m.date == fileDate) + break; + } + if (!media) { + media = [NSEntityDescription insertNewObjectForEntityForName:@"MAMedia" inManagedObjectContext:moc]; + media.size = fileSize; + media.name = name; + media.notes = @""; + } + media.date = fileDate; media.media = path; - media.date = [date timeIntervalSinceReferenceDate]; - media.name = name; - media.notes = @""; - media.size = size ? [size longLongValue] : 0; } #pragma mark Annotation management