VLCHTTPConnection.m 35.3 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 "HTTPErrorResponse.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 31
#if TARGET_OS_IOS
#import "VLCThumbnailsCache.h"
#endif
32 33 34
#if TARGET_OS_TV
#import "VLCPlayerControlWebSocket.h"
#endif
35

36 37
@interface VLCHTTPConnection()
{
38 39 40
    MultipartFormDataParser *_parser;
    NSFileHandle *_storeFile;
    NSString *_filepath;
41 42
    UInt64 _contentLength;
    UInt64 _receivedContent;
43
#if TARGET_OS_TV
44
    NSMutableArray *_receivedFiles;
45
#endif
46 47 48 49 50 51 52 53
}
@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
54
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
55
        return YES;
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

    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
81 82 83
        NSUInteger count = params.count;
        for (NSUInteger i = 0; i < count; i++) {
            NSString *param = params[i];
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
            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];
}

104
- (NSObject<HTTPResponse> *)_httpPOSTresponseUploadJSON
105
{
106 107
    return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
}
Felix Paul Kühne's avatar
Felix Paul Kühne committed
108

109
#if TARGET_OS_IOS
110 111 112 113 114 115 116
- (NSObject<HTTPResponse> *)_httpGETDownloadForPath:(NSString *)path
{
    NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    HTTPFileResponse *fileResponse = [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
    fileResponse.contentType = @"application/octet-stream";
    return fileResponse;
}
117

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
- (NSObject<HTTPResponse> *)_httpGETThumbnailForPath:(NSString *)path
{
    NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/thumbnail/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    filePath = [filePath stringByReplacingOccurrencesOfString:@".png" withString:@""];

    NSManagedObjectContext *moc = [[MLMediaLibrary sharedMediaLibrary] managedObjectContext];
    if (moc) {
        NSPersistentStoreCoordinator *psc = [moc persistentStoreCoordinator];
        if (psc) {
            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
            }
133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
            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";
            }

            if (theData) {
                HTTPDataResponse *dataResponse = [[HTTPDataResponse alloc] initWithData:theData];
                dataResponse.contentType = contentType;
                return dataResponse;
151
            }
152
        }
153
    }
154 155 156 157
}

- (NSObject<HTTPResponse> *)_httpGETLibraryForPath:(NSString *)path
{
158 159 160
    NSString *filePath = [self filePathForURI:path];
    NSString *documentRoot = [config documentRoot];
    NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
161
    BOOL shouldReturnLibVLCXML = [relativePath isEqualToString:@"/libMediaVLC.xml"];
162

163
    NSMutableArray *allMedia = [[NSMutableArray alloc] init];
164

165 166 167 168 169 170
    /* add all albums */
    NSArray *allAlbums = [MLAlbum allAlbums];
    for (MLAlbum *album in allAlbums) {
        if (album.name.length > 0 && album.tracks.count > 1)
            [allMedia addObject:album];
    }
171

172 173 174 175 176 177
    /* add all shows */
    NSArray *allShows = [MLShow allShows];
    for (MLShow *show in allShows) {
        if (show.name.length > 0 && show.episodes.count > 1)
            [allMedia addObject:show];
    }
178

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

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

189 190 191 192 193 194 195
        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)
196 197
                [allMedia addObject:file];
        }
198
    }
