VLCHTTPUploaderController.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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:80];
  73. [self.httpServer setConnectionClass:[VLCHTTPConnection class]];
  74. NSError *error = nil;
  75. if(![self.httpServer start:&error])
  76. {
  77. if (error.code == 13) {
  78. DDLogError(@"Port forbidden by OS, trying another one");
  79. [self.httpServer setPort:8888];
  80. if(![self.httpServer start:&error])
  81. return true;
  82. }
  83. /* Address already in Use, take a random one */
  84. if(error.code == 48) {
  85. DDLogError(@"Port already in use, trying another one");
  86. [self.httpServer setPort:0];
  87. if(![self.httpServer start:&error])
  88. return true;
  89. }
  90. DDLogError(@"Error starting HTTP Server: %@", error);
  91. return false;
  92. }
  93. return true;
  94. } else {
  95. [self.httpServer stop];
  96. return true;
  97. }
  98. }
  99. - (NSString *)currentIPAddress
  100. {
  101. NSString *address = @"";
  102. struct ifaddrs *interfaces = NULL;
  103. struct ifaddrs *temp_addr = NULL;
  104. int success = getifaddrs(&interfaces);
  105. if (success == 0) {
  106. temp_addr = interfaces;
  107. while(temp_addr != NULL) {
  108. if(temp_addr->ifa_addr->sa_family == AF_INET) {
  109. if([@(temp_addr->ifa_name) isEqualToString:WifiInterfaceName])
  110. address = @(inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr));
  111. }
  112. temp_addr = temp_addr->ifa_next;
  113. }
  114. }
  115. // Free memory
  116. freeifaddrs(interfaces);
  117. return address;
  118. }
  119. @end
  120. /**
  121. * All we have to do is override appropriate methods in HTTPConnection.
  122. **/
  123. @implementation VLCHTTPConnection
  124. - (BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path
  125. {
  126. HTTPLogTrace();
  127. // Add support for POST
  128. if ([method isEqualToString:@"POST"])
  129. {
  130. if ([path isEqualToString:@"/upload.json"])
  131. {
  132. return YES;
  133. }
  134. }
  135. return [super supportsMethod:method atPath:path];
  136. }
  137. - (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path
  138. {
  139. HTTPLogTrace();
  140. // Inform HTTP server that we expect a body to accompany a POST request
  141. if([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"]) {
  142. // here we need to make sure, boundary is set in header
  143. NSString* contentType = [request headerField:@"Content-Type"];
  144. NSUInteger paramsSeparator = [contentType rangeOfString:@";"].location;
  145. if( NSNotFound == paramsSeparator ) {
  146. return NO;
  147. }
  148. if( paramsSeparator >= contentType.length - 1 ) {
  149. return NO;
  150. }
  151. NSString* type = [contentType substringToIndex:paramsSeparator];
  152. if( ![type isEqualToString:@"multipart/form-data"] ) {
  153. // we expect multipart/form-data content type
  154. return NO;
  155. }
  156. // enumerate all params in content-type, and find boundary there
  157. NSArray* params = [[contentType substringFromIndex:paramsSeparator + 1] componentsSeparatedByString:@";"];
  158. for( NSString* param in params ) {
  159. paramsSeparator = [param rangeOfString:@"="].location;
  160. if( (NSNotFound == paramsSeparator) || paramsSeparator >= param.length - 1 ) {
  161. continue;
  162. }
  163. NSString* paramName = [param substringWithRange:NSMakeRange(1, paramsSeparator-1)];
  164. NSString* paramValue = [param substringFromIndex:paramsSeparator+1];
  165. if( [paramName isEqualToString: @"boundary"] ) {
  166. // let's separate the boundary from content-type, to make it more handy to handle
  167. [request setHeaderField:@"boundary" value:paramValue];
  168. }
  169. }
  170. // check if boundary specified
  171. if( nil == [request headerField:@"boundary"] ) {
  172. return NO;
  173. }
  174. return YES;
  175. }
  176. return [super expectsRequestBodyFromMethod:method atPath:path];
  177. }
  178. - (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path
  179. {
  180. HTTPLogTrace();
  181. if ([method isEqualToString:@"POST"] && [path isEqualToString:@"/upload.json"])
  182. {
  183. return [[HTTPDataResponse alloc] initWithData:[@"\"OK\"" dataUsingEncoding:NSUTF8StringEncoding]];
  184. }
  185. if( [method isEqualToString:@"GET"] && [path hasPrefix:@"/upload/"] ) {
  186. // let download the uploaded files
  187. return [[HTTPFileResponse alloc] initWithFilePath: [[config documentRoot] stringByAppendingString:path] forConnection:self];
  188. }
  189. return [super httpResponseForMethod:method URI:path];
  190. }
  191. - (void)prepareForBodyWithSize:(UInt64)contentLength
  192. {
  193. HTTPLogTrace();
  194. // set up mime parser
  195. NSString* boundary = [request headerField:@"boundary"];
  196. parser = [[MultipartFormDataParser alloc] initWithBoundary:boundary formEncoding:NSUTF8StringEncoding];
  197. parser.delegate = self;
  198. uploadedFiles = [[NSMutableArray alloc] init];
  199. }
  200. - (void)processBodyData:(NSData *)postDataChunk
  201. {
  202. HTTPLogTrace();
  203. // append data to the parser. It will invoke callbacks to let us handle
  204. // parsed data.
  205. [parser appendData:postDataChunk];
  206. }
  207. //-----------------------------------------------------------------
  208. #pragma mark multipart form data parser delegate
  209. - (void) processStartOfPartWithHeader:(MultipartMessageHeader*) header {
  210. // in this sample, we are not interested in parts, other then file parts.
  211. // check content disposition to find out filename
  212. MultipartMessageHeaderField* disposition = (header.fields)[@"Content-Disposition"];
  213. NSString* filename = [(disposition.params)[@"filename"] lastPathComponent];
  214. if ( (nil == filename) || [filename isEqualToString: @""] ) {
  215. // it's either not a file part, or
  216. // an empty form sent. we won't handle it.
  217. return;
  218. }
  219. // create the path where to store the media
  220. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  221. NSString* uploadDirPath = searchPaths[0];
  222. BOOL isDir = YES;
  223. if (![[NSFileManager defaultManager]fileExistsAtPath:uploadDirPath isDirectory:&isDir ]) {
  224. [[NSFileManager defaultManager]createDirectoryAtPath:uploadDirPath withIntermediateDirectories:YES attributes:nil error:nil];
  225. }
  226. NSString* filePath = [uploadDirPath stringByAppendingPathComponent: filename];
  227. if( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
  228. storeFile = nil;
  229. }
  230. else {
  231. HTTPLogVerbose(@"Saving file to %@", filePath);
  232. if(![[NSFileManager defaultManager] createDirectoryAtPath:uploadDirPath withIntermediateDirectories:true attributes:nil error:nil]) {
  233. HTTPLogError(@"Could not create directory at path: %@", filePath);
  234. }
  235. if(![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
  236. HTTPLogError(@"Could not create file at path: %@", filePath);
  237. }
  238. storeFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
  239. [uploadedFiles addObject: [NSString stringWithFormat:@"/upload/%@", filename]];
  240. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  241. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  242. }
  243. }
  244. - (void) processContent:(NSData*) data WithHeader:(MultipartMessageHeader*) header
  245. {
  246. // here we just write the output from parser to the file.
  247. if( storeFile ) {
  248. [storeFile writeData:data];
  249. }
  250. }
  251. - (void) processEndOfPartWithHeader:(MultipartMessageHeader*) header
  252. {
  253. // as the file part is over, we close the file.
  254. [storeFile closeFile];
  255. storeFile = nil;
  256. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  257. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate activateIdleTimer];
  258. /* update media library when file upload was completed */
  259. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  260. [appDelegate updateMediaList];
  261. }
  262. @end