VLCHTTPFileDownloader.m 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 "VLCAppDelegate.h"
  16. #import "UIDevice+VLC.h"
  17. @interface VLCHTTPFileDownloader ()
  18. {
  19. NSString *_filePath;
  20. NSUInteger _expectedDownloadSize;
  21. NSUInteger _receivedDataSize;
  22. NSString *_fileName;
  23. NSURLConnection *_urlConnection;
  24. NSMutableURLRequest *_originalRequest;
  25. NSUInteger _statusCode;
  26. }
  27. @end
  28. @implementation VLCHTTPFileDownloader
  29. - (NSString *)userReadableDownloadName
  30. {
  31. return _fileName;
  32. }
  33. - (void)downloadFileFromURL:(NSURL *)url
  34. {
  35. [self downloadFileFromURL:url withFileName:nil];
  36. }
  37. - (void)downloadFileFromURL:(NSURL *)url withFileName:(NSString*)fileName
  38. {
  39. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  40. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  41. if (fileName)
  42. _fileName = fileName;
  43. else
  44. _fileName = url.lastPathComponent;
  45. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  46. NSFileManager *fileManager = [NSFileManager defaultManager];
  47. if (![fileManager fileExistsAtPath:basePath])
  48. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  49. _expectedDownloadSize = _receivedDataSize = 0;
  50. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
  51. [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"];
  52. _originalRequest = [theRequest mutableCopy];
  53. _urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
  54. if (!_urlConnection) {
  55. APLog(@"failed to establish connection");
  56. _downloadInProgress = NO;
  57. } else {
  58. _downloadInProgress = YES;
  59. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  60. [appDelegate networkActivityStarted];
  61. [appDelegate disableIdleTimer];
  62. }
  63. }
  64. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
  65. {
  66. if (redirectResponse) {
  67. NSURL *URL = [request URL];
  68. NSFileManager *fileManager = [NSFileManager defaultManager];
  69. if ([fileManager fileExistsAtPath:_filePath])
  70. [fileManager removeItemAtPath:_filePath error:nil];
  71. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  72. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  73. _fileName = [URL lastPathComponent];
  74. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  75. if (![fileManager fileExistsAtPath:basePath])
  76. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  77. NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
  78. [newRequest setURL:URL];
  79. return newRequest;
  80. } else
  81. return request;
  82. }
  83. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
  84. {
  85. _statusCode = [response statusCode];
  86. if (_statusCode == 200) {
  87. if (![[response suggestedFilename] isSupportedFormat]) {
  88. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  89. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [response suggestedFilename]]
  90. delegate:self
  91. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  92. otherButtonTitles:nil];
  93. [alert show];
  94. [_urlConnection cancel];
  95. NSFileManager *fileManager = [NSFileManager defaultManager];
  96. if ([fileManager fileExistsAtPath:_filePath])
  97. [fileManager removeItemAtPath:_filePath error:nil];
  98. [self _downloadEnded];
  99. } else {
  100. _expectedDownloadSize = [response expectedContentLength];
  101. if (_expectedDownloadSize < [[UIDevice currentDevice] freeDiskspace].longLongValue)
  102. [self.delegate downloadStarted];
  103. else {
  104. [_urlConnection cancel];
  105. [self _downloadEnded];
  106. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  107. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _fileName, [[UIDevice currentDevice] model]]
  108. delegate:self
  109. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  110. otherButtonTitles:nil];
  111. [alert show];
  112. }
  113. APLog(@"expected download size: %lu", (unsigned long)_expectedDownloadSize);
  114. }
  115. } else {
  116. APLog(@"unhandled status code %lu", (unsigned long)_statusCode);
  117. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  118. [self.delegate downloadFailedWithErrorDescription:[NSString stringWithFormat:NSLocalizedString(@"HTTP_DOWNLOAD_FAILED",nil), _statusCode]];
  119. }
  120. }
  121. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  122. {
  123. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  124. if (!fileHandle && _statusCode != 404) {
  125. // create file
  126. [[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
  127. fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
  128. if (!fileHandle) {
  129. APLog(@"file creation failed, no data was saved");
  130. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  131. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_FILE_CREATION_FAILED",nil)];
  132. return;
  133. }
  134. }
  135. @try {
  136. [fileHandle seekToEndOfFile];
  137. [fileHandle writeData:data];
  138. _receivedDataSize = _receivedDataSize + [data length];
  139. if ([self.delegate respondsToSelector:@selector(progressUpdatedTo:receivedDataSize:expectedDownloadSize:)])
  140. [self.delegate progressUpdatedTo: (float)_receivedDataSize / (float)_expectedDownloadSize receivedDataSize:_receivedDataSize expectedDownloadSize:_expectedDownloadSize];
  141. }
  142. @catch (NSException * e) {
  143. APLog(@"exception when writing to file %@", _filePath);
  144. }
  145. [fileHandle closeFile];
  146. }
  147. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  148. {
  149. APLog(@"http file download complete");
  150. [self _downloadEnded];
  151. }
  152. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
  153. {
  154. APLog(@"http file download failed (%li)", (long)error.code);
  155. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  156. [self.delegate downloadFailedWithErrorDescription:error.description];
  157. [self _downloadEnded];
  158. }
  159. - (void)cancelDownload
  160. {
  161. [_urlConnection cancel];
  162. /* remove partially downloaded content */
  163. NSFileManager *fileManager = [NSFileManager defaultManager];
  164. if ([fileManager fileExistsAtPath:_filePath])
  165. [fileManager removeItemAtPath:_filePath error:nil];
  166. if ([self.delegate respondsToSelector:@selector(downloadFailedWithErrorDescription:)])
  167. [self.delegate downloadFailedWithErrorDescription:NSLocalizedString(@"HTTP_DOWNLOAD_CANCELLED",nil)];
  168. [self _downloadEnded];
  169. }
  170. - (void)_downloadEnded
  171. {
  172. _downloadInProgress = NO;
  173. VLCAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
  174. [appDelegate networkActivityStopped];
  175. [appDelegate activateIdleTimer];
  176. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  177. NSString *libraryPath = searchPaths[0];
  178. NSFileManager *fileManager = [NSFileManager defaultManager];
  179. NSString *finalFilePath = [libraryPath stringByAppendingPathComponent:_fileName];
  180. if ([fileManager fileExistsAtPath:_filePath]) {
  181. [fileManager moveItemAtPath:_filePath toPath:finalFilePath error:nil];
  182. [appDelegate performSelectorOnMainThread:@selector(updateMediaList) withObject:nil waitUntilDone:NO];
  183. }
  184. [self.delegate downloadEnded];
  185. }
  186. @end