VLCHTTPUploaderController.m 10 KB

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