From dc85d6386153ca36867a26010d1da286bab92e87 Mon Sep 17 00:00:00 2001 From: Deadpikle Date: Wed, 20 Dec 2017 11:14:02 -0500 Subject: [PATCH] Refactor download NSURLSession to a child class --- Sparkle.xcodeproj/project.pbxproj | 10 +++ Sparkle/SPUDownloader.m | 119 +------------------------ Sparkle/SPUDownloaderSession.h | 15 ++++ Sparkle/SPUDownloaderSession.m | 142 ++++++++++++++++++++++++++++++ Sparkle/SPUDownloader_Private.h | 38 ++++++++ 5 files changed, 206 insertions(+), 118 deletions(-) create mode 100644 Sparkle/SPUDownloaderSession.h create mode 100644 Sparkle/SPUDownloaderSession.m create mode 100644 Sparkle/SPUDownloader_Private.h diff --git a/Sparkle.xcodeproj/project.pbxproj b/Sparkle.xcodeproj/project.pbxproj index 06ddce0a..c74dae2f 100644 --- a/Sparkle.xcodeproj/project.pbxproj +++ b/Sparkle.xcodeproj/project.pbxproj @@ -59,6 +59,8 @@ 34074B9B1FEABD49001CB3A5 /* SPUURLRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */; }; 34074B9E1FEABD5A001CB3A5 /* SPUDownloadData.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */; }; 34074B9F1FEABD5A001CB3A5 /* SPUDownloadData.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */; }; + 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */ = {isa = PBXBuildFile; fileRef = 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */; }; + 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */ = {isa = PBXBuildFile; fileRef = 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */; }; 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */ = {isa = PBXBuildFile; fileRef = 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */; settings = {ATTRIBUTES = (Public, ); }; }; 55C14BD4136EEFCE00649790 /* Autoupdate.m in Sources */ = {isa = PBXBuildFile; fileRef = 55C14BD3136EEFCE00649790 /* Autoupdate.m */; }; 55C14BD9136EF00C00649790 /* SUStatus.xib in Resources */ = {isa = PBXBuildFile; fileRef = 55C14BD8136EF00C00649790 /* SUStatus.xib */; }; @@ -540,6 +542,9 @@ 34074B991FEABD49001CB3A5 /* SPUURLRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUURLRequest.h; sourceTree = ""; }; 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPUDownloadData.m; sourceTree = ""; }; 34074B9D1FEABD5A001CB3A5 /* SPUDownloadData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPUDownloadData.h; sourceTree = ""; }; + 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloaderSession.h; sourceTree = ""; }; + 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SPUDownloaderSession.m; sourceTree = ""; }; + 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SPUDownloader_Private.h; sourceTree = ""; }; 3772FEA813DE0B6B00F79537 /* SUVersionDisplayProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SUVersionDisplayProtocol.h; sourceTree = ""; }; 4607BEA21948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nb; path = nb.lproj/Sparkle.strings; sourceTree = ""; }; 4607BEA31948443800EF8DA4 /* nb */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = nb; path = nb.lproj/SUAutomaticUpdateAlert.xib; sourceTree = ""; }; @@ -1107,6 +1112,9 @@ 34074B9C1FEABD5A001CB3A5 /* SPUDownloadData.m */, 34074B8D1FEABD08001CB3A5 /* SPUDownloader.h */, 34074B8C1FEABD08001CB3A5 /* SPUDownloader.m */, + 34074BA41FEAC0BC001CB3A5 /* SPUDownloader_Private.h */, + 34074BA01FEABFD2001CB3A5 /* SPUDownloaderSession.h */, + 34074BA11FEABFD2001CB3A5 /* SPUDownloaderSession.m */, 34074B8E1FEABD08001CB3A5 /* SPUDownloaderDelegate.h */, 34074B8F1FEABD08001CB3A5 /* SPUDownloaderProtocol.h */, 34074B941FEABD23001CB3A5 /* SPULocalCacheDirectory.h */, @@ -1472,6 +1480,7 @@ 61A354550DF113C70076ECB1 /* SUUserInitiatedUpdateDriver.h in Headers */, 61A2259E0D1C495D00430CCD /* SUVersionComparisonProtocol.h in Headers */, 3772FEA913DE0B6B00F79537 /* SUVersionDisplayProtocol.h in Headers */, + 34074BA21FEABFD2001CB3A5 /* SPUDownloaderSession.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2052,6 +2061,7 @@ 5D06E8EC0FD68CE4005AE3F6 /* SUBinaryDeltaApply.m in Sources */, 34074B971FEABD24001CB3A5 /* SPULocalCacheDirectory.m in Sources */, 5D06E8ED0FD68CE4005AE3F6 /* SUBinaryDeltaCommon.m in Sources */, + 34074BA31FEABFD2001CB3A5 /* SPUDownloaderSession.m in Sources */, 5D06E93A0FD69271005AE3F6 /* SUBinaryDeltaUnarchiver.m in Sources */, 72316BDA1E0E17180039EFD9 /* SUBundleIcon.m in Sources */, 61B078CF15A5FB6100600039 /* SUCodeSigningVerifier.m in Sources */, diff --git a/Sparkle/SPUDownloader.m b/Sparkle/SPUDownloader.m index 2f0447de..8e3d776f 100755 --- a/Sparkle/SPUDownloader.m +++ b/Sparkle/SPUDownloader.m @@ -12,30 +12,13 @@ #import "SPUURLRequest.h" #import "SPUDownloadData.h" #import "SUErrors.h" - +#import "SPUDownloader_Private.h" #include "AppKitPrevention.h" -typedef NS_ENUM(NSUInteger, SPUDownloadMode) -{ - SPUDownloadModePersistent, - SPUDownloadModeTemporary -}; - -static NSString *SUDownloadingReason = @"Downloading update related file"; - @interface SPUDownloader () -// Delegate is intentionally strongly referenced; see header -@property (nonatomic) id delegate; -@property (nonatomic) NSURLSessionDownloadTask *download; @property (nonatomic) NSURLSession *downloadSession; -@property (nonatomic, copy) NSString *bundleIdentifier; -@property (nonatomic, copy) NSString *desiredFilename; -@property (nonatomic, copy) NSString *downloadFilename; -@property (nonatomic) BOOL disabledAutomaticTermination; -@property (nonatomic) SPUDownloadMode mode; -@property (nonatomic) BOOL receivedExpectedBytes; @end @@ -43,7 +26,6 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; @synthesize delegate = _delegate; @synthesize download = _download; -@synthesize downloadSession = _downloadSession; @synthesize bundleIdentifier = _bundleIdentifier; @synthesize desiredFilename = _desiredFilename; @synthesize downloadFilename = _downloadFilename; @@ -74,33 +56,10 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; - (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename { - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.download == nil && self.delegate != nil) { - // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks - [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = YES; - - self.mode = SPUDownloadModePersistent; - self.desiredFilename = desiredFilename; - self.bundleIdentifier = bundleIdentifier; - - [self startDownloadWithRequest:request]; - } - }); } - (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request { - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.download == nil && self.delegate != nil) { - // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks - [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; - self.disabledAutomaticTermination = YES; - - self.mode = SPUDownloadModeTemporary; - [self startDownloadWithRequest:request]; - } - }); } - (void)enableAutomaticTermination @@ -126,72 +85,6 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; } } -- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location -{ - if (self.mode == SPUDownloadModeTemporary) - { - self.downloadFilename = location.path; - [self downloadDidFinish]; // file is already in a system temp dir - } - else - { - // Remove our old caches path so we don't start accumulating files in there - NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; - - [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; - - NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; - if (tempDir == nil) - { - // Okay, something's really broken with this user's file structure. - [self.download cancel]; - self.download = nil; - - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; - - [self.delegate downloaderDidFailWithError:error]; - } else { - NSString *downloadFileName = self.desiredFilename; - NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; - - NSError *createError = nil; - if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { - NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; - - [self.delegate downloaderDidFailWithError:error]; - } else { - NSString *name = self.download.response.suggestedFilename; - if (!name) { - name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp) - } - NSString *toPath = [downloadFileNameDirectory stringByAppendingPathComponent:name]; - NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning - NSError *error = nil; - if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) { - self.downloadFilename = toPath; - [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; - [self downloadDidFinish]; - } else { - [self.delegate downloaderDidFailWithError:error]; - } - } - } - } -} - -- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite -{ - - if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) { - self.receivedExpectedBytes = YES; - [self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; - } - - if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) { - [self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; - } -} - - (void)downloadDidFinish { assert(self.downloadFilename != nil); @@ -224,14 +117,4 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; [self cleanup]; } -- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error -{ - self.download = nil; - [self.delegate downloaderDidFailWithError:error]; - [self cleanup]; -} - -// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. -// This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. - @end diff --git a/Sparkle/SPUDownloaderSession.h b/Sparkle/SPUDownloaderSession.h new file mode 100644 index 00000000..b8a25bf1 --- /dev/null +++ b/Sparkle/SPUDownloaderSession.h @@ -0,0 +1,15 @@ +// +// SPUDownloaderSession.h +// Sparkle +// +// Created by Deadpikle on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#import +#import "SPUDownloader.h" +#import "SPUDownloaderProtocol.h" + +@interface SPUDownloaderSession : SPUDownloader + +@end diff --git a/Sparkle/SPUDownloaderSession.m b/Sparkle/SPUDownloaderSession.m new file mode 100644 index 00000000..d9abbcf4 --- /dev/null +++ b/Sparkle/SPUDownloaderSession.m @@ -0,0 +1,142 @@ +// +// SPUDownloaderSession.m +// Sparkle +// +// Created by Deadpikle on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#import "SPUDownloaderSession.h" +#import "SPUURLRequest.h" +#import "SPUDownloader_Private.h" +#import "SPULocalCacheDirectory.h" +#import "SUErrors.h" + +@interface SPUDownloaderSession () + +@property (nonatomic) NSURLSession *downloadSession; + +@end + +@implementation SPUDownloaderSession + +@synthesize downloadSession = _downloadSession; + +- (void)startDownloadWithRequest:(SPUURLRequest *)request +{ + self.downloadSession = [NSURLSession + sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] + delegate:self + delegateQueue:[NSOperationQueue mainQueue]]; + self.download = [self.downloadSession downloadTaskWithRequest:request.request]; + [self.download resume]; +} + +- (void)startPersistentDownloadWithRequest:(SPUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModePersistent; + self.desiredFilename = desiredFilename; + self.bundleIdentifier = bundleIdentifier; + + [self startDownloadWithRequest:request]; + } + }); +} + +- (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.download == nil && self.delegate != nil) { + // Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks + [[NSProcessInfo processInfo] disableAutomaticTermination:SUDownloadingReason]; + self.disabledAutomaticTermination = YES; + + self.mode = SPUDownloadModeTemporary; + [self startDownloadWithRequest:request]; + } + }); +} + +- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location +{ + if (self.mode == SPUDownloadModeTemporary) + { + self.downloadFilename = location.path; + [self downloadDidFinish]; // file is already in a system temp dir + } + else + { + // Remove our old caches path so we don't start accumulating files in there + NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; + + [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; + + NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; + if (tempDir == nil) + { + // Okay, something's really broken with this user's file structure. + [self.download cancel]; + self.download = nil; + + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a temporary directory for the update download at %@.", tempDir] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *downloadFileName = self.desiredFilename; + NSString *downloadFileNameDirectory = [tempDir stringByAppendingPathComponent:downloadFileName]; + + NSError *createError = nil; + if (![[NSFileManager defaultManager] createDirectoryAtPath:downloadFileNameDirectory withIntermediateDirectories:NO attributes:nil error:&createError]) { + NSError *error = [NSError errorWithDomain:SUSparkleErrorDomain code:SUTemporaryDirectoryError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Can't make a download file name %@ directory inside temporary directory for the update download at %@.", downloadFileName, downloadFileNameDirectory] }]; + + [self.delegate downloaderDidFailWithError:error]; + } else { + NSString *name = self.download.response.suggestedFilename; + if (!name) { + name = location.lastPathComponent; // This likely contains nothing useful to identify the file (e.g. CFNetworkDownload_87LVIz.tmp) + } + NSString *toPath = [downloadFileNameDirectory stringByAppendingPathComponent:name]; + NSString *fromPath = location.path; // suppress moveItemAtPath: non-null warning + NSError *error = nil; + if ([[NSFileManager defaultManager] moveItemAtPath:fromPath toPath:toPath error:&error]) { + self.downloadFilename = toPath; + [self.delegate downloaderDidSetDestinationName:name temporaryDirectory:downloadFileNameDirectory]; + [self downloadDidFinish]; + } else { + [self.delegate downloaderDidFailWithError:error]; + } + } + } + } +} + +- (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)__unused totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + + if (self.mode == SPUDownloadModePersistent && totalBytesExpectedToWrite > 0 && !self.receivedExpectedBytes) { + self.receivedExpectedBytes = YES; + [self.delegate downloaderDidReceiveExpectedContentLength:totalBytesExpectedToWrite]; + } + + if (self.mode == SPUDownloadModePersistent && bytesWritten >= 0) { + [self.delegate downloaderDidReceiveDataOfLength:(uint64_t)bytesWritten]; + } +} + +- (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error +{ + self.download = nil; + [self.delegate downloaderDidFailWithError:error]; + [self cleanup]; +} + +// NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. +// This does not exist for NSURLSessionDownloadTask and appears unnecessary. Data tasks will decode data, but not download tasks. + +@end diff --git a/Sparkle/SPUDownloader_Private.h b/Sparkle/SPUDownloader_Private.h new file mode 100644 index 00000000..254c7846 --- /dev/null +++ b/Sparkle/SPUDownloader_Private.h @@ -0,0 +1,38 @@ +// +// SPUDownloader_Private.h +// Sparkle +// +// Created by Deadpikle on 12/20/17. +// Copyright © 2017 Sparkle Project. All rights reserved. +// + +#ifndef SPUDownloader_Private_h +#define SPUDownloader_Private_h + +#import "SPUDownloaderDelegate.h" + +typedef NS_ENUM(NSUInteger, SPUDownloadMode) +{ + SPUDownloadModePersistent, + SPUDownloadModeTemporary +}; + +static NSString *SUDownloadingReason = @"Downloading update related file"; + +@interface SPUDownloader () + +// Delegate is intentionally strongly referenced; see header +@property (nonatomic) id delegate; +@property (nonatomic) NSURLSessionDownloadTask *download; +@property (nonatomic, copy) NSString *bundleIdentifier; +@property (nonatomic, copy) NSString *desiredFilename; +@property (nonatomic, copy) NSString *downloadFilename; +@property (nonatomic) BOOL disabledAutomaticTermination; +@property (nonatomic) SPUDownloadMode mode; +@property (nonatomic) BOOL receivedExpectedBytes; + +-(void)downloadDidFinish; + +@end + +#endif /* SPUDownloader_Private_h */