VLCHTTPUploaderController.m 7.4 KB

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