MLFile.m 16 KB
Newer Older
1 2 3 4 5
/*****************************************************************************
 * MLFile.m
 * Lunettes
 *****************************************************************************
 * Copyright (C) 2010 Pierre d'Herbemont
6
 * Copyright (C) 2010-2015 VLC authors and VideoLAN
7 8 9 10
 * $Id$
 *
 * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
 *          Felix Paul Kühne <fkuehne # videolan.org>
11
 *          Tobias Conradi <videolan # tobias-conradi.de
12
 *
13 14 15
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
16 17 18 19
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
22
 *
23 24 25
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26
 *****************************************************************************/
Pierre's avatar
Pierre committed
27 28 29 30

#import "MLFile.h"
#import "MLShow.h"
#import "MLShowEpisode.h"
31 32
#import "MLAlbum.h"
#import "MLAlbumTrack.h"
Pierre's avatar
Pierre committed
33
#import "MLMediaLibrary.h"
34
#import "MLThumbnailerQueue.h"
35
#import "MLFileParserQueue.h"
Pierre's avatar
Pierre committed
36 37 38 39

NSString *kMLFileTypeMovie = @"movie";
NSString *kMLFileTypeClip = @"clip";
NSString *kMLFileTypeTVShowEpisode = @"tvShowEpisode";
40
NSString *kMLFileTypeAudio = @"audio";
41
NSString *const MLFileThumbnailWasUpdated = @"MLFileThumbnailWasUpdated";
Pierre's avatar
Pierre committed
42 43 44

@implementation MLFile

45 46 47 48 49
- (NSString *)description
{
    return [NSString stringWithFormat:@"<MLFile title='%@'>", [self title]];
}

50 51 52 53 54 55
- (void)awakeFromInsert
{
    [super awakeFromInsert];
    self.thumbnailName = [NSUUID UUID].UUIDString;
}

Pierre's avatar
Pierre committed
56 57 58 59
+ (NSArray *)allFiles
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
60 61 62
    if (!moc || moc.persistentStoreCoordinator == nil)
        return [NSArray array];

Pierre's avatar
Pierre committed
63 64
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:moc];
    [request setEntity:entity];
65
    [request setPredicate:[NSPredicate predicateWithFormat:@"isOnDisk == YES"]];
Pierre's avatar
Pierre committed
66

Pierre's avatar
Pierre committed
67
    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
68
    [request setSortDescriptors:@[descriptor]];
Pierre's avatar
Pierre committed
69

70 71
    NSError *error;
    NSArray *movies = [moc executeFetchRequest:request error:&error];
72
    if (!movies) {
73
        APLog(@"WARNING: %@", error);
74
    }
Pierre's avatar
Pierre committed
75 76 77 78

    return movies;
}

79
+ (NSArray *)fileForURL:(NSURL *)url;
80 81 82
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
83 84 85
    if (!moc || moc.persistentStoreCoordinator == nil)
        return [NSArray array];

86 87 88 89
    NSString *path = url.path;
#if TARGET_OS_IPHONE
    path = [[MLMediaLibrary sharedMediaLibrary] pathRelativeToDocumentsFolderFromAbsolutPath:path];
#endif
90 91
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:moc];
    [request setEntity:entity];
92
    [request setPredicate:[NSPredicate predicateWithFormat:@"path == %@", path]];
93 94 95 96 97 98 99 100 101 102 103 104

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
    [request setSortDescriptors:@[descriptor]];

    NSError *error;
    NSArray *files = [moc executeFetchRequest:request error:&error];
    if (!files)
        APLog(@"WARNING: %@", error);

    return files;
}

105 106 107 108 109 110 111 112 113
+ (instancetype)fileForURIRepresentation:(NSURL *)uriRepresentation {
    NSManagedObject *object = [[MLMediaLibrary sharedMediaLibrary] objectForURIRepresentation:uriRepresentation];
    if ([object isKindOfClass:[MLFile class]]) {
        return (MLFile *)object;
    } else {
        return nil;
    }
}

