VLCHTTPConnection.m 27.8 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 16 17 18 19 20 21 22

#import "VLCAppDelegate.h"
#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"
27 28 29

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

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

        NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
109 110 111 112
        if (moc) {
            NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
            if (psc) {
                NSManagedObject *mo = [moc existingObjectWithID:[psc managedObjectIDForURIRepresentation:[NSURL URLWithString:filePath]] error:nil];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
113 114 115 116 117 118 119 120 121 122 123 124
                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";
                }
125 126 127

                if (theData) {
                    HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
128
                    dataResponse.contentType = contentType;
129 130 131
                    return dataResponse;
                }
            }
132
        }
133
    }
134 135 136
    NSString *filePath = [self filePathForURI:path];
    NSString *documentRoot = [config documentRoot];
    NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
137
    BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
138

139
    if ([relativePath isEqualToString:@"/index.html"] || shouldReturnLibVLCXML) {
140 141 142
        NSMutableArray *allMedia = [[NSMutableArray alloc] init];

        /* add all albums */
143 144
        NSArray *allAlbums = [MLAlbum allAlbums];
        for (MLAlbum *album in allAlbums) {
145 146
            if (album.name.length > 0 && album.tracks.count > 1)
                [allMedia addObject:album];
147
        }
148 149

        /* add all shows */
150 151
        NSArray *allShows = [MLShow allShows];
        for (MLShow *show in allShows) {
152 153
            if (show.name.length > 0 && show.episodes.count > 1)
                [allMedia addObject:show];
154
        }
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

        /* 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
177 178 179 180
        NSUInteger mediaCount = allMedia.count;
        NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
        NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
        NSString *hostName = [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] hostname];
181
        NSString *duration;
182 183

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

Felix Paul Kühne's avatar
Felix Paul Kühne committed
331 332
        UIDevice *currentDevice = [UIDevice currentDevice];
        NSString *deviceModel = [currentDevice model];
333
        NSDictionary *replacementDict;
334
        HTTPDynamicFileResponse *fileResponse;
335

336
        if (shouldReturnLibVLCXML) {
337 338
            replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
                                @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
Felix Paul Kühne's avatar
Felix Paul Kühne committed
339
                                @"LIB_TITLE" : [currentDevice name]};
340 341 342 343 344 345 346

            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"application/xml";
        } else {
347 348 349 350 351 352
            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]};
353 354 355 356 357 358
            fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                               forConnection:self
                                                                   separator:@"%%"
                                                       replacementDictionary:replacementDict];
            fileResponse.contentType = @"text/html";
        }
359

360
        return fileResponse;
361
    } else if ([relativePath isEqualToString:@"/style.css"]) {
362
        NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
363 364 365 366 367 368
        HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                                                    forConnection:self
                                                                                        separator:@"%%"
                                                                            replacementDictionary:replacementDict];
        fileResponse.contentType = @"text/css";
        return fileResponse;
369
    }
370

371 372 373 374 375 376 377 378 379 380
    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;

381 382
    APLog(@"expecting file of size %lli kB", contentLength / 1024);
    _contentLength = contentLength;
383 384 385 386 387 388 389
}

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

391
    _receivedContent += postDataChunk.length;
392

393
    APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
}

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

414
    // create the path where to store the media temporarily
415
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
416
    NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
417
    NSFileManager *fileManager = [NSFileManager defaultManager];
418 419

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

423
    _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
424

425 426 427 428 429 430 431 432 433
    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;
    }

434
    APLog(@"Saving file to %@", _filepath);
435
    if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
436
        APLog(@"Could not create directory at path: %@", _filepath);
437

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

441
    _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
442 443 444
    VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate networkActivityStarted];
    [appDelegate disableIdleTimer];
445 446
}

447 448 449 450 451 452 453 454 455 456 457 458 459
- (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];
}

460 461 462
- (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
{
    // here we just write the output from parser to the file.
463 464 465 466 467 468 469 470 471 472 473 474 475
    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];
        }
    }

476 477 478 479 480
}

- (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
{
    // as the file part is over, we close the file.
481
    APLog(@"closing file");
482 483 484 485
    [_storeFile closeFile];
    _storeFile = nil;
}

486
- (BOOL)shouldDie
487
{
488 489 490
    if (_filepath) {
        if (_filepath.length > 0)
            [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
491
    }
492
    return [super shouldDie];
493 494
}

495 496
#pragma mark subtitle

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

512
- (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
513
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
514
    NSString *subtitlePath;
515
    NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
516
    NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
517
    NSString *fileSub;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
518 519 520 521 522
    NSUInteger count = listOfSubtitles.count;
    NSString *currentPath;
    for (NSUInteger i = 0; i < count; i++) {
        currentPath = listOfSubtitles[i];
        fileSub = [NSString stringWithFormat:@"%@", currentPath];
523
        if ([fileSub rangeOfString:fileName].location != NSNotFound)
Felix Paul Kühne's avatar
Felix Paul Kühne committed
524
            subtitlePath = currentPath;
525 526 527 528
    }
    return subtitlePath;
}

529
@end