VLCHTTPUploaderController.m 9.9 KB

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