VLCHTTPConnection.m 28 KB
Newer Older
1 2 3 4
/*****************************************************************************
 * VLCHTTPConnection.m
 * VLC for iOS
 *****************************************************************************
5
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
6 7 8
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne # videolan.org>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
9 10
 *          Pierre Sagaspe <pierre.sagaspe # me.com>
 *          Carola Nitz <caro # videolan.org>
11 12 13 14
 *          Jean-Baptiste Kempf <jb # videolan.org>
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
15

Felix Paul Kühne's avatar
Felix Paul Kühne committed
16
#import "VLCActivityManager.h"
17 18 19 20 21 22
#import "VLCHTTPConnection.h"
#import "MultipartFormDataParser.h"
#import "HTTPMessage.h"
#import "HTTPDataResponse.h"
#import "HTTPFileResponse.h"
#import "MultipartMessageHeaderField.h"
23
#import "HTTPDynamicFileResponse.h"
24
#import "VLCThumbnailsCache.h"
25
#import "NSString+SupportedMedia.h"
26
#import "UIDevice+VLC.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
27
#import "VLCHTTPUploaderController.h"
28 29 30

@interface VLCHTTPConnection()
{
31 32 33
    MultipartFormDataParser *_parser;
    NSFileHandle *_storeFile;
    NSString *_filepath;
34 35
    UInt64 _contentLength;
    UInt64 _receivedContent;
36 37 38 39 40 41 42 43
}
@end

@implementation VLCHTTPConnection

- (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
{
    // Add support for POST
Felix Paul Kühne's avatar
Felix Paul Kühne committed
44
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
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
            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:@";"];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
71 72 73
        NSUInteger count = params.count;
        for (NSUInteger i = 0; i < count; i++) {
            NSString *param = params[i];
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
            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
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
96
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
97
        return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
98

99 100
    if ([path hasPrefix:@"/download/"]) {
        NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
101 102 103
        HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
        fileResponse.contentType = @"application/octet-stream";
        return fileResponse;
104
    }
105 106 107 108 109
    if ([path hasPrefix:@"/thumbnail"]) {
        NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];

        NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
110 111 112
        if (moc) {
            NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
            if (psc) {
113 114 115 116 117 118 119
                NSManagedObject *mo = nil;
                @try {
                    mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
                }@catch (NSException *exeption) {
                    // somebody gave us a malformed or stale URIRepresentation
                }

Felix Paul Kühne's avatar
Felix Paul Kühne committed
120 121 122 123 124 125 126 127 128 129 130 131
                NSData *theData;
                NSString *contentType;

                /* devices category 3 and faster include HW accelerated JPEG encoding
                 * so we can make our transfers faster by using waaay smaller images */
                if ([[UIDevice currentDevice] speedCategory] < 3) {
                    theData = UIImagePNGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo]);
                    contentType = @"image/png";
                } else {
                    theData = UIImageJPEGRepresentation([VLCThumbnailsCache thumbnailForManagedObject:mo], .9);
                    contentType = @"image/jpg";
                }
132 133 134

                if (theData) {
                    HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
135
                    dataResponse.contentType = contentType;
136 137 138
                    return dataResponse;
                }
            }
139
        }
140
    }
141 142 143
    NSString *filePath = [self filePathForURI:path];
    NSString *documentRoot = [config documentRoot];
    NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
144
    BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
145

