VLCHTTPUploaderController.m 7.5 KB

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