VLCHTTPConnection.m 27.6 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * VLCHTTPConnection.m
 * VLC for iOS
 *****************************************************************************
5
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
6 7 8 9 10 11 12
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
 *          Jean-Baptiste Kempf <jb # videolan.org>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
13 14 15 16 17 18 19 20 21

#import "VLCAppDelegate.h"
#import "VLCHTTPConnection.h"
#import "HTTPConnection.h"
#import "MultipartFormDataParser.h"
#import "HTTPMessage.h"
#import "HTTPDataResponse.h"
#import "HTTPFileResponse.h"
#import "MultipartMessageHeaderField.h"
22
#import "VLCHTTPUploaderController.h"
23
#import "HTTPDynamicFileResponse.h"
24
#import "VLCThumbnailsCache.h"
25
#import "NSString+SupportedMedia.h"
26
#import "UIDevice+VLC.h"
27 28 29

@interface VLCHTTPConnection()
{
30 31 32
    MultipartFormDataParser *_parser;
    NSFileHandle *_storeFile;
    NSString *_filepath;
33 34
    UInt64 _contentLength;
    UInt64 _receivedContent;
35
}
36 37 38

@property (nonatomic) VLCHTTPUploaderController *uploadController;

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 100
@end

@implementation VLCHTTPConnection

- (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
{
    // Add support for POST
    if ([method isEqualToString:@"POST"]) {
        if ([path isEqualToString:@"/upload.json"])
            return YES;
    }

    return [super supportsMethod:method atPath:path];
}

- (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
{
    // Inform HTTP server that we expect a body to accompany a POST request
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
        // here we need to make sure, boundary is set in header
        NSString* contentType = [request headerField:@"Content-Type"];
        NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
        if (NSNotFound == paramsSeparator)
            return NO;

        if (paramsSeparator >= contentType.length - 1)
            return NO;

        NSString* type = [contentType substringToIndex:paramsSeparator];
        if (![type isEqualToString:@"multipart/form-data"]) {
            // we expect multipart/form-data content type
            return NO;
        }

        // enumerate all params in content-type, and find boundary there
        NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
        for (NSString* param in params) {
            paramsSeparator = [param rangeOfString:@"="].location;
            if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
                continue;

            NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
            NSString* paramValue = [param substringFromIndex:paramsSeparator+1];

            if ([paramName isEqualToString: @"boundary"])
                // let's separate the boundary from content-type, to make it more handy to handle
                [request setHeaderField:@"boundary" value:paramValue];
        }
        // check if boundary specified
        if (nil == [request headerField:@"boundary"])
            return NO;

        return YES;
    }
    return [super expectsRequestBodyFromMethod:method atPath:path];
}

- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
{
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
        return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
    }
101 102
    if ([path hasPrefix:@"/download/"]) {
        NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
103 104 105
        HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
        fileResponse.contentType = @"application/octet-stream";
        return fileResponse;
106
    }
107 108 109 110 111
    if ([path hasPrefix:@"/thumbnail"]) {
        NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];

        NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
112 113 114 115 116
        if (moc) {
            NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
            if (psc) {
                NSManagedObject *mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];

117
                NSData *theData =  UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo]);
118 119 120 121 122 123
                if (theData) {
                    HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
                    dataResponse.contentType = @"image/png";
                    return dataResponse;
                }
            }
124
        }
125
    }
126 127 128
    NSString *filePath = [self filePathForURI:path];
    NSString *documentRoot = [config documentRoot];
    NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
129
    BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
130