199

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    NSUInteger mediaCount = allMedia.count;
    NSMutableArray *mediaInHtml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
    NSMutableArray *mediaInXml = [[NSMutableArray alloc] initWithCapacity:mediaCount];
    NSString *hostName = [[VLCHTTPUploaderController sharedInstance] hostname];
    NSString *duration;

    for (NSManagedObject *mo in allMedia) {
        if ([mo isKindOfClass:[MLFile class]]) {
            MLFile *file = (MLFile *)mo;
            duration = [[VLCTime timeWithNumber:file.duration] stringValue];
            [mediaInHtml addObject:[NSString stringWithFormat:
                                    @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
                                    <a href=\"download/%@\" class=\"inner\"> \
                                    <div class=\"down icon\"></div> \
                                    <div class=\"infos\"> \
                                    <span class=\"first-line\">%@</span> \
                                    <span class=\"second-line\">%@ - %0.2f MB</span> \
                                    </div> \
                                    </a> \
                                    </div>",
                                    file.objectID.URIRepresentation,
                                    [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                                    file.title,
                                    duration, (float)(file.fileSizeInBytes / 1e6)]];
            if (shouldReturnLibVLCXML) {
                NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
                if (pathSub)
                    pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
                [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]];
            }
        }
        else if ([mo isKindOfClass:[MLShow class]]) {
            MLShow *show = (MLShow *)mo;
            NSArray *episodes = [show sortedEpisodes];
            [mediaInHtml addObject:[NSString stringWithFormat:
                                    @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
                                    <a href=\"#\" class=\"inner folder\"> \
                                    <div class=\"open icon\"></div> \
                                    <div class=\"infos\"> \
                                    <span class=\"first-line\">%@</span> \
                                    <span class=\"second-line\">%lu items</span> \
                                    </div> \
                                    </a> \
                                    <div class=\"content\">",
                                    mo.objectID.URIRepresentation,
                                    show.name,
                                    (unsigned long)[episodes count]]];
            for (MLShowEpisode *showEp in episodes) {
                MLFile *anyFileFromEpisode = (MLFile *)[[showEp files] anyObject];
                duration = [[VLCTime timeWithNumber:[anyFileFromEpisode duration]] stringValue];
250 251
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
252
                                        <a href=\"download/%@\" class=\"inner\"> \
253 254
                                        <div class=\"down icon\"></div> \
                                        <div class=\"infos\"> \
255
                                        <span class=\"first-line\">S%@E%@ - %@</span> \
256
                                        <span class=\"second-line\">%@ - %0.2f MB</span> \
257 258 259
                                        </div> \
                                        </a> \
                                        </div>",
260 261 262 263 264 265
                                        showEp.objectID.URIRepresentation,
                                        [anyFileFromEpisode.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                                        showEp.seasonNumber,
                                        showEp.episodeNumber,
                                        showEp.name,
                                        duration, (float)([anyFileFromEpisode fileSizeInBytes] / 1e6)]];
266
                if (shouldReturnLibVLCXML) {
267 268
                    NSString *pathSub = [self _checkIfSubtitleWasFound:[anyFileFromEpisode path]];
                    if (![pathSub isEqualToString:@""])
269
                        pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
270
                    [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]];
271
                }
272
            }
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
            [mediaInHtml addObject:@"</div></div>"];
        } else if ([mo isKindOfClass:[MLLabel class]]) {
            MLLabel *label = (MLLabel *)mo;
            NSArray *folderItems = [label sortedFolderItems];
            [mediaInHtml addObject:[NSString stringWithFormat:
                                    @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
                                    <a href=\"#\" class=\"inner folder\"> \
                                    <div class=\"open icon\"></div> \
                                    <div class=\"infos\"> \
                                    <span class=\"first-line\">%@</span> \
                                    <span class=\"second-line\">%lu items</span> \
                                    </div> \
                                    </a> \
                                    <div class=\"content\">",
                                    label.objectID.URIRepresentation,
                                    label.name,
                                    (unsigned long)folderItems.count]];
            for (MLFile *file in folderItems) {
                duration = [[VLCTime timeWithNumber:[file duration]] stringValue];
292 293
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
294 295
                                        <a href=\"download/%@\" class=\"inner\"> \
                                        <div class=\"down icon\"></div> \
296 297
                                        <div class=\"infos\"> \
                                        <span class=\"first-line\">%@</span> \
298
                                        <span class=\"second-line\">%@ - %0.2f MB</span> \
299 300
                                        </div> \
                                        </a> \
301 302 303 304 305 306 307 308 309 310
                                        </div>",
                                        file.objectID.URIRepresentation,
                                        [file.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                                        file.title,
                                        duration, (float)(file.fileSizeInBytes / 1e6)]];
                if (shouldReturnLibVLCXML) {
                    NSString *pathSub = [self _checkIfSubtitleWasFound:file.path];
                    if (pathSub)
                        pathSub = [NSString stringWithFormat:@"http://%@/download/%@", hostName, pathSub];
                    [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]];
311
                }
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            }
            [mediaInHtml addObject:@"</div></div>"];
        } else if ([mo isKindOfClass:[MLAlbum class]]) {
            MLAlbum *album = (MLAlbum *)mo;
            NSArray *albumTracks = [album sortedTracks];
            [mediaInHtml addObject:[NSString stringWithFormat:
                                    @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
                                    <a href=\"#\" class=\"inner folder\"> \
                                    <div class=\"open icon\"></div> \
                                    <div class=\"infos\"> \
                                    <span class=\"first-line\">%@</span> \
                                    <span class=\"second-line\">%lu items</span> \
                                    </div> \
                                    </a> \
                                    <div class=\"content\">",
                                    album.objectID.URIRepresentation,
                                    album.name,
                                    (unsigned long)albumTracks.count]];
            for (MLAlbumTrack *track in albumTracks) {
                MLFile *anyFileFromTrack = [track anyFileFromTrack];
                duration = [[VLCTime timeWithNumber:[anyFileFromTrack duration]] stringValue];
333 334
                [mediaInHtml addObject:[NSString stringWithFormat:
                                        @"<div style=\"background-image:url('thumbnail/%@.png')\"> \
335 336
                                        <a href=\"download/%@\" class=\"inner\"> \
                                        <div class=\"down icon\"></div> \
337 338
                                        <div class=\"infos\"> \
                                        <span class=\"first-line\">%@</span> \
339
                                        <span class=\"second-line\">%@ - %0.2f MB</span> \
340 341
                                        </div> \
                                        </a> \
342 343 344 345 346 347 348
                                        </div>",
                                        track.objectID.URIRepresentation,
                                        [anyFileFromTrack.url.path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                                        track.title,
                                        duration, (float)([anyFileFromTrack fileSizeInBytes] / 1e6)]];
                if (shouldReturnLibVLCXML)
                    [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]]];
349
            }
