VLCHTTPUploaderController.m 9.3 KB

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