VLCHTTPUploaderController.m 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /*****************************************************************************
  2. * VLCHTTPUploaderViewController.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 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. _backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"VLCUploader" expirationHandler:^{
  50. [self changeHTTPServerState:NO];
  51. [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier];
  52. _backgroundTaskIdentifier = 0;
  53. }];
  54. }
  55. }
  56. }
  57. - (BOOL)changeHTTPServerState:(BOOL)state
  58. {
  59. if (!state) {
  60. [self.httpServer stop];
  61. return true;
  62. }
  63. // Initialize our http server
  64. _httpServer = [[HTTPServer alloc] init];
  65. [_httpServer setInterface:WifiInterfaceName];
  66. // Tell the server to broadcast its presence via Bonjour.
  67. // This allows browsers such as Safari to automatically discover our service.
  68. [self.httpServer setType:@"_http._tcp."];
  69. // Serve files from the standard Sites folder
  70. NSString *docRoot = [[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] stringByDeletingLastPathComponent];
  71. APLog(@"Setting document root: %@", docRoot);
  72. [self.httpServer setDocumentRoot:docRoot];
  73. [self.httpServer setPort:80];
  74. [self.httpServer setConnectionClass:[VLCHTTPConnection class]];
  75. NSError *error = nil;
  76. if (![self.httpServer start:&error]) {
  77. if (error.code == 13) {
  78. APLog(@"Port forbidden by OS, trying another one");
  79. [self.httpServer setPort:8888];
  80. if(![self.httpServer start:&error])
  81. return true;
  82. }
  83. /* Address already in Use, take a random one */
  84. if (error.code == 48) {
  85. APLog(@"Port already in use, trying another one");
  86. [self.httpServer setPort:0];
  87. if(![self.httpServer start:&error])
  88. return true;
  89. }
  90. if (error.code != 0) {
  91. APLog(@"Error starting HTTP Server: %@", error.localizedDescription);
  92. [self.httpServer stop];
  93. }
  94. return false;
  95. }
  96. return true;
  97. }
  98. - (NSString *)currentIPAddress
  99. {
  100. NSString *address = @"";
  101. struct ifaddrs *interfaces = NULL;
  102. struct ifaddrs *temp_addr = NULL;
  103. int success = getifaddrs(&interfaces);
  104. if (success != 0) {
  105. freeifaddrs(interfaces);
  106. return address;
  107. }
  108. temp_addr = interfaces;
  109. while (temp_addr != NULL) {
  110. if (temp_addr->ifa_addr->sa_family == AF_INET) {
  111. if([@(temp_addr->ifa_name) isEqualToString:WifiInterfaceName])
  112. address = @(inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr));
  113. }
  114. temp_addr = temp_addr->ifa_next;
  115. }
  116. freeifaddrs(interfaces);
  117. return address;
  118. }
  119. - (void)moveFileFrom:(NSString *)filepath
  120. {
  121. NSString *fileName = [filepath lastPathComponent];
  122. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  123. NSString *libraryPath = searchPaths[0];
  124. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:fileName];
  125. NSFileManager *fileManager = [NSFileManager defaultManager];
  126. if ([fileManager fileExistsAtPath:finalFilePath]) {
  127. /* we don't want to over-write existing files, so add an integer to the file name */
  128. NSString *potentialFilename;
  129. NSString *fileExtension = [fileName pathExtension];
  130. NSString *rawFileName = [fileName stringByDeletingPathExtension];
  131. for (NSUInteger x = 1; x < 100; x++) {
  132. potentialFilename = [NSString stringWithFormat:@"%@ %lu.%@", rawFileName, (unsigned long)x, fileExtension];
  133. if (![[NSFileManager defaultManager] fileExistsAtPath:[libraryPath stringByAppendingPathComponent:potentialFilename]])
  134. break;
  135. }
  136. finalFilePath = [libraryPath stringByAppendingPathComponent:potentialFilename];
  137. }
  138. NSError *error;
  139. [fileManager moveItemAtPath:filepath toPath:finalFilePath error:&error];
  140. if (error) {
  141. APLog(@"Moving received media %@ to library folder failed (%li), deleting", fileName, (long)error.code);
  142. [fileManager removeItemAtPath:filepath error:nil];
  143. }
  144. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  145. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate activateIdleTimer];
  146. /* update media library when file upload was completed */
  147. VLCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
  148. [appDelegate performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  149. }
  150. @end