Pierre's avatar
Pierre committed
114 115 116 117 118 119
- (BOOL)isKindOfType:(NSString *)type
{
    return [self.type isEqualToString:type];
}
- (BOOL)isMovie
{
Tobias's avatar
Tobias committed
120
    return [self isKindOfType:kMLFileTypeMovie];
Pierre's avatar
Pierre committed
121 122 123
}
- (BOOL)isClip
{
Tobias's avatar
Tobias committed
124
    return [self isKindOfType:kMLFileTypeClip];
Pierre's avatar
Pierre committed
125 126 127 128 129
}
- (BOOL)isShowEpisode
{
    return [self isKindOfType:kMLFileTypeTVShowEpisode];
}
130 131 132 133
- (BOOL)isAlbumTrack
{
    return [self isKindOfType:kMLFileTypeAudio];
}
134

135 136 137
- (BOOL)isSupportedAudioFile
{
    NSUInteger options = NSRegularExpressionSearch | NSCaseInsensitiveSearch;
138
    return ([[self.path lastPathComponent] rangeOfString:@"\\.(aac|aiff|aif|amr|aob|ape|axa|caf|flac|it|m2a|m4a|m4b|mka|mlp|mod|mp1|mp2|mp3|mpa|mpc|oga|oma|opus|rmi|s3m|spx|tta|voc|vqf|w64|wav|wma|wv|xa|xm)$" options:options].location != NSNotFound);
139 140
}

Pierre's avatar
Pierre committed
141 142
- (NSString *)artworkURL
{
143
    if ([self isShowEpisode]) {
Pierre's avatar
Pierre committed
144
        return self.showEpisode.artworkURL;
145
    }
Pierre's avatar
Pierre committed
146 147 148 149 150 151 152
    return [self primitiveValueForKey:@"artworkURL"];
}

- (NSString *)title
{
    if ([self isShowEpisode]) {
        MLShowEpisode *episode = self.showEpisode;
153
        NSMutableString *name = [[NSMutableString alloc] init];
154
        if (episode.show.name.length > 0)
155 156
            [name appendString:episode.show.name];

157 158 159 160 161
        if ([episode.seasonNumber intValue] > 0) {
            if (![name isEqualToString:@""])
                [name appendString:@" - "];
            [name appendFormat:@"S%02dE%02d", [episode.seasonNumber intValue], [episode.episodeNumber intValue]];
        }
162

163
        if (episode.name.length > 0) {
164 165 166 167 168
            if ([name length] > 0)
                [name appendString:@" - "];
            [name appendString:episode.name];
        }

169 170
        NSString *returnValue = [NSString stringWithString:name];
        return returnValue;
171 172
    } else if ([self isAlbumTrack]) {
        MLAlbumTrack *track = self.albumTrack;
173 174
        if (track && track.title.length > 0) {
            NSMutableString *name = [[NSMutableString alloc] initWithString:track.title];
175

176 177
            if (track.album.name.length > 0)
                [name appendFormat:@" - %@", track.album.name];
178

179 180
            if (track.artist.length > 0)
                [name appendFormat:@" - %@", track.artist];
181

182 183
            NSString *returnValue = [NSString stringWithString:name];
            return returnValue;
184 185
        }
    }
186 187 188 189 190

    [self willAccessValueForKey:@"title"];
    NSString *ret = [self primitiveValueForKey:@"title"];
    [self didAccessValueForKey:@"title"];

Pierre's avatar
Pierre committed
191 192 193 194 195 196
    return ret;
}