146
    if ([relativePath isEqualToString:@"/index.html"] || shouldReturnLibVLCXML) {
147 148 149
        NSMutableArray *allMedia = [[NSMutableArray alloc] init];

        /* add all albums */
150 151
        NSArray *allAlbums = [MLAlbum allAlbums];
        for (MLAlbum *album in allAlbums) {
152 153
            if (album.name.length > 0 && album.tracks.count > 1)
                [allMedia addObject:album];
154
        }
155 156

        /* add all shows */
157 158
        NSArray *allShows = [MLShow allShows];
        for (MLShow *show in allShows) {
159 160
            if (show.name.length > 0 && show.episodes.count > 1)
                [allMedia addObject:show];
161
        }
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

        /* 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];
            }
        }

Felix Paul Kühne's avatar
Felix Paul Kühne committed
184 185 186
        NSUInteger mediaCount = allMedia.count;
        NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
        NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
187
        NSString *hostName = [[VLCHTTPUploaderController sharedInstance] hostname];
188
        NSString *duration;
189 190

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

Felix Paul Kühne's avatar
Felix Paul Kühne committed
338 339
        UIDevice *currentDevice = [UIDevice currentDevice];
        NSString *deviceModel = [currentDevice model];
340
        NSDictionary *replacementDict;
341
        HTTPDynamicFileResponse *fileResponse;
342

343
        if (shouldReturnLibVLCXML) {
344 345
            replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
                                @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
Felix Paul Kühne's avatar
Felix Paul Kühne committed
346
                                @"LIB_TITLE" : [currentDevice name]};
347 348 349 350 351 352 353

            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"application/xml";
        } else {
354 355 356 357 358 359
            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]};
360 361 362 363 364 365
            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"text/html";
        }
366

367
        return fileResponse;
368
    } else if ([relativePath isEqualToString:@"/style.css"]) {
369
        NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
370 371 372 373 374 375
        HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                                                    forConnection:self
                                                                                        separator:@"%%"
                                                                            replacementDictionary:replacementDict];
        fileResponse.contentType = @"text/css";
        return fileResponse;
376
    }
377

378 379 380 381 382 383 384 385 386 387
    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;

388 389
    APLog(@"expecting file of size %lli kB", contentLength / 1024);
    _contentLength = contentLength;
390 391 392 393 394 395 396
}

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

398
    _receivedContent += postDataChunk.length;
399

400
    APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
}

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

421
    // create the path where to store the media temporarily
422
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
423
    NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
424
    NSFileManager *fileManager = [NSFileManager defaultManager];
425 426

    BOOL isDir = YES;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
427
    if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir])
428
        [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
429

430
    _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
431

432 433 434 435 436 437 438 439 440
    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;
    }

441
    APLog(@"Saving file to %@", _filepath);
442
    if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
443
        APLog(@"Could not create directory at path: %@", _filepath);
444

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

448
    _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
449 450 451 452

    VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
    [activityManager networkActivityStarted];
    [activityManager disableIdleTimer];
453 454
}

455 456
- (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
{
457 458 459 460 461 462 463 464
    VLCAlertView *alert = [[VLCAlertView 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];
465 466 467
    [alert show];
}

468 469 470
- (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
{
    // here we just write the output from parser to the file.
471 472 473 474 475 476 477 478 479 480 481 482 483
    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];
        }
    }

484 485 486 487 488
}

- (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
{
    // as the file part is over, we close the file.
489
    APLog(@"closing file");
490 491 492 493
    [_storeFile closeFile];
    _storeFile = nil;
}

494
- (BOOL)shouldDie
495
{
496 497
    if (_filepath) {
        if (_filepath.length > 0)
Felix Paul Kühne's avatar
Felix Paul Kühne committed
498
            [[VLCHTTPUploaderController sharedInstance] moveFileFrom:_filepath];
499
    }
500
    return [super shouldDie];
501 502
}

503 504
#pragma mark subtitle

Felix Paul Kühne's avatar
Felix Paul Kühne committed
505
- (NSMutableArray *)_listOfSubtitles
506
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
507
    NSMutableArray *listOfSubtitles = [[NSMutableArray alloc] init];
508
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
509
    NSArray *allFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
510
    NSString *filePath;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
511 512 513
    NSUInteger count = allFiles.count;
    for (NSUInteger i = 0; i < count; i++) {
        filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allFiles[i]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
514
        if ([filePath isSupportedSubtitleFormat])
Felix Paul Kühne's avatar
Felix Paul Kühne committed
515
            [listOfSubtitles addObject:filePath];
516
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
517
    return listOfSubtitles;
518 519
}

520
- (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
521
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
522
    NSString *subtitlePath;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
523 524 525
    NSString *fileSub;
    NSString *currentPath;

526
    NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
527 528 529
    if (fileName == nil)
        return nil;

Felix Paul Kühne's avatar
Felix Paul Kühne committed
530 531
    NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
    NSUInteger count = listOfSubtitles.count;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
532

Felix Paul Kühne's avatar
Felix Paul Kühne committed
533 534 535
    for (NSUInteger i = 0; i < count; i++) {
        currentPath = listOfSubtitles[i];
        fileSub = [NSString stringWithFormat:@"%@", currentPath];
536
        if ([fileSub rangeOfString:fileName].location != NSNotFound)
Felix Paul Kühne's avatar
Felix Paul Kühne committed
537
            subtitlePath = currentPath;
538 539 540 541
    }
    return subtitlePath;
}

542
@end