VLCHTTPUploaderController.m 11 KB

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