From 842d25833017a2d05c70bdbd9ab2f563c0835e7d Mon Sep 17 00:00:00 2001 From: Zorg Date: Sat, 24 Apr 2021 19:00:06 -0700 Subject: [PATCH] Clean up download directory upon skipping already downloaded update --- Downloader/SPUDownloader.m | 41 ++++++-- Downloader/SPUDownloaderProtocol.h | 5 +- Sparkle/SPUCoreBasedUpdateDriver.m | 43 ++++++++- Sparkle/SPUDownloadDriver.h | 6 +- Sparkle/SPUDownloadDriver.m | 149 ++++++++++++++++++----------- Sparkle/SPUInstallerDriver.h | 1 + Sparkle/SPUInstallerDriver.m | 1 + Sparkle/SPUUIBasedUpdateDriver.m | 6 +- Sparkle/SPUURLDownload.m | 14 ++- 9 files changed, 187 insertions(+), 79 deletions(-) diff --git a/Downloader/SPUDownloader.m b/Downloader/SPUDownloader.m index 6ea3aed3..05e3518b 100644 --- a/Downloader/SPUDownloader.m +++ b/Downloader/SPUDownloader.m @@ -111,12 +111,25 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; } } -- (void)cancelDownload +- (NSString *)rootPersistentDownloadCachePathForBundleIdentifier:(NSString *)bundleIdentifier { - [self cleanup]; + return [[SPULocalCacheDirectory cachePathForBundleIdentifier:bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; } -- (void)cleanup +- (void)removeDownloadDirectory:(NSString *)directoryName bundleIdentifier:(NSString *)bundleIdentifier +{ + dispatch_async(dispatch_get_main_queue(), ^{ + NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:bundleIdentifier]; + if (rootPersistentDownloadCachePath != nil) { + NSString *sanitizedDirectoryName = directoryName.lastPathComponent; + NSString *tempDir = [rootPersistentDownloadCachePath stringByAppendingPathComponent:sanitizedDirectoryName]; + + [[NSFileManager defaultManager] removeItemAtPath:tempDir error:NULL]; + } + }); +} + +- (void)_cleanup { [self enableAutomaticTermination]; [self.download cancel]; @@ -132,6 +145,15 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; } } +- (void)cleanup:(void (^)(void))completionHandler +{ + dispatch_async(dispatch_get_main_queue(), ^{ + [self _cleanup]; + + completionHandler(); + }); +} + - (void)URLSession:(NSURLSession *)__unused session downloadTask:(NSURLSessionDownloadTask *)__unused downloadTask didFinishDownloadingToURL:(NSURL *)location { if (self.mode == SPUDownloadModeTemporary) @@ -142,8 +164,8 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; else { // Remove our old caches path so we don't start accumulating files in there - NSString *rootPersistentDownloadCachePath = [[SPULocalCacheDirectory cachePathForBundleIdentifier:self.bundleIdentifier] stringByAppendingPathComponent:@"PersistentDownloads"]; - + NSString *rootPersistentDownloadCachePath = [self rootPersistentDownloadCachePathForBundleIdentifier:self.bundleIdentifier]; + [SPULocalCacheDirectory removeOldItemsInDirectory:rootPersistentDownloadCachePath]; NSString *tempDir = [SPULocalCacheDirectory createUniqueDirectoryInDirectory:rootPersistentDownloadCachePath]; @@ -231,20 +253,21 @@ static NSString *SUDownloadingReason = @"Downloading update related file"; } else { [self.delegate downloaderDidFailWithError:[NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Failed to read temporary downloaded data from %@", self.downloadFilename]}]]; } + + [self _cleanup]; break; case SPUDownloadModePersistent: [self.delegate downloaderDidFinishWithTemporaryDownloadData:nil]; break; } - - [self cleanup]; } - (void)URLSession:(NSURLSession *)__unused session task:(NSURLSessionTask *)__unused task didCompleteWithError:(NSError *)error { self.download = nil; - [self.delegate downloaderDidFailWithError:error]; - [self cleanup]; + if (error != nil) { + [self.delegate downloaderDidFailWithError:error]; + } } // NSURLDownload has a [downlaod:shouldDecodeSourceDataOfMIMEType:] to determine if the data should be decoded. diff --git a/Downloader/SPUDownloaderProtocol.h b/Downloader/SPUDownloaderProtocol.h index aab8da03..7af06c70 100644 --- a/Downloader/SPUDownloaderProtocol.h +++ b/Downloader/SPUDownloaderProtocol.h @@ -19,8 +19,9 @@ NS_ASSUME_NONNULL_BEGIN - (void)startTemporaryDownloadWithRequest:(SPUURLRequest *)request; -// Cancels any ongoing download -- (void)cancelDownload; +- (void)removeDownloadDirectory:(NSString *)directoryName bundleIdentifier:(NSString *)bundleIdentifier; + +- (void)cleanup:(void (^)(void))completionHandler; @end diff --git a/Sparkle/SPUCoreBasedUpdateDriver.m b/Sparkle/SPUCoreBasedUpdateDriver.m index 2b36f0c3..1d8a48d4 100644 --- a/Sparkle/SPUCoreBasedUpdateDriver.m +++ b/Sparkle/SPUCoreBasedUpdateDriver.m @@ -33,6 +33,7 @@ @property (nonatomic, weak, readonly) id delegate; @property (nonatomic) SUAppcastItem *updateItem; @property (nonatomic) id resumableUpdate; +@property (nonatomic) SPUDownloadedUpdate *downloadedUpdateForRemoval; @property (nonatomic, readonly) SUHost *host; @property (nonatomic) BOOL resumingInstallingUpdate; @@ -61,6 +62,7 @@ @synthesize userAgent = _userAgent; @synthesize httpHeaders = _httpHeaders; @synthesize resumableUpdate = _resumableUpdate; +@synthesize downloadedUpdateForRemoval = _downloadedUpdateForRemoval; - (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id )updaterDelegate delegate:(id)delegate { @@ -233,6 +235,19 @@ - (void)clearDownloadedUpdate { + id downloadedUpdateObject = (self.resumableUpdate != nil) ? self.resumableUpdate : self.downloadedUpdateForRemoval; + assert(downloadedUpdateObject != nil); + + if (downloadedUpdateObject != nil && [downloadedUpdateObject isKindOfClass:[SPUDownloadedUpdate class]]) { + if (self.downloadDriver == nil) { + self.downloadDriver = [[SPUDownloadDriver alloc] initWithHost:self.host]; + } + + SPUDownloadedUpdate *downloadedUpdate = (SPUDownloadedUpdate *)downloadedUpdateObject; + [self.downloadDriver removeDownloadedUpdate:downloadedUpdate]; + } + + // Clear any type of resumable update self.resumableUpdate = nil; } @@ -249,11 +264,16 @@ [self.installerDriver extractDownloadedUpdate:downloadedUpdate silently:self.silentInstall preventsInstallerInteraction:self.preventsInstallerInteraction completion:^(NSError * _Nullable error) { if (error != nil) { + if (error.code != SUInstallationAuthorizeLaterError) { + [self clearDownloadedUpdate]; + } + [self.delegate coreDriverIsRequestingAbortUpdateWithError:error]; } else { // If the installer started properly, we can't use the downloaded update archive anymore // Especially if the installer fails later and we try resuming the update with a missing archive file - [self clearDownloadedUpdate]; + self.downloadedUpdateForRemoval = downloadedUpdate; + self.resumableUpdate = nil; if ([self.updaterDelegate respondsToSelector:@selector(updater:didExtractUpdate:)]) { [self.updaterDelegate updater:self.updater didExtractUpdate:self.updateItem]; @@ -285,6 +305,12 @@ } } +- (void)installerDidStartExtracting +{ + // The installer has moved the archive and no longer needs the download directory + [self clearDownloadedUpdate]; +} + - (void)installerDidExtractUpdateWithProgress:(double)progress { if ([self.delegate respondsToSelector:@selector(installerDidExtractUpdateWithProgress:)]) { @@ -369,11 +395,20 @@ - (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately error:(nullable NSError *)error { [self.installerDriver abortInstall]; - [self.downloadDriver cleanup]; - id resumableUpdate = (error == nil || error.code == SUInstallationAuthorizeLaterError) ? self.resumableUpdate : nil; + void (^basicDriverAbort)(void) = ^{ + id resumableUpdate = (error == nil || error.code == SUInstallationAuthorizeLaterError) ? self.resumableUpdate : nil; + + [self.basicDriver abortUpdateAndShowNextUpdateImmediately:shouldShowUpdateImmediately resumableUpdate:resumableUpdate error:error]; + }; - [self.basicDriver abortUpdateAndShowNextUpdateImmediately:shouldShowUpdateImmediately resumableUpdate:resumableUpdate error:error]; + if (self.downloadDriver != nil) { + [self.downloadDriver cleanup:^{ + basicDriverAbort(); + }]; + } else { + basicDriverAbort(); + } } @end diff --git a/Sparkle/SPUDownloadDriver.h b/Sparkle/SPUDownloadDriver.h index 910d39bb..43fd6667 100644 --- a/Sparkle/SPUDownloadDriver.h +++ b/Sparkle/SPUDownloadDriver.h @@ -30,12 +30,16 @@ NS_ASSUME_NONNULL_BEGIN - (instancetype)initWithUpdateItem:(SUAppcastItem *)updateItem host:(SUHost *)host userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background delegate:(id)delegate; +- (instancetype)initWithHost:(SUHost *)host; + - (void)downloadUpdate; +- (void)removeDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate; + @property (nonatomic, readonly) NSMutableURLRequest *request; @property (nonatomic, readonly) BOOL inBackground; -- (void)cleanup; +- (void)cleanup:(void (^)(void))completionHandler; @end diff --git a/Sparkle/SPUDownloadDriver.m b/Sparkle/SPUDownloadDriver.m index aee88dc2..7624510a 100644 --- a/Sparkle/SPUDownloadDriver.m +++ b/Sparkle/SPUDownloadDriver.m @@ -53,12 +53,64 @@ @synthesize expectedContentLength = _expectedContentLength; @synthesize cleaningUp = _cleaningUp; -- (instancetype)initWithUpdateItem:(SUAppcastItem *)updateItem host:(SUHost *)host userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background delegate:(id)delegate +- (instancetype)initWithHost:(SUHost *)host { self = [super init]; if (self != nil) { - _updateItem = updateItem; _host = host; + + if (!SPUXPCServiceExists(@DOWNLOADER_BUNDLE_ID)) { + _downloader = [[SPUDownloader alloc] initWithDelegate:self]; + } else { + _connection = [[NSXPCConnection alloc] initWithServiceName:@DOWNLOADER_BUNDLE_ID]; + _connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderProtocol)]; + _connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderDelegate)]; + _connection.exportedObject = self; + + _downloader = _connection.remoteObjectProxy; + + __weak SPUDownloadDriver *weakSelf = self; + + _connection.interruptionHandler = ^{ + dispatch_async(dispatch_get_main_queue(), ^{ + SPUDownloadDriver *strongSelf = weakSelf; + if (strongSelf != nil && !strongSelf.retrievedDownloadResult) { + [strongSelf.connection invalidate]; + } + }); + }; + + _connection.invalidationHandler = ^{ + dispatch_async(dispatch_get_main_queue(), ^{ + SPUDownloadDriver *strongSelf = weakSelf; + if (strongSelf != nil && !strongSelf.retrievedDownloadResult && !strongSelf.cleaningUp) { + strongSelf.downloader = nil; + + SULog(SULogLevelError, @"Connection to update downloader was invalidated"); + + NSDictionary *userInfo = + @{ + NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), + }; + + NSError *downloadError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]; + + [strongSelf.delegate downloadDriverDidFailToDownloadUpdateWithError:downloadError]; + } + }); + }; + + [_connection resume]; + } + } + return self; +} + +- (instancetype)initWithUpdateItem:(SUAppcastItem *)updateItem host:(SUHost *)host userAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background delegate:(id)delegate +{ + self = [self initWithHost:host]; + if (self != nil) { + _updateItem = updateItem; _delegate = delegate; _inBackground = background; @@ -72,75 +124,59 @@ [_request setValue:value forHTTPHeaderField:key]; } } - - if (!SPUXPCServiceExists(@DOWNLOADER_BUNDLE_ID)) { - _downloader = [[SPUDownloader alloc] initWithDelegate:self]; - } else { - _connection = [[NSXPCConnection alloc] initWithServiceName:@DOWNLOADER_BUNDLE_ID]; - _connection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderProtocol)]; - _connection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SPUDownloaderDelegate)]; - _connection.exportedObject = self; - - _downloader = _connection.remoteObjectProxy; - } } return self; } - (void)downloadUpdate { - NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; - assert(bundleIdentifier != nil); - - __weak SPUDownloadDriver *weakSelf = self; - - self.connection.interruptionHandler = ^{ - dispatch_async(dispatch_get_main_queue(), ^{ - SPUDownloadDriver *strongSelf = weakSelf; - if (strongSelf != nil && !strongSelf.retrievedDownloadResult) { - [strongSelf.connection invalidate]; - } - }); - }; - - self.connection.invalidationHandler = ^{ - dispatch_async(dispatch_get_main_queue(), ^{ - SPUDownloadDriver *strongSelf = weakSelf; - if (strongSelf != nil && !strongSelf.retrievedDownloadResult && !strongSelf.cleaningUp) { - SULog(SULogLevelError, @"Connection to update downloader was invalidated"); - - NSDictionary *userInfo = - @{ - NSLocalizedDescriptionKey: SULocalizedString(@"An error occurred while downloading the update. Please try again later.", nil), - }; - - NSError *downloadError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]; - - [strongSelf.delegate downloadDriverDidFailToDownloadUpdateWithError:downloadError]; - } - }); - }; - - [self.connection resume]; - [self.delegate downloadDriverWillBeginDownload]; NSString *desiredFilename = [NSString stringWithFormat:@"%@ %@", [self.host name], [self.updateItem versionString]]; + + NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + assert(bundleIdentifier != nil); + [self.downloader startPersistentDownloadWithRequest:[SPUURLRequest URLRequestWithRequest:self.request] bundleIdentifier:bundleIdentifier desiredFilename:desiredFilename]; } -- (void)cleanup +- (void)removeDownloadedUpdate:(SPUDownloadedUpdate *)downloadedUpdate { - self.cleaningUp = YES; + NSString *bundleIdentifier = self.host.bundle.bundleIdentifier; + assert(bundleIdentifier != nil); - if (self.connection != nil) { - [self.connection invalidate]; - self.connection = nil; + if (bundleIdentifier != nil) { + // Grab eg "0bCSun8tj" from org.sparkle-project.Sparkle/PersistentDownloads/0bCSun8tj/Sparkle Test App 2.0/ + NSString *tempDirectoryName = downloadedUpdate.temporaryDirectory.stringByDeletingLastPathComponent.lastPathComponent; + + [self.downloader removeDownloadDirectory:tempDirectoryName bundleIdentifier:bundleIdentifier]; } - self.downloadName = nil; +} + +- (void)cleanup:(void (^)(void))completionHandler +{ + void (^cleanupBlock)(void) = ^{ + self.cleaningUp = YES; + + if (self.connection != nil) { + [self.connection invalidate]; + self.connection = nil; + } + self.downloadName = nil; + self.downloader = nil; + + completionHandler(); + }; - [self.downloader cancelDownload]; - self.downloader = nil; + if (self.downloader == nil) { + cleanupBlock(); + } else { + [self.downloader cleanup:^{ + dispatch_async(dispatch_get_main_queue(), ^{ + cleanupBlock(); + }); + }]; + } } - (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)__unused downloadData @@ -155,7 +191,6 @@ SPUDownloadedUpdate *downloadedUpdate = [[SPUDownloadedUpdate alloc] initWithAppcastItem:self.updateItem downloadName:self.downloadName temporaryDirectory:self.temporaryDirectory]; [self.delegate downloadDriverDidDownloadUpdate:downloadedUpdate]; - [self cleanup]; }); } @@ -179,8 +214,6 @@ NSError *downloadError = [NSError errorWithDomain:SUSparkleErrorDomain code:SUDownloadError userInfo:userInfo]; [self.delegate downloadDriverDidFailToDownloadUpdateWithError:downloadError]; - - [self cleanup]; }); } diff --git a/Sparkle/SPUInstallerDriver.h b/Sparkle/SPUInstallerDriver.h index 2426f9a2..2bb25107 100644 --- a/Sparkle/SPUInstallerDriver.h +++ b/Sparkle/SPUInstallerDriver.h @@ -16,6 +16,7 @@ NS_ASSUME_NONNULL_BEGIN @protocol SPUInstallerDriverDelegate - (void)installerDidStartInstalling; +- (void)installerDidStartExtracting; - (void)installerDidExtractUpdateWithProgress:(double)progress; - (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately silently:(BOOL)willInstallSilently; - (void)installerIsSendingAppTerminationSignal; diff --git a/Sparkle/SPUInstallerDriver.m b/Sparkle/SPUInstallerDriver.m index da340bfc..ea1883c2 100644 --- a/Sparkle/SPUInstallerDriver.m +++ b/Sparkle/SPUInstallerDriver.m @@ -229,6 +229,7 @@ if (identifier == SPUExtractionStarted) { self.extractionAttempts++; self.currentStage = identifier; + [self.delegate installerDidStartExtracting]; } else if (identifier == SPUExtractedArchiveWithProgress) { if (data.length == sizeof(double) && sizeof(double) == sizeof(uint64_t)) { uint64_t progressValue = CFSwapInt64LittleToHost(*(const uint64_t *)data.bytes); diff --git a/Sparkle/SPUUIBasedUpdateDriver.m b/Sparkle/SPUUIBasedUpdateDriver.m index fb01cee1..ea29f6d0 100644 --- a/Sparkle/SPUUIBasedUpdateDriver.m +++ b/Sparkle/SPUUIBasedUpdateDriver.m @@ -157,7 +157,11 @@ [self.updaterDelegate updater:self.updater userDidSkipThisVersion:updateItem]; } - [self.coreDriver clearDownloadedUpdate]; + // Informational updates can be resumed too, so make sure we check + // self.resumingDownloadedUpdate instead of the state we pass to user driver + if (self.resumingDownloadedUpdate) { + [self.coreDriver clearDownloadedUpdate]; + } [self.delegate uiDriverIsRequestingAbortUpdateWithError:nil]; diff --git a/Sparkle/SPUURLDownload.m b/Sparkle/SPUURLDownload.m index 911befed..5c67de29 100644 --- a/Sparkle/SPUURLDownload.m +++ b/Sparkle/SPUURLDownload.m @@ -51,14 +51,20 @@ - (void)downloaderDidFinishWithTemporaryDownloadData:(SPUDownloadData * _Nullable)downloadData { - self.completionBlock(downloadData, nil); - self.completionBlock = nil; + assert(self.completionBlock != nil); + if (self.completionBlock != nil) { + self.completionBlock(downloadData, nil); + self.completionBlock = nil; + } } - (void)downloaderDidFailWithError:(NSError *)error { - self.completionBlock(nil, error); - self.completionBlock = nil; + assert(self.completionBlock != nil); + if (self.completionBlock != nil) { + self.completionBlock(nil, error); + self.completionBlock = nil; + } } @end