VLCHTTPFileDownloader.m 9.4 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. #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*)[UIApplication sharedApplication].delegate networkActivityStarted];
  60. [(VLCAppDelegate*)[UIApplication sharedApplication].delegate disableIdleTimer];
  61. }
  62. }
  63. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
  64. {
  65. if (redirectResponse) {
  66. NSURL *URL = [request URL];
  67. NSFileManager *fileManager = [NSFileManager defaultManager];
  68. if ([fileManager fileExistsAtPath:_filePath])
  69. [fileManager removeItemAtPath:_filePath error:nil];
  70. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  71. NSString *basePath = [searchPaths[0] stringByAppendingPathComponent:@"Upload"];
  72. _fileName = [URL lastPathComponent];
  73. _filePath = [basePath stringByAppendingPathComponent:_fileName];
  74. if (![fileManager fileExistsAtPath:basePath])
  75. [fileManager createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:nil];
  76. NSMutableURLRequest *newRequest = [_originalRequest mutableCopy];
  77. [newRequest setURL:URL];
  78. return newRequest;
  79. } else
  80. return request;
  81. }
  82. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
  83. {
  84. _statusCode = [response statusCode];
  85. if (_statusCode == 200) {
  86. if (![[response suggestedFilename] isSupportedFormat]) {
  87. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"FILE_NOT_SUPPORTED", nil)
  88. message:[NSString stringWithFormat:NSLocalizedString(@"FILE_NOT_SUPPORTED_LONG", nil), [response suggestedFilename]]
  89. delegate:self
  90. cancelButtonTitle:NSLocalizedString(@"BUTTON_CANCEL", nil)
  91. otherButtonTitles:nil];
  92. [alert show];
  93. [_urlConnection cancel];
  94. NSFileManager *fileManager = [NSFileManager defaultManager];
  95. if ([fileManager fileExistsAtPath:_filePath])
  96. [fileManager removeItemAtPath:_filePath error:nil];
  97. [self _downloadEnded];
  98. } else {
  99. _expectedDownloadSize = [response expectedContentLength];
  100. if (_expectedDownloadSize < [[UIDevice currentDevice] freeDiskspace].longLongValue)
  101. [self.delegate downloadStarted];
  102. else {
  103. [_urlConnection cancel];
  104. [self _downloadEnded];
  105. VLCAlertView *alert = [[VLCAlertView alloc] initWithTitle:NSLocalizedString(@"DISK_FULL", nil)
  106. message:[NSString stringWithFormat:NSLocalizedString(@"DISK_FULL_FORMAT", nil), _fileName, [[UIDevice currentDevice] model]]
  107. delegate:self
  108. cancelButtonTitle:NSLocalizedString(@"BUTTON_OK", nil)
  109. otherButtonTitles:nil];
  110. [alert show];
  111. }
  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