VLCHTTPFileDownloader.m 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*****************************************************************************
  2. * VLCHTTPFileDownloader.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Felix Paul Kühne <fkuehne # videolan.org>
  9. * Pierre Sagaspe <pierre.sagaspe # me.com>
  10. *
  11. * Refer to the COPYING file of the official project for license.
  12. *****************************************************************************/
  13. #import "VLCHTTPFileDownloader.h"
  14. #import "NSString+SupportedMedia.h"
  15. #import "VLCActivityManager.h"
  16. #import "UIDevice+VLC.h"
  17. #import "VLCMediaFileDiscoverer.h"
  18. @interface VLCHTTPFileDownloader ()
  19. {
  20. NSString *_filePath;
  21. NSUInteger _expectedDownloadSize;
  22. NSUInteger _receivedDataSize;
  23. NSString *_fileName;
  24. NSURLConnection *_urlConnection;
  25. NSMutableURLRequest *_originalRequest;
  26. NSUInteger _statusCode;
  27. }
  28. @end
  29. @implementation VLCHTTPFileDownloader
  30. - (NSString *)userReadableDownloadName
  31. {
  32. return _fileName;
  33. }
  34. - (void)downloadFileFromURL:(NSURL *)url
  35. {
  36. [self downloadFileFromURL:url withFileName:nil];
  37. }
  38. - (void)downloadFileFromURL:(NSURL *)url withFileName:(NSString*)fileName
  39. {
  40. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  41. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  42. if (fileName)
  43. _fileName = fileName;
  44. else
  45. _fileName = url.lastPathComponent;
  46. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  47. NSFileManager *fileManager = [NSFileManager defaultManager];
  48. if (![fileManager fileExistsAtPath:basePath])
  49. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  50. _expectedDownloadSize = _receivedDataSize = 0;
  51. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
  52. [theRequest addValue:[NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/%@ Mobile/11A465 Safari/9537.53 VLC for iOS/%@", UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone", [[UIDevice currentDevice] systemVersion], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"User-Agent"];
  53. _originalRequest = [theRequest mutableCopy];
  54. _urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  55. if (!_urlConnection) {
  56. APLog(@"failed to establish connection");
  57. _downloadInProgress = NO;
  58. } else {
  59. _downloadInProgress = YES;
  60. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  61. [activityManager networkActivityStarted];
  62. [activityManager disableIdleTimer];
  63. }
  64. }
  65. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
  66. {
  67. if (redirectResponse) {
  68. NSURL *URL = [request URL];
  69. NSFileManager *fileManager = [NSFileManager defaultManager];
  70. if ([fileManager fileExistsAtPath:_filePath])
  71. [fileManager removeItemAtPath:_filePath error:nil];
  72. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  73. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  74. _fileName = [URL lastPathComponent];
  75. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  76. if (![fileManager fileExistsAtPath:basePath])
  77. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  78. NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
  79. [newRequest setURL:URL];
  80. return newRequest;
  81. } else
  82. return request;
  83. }
  84. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
  85. {
  86. _statusCode = [response statusCode];
  87. if (_statusCode == 200) {
  88. if (![[response suggestedFilename] isSupportedFormat]) {
  89. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  90. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [response suggestedFilename]]
  91. delegate:self
  92. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  93. otherButtonTitles:nil];
  94. [alert show];
  95. [_urlConnection cancel];
  96. NSFileManager *fileManager = [NSFileManager defaultManager];
  97. if ([fileManager fileExistsAtPath:_filePath])
  98. [fileManager removeItemAtPath:_filePath error:nil];
  99. [self _downloadEnded];
  100. } else {
  101. _expectedDownloadSize = [response expectedContentLength];
  102. if (_expectedDownloadSize < [[UIDevice currentDevice] freeDiskspace].longLongValue)
  103. [self.delegate downloadStarted];
  104. else {
  105. [_urlConnection cancel];
  106. [self _downloadEnded];
  107. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  108. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _fileName, [[UIDevice currentDevice] model]]
  109. delegate:self
  110. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  111. otherButtonTitles:nil];
  112. [alert show];
  113. }
  114. APLog(@"expected download size: %lu", (unsigned long)_expectedDownloadSize);
  115. }
  116. } else {
  117. APLog(@"unhandled status code %lu", (unsigned long)_statusCode);
  118. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  119. [self.delegate downloadFailedWithErrorDescription:[NSString stringWithFormat:NSLocalizedString(@"HTTP_DOWNLOAD_FAILED",nil), _statusCode]];
  120. }
  121. }
  122. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  123. {
  124. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  125. if (!fileHandle && _statusCode != 404) {
  126. // create file
  127. [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
  128. fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  129. if (!fileHandle) {
  130. APLog(@"file creation failed, no data was saved");
  131. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  132. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_FILE_CREATION_FAILED",nil)];
  133. return;
  134. }
  135. }
  136. @try {
  137. [fileHandle seekToEndOfFile];
  138. [fileHandle writeData:data];
  139. _receivedDataSize = _receivedDataSize + [data length];
  140. if ([self.delegate respondsToSelector:@selector(progressUpdatedTo:receivedDataSize:expectedDownloadSize:)])
  141. [self.delegate progressUpdatedTo: (float)_receivedDataSize / (float)_expectedDownloadSize receivedDataSize:_receivedDataSize expectedDownloadSize:_expectedDownloadSize];
  142. }
  143. @catch (NSException * e) {
  144. APLog(@"exception when writing to file %@", _filePath);
  145. }
  146. [fileHandle closeFile];
  147. }
  148. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  149. {
  150. APLog(@"http file download complete");
  151. [self _downloadEnded];
  152. }
  153. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
  154. {
  155. APLog(@"http file download failed (%li)", (long)error.code);
  156. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  157. [self.delegate downloadFailedWithErrorDescription:error.description];
  158. [self _downloadEnded];
  159. }
  160. - (void)cancelDownload
  161. {
  162. [_urlConnection cancel];
  163. /* remove partially downloaded content */
  164. NSFileManager *fileManager = [NSFileManager defaultManager];
  165. if ([fileManager fileExistsAtPath:_filePath])
  166. [fileManager removeItemAtPath:_filePath error:nil];
  167. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  168. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_DOWNLOAD_CANCELLED",nil)];
  169. [self _downloadEnded];
  170. }
  171. - (void)_downloadEnded
  172. {
  173. _downloadInProgress = NO;
  174. VLCActivityManager *activityManager = [VLCActivityManager defaultManager];
  175. [activityManager networkActivityStopped];
  176. [activityManager activateIdleTimer];
  177. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  178. NSString *libraryPath = searchPaths[0];
  179. NSFileManager *fileManager = [NSFileManager defaultManager];
  180. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_fileName];
  181. if ([fileManager fileExistsAtPath:_filePath]) {
  182. [fileManager moveItemAtPath:_filePath toPath:finalFilePath error:nil];
  183. [[VLCMediaFileDiscoverer sharedInstance] performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  184. }
  185. [self.delegate downloadEnded];
  186. }
  187. @end