350
            [mediaInHtml addObject:@"</div></div>"];
351
        }
352
    }
353

354

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    UIDevice *currentDevice = [UIDevice currentDevice];
    NSString *deviceModel = [currentDevice model];
    NSDictionary *replacementDict;
    HTTPDynamicFileResponse *fileResponse;

    if (shouldReturnLibVLCXML) {
        replacementDict = @{@"FILES" : [mediaInXml componentsJoinedByString:@" "],
                            @"NB_FILE" : [NSString stringWithFormat:@"%li", (unsigned long)mediaInXml.count],
                            @"LIB_TITLE" : [currentDevice name]};

        fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                           forConnection:self
                                                               separator:@"%%"
                                                   replacementDictionary:replacementDict];
        fileResponse.contentType = @"application/xml";
    } else {
        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]};
        fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                           forConnection:self
                                                               separator:@"%%"
                                                   replacementDictionary:replacementDict];
        fileResponse.contentType = @"text/html";
    }

    return fileResponse;
}
386
#else
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
- (NSObject<HTTPResponse> *)_httpGETLibraryForPath:(NSString *)path
{
    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_ATV", nil),
                                      @"WEBINTF_DROPFILES" : NSLocalizedString(@"WEBINTF_DROPFILES", nil),
                                      @"WEBINTF_DROPFILES_LONG" : [NSString stringWithFormat:NSLocalizedString(@"WEBINTF_DROPFILES_LONG_ATV", 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";
    }

    return fileResponse;
}
409
#endif
410

411 412 413

- (NSObject<HTTPResponse> *)_httpGETCSSForPath:(NSString *)path
{
414
#if TARGET_OS_IOS
415
    NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE", nil)};
416
#else
417
    NSDictionary *replacementDict = @{@"WEBINTF_TITLE" : NSLocalizedString(@"WEBINTF_TITLE_ATV", nil)};
418
#endif
419 420 421 422 423 424 425 426
    HTTPDynamicFileResponse *fileResponse = [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
                                                                                forConnection:self
                                                                                    separator:@"%%"
                                                                        replacementDictionary:replacementDict];
    fileResponse.contentType = @"text/css";
    return fileResponse;
}

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
#if TARGET_OS_TV
- (NSObject <HTTPResponse> *)_HTTPGETPlaying
{
    /* JSON response:
     {
        "currentTime": 42,
        "media": {
            "id": "some id",
            "title": "some title",
            "duration": 120000
        }
     }
     */

    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    if (!vpc.activePlaybackSession) {
        return [[HTTPErrorResponse alloc] initWithErrorCode:404];
    }
    VLCMediaPlayer *player = vpc.mediaPlayer;
    VLCMedia *media = player.media;
    if (!media) {
        return [[HTTPErrorResponse alloc] initWithErrorCode:404];
    }

    NSString *mediaTitle = vpc.mediaTitle;
    if (!mediaTitle)
        mediaTitle = @"";
    NSDictionary *mediaDict = @{ @"id" : media.url.absoluteString,
                                 @"title" : mediaTitle,
                                 @"duration" : @(media.length.intValue)};
    NSDictionary *returnDict = @{ @"currentTime" : @(player.time.intValue),
                                  @"media" : mediaDict };

    NSError *error;
    NSData *returnData = [NSJSONSerialization dataWithJSONObject:returnDict options:0 error:&error];
    if (error != nil) {
        APLog(@"JSON serialization failed %@", error);
        return [[HTTPErrorResponse alloc] initWithErrorCode:500];
    }

    return [[HTTPDataResponse alloc] initWithData:returnData];
}

- (NSObject <HTTPResponse> *)_HTTPGETPlaylist
{
    /* JSON response:
     [
        {
            "media": {
                "id": "some id 1",
                "title": "some title 1",
                "duration": 120000
            }
        },
     ...]
     */

    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
    if (!vpc.activePlaybackSession || !vpc.mediaList) {
        return [[HTTPErrorResponse alloc] initWithErrorCode:404];
    }

    VLCMediaList *mediaList = vpc.mediaList;
    [mediaList lock];
    NSUInteger mediaCount = mediaList.count;
    NSMutableArray *retArray = [NSMutableArray array];
    for (NSUInteger x = 0; x < mediaCount; x++) {
        VLCMedia *media = [mediaList mediaAtIndex:x];
        NSString *mediaTitle;
        if (media.isParsed) {
            mediaTitle = [media metadataForKey:VLCMetaInformationTitle];
        } else {
            mediaTitle = media.url.lastPathComponent;
        }

        NSDictionary *mediaDict = @{ @"id" : media.url.absoluteString,
                                     @"title" : mediaTitle,
                                     @"duration" : @(media.length.intValue) };
        [retArray addObject:@{ @"media" : mediaDict }];
    }
    [mediaList unlock];

    NSError *error;
    NSData *returnData = [NSJSONSerialization dataWithJSONObject:retArray options:0 error:&error];
    if (error != nil) {
        APLog(@"JSON serialization failed %@", error);
        return [[HTTPErrorResponse alloc] initWithErrorCode:500];
    }

    return [[HTTPDataResponse alloc] initWithData:returnData];
}
#endif
519 520 521 522 523 524 525 526 527 528 529 530 531

- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
{
    if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
        return [self _httpPOSTresponseUploadJSON];

#if TARGET_OS_IOS
    if ([path hasPrefix:@"/download/"]) {
        return [self _httpGETDownloadForPath:path];
    }
    if ([path hasPrefix:@"/thumbnail"]) {
        return [self _httpGETThumbnailForPath:path];
    }
532 533 534 535 536 537 538
#else
    if ([path hasPrefix:@"/playing"]) {
        return [self _HTTPGETPlaying];
    }
    if ([path hasPrefix:@"/playlist"]) {
        return [self _HTTPGETPlaylist];
    }
539 540 541 542 543 544 545 546 547 548
#endif

    NSString *filePath = [self filePathForURI:path];
    NSString *documentRoot = [config documentRoot];
    NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];

    if ([relativePath isEqualToString:@"/index.html"] || [relativePath isEqualToString:@"/libMediaVLC.xml"]) {
        return [self _httpGETLibraryForPath:path];
    } else if ([relativePath isEqualToString:@"/style.css"]) {
        return [self _httpGETCSSForPath:path];
549
    }
550

551 552 553
    return [super httpResponseForMethod:method URI:path];
}

