VLCHTTPFileDownloader.m 6.9 KB

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