@dynamic seasonNumber;
@dynamic remainingTime;
@dynamic releaseYear;
197 198
@dynamic lastSubtitleTrack;
@dynamic lastAudioTrack;
Pierre's avatar
Pierre committed
199 200 201 202 203 204 205 206 207 208 209
@dynamic playCount;
@dynamic artworkURL;
@dynamic type;
@dynamic title;
@dynamic shortSummary;
@dynamic currentlyWatching;
@dynamic episodeNumber;
@dynamic hasFetchedInfo;
@dynamic noOnlineMetaData;
@dynamic showEpisode;
@dynamic labels;
210
@dynamic tracks;
Pierre's avatar
Pierre committed
211
@dynamic isOnDisk;
212
@dynamic duration;
213 214 215
@dynamic artist;
@dynamic album;
@dynamic albumTrackNumber;
216
@dynamic folderTrackNumber;
217 218
@dynamic genre;
@dynamic albumTrack;
219
@dynamic unread;
220
@dynamic thumbnailName;
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
- (NSNumber *)lastPosition
{
    [self willAccessValueForKey:@"lastPosition"];
    NSNumber *ret = [self primitiveValueForKey:@"lastPosition"];
    [self didAccessValueForKey:@"lastPosition"];
    return ret;
}

- (void)setLastPosition:(NSNumber *)lastPosition
{
    @try {
        [self willChangeValueForKey:@"lastPosition"];
        [self setPrimitiveValue:lastPosition forKey:@"lastPosition"];
        [self didChangeValueForKey:@"lastPosition"];
    }
    @catch (NSException *exception) {
238 239 240 241
        APLog(@"setLastPosition raised exception");
    }
}

242
- (NSString *)path
243
{
244 245 246
    [self willAccessValueForKey:@"path"];
    NSString *ret = [self primitiveValueForKey:@"path"];
    [self didAccessValueForKey:@"path"];
247 248 249
    return ret;
}

250
- (void)setPath:(NSString *)path
251 252
{
    @try {
253 254 255
        [self willChangeValueForKey:@"path"];
        [self setPrimitiveValue:path forKey:@"path"];
        [self didChangeValueForKey:@"path"];
256 257 258
    }
    @catch (NSException *exception) {
        APLog(@"setUrl raised exception");
259 260
    }
}
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
- (void)setUrl:(NSURL *)url {
    NSString *path = url.path;
#if TARGET_OS_IPHONE
    path = [[MLMediaLibrary sharedMediaLibrary] pathRelativeToDocumentsFolderFromAbsolutPath:path];
#endif
    self.path = path;
}

- (NSURL *)url {
    NSString *path = self.path;
#if TARGET_OS_IPHONE
    path = [[MLMediaLibrary sharedMediaLibrary] absolutPathFromPathRelativeToDocumentsFolder:path];
#endif
    return [NSURL fileURLWithPath:path];
}
276

277 278
- (NSString *)thumbnailPath
{
279 280
    MLMediaLibrary *sharedLibrary = [MLMediaLibrary sharedMediaLibrary];
    NSString *folder = [sharedLibrary thumbnailFolderPath];
281 282
    NSString *thumbnailFullName = [[self thumbnailName] stringByAppendingPathExtension:@"png"];
    return [folder stringByAppendingPathComponent:thumbnailFullName];
283 284 285 286
}

- (UIImage *)computedThumbnail
{
287 288 289 290 291 292 293 294 295 296
    NSString *thumbnailPath = [self thumbnailPath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:thumbnailPath])
        return [UIImage imageWithContentsOfFile:[self thumbnailPath]];
    else {
        if (self.isAlbumTrack) {
            if (self.albumTrack.containsArtwork)
                [[MLFileParserQueue sharedFileParserQueue] addFile:self];
        }
    }
    return nil;
297 298
}

299 300 301 302 303 304
- (void)setComputedThumbnailScaledForDevice:(UIImage *)thumbnail
{
    [self setComputedThumbnail:[UIImage scaleImage:thumbnail
                                         toFitRect:(CGRect){CGPointZero, [UIImage preferredThumbnailSizeForDevice]}]];
}

