VLCHTTPUploaderController.m 8.0 KB

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