WIP: integrate isolated beta update and diagnostic client; Release build passes, end-to-end validation pending
这个提交包含在:
1 父节点
f453508be6
当前提交
15d644c7e7
14 个文件已更改
+726
-18
没有与搜索条件相匹配的文件
@@ -1,4 +1,6 @@
|
||||
#import "AppDelegate.h"
|
||||
#import "DYBetaUpdater.h"
|
||||
#import "../Shared/DYBetaDiagnostics.h"
|
||||
|
||||
static NSString *const DYPluginID = @"com.dayu.color.XPC";
|
||||
static NSString *const DYReleaseAddress = @"https://dayu.media";
|
||||
@@ -116,6 +118,13 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
@property NSInteger secondsRemaining;
|
||||
@property(retain) NSTimer *exitTimer;
|
||||
@property(retain) NSMutableDictionary *diagnostics;
|
||||
@property(retain) DYBetaUpdater *updater;
|
||||
@property(assign) NSTextField *updateTitle, *updateDetail, *diagnosticDetail, *reportID;
|
||||
@property(assign) DYActionButton *updateCheckButton, *updateInstallButton, *updateCancelButton, *sendSummaryButton;
|
||||
@property(assign) NSButton *diagnosticToggle;
|
||||
@property(assign) NSProgressIndicator *updateProgress;
|
||||
@property(retain) NSTimer *updateProgressTimer;
|
||||
@property BOOL updateCheckDone;
|
||||
@end
|
||||
|
||||
@implementation AppDelegate
|
||||
@@ -125,10 +134,21 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
self.window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
|
||||
self.window.titlebarAppearsTransparent = YES; self.window.backgroundColor = DYColor(.105,.14,.20);
|
||||
self.window.contentMinSize = NSMakeSize(760,620); [self.window setContentSize:NSMakeSize(920,850)]; [self.window center];
|
||||
DYBetaStart();
|
||||
[self buildInterface]; [self buildMenu];
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(refreshDiagnostics:) name:DYBetaDiagnosticsChanged object:nil];
|
||||
self.updater = [[[DYBetaUpdater alloc] init] autorelease];
|
||||
__block AppDelegate *owner = self;
|
||||
self.updater.changed = ^(NSDictionary *state) { [owner updateChanged:state]; };
|
||||
self.updateProgressTimer = [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(refreshUpdateProgress:) userInfo:nil repeats:YES];
|
||||
NSInteger expected=[NSUserDefaults.standardUserDefaults integerForKey:@"betaPendingUpdateBuild"];
|
||||
if(expected>0 && [NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"]integerValue]>=expected){
|
||||
DYBetaEvent(@"update_installer",@{@"status":@"completed",@"count":@(expected)});
|
||||
[NSUserDefaults.standardUserDefaults removeObjectForKey:@"betaPendingUpdateBuild"];
|
||||
}
|
||||
[NSWorkspace.sharedWorkspace.notificationCenter addObserver:self selector:@selector(accessibilityChanged:)
|
||||
name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
|
||||
[self.window makeKeyAndOrderFront:nil]; [self checkRegistration:nil];
|
||||
[self.window makeKeyAndOrderFront:nil]; [self refreshDiagnostics:nil]; [self checkRegistration:nil]; [self.updater check];
|
||||
}
|
||||
- (void)buildMenu {
|
||||
NSMenu *menu = [[[NSMenu alloc] initWithTitle:@"大鱼调色"] autorelease];
|
||||
@@ -137,6 +157,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
for (NSArray *entry in @[@[@"关于大鱼调色",NSStringFromSelector(@selector(orderFrontStandardAboutPanel:)),@""],
|
||||
@[@"查看功能介绍",NSStringFromSelector(@selector(keepIntroduction:)),@"i"],
|
||||
@[@"重新检查插件",NSStringFromSelector(@selector(checkRegistration:)),@"r"],
|
||||
@[@"检查公测更新",NSStringFromSelector(@selector(checkUpdate:)),@"u"],
|
||||
@[@"访问发布地址",NSStringFromSelector(@selector(openWebsite:)),@""],
|
||||
@[@"关闭窗口",NSStringFromSelector(@selector(closeWindow:)),@"w"],
|
||||
@[@"退出大鱼调色",NSStringFromSelector(@selector(terminate:)),@"q"]]) {
|
||||
@@ -190,6 +211,28 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
DYSurface *hostCard = DYCard(DYGreen(),host);
|
||||
NSStackView *top = DYStack(@[self.registrationCard,hostCard],NSUserInterfaceLayoutOrientationHorizontal,14);
|
||||
[self.registrationCard.heightAnchor constraintEqualToAnchor:hostCard.heightAnchor].active = YES;
|
||||
self.updateTitle = DYLabel(@"公测更新",20,NSFontWeightSemibold,NSColor.whiteColor);
|
||||
self.updateDetail = DYLabel(@"启动时自动检查,新版本由你确认安装。",13,NSFontWeightRegular,DYSecondary());
|
||||
[self.updateDetail.heightAnchor constraintGreaterThanOrEqualToConstant:42].active = YES;
|
||||
self.updateProgress = [[[NSProgressIndicator alloc] initWithFrame:NSZeroRect] autorelease];
|
||||
self.updateProgress.style=NSProgressIndicatorStyleBar; self.updateProgress.indeterminate=NO;
|
||||
self.updateProgress.minValue=0; self.updateProgress.maxValue=1; self.updateProgress.translatesAutoresizingMaskIntoConstraints=NO;
|
||||
self.updateCheckButton=DYButton(@"检查更新",DYBlue(),NO,self,@selector(checkUpdate:));
|
||||
self.updateInstallButton=DYButton(@"下载更新",DYColor(.20,.46,.94),YES,self,@selector(installUpdate:));
|
||||
self.updateInstallButton.enabled=NO;
|
||||
self.updateCancelButton=DYButton(@"取消下载",DYBlue(),NO,self,@selector(cancelUpdate:)); self.updateCancelButton.hidden=YES;
|
||||
DYSurface *updateCard=DYCard(DYBlue(),DYStack(@[DYHeading(@"arrow.triangle.2.circlepath",@"持续改进,及时更新",DYBlue()),self.updateTitle,self.updateDetail,self.updateProgress,
|
||||
DYStack(@[self.updateCheckButton,self.updateInstallButton],NSUserInterfaceLayoutOrientationHorizontal,8),self.updateCancelButton],NSUserInterfaceLayoutOrientationVertical,10));
|
||||
self.diagnosticToggle=[NSButton checkboxWithTitle:@"参与公测诊断" target:self action:@selector(toggleDiagnostics:)];
|
||||
self.diagnosticToggle.font=[NSFont systemFontOfSize:16 weight:NSFontWeightSemibold]; self.diagnosticToggle.state=DYBetaEnabled()?NSControlStateValueOn:NSControlStateValueOff;
|
||||
self.diagnosticDetail=DYLabel(@"诊断准备中…",12,NSFontWeightRegular,DYSecondary());
|
||||
self.reportID=DYLabel(@"报告标识准备中…",10,NSFontWeightRegular,DYSecondary());self.reportID.selectable=YES;
|
||||
self.sendSummaryButton=DYButton(@"发送诊断摘要",DYColor(.67,.59,1),NO,self,@selector(sendSummary:));
|
||||
DYSurface *diagnosticCard=DYCard(DYColor(.67,.59,1),DYStack(@[DYHeading(@"waveform.path.ecg",@"一起完善大鱼调色",DYColor(.67,.59,1)),self.diagnosticToggle,
|
||||
DYLabel(@"仅发送版本、系统环境、加载耗时和本插件错误摘要;不发送素材、预设或账号。可随时关闭,诊断保留 30 天。",12,NSFontWeightRegular,DYSecondary()),
|
||||
self.reportID,self.diagnosticDetail,self.sendSummaryButton],NSUserInterfaceLayoutOrientationVertical,10));
|
||||
NSStackView *beta=DYStack(@[updateCard,diagnosticCard],NSUserInterfaceLayoutOrientationHorizontal,14);
|
||||
[updateCard.heightAnchor constraintEqualToAnchor:diagnosticCard.heightAnchor].active=YES;
|
||||
NSArray *features = @[
|
||||
@[@"slider.horizontal.3",@"完整调色",@"精准还原,自由塑造",@"CST 色彩管理、光影与曲线\nHSL、色轮、蜘蛛盘与白平衡",DYBlue()],
|
||||
@[@"square.grid.2x2",@"LUT 与风格",@"灵感,所见即所得",@"LUT 缩略图浏览与实时预览\n快速收藏,管理常用风格",DYColor(.67,.59,1)],
|
||||
@@ -202,7 +245,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
NSStackView *row2 = DYStack(@[cards[2],cards[3]],NSUserInterfaceLayoutOrientationHorizontal,14);
|
||||
[((NSView *)cards[0]).heightAnchor constraintEqualToAnchor:((NSView *)cards[1]).heightAnchor].active = YES;
|
||||
[((NSView *)cards[2]).heightAnchor constraintEqualToAnchor:((NSView *)cards[3]).heightAnchor].active = YES;
|
||||
NSStackView *content = DYStack(@[website,hero,top,DYHeading(@"sparkles",@"一套工具,完成你的色彩表达",NSColor.whiteColor),row1,row2],NSUserInterfaceLayoutOrientationVertical,18);
|
||||
NSStackView *content = DYStack(@[website,hero,top,beta,DYHeading(@"sparkles",@"一套工具,完成你的色彩表达",NSColor.whiteColor),row1,row2],NSUserInterfaceLayoutOrientationVertical,18);
|
||||
DYPin(content,document,30);
|
||||
for (NSView *view in content.arrangedSubviews) [view.widthAnchor constraintEqualToAnchor:content.widthAnchor].active = YES;
|
||||
[document.heightAnchor constraintGreaterThanOrEqualToAnchor:scroll.contentView.heightAnchor].active = YES;
|
||||
@@ -294,11 +337,56 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
[self.diagnostics addEntriesFromDictionary:results]; self.diagnostics[@"status"] = success ? @"registered" : @"failed"; [self writeDiagnostics];
|
||||
NSAccessibilityPostNotificationWithUserInfo(self.window,NSAccessibilityAnnouncementRequestedNotification,
|
||||
@{NSAccessibilityAnnouncementKey:self.statusTitle.stringValue,NSAccessibilityPriorityKey:@(NSAccessibilityPriorityHigh)});
|
||||
if (success && !self.keepOpen) {
|
||||
self.secondsRemaining = 3; [self updateCountdown];
|
||||
self.exitTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(exitTick:) userInfo:nil repeats:YES];
|
||||
} else self.exitDetail.stringValue = success ? @"插件已就绪。关闭此窗口后,可继续在宿主中使用。" : @"注册尚未完成,应用会保留此窗口以便重试。";
|
||||
DYBetaEvent(@"registration",@{@"status":success?@"registered":@"failed"});
|
||||
if(success)[self maybeStartCountdown];
|
||||
else self.exitDetail.stringValue=@"注册尚未完成,应用会保留此窗口以便重试。";
|
||||
}
|
||||
- (void)maybeStartCountdown {
|
||||
if(self.terminating || self.registrationState!=DYReady)return;
|
||||
if(self.keepOpen){self.exitDetail.stringValue=@"插件已就绪。关闭此窗口后,可继续在宿主中使用。";return;}
|
||||
if(!self.updateCheckDone){self.exitDetail.stringValue=@"注册成功,正在检查公测更新…";return;}
|
||||
if(self.exitTimer)return;
|
||||
self.secondsRemaining=3;[self updateCountdown];
|
||||
self.exitTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(exitTick:) userInfo:nil repeats:YES];
|
||||
}
|
||||
- (void)updateChanged:(NSDictionary *)state {
|
||||
if(self.terminating)return;
|
||||
NSString *phase=state[@"phase"];
|
||||
BOOL busy=[@[@"checking",@"downloading",@"validating"]containsObject:phase];
|
||||
BOOL available=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase];
|
||||
if(![phase isEqual:@"checking"]){self.updateCheckDone=YES;if(available)[self keepIntroduction:nil];}
|
||||
self.updateTitle.stringValue=[phase isEqual:@"available"]?state[@"message"]:@"公测更新";
|
||||
self.updateDetail.stringValue=state[@"message"]?:@"";
|
||||
self.updateCheckButton.enabled=!busy;
|
||||
self.updateInstallButton.enabled=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase];
|
||||
self.updateInstallButton.title=[phase isEqual:@"available"]?@"下载更新":@"安装更新";
|
||||
self.updateCancelButton.hidden=![phase isEqual:@"downloading"];
|
||||
self.updateProgress.indeterminate=[@[@"checking",@"validating"]containsObject:phase];
|
||||
if(self.updateProgress.indeterminate)[self.updateProgress startAnimation:nil];else [self.updateProgress stopAnimation:nil];
|
||||
self.updateProgress.doubleValue=[@[@"ready",@"host_wait",@"installer"]containsObject:phase]?1:0;
|
||||
[self maybeStartCountdown];
|
||||
}
|
||||
- (void)refreshUpdateProgress:(NSTimer *)timer {
|
||||
if([self.updater.state[@"phase"]isEqual:@"downloading"])self.updateProgress.doubleValue=self.updater.downloadFraction;
|
||||
}
|
||||
- (void)checkUpdate:(id)sender { [self keepIntroduction:nil]; [self.updater check]; }
|
||||
- (void)installUpdate:(id)sender {
|
||||
[self keepIntroduction:nil];NSString *phase=self.updater.state[@"phase"];
|
||||
if([phase isEqual:@"available"])[self.updater download];else [self.updater install];
|
||||
}
|
||||
- (void)cancelUpdate:(id)sender { [self keepIntroduction:nil];[self.updater cancel]; }
|
||||
- (void)refreshDiagnostics:(NSNotification *)note {
|
||||
NSDictionary *state=DYBetaStatus();BOOL enabled=DYBetaEnabled();self.diagnosticToggle.state=enabled?NSControlStateValueOn:NSControlStateValueOff;
|
||||
self.sendSummaryButton.enabled=enabled;
|
||||
self.reportID.stringValue=[NSString stringWithFormat:@"报告标识:%@",state[@"installation_id"]?:@"准备中…"];
|
||||
NSNumber *uploaded=state[@"last_upload"];
|
||||
if(!enabled)self.diagnosticDetail.stringValue=@"诊断已关闭。不会继续上传,待发送摘要已清除。";
|
||||
else if(uploaded){NSDateFormatter *format=[[[NSDateFormatter alloc]init]autorelease];format.dateFormat=@"HH:mm:ss";
|
||||
self.diagnosticDetail.stringValue=[NSString stringWithFormat:@"最近送达 %@ · 待发送 %@ 条",[format stringFromDate:[NSDate dateWithTimeIntervalSince1970:uploaded.doubleValue]],state[@"pending"]?:@0];}
|
||||
else self.diagnosticDetail.stringValue=@"诊断将在后台发送,离线时暂存并稍后重试。";
|
||||
}
|
||||
- (void)toggleDiagnostics:(id)sender { [self keepIntroduction:nil];DYBetaSetEnabled(self.diagnosticToggle.state==NSControlStateValueOn);[self refreshDiagnostics:nil]; }
|
||||
- (void)sendSummary:(id)sender { [self keepIntroduction:nil];DYBetaSendSummary();self.diagnosticDetail.stringValue=@"已加入后台发送队列,送达后会显示时间。"; }
|
||||
- (void)updateCountdown { self.exitDetail.stringValue = [NSString stringWithFormat:@"%ld 秒后自动退出\n点击“查看功能介绍”可保留窗口",(long)self.secondsRemaining]; }
|
||||
- (void)exitTick:(NSTimer *)timer {
|
||||
if (--self.secondsRemaining <= 0) {
|
||||
@@ -312,6 +400,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
}
|
||||
- (void)confirmHost:(id)sender {
|
||||
if (self.registrationState != DYReady) return;
|
||||
DYBetaEvent(@"host_confirmed",@{@"status":@"user_confirmed"});
|
||||
self.diagnostics[@"hostVerification"] = @"user-confirmed";
|
||||
self.diagnostics[@"terminationReason"] = @"user-confirmed-host";
|
||||
[self writeDiagnostics]; [NSApp terminate:nil];
|
||||
@@ -343,7 +432,10 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app { return YES; }
|
||||
- (void)applicationWillTerminate:(NSNotification *)note {
|
||||
self.terminating = YES; [self.exitTimer invalidate]; self.exitTimer = nil;
|
||||
self.updater.changed=nil; [self.updater cancel];DYBetaStop();
|
||||
[self.updateProgressTimer invalidate];self.updateProgressTimer=nil;
|
||||
[NSNotificationCenter.defaultCenter removeObserver:self];
|
||||
[NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
|
||||
}
|
||||
- (void)dealloc { [_exitTimer invalidate]; [_exitTimer release]; [_diagnostics release]; [super dealloc]; }
|
||||
- (void)dealloc { [_exitTimer invalidate]; [_exitTimer release]; [_diagnostics release]; [_updater release]; [_updateProgressTimer invalidate]; [_updateProgressTimer release]; [super dealloc]; }
|
||||
@end
|
||||
@@ -0,0 +1,12 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface DYBetaUpdater : NSObject <NSURLSessionTaskDelegate>
|
||||
@property(copy) void (^changed)(NSDictionary *state);
|
||||
@property(readonly,copy) NSDictionary *state;
|
||||
@property(readonly) double downloadFraction;
|
||||
- (void)check;
|
||||
- (void)download;
|
||||
- (void)install;
|
||||
- (void)cancel;
|
||||
+ (BOOL)validateManifest:(NSDictionary *)manifest error:(NSError **)error;
|
||||
+ (BOOL)validatePackage:(NSURL *)package manifest:(NSDictionary *)manifest error:(NSError **)error;
|
||||
@end
|
||||
@@ -0,0 +1,166 @@
|
||||
#import "DYBetaUpdater.h"
|
||||
#import "../Shared/DYBetaDiagnostics.h"
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
#include <atomic>
|
||||
#include <sys/xattr.h>
|
||||
|
||||
static NSError *DYUpdateError(NSString *message) { return [NSError errorWithDomain:@"com.dayu.color.update" code:1 userInfo:@{NSLocalizedDescriptionKey:message}]; }
|
||||
static NSURL *updateFolder(void) {
|
||||
NSURL *folder=[[NSFileManager.defaultManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask].firstObject URLByAppendingPathComponent:@"com.dayu.color/Updates" isDirectory:YES];
|
||||
[NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil];return folder;
|
||||
}
|
||||
static NSString *digest(NSURL *url) {
|
||||
NSFileHandle *file=[NSFileHandle fileHandleForReadingFromURL:url error:nil];if(!file)return nil;
|
||||
CC_SHA256_CTX context;CC_SHA256_Init(&context);for(;;){NSData *data=[file readDataUpToLength:1024*1024 error:nil];if(!data.length)break;CC_SHA256_Update(&context,data.bytes,(CC_LONG)data.length);}[file closeFile];
|
||||
unsigned char bytes[CC_SHA256_DIGEST_LENGTH];CC_SHA256_Final(bytes,&context);NSMutableString *text=[NSMutableString string];for(int i=0;i<CC_SHA256_DIGEST_LENGTH;i++)[text appendFormat:@"%02x",bytes[i]];return text;
|
||||
}
|
||||
static NSString *command(NSString *path,NSArray *arguments,NSError **error) {
|
||||
NSTask *task=[[[NSTask alloc]init]autorelease];task.executableURL=[NSURL fileURLWithPath:path];task.arguments=arguments;
|
||||
NSPipe *output=[NSPipe pipe];task.standardOutput=output;task.standardError=output;
|
||||
if(![task launchAndReturnError:error])return nil;NSDate *deadline=[NSDate dateWithTimeIntervalSinceNow:40];
|
||||
while(task.running&&deadline.timeIntervalSinceNow>0)[NSThread sleepForTimeInterval:.05];
|
||||
if(task.running){[task terminate];if(error)*error=DYUpdateError(@"更新包验证超时,请稍后重试。");return nil;}
|
||||
NSData *data=[output.fileHandleForReading readDataToEndOfFile];NSString *value=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease]?:@"";
|
||||
if(task.terminationStatus!=0){if(error)*error=DYUpdateError(@"更新包未通过系统签名或完整性验证。");return nil;}return value;
|
||||
}
|
||||
@interface DYBetaUpdater () {
|
||||
NSURLSession *_session;
|
||||
NSURLSessionTask *_task;
|
||||
NSURL *_package;
|
||||
NSDictionary *_state,*_manifest;
|
||||
std::atomic_uint _generation;
|
||||
}
|
||||
- (void)emit:(NSString *)phase message:(NSString *)message;
|
||||
@end
|
||||
@implementation DYBetaUpdater
|
||||
- (instancetype)init {
|
||||
if((self=[super init])){_generation.store(0);NSURLSessionConfiguration *config=NSURLSessionConfiguration.ephemeralSessionConfiguration;
|
||||
config.timeoutIntervalForRequest=6;config.timeoutIntervalForResource=300;config.HTTPShouldSetCookies=NO;config.URLCache=nil;
|
||||
_session=[[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]retain];_state=[@{@"phase":@"idle",@"message":@"启动时自动检查公测更新。"}copy];
|
||||
// Only this updater's abandoned inspection folders are disposable.
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0),^{for(NSURL *url in [NSFileManager.defaultManager contentsOfDirectoryAtURL:updateFolder() includingPropertiesForKeys:nil options:0 error:nil])if([url.lastPathComponent hasPrefix:@"inspection-"])[NSFileManager.defaultManager removeItemAtURL:url error:nil];});
|
||||
}return self;
|
||||
}
|
||||
- (void)dealloc {[_session invalidateAndCancel];[_session release];[_task release];[_package release];[_state release];[_manifest release];[_changed release];[super dealloc];}
|
||||
- (NSDictionary *)state { return [[_state copy]autorelease]; }
|
||||
- (double)downloadFraction {int64_t expected=[_manifest[@"size"]longLongValue];return expected>0?MIN(1.,double(_task.countOfBytesReceived)/expected):0;}
|
||||
- (void)emit:(NSString *)phase message:(NSString *)message {
|
||||
if(!NSThread.isMainThread){dispatch_async(dispatch_get_main_queue(),^{[self emit:phase message:message];});return;}
|
||||
[_state release];_state=[@{@"phase":phase,@"message":message?:@"",@"version":_manifest[@"version"]?:@""}copy];if(self.changed)self.changed(_state);
|
||||
}
|
||||
+ (BOOL)validateManifest:(NSDictionary *)manifest error:(NSError **)error {
|
||||
if(![manifest isKindOfClass:NSDictionary.class]){if(error)*error=DYUpdateError(@"公测更新清单格式错误。");return NO;}
|
||||
id build=manifest[@"build"],size=manifest[@"size"];
|
||||
BOOL numbers=[build isKindOfClass:NSNumber.class]&&[size isKindOfClass:NSNumber.class]&&
|
||||
CFGetTypeID((CFTypeRef)build)!=CFBooleanGetTypeID()&&CFGetTypeID((CFTypeRef)size)!=CFBooleanGetTypeID();
|
||||
BOOL valid=numbers&&[manifest[@"bundle_id"]isEqual:@"com.dayu.color"]&&[manifest[@"channel"]isEqual:@"beta"]&&
|
||||
[manifest[@"version"]isKindOfClass:NSString.class]&&[manifest[@"version"]length]>0&&[manifest[@"version"]length]<33&&
|
||||
[build doubleValue]==[build longLongValue]&&[build longLongValue]>0&&[build longLongValue]<1000000000&&
|
||||
[manifest[@"package_type"]isEqual:@"pkg"]&&[manifest[@"install_mode"]isEqual:@"pkg_installer"]&&
|
||||
[size doubleValue]==[size longLongValue]&&[size longLongValue]>0&&[size longLongValue]<=1024LL*1024*1024;
|
||||
NSString *hash=[manifest[@"sha256"]isKindOfClass:NSString.class]?manifest[@"sha256"]:@"";
|
||||
valid=valid&&hash.length==64&&[hash rangeOfString:@"^[a-f0-9]{64}$" options:NSRegularExpressionSearch].location!=NSNotFound;
|
||||
NSURL *url=[manifest[@"download_url"]isKindOfClass:NSString.class]?[NSURL URLWithString:manifest[@"download_url"]]:nil;
|
||||
valid=valid&&DYBetaAllowedURL(url,YES)&&[url.pathExtension.lowercaseString isEqual:@"pkg"];
|
||||
if(!valid&&error)*error=DYUpdateError(@"公测更新清单不完整或不属于大鱼调色。");return valid;
|
||||
}
|
||||
+ (BOOL)validatePackage:(NSURL *)package manifest:(NSDictionary *)manifest error:(NSError **)error {
|
||||
if(![self validateManifest:manifest error:error])return NO;
|
||||
NSDictionary *attributes=[NSFileManager.defaultManager attributesOfItemAtPath:package.path error:error];
|
||||
if(!attributes||[attributes[NSFileSize]longLongValue]!=[manifest[@"size"]longLongValue]||![[digest(package)lowercaseString]isEqual:manifest[@"sha256"]]){if(error)*error=DYUpdateError(@"更新包大小或 SHA-256 不匹配,未打开安装程序。");return NO;}
|
||||
NSString *signature=command(@"/usr/sbin/pkgutil",@[@"--check-signature",package.path],error);
|
||||
if(!signature||![signature containsString:@"Developer ID Installer:"]||![signature containsString:@"(B3W25FX5H5)"]){if(error)*error=DYUpdateError(@"更新包签名团队不匹配。");return NO;}
|
||||
if(!command(@"/usr/sbin/spctl",@[@"--assess",@"--type",@"install",@"--verbose=2",package.path],error))return NO;
|
||||
NSURL *inspection=[updateFolder() URLByAppendingPathComponent:[@"inspection-" stringByAppendingString:NSUUID.UUID.UUIDString]];
|
||||
@try {
|
||||
if(!command(@"/usr/sbin/pkgutil",@[@"--expand-full",package.path,inspection.path],error))return NO;
|
||||
NSMutableArray *apps=[NSMutableArray array];NSUInteger entries=0;
|
||||
NSDirectoryEnumerator *iterator=[NSFileManager.defaultManager enumeratorAtURL:inspection includingPropertiesForKeys:@[NSURLIsSymbolicLinkKey] options:0 errorHandler:nil];
|
||||
for(NSURL *url in iterator){if(++entries>50000){if(error)*error=DYUpdateError(@"更新包文件数量异常。");return NO;}
|
||||
if([url.pathExtension isEqual:@"app"]){[apps addObject:url];[iterator skipDescendants];}
|
||||
}
|
||||
if(apps.count!=1){if(error)*error=DYUpdateError(@"更新包必须包含一个完整的大鱼调色 APP。");return NO;}
|
||||
NSURL *app=apps.firstObject;NSDictionary *info=[NSDictionary dictionaryWithContentsOfURL:[app URLByAppendingPathComponent:@"Contents/Info.plist"]];
|
||||
NSDictionary *plugin=[NSDictionary dictionaryWithContentsOfURL:[app URLByAppendingPathComponent:@"Contents/PlugIns/大鱼调色 XPC Service.pluginkit/Contents/Info.plist"]];
|
||||
if(![info[@"CFBundleIdentifier"]isEqual:@"com.dayu.color"]||![plugin[@"CFBundleIdentifier"]isEqual:@"com.dayu.color.XPC"]||
|
||||
[info[@"CFBundleVersion"]integerValue]!=[manifest[@"build"]integerValue]||[plugin[@"CFBundleVersion"]integerValue]!=[manifest[@"build"]integerValue]||
|
||||
![info[@"CFBundleShortVersionString"]isEqual:manifest[@"version"]]){if(error)*error=DYUpdateError(@"更新包产品或版本与清单不一致。");return NO;}
|
||||
if(!command(@"/usr/bin/codesign",@[@"--verify",@"--deep",@"--strict",app.path],error))return NO;
|
||||
NSString *identity=command(@"/usr/bin/codesign",@[@"-dvvv",app.path],error);
|
||||
if(![identity containsString:@"TeamIdentifier=B3W25FX5H5"]){if(error)*error=DYUpdateError(@"包内 APP 签名团队不匹配。");return NO;}
|
||||
// Product PKGs install the wrapper at its fixed FxPlug location and carry templates.
|
||||
BOOL appTarget=NO,templates=NO;
|
||||
for(NSURL *url in [NSFileManager.defaultManager enumeratorAtURL:inspection includingPropertiesForKeys:nil options:0 errorHandler:nil]){
|
||||
if([url.lastPathComponent isEqual:@"PackageInfo"]){NSString *xml=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
|
||||
if([xml containsString:@"install-location=\"/Library/Plug-Ins/FxPlug\""])appTarget=YES;
|
||||
if(![xml containsString:@"com.dayu.color.installer"]){if(error)*error=DYUpdateError(@"更新包含不属于本产品的安装组件。");return NO;}
|
||||
}
|
||||
if([url.lastPathComponent isEqual:@"大鱼调色.moef"])templates=YES;
|
||||
}
|
||||
if(!appTarget||!templates){if(error)*error=DYUpdateError(@"更新包缺少正确的插件安装位置或 FCP 模板。");return NO;}
|
||||
return YES;
|
||||
} @finally {[NSFileManager.defaultManager removeItemAtURL:inspection error:nil];}
|
||||
}
|
||||
- (void)check {
|
||||
NSString *phase=_state[@"phase"];if([@[@"checking",@"downloading",@"validating"]containsObject:phase])return;
|
||||
unsigned generation=++_generation;[self emit:@"checking" message:@"正在检查公测更新…"];
|
||||
NSString *url=[NSString stringWithFormat:@"https://dayu.media/wp-json/dayu-color/v1/update?bundle_id=com.dayu.color&channel=beta¤t_build=%@",[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]];
|
||||
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:6];
|
||||
[_task release];_task=[[_session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error){@autoreleasepool{
|
||||
NSDictionary *value=data.length<=32768?[NSJSONSerialization JSONObjectWithData:data?:[NSData data] options:0 error:nil]:nil;
|
||||
if(![value isKindOfClass:NSDictionary.class])value=nil;
|
||||
BOOL ok=!error&&[(NSHTTPURLResponse*)response statusCode]==200&&[value[@"bundle_id"]isEqual:@"com.dayu.color"]&&[value[@"channel"]isEqual:@"beta"]&&[value[@"update_available"]isKindOfClass:NSNumber.class]&&CFGetTypeID((CFTypeRef)value[@"update_available"])==CFBooleanGetTypeID();
|
||||
if(ok&&[value[@"update_available"]boolValue])ok=[DYBetaUpdater validateManifest:value error:&error];
|
||||
NSDictionary *result=[[value copy]autorelease];
|
||||
dispatch_async(dispatch_get_main_queue(),^{if(generation!=self->_generation.load())return;
|
||||
if(!ok){[self emit:@"failed" message:@"暂时无法检查更新,不影响插件使用。"];
|
||||
DYBetaEvent(@"update_check",@{@"status":@"failed",@"error_code":@(error.code)});return;}
|
||||
[self->_manifest release];self->_manifest=[result copy];
|
||||
BOOL newer=[result[@"update_available"]boolValue]&&[result[@"build"]integerValue]>[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue];
|
||||
[self emit:newer?@"available":@"latest" message:newer?[NSString stringWithFormat:@"发现公测版 %@(%@)",result[@"version"],result[@"build"]]:@"当前已是最新公测版。"];
|
||||
DYBetaEvent(@"update_check",@{@"status":newer?@"available":@"latest"});
|
||||
});
|
||||
}}]retain];[_task resume];
|
||||
}
|
||||
- (void)download {
|
||||
if(![_state[@"phase"]isEqual:@"available"])return;NSError *error=nil;
|
||||
if(![DYBetaUpdater validateManifest:_manifest error:&error]){[self emit:@"failed" message:error.localizedDescription];return;}
|
||||
if([_manifest[@"build"]integerValue]<=[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue])return;
|
||||
unsigned generation=++_generation;NSDictionary *manifest=[[_manifest copy]autorelease];[self emit:@"downloading" message:@"正在下载公测更新,可随时取消。"];
|
||||
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:manifest[@"download_url"]]];request.timeoutInterval=30;
|
||||
[_task release];_task=[[_session downloadTaskWithRequest:request completionHandler:^(NSURL *temporary,NSURLResponse *response,NSError *failure){@autoreleasepool{
|
||||
if(generation!=self->_generation.load())return;
|
||||
NSError *error=failure;NSURL *destination=[updateFolder() URLByAppendingPathComponent:[NSString stringWithFormat:@"dayu-color-update-%@.pkg",manifest[@"build"]]];
|
||||
if(!error&&[(NSHTTPURLResponse*)response statusCode]==200&&DYBetaAllowedURL(response.URL,YES)){
|
||||
[NSFileManager.defaultManager removeItemAtURL:destination error:nil];
|
||||
if([NSFileManager.defaultManager moveItemAtURL:temporary toURL:destination error:&error]){
|
||||
[self emit:@"validating" message:@"正在验证完整性、签名、公证和插件版本…"];
|
||||
BOOL valid=[DYBetaUpdater validatePackage:destination manifest:manifest error:&error];
|
||||
if(!valid&&!error)error=DYUpdateError(@"更新包未通过验证。");
|
||||
}
|
||||
}else if(!error)error=DYUpdateError(@"更新包下载失败。");
|
||||
if(generation!=self->_generation.load()){[NSFileManager.defaultManager removeItemAtURL:destination error:nil];return;}
|
||||
if(error)[NSFileManager.defaultManager removeItemAtURL:destination error:nil];
|
||||
dispatch_async(dispatch_get_main_queue(),^{if(generation!=self->_generation.load())return;
|
||||
if(error){[self emit:@"available" message:error.localizedDescription];DYBetaEvent(@"update_download",@{@"status":@"failed",@"error_code":@(error.code)});}
|
||||
else{[self->_package release];self->_package=[destination retain];[self emit:@"ready" message:@"更新包已通过校验。保存并退出 FCP / Motion 后可安装。"];
|
||||
DYBetaEvent(@"update_validation",@{@"status":@"passed"});}
|
||||
});
|
||||
}}]retain];[_task resume];
|
||||
}
|
||||
- (void)install {
|
||||
if(![_state[@"phase"]isEqual:@"ready"]&&![_state[@"phase"]isEqual:@"host_wait"])return;
|
||||
for(NSString *ID in @[@"com.apple.FinalCut",@"com.apple.FinalCutApp",@"com.apple.motionapp",@"com.apple.motionappApp"])
|
||||
if([NSRunningApplication runningApplicationsWithBundleIdentifier:ID].count){[self emit:@"host_wait" message:@"请先保存并正常退出 FCP / Motion,再点击安装更新。不会强制退出宿主。"];
|
||||
DYBetaEvent(@"update_installer",@{@"status":@"waiting_for_host"});return;}
|
||||
if(_package&&[NSWorkspace.sharedWorkspace openURL:_package]){
|
||||
[NSUserDefaults.standardUserDefaults setObject:_manifest[@"build"] forKey:@"betaPendingUpdateBuild"];[self emit:@"installer" message:@"已打开系统安装程序,请按提示授权并完成安装。"];
|
||||
DYBetaEvent(@"update_installer",@{@"status":@"system_installer_opened"});}
|
||||
else [self emit:@"failed" message:@"无法打开系统安装程序,请重试。"];
|
||||
}
|
||||
- (void)cancel {++_generation;[_task cancel];BOOL newer=[_manifest[@"build"]integerValue]>[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue];[self emit:newer?@"available":@"idle" message:@"已取消,不影响当前插件。"];}
|
||||
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completion {
|
||||
BOOL download=[task isKindOfClass:NSURLSessionDownloadTask.class];completion(DYBetaAllowedURL(request.URL,download)?request:nil);
|
||||
}
|
||||
@end
|
||||
@@ -17,9 +17,9 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.6.1</string>
|
||||
<string>1.7.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>44</string>
|
||||
<string>45</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
|
||||
在新工单中引用
屏蔽一个用户