VLCHTTPFileDownloader.m 7.8 KB

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