VLCHTTPUploaderController.m 6.5 KB

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