VLCHTTPFileDownloader.m 8.6 KB

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