VLCHTTPUploaderController.m 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. //
  2. // VLCHTTPUploaderViewController.m
  3. // VLC for iOS
  4. //
  5. // Created by Jean-Baptiste Kempf on 19/05/13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCHTTPUploaderController.h"
  11. #import "VLCAppDelegate.h"
  12. #import "DDLog.h"
  13. #import "DDTTYLogger.h"
  14. #import "DDNumber.h"
  15. #import "HTTPServer.h"
  16. #import "HTTPMessage.h"
  17. #import "HTTPDataResponse.h"
  18. #import "HTTPLogging.h"
  19. #import "HTTPDynamicFileResponse.h"
  20. #import "HTTPFileResponse.h"
  21. #import "MultipartFormDataParser.h"
  22. #import "MultipartMessageHeaderField.h"
  23. static const int ddLogLevel = LOG_LEVEL_VERBOSE;
  24. static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; // | HTTP_LOG_FLAG_TRACE;
  25. @interface VLCHTTPUploaderController ()
  26. @end
  27. @implementation VLCHTTPUploaderController
  28. -(BOOL)changeHTTPServerState:(BOOL)state
  29. {
  30. if(state) {
  31. // Just log to the Xcode console.
  32. [DDLog addLogger:[DDTTYLogger sharedInstance]];
  33. // Initalize our http server
  34. _httpServer = [[HTTPServer alloc] init];
  35. // Tell the server to broadcast its presence via Bonjour.
  36. // This allows browsers such as Safari to automatically discover our service.
  37. [self.httpServer setType:@"_http._tcp."];
  38. // Serve files from the standard Sites folder
  39. NSString *docRoot = [[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] stringByDeletingLastPathComponent];
  40. DDLogInfo(@"Setting document root: %@", docRoot);
  41. [self.httpServer setDocumentRoot:docRoot];
  42. [self.httpServer setPort:8888];
  43. [self.httpServer setConnectionClass:[VLCHTTPConnection class]];
  44. NSError *error = nil;
  45. if(![self.httpServer start:&error])
  46. {
  47. /* Address already in Use, take a random one */
  48. if(error.code == 48) {
  49. DDLogError(@"Address already in use, trying another one");
  50. [self.httpServer setPort:0];
  51. if([self.httpServer start:&error])
  52. return true;
  53. }
  54. DDLogError(@"Error starting HTTP Server: %@", error);
  55. return false;
  56. }
  57. return true;
  58. } else {
  59. [self.httpServer stop];
  60. return true;
  61. }
  62. }
  63. @end
  64. /**
  65. * All we have to do is override appropriate methods in HTTPConnection.
  66. **/
  67. @implementation VLCHTTPConnection
  68. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  69. {
  70. HTTPLogTrace();
  71. // Add support for POST
  72. if ([method isEqualToString:@"POST"])
  73. {
  74. if ([path isEqualToString:@"/upload.json"])
  75. {
  76. return YES;
  77. }
  78. }
  79. return [super supportsMethod:method atPath:path];
  80. }
  81. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  82. {
  83. HTTPLogTrace();
  84. // Inform HTTP server that we expect a body to accompany a POST request
  85. if([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  86. // here we need to make sure, boundary is set in header
  87. NSString* contentType = [request headerField:@"Content-Type"];
  88. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  89. if( NSNotFound == paramsSeparator ) {
  90. return NO;
  91. }
  92. if( paramsSeparator >= contentType.length - 1 ) {
  93. return NO;
  94. }
  95. NSString* type = [contentType substringToIndex:paramsSeparator];
  96. if( ![type isEqualToString:@"multipart/form-data"] ) {
  97. // we expect multipart/form-data content type
  98. return NO;
  99. }
  100. // enumerate all params in content-type, and find boundary there
  101. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  102. for( NSString* param in params ) {
  103. paramsSeparator = [param rangeOfString:@"="].location;
  104. if( (NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1 ) {
  105. continue;
  106. }
  107. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  108. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  109. if( [paramName isEqualToString: @"boundary"] ) {
  110. // let's separate the boundary from content-type, to make it more handy to handle
  111. [request setHeaderField:@"boundary" value:paramValue];
  112. }
  113. }
  114. // check if boundary specified
  115. if( nil == [request headerField:@"boundary"] ) {
  116. return NO;
  117. }
  118. return YES;
  119. }
  120. return [super expectsRequestBodyFromMethod:method atPath:path];
  121. }
  122. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  123. {
  124. HTTPLogTrace();
  125. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  126. {
  127. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  128. }
  129. if( [method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"] ) {
  130. // let download the uploaded files
  131. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  132. }
  133. return [super httpResponseForMethod:method URI:path];
  134. }
  135. - (void)prepareForBodyWithSize:(UInt64)contentLength
  136. {
  137. HTTPLogTrace();
  138. // set up mime parser
  139. NSString* boundary = [request headerField:@"boundary"];
  140. parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  141. parser.delegate = self;
  142. uploadedFiles = [[NSMutableArray alloc] init];
  143. }
  144. - (void)processBodyData:(NSData *)postDataChunk
  145. {
  146. HTTPLogTrace();
  147. // append data to the parser. It will invoke callbacks to let us handle
  148. // parsed data.
  149. [parser appendData:postDataChunk];
  150. }
  151. //-----------------------------------------------------------------
  152. #pragma mark multipart form data parser delegate
  153. - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header {
  154. // in this sample, we are not interested in parts, other then file parts.
  155. // check content disposition to find out filename
  156. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  157. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  158. if ( (nil == filename) || [filename isEqualToString: @""] ) {
  159. // it's either not a file part, or
  160. // an empty form sent. we won't handle it.
  161. return;
  162. }
  163. // create the path where to store the media
  164. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  165. NSString* uploadDirPath = searchPaths[0];
  166. BOOL isDir = YES;
  167. if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  168. [[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  169. }
  170. NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
  171. if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
  172. storeFile = nil;
  173. }
  174. else {
  175. HTTPLogVerbose(@"Saving file to %@", filePath);
  176. if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
  177. HTTPLogError(@"Could not create directory at path: %@", filePath);
  178. }
  179. if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
  180. HTTPLogError(@"Could not create file at path: %@", filePath);
  181. }
  182. storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
  183. [uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];
  184. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  185. }
  186. }
  187. - (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header
  188. {
  189. // here we just write the output from parser to the file.
  190. if( storeFile ) {
  191. [storeFile writeData:data];
  192. }
  193. }
  194. - (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header
  195. {
  196. // as the file part is over, we close the file.
  197. [storeFile closeFile];
  198. storeFile = nil;
  199. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  200. /* update media library when file upload was completed */
  201. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  202. [appDelegate updateMediaList];
  203. }
  204. @end