131
    if ([relativePath isEqualToString:@"/index.html"] || shouldReturnLibVLCXML) {
132 133 134
        NSMutableArray *allMedia = [[NSMutableArray alloc] init];

        /* add all albums */
135 136
        NSArray *allAlbums = [MLAlbum allAlbums];
        for (MLAlbum *album in allAlbums) {
137 138
            if (album.name.length > 0 && album.tracks.count > 1)
                [allMedia addObject:album];
139
        }
140 141

        /* add all shows */
142 143
        NSArray *allShows = [MLShow allShows];
        for (MLShow *show in allShows) {
144 145
            if (show.name.length > 0 && show.episodes.count > 1)
                [allMedia addObject:show];
146
        }
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

        /* add all folders*/
        NSArray *allFolders = [MLLabel allLabels];
        for (MLLabel *folder in allFolders)
            [allMedia addObject:folder];

        /* add all remaining files */
        NSArray *allFiles = [MLFile allFiles];
        for (MLFile *file in allFiles) {
            if (file.labels.count > 0) continue;

            if (!file.isShowEpisode && !file.isAlbumTrack)
                [allMedia addObject:file];
            else if (file.isShowEpisode) {
                if (file.showEpisode.show.episodes.count < 2)
                    [allMedia addObject:file];
            } else if (file.isAlbumTrack) {
                if (file.albumTrack.album.tracks.count < 2)
                    [allMedia addObject:file];
            }
        }

        NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:allMedia.count];
170 171 172
        NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:allMedia.count];
        self.uploadController = [[VLCHTTPUploaderController alloc] init];
        NSString *hostName = [self.uploadController hostname];
173
        NSString *pathLibrary = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
174
        NSString *duration;