554 555 556 557 558 559 560
#if TARGET_OS_TV
- (WebSocket *)webSocketForURI:(NSString *)path
{
    return [[VLCPlayerControlWebSocket alloc] initWithRequest:request socket:asyncSocket];
}
#endif

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

568 569
    APLog(@"expecting file of size %lli kB", contentLength / 1024);
    _contentLength = contentLength;
570 571 572 573 574 575 576
}

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

578
    _receivedContent += postDataChunk.length;
579

580 581 582 583
    long long percentage = ((_receivedContent * 100) / _contentLength);
    APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, percentage);
#if TARGET_OS_TV
        if (percentage >= 10) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
584
            [self performSelectorOnMainThread:@selector(startPlaybackOfPath:) withObject:_filepath waitUntilDone:NO];
585 586
        }
#endif
587 588
}

Tobias's avatar
Tobias committed
589
#if TARGET_OS_TV
Felix Paul Kühne's avatar
Felix Paul Kühne committed
590 591 592
- (void)startPlaybackOfPath:(NSString *)path
{
    APLog(@"Starting playback of %@", path);
593 594 595 596 597 598 599 600
    if (_receivedFiles == nil)
        _receivedFiles = [[NSMutableArray alloc] init];

    if ([_receivedFiles containsObject:path])
        return;

    [_receivedFiles addObject:path];

Felix Paul Kühne's avatar
Felix Paul Kühne committed
601
    VLCPlaybackController *vpc = [VLCPlaybackController sharedInstance];
602 603 604 605 606 607 608 609 610
    BOOL needsMediaList;
    VLCMediaList *mediaList = vpc.mediaList;

    if (!mediaList) {
        mediaList = [[VLCMediaList alloc] init];
        needsMediaList = YES;
    }

    [mediaList addMedia:[VLCMedia mediaWithURL:[NSURL fileURLWithPath:path]]];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
611

612 613 614 615 616 617 618 619 620 621 622
    if (needsMediaList) {
        [vpc playMediaList:mediaList firstIndex:0];
    }

    VLCFullscreenMovieTVViewController *movieVC = [VLCFullscreenMovieTVViewController fullscreenMovieTVViewController];

    if (![movieVC isBeingPresented]) {
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:movieVC
                                                                                     animated:YES
                                                                                   completion:nil];
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
623
}
Tobias's avatar
Tobias committed
624
#endif
Felix Paul Kühne's avatar
Felix Paul Kühne committed
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
//-----------------------------------------------------------------
#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;
    }

