VLCHTTPUploaderController.m 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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.html"])
  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.html"]) {
  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.html"])
  124. {
  125. // this method will generate response with links to uploaded file
  126. NSMutableString* filesStr = [[NSMutableString alloc] init];
  127. for( NSString* filePath in uploadedFiles ) {
  128. //generate links
  129. [filesStr appendFormat:@"<a href=\"%@\"> %@ </a><br/>",filePath, [filePath lastPathComponent]];
  130. }
  131. NSString* templatePath = [[config documentRoot] stringByAppendingPathComponent:@"upload.html"];
  132. NSDictionary* replacementDict = @{@"MyFiles": filesStr};
  133. // use dynamic file response to apply our links to response template
  134. return [[HTTPDynamicFileResponse alloc] initWithFilePath:templatePath forConnection:self separator:@"%" replacementDictionary:replacementDict];
  135. }
  136. if( [method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"] ) {
  137. // let download the uploaded files
  138. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  139. }
  140. return [super httpResponseForMethod:method URI:path];
  141. }
  142. - (void)prepareForBodyWithSize:(UInt64)contentLength
  143. {
  144. HTTPLogTrace();
  145. // set up mime parser
  146. NSString* boundary = [request headerField:@"boundary"];
  147. parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  148. parser.delegate = self;
  149. uploadedFiles = [[NSMutableArray alloc] init];
  150. }
  151. - (void)processBodyData:(NSData *)postDataChunk
  152. {
  153. HTTPLogTrace();
  154. // append data to the parser. It will invoke callbacks to let us handle
  155. // parsed data.
  156. [parser appendData:postDataChunk];
  157. }
  158. //-----------------------------------------------------------------
  159. #pragma mark multipart form data parser delegate
  160. - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header {
  161. // in this sample, we are not interested in parts, other then file parts.
  162. // check content disposition to find out filename
  163. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  164. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  165. if ( (nil == filename) || [filename isEqualToString: @""] ) {
  166. // it's either not a file part, or
  167. // an empty form sent. we won't handle it.
  168. return;
  169. }
  170. // create the path where to store the media
  171. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  172. NSString* uploadDirPath = searchPaths[0];
  173. BOOL isDir = YES;
  174. if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  175. [[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  176. }
  177. NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
  178. if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
  179. storeFile = nil;
  180. }
  181. else {
  182. HTTPLogVerbose(@"Saving file to %@", filePath);
  183. if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
  184. HTTPLogError(@"Could not create directory at path: %@", filePath);
  185. }
  186. if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
  187. HTTPLogError(@"Could not create file at path: %@", filePath);
  188. }
  189. storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
  190. [uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];
  191. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  192. }
  193. }
  194. - (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header
  195. {
  196. // here we just write the output from parser to the file.
  197. if( storeFile ) {
  198. [storeFile writeData:data];
  199. }
  200. }
  201. - (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header
  202. {
  203. // as the file part is over, we close the file.
  204. [storeFile closeFile];
  205. storeFile = nil;
  206. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  207. /* update media library when file upload was completed */
  208. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  209. [appDelegate updateMediaList];
  210. }
  211. @end