175 176

        for (NSManagedObject *mo in allMedia) {
177
            if ([mo isKindOfClass:[MLFile class]]) {
178
                duration = [[VLCTime timeWithNumber:[(MLFile *)mo duration]] stringValue];
179 180
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
181
                                        <a href=\"download/%@\" class=\"inner\"> \
182 183 184
                                        <div class=\"down icon\"></div> \
                                        <div class=\"infos\"> \
                                        <span class=\"first-line\">%@</span> \
185
                                        <span class=\"second-line\">%@ - %0.2f MB</span> \
186 187 188 189 190
                                        </div> \
                                        </a> \
                                        </div>",
                                        mo.objectID.URIRepresentation,
                                        [[(MLFile *)mo url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
191 192
                                        [(MLFile *)mo title],
                                        duration, (float)([(MLFile *)mo fileSizeInBytes] / 1e6)]];
193
                if (shouldReturnLibVLCXML) {
194 195 196 197 198
                    NSString *pathSub = [self _checkSubtitleFound:[(MLFile *)mo url]];
                    if (![pathSub isEqualToString:@""])
                        pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
                    [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", [(MLFile *)mo title], hostName, pathLibrary, [[NSString stringWithFormat:@"%@", mo.objectID.URIRepresentation] lastPathComponent], duration, [(MLFile *)mo fileSizeInBytes], hostName, [[(MLFile *)mo url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], pathSub]];
                }
199
            }
200 201
            else if ([mo isKindOfClass:[MLShow class]]) {
                NSArray *episodes = [(MLShow *)mo sortedEpisodes];
202 203
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
204
                                        <a href=\"#\" class=\"inner folder\"> \
205 206 207
                                        <div class=\"open icon\"></div> \
                                        <div class=\"infos\"> \
                                        <span class=\"first-line\">%@</span> \
Felix Paul Kühne's avatar
Felix Paul Kühne committed
208
                                        <span class=\"second-line\">%lu items</span> \
209 210 211 212
                                        </div> \
                                        </a> \
                                        <div class=\"content\">",
                                        mo.objectID.URIRepresentation,
213
                                        [(MLShow *)mo name],
Felix Paul Kühne's avatar
Felix Paul Kühne committed
214
                                        (unsigned long)[episodes count]]];
215
                for (MLShowEpisode *showEp in episodes) {
216
                    duration = [[VLCTime timeWithNumber:[(MLFile *)[[showEp files] anyObject] duration]] stringValue];
217 218
                    [mediaInHtml addObject:[NSString stringWithFormat:
                                            @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
219
                                            <a href=\"download/%@\" class=\"inner\"> \
220 221 222
                                            <div class=\"down icon\"></div> \
                                            <div class=\"infos\"> \
                                            <span class=\"first-line\">S%@E%@ - %@</span> \
223
                                            <span class=\"second-line\">%@ - %0.2f MB</span> \
224 225 226 227 228 229 230
                                            </div> \
                                            </a> \
                                            </div>",
                                            showEp.objectID.URIRepresentation,
                                            [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
                                            showEp.seasonNumber,
                                            showEp.episodeNumber,
231 232
                                            showEp.name,
                                            duration, (float)([(MLFile *)[[showEp files] anyObject] fileSizeInBytes] / 1e6)]];
233
                    if (shouldReturnLibVLCXML) {
234 235 236 237 238
                        NSString *pathSub = [self _checkSubtitleFound:[(MLFile *)[[showEp files] anyObject] url]];
                        if (![pathSub isEqualToString:@""])
                            pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
                        [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@ - S%@E%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", [(MLShow *)mo name], showEp.seasonNumber, showEp.episodeNumber, hostName, pathLibrary, [[NSString stringWithFormat:@"%@", showEp.objectID.URIRepresentation] lastPathComponent], duration, [(MLFile *)[[showEp files] anyObject] fileSizeInBytes], hostName, [[(MLFile *)[[showEp files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], pathSub]];
                    }
239
                }
240
                [mediaInHtml addObject:@"</div></div>"];
241 242
            } else if ([mo isKindOfClass:[MLLabel class]]) {
                NSArray *folderItems = [(MLLabel *)mo sortedFolderItems];
243 244
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
245
                                        <a href=\"#\" class=\"inner folder\"> \
246 247 248
                                        <div class=\"open icon\"></div> \
                                        <div class=\"infos\"> \
                                        <span class=\"first-line\">%@</span> \
Felix Paul Kühne's avatar
Felix Paul Kühne committed
249
                                        <span class=\"second-line\">%lu items</span> \
250 251 252 253
                                        </div> \
                                        </a> \
                                        <div class=\"content\">",
                                        mo.objectID.URIRepresentation,
254
                                        [(MLLabel *)mo name],
Felix Paul Kühne's avatar
Felix Paul Kühne committed
255
                                        (unsigned long)[folderItems count]]];
256
                for (MLFile *file in folderItems) {
257
                    duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
258 259
                    [mediaInHtml addObject:[NSString stringWithFormat:
                                            @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
260
                                            <a href=\"download/%@\" class=\"inner\"> \
261 262 263
                                            <div class=\"down icon\"></div> \
                                            <div class=\"infos\"> \
                                            <span class=\"first-line\">%@</span> \
264
                                            <span class=\"second-line\">%@ - %0.2f MB</span> \
265 266 267 268 269
                                            </div> \
                                            </a> \
                                            </div>",
                                            file.objectID.URIRepresentation,
                                            [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
270 271
                                            file.title,
                                            duration, (float)([file fileSizeInBytes] / 1e6)]];
272
                    if (shouldReturnLibVLCXML) {
273 274 275 276 277
                        NSString *pathSub = [self _checkSubtitleFound:[file url]];
                        if (![pathSub isEqualToString:@""])
                            pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
                        [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"%@\"/>", file.title, hostName, pathLibrary, [[NSString stringWithFormat:@"%@", file.objectID.URIRepresentation] lastPathComponent], duration, [file fileSizeInBytes], hostName, [[file url] stringByReplacingOccurrencesOfString:@"file://"withString:@""], pathSub]];
                    }
278
                }
279
                [mediaInHtml addObject:@"</div></div>"];
280 281
            } else if ([mo isKindOfClass:[MLAlbum class]]) {
                NSArray *albumTracks = [(MLAlbum *)mo sortedTracks];
282 283
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
284
                                        <a href=\"#\" class=\"inner folder\"> \
285 286 287
                                        <div class=\"open icon\"></div> \
                                        <div class=\"infos\"> \
                                        <span class=\"first-line\">%@</span> \
Felix Paul Kühne's avatar
Felix Paul Kühne committed
288
                                        <span class=\"second-line\">%lu items</span> \
289 290 291 292
                                        </div> \
                                        </a> \
                                        <div class=\"content\">",
                                        mo.objectID.URIRepresentation,
293
                                        [(MLAlbum *)mo name],
Felix Paul Kühne's avatar
Felix Paul Kühne committed
294
                                        (unsigned long)[albumTracks count]]];
