VLCHTTPConnection.m 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. #import "HTTPDynamicFileResponse.h"
  23. @interface VLCHTTPConnection()
  24. {
  25. MultipartFormDataParser *_parser;
  26. NSFileHandle *_storeFile;
  27. NSString *_filepath;
  28. UInt64 _contentLength;
  29. UInt64 _receivedContent;
  30. }
  31. @end
  32. @implementation VLCHTTPConnection
  33. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  34. {
  35. // Add support for POST
  36. if ([method isEqualToString:@"POST"]) {
  37. if ([path isEqualToString:@"/upload.json"])
  38. return YES;
  39. }
  40. return [super supportsMethod:method atPath:path];
  41. }
  42. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  43. {
  44. // Inform HTTP server that we expect a body to accompany a POST request
  45. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  46. // here we need to make sure, boundary is set in header
  47. NSString* contentType = [request headerField:@"Content-Type"];
  48. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  49. if (NSNotFound == paramsSeparator)
  50. return NO;
  51. if (paramsSeparator >= contentType.length - 1)
  52. return NO;
  53. NSString* type = [contentType substringToIndex:paramsSeparator];
  54. if (![type isEqualToString:@"multipart/form-data"]) {
  55. // we expect multipart/form-data content type
  56. return NO;
  57. }
  58. // enumerate all params in content-type, and find boundary there
  59. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  60. for (NSString* param in params) {
  61. paramsSeparator = [param rangeOfString:@"="].location;
  62. if ((NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1)
  63. continue;
  64. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  65. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  66. if ([paramName isEqualToString: @"boundary"])
  67. // let's separate the boundary from content-type, to make it more handy to handle
  68. [request setHeaderField:@"boundary" value:paramValue];
  69. }
  70. // check if boundary specified
  71. if (nil == [request headerField:@"boundary"])
  72. return NO;
  73. return YES;
  74. }
  75. return [super expectsRequestBodyFromMethod:method atPath:path];
  76. }
  77. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  78. {
  79. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  80. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  81. }
  82. if ([method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"]) {
  83. // let download the uploaded files
  84. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  85. }
  86. if ([path hasPrefix:@"/download/"]) {
  87. NSString *filePath = [[path stringByReplacingOccurrencesOfString:@"/download/" withString:@""]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  88. return [[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self];
  89. }
  90. NSString *filePath = [self filePathForURI:path];
  91. NSString *documentRoot = [config documentRoot];
  92. NSString *relativePath = [filePath substringFromIndex:[documentRoot length]];
  93. if ([relativePath isEqualToString:@"/index.html"])
  94. {
  95. NSArray *allFiles = [MLFile allFiles];
  96. NSString *fileList = @"";
  97. for (MLFile *file in allFiles) {
  98. NSString *fileHTML = [NSString stringWithFormat:@"<li><a href=\"download/%@\" download>%@</a></li>",[file.url stringByReplacingOccurrencesOfString:@"file://"withString:@""], file.title];
  99. fileList = [fileList stringByAppendingString:fileHTML];
  100. }
  101. NSMutableDictionary *replacementDict = [NSMutableDictionary new];
  102. [replacementDict setObject:fileList forKey:@"FILES"];
  103. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  104. forConnection:self
  105. separator:@"%%"
  106. replacementDictionary:replacementDict];
  107. }
  108. return [super httpResponseForMethod:method URI:path];
  109. }
  110. - (void)prepareForBodyWithSize:(UInt64)contentLength
  111. {
  112. // set up mime parser
  113. NSString* boundary = [request headerField:@"boundary"];
  114. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  115. _parser.delegate = self;
  116. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  117. _contentLength = contentLength;
  118. }
  119. - (void)processBodyData:(NSData *)postDataChunk
  120. {
  121. /* append data to the parser. It will invoke callbacks to let us handle
  122. * parsed data. */
  123. [_parser appendData:postDataChunk];
  124. _receivedContent += postDataChunk.length;
  125. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  126. }
  127. //-----------------------------------------------------------------
  128. #pragma mark multipart form data parser delegate
  129. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  130. {
  131. /* in this sample, we are not interested in parts, other then file parts.
  132. * check content disposition to find out filename */
  133. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  134. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  135. if ((nil == filename) || [filename isEqualToString: @""]) {
  136. // it's either not a file part, or
  137. // an empty form sent. we won't handle it.
  138. return;
  139. }
  140. // create the path where to store the media temporarily
  141. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  142. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  143. NSFileManager *fileManager = [NSFileManager defaultManager];
  144. BOOL isDir = YES;
  145. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  146. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  147. }
  148. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  149. APLog(@"Saving file to %@", _filepath);
  150. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  151. APLog(@"Could not create directory at path: %@", _filepath);
  152. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  153. APLog(@"Could not create file at path: %@", _filepath);
  154. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  155. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  156. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  157. }
  158. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  159. {
  160. // here we just write the output from parser to the file.
  161. if (_storeFile) {
  162. @try {
  163. [_storeFile writeData:data];
  164. }
  165. @catch (NSException *exception) {
  166. APLog(@"File to write further data because storage is full.");
  167. [_storeFile closeFile];
  168. _storeFile = nil;
  169. /* don't block */
  170. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  171. }
  172. }
  173. }
  174. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  175. {
  176. // as the file part is over, we close the file.
  177. APLog(@"closing file");
  178. [_storeFile closeFile];
  179. _storeFile = nil;
  180. }
  181. - (BOOL)shouldDie
  182. {
  183. if (_filepath) {
  184. if (_filepath.length > 0)
  185. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  186. }
  187. return [super shouldDie];
  188. }
  189. @end