VLCHTTPUploaderController.m 8.3 KB

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