diff --git a/Backend/README.md b/Backend/README.md index ebd8874..bc9769f 100644 --- a/Backend/README.md +++ b/Backend/README.md @@ -4,7 +4,7 @@ LOCAL_PROJECT=/Users/mac/Downloads/dayumedia/dayu-color-beta NAS_ROOT=/Volumes/dayumedia (存储空间1)/wwwroot/dayu_media SOURCE_BACKUP=大鱼调色仓库 Backend/ -映射:wp-content/mu-plugins/dayu-color-beta.php → 同相对路径;wp-content/uploads/dayu-color-beta/updates/manifest.json → 同相对路径。发行PKG不进Git,由产品Release及生产公测下载空间保存。部署工作副本仅含本专项文件,源码和脱敏交付记录由产品已有仓库保存。 +映射:wp-content/mu-plugins/dayu-color-beta.php → 同相对路径;wp-content/uploads/dayu-color-beta/updates/beta.json → 同相对路径。发行PKG不进Git,由产品Release及生产公测下载空间保存。部署工作副本仅含本专项文件,源码和脱敏交付记录由产品已有仓库保存。 2026-11-02盘点:目标MU插件不存在;本地工作目录新建,无未部署改动。生产共享已确认来自192.168.31.21、dayumedia (存储空间1)、smbfs且可读写。仅操作本产品命名空间,不改共享鉴权插件或其他APP。参考fcpx-qwen3-asr提交113069c74aff935db2082b5bcd8e1aa47fe1fbf2的更新校验、分批诊断与崩溃脱敏流程。 diff --git a/Backend/wp-content/mu-plugins/dayu-color-beta.php b/Backend/wp-content/mu-plugins/dayu-color-beta.php new file mode 100644 index 0000000..270e5bb --- /dev/null +++ b/Backend/wp-content/mu-plugins/dayu-color-beta.php @@ -0,0 +1,179 @@ +prefix . 'dayu_color_beta_events'; } + public static function ensure_schema() { + if (get_option('dayu_color_beta_schema') === self::SCHEMA) return; + global $wpdb; + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + $table = self::table(); $collation = $wpdb->get_charset_collate(); + dbDelta("CREATE TABLE {$table} ( + event_id varchar(36) NOT NULL, + installation_id varchar(36) NOT NULL, + session_id varchar(36) NOT NULL, + client_version varchar(32) NOT NULL, + client_build bigint unsigned NOT NULL, + source varchar(12) NOT NULL, + event varchar(64) NOT NULL, + fields_json text NOT NULL, + occurred_at datetime NOT NULL, + received_at datetime NOT NULL, + PRIMARY KEY (event_id), + KEY received_at (received_at), + KEY client_event (client_build,event), + KEY installation (installation_id) + ) {$collation};"); + if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) === $table) { + update_option('dayu_color_beta_schema', self::SCHEMA, false); + if (!wp_next_scheduled('dayu_color_beta_cleanup')) wp_schedule_event(time()+3600, 'daily', 'dayu_color_beta_cleanup'); + } + } + public static function routes() { + self::ensure_schema(); + register_rest_route('dayu-color/v1', '/update', array('methods'=>'GET', 'permission_callback'=>'__return_true', 'callback'=>array(__CLASS__,'update'))); + register_rest_route('dayu-color/v1', '/diagnostics', array( + array('methods'=>'POST', 'permission_callback'=>'__return_true', 'callback'=>array(__CLASS__,'ingest')), + array('methods'=>'GET', 'permission_callback'=>function(){ return current_user_can('manage_options'); }, 'callback'=>array(__CLASS__,'events')) + )); + } + public static function manifest_path() { + $upload = wp_upload_dir(null, false); + return rtrim($upload['basedir'], '/\\') . '/dayu-color-beta/updates/beta.json'; + } + public static function manifest() { + $path = self::manifest_path(); + if (!is_file($path) || filesize($path)>32768) return array(); + $value = json_decode((string)file_get_contents($path), true); + if (!is_array($value) || ($value['bundle_id']??'')!==self::BUNDLE || ($value['channel']??'')!=='beta') return array(); + if (!is_string($value['download_url']??null) || !is_string($value['sha256']??null) || !is_string($value['version']??null) || !is_int($value['build']??null) || !is_int($value['size']??null) || ($value['package_type']??'')!=='pkg' || ($value['install_mode']??'')!=='pkg_installer') return array(); + $url = $value['download_url']; + if (!preg_match('~^https://dayu\.media/wp-content/uploads/dayu-color-beta/updates/[A-Za-z0-9_-]+\.pkg$~D', $url)) return array(); + if (!preg_match('/^[a-f0-9]{64}$/D', (string)($value['sha256']??'')) || intval($value['size']??0)<=0 || intval($value['build']??0)<=0 || intval($value['size'])>1073741824) return array(); + return $value; + } + public static function update($request) { + if (($request->get_param('bundle_id')??'')!==self::BUNDLE || ($request->get_param('channel')??'beta')!=='beta') { + return new WP_Error('product_mismatch','此通道仅用于大鱼调色公测。',array('status'=>400)); + } + $manifest = self::manifest(); + if (!$manifest) return new WP_REST_Response(array('bundle_id'=>self::BUNDLE,'channel'=>'beta','update_available'=>false,'message'=>'当前没有公测更新。'),200,array('Cache-Control'=>'no-store')); + $current = max(0, intval($request->get_param('current_build'))); + $manifest['update_available'] = intval($manifest['build']) > $current; + $manifest['checked_at'] = gmdate('c'); + return new WP_REST_Response($manifest,200,array('Cache-Control'=>'no-store')); + } + public static function clean_fields($input) { + if (!is_array($input)) return array(); + $out = array(); + foreach (self::FIELDS as $key) { + if (!array_key_exists($key,$input) || !is_scalar($input[$key])) continue; + if (in_array($key,array('duration_ms','main_delay_ms','memory_gb','cpu_cores','count','pending','error_code'),true)) { + if (is_numeric($input[$key]) && is_finite((float)$input[$key])) $out[$key]=max(-1000000,min(86400000,(float)$input[$key])); + continue; + } + $value = sanitize_textarea_field((string)$input[$key]); + $value = preg_replace('~(?:https?://\S+|(?:/Users/|/Volumes/|/private/|/var/)[^\r\n]*)~i','[REDACTED]',$value); + $value = preg_replace('/(?:bearer\s+\S+|(?:token|api[_-]?key|secret|password)\s*[=:]\s*\S+)/i','[REDACTED]',$value); + $limit = $key==='frames' ? 6000 : ($key==='active_stages' ? 1000 : 200); + $out[$key] = function_exists('mb_substr') ? mb_substr($value,0,$limit,'UTF-8') : substr($value,0,$limit); + } + return $out; + } + private static function uuid($value) { return is_string($value) && preg_match('/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/iD',$value); } + public static function ingest($request) { + if (strlen($request->get_body())>self::MAX_BODY) return new WP_Error('body_too_large','诊断批次过大。',array('status'=>413)); + $body = $request->get_json_params(); + if (!is_array($body) || ($body['bundle_id']??'')!==self::BUNDLE || !self::uuid($body['installation_id']??null) + || !isset($body['events']) || !is_array($body['events']) || count($body['events'])<1 || count($body['events'])>self::MAX_BATCH) { + return new WP_Error('invalid_batch','诊断批次无效。',array('status'=>400)); + } + // Anonymous beta diagnostics are untrusted input, never an authorization proof. + $ip = (string)($_SERVER['REMOTE_ADDR']??'unknown'); + $bucket = 'dayu_color_rate_' . substr(hash_hmac('sha256',$ip,wp_salt('nonce')),0,32); + $count = intval(get_transient($bucket)); + if ($count>=300) return new WP_Error('rate_limit','请稍后重试。',array('status'=>429)); + set_transient($bucket,$count+1,10*MINUTE_IN_SECONDS); + $normalized = array(); + foreach ($body['events'] as $event) { + if (!is_array($event) || !self::uuid($event['event_id']??null) || !self::uuid($event['session_id']??null) + || !in_array($event['event']??'',self::EVENTS,true) || !in_array($event['source']??'',array('app','plugin'),true) + || !is_string($event['version']??null) || strlen($event['version'])>32 || !preg_match('/^[0-9]+(?:\.[0-9A-Za-z_-]+){1,3}$/D',$event['version']) + || !is_int($event['build']??null) || $event['build']<1 || $event['build']>999999999 + || !is_numeric($event['occurred_at']??null) || !is_finite((float)$event['occurred_at']) || abs((float)$event['occurred_at']-time())>366*DAY_IN_SECONDS) return new WP_Error('invalid_event','诊断事件无效。',array('status'=>400)); + $normalized[] = array('event_id'=>strtolower($event['event_id']),'installation_id'=>strtolower($body['installation_id']), + 'session_id'=>strtolower($event['session_id']),'client_version'=>substr($event['version'],0,32), + 'client_build'=>intval($event['build']),'source'=>$event['source'],'event'=>$event['event'], + 'fields_json'=>wp_json_encode(self::clean_fields($event['fields']??array()),JSON_UNESCAPED_UNICODE), + 'occurred_at'=>gmdate('Y-m-d H:i:s',(int)$event['occurred_at']), 'received_at'=>gmdate('Y-m-d H:i:s')); + } + global $wpdb; $table=self::table(); $accepted=array(); + foreach ($normalized as $row) { + // Idempotent event IDs permit bounded retry after an ambiguous connection loss. + if ($wpdb->get_var($wpdb->prepare("SELECT event_id FROM {$table} WHERE event_id=%s",$row['event_id']))) { $accepted[]=$row['event_id']; continue; } + if ($wpdb->insert($table,$row)===false && !$wpdb->get_var($wpdb->prepare("SELECT event_id FROM {$table} WHERE event_id=%s",$row['event_id']))) return new WP_Error('storage_failed','诊断存储失败,请稍后重试。',array('status'=>503)); + $accepted[]=$row['event_id']; + } + return new WP_REST_Response(array('accepted'=>true,'event_ids'=>$accepted,'received_at'=>gmdate('c')),200,array('Cache-Control'=>'no-store')); + } + public static function cleanup() { + global $wpdb; $table=self::table(); + $wpdb->query($wpdb->prepare("DELETE FROM {$table} WHERE received_at < %s",gmdate('Y-m-d H:i:s',time()-30*DAY_IN_SECONDS))); + } + public static function events($request) { + global $wpdb; $table=self::table(); $where='1=1'; $values=array(); + foreach (array('build'=>'client_build','event'=>'event','installation'=>'installation_id') as $param=>$column) { + $raw=$request->get_param($param);$value = is_scalar($raw)?sanitize_text_field((string)$raw):''; + if ($value!=='') { $where.=" AND {$column}=%s"; $values[]=$value; } + } + $page=max(1,min(1000,intval($request->get_param('page')))); + $sql="SELECT event_id,installation_id,session_id,client_version,client_build,source,event,fields_json,occurred_at,received_at FROM {$table} WHERE {$where} ORDER BY received_at DESC LIMIT 50 OFFSET " . (($page-1)*50); + $rows=$wpdb->get_results($values?$wpdb->prepare($sql,$values):$sql,ARRAY_A); + return array('events'=>$rows?:array(),'page'=>$page,'retention_days'=>30); + } + public static function admin() { + if (!current_user_can('manage_options')) return; + self::ensure_schema(); global $wpdb; $table=self::table(); + $request = new WP_REST_Request('GET'); + foreach (array('build','event','installation') as $key) $request->set_param($key,is_string($_GET[$key]??null)?sanitize_text_field(wp_unslash($_GET[$key])):''); + $request->set_param('page',max(1,intval($_GET['paged']??1))); + $result=self::events($request);$manifest=self::manifest(); + $devices=intval($wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT installation_id) FROM {$table} WHERE received_at >= %s",gmdate('Y-m-d H:i:s',time()-7*DAY_IN_SECONDS)))); + echo '

大鱼调色公测

近7天报告设备:'.esc_html($devices).' · 诊断保留30天。匿名公测标识用于关联问题,不代表账号或设备授权。

'; + echo '

公测更新

'.($manifest?'当前版本:'.esc_html($manifest['version']).'('.esc_html($manifest['build']).')':'尚未发布更新包').'

'; + echo '

诊断事件

'; + foreach (array('build'=>'构建号','event'=>'事件','installation'=>'完整报告标识') as $key=>$label) echo ' '; + echo '
'; + foreach ($result['events'] as $row) { + echo ''; + } + echo '
时间(UTC)版本报告标识来源/事件内容
'.esc_html($row['received_at']).''.esc_html($row['client_version'].' ('.$row['client_build'].')').''.esc_html($row['installation_id']).'
会话 '.esc_html(substr($row['session_id'],0,8)).'
'.esc_html($row['source'].' / '.$row['event']).'
'.esc_html(wp_json_encode(json_decode($row['fields_json'],true),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)).'

'; + $base=array('page'=>'dayu-color-beta','build'=>$request->get_param('build'),'event'=>$request->get_param('event'),'installation'=>$request->get_param('installation')); + if ($result['page']>1) echo '上一页 '; + if (count($result['events'])===50) echo '下一页'; + echo '

仅包含产品版本、环境、阶段耗时、错误代码及本插件崩溃摘要,不接收素材、预设、硬件UUID或账户凭据。

'; + } +} +Dayu_Color_Beta::boot(); diff --git a/大鱼调色.xcodeproj/project.pbxproj b/大鱼调色.xcodeproj/project.pbxproj index 82e51d0..ef38ba4 100644 --- a/大鱼调色.xcodeproj/project.pbxproj +++ b/大鱼调色.xcodeproj/project.pbxproj @@ -123,6 +123,7 @@ Plugin/Resources/InputLUTs/sony_slog3_sgamut3cine_to_rec709.dylut, "Plugin/Resources/THIRD-PARTY-NOTICES.txt", "Wrapper Application/AppDelegate.m", + "Wrapper Application/DYBetaUpdater.mm", "Wrapper Application/Info.plist", "Wrapper Application/main.m", "Wrapper Application/Resources/DayuColor.icns", diff --git a/大鱼调色/Plugin/DYInspector.mm b/大鱼调色/Plugin/DYInspector.mm index 3f71b70..f3e0a90 100644 --- a/大鱼调色/Plugin/DYInspector.mm +++ b/大鱼调色/Plugin/DYInspector.mm @@ -1,4 +1,5 @@ #import "DYInspector.h" +#import "../Shared/DYBetaDiagnostics.h" #import "DYModel.h" #import "DYToolState.h" #import "DYAutoGrade.h" @@ -447,6 +448,7 @@ static NSImage *DYWheelImage(void) { return [self initWithAPIManager:manager renderer:nil]; } - (instancetype)initWithAPIManager:(id)manager renderer:(DYRenderer *)renderer { + uint64_t beta=DYBetaSpanBegin(@"inspector_create",nil); if((self=[super initWithFrame:NSMakeRect(0,0,360,780)])) { _assetLoads=[NSMutableDictionary new];_assetLoadIDs=[NSMutableDictionary new];_manager=manager; _renderer=[renderer retain];_library=[DYLUTLibrary new];_tabs=[NSMutableDictionary new];_visibleLooks=1; _embedded=[manager isKindOfClass:DYToolManager.class];if(_embedded)[(id)_manager retain]; @@ -491,7 +493,7 @@ static NSImage *DYWheelImage(void) { [self setAccessibilityLabel:@"大鱼调色检查器"]; [self setNeedsLayout:YES]; } - return self; + DYBetaSpanEnd(beta,nil);return self; } - (void)dealloc { [self graphicGesture:NO title:nil];_spiderPanel.delegate=nil; @@ -754,6 +756,7 @@ static NSImage *DYWheelImage(void) { if(_refreshing||!_manager)return; id action=[self actionAPI]; if(!action)return; _refreshing=YES; + uint64_t beta=DYBetaSpanBegin(@"inspector_refresh",nil); BOOL groupingChanged=NO; [action startAction:self]; @try { @@ -813,6 +816,7 @@ static NSImage *DYWheelImage(void) { // Remote layout/accessibility can re-enter the host. Let the parameter // action and current callback unwind before notifying the remote view. if(!_embedded)[self synchronizeTools]; + DYBetaSpanEnd(beta,nil); if(groupingChanged)dispatch_async(dispatch_get_main_queue(),^{NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);}); } - (void)postChanged { [[NSNotificationCenter defaultCenter] postNotificationName:@"DYModelChanged" object:_embedded?[(DYToolManager*)_manager host]:_manager]; } diff --git a/大鱼调色/Plugin/DYPlugIn.mm b/大鱼调色/Plugin/DYPlugIn.mm index 67be468..2fab45d 100644 --- a/大鱼调色/Plugin/DYPlugIn.mm +++ b/大鱼调色/Plugin/DYPlugIn.mm @@ -1,4 +1,5 @@ #import "DYPlugIn.h" +#import "../Shared/DYBetaDiagnostics.h" #import "DYModel.h" #import "DYRenderer.h" #import "DYInspector.h" @@ -15,10 +16,11 @@ @implementation DYPlugIn { DYRenderer *_renderer; BOOL _copyAnalyzed; + std::atomic_bool _betaFirstRenderStarted; #include "DYToolHostIvars.inc.h" } #include "DYToolHostMethods.inc.h" -- (instancetype)initWithAPIManager:(id)manager{if((self=[super init])){_apiManager=manager;_renderer=[DYRenderer new];[self initializeToolHost];NSNotificationCenter*n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(exportRequested:) name:@"DYExportLUT" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoGrade" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoWhiteBalance" object:manager];[n addObserver:self selector:@selector(whiteBalanceRequested:) name:@"DYWhiteBalanceColor" object:manager];}return self;} +- (instancetype)initWithAPIManager:(id)manager{uint64_t beta=DYBetaSpanBegin(@"plugin_init",nil);if((self=[super init])){_betaFirstRenderStarted.store(false);_apiManager=manager;_renderer=[DYRenderer new];[self initializeToolHost];NSNotificationCenter*n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(exportRequested:) name:@"DYExportLUT" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoGrade" object:manager];[n addObserver:self selector:@selector(autoRequested:) name:@"DYAutoWhiteBalance" object:manager];[n addObserver:self selector:@selector(whiteBalanceRequested:) name:@"DYWhiteBalanceColor" object:manager];}DYBetaSpanEnd(beta,nil);return self;} - (void)dealloc{[self tearDownToolHost];[NSNotificationCenter.defaultCenter removeObserver:self];[_renderer release];[super dealloc];} - (BOOL)properties:(NSDictionary**)p error:(NSError**)e{*p=@{kFxPropertyKey_MayRemapTime:@NO,kFxPropertyKey_PixelTransformSupport:@(kFxPixelTransform_ScaleTranslate),kFxPropertyKey_VariesWhenParamsAreStatic:@YES,kFxPropertyKey_DesiredProcessingColorInfo:@(kFxImageColorInfo_RGB_LINEAR),kFxPropertyKey_NeedsFullBuffer:@YES};return YES;} - (BOOL)addParametersWithError:(NSError**)e{return DYCreateParameters(_apiManager,e);} @@ -31,7 +33,7 @@ - (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;} - (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;} - (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{ - if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] error:e];if(ok){if(_toolCaptureEnabled&&!_trackingActive.load()){dy::GrayFrame frame=[self toolGrayFrame:src[0] error:nil];if(frame.valid()){@synchronized(self){_toolSourceFrame=std::move(frame);_toolSourceTime=t;}}}BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok; + if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] error:e];DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",@{@"error_domain":(e&&*e)?(*e).domain:@"unknown",@"error_code":@((e&&*e)?(*e).code:0)});if(ok){if(_toolCaptureEnabled&&!_trackingActive.load()){dy::GrayFrame frame=[self toolGrayFrame:src[0] error:nil];if(frame.valid()){@synchronized(self){_toolSourceFrame=std::move(frame);_toolSourceTime=t;}}}BOOL analyze=NO;@synchronized(self){if(![p[@"copyAuto"]boolValue])_copyAnalyzed=NO;else if(!_copyAnalyzed){_copyAnalyzed=YES;analyze=YES;}}if(analyze){NSDictionary*values=DYAutoGrade([_renderer preview]);if(values)dispatch_async(dispatch_get_main_queue(),^{[self applyValues:values];});}}return ok; } - (void)alert:(NSString*)message{dispatch_async(dispatch_get_main_queue(),^{NSAlert*a=[NSAlert new];a.messageText=@"大鱼调色";a.informativeText=message?:@"操作未完成";[a runModal];[a release];});} - (void)exportRequested:(NSNotification*)n{ diff --git a/大鱼调色/Plugin/DYRenderer.mm b/大鱼调色/Plugin/DYRenderer.mm index 526faf5..50c3ae4 100644 --- a/大鱼调色/Plugin/DYRenderer.mm +++ b/大鱼调色/Plugin/DYRenderer.mm @@ -1,4 +1,5 @@ #import "DYRenderer.h" +#import "../Shared/DYBetaDiagnostics.h" #import "DYModel.h" #include "DYSpiderState.h" #include "DYToolGPU.h" @@ -99,15 +100,17 @@ static void bypassIdleSkin(DYUniforms *u){ - (NSData*)lookLUTPreview{@synchronized(_previewLock){return [[_lookLUTPreview retain]autorelease];}} - (NSMutableDictionary*)device:(uint64_t)registry error:(NSError**)err{ NSNumber*k=@(registry);NSMutableDictionary*entry=_devices[k];if(entry)return entry; + uint64_t beta=DYBetaSpanBegin(@"device_prepare",nil);@try{ idd=nil;NSArray*all=MTLCopyAllDevices();for(idcandidate in all)if(candidate.registryID==registry||!registry){d=[candidate retain];break;}[all release];if(!d){fail(err,@"宿主的 Metal 设备不可用");return nil;} NSURL*url=[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"]; idlib=[d newLibraryWithURL:url error:err];if(!lib){[d release];return nil;} idq=[d newCommandQueue];entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"library":lib,@"queue":q,@"pipelines":[NSMutableDictionary dictionary]}]; - for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyColorManagement",@"dyToolBlend",@"dyToolSkin",@"dyFilmPoint",@"dyFilmNoise",@"dyFilmSparseBlur",@"dyFilmBloomEdges",@"dyFilmMix",@"dyFilmPrint"]){idf=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}idp=[d newComputePipelineStateWithFunction:f error:err];[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];} + for(NSString*fn in @[@"dyUnpremultiply",@"dyWhitesSceneStatistics",@"dyLUTExportKernel",@"dyInputAnalysis",@"dyColorManagement",@"dyToolBlend",@"dyToolSkin",@"dyFilmPoint",@"dyFilmNoise",@"dyFilmSparseBlur",@"dyFilmBloomEdges",@"dyFilmMix",@"dyFilmPrint"]){idf=[lib newFunctionWithName:fn];if(!f){fail(err,[fn stringByAppendingString:@" 缺失"]);[lib release];[q release];[d release];return nil;}uint64_t pipelineSpan=DYBetaSpanBegin(@"gpu_pipeline",@{@"pipeline":fn,@"gpu":d.name?:@"unknown"});idp=[d newComputePipelineStateWithFunction:f error:err];DYBetaSpanEnd(pipelineSpan,@{@"status":p?@"passed":@"failed"});[f release];if(!p){[lib release];[q release];[d release];return nil;}entry[fn]=p;[p release];} float identity[32];for(int z=0;z<2;z++)for(int y=0;y<2;y++)for(int x=0;x<2;x++){int i=((z*2+y)*2+x)*4;identity[i]=x;identity[i+1]=y;identity[i+2]=z;identity[i+3]=1;}idneutral=texture3D(d,identity,2);if(!neutral){fail(err,@"无法分配中性 LUT");return nil;}entry[@"identity"]=neutral; // Preparing before the first frame may use registry 0. Reuse those pipelines // when the host subsequently supplies that device's actual registry ID. _devices[k]=entry;_devices[@(d.registryID)]=entry;[d release];[lib release];[q release];return entry; + }@finally{DYBetaSpanEnd(beta,nil);} } - (id)lut:(NSString*)path entry:(NSDictionary*)e error:(NSError**)err{ if(!path.length)return e[@"identity"]; diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist index eb532da..a297cb8 100644 --- a/大鱼调色/Plugin/Info.plist +++ b/大鱼调色/Plugin/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 1.6.1 + 1.7.0 CFBundleVersion - 44 + 45 NSHumanReadableCopyright PlugInKit @@ -71,7 +71,7 @@ uuid 1C17B73B-F229-4C09-A434-EAF6DFF5F22A version - 1.6.1 + 1.7.0 className diff --git a/大鱼调色/Plugin/main.m b/大鱼调色/Plugin/main.m index 10c6b1c..231d4c0 100644 --- a/大鱼调色/Plugin/main.m +++ b/大鱼调色/Plugin/main.m @@ -1,4 +1,5 @@ #import #import "DYDiagnostics.h" +#import "../Shared/DYBetaDiagnostics.h" #include -int main(int argc,const char*argv[]){@autoreleasepool{if(argc==2&&strcmp(argv[1],"--self-test")==0)return DYRunDiagnostics();[FxPrincipal startServicePrincipal];return 0;}} +int main(int argc,const char*argv[]){@autoreleasepool{if(argc==2&&strcmp(argv[1],"--self-test")==0)return DYRunDiagnostics();DYBetaStart();[FxPrincipal startServicePrincipal];DYBetaStop();return 0;}} diff --git a/大鱼调色/Shared/DYBetaDiagnostics.h b/大鱼调色/Shared/DYBetaDiagnostics.h new file mode 100644 index 0000000..b50504c --- /dev/null +++ b/大鱼调色/Shared/DYBetaDiagnostics.h @@ -0,0 +1,15 @@ +#import +#include + +FOUNDATION_EXPORT NSString *const DYBetaDiagnosticsChanged; +FOUNDATION_EXPORT void DYBetaStart(void); +FOUNDATION_EXPORT void DYBetaStop(void); +FOUNDATION_EXPORT void DYBetaEvent(NSString *event, NSDictionary *fields); +FOUNDATION_EXPORT uint64_t DYBetaSpanBegin(NSString *stage, NSDictionary *fields); +FOUNDATION_EXPORT void DYBetaSpanEnd(uint64_t token, NSDictionary *fields); +FOUNDATION_EXPORT NSDictionary *DYBetaSafeFields(NSDictionary *fields); +FOUNDATION_EXPORT BOOL DYBetaEnabled(void); +FOUNDATION_EXPORT void DYBetaSetEnabled(BOOL enabled); +FOUNDATION_EXPORT NSDictionary *DYBetaStatus(void); +FOUNDATION_EXPORT void DYBetaSendSummary(void); +FOUNDATION_EXPORT BOOL DYBetaAllowedURL(NSURL *url, BOOL download); diff --git a/大鱼调色/Shared/DYBetaDiagnostics.mm b/大鱼调色/Shared/DYBetaDiagnostics.mm new file mode 100644 index 0000000..fd8bc54 --- /dev/null +++ b/大鱼调色/Shared/DYBetaDiagnostics.mm @@ -0,0 +1,233 @@ +#import "DYBetaDiagnostics.h" +#import +#include +#include +#include +#include +#include +#include +#include + +NSString *const DYBetaDiagnosticsChanged = @"DYBetaDiagnosticsChanged"; +static NSString *const DYBetaPreferenceDomain = @"com.dayu.color.preferences"; +static std::atomic_bool gEnabled(true); +static std::atomic_uint_fast64_t gSpan(0); +static std::atomic gMainReply(0); +static NSObject *gSpanLock, *gStatusLock; +static NSMutableDictionary *gActive; +static NSDictionary *gStatus; +static BOOL gProduct; + +BOOL DYBetaAllowedURL(NSURL *url, BOOL download) { + if (![url.scheme.lowercaseString isEqual:@"https"] || ![url.host.lowercaseString isEqual:@"dayu.media"] || + url.user.length || url.password.length || (url.port && url.port.integerValue!=443)) return NO; + NSString *prefix=download?@"/wp-content/uploads/dayu-color-beta/updates/":@"/wp-json/dayu-color/v1/"; + return [url.path hasPrefix:prefix] && ![url.path.pathComponents containsObject:@".."]; +} +NSDictionary *DYBetaSafeFields(NSDictionary *fields) { + static NSSet *allowed; static dispatch_once_t once; + dispatch_once(&once,^{allowed=[[NSSet alloc]initWithArray:@[@"phase",@"stage",@"pipeline",@"duration_ms",@"status",@"error_domain",@"error_code",@"exception",@"signal",@"frames",@"report_time",@"count",@"pending",@"model",@"os_version",@"fcp_version",@"cpu_cores",@"memory_gb",@"gpu",@"main_delay_ms",@"active_stages",@"source_version"]];}); + NSMutableDictionary *out=[NSMutableDictionary dictionary]; + if(![fields isKindOfClass:NSDictionary.class])return @{}; + for (NSString *key in fields) { + if (![allowed containsObject:key]) continue; + id value=fields[key]; + if ([value isKindOfClass:NSNumber.class]) { if (std::isfinite([value doubleValue])) out[key]=value; continue; } + if (![value isKindOfClass:NSString.class]) continue; + NSString *text=value; + for (NSString *pattern in @[@"(?:https?://\\S+|(?:/Users/|/Volumes/|/private/|/var/)[^\\r\\n]*)",@"(?i)(?:bearer\\s+\\S+|(?:token|api[_-]?key|secret|password)\\s*[=:]\\s*\\S+)"]) + text=[text stringByReplacingOccurrencesOfString:pattern withString:@"[REDACTED]" options:NSRegularExpressionSearch range:NSMakeRange(0,text.length)]; + NSUInteger limit=[key isEqual:@"frames"]?6000:[key isEqual:@"active_stages"]?1000:200; + out[key]=text.length>limit?[text substringToIndex:limit]:text; + } + return out; +} + +@interface DYBetaTransport : NSObject { +@public + dispatch_queue_t queue; + dispatch_source_t timer; + NSMutableArray *pending; + NSMutableSet *seenCrashes; + NSMutableDictionary *lastEvents; + NSURLSession *session; + NSURLSessionDataTask *sending; + NSString *sessionID, *installationID, *source, *version; + NSNumber *build; + NSURL *folder, *journal; + NSDictionary *environment; + NSTimeInterval nextAttempt, lastTick, lastStall; + BOOL ready; +} +- (void)enqueue:(NSString *)event fields:(NSDictionary *)fields; +- (void)drain; +- (void)persist; +- (void)scanCrashSummaries; +@end +static DYBetaTransport *transport; +static void publishStatus(NSDictionary *values) { + @synchronized(gStatusLock) { [gStatus release]; gStatus=[values copy]; } + dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYBetaDiagnosticsChanged object:nil];}); +} +static NSDictionary *statusSnapshot(void) { @synchronized(gStatusLock) { return [[gStatus copy]autorelease]?:@{}; } } +static NSUserDefaults *preferences(void) { return [[[NSUserDefaults alloc]initWithSuiteName:DYBetaPreferenceDomain]autorelease]; } +static NSString *sysctlString(const char *key) { + char buffer[256]={};size_t size=sizeof(buffer);if(sysctlbyname(key,buffer,&size,NULL,0))return @"unknown"; + return [NSString stringWithUTF8String:buffer]?:@"unknown"; +} +@implementation DYBetaTransport +- (instancetype)init { + if((self=[super init])) { + queue=dispatch_queue_create("com.dayu.color.beta-diagnostics",DISPATCH_QUEUE_SERIAL); + pending=[NSMutableArray new];seenCrashes=[NSMutableSet new];lastEvents=[NSMutableDictionary new];sessionID=[NSUUID.UUID.UUIDString.lowercaseString copy]; + source=[([NSBundle.mainBundle.bundleIdentifier isEqual:@"com.dayu.color.XPC"]?@"plugin":@"app")copy]; + version=[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]copy];build=@([[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue]);[build retain]; + dispatch_async(queue,^{@autoreleasepool{[self prepare];}}); + }return self; +} +- (void)prepare { + NSUserDefaults *prefs=preferences();[prefs registerDefaults:@{@"betaDiagnosticsEnabled":@YES}];gEnabled.store([prefs boolForKey:@"betaDiagnosticsEnabled"]); + folder=[[[NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask].firstObject URLByAppendingPathComponent:@"com.dayu.color/Beta" isDirectory:YES]retain]; + [NSFileManager.defaultManager createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:@{NSFilePosixPermissions:@0700} error:nil]; + // O_EXCL gives the APP and XPC one random installation ID without hardware UUIDs. + NSURL *identity=[folder URLByAppendingPathComponent:@"installation.txt"]; + NSString *newID=NSUUID.UUID.UUIDString.lowercaseString; + int fd=open(identity.fileSystemRepresentation,O_WRONLY|O_CREAT|O_EXCL,0600); + if(fd>=0){NSData *data=[newID dataUsingEncoding:NSUTF8StringEncoding];write(fd,data.bytes,data.length);close(fd);} + for(int attempt=0;attempt<20;attempt++) { + [installationID release];installationID=[[[NSString stringWithContentsOfURL:identity encoding:NSUTF8StringEncoding error:nil]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]copy]; + if([[[NSUUID alloc]initWithUUIDString:installationID]autorelease])break; + [NSThread sleepForTimeInterval:.01]; + } + if(![[[NSUUID alloc]initWithUUIDString:installationID]autorelease]){gEnabled.store(false);return;} + NSURLSessionConfiguration *config=NSURLSessionConfiguration.ephemeralSessionConfiguration; + config.timeoutIntervalForRequest=8;config.timeoutIntervalForResource=12;config.HTTPShouldSetCookies=NO;config.URLCache=nil; + session=[[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]retain]; + uint64_t memory=0;size_t length=sizeof(memory);sysctlbyname("hw.memsize",&memory,&length,NULL,0); + NSString *fcp=@"not-installed"; + for(NSString *ID in @[@"com.apple.FinalCut",@"com.apple.FinalCutApp"]){NSURL *url=[NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:ID];if(url){fcp=[[NSBundle bundleWithURL:url]objectForInfoDictionaryKey:@"CFBundleShortVersionString"]?:@"unknown";break;}} + environment=[@{@"model":sysctlString("hw.model"),@"os_version":NSProcessInfo.processInfo.operatingSystemVersionString,@"fcp_version":fcp,@"cpu_cores":@(NSProcessInfo.processInfo.processorCount),@"memory_gb":@(double(memory)/(1024*1024*1024))}copy]; + journal=[[folder URLByAppendingPathComponent:[NSString stringWithFormat:@"pending-%d-%@.json",getpid(),sessionID]]retain]; + NSArray *files=[NSFileManager.defaultManager contentsOfDirectoryAtURL:folder includingPropertiesForKeys:@[NSURLContentModificationDateKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil]; + NSUInteger recovered=0; + for(NSURL *url in files){if(![url.lastPathComponent hasPrefix:@"pending-"]||![url.pathExtension isEqual:@"json"])continue; + NSNumber *bytes=nil;[url getResourceValue:&bytes forKey:NSURLFileSizeKey error:nil];if(bytes.unsignedLongLongValue>384*1024)continue; + NSDictionary *old=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:url]?:[NSData data] options:0 error:nil];if(![old isKindOfClass:NSDictionary.class])continue; + if(![old[@"pid"]isKindOfClass:NSNumber.class])continue;int pid=[old[@"pid"]intValue];if(pid>0&&kill(pid,0)==0)continue; + NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil]; + if(gEnabled.load()&&date.timeIntervalSinceNow> -7*86400&&[old[@"events"]isKindOfClass:NSArray.class])for(NSDictionary *event in old[@"events"]){if(pending.count>=256)break; + if(![event isKindOfClass:NSDictionary.class]||![event[@"event_id"]isKindOfClass:NSString.class]||![event[@"session_id"]isKindOfClass:NSString.class]|| + ![[[NSUUID alloc]initWithUUIDString:event[@"event_id"]]autorelease]||![[[NSUUID alloc]initWithUUIDString:event[@"session_id"]]autorelease]|| + ![event[@"version"]isKindOfClass:NSString.class]||![event[@"build"]isKindOfClass:NSNumber.class]||![event[@"event"]isKindOfClass:NSString.class]|| + ![@[@"app",@"plugin"]containsObject:event[@"source"]]||![event[@"fields"]isKindOfClass:NSDictionary.class]||![event[@"occurred_at"]isKindOfClass:NSNumber.class])continue; + NSMutableDictionary *safe=[[event mutableCopy]autorelease];safe[@"fields"]=DYBetaSafeFields(event[@"fields"]);[pending addObject:safe];recovered++;} + [NSFileManager.defaultManager removeItemAtURL:url error:nil]; + } + ready=YES;gMainReply.store(NSProcessInfo.processInfo.systemUptime);lastTick=gMainReply.load(); + [self enqueue:@"process_start" fields:environment];if(recovered)[self enqueue:@"previous_session_pending" fields:@{@"count":@(recovered)}]; + publishStatus(@{@"installation_id":installationID,@"enabled":@(gEnabled.load()),@"pending":@(pending.count)}); + timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue); + dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW,2*NSEC_PER_SEC),3*NSEC_PER_SEC,NSEC_PER_SEC/4); + dispatch_source_set_event_handler(timer,^{@autoreleasepool{[self tick];}});dispatch_resume(timer); + [NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(settingsChanged:) name:@"com.dayu.color.beta.preferences" object:nil]; + if([source isEqual:@"app"])[self scanCrashSummaries]; +} +- (void)enqueue:(NSString *)event fields:(NSDictionary *)fields { + if(!ready||!gEnabled.load())return; + // A bad render must not turn diagnostics into per-frame disk writes. + if([@[@"render_error",@"inspector_refresh"]containsObject:event]){ + double now=NSProcessInfo.processInfo.systemUptime;if(now-[lastEvents[event]doubleValue]<5)return;lastEvents[event]=@(now); + } + if(pending.count>=256)[pending removeObjectsInRange:NSMakeRange(0,32)]; + [pending addObject:@{@"event_id":NSUUID.UUID.UUIDString.lowercaseString,@"session_id":sessionID,@"source":source,@"version":version?:@"0.0",@"build":build?:@1,@"event":event,@"occurred_at":@(NSDate.date.timeIntervalSince1970),@"fields":DYBetaSafeFields(fields?:@{})}]; + [self persist]; +} +- (void)persist { + if(!journal)return; + NSData *data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil]; + if(data.length>384*1024){while(pending.count>64)[pending removeObjectAtIndex:0];data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil];} + [data writeToURL:journal options:NSDataWritingAtomic error:nil];chmod(journal.fileSystemRepresentation,0600); +} +- (void)drain { + if(!ready||!gEnabled.load()||sending||!pending.count||NSDate.date.timeIntervalSince197098304){[pending removeObjectAtIndex:0];[batch release];[self persist];return;} + NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dayu.media/wp-json/dayu-color/v1/diagnostics"]];request.HTTPMethod=@"POST";request.HTTPBody=data;[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + sending=[[session dataTaskWithRequest:request completionHandler:^(NSData *body,NSURLResponse *response,NSError *error){ + dispatch_async(self->queue,^{@autoreleasepool{ + NSDictionary *reply=body?[NSJSONSerialization JSONObjectWithData:body options:0 error:nil]:nil;if(![reply isKindOfClass:NSDictionary.class])reply=nil; + NSSet *accepted=[reply[@"event_ids"]isKindOfClass:NSArray.class]?[NSSet setWithArray:reply[@"event_ids"]]:[NSSet set]; + NSSet *expected=[NSSet setWithArray:[batch valueForKey:@"event_id"]]; + BOOL ok=!error&&[(NSHTTPURLResponse*)response statusCode]==200&&[reply[@"accepted"]isKindOfClass:NSNumber.class]&&[reply[@"accepted"]boolValue]&&[accepted isEqualToSet:expected]; + if(ok){NSIndexSet *remove=[self->pending indexesOfObjectsPassingTest:^BOOL(NSDictionary *event,NSUInteger i,BOOL *stop){return [accepted containsObject:event[@"event_id"]];}];[self->pending removeObjectsAtIndexes:remove];self->nextAttempt=0; + publishStatus(@{@"installation_id":self->installationID,@"enabled":@(gEnabled.load()),@"pending":@(self->pending.count),@"last_upload":@([NSDate.date timeIntervalSince1970])}); + }else self->nextAttempt=NSDate.date.timeIntervalSince1970+30; + [self->sending release];self->sending=nil;[batch release];[self persist]; + }}); + }]retain];[sending resume]; +} +- (void)tick { + double now=NSProcessInfo.processInfo.systemUptime; + if(now-lastTick>15)gMainReply.store(now); // Sleep/wake and timer coalescing are not proof of a hang. + lastTick=now; + if(gEnabled.load()&&now-gMainReply.load()>6&&now-lastStall>30){lastStall=now;[self enqueue:@"main_thread_stall" fields:@{@"status":@"suspected",@"main_delay_ms":@((now-gMainReply.load())*1000),@"active_stages":[self activeStages:now]}];} + else if(gEnabled.load()&&now-lastStall>30){NSString *stages=[self activeStages:now];if(stages.length){lastStall=now;[self enqueue:@"operation_stall" fields:@{@"status":@"suspected",@"active_stages":stages}];}} + dispatch_async(dispatch_get_main_queue(),^{gMainReply.store(NSProcessInfo.processInfo.systemUptime);}); + [self drain]; +} +- (NSString *)activeStages:(double)now { + NSArray *values;@synchronized(gSpanLock){values=[[gActive.allValues copy]autorelease];} + NSMutableArray *slow=[NSMutableArray array];for(NSDictionary *span in values)if(now-[span[@"start"]doubleValue]>6)[slow addObject:[NSString stringWithFormat:@"%@: %.0fms",span[@"stage"],(now-[span[@"start"]doubleValue])*1000]]; + return [slow componentsJoinedByString:@"; "]; +} +- (void)settingsChanged:(NSNotification *)note { + dispatch_async(queue,^{@autoreleasepool{NSUserDefaults *prefs=preferences();[prefs synchronize];gEnabled.store([prefs objectForKey:@"betaDiagnosticsEnabled"]?[prefs boolForKey:@"betaDiagnosticsEnabled"]:YES); + if(!gEnabled.load()){[self->sending cancel];[self->pending removeAllObjects];[self persist];} + publishStatus(@{@"installation_id":self->installationID?:@"",@"enabled":@(gEnabled.load()),@"pending":@(self->pending.count)}); + }}); +} +- (void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler { + completionHandler(DYBetaAllowedURL(request.URL,NO)?request:nil); +} +- (void)scanCrashSummaries { + if(!gEnabled.load())return; + NSURL *reports=[NSFileManager.defaultManager.homeDirectoryForCurrentUser URLByAppendingPathComponent:@"Library/Logs/DiagnosticReports"]; + NSArray *files=[NSFileManager.defaultManager contentsOfDirectoryAtURL:reports includingPropertiesForKeys:@[NSURLContentModificationDateKey,NSURLFileSizeKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil]; + NSUInteger count=0; + for(NSURL *url in files){if(count>=12)break;if(![url.pathExtension isEqual:@"ips"])continue; + NSNumber *size=nil;[url getResourceValue:&size forKey:NSURLFileSizeKey error:nil];if(size.unsignedLongLongValue>8*1024*1024)continue; + NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];if(date.timeIntervalSinceNow< -7*86400)continue; + NSFileHandle *handle=[NSFileHandle fileHandleForReadingFromURL:url error:nil];NSData *head=[handle readDataUpToLength:8192 error:nil];[handle closeFile]; + if(!head.length)continue;NSString *prefix=[[[NSString alloc]initWithData:head encoding:NSUTF8StringEncoding]autorelease];NSRange first=[prefix rangeOfString:@"\n"];if(!prefix||first.location==NSNotFound)continue; + NSDictionary *header=[NSJSONSerialization JSONObjectWithData:[[prefix substringToIndex:first.location]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];if(![header isKindOfClass:NSDictionary.class]||![header[@"bundleID"]isEqual:@"com.dayu.color.XPC"])continue; + NSData *data=[NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:nil];if(!data.length)continue;NSString *text=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];NSRange newline=[text rangeOfString:@"\n"];if(!text||newline.location==NSNotFound)continue; + NSString *key=header[@"incident_id"];if(![key isKindOfClass:NSString.class]||![[[NSUUID alloc]initWithUUIDString:key]autorelease])continue;if([seenCrashes containsObject:key])continue;[seenCrashes addObject:key]; + NSDictionary *body=[NSJSONSerialization JSONObjectWithData:[[text substringFromIndex:newline.location+1]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; + if(![body isKindOfClass:NSDictionary.class])continue;NSDictionary *exception=[body[@"exception"]isKindOfClass:NSDictionary.class]?body[@"exception"]:@{}; + NSInteger fault=[body[@"faultingThread"]isKindOfClass:NSNumber.class]?[body[@"faultingThread"]integerValue]:-1;NSArray *threads=body[@"threads"];NSMutableArray *frames=[NSMutableArray array]; + if([threads isKindOfClass:NSArray.class]&&fault>=0&&fault=30)break;if(![frame isKindOfClass:NSDictionary.class])continue;NSString *symbol=frame[@"symbol"];if([symbol isKindOfClass:NSString.class]&&![symbol containsString:@"/"])[frames addObject:symbol];} + [self enqueue:@"crash_summary" fields:@{@"source_version":header[@"app_version"]?:@"unknown",@"report_time":header[@"timestamp"]?:@"unknown",@"exception":exception[@"type"]?:@"unknown",@"signal":exception[@"signal"]?:@"unknown",@"frames":[frames componentsJoinedByString:@"\n"]}]; + if(pending.count){NSMutableDictionary *event=[[pending.lastObject mutableCopy]autorelease];event[@"event_id"]=key.lowercaseString;[pending replaceObjectAtIndex:pending.count-1 withObject:event];[self persist];}count++; + } +} +@end + +void DYBetaStart(void) { + static dispatch_once_t once;dispatch_once(&once,^{ + NSString *ID=NSBundle.mainBundle.bundleIdentifier; + gProduct=([ID isEqual:@"com.dayu.color"]||[ID isEqual:@"com.dayu.color.XPC"])&&![NSProcessInfo.processInfo.arguments containsObject:@"--self-test"]; + gSpanLock=[NSObject new];gStatusLock=[NSObject new];gActive=[NSMutableDictionary new]; + if(gProduct)transport=[DYBetaTransport new]; + }); +} +BOOL DYBetaEnabled(void){DYBetaStart();return gEnabled.load();} +void DYBetaSetEnabled(BOOL enabled){DYBetaStart();gEnabled.store(enabled);NSUserDefaults *prefs=preferences();[prefs setBool:enabled forKey:@"betaDiagnosticsEnabled"];[prefs synchronize];[NSDistributedNotificationCenter.defaultCenter postNotificationName:@"com.dayu.color.beta.preferences" object:nil userInfo:nil deliverImmediately:YES];} +NSDictionary *DYBetaStatus(void){DYBetaStart();return statusSnapshot();} +void DYBetaEvent(NSString *event,NSDictionary *fields){DYBetaStart();if(!gProduct||!gEnabled.load())return;NSDictionary *safe=DYBetaSafeFields(fields?:@{});dispatch_async(transport->queue,^{@autoreleasepool{[transport enqueue:event fields:safe];}});} +uint64_t DYBetaSpanBegin(NSString *stage,NSDictionary *fields){DYBetaStart();if(!gProduct||!gEnabled.load())return 0;uint64_t token=++gSpan;NSDictionary *value=@{@"stage":stage,@"start":@(NSProcessInfo.processInfo.systemUptime),@"fields":DYBetaSafeFields(fields?:@{})};@synchronized(gSpanLock){if(gActive.count>=128)return 0;gActive[@(token)]=value;} + if(![stage isEqual:@"inspector_refresh"]){NSMutableDictionary *begin=[[value[@"fields"]mutableCopy]autorelease];begin[@"phase"]=@"begin";DYBetaEvent(stage,begin);}return token; +} +void DYBetaSpanEnd(uint64_t token,NSDictionary *fields){if(!token)return;NSDictionary *span;@synchronized(gSpanLock){span=[[gActive[@(token)]retain]autorelease];[gActive removeObjectForKey:@(token)];}if(!span)return;double elapsed=(NSProcessInfo.processInfo.systemUptime-[span[@"start"]doubleValue])*1000;if([span[@"stage"]isEqual:@"inspector_refresh"]&&elapsed<100)return;NSMutableDictionary *result=[[span[@"fields"]mutableCopy]autorelease];[result addEntriesFromDictionary:fields?:@{}];result[@"duration_ms"]=@(elapsed);result[@"phase"]=@"end";DYBetaEvent(span[@"stage"],result);} +void DYBetaStop(void){DYBetaEvent(@"process_exit",@{@"status":@"normal"});} +void DYBetaSendSummary(void){DYBetaStart();if(!gProduct)return;dispatch_async(transport->queue,^{@autoreleasepool{[transport enqueue:@"diagnostic_summary" fields:transport->environment];[transport scanCrashSummaries];[transport drain];}});} diff --git a/大鱼调色/Wrapper Application/AppDelegate.m b/大鱼调色/Wrapper Application/AppDelegate.m index 636ef7c..6f96321 100644 --- a/大鱼调色/Wrapper Application/AppDelegate.m +++ b/大鱼调色/Wrapper Application/AppDelegate.m @@ -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 diff --git a/大鱼调色/Wrapper Application/DYBetaUpdater.h b/大鱼调色/Wrapper Application/DYBetaUpdater.h new file mode 100644 index 0000000..dc7f99e --- /dev/null +++ b/大鱼调色/Wrapper Application/DYBetaUpdater.h @@ -0,0 +1,12 @@ +#import +@interface DYBetaUpdater : NSObject +@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 diff --git a/大鱼调色/Wrapper Application/DYBetaUpdater.mm b/大鱼调色/Wrapper Application/DYBetaUpdater.mm new file mode 100644 index 0000000..155e521 --- /dev/null +++ b/大鱼调色/Wrapper Application/DYBetaUpdater.mm @@ -0,0 +1,166 @@ +#import "DYBetaUpdater.h" +#import "../Shared/DYBetaDiagnostics.h" +#import +#import +#include +#include + +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;i0)[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 diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist index 7b0897f..80a37b0 100644 --- a/大鱼调色/Wrapper Application/Info.plist +++ b/大鱼调色/Wrapper Application/Info.plist @@ -17,9 +17,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.6.1 + 1.7.0 CFBundleVersion - 44 + 45 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright