VLCHTTPConnection.m 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*****************************************************************************
  2. * VLCHTTPConnection.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Jean-Baptiste Kempf <jb # videolan.org>
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCAppDelegate.h"
  14. #import "VLCHTTPConnection.h"
  15. #import "HTTPConnection.h"
  16. #import "MultipartFormDataParser.h"
  17. #import "HTTPMessage.h"
  18. #import "HTTPDataResponse.h"
  19. #import "HTTPFileResponse.h"
  20. #import "MultipartMessageHeaderField.h"
  21. #import "VLCHTTPUploaderController.h"
  22. @interface VLCHTTPConnection()
  23. {
  24. MultipartFormDataParser *_parser;
  25. NSFileHandle *_storeFile;
  26. NSString *_filepath;
  27. UInt64 _contentLength;
  28. UInt64 _receivedContent;
  29. }
  30. @end
  31. @implementation VLCHTTPConnection
  32. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  33. {
  34. // Add support for POST
  35. if ([method isEqualToString:@"POST"]) {
  36. if ([path isEqualToString:@"/upload.json"])
  37. return YES;
  38. }
  39. return [super supportsMethod:method atPath:path];
  40. }
  41. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  42. {
  43. // Inform HTTP server that we expect a body to accompany a POST request
  44. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  45. // here we need to make sure, boundary is set in header
  46. NSString* contentType = [request headerField:@"Content-Type"];
  47. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  48. if (NSNotFound == paramsSeparator)
  49. return NO;
  50. if (paramsSeparator >= contentType.length - 1)
  51. return NO;
  52. NSString* type = [contentType substringToIndex:paramsSeparator];
  53. if (![type isEqualToString:@"multipart/form-data"]) {
  54. // we expect multipart/form-data content type
  55. return NO;
  56. }
  57. // enumerate all params in content-type, and find boundary there
  58. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  59. for (NSString* param in params) {
  60. paramsSeparator = [param rangeOfString:@"="].location;
  61. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  62. continue;
  63. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  64. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  65. if ([paramName isEqualToString: @"boundary"])
  66. // let's separate the boundary from content-type, to make it more handy to handle
  67. [request setHeaderField:@"boundary" value:paramValue];
  68. }
  69. // check if boundary specified
  70. if (nil == [request headerField:@"boundary"])
  71. return NO;
  72. return YES;
  73. }
  74. return [super expectsRequestBodyFromMethod:method atPath:path];
  75. }
  76. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  77. {
  78. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  79. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  80. }
  81. if ([method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"]) {
  82. // let download the uploaded files
  83. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  84. }
  85. return [super httpResponseForMethod:method URI:path];
  86. }
  87. - (void)prepareForBodyWithSize:(UInt64)contentLength
  88. {
  89. // set up mime parser
  90. NSString* boundary = [request headerField:@"boundary"];
  91. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  92. _parser.delegate = self;
  93. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  94. _contentLength = contentLength;
  95. }
  96. - (void)processBodyData:(NSData *)postDataChunk
  97. {
  98. /* append data to the parser. It will invoke callbacks to let us handle
  99. * parsed data. */
  100. [_parser appendData:postDataChunk];
  101. _receivedContent += postDataChunk.length;
  102. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  103. }
  104. //-----------------------------------------------------------------
  105. #pragma mark multipart form data parser delegate
  106. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  107. {
  108. /* in this sample, we are not interested in parts, other then file parts.
  109. * check content disposition to find out filename */
  110. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  111. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  112. if ((nil == filename) || [filename isEqualToString: @""]) {
  113. // it's either not a file part, or
  114. // an empty form sent. we won't handle it.
  115. return;
  116. }
  117. // create the path where to store the media temporarily
  118. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  119. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  120. NSFileManager *fileManager = [NSFileManager defaultManager];
  121. BOOL isDir = YES;
  122. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  123. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  124. }
  125. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  126. APLog(@"Saving file to %@", _filepath);
  127. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  128. APLog(@"Could not create directory at path: %@", _filepath);
  129. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  130. APLog(@"Could not create file at path: %@", _filepath);
  131. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  132. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  133. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  134. }
  135. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  136. {
  137. // here we just write the output from parser to the file.
  138. if (_storeFile) {
  139. @try {
  140. [_storeFile writeData:data];
  141. }
  142. @catch (NSException *exception) {
  143. APLog(@"File to write further data because storage is full.");
  144. [_storeFile closeFile];
  145. _storeFile = nil;
  146. /* don't block */
  147. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  148. }
  149. }
  150. }
  151. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  152. {
  153. // as the file part is over, we close the file.
  154. APLog(@"closing file");
  155. [_storeFile closeFile];
  156. _storeFile = nil;
  157. }
  158. - (BOOL)shouldDie
  159. {
  160. if (_filepath) {
  161. if (_filepath.length > 0)
  162. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  163. }
  164. return [super shouldDie];
  165. }
  166. @end