644
    // create the path where to store the media temporarily
645
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
646
    NSString *uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
647
    NSFileManager *fileManager = [NSFileManager defaultManager];
648 649

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

653
    _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
654

655 656 657 658 659 660 661 662 663
    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;
    }

664
    APLog(@"Saving file to %@", _filepath);
665
    if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
666
        APLog(@"Could not create directory at path: %@", _filepath);
667

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

671
    _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
672 673 674 675

    VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
    [activityManager networkActivityStarted];
    [activityManager disableIdleTimer];
676 677
}

678 679
- (void)notifyUserAboutEndOfFreeStorage:(NSString *)filename
{
680
#if TARGET_OS_IOS
681 682 683 684 685 686 687 688
    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];
689
    [alert show];
690 691 692 693 694 695 696 697 698 699 700 701
#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
702 703
}

704 705 706
- (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
{
    // here we just write the output from parser to the file.
707 708 709 710 711 712 713 714 715 716 717 718 719
    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];
        }
    }

720 721 722 723 724
}

- (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
{
    // as the file part is over, we close the file.
725
    APLog(@"closing file");
726 727 728 729
    [_storeFile closeFile];
    _storeFile = nil;
}

730
- (BOOL)shouldDie
731
{
732
    if (_filepath) {
733
        if (_filepath.length > 0) {
Felix Paul Kühne's avatar
Felix Paul Kühne committed
734
            [[VLCHTTPUploaderController sharedInstance] moveFileFrom:_filepath];
735 736 737 738 739

#if TARGET_OS_TV
            [_receivedFiles removeObject:_filepath];
#endif
        }
740
    }
741
    return [super shouldDie];
742 743
}

744 745
#pragma mark subtitle

Felix Paul Kühne's avatar
Felix Paul Kühne committed
746
- (NSMutableArray *)_listOfSubtitles
747
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
748
    NSMutableArray *listOfSubtitles = [[NSMutableArray alloc] init];
749
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
750
    NSArray *allFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
751
    NSString *filePath;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
752 753 754
    NSUInteger count = allFiles.count;
    for (NSUInteger i = 0; i < count; i++) {
        filePath = [[NSString stringWithFormat:@"%@/%@", documentsDirectory, allFiles[i]] stringByReplacingOccurrencesOfString:@"file://"withString:@""];
755
        if ([filePath isSupportedSubtitleFormat])
Felix Paul Kühne's avatar
Felix Paul Kühne committed
756
            [listOfSubtitles addObject:filePath];
757
    }
Felix Paul Kühne's avatar
Felix Paul Kühne committed
758
    return listOfSubtitles;
759 760
}

761
- (NSString *)_checkIfSubtitleWasFound:(NSString *)filePath
762
{
Felix Paul Kühne's avatar
Felix Paul Kühne committed
763
    NSString *subtitlePath;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
764 765 766
    NSString *fileSub;
    NSString *currentPath;

767
    NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
768 769 770
    if (fileName == nil)
        return nil;

Felix Paul Kühne's avatar
Felix Paul Kühne committed
771 772
    NSMutableArray *listOfSubtitles = [self _listOfSubtitles];
    NSUInteger count = listOfSubtitles.count;
Felix Paul Kühne's avatar
Felix Paul Kühne committed
773

Felix Paul Kühne's avatar
Felix Paul Kühne committed
774 775 776
    for (NSUInteger i = 0; i < count; i++) {
        currentPath = listOfSubtitles[i];
        fileSub = [NSString stringWithFormat:@"%@", currentPath];
777
        if ([fileSub rangeOfString:fileName].location != NSNotFound)
Felix Paul Kühne's avatar
Felix Paul Kühne committed
778
            subtitlePath = currentPath;
779 780 781 782
    }
    return subtitlePath;
}

783
@end