VLCHTTPUploaderController.m 9.2 KB

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