295
                for (MLAlbumTrack *track in albumTracks) {
296
                    duration = [[VLCTime timeWithNumber:[(MLFile *)[[track files] anyObject] duration]] stringValue];
297 298
                    [mediaInHtml addObject:[NSString stringWithFormat:
                                            @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
299
                                            <a href=\"download/%@\" class=\"inner\"> \
300 301 302
                                            <div class=\"down icon\"></div> \
                                            <div class=\"infos\"> \
                                            <span class=\"first-line\">%@</span> \
303
                                            <span class=\"second-line\">%@ - %0.2f MB</span> \
304 305 306 307 308
                                            </div> \
                                            </a> \
                                            </div>",
                                            track.objectID.URIRepresentation,
                                            [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""],
309 310
                                            track.title,
                                            duration, (float)([(MLFile *)[[track files] anyObject] fileSizeInBytes] / 1e6)]];
311
                    if (shouldReturnLibVLCXML)
312
                        [mediaInXml addObject:[NSString stringWithFormat:@"<Media title=\"%@\" thumb=\"http://%@/download/%@/Thumbnails/File/%@.png\" duration=\"%@\" size=\"%li\" pathfile=\"http://%@/download/%@\" pathSubtitle=\"\"/>", track.title, hostName, pathLibrary, [[NSString stringWithFormat:@"%@", track.objectID.URIRepresentation] lastPathComponent], duration, [(MLFile *)[[track files] anyObject] fileSizeInBytes], hostName, [[(MLFile *)[[track files] anyObject] url] stringByReplacingOccurrencesOfString:@"file://"withString:@""]]];
313
                }
314
                [mediaInHtml addObject:@"</div></div>"];
315
            }
316
        }
317

318
        NSString *deviceModel = [[UIDevice currentDevice] model];
319
        NSDictionary *replacementDict;
320
        HTTPDynamicFileResponse *fileResponse;
321

322
        if (shouldReturnLibVLCXML) {
323 324 325
            replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
                                @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
                                @"LIB_TITLE" : [[UIDevice currentDevice] name]};
326 327 328 329 330 331 332

            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"application/xml";
        } else {
333 334 335 336 337 338
            replacementDict = @{@"FILES" : [mediaInHtml componentsJoinedByString:@" "],
                                @"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil),
                                @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
                                @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil), deviceModel],
                                @"WEBINTF_DOWNLOADFILES" : NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil),
                                @"WEBINTF_DOWNLOADFILES_LONG" : [NSString stringWithFormat: NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil), deviceModel]};
339 340 341 342 343 344
            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"text/html";
        }
345

346
        return fileResponse;
347
    } else if ([relativePath isEqualToString:@"/style.css"]) {
348
        NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
349 350 351 352 353 354
        HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                                                    forConnection:self
                                                                                        separator:@"%%"
                                                                            replacementDictionary:replacementDict];
        fileResponse.contentType = @"text/css";
        return fileResponse;
355
    }
356

357 358 359 360 361 362 363 364 365 366
    return [super httpResponseForMethod:method URI:path];
}

- (void)prepareForBodyWithSize:(UInt64)contentLength
{
    // set up mime parser
    NSString* boundary = [request headerField:@"boundary"];
    _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
    _parser.delegate = self;

367 368
    APLog(@"expecting file of size %lli kB", contentLength / 1024);
    _contentLength = contentLength;
369 370 371 372 373 374 375
}

