Rename UpdateDownloader service to PersistentDownloader

This commit is contained in:
Zorg committed 2016-05-26 18:10:07 -04:00
1 parent c9cb670761
commit c5026976ee
17 files changed
+101 -103

No files matched your search

+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2016 Sparkle Project. All rights reserved.</string>
<key>XPCService</key>
<dict>
<key>ServiceType</key>
<string>Application</string>
<key>RunLoopType</key>
<string>NSRunLoop</string>
</dict>
</dict>
</plist>
@@ -0,0 +1,21 @@
//
// SUPersistentDownloader.h
// PersistentDownloader
//
// Created by Mayur Pawashe on 4/1/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUPersistentDownloaderProtocol.h"
@protocol SUPersistentDownloaderDelegate;
// This object implements the protocol which we have defined. It provides the actual behavior for the service. It is 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection.
@interface SUPersistentDownloader : NSObject <SUPersistentDownloaderProtocol>
// Due to XPC remote object reasons, this delegate is strongly referenced
// Invoke cleanup when done with this instance
- (instancetype)initWithDelegate:(id <SUPersistentDownloaderDelegate>)delegate;
@end
@@ -0,0 +1,162 @@
//
// SUPersistentDownloader.m
// PersistentDownloader
//
// Created by Mayur Pawashe on 4/1/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import "SUPersistentDownloader.h"
#import "SUPersistentDownloaderDelegate.h"
#import "SUURLRequest.h"
#import "SUErrors.h"
static NSString *SUPersistentDownloadingReason = @"Downloading persistent file";
@interface SUPersistentDownloader () <NSURLDownloadDelegate>
// Delegate is intentionally strongly referenced; see header
@property (nonatomic) id <SUPersistentDownloaderDelegate> delegate;
@property (nonatomic) NSURLDownload *download;
@property (nonatomic, copy) NSString *bundleIdentifier;
@property (nonatomic, copy) NSString *desiredFilename;
@property (nonatomic) BOOL disabledAutomaticTermination;
@end
@implementation SUPersistentDownloader
@synthesize delegate = _delegate;
@synthesize download = _download;
@synthesize bundleIdentifier = _bundleIdentifier;
@synthesize desiredFilename = _desiredFilename;
@synthesize disabledAutomaticTermination = _disabledAutomaticTermination;
- (instancetype)initWithDelegate:(id <SUPersistentDownloaderDelegate>)delegate
{
self = [super init];
if (self != nil) {
_delegate = delegate;
}
return self;
}
// Don't implement dealloc - make the client call cleanup, which is the only way to remove the reference cycle from the delegate anyway
- (void)startDownloadWithRequest:(SUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename
{
dispatch_async(dispatch_get_main_queue(), ^{
// Remove our old caches path so we don't start accumulating files in there
NSString *cachePath = [[self class] sparkleCachePathForBundleIdentifier:bundleIdentifier];
if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
[[NSFileManager defaultManager] removeItemAtPath:cachePath error:NULL];
}
// Prevent service from automatically terminating while downloading the update asynchronously without any reply blocks
[[NSProcessInfo processInfo] disableAutomaticTermination:SUPersistentDownloadingReason];
self.disabledAutomaticTermination = YES;
self.download = [[NSURLDownload alloc] initWithRequest:request.request delegate:self];
self.desiredFilename = desiredFilename;
self.bundleIdentifier = bundleIdentifier;
});
}
- (void)enableAutomaticTermination
{
if (self.disabledAutomaticTermination) {
[[NSProcessInfo processInfo] enableAutomaticTermination:SUPersistentDownloadingReason];
self.disabledAutomaticTermination = NO;
}
}
- (void)cleanup
{
[self enableAutomaticTermination];
[self.download cancel];
self.download = nil;
self.delegate = nil;
}
- (void)cleanupWithCompletion:(void (^)(void))completionBlock
{
dispatch_async(dispatch_get_main_queue(), ^{
[self cleanup];
completionBlock();
});
}
// If we support sandboxing this component in the future, it is important to note this may return a different path
// For this reason, this method should not be a part of SUHost because its behavior depends on what kind of process it's being invoked from
+ (NSString *)sparkleCachePathForBundleIdentifier:(NSString *)bundleIdentifier
{
NSURL *cacheURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:NULL];
assert(cacheURL != nil);
return [[[cacheURL URLByAppendingPathComponent:bundleIdentifier] URLByAppendingPathComponent:@SPARKLE_BUNDLE_IDENTIFIER] path];
}
- (void)download:(NSURLDownload *)__unused d decideDestinationWithSuggestedFilename:(NSString *)name
{
NSString *downloadFileName = self.desiredFilename;
NSString *cachePath = [[self class] sparkleCachePathForBundleIdentifier:self.bundleIdentifier];
NSString *tempDir = [cachePath stringByAppendingPathComponent:downloadFileName];
int count = 1;
while ([[NSFileManager defaultManager] fileExistsAtPath:tempDir] && count <= 999)
{
tempDir = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ %d", downloadFileName, count++]];
}
// Create the temporary directory if necessary.
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:tempDir withIntermediateDirectories:YES attributes:nil error:NULL];
if (!success)
{
// 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 {
[self.download setDestination:[tempDir stringByAppendingPathComponent:name] allowOverwrite:YES];
[self.delegate downloaderDidSetDestinationName:name temporaryDirectory:tempDir];
}
}
- (void)download:(NSURLDownload *)__unused download didReceiveResponse:(NSURLResponse *)response
{
// It might be tempting to send over the response object instead of the expected content length but this isn't a good idea
// For one, we are only ever concerned about the expected content length
// Another reason is that NSURLResponse doesn't support NSSecureCoding in older OS releases (eg: 10.8), which cause issues with XPC
[self.delegate downloaderDidReceiveExpectedContentLength:response.expectedContentLength];
}
- (void)download:(NSURLDownload *)__unused download didReceiveDataOfLength:(NSUInteger)length
{
[self.delegate downloaderDidReceiveDataOfLength:length];
}
- (void)downloadDidFinish:(NSURLDownload *)__unused d
{
self.download = nil;
[self.delegate downloaderDidFinishDownloading];
}
- (void)download:(NSURLDownload *)__unused download didFailWithError:(NSError *)error
{
self.download = nil;
[self.delegate downloaderDidFailWithError:error];
}
- (BOOL)download:(NSURLDownload *)__unused download shouldDecodeSourceDataOfMIMEType:(NSString *)encodingType
{
// We don't want the download system to extract our gzips.
// Note that we use a substring matching here instead of direct comparison because the docs say "application/gzip" but the system *uses* "application/x-gzip". This is a documentation bug.
return ([encodingType rangeOfString:@"gzip"].location == NSNotFound);
}
@end
@@ -0,0 +1,27 @@
//
// SUPersistentDownloaderDelegate.h
// Sparkle
//
// Created by Mayur Pawashe on 4/1/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol SUPersistentDownloaderDelegate <NSObject>
- (void)downloaderDidSetDestinationName:(NSString *)destinationName temporaryDirectory:(NSString *)temporaryDirectory;
- (void)downloaderDidReceiveExpectedContentLength:(int64_t)expectedContentLength;
- (void)downloaderDidReceiveDataOfLength:(NSUInteger)length;
- (void)downloaderDidFinishDownloading;
- (void)downloaderDidFailWithError:(NSError *)error;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,24 @@
//
// SUPersistentDownloaderProtocol.h
// PersistentDownloader
//
// Created by Mayur Pawashe on 4/1/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class SUURLRequest;
// The protocol that this service will vend as its API. This header file will also need to be visible to the process hosting the service.
@protocol SUPersistentDownloaderProtocol
- (void)startDownloadWithRequest:(SUURLRequest *)request bundleIdentifier:(NSString *)bundleIdentifier desiredFilename:(NSString *)desiredFilename;
- (void)cleanupWithCompletion:(void (^)(void))completionBlock;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
</dict>
</plist>
+53
View File
@@ -0,0 +1,53 @@
//
// main.m
// PersistentDownloader
//
// Created by Mayur Pawashe on 4/1/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "SUPersistentDownloader.h"
#import "SUPersistentDownloaderDelegate.h"
@interface ServiceDelegate : NSObject <NSXPCListenerDelegate>
@end
@implementation ServiceDelegate
- (BOOL)listener:(NSXPCListener *)__unused listener shouldAcceptNewConnection:(NSXPCConnection *)newConnection {
// This method is where the NSXPCListener configures, accepts, and resumes a new incoming NSXPCConnection.
// Configure the connection.
// First, set the interface that the exported object implements.
newConnection.exportedInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUPersistentDownloaderProtocol)];
// Then set remote object interface
newConnection.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol(SUPersistentDownloaderDelegate)];
// Next, set the object that the connection exports. All messages sent on the connection to this service will be sent to the exported object to handle. The connection retains the exported object.
SUPersistentDownloader *exportedObject = [[SUPersistentDownloader alloc] initWithDelegate:newConnection.remoteObjectProxy];
newConnection.exportedObject = exportedObject;
// Resuming the connection allows the system to deliver more incoming messages.
[newConnection resume];
// Returning YES from this method tells the system that you have accepted this connection. If you want to reject the connection for some reason, call -invalidate on the connection and return NO.
return YES;
}
@end
int main(int __unused argc, const char * __unused argv[])
{
// Create the delegate for the service.
ServiceDelegate *delegate = [ServiceDelegate new];
// Set up the one NSXPCListener for this service. It will handle all incoming connections.
NSXPCListener *listener = [NSXPCListener serviceListener];
listener.delegate = delegate;
// Resuming the serviceListener starts this service. This method does not return.
[listener resume];
return 0;
}