VLCHTTPUploaderController.m 6.9 KB

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