- (void)processBodyData:(NSData *)postDataChunk
{
    /* append data to the parser. It will invoke callbacks to let us handle
     * parsed data. */
    [_parser appendData:postDataChunk];
376

377
    _receivedContent += postDataChunk.length;
378

379
    APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
}

//-----------------------------------------------------------------
#pragma mark multipart form data parser delegate


- (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
{
    /* in this sample, we are not interested in parts, other then file parts.
     * check content disposition to find out filename */

    MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
    NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];

    if ((nil == filename) || [filename isEqualToString: @""]) {
        // it's either not a file part, or
        // an empty form sent. we won't handle it.
        return;
    }

400
    // create the path where to store the media temporarily
401
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
402
    NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
403
    NSFileManager *fileManager = [NSFileManager defaultManager];
404 405

    BOOL isDir = YES;
406
    if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ])
407
        [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
408

409
    _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
410

411 412 413 414 415 416 417 418 419
    NSNumber *freeSpace = [[UIDevice currentDevice] freeDiskspace];
    if (_contentLength >= freeSpace.longLongValue) {
        /* avoid deadlock since we are on a background thread */
        [self performSelectorOnMainThread:@selector(notifyUserAboutEndOfFreeStorage:) withObject:filename waitUntilDone:NO];
        [self handleResourceNotFound];
        [self stop];
        return;
    }

420
    APLog(@"Saving file to %@", _filepath);
421
    if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
422
        APLog(@"Could not create directory at path: %@", _filepath);
423

424
    if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
425
        APLog(@"Could not create file at path: %@", _filepath);
426

427
    _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
428
    [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
429
    [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
430 431
}

432 433 434 435 436 437 438 439 440 441 442 443 444
- (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
                                                    message:[NSString stringWithFormat:
                                                             NSLocalizedString(@"DISK_FULL_FORMAT", nil),
                                                             filename,
                                                             [[UIDevice currentDevice] model]]
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
                                          otherButtonTitles:nil];
    [alert show];
}

445 446 447
- (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
{
    // here we just write the output from parser to the file.
448 449 450 451 452 453 454 455 456 457 458 459 460
    if (_storeFile) {
        @try {
            [_storeFile writeData:data];
        }
        @catch (NSException *exception) {
            APLog(@"File to write further data because storage is full.");
            [_storeFile closeFile];
            _storeFile = nil;
            /* don't block */
            [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
        }
    }

461 462 463 464 465
}

- (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
{
    // as the file part is over, we close the file.
466
    APLog(@"closing file");
467 468 469 470
    [_storeFile closeFile];
    _storeFile = nil;
}

471
- (BOOL)shouldDie
472
{
473 474 475
    if (_filepath) {
        if (_filepath.length > 0)
            [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
476
    }
477
    return [super shouldDie];
478 479
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
#pragma mark subtitle

- (NSMutableArray *)_listOfSubtitle
{
    NSMutableArray *listOfSubtitle = [[NSMutableArray alloc] init];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSArray *allfiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSString *filePath;
    for (int count = 0; count < allfiles.count; count++) {
        filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allfiles[count]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
        if ([filePath isSupportedSubtitleFormat])
            [listOfSubtitle addObject:filePath];
    }
    return listOfSubtitle;
}

- (NSString *)_checkSubtitleFound:(NSString *)fileURL
{
    NSString *subtitlePath = @"";
    NSString *fileName = [[fileURL lastPathComponent] stringByDeletingPathExtension];
    NSMutableArray *listOfSubtitle = [[NSMutableArray alloc] init];
    listOfSubtitle = [self _listOfSubtitle];
    NSString *fileSub;
    for (int count = 0; count < listOfSubtitle.count; count++) {
        fileSub = [NSString stringWithFormat:@"%@", listOfSubtitle[count]];
        if ([fileSub rangeOfString:fileName].location != NSNotFound)
            subtitlePath = [listOfSubtitle objectAtIndex:count];
    }
    return subtitlePath;
}

511
@end