305 306 307 308 309 310 311 312 313 314
- (void)setComputedThumbnail:(UIImage *)image
{
    NSURL *url = [NSURL fileURLWithPath:[self thumbnailPath]];

    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createDirectoryAtPath:[[self thumbnailPath] stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    if (!image) {
        [manager removeItemAtURL:url error:nil];
        return;
    }
315 316 317 318 319 320 321 322

    /* device category 3 or later include hardware accelerated JPEG support so we should prefer
     * the now faster and smaller format.
     * For compatiblity reasons, we also call those JPEG files *.png */
    if ([[MLMediaLibrary sharedMediaLibrary] deviceSpeedCategory] >= 3)
        [UIImageJPEGRepresentation(image, .9) writeToURL:url atomically:YES];
    else
        [UIImagePNGRepresentation(image) writeToURL:url atomically:YES];
323 324 325

    [[NSNotificationCenter defaultCenter] postNotificationName:MLFileThumbnailWasUpdated
                                                        object:self];
326 327
}

328 329 330 331 332 333 334 335 336 337
- (BOOL)isSafe
{
    [self willAccessValueForKey:@"isSafe"];
    NSNumber *ret = [self primitiveValueForKey:@"isSafe"];
    [self didAccessValueForKey:@"isSafe"];
    return [ret boolValue];
}

- (void)setIsSafe:(BOOL)isSafe
{
338 339 340 341 342 343 344 345
    @try {
        [self willChangeValueForKey:@"isSafe"];
        [self setPrimitiveValue:@(isSafe) forKey:@"isSafe"];
        [self didChangeValueForKey:@"isSafe"];
    }
    @catch (NSException *exception) {
        APLog(@"setIsSafe raised exception");
    }
346 347 348 349 350 351 352 353 354 355 356 357
}

- (BOOL)isBeingParsed
{
    [self willAccessValueForKey:@"isBeingParsed"];
    NSNumber *ret = [self primitiveValueForKey:@"isBeingParsed"];
    [self didAccessValueForKey:@"isBeingParsed"];
    return [ret boolValue];
}

- (void)setIsBeingParsed:(BOOL)isBeingParsed
{
358 359 360 361 362 363 364 365
    @try {
        [self willChangeValueForKey:@"isBeingParsed"];
        [self setPrimitiveValue:@(isBeingParsed) forKey:@"isBeingParsed"];
        [self didChangeValueForKey:@"isBeingParsed"];
    }
    @catch (NSException *exception) {
        APLog(@"setIsBeingParsed raised exception");
    }
366 367
}

Pierre's avatar
Pierre committed
368 369 370 371 372 373 374 375 376 377
- (BOOL)thumbnailTimeouted
{
    [self willAccessValueForKey:@"thumbnailTimeouted"];
    NSNumber *ret = [self primitiveValueForKey:@"thumbnailTimeouted"];
    [self didAccessValueForKey:@"thumbnailTimeouted"];
    return [ret boolValue];
}

- (void)setThumbnailTimeouted:(BOOL)thumbnailTimeouted
{
378 379 380 381 382 383 384 385
    @try {
        [self willChangeValueForKey:@"thumbnailTimeouted"];
        [self setPrimitiveValue:@(thumbnailTimeouted) forKey:@"thumbnailTimeouted"];
        [self didChangeValueForKey:@"thumbnailTimeouted"];
    }
    @catch (NSException *exception) {
        APLog(@"setThumbnailTimeouted raised exception");
    }
Pierre's avatar
Pierre committed
386 387
}

388 389 390 391 392 393 394 395 396 397
- (void)willDisplay
{
    [[MLThumbnailerQueue sharedThumbnailerQueue] setHighPriorityForFile:self];
}

- (void)didHide
{
    [[MLThumbnailerQueue sharedThumbnailerQueue] setDefaultPriorityForFile:self];
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
- (NSManagedObject *)videoTrack
{
    NSSet *tracks = [self tracks];
    if (!tracks)
        return nil;
    for (NSManagedObject *track in tracks) {
        if ([[[track entity] name] isEqualToString:@"VideoTrackInformation"])
            return track;
    }
    return nil;
}

- (size_t)fileSizeInBytes
{
    NSFileManager *manager = [NSFileManager defaultManager];
413
    NSDictionary *fileAttributes = [manager attributesOfItemAtPath:[self.url path] error:nil];
414
    NSNumber *fileSize = fileAttributes[NSFileSize];
415 416 417
    return [fileSize unsignedLongLongValue];
}

418
#if TARGET_OS_IPHONE
Felix Paul Kühne's avatar
Felix Paul Kühne committed
419
#ifndef MLKIT_READONLY_TARGET
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
- (CSSearchableItemAttributeSet *)coreSpotlightAttributeSet
{
    if (!SYSTEM_RUNS_IOS9)
        return nil;

    NSString *workString;

    CSSearchableItemAttributeSet* attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:@"public.audiovisual-content"];
    attributeSet.title = self.title;
    attributeSet.metadataModificationDate = [NSDate date];
    attributeSet.addedDate = [NSDate date];
    attributeSet.duration = @(self.duration.intValue / 1000);
    attributeSet.streamable = @(0);
    attributeSet.deliveryType = @(0);
    attributeSet.local = @(1);
    attributeSet.playCount = @(0);

    UIImage *computedThumb = self.computedThumbnail;
    if (computedThumb) {
        attributeSet.thumbnailData = UIImageJPEGRepresentation(computedThumb, .9);
        computedThumb = nil;
    }

    NSArray *tracks = [[self tracks] allObjects];
    NSUInteger trackCount = tracks.count;
    NSMutableArray *codecs = [NSMutableArray new];
    NSMutableArray *languages = [NSMutableArray new];
    for (NSUInteger x = 0; x < trackCount; x++) {
        NSManagedObject *track = tracks[x];
        [codecs addObject:[track valueForKey:@"codec"]];
        NSString *language = [track valueForKey:@"language"];
        if (language != nil)
            [languages addObject:language];

        NSString *trackEntityName = [[track entity] name];
        if ([trackEntityName isEqualToString:@"VideoTrackInformation"]) {
            attributeSet.videoBitRate = [track valueForKey:@"bitrate"];
        } else if ([trackEntityName isEqualToString:@"AudioTrackInformation"]) {
            attributeSet.audioSampleRate = [track valueForKey:@"sampleRate"];
            attributeSet.audioChannelCount = [track valueForKey:@"channelsNumber"];
            attributeSet.audioBitRate = [track valueForKey:@"bitrate"];
        }
    }
    attributeSet.codecs = [NSArray arrayWithArray:codecs];
    attributeSet.languages = [NSArray arrayWithArray:languages];

    workString = self.genre;
    if (workString)
        attributeSet.genre = workString;

    MLAlbumTrack *albumTrack = self.albumTrack;
    if (albumTrack) {
        attributeSet.artist = albumTrack.artist;
        attributeSet.title = albumTrack.title;
        attributeSet.audioTrackNumber = albumTrack.trackNumber;
        MLAlbum *album = albumTrack.album;
        if (album) {
            attributeSet.album = album.name;
        }
        if (attributeSet.genre == nil)
            attributeSet.genre = albumTrack.genre;
    }

    return attributeSet;
}

- (void)updateCoreSpotlightEntry
{
    if (SYSTEM_RUNS_IOS9) {
        /* create final CS item, which will replace the earlier entity */
        CSSearchableItemAttributeSet *attributeSet = [self coreSpotlightAttributeSet];

        CSSearchableItem *item;
        item = [[CSSearchableItem alloc] initWithUniqueIdentifier:self.objectID.URIRepresentation.absoluteString
                                                 domainIdentifier:[[MLMediaLibrary sharedMediaLibrary] applicationGroupIdentifier]
                                                     attributeSet:attributeSet];
        [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:@[item] completionHandler:nil];
    }
}
499
#endif
Felix Paul Kühne's avatar
Felix Paul Kühne committed
500
#endif
501

Pierre's avatar
Pierre committed
502
@end