VLCMediaFileDiscoverer.m 6.49 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
15
16
17

#import "VLCMediaFileDiscoverer.h"
#import "NSString+SupportedMedia.h"

const float MediaTimerInterval = 2.f;

18
@interface VLCMediaFileDiscoverer () {
Gleb Pinigin's avatar
Gleb Pinigin committed
19
    NSMutableArray *_observers;
20
    dispatch_source_t _directorySource;
Gleb Pinigin's avatar
Gleb Pinigin committed
21
22
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
97
98
99

    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

- (void)startDiscovering:(NSString *)directoryPath
{
    _directoryPath = directoryPath;
     _directoryFiles = [self directoryFiles];

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
    int const folderDescriptor = open([directoryPath fileSystemRepresentation], O_EVTONLY);
    _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
120
121
122
123
}

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

    [self invalidateTimer];
}

#pragma mark -

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

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

#pragma mark - directory watcher delegate

145
- (void)directoryDidChange
Gleb Pinigin's avatar
Gleb Pinigin committed
146
147
148
149
150
151
152
{
    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];

153
        for (NSString *fileName in deletedFiles)
Gleb Pinigin's avatar
Gleb Pinigin committed
154
155
156
157
158
159
            [self notifyFileDeleted:fileName];
    } else if (_directoryFiles.count < foundFiles.count) { // File was added
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"not (self in %@)", _directoryFiles];
        NSArray *addedFiles = [foundFiles filteredArrayUsingPredicate:filterPredicate];

        for (NSString *fileName in addedFiles) {
160
            if ([fileName isSupportedMediaFormat] || [fileName isSupportedAudioMediaFormat]) {
Gleb Pinigin's avatar
Gleb Pinigin committed
161
162
163
164
165
166
167
168
169
170
171
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
                [_addedFilesMapping setObject:@(0) forKey:fileName];
                [self notifyFileAdded:fileName loading:YES];
            }
        }

        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;
}

@end