VLCHTTPUploaderController.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /*****************************************************************************
  2. * VLCHTTPUploaderViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Jean-Baptiste Kempf <jb # videolan.org>
  9. * Gleb Pinigin <gpinigin # gmail.com>
  10. * Felix Paul Kühne <fkuehne # videolan.org>
  11. * Jean-Romain Prévost <jr # 3on.fr>
  12. *
  13. * Refer to the COPYING file of the official project for license.
  14. *****************************************************************************/
  15. #import "VLCHTTPUploaderController.h"
  16. #import "VLCHTTPConnection.h"
  17. #import "VLCActivityManager.h"
  18. #import "HTTPServer.h"
  19. #import "Reachability.h"
  20. #import <ifaddrs.h>
  21. #import <arpa/inet.h>
  22. #if TARGET_OS_IOS
  23. #import "VLCMediaFileDiscoverer.h"
  24. #endif
  25. @interface VLCHTTPUploaderController()
  26. @property(nonatomic, strong) HTTPServer *httpServer;
  27. @end
  28. @implementation VLCHTTPUploaderController
  29. {
  30. UIBackgroundTaskIdentifier _backgroundTaskIdentifier;
  31. Reachability *_reachability;
  32. }
  33. + (instancetype)sharedInstance
  34. {
  35. static VLCHTTPUploaderController *sharedInstance = nil;
  36. static dispatch_once_t pred;
  37. dispatch_once(&pred, ^{
  38. sharedInstance = [VLCHTTPUploaderController new];
  39. });
  40. return sharedInstance;
  41. }
  42. - (id)init
  43. {
  44. if (self = [super init]) {
  45. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  46. [center addObserver:self selector:@selector(applicationDidBecomeActive:)
  47. name:UIApplicationDidBecomeActiveNotification object:nil];
  48. [center addObserver:self selector:@selector(applicationDidEnterBackground:)
  49. name:UIApplicationDidEnterBackgroundNotification object:nil];
  50. [center addObserver:self selector:@selector(netReachabilityChanged) name:kReachabilityChangedNotification object:nil];
  51. BOOL isHTTPServerOn = [[NSUserDefaults standardUserDefaults] boolForKey:kVLCSettingSaveHTTPUploadServerStatus];
  52. [self changeHTTPServerState:isHTTPServerOn];
  53. }
  54. return self;
  55. }
  56. - (void)dealloc
  57. {
  58. [[NSNotificationCenter defaultCenter] removeObserver:self];
  59. }
  60. - (void)applicationDidBecomeActive: (NSNotification *)notification
  61. {
  62. if (!self.httpServer.isRunning)
  63. [self changeHTTPServerState:[[NSUserDefaults standardUserDefaults] boolForKey:kVLCSettingSaveHTTPUploadServerStatus]];
  64. if (_backgroundTaskIdentifier && _backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
  65. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  66. _backgroundTaskIdentifier = 0;
  67. }
  68. }
  69. - (void)applicationDidEnterBackground: (NSNotification *)notification
  70. {
  71. if (self.httpServer.isRunning) {
  72. if (!_backgroundTaskIdentifier || _backgroundTaskIdentifier == UIBackgroundTaskInvalid) {
  73. dispatch_block_t expirationHandler = ^{
  74. [self changeHTTPServerState:NO];
  75. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  76. _backgroundTaskIdentifier = 0;
  77. };
  78. if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginBackgroundTaskWithName:expirationHandler:)]) {
  79. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCUploader" expirationHandler:expirationHandler];
  80. } else {
  81. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:expirationHandler];
  82. }
  83. }
  84. }
  85. }
  86. - (NSString *)httpStatus
  87. {
  88. if (self.httpServer.isRunning) {
  89. if (self.httpServer.listeningPort != 80) {
  90. return [NSString stringWithFormat:@"http://%@:%i\nhttp://%@:%i", [self currentIPAddress], self.httpServer.listeningPort, [self hostname], self.httpServer.listeningPort];
  91. } else {
  92. return [NSString stringWithFormat:@"http://%@\nhttp://%@", [self currentIPAddress], [self hostname]];
  93. }
  94. } else {
  95. return NSLocalizedString(@"HTTP_UPLOAD_SERVER_OFF", nil);
  96. }
  97. }
  98. - (BOOL)isServerRunning
  99. {
  100. return self.httpServer.isRunning;
  101. }
  102. - (void)netReachabilityChanged
  103. {
  104. if (_reachability.currentReachabilityStatus != ReachableViaWiFi) {
  105. [[VLCHTTPUploaderController sharedInstance] changeHTTPServerState:NO];
  106. }
  107. }
  108. - (BOOL)changeHTTPServerState:(BOOL)state
  109. {
  110. if (!state) {
  111. [self.httpServer stop];
  112. return true;
  113. }
  114. // clean cache before accepting new stuff
  115. [self cleanCache];
  116. // Initialize our http server
  117. _httpServer = [[HTTPServer alloc] init];
  118. [_httpServer setInterface:WifiInterfaceName];
  119. [_httpServer setIPv4Enabled:YES];
  120. [_httpServer setIPv6Enabled:[[[NSUserDefaults standardUserDefaults] objectForKey:kVLCSettingWiFiSharingIPv6] boolValue]];
  121. // Tell the server to broadcast its presence via Bonjour.
  122. // This allows browsers such as Safari to automatically discover our service.
  123. [self.httpServer setType:@"_http._tcp."];
  124. // Serve files from the standard Sites folder
  125. NSString *docRoot = [[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] stringByDeletingLastPathComponent];
  126. APLog(@"Setting document root: %@", docRoot);
  127. [self.httpServer setDocumentRoot:docRoot];
  128. [self.httpServer setPort:80];
  129. [self.httpServer setConnectionClass:[VLCHTTPConnection class]];
  130. NSError *error = nil;
  131. if (![self.httpServer start:&error]) {
  132. if (error.code == EACCES) {
  133. APLog(@"Port forbidden by OS, trying another one");
  134. [self.httpServer setPort:8888];
  135. if(![self.httpServer start:&error])
  136. return true;
  137. }
  138. /* Address already in Use, take a random one */
  139. if (error.code == EADDRINUSE) {
  140. APLog(@"Port already in use, trying another one");
  141. [self.httpServer setPort:0];
  142. if(![self.httpServer start:&error])
  143. return true;
  144. }
  145. if (error) {
  146. APLog(@"Error starting HTTP Server: %@", error.localizedDescription);
  147. [self.httpServer stop];
  148. }
  149. return false;
  150. }
  151. return true;
  152. }
  153. - (NSString *)currentIPAddress
  154. {
  155. NSString *address = @"";
  156. struct ifaddrs *interfaces = NULL;
  157. struct ifaddrs *temp_addr = NULL;
  158. int success = getifaddrs(&interfaces);
  159. if (success != 0) {
  160. freeifaddrs(interfaces);
  161. return address;
  162. }
  163. temp_addr = interfaces;
  164. while (temp_addr != NULL) {
  165. if (temp_addr->ifa_addr->sa_family == AF_INET) {
  166. if([@(temp_addr->ifa_name) isEqualToString:WifiInterfaceName])
  167. address = @(inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr));
  168. }
  169. temp_addr = temp_addr->ifa_next;
  170. }
  171. freeifaddrs(interfaces);
  172. return address;
  173. }
  174. - (NSString *)hostname
  175. {
  176. char baseHostName[256];
  177. int success = gethostname(baseHostName, 255);
  178. if (success != 0)
  179. return nil;
  180. baseHostName[255] = '\0';
  181. #if !TARGET_IPHONE_SIMULATOR
  182. return [NSString stringWithFormat:@"%s.local", baseHostName];
  183. #else
  184. return [NSString stringWithFormat:@"%s", baseHostName];
  185. #endif
  186. }
  187. - (void)moveFileFrom:(NSString *)filepath
  188. {
  189. /* update media library when file upload was completed */
  190. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  191. [activityManager networkActivityStopped];
  192. [activityManager activateIdleTimer];
  193. #if TARGET_OS_IOS
  194. NSString *fileName = [filepath lastPathComponent];
  195. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  196. NSString *libraryPath = searchPaths[0];
  197. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:fileName];
  198. NSFileManager *fileManager = [NSFileManager defaultManager];
  199. if ([fileManager fileExistsAtPath:finalFilePath]) {
  200. /* we don't want to over-write existing files, so add an integer to the file name */
  201. NSString *potentialFilename;
  202. NSString *fileExtension = [fileName pathExtension];
  203. NSString *rawFileName = [fileName stringByDeletingPathExtension];
  204. for (NSUInteger x = 1; x < 100; x++) {
  205. potentialFilename = [NSString stringWithFormat:@"%@ %lu.%@", rawFileName, (unsigned long)x, fileExtension];
  206. if (![[NSFileManager defaultManager] fileExistsAtPath:[libraryPath stringByAppendingPathComponent:potentialFilename]])
  207. break;
  208. }
  209. finalFilePath = [libraryPath stringByAppendingPathComponent:potentialFilename];
  210. }
  211. NSError *error;
  212. [fileManager moveItemAtPath:filepath toPath:finalFilePath error:&error];
  213. if (error) {
  214. APLog(@"Moving received media %@ to library folder failed (%li), deleting", fileName, (long)error.code);
  215. [fileManager removeItemAtPath:filepath error:nil];
  216. }
  217. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  218. #endif
  219. }
  220. - (void)cleanCache
  221. {
  222. if ([[VLCActivityManager defaultManager] haveNetworkActivity])
  223. return;
  224. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  225. NSString* uploadDirPath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  226. NSFileManager *fileManager = [NSFileManager defaultManager];
  227. if ([fileManager fileExistsAtPath:uploadDirPath])
  228. [fileManager removeItemAtPath:uploadDirPath error:nil];
  229. }
  230. @end