VLCHTTPConnection.m 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. [replacementDict setObject:NSLocalizedString(@"WEBINTF_DROPFILES", nil) forKey:@"WEBINTF_DROPFILES"];
  104. [replacementDict setObject:NSLocalizedString(@"WEBINTF_DROPFILES_LONG", nil) forKey:@"WEBINTF_DROPFILES_LONG"];
  105. [replacementDict setObject:NSLocalizedString(@"WEBINTF_DOWNLOADFILES", nil) forKey:@"WEBINTF_DOWNLOADFILES"];
  106. [replacementDict setObject:NSLocalizedString(@"WEBINTF_DOWNLOADFILES_LONG", nil) forKey:@"WEBINTF_DOWNLOADFILES_LONG"];
  107. return [[HTTPDynamicFileResponse alloc] initWithFilePath:[self filePathForURI:path]
  108. forConnection:self
  109. separator:@"%%"
  110. replacementDictionary:replacementDict];
  111. }
  112. return [super httpResponseForMethod:method URI:path];
  113. }
  114. - (void)prepareForBodyWithSize:(UInt64)contentLength
  115. {
  116. // set up mime parser
  117. NSString* boundary = [request headerField:@"boundary"];
  118. _parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  119. _parser.delegate = self;
  120. APLog(@"expecting file of size %lli kB", contentLength / 1024);
  121. _contentLength = contentLength;
  122. }
  123. - (void)processBodyData:(NSData *)postDataChunk
  124. {
  125. /* append data to the parser. It will invoke callbacks to let us handle
  126. * parsed data. */
  127. [_parser appendData:postDataChunk];
  128. _receivedContent += postDataChunk.length;
  129. APLog(@"received %lli kB (%lli %%)", _receivedContent / 1024, ((_receivedContent * 100) / _contentLength));
  130. }
  131. //-----------------------------------------------------------------
  132. #pragma mark multipart form data parser delegate
  133. - (void)processStartOfPartWithHeader:(MultipartMessageHeader*) header
  134. {
  135. /* in this sample, we are not interested in parts, other then file parts.
  136. * check content disposition to find out filename */
  137. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  138. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  139. if ((nil == filename) || [filename isEqualToString: @""]) {
  140. // it's either not a file part, or
  141. // an empty form sent. we won't handle it.
  142. return;
  143. }
  144. // create the path where to store the media temporarily
  145. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  146. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  147. NSFileManager *fileManager = [NSFileManager defaultManager];
  148. BOOL isDir = YES;
  149. if (![fileManager fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  150. [fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  151. }
  152. _filepath = [uploadDirPath stringByAppendingPathComponent: filename];
  153. APLog(@"Saving file to %@", _filepath);
  154. if (![fileManager createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil])
  155. APLog(@"Could not create directory at path: %@", _filepath);
  156. if (![fileManager createFileAtPath:_filepath contents:nil attributes:nil])
  157. APLog(@"Could not create file at path: %@", _filepath);
  158. _storeFile = [NSFileHandle fileHandleForWritingAtPath:_filepath];
  159. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate networkActivityStarted];
  160. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  161. }
  162. - (void)processContent:(NSData*)data WithHeader:(MultipartMessageHeader*) header
  163. {
  164. // here we just write the output from parser to the file.
  165. if (_storeFile) {
  166. @try {
  167. [_storeFile writeData:data];
  168. }
  169. @catch (NSException *exception) {
  170. APLog(@"File to write further data because storage is full.");
  171. [_storeFile closeFile];
  172. _storeFile = nil;
  173. /* don't block */
  174. [self performSelector:@selector(stop) withObject:nil afterDelay:0.1];
  175. }
  176. }
  177. }
  178. - (void)processEndOfPartWithHeader:(MultipartMessageHeader*)header
  179. {
  180. // as the file part is over, we close the file.
  181. APLog(@"closing file");
  182. [_storeFile closeFile];
  183. _storeFile = nil;
  184. }
  185. - (BOOL)shouldDie
  186. {
  187. if (_filepath) {
  188. if (_filepath.length > 0)
  189. [[(VLCAppDelegate*)[UIApplication sharedApplication].delegate uploadController] moveFileFrom:_filepath];
  190. }
  191. return [super shouldDie];
  192. }
  193. @end