VLCHTTPFileDownloader.m 10 KB

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