VLCHTTPFileDownloader.m 9.8 KB

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