VLCHTTPConnection.m 30.7 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 "NSString+SupportedMedia.h"
25
#import "UIDevice+VLC.h"
Felix Paul Kühne's avatar
Felix Paul Kühne committed
26
#import "VLCHTTPUploaderController.h"
27

28 29 30 31
#if TARGET_OS_IOS
#import "VLCThumbnailsCache.h"
#endif

32 33
@interface VLCHTTPConnection()
{
34 35 36
    MultipartFormDataParser *_parser;
    NSFileHandle *_storeFile;
    NSString *_filepath;
37 38
    UInt64 _contentLength;
    UInt64 _receivedContent;
39 40 41 42 43 44 45 46
}
@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
47
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
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
            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
74 75 76
        NSUInteger count = params.count;
        for (NSUInteger i = 0; i < count; i++) {
            NSString *param = params[i];
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
            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
99
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
100
        return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
101

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

        NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
114 115 116
        if (moc) {
            NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
            if (psc) {
117 118 119 120 121 122 123
                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
124 125 126 127 128 129 130 131 132 133 134 135
                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";
                }
136 137 138

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

150
    if ([relativePath isEqualToString:@"/index.html"] || shouldReturnLibVLCXML) {
151 152 153
        NSMutableArray *allMedia = [[NSMutableArray alloc] init];

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

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

        /* 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
188 189 190
        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
191
        NSString *hostName = [[VLCHTTPUploaderController sharedInstance] hostname];
192
        NSString *duration;
193 194

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

342

Felix Paul Kühne's avatar
Felix Paul Kühne committed
343 344
        UIDevice *currentDevice = [UIDevice currentDevice];
        NSString *deviceModel = [currentDevice model];
345
        NSDictionary *replacementDict;
346
        HTTPDynamicFileResponse *fileResponse;
347

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

            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"application/xml";
        } else {
359 360 361 362 363 364
            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]};
365 366 367 368 369 370
            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"text/html";
        }
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
#else
#warning FIXME
        UIDevice *currentDevice = [UIDevice currentDevice];
        NSString *deviceModel = [currentDevice model];
        NSString *filePath = [self filePathForURI:path];
        NSString *documentRoot = [config documentRoot];
        NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
        NSDictionary *replacementDict = @{@"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]};

        HTTPDynamicFileResponse *fileResponse;
    if ([relativePath isEqualToString:@"/index.html"]) {
        fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                           forConnection:self
                                                               separator:@"%%"
                                                   replacementDictionary:replacementDict];
        fileResponse.contentType = @"text/html";
#endif
392

393
        return fileResponse;
394
    } else if ([relativePath isEqualToString:@"/style.css"]) {
395
        NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
396 397 398 399 400 401
        HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                                                    forConnection:self
                                                                                        separator:@"%%"
                                                                            replacementDictionary:replacementDict];
        fileResponse.contentType = @"text/css";
        return fileResponse;
402
    }
403

404 405 406 407 408 409 410 411 412 413
    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;

414 415
    APLog(@"expecting file of size %lli kB", contentLength / 1024);
    _contentLength = contentLength;
416 417 418 419 420 421 422
}

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

424
    _receivedContent += postDataChunk.length;
425

426
    APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
}

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

447
    // create the path where to store the media temporarily
448
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
449
    NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
450
    NSFileManager *fileManager = [NSFileManager defaultManager];
451 452

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

456
    _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
457

458 459 460 461 462 463 464 465 466
    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;
    }

467
    APLog(@"Saving file to %@", _filepath);
468
    if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
469
        APLog(@"Could not create directory at path: %@", _filepath);
470

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

474
    _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
475 476 477 478

    VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
    [activityManager networkActivityStarted];
    [activityManager disableIdleTimer];
479 480
}

481 482
- (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
{
483
#if TARGET_OS_IOS
484 485 486 487 488 489 490 491
    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];
492
    [alert show];
493 494 495 496 497 498 499 500 501 502 503 504
#else
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"DISK_FULL", nil)
                                                                             message:[NSString stringWithFormat:
                                                                                      NSLocalizedString(@"DISK_FULL_FORMAT", nil),
                                                                                      filename,
                                                                                      [[UIDevice currentDevice] model]]
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
                                                        style:UIAlertActionStyleCancel
                                                      handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
#endif
505 506
}

507 508 509
- (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
{
    // here we just write the output from parser to the file.
510 511 512 513 514 515 516 517 518 519 520 521 522
    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];
        }
    }

523 524 525 526 527
}

- (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
{
    // as the file part is over, we close the file.
528
    APLog(@"closing file");
529 530 531 532
    [_storeFile closeFile];
    _storeFile = nil;
}

533
- (BOOL)shouldDie
534
{
535 536
    if (_filepath) {
        if (_filepath.length > 0)
Felix Paul Kühne's avatar
Felix Paul Kühne committed
537
            [[VLCHTTPUploaderController sharedInstance] moveFileFrom:_filepath];
538
    }
539
    return [super shouldDie];
540 541
}

542 543
#pragma mark subtitle

Felix Paul Kühne's avatar
Felix Paul Kühne committed
544
- (NSMutableArray *)_listOfSubtitles
545
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
546
    NSMutableArray *listOfSubtitles = [[NSMutableArray alloc] init];
547
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
548
    NSArray *allFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
549
    NSString *filePath;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
550 551 552
    NSUInteger count = allFiles.count;
    for (NSUInteger i = 0; i < count; i++) {
        filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allFiles[i]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
553
        if ([filePath isSupportedSubtitleFormat])
Felix Paul Kühne's avatar
Felix Paul Kühne committed
554
            [listOfSubtitles addObject:filePath];
555
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
556
    return listOfSubtitles;
557 558
}

559
- (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
560
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
561
    NSString *subtitlePath;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
562 563 564
    NSString *fileSub;
    NSString *currentPath;

565
    NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
566 567 568
    if (fileName == nil)
        return nil;

Felix Paul Kühne's avatar
Felix Paul Kühne committed
569 570
    NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
    NSUInteger count = listOfSubtitles.count;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
571

Felix Paul Kühne's avatar
Felix Paul Kühne committed
572 573 574
    for (NSUInteger i = 0; i < count; i++) {
        currentPath = listOfSubtitles[i];
        fileSub = [NSString stringWithFormat:@"%@", currentPath];
575
        if ([fileSub rangeOfString:fileName].location != NSNotFound)
Felix Paul Kühne's avatar
Felix Paul Kühne committed
576
            subtitlePath = currentPath;
577 578 579 580
    }
    return subtitlePath;
}

581
@end