VLCMediaFileDiscoverer.m 10.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
/*****************************************************************************
 * VLCMediaFileDiscoverer.m
 * VLC for iOS
 *****************************************************************************
 * Copyright (c) 2013 VideoLAN. All rights reserved.
 * $Id$
 *
 * Authors: Gleb Pinigin <gpinigin # gmail.com>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
Gleb Pinigin's avatar
Gleb Pinigin committed
12
13
14

#import "VLCMediaFileDiscoverer.h"
#import "NSString+SupportedMedia.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
15
16
#import "VLCAppDelegate.h"
#import "VLCPlaylistViewController.h"
Gleb Pinigin's avatar
Gleb Pinigin committed
17
18
19

const float MediaTimerInterval = 2.f;

20
@interface VLCMediaFileDiscoverer () {
Gleb Pinigin's avatar
Gleb Pinigin committed
21
    NSMutableArray *_observers;
22
    dispatch_source_t _directorySource;
Gleb Pinigin's avatar
Gleb Pinigin committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

    NSString *_directoryPath;
    NSArray *_directoryFiles;
    NSMutableDictionary *_addedFilesMapping;
    NSTimer *_addMediaTimer;
}

@end

@implementation VLCMediaFileDiscoverer

- (id)init
{
    self = [super init];
    if (self) {
        _observers = [NSMutableArray array];
        _addedFilesMapping = [NSMutableDictionary dictionary];
    }

    return self;
}

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static VLCMediaFileDiscoverer *instance;
    dispatch_once(&onceToken, ^{
        instance = [VLCMediaFileDiscoverer new];
    });

    return instance;
}

#pragma mark - observation

- (void)addObserver:(id<VLCMediaFileDiscovererDelegate>)delegate
{
    [_observers addObject:delegate];
}

- (void)removeObserver:(id<VLCMediaFileDiscovererDelegate>)delegate
{
    [_observers removeObject:delegate];
}

- (void)notifyFileDeleted:(NSString *)fileName
{
    for (id<VLCMediaFileDiscovererDelegate> delegate in _observers) {
        if ([delegate respondsToSelector:@selector(mediaFileDeleted:)]) {
            [delegate mediaFileDeleted:[self filePath:fileName]];
        }
    }
}

- (void)notifyFileAdded:(NSString *)fileName loading:(BOOL)isLoading
{
    for (id<VLCMediaFileDiscovererDelegate> delegate in _observers) {
        if ([delegate respondsToSelector:@selector(mediaFileAdded:loading:)]) {
            [delegate mediaFileAdded:[self filePath:fileName] loading:isLoading];
        }
    }
}

- (void)notifySizeChanged:(NSString *)fileName size:(unsigned long long)size
{
    for (id<VLCMediaFileDiscovererDelegate> delegate in _observers) {
        if ([delegate respondsToSelector:@selector(mediaFileChanged:size:)]) {
            [delegate mediaFileChanged:[self filePath:fileName] size:size];
        }
    }
}

#pragma mark - discovering

Felix Paul Kühne's avatar
Felix Paul Kühne committed
97
- (void)startDiscovering
Gleb Pinigin's avatar
Gleb Pinigin committed
98
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
99
100
    _directoryPath = [self directoryPath];
    _directoryFiles = [self directoryFiles];
Gleb Pinigin's avatar
Gleb Pinigin committed
101

Felix Paul Kühne's avatar
Felix Paul Kühne committed
102
    int const folderDescriptor = open([_directoryPath fileSystemRepresentation], O_EVTONLY);
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    _directorySource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, folderDescriptor,
                                              DISPATCH_VNODE_WRITE, DISPATCH_TARGET_QUEUE_DEFAULT);

    dispatch_source_set_event_handler(_directorySource, ^(){
        unsigned long const data = dispatch_source_get_data(_directorySource);
        if (data & DISPATCH_VNODE_WRITE) {
            // Do all the work on the main thread,
            // including timer scheduling, notifications delivering
            dispatch_async(dispatch_get_main_queue(), ^{
                [self directoryDidChange];
            });
        }
    });

    dispatch_source_set_cancel_handler(_directorySource, ^(){
        close(folderDescriptor);
    });

    dispatch_resume(_directorySource);
Gleb Pinigin's avatar
Gleb Pinigin committed
122
123
124
125
}

- (void)stopDiscovering
{
126
    dispatch_source_cancel(_directorySource);
Gleb Pinigin's avatar
Gleb Pinigin committed
127
128
129
130
131
132
133
134

    [self invalidateTimer];
}

#pragma mark -

- (NSArray *)directoryFiles
{
135
136
    NSArray *foundFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:_directoryPath
                                                                              error:nil];
Gleb Pinigin's avatar
Gleb Pinigin committed
137
138
139
140
141
142
143
144
145
146
    return foundFiles;
}

- (NSString *)filePath:(NSString *)fileName
{
    return [_directoryPath stringByAppendingPathComponent:fileName];
}

#pragma mark - directory watcher delegate

147
148
149
150
151
152
153
- (NSString *)directoryPath
{
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *directoryPath = searchPaths[0];
    return directoryPath;
}

154
- (void)directoryDidChange
Gleb Pinigin's avatar
Gleb Pinigin committed
155
156
157
158
159
160
161
{
    NSArray *foundFiles = [self directoryFiles];

    if (_directoryFiles.count > foundFiles.count) { // File was deleted
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"not (self in %@)", foundFiles];
        NSArray *deletedFiles = [_directoryFiles filteredArrayUsingPredicate:filterPredicate];

162
        for (NSString *fileName in deletedFiles)
Gleb Pinigin's avatar
Gleb Pinigin committed
163
164
165
            [self notifyFileDeleted:fileName];
    } else if (_directoryFiles.count < foundFiles.count) { // File was added
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"not (self in %@)", _directoryFiles];
166
        NSMutableArray *addedFiles = [NSMutableArray arrayWithArray:[foundFiles filteredArrayUsingPredicate:filterPredicate]];
Gleb Pinigin's avatar
Gleb Pinigin committed
167
168

        for (NSString *fileName in addedFiles) {
169
            if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
Gleb Pinigin's avatar
Gleb Pinigin committed
170
171
                [_addedFilesMapping setObject:@(0) forKey:fileName];
                [self notifyFileAdded:fileName loading:YES];
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
            } else {
                BOOL isDirectory = NO;
                NSString *directoryPath = [self directoryPath];
                NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
                BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];

                // add folders
                if (exists && isDirectory) {
                    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
                    for (NSString* file in files) {
                        NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:file];
                        isDirectory = NO;
                        exists = [[NSFileManager defaultManager] fileExistsAtPath:fullFilePath isDirectory:&isDirectory];
                        //only add folders or files in folders
                        if ((exists && isDirectory) || ![filePath.lastPathComponent isEqualToString:@"Documents"]) {
                            NSString *folderpath = [filePath stringByReplacingOccurrencesOfString:directoryPath withString:@""];
                            if (![folderpath isEqualToString:@""]) {
                                folderpath = [folderpath stringByAppendingString:@"/"];
                            }
                            NSString *path = [folderpath stringByAppendingString:file];
                            [_addedFilesMapping setObject:@(0) forKey:path];
                            [self notifyFileAdded:path loading:YES];
                        }
                    }
                }
Gleb Pinigin's avatar
Gleb Pinigin committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
            }
        }

        if (![_addMediaTimer isValid]) {
            _addMediaTimer = [NSTimer scheduledTimerWithTimeInterval:MediaTimerInterval
                                          target:self selector:@selector(addFileTimerFired)
                                                            userInfo:nil repeats:YES];
        }
    }

    _directoryFiles = foundFiles;
}

#pragma mark - media timer

- (void)addFileTimerFired
{
    NSArray *allKeys = [_addedFilesMapping allKeys];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    for (NSString *fileName in allKeys) {
        NSString *filePath = [self filePath:fileName];
        if (![fileManager fileExistsAtPath:filePath]) {
            [_addedFilesMapping removeObjectForKey:fileName];
            continue;
        }

        NSNumber *prevFetchedSize = [_addedFilesMapping objectForKey:fileName];

        NSDictionary *attribs = [fileManager attributesOfItemAtPath:filePath error:nil];
        NSNumber *updatedSize = [attribs objectForKey:NSFileSize];
        if (!updatedSize)
            continue;

        [self notifySizeChanged:fileName size:[updatedSize unsignedLongLongValue]];

        if ([prevFetchedSize compare:updatedSize] == NSOrderedSame) {
            [_addedFilesMapping removeObjectForKey:fileName];
            [self notifyFileAdded:fileName loading:NO];

        } else
            [_addedFilesMapping setObject:updatedSize forKey:fileName];
    }

    if (_addedFilesMapping.count == 0)
        [self invalidateTimer];
}

- (void)invalidateTimer
{
    [_addMediaTimer invalidate];
    _addMediaTimer = nil;
}

Felix Paul Kühne's avatar
Felix Paul Kühne committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#pragma mark - media list management

- (void)updateMediaList
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
        return;
    }

    NSString *directoryPath = [self directoryPath];
    NSMutableArray *foundFiles = [NSMutableArray arrayWithArray:[[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil]];
    NSMutableArray *filePaths = [NSMutableArray array];
    NSURL *fileURL;
    while (foundFiles.count) {
        NSString *fileName = foundFiles.firstObject;
        NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
        [foundFiles removeObject:fileName];

        if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
            [filePaths addObject:filePath];

            /* exclude media files from backup (QA1719) */
            fileURL = [NSURL fileURLWithPath:filePath];
            [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
        } else {
            BOOL isDirectory = NO;
            BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];

            // add folders
            if (exists && isDirectory) {
                NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil];
                for (NSString* file in files) {
                    NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:file];
                    isDirectory = NO;
                    exists = [[NSFileManager defaultManager] fileExistsAtPath:fullFilePath isDirectory:&isDirectory];
                    //only add folders or files in folders
                    if ((exists && isDirectory) || ![filePath.lastPathComponent isEqualToString:@"Documents"]) {
                        NSString *folderpath = [filePath stringByReplacingOccurrencesOfString:directoryPath withString:@""];
                        if (![folderpath isEqualToString:@""]) {
                            folderpath = [folderpath stringByAppendingString:@"/"];
                        }
                        NSString *path = [folderpath stringByAppendingString:file];
                        [foundFiles addObject:path];
                    }
                }
            }
        }
    }
    [[MLMediaLibrary sharedMediaLibrary] addFilePaths:filePaths];
    [[(VLCAppDelegate *)[UIApplication sharedApplication].delegate playlistViewController] updateViewContents];
}

Gleb Pinigin's avatar
Gleb Pinigin committed
303
@end