接入在线 LUT 权限、登录与服务器帧预览初版,待正式验收
这个提交包含在:
1 父节点
f7d0a80a2e
当前提交
a2a8624dc0
12 个文件已更改
+938
-18
没有与搜索条件相匹配的文件
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
// Isolated WordPress contract tests. Never load production configuration or user data.
|
||||
define('ABSPATH', __DIR__.'/'); define('ARRAY_A','ARRAY_A');
|
||||
class WP_Error { public $code,$message,$data; function __construct($c,$m,$d=array()){$this->code=$c;$this->message=$m;$this->data=$d;} }
|
||||
class WP_REST_Response { private $data; public $headers=array(); function __construct($d,$status=200){$this->data=$d;} function get_data(){return $this->data;} function header($k,$v){$this->headers[$k]=$v;} }
|
||||
class Request implements ArrayAccess {
|
||||
private $params,$headers;
|
||||
function __construct($p=array(),$token=''){$this->params=$p;$this->headers=array('authorization'=>$token?'Bearer '.$token:'');}
|
||||
function get_param($k){return $this->params[$k]??null;} function get_header($k){return $this->headers[$k]??'';} function get_body(){return json_encode($this->params);}
|
||||
function offsetExists($k):bool{return isset($this->params[$k]);} function offsetGet($k):mixed{return $this->get_param($k);} function offsetSet($k,$v):void{$this->params[$k]=$v;} function offsetUnset($k):void{unset($this->params[$k]);}
|
||||
}
|
||||
$transients=array();$options=array();$meta=array();$purchase=array();$admin=false;$member=false;$bound=7;$rows=array();$checks=array();
|
||||
function add_action(...$a){} function add_filter(...$a){} function register_rest_route(...$a){} function wp_schedule_single_event(...$a){}
|
||||
function add_option($k,$v,...$a){global $options;if(isset($options[$k]))return false;$options[$k]=$v;return true;}
|
||||
function delete_option($k){global $options;unset($options[$k]);}
|
||||
function get_transient($k){global $transients;return $transients[$k]??false;} function set_transient($k,$v,$ttl){global $transients;$transients[$k]=$v;return true;} function delete_transient($k){global $transients;unset($transients[$k]);}
|
||||
function sanitize_key($v){return preg_replace('/[^a-z0-9_\-]/','',strtolower($v));} function sanitize_text_field($v){return trim(strip_tags($v));}
|
||||
function get_user_by($key,$id){return $id===7?(object)array('ID'=>7,'display_name'=>'测试用户'):false;}
|
||||
function get_user_meta($id,$key,$single){global $meta;return $meta[$key]??'';} function user_can($id,$cap){global $admin;return $admin;}
|
||||
function dayu_check_user_purchased_article($id,$post){global $purchase;return !empty($purchase[$post]);}
|
||||
function is_boosvip_status($id){global $member;return $member;}
|
||||
function is_wp_error($v){return $v instanceof WP_Error;}
|
||||
class DB {
|
||||
public $prefix='test_';
|
||||
function prepare($sql,...$args){if(count($args)===1&&is_array($args[0]))$args=$args[0];return array($sql,$args);}
|
||||
function get_var($q){global $bound;$sql=is_array($q)?$q[0]:$q;if(strpos($sql,'app_login_records')!==false)return $bound;if(strpos($sql,'COUNT(')!==false)return 1;return null;}
|
||||
function get_results($q,$mode=null){global $rows;return array_map(function($r){return (array)$r;},array_values(array_filter($rows,function($r){return $r->status==='published';})));}
|
||||
function get_col($q){return array('测试分类');} function esc_like($s){return addcslashes($s,'_%\\');}
|
||||
function get_row($q){global $rows;$id=$q[1][0];$row=$rows[$id]??null;return $row&&$row->status==='published'&&$row->material_type==='lut'?$row:null;}
|
||||
}
|
||||
$wpdb=new DB;
|
||||
require __DIR__.'/../wp-content/mu-plugins/dayu-color-online-luts.php';
|
||||
function check($pass,$name){global $checks;$checks[]=array('name'=>$name,'pass'=>(bool)$pass);if(!$pass){fwrite(STDERR,'FAIL '.$name."\n");exit(1);}}
|
||||
function denied($value,$status){return is_wp_error($value)&&($value->data['status']??0)===$status;}
|
||||
function body($value){return $value instanceof WP_REST_Response?$value->get_data():null;}
|
||||
check(!Dayu_Color_Online_LUTs::access(7),'ordinary account denied');
|
||||
foreach(array(14421,15792) as $post){$purchase=array($post=>true);check(Dayu_Color_Online_LUTs::access(7),'either individual purchase grants '.$post);}
|
||||
$purchase=array();$member=true;check(Dayu_Color_Online_LUTs::access(7),'active member allowed');$member=false;
|
||||
$meta=array('cao_user_type'=>'vip','cao_vip_end_time'=>'9999-09-09');check(Dayu_Color_Online_LUTs::access(7),'lifetime member allowed');
|
||||
$meta=array('cao_user_type'=>'vip','cao_vip_end_time'=>time()-1);check(!Dayu_Color_Online_LUTs::access(7),'expired member denied');
|
||||
$meta=array('cao_vip_type'=>'year','cao_vip_expire'=>time()+100);check(Dayu_Color_Online_LUTs::access(7),'legacy active membership supported');$meta=array();
|
||||
check(!Dayu_Color_Online_LUTs::access(8),'deleted user denied');
|
||||
$device='00000000-0000-0000-0000-000000000001';$key=str_repeat('a',40);$login='dayu_app_login_'.hash('sha256',$key);
|
||||
$session=array('app_name'=>'DayuColor','device_uuid'=>$device,'expires_at'=>time()+120,'status'=>'pending','user_id'=>7);
|
||||
$transients[$login]=$session;
|
||||
check(body(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))))['status']==='pending','pending login cannot mint a credential');
|
||||
$transients[$login]['app_name']='FCPXSoundEffects';check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'another product login rejected');
|
||||
$transients[$login]=$session;$transients[$login]['status']='approved';
|
||||
$issued=Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device)));$token=body($issued)['token']??'';
|
||||
check(strlen($token)===64,'approved product login exchanges a random token');check($issued->headers['Cache-Control']==='no-store, private','credential responses cannot be cached');
|
||||
check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'one-time login replay rejected');
|
||||
check(denied(Dayu_Color_Online_LUTs::catalog(new Request()),401),'anonymous catalogue rejected');
|
||||
check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1))),401),'anonymous file rejected');
|
||||
check(denied(Dayu_Color_Online_LUTs::preview(new Request(array('id'=>1))),401),'anonymous frame rejected before decoding');
|
||||
check(body(Dayu_Color_Online_LUTs::status(new Request(array(),$token)))['allowed']===false,'signed-in unpaid account has no online permission');
|
||||
check(denied(Dayu_Color_Online_LUTs::catalog(new Request(array(),$token)),403),'unpaid catalogue denied server-side');
|
||||
$purchase=array(15792=>true);
|
||||
check(body(Dayu_Color_Online_LUTs::status(new Request(array(),$token)))['allowed']===true,'new purchase is recognized without another login');
|
||||
$bound=8;check(denied(Dayu_Color_Online_LUTs::status(new Request(array(),$token)),401),'device rebind revokes previous session');$bound=7;
|
||||
$root=sys_get_temp_dir().'/dayu-color-lut-contract-'.bin2hex(random_bytes(8));mkdir($root);mkdir($root.'/materials');
|
||||
class Storage {public $root;function material_storage_root(){return $this->root;}}
|
||||
$storage=new Storage;$storage->root=$root;$GLOBALS['dayu_fcpx_sfx_api']=$storage;
|
||||
$cube="TITLE test\nLUT_3D_SIZE 2\n";for($z=0;$z<2;$z++)for($y=0;$y<2;$y++)for($x=0;$x<2;$x++)$cube.=(1-$x).' '.(1-$y).' '.(1-$z)."\n";
|
||||
$path=$root.'/materials/test.cube';file_put_contents($path,$cube);
|
||||
$rows[1]=(object)array('id'=>1,'title'=>'测试 LUT','category'=>'测试分类','file_size'=>strlen($cube),'checksum'=>hash('sha256',$cube),'material_type'=>'lut','status'=>'published','relative_path'=>'test.cube');
|
||||
$rows[2]=clone $rows[1];$rows[2]->id=2;$rows[2]->status='draft';
|
||||
check(count(body(Dayu_Color_Online_LUTs::catalog(new Request(array(),$token)))['items'])===1,'catalogue excludes private drafts');
|
||||
check(body(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1),$token))) instanceof Dayu_Color_LUT_Binary,'authorized published LUT streams original bytes');
|
||||
check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>2),$token)),404),'private LUT cannot be downloaded by guessed ID');
|
||||
$rows[1]->relative_path='../outside.cube';file_put_contents($root.'/outside.cube',$cube);
|
||||
check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1),$token)),503),'catalogue path traversal rejected');$rows[1]->relative_path='test.cube';
|
||||
$rows[1]->checksum=str_repeat('0',64);check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1),$token)),503),'server rejects modified LUT bytes');$rows[1]->checksum=hash('sha256',$cube);
|
||||
$image=imagecreatetruecolor(3,2);imagesetpixel($image,0,0,0x204060);imagesetpixel($image,1,0,0xabcdef);ob_start();imagepng($image);$png=ob_get_clean();unset($image);
|
||||
$render=Dayu_Color_LUT_Renderer::render($path,$png);check(is_string($render),'renderer returns a PNG');$out=imagecreatefromstring($render);
|
||||
check(imagesx($out)===3&&imagesy($out)===2,'renderer preserves source aspect and size');check((imagecolorat($out,0,0)&0xffffff)===0xdfbf9f,'known inverse LUT transforms pixel values correctly');unset($out);
|
||||
$preview=body(Dayu_Color_Online_LUTs::preview(new Request(array('id'=>1,'frame_png'=>base64_encode($png)),$token)));check($preview instanceof Dayu_Color_LUT_Binary&&$preview->bytes()===$render,'authorized frame route returns the actual LUT effect');
|
||||
check(is_wp_error(Dayu_Color_LUT_Renderer::render($path,'invalid')),'malformed image rejected');
|
||||
$large=imagecreatetruecolor(641,1);ob_start();imagepng($large);$too_large=ob_get_clean();unset($large);check(is_wp_error(Dayu_Color_LUT_Renderer::render($path,$too_large)),'over-limit image rejected');
|
||||
file_put_contents($path,"LUT_3D_SIZE 2\n0 0 0\n");check(is_wp_error(Dayu_Color_LUT_Renderer::render($path,$png)),'truncated LUT rejected');
|
||||
file_put_contents($path,"\xff\xfe".iconv('UTF-8','UTF-16LE',$cube));check(is_string(Dayu_Color_LUT_Renderer::render($path,$png)),'UTF-16 BOM LUT supported');
|
||||
$purchase=array();check(denied(Dayu_Color_Online_LUTs::preview(new Request(array('id'=>1,'frame_png'=>base64_encode($png)),$token)),403),'permission revoked before another frame is processed');
|
||||
check(body(Dayu_Color_Online_LUTs::logout(new Request(array(),$token)))['success']===true,'logout invalidates server credential');check(denied(Dayu_Color_Online_LUTs::status(new Request(array(),$token)),401),'logged-out token cannot be reused');
|
||||
unlink($path);unlink($root.'/outside.cube');rmdir($root.'/materials');rmdir($root);
|
||||
$report=array('pass'=>true,'count'=>count($checks),'scope'=>'Isolated PHP/GD contracts; synthetic users, purchases and frames; no production credentials or account data.','checks'=>$checks);
|
||||
echo json_encode($report,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)."\n";
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
/** Plugin Name: Dayu Color Online LUTs
|
||||
* Product-scoped sessions and access to the existing published LUT catalogue.
|
||||
*/
|
||||
if (!defined('ABSPATH')) { exit; }
|
||||
require_once __DIR__ . '/dayu-color-online-luts/renderer.php';
|
||||
|
||||
final class Dayu_Color_LUT_Binary {
|
||||
private $path;
|
||||
private $bytes;
|
||||
private $mime;
|
||||
public function __construct($path, $bytes, $mime) { $this->path=$path; $this->bytes=$bytes; $this->mime=$mime; }
|
||||
public function send() {
|
||||
header('Content-Type: ' . $this->mime);
|
||||
header('Cache-Control: no-store, private');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('Content-Length: ' . ($this->path ? filesize($this->path) : strlen($this->bytes)));
|
||||
if ($this->path) { readfile($this->path); } else { echo $this->bytes; }
|
||||
}
|
||||
public function bytes() { return $this->bytes; }
|
||||
}
|
||||
|
||||
final class Dayu_Color_Online_LUTs {
|
||||
const APP = 'DayuColor';
|
||||
const TTL = 2592000;
|
||||
public static function init() {
|
||||
add_action('rest_api_init', array(__CLASS__, 'routes'));
|
||||
add_filter('rest_pre_serve_request', array(__CLASS__, 'serve'), 10, 4);
|
||||
add_action('dayu_color_lut_consumed_cleanup', 'delete_option');
|
||||
}
|
||||
public static function routes() {
|
||||
foreach (array('session'=>'exchange', 'status'=>'status', 'logout'=>'logout', 'catalog'=>'catalog', '(?P<id>\d+)/download'=>'download', '(?P<id>\d+)/preview'=>'preview') as $path=>$handler) {
|
||||
register_rest_route('dayu-color/v1', '/lut/' . $path, array('methods'=>'POST', 'callback'=>array(__CLASS__, $handler), 'permission_callback'=>'__return_true'));
|
||||
}
|
||||
}
|
||||
public static function serve($served, $result, $request, $server) {
|
||||
if (strpos($request->get_route(), '/dayu-color/v1/lut/') !== 0) { return $served; }
|
||||
$data=$result->get_data();
|
||||
if ($data instanceof Dayu_Color_LUT_Binary) { $data->send(); return true; }
|
||||
return $served;
|
||||
}
|
||||
private static function response($data) {
|
||||
$response=new WP_REST_Response($data, 200);
|
||||
$response->header('Cache-Control', 'no-store, private');
|
||||
return $response;
|
||||
}
|
||||
private static function error($code, $message, $status) { return new WP_Error('dayu_color_lut_' . $code, $message, array('status'=>$status)); }
|
||||
private static function device($value) {
|
||||
$value=strtoupper(trim((string)$value));
|
||||
return preg_match('/^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/D', $value) ? $value : '';
|
||||
}
|
||||
private static function bound_user($device) {
|
||||
global $wpdb;
|
||||
return intval($wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->prefix}app_login_records WHERE device_uuid=%s AND is_active=1 ORDER BY last_active DESC, id DESC LIMIT 1", $device)));
|
||||
}
|
||||
public static function access($user_id) {
|
||||
if (!$user_id || !get_user_by('ID', $user_id)) { return false; }
|
||||
if (user_can($user_id, 'manage_options')) { return true; }
|
||||
if (class_exists('CaoUser')) { $user=new CaoUser($user_id); if (method_exists($user, 'vip_status') && $user->vip_status()) { return true; } }
|
||||
if (function_exists('is_boosvip_status') && is_boosvip_status($user_id)) { return true; }
|
||||
$type=get_user_meta($user_id, 'cao_user_type', true);
|
||||
$end=get_user_meta($user_id, 'cao_vip_end_time', true);
|
||||
$until=is_numeric($end) ? intval($end) : strtotime((string)$end);
|
||||
if ($type === 'vip' && ($end === '9999-09-09' || ($until && $until > time()))) { return true; }
|
||||
if (get_user_meta($user_id, 'cao_vip_type', true) && intval(get_user_meta($user_id, 'cao_vip_expire', true)) > time()) { return true; }
|
||||
global $wpdb;
|
||||
foreach (array(14421, 15792) as $post) {
|
||||
if (function_exists('dayu_check_user_purchased_article') && dayu_check_user_purchased_article($user_id, $post)) { return true; }
|
||||
if ($wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}cao_paylog WHERE user_id=%d AND post_id=%d AND status=1 LIMIT 1", $user_id, $post))) { return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public static function exchange($request) {
|
||||
$key=(string)$request->get_param('session_key'); $device=self::device($request->get_param('device_uuid'));
|
||||
if (!$device || !preg_match('/^[A-Za-z0-9_-]{32,80}$/D', $key)) { return self::error('login', '登录会话无效,请重新登录。', 400); }
|
||||
$transient='dayu_app_login_' . hash('sha256', $key); $session=get_transient($transient);
|
||||
if (!is_array($session) || intval($session['expires_at'] ?? 0) < time() || ($session['app_name'] ?? '') !== self::APP || !hash_equals((string)($session['device_uuid'] ?? ''), $device)) { return self::error('expired', '登录会话已过期,请重新登录。', 401); }
|
||||
if (($session['status'] ?? '') !== 'approved') { return self::response(array('status'=>sanitize_key($session['status'] ?? 'pending'), 'message'=>sanitize_text_field($session['message'] ?? '等待微信登录'))); }
|
||||
$user_id=intval($session['user_id'] ?? 0);
|
||||
if (!$user_id || self::bound_user($device) !== $user_id || !get_user_by('ID', $user_id)) { return self::error('binding', '账号绑定已变化,请重新登录。', 401); }
|
||||
// Atomic one-time exchange; add_option is unique in the shared DB, unlike get/set transient pairs.
|
||||
$once='dayu_color_lut_once_' . hash('sha256', $key);
|
||||
if (!add_option($once, time(), '', false)) { return self::error('used', '登录会话已使用,请重新登录。', 401); }
|
||||
delete_transient($transient);
|
||||
$token=bin2hex(random_bytes(32)); $expires=time()+self::TTL;
|
||||
set_transient('dayu_color_lut_' . hash('sha256', $token), array('user_id'=>$user_id, 'device'=>$device, 'expires'=>$expires), self::TTL);
|
||||
// Keep the marker past the original login lifetime, including concurrent poll requests.
|
||||
wp_schedule_single_event(time()+1200, 'dayu_color_lut_consumed_cleanup', array($once));
|
||||
return self::response(array('status'=>'approved', 'token'=>$token, 'expires_at'=>$expires, 'allowed'=>self::access($user_id), 'username'=>get_user_by('ID', $user_id)->display_name));
|
||||
}
|
||||
private static function authentication($request, $paid=true) {
|
||||
$header=trim((string)$request->get_header('authorization'));
|
||||
if (!preg_match('/^Bearer ([a-f0-9]{64})$/D', $header, $match)) { return self::error('login_required', '请先在大鱼调色主 APP 登录。', 401); }
|
||||
$key='dayu_color_lut_' . hash('sha256', $match[1]); $session=get_transient($key);
|
||||
if (!is_array($session) || intval($session['expires'] ?? 0)<time() || self::bound_user($session['device']) !== intval($session['user_id']) || !get_user_by('ID', intval($session['user_id']))) { return self::error('login_required', '登录已失效,请在主 APP 重新登录。', 401); }
|
||||
if ($paid && !self::access(intval($session['user_id']))) { return self::error('access_denied', '在线 LUT 需要有效会员,或已购买文章 14421 / 15792。', 403); }
|
||||
$session['key']=$key; return $session;
|
||||
}
|
||||
public static function status($request) {
|
||||
$session=self::authentication($request, false); if (is_wp_error($session)) { return $session; }
|
||||
return self::response(array('allowed'=>self::access($session['user_id']), 'username'=>get_user_by('ID', $session['user_id'])->display_name, 'expires_at'=>$session['expires'], 'renderer'=>function_exists('imagecreatefromstring')));
|
||||
}
|
||||
public static function logout($request) {
|
||||
$session=self::authentication($request, false); if (is_wp_error($session)) { return $session; }
|
||||
delete_transient($session['key']); return self::response(array('success'=>true));
|
||||
}
|
||||
public static function catalog($request) {
|
||||
$session=self::authentication($request); if (is_wp_error($session)) { return $session; }
|
||||
global $wpdb; $table=$wpdb->prefix . 'dayu_sfx_materials';
|
||||
$page=max(1, intval($request->get_param('page'))); $limit=60;
|
||||
$category=mb_substr(sanitize_text_field((string)$request->get_param('category')), 0, 191);
|
||||
$search=mb_substr(sanitize_text_field((string)$request->get_param('search')), 0, 100);
|
||||
$where="material_type='lut' AND status='published'"; $values=array();
|
||||
if ($category!=='') { $where.=' AND category=%s'; $values[]=$category; }
|
||||
if ($search!=='') { $where.=' AND (title LIKE %s OR category LIKE %s)'; $like='%'.$wpdb->esc_like($search).'%'; array_push($values, $like, $like); }
|
||||
$count="SELECT COUNT(*) FROM {$table} WHERE {$where}";
|
||||
$total=intval($wpdb->get_var($values ? $wpdb->prepare($count, $values) : $count));
|
||||
$rows=$wpdb->get_results($wpdb->prepare("SELECT id,title,category,file_size,checksum FROM {$table} WHERE {$where} ORDER BY title ASC,id ASC LIMIT %d OFFSET %d", array_merge($values, array($limit,($page-1)*$limit))), ARRAY_A);
|
||||
$categories=$wpdb->get_col("SELECT DISTINCT category FROM {$table} WHERE material_type='lut' AND status='published' AND category<>'' ORDER BY category ASC");
|
||||
foreach ((array)$rows as &$row) { $row['id']=intval($row['id']); $row['file_size']=intval($row['file_size']); } unset($row);
|
||||
return self::response(array('items'=>(array)$rows, 'categories'=>array_values((array)$categories), 'page'=>$page, 'total'=>$total, 'per_page'=>$limit));
|
||||
}
|
||||
private static function material($id) {
|
||||
global $wpdb;
|
||||
$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dayu_sfx_materials WHERE id=%d AND material_type='lut' AND status='published'", intval($id)));
|
||||
if (!$row) { return self::error('missing', '此 LUT 已下架或不存在。', 404); }
|
||||
$api=$GLOBALS['dayu_fcpx_sfx_api'] ?? null;
|
||||
if (!$api || !method_exists($api, 'material_storage_root')) { return self::error('storage', '素材服务暂不可用。', 503); }
|
||||
$root=realpath($api->material_storage_root().'/materials');
|
||||
$path=$root ? realpath($root.'/'.ltrim($row->relative_path, '/\\')) : false;
|
||||
if (!$root || !$path || strpos($path, $root.DIRECTORY_SEPARATOR)!==0 || strtolower(pathinfo($path,PATHINFO_EXTENSION))!=='cube' || !is_file($path) || !is_readable($path) || filesize($path)>67108864 || !hash_equals(strtolower($row->checksum), hash_file('sha256',$path))) { return self::error('file', 'LUT 文件未通过完整性检查。', 503); }
|
||||
return $path;
|
||||
}
|
||||
public static function download($request) {
|
||||
$session=self::authentication($request); if (is_wp_error($session)) { return $session; }
|
||||
$path=self::material($request['id']); if (is_wp_error($path)) { return $path; }
|
||||
return self::response(new Dayu_Color_LUT_Binary($path, null, 'application/octet-stream'));
|
||||
}
|
||||
public static function preview($request) {
|
||||
$session=self::authentication($request); if (is_wp_error($session)) { return $session; }
|
||||
if (strlen($request->get_body())>2100000) { return self::error('frame_size', '预览帧过大。', 413); }
|
||||
$rate='dayu_color_lut_rate_' . $session['user_id'].'_'.intval(time()/60);
|
||||
$count=intval(get_transient($rate)); if ($count>=120) { return self::error('rate', '预览请求较多,请稍后刷新。', 429); }
|
||||
set_transient($rate, $count+1, 120);
|
||||
$path=self::material($request['id']); if (is_wp_error($path)) { return $path; }
|
||||
$encoded=$request->get_param('frame_png');
|
||||
if (!is_string($encoded) || strlen($encoded)>2000000) { return self::error('frame', '预览帧无效。', 400); }
|
||||
$bytes=base64_decode($encoded, true);
|
||||
if (!is_string($bytes) || strlen($bytes)>1500000) { return self::error('frame', '预览帧无效。', 400); }
|
||||
$result=Dayu_Color_LUT_Renderer::render($path, $bytes);
|
||||
if (is_wp_error($result)) { return $result; }
|
||||
return self::response(new Dayu_Color_LUT_Binary(null, $result, 'image/png'));
|
||||
}
|
||||
}
|
||||
Dayu_Color_Online_LUTs::init();
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
if (!defined('ABSPATH')) { exit; }
|
||||
|
||||
/** Display-reference renderer. Uploaded PNGs and returned PNGs stay in request memory. */
|
||||
final class Dayu_Color_LUT_Renderer {
|
||||
private static function error($message) { return new WP_Error('dayu_color_lut_render', $message, array('status'=>422)); }
|
||||
public static function read_cube($path) {
|
||||
$text=file_get_contents($path);
|
||||
if (!is_string($text) || strlen($text)>67108864) { return self::error('无法读取 LUT。'); }
|
||||
foreach (array("\x00\x00\xfe\xff"=>'UTF-32BE', "\xff\xfe\x00\x00"=>'UTF-32LE', "\xfe\xff"=>'UTF-16BE', "\xff\xfe"=>'UTF-16LE') as $bom=>$encoding) {
|
||||
if (strncmp($text, $bom, strlen($bom))===0) { $text=iconv($encoding, 'UTF-8', substr($text,strlen($bom))); break; }
|
||||
}
|
||||
if (!is_string($text) || strpos($text,"\0")!==false) { return self::error('LUT 编码无效。'); }
|
||||
$text=preg_replace('/^\xEF\xBB\xBF/', '', $text);
|
||||
$n=0; $rows=0; $packed=''; $min=array(0,0,0); $max=array(1,1,1);
|
||||
$stream=fopen('php://memory', 'w+'); fwrite($stream,str_replace("\r","\n",$text)); rewind($stream); unset($text);
|
||||
while (($line=fgets($stream))!==false) {
|
||||
$line=trim(explode('#',$line,2)[0]); if ($line==='') { continue; }
|
||||
if (preg_match('/^LUT_3D_SIZE\s+(\d+)\s*$/D',$line,$m)) {
|
||||
if ($n || intval($m[1])<2 || intval($m[1])>128) { fclose($stream); return self::error('LUT 尺寸无效。'); }
|
||||
$n=intval($m[1]); continue;
|
||||
}
|
||||
if (preg_match('/^(DOMAIN_MIN|DOMAIN_MAX)\s+(.+)$/D',$line,$m)) {
|
||||
$parts=preg_split('/\s+/',trim($m[2]));
|
||||
if (count($parts)!==3 || count(array_filter($parts,'is_numeric'))!==3) { fclose($stream); return self::error('LUT DOMAIN 无效。'); }
|
||||
if ($m[1]==='DOMAIN_MIN') { $min=array_map('floatval',$parts); } else { $max=array_map('floatval',$parts); }
|
||||
continue;
|
||||
}
|
||||
if (preg_match('/^(TITLE|LUT_3D_INPUT_RANGE)(?:\s|$)/',$line)) { continue; }
|
||||
$parts=preg_split('/\s+/', $line);
|
||||
if (!$n || count($parts)!==3 || count(array_filter($parts,'is_numeric'))!==3 || $rows>=$n*$n*$n) { fclose($stream); return self::error('LUT 数据格式无效。'); }
|
||||
$rgb=array_map('floatval',$parts);
|
||||
foreach ($rgb as $v) { if (!is_finite($v)) { fclose($stream); return self::error('LUT 含无效数字。'); } }
|
||||
$packed.=pack('g3',$rgb[0],$rgb[1],$rgb[2]); $rows++;
|
||||
}
|
||||
fclose($stream);
|
||||
for ($c=0;$c<3;$c++) { if (!is_finite($min[$c]) || !is_finite($max[$c]) || $max[$c]<=$min[$c]) { return self::error('LUT DOMAIN 无效。'); } }
|
||||
if (!$n || $rows!==$n*$n*$n) { return self::error('LUT 数据不完整。'); }
|
||||
return array($n,$packed,$min,$max);
|
||||
}
|
||||
public static function sample($table, $rgb) {
|
||||
list($n,$packed,$min,$max)=$table; $index=array(); $fraction=array();
|
||||
for ($c=0;$c<3;$c++) {
|
||||
$s=max(0.,min(1.,($rgb[$c]-$min[$c])/($max[$c]-$min[$c])))*($n-1);
|
||||
$index[$c]=min($n-2,intval($s)); $fraction[$c]=$s-$index[$c];
|
||||
}
|
||||
$out=array(0.,0.,0.);
|
||||
for ($k=0;$k<8;$k++) {
|
||||
$x=$k&1; $y=($k>>1)&1; $z=($k>>2)&1;
|
||||
$offset=((($index[2]+$z)*$n+$index[1]+$y)*$n+$index[0]+$x)*12;
|
||||
$v=unpack('g3',$packed,$offset);
|
||||
$w=($x?$fraction[0]:1-$fraction[0])*($y?$fraction[1]:1-$fraction[1])*($z?$fraction[2]:1-$fraction[2]);
|
||||
for ($c=0;$c<3;$c++) { $out[$c]+=$v[$c+1]*$w; }
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
public static function render($path, $bytes) {
|
||||
if (!function_exists('imagecreatefromstring')) { return self::error('服务器图像处理暂不可用。'); }
|
||||
$size=@getimagesizefromstring($bytes);
|
||||
if (!$size || $size[2]!==IMAGETYPE_PNG || $size[0]<1 || $size[1]<1 || max($size[0],$size[1])>640 || $size[0]*$size[1]>230400) { return self::error('请发送最长边不超过 640 像素的 PNG 预览帧。'); }
|
||||
$table=self::read_cube($path); if (is_wp_error($table)) { return $table; }
|
||||
$input=@imagecreatefromstring($bytes); if (!$input) { return self::error('无法解码预览帧。'); }
|
||||
$output=imagecreatetruecolor($size[0],$size[1]); imagealphablending($output,false); imagesavealpha($output,true);
|
||||
// Memoize repeated display pixels within this request only. No frame cache on disk or in WP.
|
||||
$memo=array();
|
||||
for ($y=0;$y<$size[1];$y++) { for ($x=0;$x<$size[0];$x++) {
|
||||
$pixel=imagecolorat($input,$x,$y);
|
||||
if (isset($memo[$pixel])) { $color=$memo[$pixel]; } else {
|
||||
$rgba=imagecolorsforindex($input,$pixel);
|
||||
$v=self::sample($table,array($rgba['red']/255,$rgba['green']/255,$rgba['blue']/255));
|
||||
$color=($rgba['alpha']<<24)|(intval(round(max(0,min(1,$v[0]))*255))<<16)|(intval(round(max(0,min(1,$v[1]))*255))<<8)|intval(round(max(0,min(1,$v[2]))*255));
|
||||
if (count($memo)<65536) { $memo[$pixel]=$color; }
|
||||
}
|
||||
imagesetpixel($output,$x,$y,$color);
|
||||
} }
|
||||
ob_start(); imagepng($output,null,3); $png=ob_get_clean();
|
||||
unset($input, $output);
|
||||
return $png;
|
||||
}
|
||||
}
|
||||
@@ -17,3 +17,7 @@
|
||||
`LOCAL_PROJECT=/Users/mac/Downloads/dayumedia/dayu-color-beta`;`NAS_ROOT=/Volumes/dayumedia (存储空间1)/wwwroot/dayu_media`。仓库 `Backend/wp-content/mu-plugins/dayu-color-online-luts.php` 及 `Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php` 分别映射到上述两处根目录下同相对路径。只部署这两个文件,覆盖前按原目录旁路备份并核对基线。
|
||||
|
||||
当前状态:接入前基线 `5fae1150f4b7b6087f5da8298b5ac3ad8916e529`,正式 1.21.8(126)。工程文件已有 Security 引用排序改动保留;本轮采用自动同步的 Shared 源文件,不需改写该工程文件。实现、测试与交付结果持续补充到本记录和开发交接。
|
||||
|
||||
## 实现检查点
|
||||
|
||||
已完成专用会话与权限接口、在线目录及内存 PNG 渲染器;主 APP 微信登录/权限卡片、共享钥匙串客户端、浏览器在线分类/分页/帧预览/下载应用及去重导入已接入。首次 Release 配置编译通过,PHP 合约检查通过。尚未部署后端、尚未运行正式新版、尚未公证或发布;下一步补充原生浏览器与导入检查,检查线上接口后进行正式交付。
|
||||
@@ -0,0 +1,169 @@
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/tests/online_luts.php on line 73
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php on line 77
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php on line 77
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/tests/online_luts.php on line 75
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php on line 77
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php on line 77
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/tests/online_luts.php on line 78
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php on line 77
|
||||
|
||||
Deprecated: Function imagedestroy() is deprecated since 8.5, as it has no effect since PHP 8.0 in /Volumes/备份/大鱼调色/大鱼调色/Backend/wp-content/mu-plugins/dayu-color-online-luts/renderer.php on line 77
|
||||
{
|
||||
"pass": true,
|
||||
"count": 36,
|
||||
"scope": "Isolated PHP\/GD contracts; synthetic users, purchases and frames; no production credentials or account data.",
|
||||
"checks": [
|
||||
{
|
||||
"name": "ordinary account denied",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "either individual purchase grants 14421",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "either individual purchase grants 15792",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "active member allowed",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "lifetime member allowed",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "expired member denied",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "legacy active membership supported",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "deleted user denied",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "pending login cannot mint a credential",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "another product login rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "approved product login exchanges a random token",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "credential responses cannot be cached",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "one-time login replay rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "anonymous catalogue rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "anonymous file rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "anonymous frame rejected before decoding",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "signed-in unpaid account has no online permission",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "unpaid catalogue denied server-side",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "new purchase is recognized without another login",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "device rebind revokes previous session",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "catalogue excludes private drafts",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "authorized published LUT streams original bytes",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "private LUT cannot be downloaded by guessed ID",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "catalogue path traversal rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "server rejects modified LUT bytes",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "renderer returns a PNG",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "renderer preserves source aspect and size",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "known inverse LUT transforms pixel values correctly",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "authorized frame route returns the actual LUT effect",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "malformed image rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "over-limit image rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "truncated LUT rejected",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "UTF-16 BOM LUT supported",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "permission revoked before another frame is processed",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "logout invalidates server credential",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"name": "logged-out token cannot be reused",
|
||||
"pass": true
|
||||
}
|
||||
]
|
||||
}
|
||||
+179
-16
@@ -1,5 +1,6 @@
|
||||
#import "DYLUTBrowser.h"
|
||||
#import "DYLUTLibrary.h"
|
||||
#import "../Shared/DYOnlineLUT.h"
|
||||
#import <QuartzCore/QuartzCore.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -96,6 +97,7 @@ static NSRect DYBrowserTileImageRect(NSRect bounds,BOOL list) {
|
||||
@property BOOL doubleClicked;
|
||||
@property BOOL listLayout;
|
||||
@property BOOL shortcut;
|
||||
@property BOOL online;
|
||||
@end
|
||||
@implementation DYBrowserTile
|
||||
- (BOOL)isFlipped{return YES;}
|
||||
@@ -121,7 +123,7 @@ static NSRect DYBrowserTileImageRect(NSRect bounds,BOOL list) {
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
}else{
|
||||
[DYBrowserColor(_palette,@"background")setFill];NSRectFill(imageRect);
|
||||
NSString *message=_failure.length?@"无法预览":@"生成预览…";
|
||||
NSString *message=_failure.length?@"无法预览":_online?@"点“预览当前帧”":@"生成预览…";
|
||||
NSDictionary *attributes=@{NSFontAttributeName:[NSFont systemFontOfSize:11],NSForegroundColorAttributeName:DYBrowserColor(_palette,@"secondary")};
|
||||
NSSize size=[message sizeWithAttributes:attributes];
|
||||
[message drawAtPoint:NSMakePoint(NSMidX(imageRect)-size.width/2,NSMidY(imageRect)-size.height/2) withAttributes:attributes];
|
||||
@@ -243,6 +245,17 @@ static NSRect DYBrowserTileImageRect(NSRect bounds,BOOL list) {
|
||||
NSUInteger _libraryGeneration,_selectionGeneration,_previewGeneration;
|
||||
NSInteger _columns;
|
||||
CGFloat _tileWidth,_tileHeight,_sidebarWidth;
|
||||
NSPopUpButton *_sourceMenu;
|
||||
NSButton *_previousPage;
|
||||
NSTextField *_onlineNotice;
|
||||
BOOL _onlineMode;
|
||||
NSArray *_onlineEntries,*_onlineCategories;
|
||||
NSDictionary *_onlineFrame;
|
||||
NSData *_onlinePNG;
|
||||
NSString *_onlineSelectedPath,*_localFolder;
|
||||
NSUInteger _onlinePage,_onlineTotal,_onlineCatalogGeneration;
|
||||
NSProgress *_onlineCatalogTask;
|
||||
NSMutableSet *_onlineTransfers;
|
||||
}
|
||||
@end
|
||||
|
||||
@@ -269,6 +282,11 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
panel.title=@"风格 LUT";panel.contentMinSize=self.class.minimumContentSize;panel.contentMaxSize=self.class.maximumContentSize;panel.releasedWhenClosed=NO;panel.hidesOnDeactivate=NO;panel.delegate=self;
|
||||
_root=[[DYBrowserCanvas alloc]initWithFrame:NSMakeRect(0,0,760,560)];_root.accessibilityLabel=@"LUT 缩略图浏览库";panel.contentView=_root;
|
||||
_titleLabel=[BrowserLabel(@"LUT 文件夹",14)retain];_titleLabel.font=[NSFont systemFontOfSize:14 weight:NSFontWeightSemibold];
|
||||
_sourceMenu=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];[_sourceMenu addItemsWithTitles:@[@"本地 LUT",@"在线 LUT"]];_sourceMenu.target=self;_sourceMenu.action=@selector(sourceChanged:);_sourceMenu.accessibilityLabel=@"LUT 来源";
|
||||
_previousPage=[BrowserButton(@"上一页",self,@selector(previousOnlinePage:))retain];_previousPage.hidden=YES;
|
||||
_onlineNotice=[BrowserLabel(@"点“预览当前帧”将缩略图发送到 dayu.media,仅供本次处理,不保存帧。",11)retain];_onlineNotice.hidden=YES;
|
||||
_onlinePage=1;_onlineTransfers=[NSMutableSet new];
|
||||
[NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(onlineIdentityChanged:) name:DYOnlineLUTIdentityChanged object:nil];
|
||||
_countLabel=[BrowserLabel(@"0 个 LUT",11)retain];
|
||||
_statusLabel=[BrowserLabel(@"单击缩略图应用 LUT",11)retain];
|
||||
_sizeLabel=[BrowserLabel(@"缩略图大小",11)retain];
|
||||
@@ -312,7 +330,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gridScrolled:) name:NSViewBoundsDidChangeNotification object:_gridScroll.contentView];
|
||||
_splitView=[[NSSplitView alloc]initWithFrame:NSMakeRect(12,80,736,425)];_splitView.vertical=YES;_splitView.dividerStyle=NSSplitViewDividerStyleThin;_splitView.accessibilityLabel=@"调整 LUT 文件夹与预览宽度";
|
||||
_folderScroll.frame=NSMakeRect(0,0,162,425);_gridScroll.frame=NSMakeRect(163,0,573,425);[_splitView addSubview:_folderScroll];[_splitView addSubview:_gridScroll];
|
||||
for(NSView *view in @[_titleLabel,_countLabel,_statusLabel,_sizeLabel,_search,_importFiles,_importFolder,_reveal,_refresh,_none,_done,_hd,_sizeSlider,_layoutMenu,_splitView,_comparePanel])[_root addSubview:view];
|
||||
for(NSView *view in @[_titleLabel,_sourceMenu,_previousPage,_onlineNotice,_countLabel,_statusLabel,_sizeLabel,_search,_importFiles,_importFolder,_reveal,_refresh,_none,_done,_hd,_sizeSlider,_layoutMenu,_splitView,_comparePanel])[_root addSubview:view];
|
||||
[_gridDocument addSubview:_emptyLabel];
|
||||
_root.postsFrameChangedNotifications=YES;_root.postsBoundsChangedNotifications=YES;
|
||||
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(browserRootResized:) name:NSViewFrameDidChangeNotification object:_root];
|
||||
@@ -322,6 +340,10 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
return self;
|
||||
}
|
||||
- (void)dealloc{
|
||||
[NSDistributedNotificationCenter.defaultCenter removeObserver:self];
|
||||
[_onlineCatalogTask cancel];[_onlineCatalogTask release];for(NSProgress *task in _onlineTransfers)[task cancel];[_onlineTransfers release];
|
||||
[_onlineEntries release];[_onlineCategories release];[_onlineFrame release];[_onlinePNG release];[_onlineSelectedPath release];[_localFolder release];
|
||||
[_sourceMenu release];[_previousPage release];[_onlineNotice release];
|
||||
[_recentSnapshot release];
|
||||
[NSObject cancelPreviousPerformRequestsWithTarget:self];[[NSNotificationCenter defaultCenter]removeObserver:self];
|
||||
[_libraryTask cancel];[_libraryTask release];[_selectionTask cancel];[_selectionTask release];[_progressTimer invalidate];[_progressTimer release];
|
||||
@@ -372,7 +394,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
_root.accessibilityLabel=@"最近使用 LUT 快捷入口";
|
||||
_titleLabel.stringValue=@"最近使用";_titleLabel.font=[NSFont systemFontOfSize:11 weight:NSFontWeightSemibold];
|
||||
[_layoutMenu selectItemAtIndex:0];_sizeSlider.doubleValue=120;
|
||||
for(NSView *view in @[_search,_importFiles,_importFolder,_reveal,_refresh,_none,_done,_hd,_comparePanel,_sizeLabel,_sizeSlider,_layoutMenu,_splitView])view.hidden=YES;
|
||||
for(NSView *view in @[_sourceMenu,_previousPage,_onlineNotice,_search,_importFiles,_importFolder,_reveal,_refresh,_none,_done,_hd,_comparePanel,_sizeLabel,_sizeSlider,_layoutMenu,_splitView])view.hidden=YES;
|
||||
[_root addSubview:_gridScroll];_gridScroll.hasHorizontalScroller=NO;_gridScroll.scrollerStyle=NSScrollerStyleOverlay;
|
||||
[self showInRemoteParent:parent close:nil];[self rebuildGrid];[self refreshRecentSelection:_selectedPath];
|
||||
}
|
||||
@@ -451,6 +473,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
else [self finishClosing];
|
||||
}
|
||||
- (void)finishClosing{
|
||||
[self cancelOnlineWork];
|
||||
if(_closed)return;
|
||||
// The API owner's completion may release this controller synchronously.
|
||||
[self retain];
|
||||
@@ -489,6 +512,14 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
if(!small){_sizeLabel.frame=NSMakeRect(174,h-29,68,18);_sizeSlider.frame=NSMakeRect(246,h-31,100,20);_statusLabel.frame=NSMakeRect(444,h-29,MAX(0,w-540),18);}
|
||||
}
|
||||
NSRect browser=_splitView.frame,comparison=browser;
|
||||
_sourceMenu.hidden=NO;_titleLabel.hidden=YES;_sourceMenu.frame=NSMakeRect(12,_embedded?6:10,145,26);
|
||||
_countLabel.frame=NSMakeRect(165,_embedded?10:14,MAX(60,w-350),18);
|
||||
_onlineNotice.hidden=!_onlineMode;_previousPage.hidden=!_onlineMode;
|
||||
if(_onlineMode){
|
||||
_previousPage.frame=NSMakeRect(w-174,_embedded?5:9,76,27);_reveal.hidden=NO;_reveal.frame=NSMakeRect(w-94,_embedded?5:9,80,27);
|
||||
_onlineNotice.frame=NSMakeRect(12,NSMinY(browser)+2,MAX(1,w-24),20);
|
||||
browser.origin.y+=26;browser.size.height=MAX(1,browser.size.height-26);comparison=browser;
|
||||
}
|
||||
if(w>=620){
|
||||
CGFloat width=MIN(560,w*.42);
|
||||
browser.size.width=MAX(1,NSWidth(browser)-width-10);
|
||||
@@ -533,6 +564,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
}
|
||||
- (void)layoutChanged:(id)sender{[NSUserDefaults.standardUserDefaults setInteger:_layoutMenu.indexOfSelectedItem forKey:DYBrowserPreference(DYBrowserLayoutPreference,_library)];[self layoutBrowser];}
|
||||
- (void)resetThumbnailWork {
|
||||
for(NSProgress *task in _onlineTransfers)[task cancel];[_onlineTransfers removeAllObjects];
|
||||
_work.cancelled=YES;_work.owner=nil;[_work release];_work=[DYBrowserWork new];_work.owner=self;[_queuedPaths removeAllObjects];
|
||||
}
|
||||
- (void)updateVisibleTiles {
|
||||
@@ -543,7 +575,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
NSMutableSet *wanted=[NSMutableSet set];BOOL changed=NO;
|
||||
for(NSUInteger i=first;i<end;i++){
|
||||
NSDictionary *entry=_visibleEntries[i];NSString *path=entry[@"path"];[wanted addObject:path];DYBrowserTile *tile=_tiles[path];
|
||||
if(!tile){tile=[[[DYBrowserTile alloc]initWithFrame:NSZeroRect]autorelease];tile.identifier=path;tile.displayName=entry[@"name"];tile.toolTip=entry[@"relativePath"]?:path;tile.palette=_palette;tile.chosen=[path isEqualToString:_selectedPath];tile.target=self;tile.action=@selector(thumbnailClicked:);tile.enabled=YES;[_gridDocument addSubview:tile];_tiles[path]=tile;changed=YES;}
|
||||
if(!tile){tile=[[[DYBrowserTile alloc]initWithFrame:NSZeroRect]autorelease];tile.identifier=path;tile.displayName=entry[@"name"];tile.toolTip=entry[@"relativePath"]?:path;tile.palette=_palette;tile.chosen=[path isEqualToString:_onlineMode?_onlineSelectedPath:_selectedPath];tile.online=_onlineMode;tile.target=self;tile.action=@selector(thumbnailClicked:);tile.enabled=YES;[_gridDocument addSubview:tile];_tiles[path]=tile;changed=YES;}
|
||||
tile.shortcut=_compactRecent;tile.listLayout=_layoutMenu.indexOfSelectedItem==1;tile.frame=NSMakeRect(7+(i%_columns)*(_tileWidth+10),8+(i/_columns)*step,_tileWidth,_tileHeight);
|
||||
}
|
||||
for(NSString *path in _tiles.allKeys)if(![wanted containsObject:path]){[_tiles[path]removeFromSuperview];[_tiles removeObjectForKey:path];changed=YES;}
|
||||
@@ -572,8 +604,9 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
return frames[@"high"]&&(high||!frames[@"standard"])?@"high":@"standard";
|
||||
}
|
||||
- (NSSize)previewSize {
|
||||
NSString *quality=[self previewQualityForFrames:_previewFrames];
|
||||
NSValue *size=_previewFrames[[quality stringByAppendingString:@"Size"]];
|
||||
NSDictionary *frames=_onlineMode&&_onlineFrame?_onlineFrame:_previewFrames;
|
||||
NSString *quality=[self previewQualityForFrames:frames];
|
||||
NSValue *size=frames[[quality stringByAppendingString:@"Size"]];
|
||||
return size?size.sizeValue:NSMakeSize(320,180);
|
||||
}
|
||||
- (void)invalidatePreviewImages {
|
||||
@@ -584,6 +617,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
}
|
||||
- (void)updatePreview:(NSDictionary *)frames{
|
||||
if(_closed||_previewFrames==frames||(!frames[@"standard"]&&!frames[@"high"]))return;
|
||||
if(_onlineMode){NSDictionary *snapshot=[frames copy];[_previewFrames release];_previewFrames=snapshot;return;}
|
||||
NSString *currentQuality=[self previewQualityForFrames:_previewFrames],*nextQuality=[self previewQualityForFrames:frames];
|
||||
NSValue *currentSize=_previewFrames[[currentQuality stringByAppendingString:@"Size"]];
|
||||
NSValue *nextSize=frames[[nextQuality stringByAppendingString:@"Size"]];
|
||||
@@ -603,6 +637,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
- (void)qualityChanged:(id)sender{
|
||||
[NSUserDefaults.standardUserDefaults setBool:_hd.state==NSControlStateValueOn forKey:DYBrowserPreference(DYBrowserHDPreference,_library)];
|
||||
[self invalidatePreviewImages];
|
||||
if(_onlineMode){[_onlinePNG release];_onlinePNG=nil;[_onlineFrame release];_onlineFrame=nil;[self setStatus:@"画质已切换,请重新点击预览当前帧。"];}
|
||||
[self layoutBrowser];
|
||||
}
|
||||
- (void)comparePositionChanged:(id)sender{_compareView.position=_compareSlider.doubleValue;}
|
||||
@@ -617,14 +652,16 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
- (void)displayPreviewResult:(NSDictionary *)result inTile:(DYBrowserTile *)tile{
|
||||
tile.previewGeneration=_previewGeneration;
|
||||
tile.thumbnail=result[@"image"];tile.failure=result[@"error"];
|
||||
tile.enabled=tile.thumbnail!=nil;
|
||||
tile.toolTip=tile.failure?:tile.identifier;
|
||||
tile.enabled=_onlineMode||tile.thumbnail!=nil;
|
||||
tile.toolTip=tile.failure?:(_onlineMode?tile.displayName:tile.identifier);
|
||||
[tile setNeedsDisplay:YES];
|
||||
}
|
||||
- (void)requestPreviewForPath:(NSString *)path comparison:(BOOL)comparison{
|
||||
if(_onlineMode&&[path hasPrefix:@"online:"]){[self requestOnlinePreview:path];return;}
|
||||
if(!_work||[_queuedPaths containsObject:path])return;
|
||||
[_queuedPaths addObject:path];
|
||||
NSData *frame=_previewFrames[[self previewQualityForFrames:_previewFrames]];
|
||||
NSDictionary *frames=_onlineMode&&_onlineFrame?_onlineFrame:_previewFrames;
|
||||
NSData *frame=frames[[self previewQualityForFrames:frames]];
|
||||
NSSize size=[self previewSize];
|
||||
DYBrowserWork *work=_work;
|
||||
dispatch_async(comparison?_compareQueue:_previewQueue,^{@autoreleasepool{
|
||||
@@ -646,7 +683,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
}
|
||||
- (void)refreshComparison{
|
||||
if(_closed||_compactRecent||!self.visible||!_previewFrames.count)return;
|
||||
NSString *path=_selectedPath;
|
||||
NSString *path=_onlineMode?_onlineSelectedPath:_selectedPath;
|
||||
NSDictionary *original=_comparisonOriginal,*styled=path.length?[self previewResultForPath:path]:nil;
|
||||
if(!original)[self requestPreviewForPath:@"" comparison:YES];
|
||||
if(path.length&&!styled)[self requestPreviewForPath:path comparison:YES];
|
||||
@@ -660,6 +697,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
}
|
||||
- (void)setStatus:(NSString *)status{_statusLabel.stringValue=status?:@"";_statusLabel.toolTip=status;}
|
||||
- (void)rebuildFolders{
|
||||
if(_onlineMode){NSMutableArray *paths=[NSMutableArray arrayWithObject:@"*"];[paths addObjectsFromArray:_onlineCategories?:@[]];if(![paths containsObject:_folder]){[_folder release];_folder=[@"*" copy];}[_folderPaths release];_folderPaths=[paths copy];[self updateVisibleFolders];return;}
|
||||
NSMutableArray *paths=[NSMutableArray arrayWithObjects:DYBrowserRecentFolder,@"*",nil];NSMutableSet *seen=[NSMutableSet setWithArray:paths];
|
||||
for(NSString *folder in _library.folders){NSString *top=folder.length?[folder componentsSeparatedByString:@"/"].firstObject:@"";if(![seen containsObject:top]){[paths addObject:top];[seen addObject:top];}}
|
||||
if(![seen containsObject:_folder]){[_folder release];_folder=[@"*" copy];}
|
||||
@@ -693,6 +731,7 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
_importFiles.enabled=YES;_importFolder.enabled=YES;_refresh.title=@"刷新";_done.title=_embedded?@"返回调整":@"完成";_done.toolTip=nil;
|
||||
}
|
||||
- (void)reloadLibrary:(id)sender{
|
||||
if(_onlineMode){[self loadOnlineCatalog];return;}
|
||||
if(_libraryTask){[_libraryTask cancel];[self setStatus:@"正在取消…"];return;}
|
||||
[self invalidatePreviewImages];NSUInteger generation=++_libraryGeneration;
|
||||
NSProgress *task=[_library reloadAsync:^(NSError *error){
|
||||
@@ -702,12 +741,13 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
}
|
||||
- (void)folderClicked:(NSButton *)sender{
|
||||
[_folder release];_folder=[sender.identifier copy];
|
||||
if(_onlineMode){_onlinePage=1;[self loadOnlineCatalog];return;}
|
||||
[[NSUserDefaults standardUserDefaults]setObject:_folder forKey:DYBrowserPreference(DYBrowserFolderPreference,_library)];
|
||||
for(DYBrowserFolderButton *button in _folderButtons){button.chosen=[button.identifier isEqualToString:_folder];[button setNeedsDisplay:YES];}
|
||||
[self rebuildGrid];
|
||||
}
|
||||
- (void)searchChanged:(id)sender{[self rebuildGrid];}
|
||||
- (void)controlTextDidChange:(NSNotification *)notification{if(notification.object==_search)[self rebuildGrid];}
|
||||
- (void)searchChanged:(id)sender{if(_onlineMode){[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(debouncedOnlineSearch) object:nil];[self performSelector:@selector(debouncedOnlineSearch) withObject:nil afterDelay:.35];}else [self rebuildGrid];}
|
||||
- (void)controlTextDidChange:(NSNotification *)notification{if(notification.object==_search)[self searchChanged:_search];}
|
||||
- (void)sizeChanged:(id)sender{
|
||||
[[NSUserDefaults standardUserDefaults]setDouble:_sizeSlider.doubleValue forKey:DYBrowserPreference(DYBrowserSizePreference,_library)];
|
||||
[self layoutBrowser];
|
||||
@@ -729,18 +769,20 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
for(NSView *tile in _tiles.allValues)[tile removeFromSuperview];[_tiles removeAllObjects];
|
||||
NSString *query=[_search.stringValue stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];NSMutableArray *entries=[NSMutableArray array];
|
||||
BOOL recent=[_folder isEqual:DYBrowserRecentFolder];NSArray *history=_recentSnapshot;
|
||||
for(NSDictionary *entry in (recent?[_library recentEntriesForPaths:history]:_library.entries)){
|
||||
for(NSDictionary *entry in (_onlineMode?(_onlineEntries?:@[]):recent?[_library recentEntriesForPaths:history]:_library.entries)){
|
||||
NSString *folder=entry[@"relativeFolder"]?:@"";
|
||||
BOOL folderMatch=recent||[_folder isEqualToString:@"*"]||[folder isEqualToString:_folder]||(_folder.length&&[folder hasPrefix:[_folder stringByAppendingString:@"/"]]);
|
||||
if(folderMatch&&(!query.length||[entry[@"name"]localizedCaseInsensitiveContainsString:query]||[entry[@"relativePath"]localizedCaseInsensitiveContainsString:query]))[entries addObject:entry];
|
||||
}
|
||||
if(!recent)[entries sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){NSUInteger i=[history indexOfObject:a[@"path"]],j=[history indexOfObject:b[@"path"]];if(i==j)return [a[@"relativePath"]localizedStandardCompare:b[@"relativePath"]];return i<j?NSOrderedAscending:NSOrderedDescending;}];
|
||||
if(!recent&&!_onlineMode)[entries sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){NSUInteger i=[history indexOfObject:a[@"path"]],j=[history indexOfObject:b[@"path"]];if(i==j)return [a[@"relativePath"]localizedStandardCompare:b[@"relativePath"]];return i<j?NSOrderedAscending:NSOrderedDescending;}];
|
||||
_emptyLabel.stringValue=recent?@"尚未使用 LUT。应用后,下次打开会显示最近使用记录。":@"此文件夹还没有 LUT。\n点“导入文件”或“导入文件夹”添加 .cube 文件。";
|
||||
[_visibleEntries release];_visibleEntries=[entries copy];_countLabel.stringValue=[NSString stringWithFormat:@"%lu 个 LUT",(unsigned long)entries.count];_emptyLabel.hidden=entries.count>0;
|
||||
if(_onlineMode){_countLabel.stringValue=[NSString stringWithFormat:@"%lu 个 · %lu/%lu 页",(unsigned long)_onlineTotal,(unsigned long)_onlinePage,(unsigned long)MAX(1,(_onlineTotal+59)/60)];_emptyLabel.stringValue=@"在线 LUT 暂未加载。\n请在主 APP 登录并刷新,或选择其他分类。";}
|
||||
[_gridScroll.contentView scrollToPoint:NSZeroPoint];[self layoutBrowser];[_gridScroll reflectScrolledClipView:_gridScroll.contentView];
|
||||
NSAccessibilityPostNotification(_gridDocument,NSAccessibilityLayoutChangedNotification);
|
||||
}
|
||||
- (void)thumbnailClicked:(DYBrowserTile *)sender{
|
||||
if(_onlineMode){[self applyOnlineTile:sender];return;}
|
||||
if(!sender.enabled||sender.failure.length)return;
|
||||
[_selectionTask cancel];[_selectionTask release];NSUInteger generation=++_selectionGeneration;
|
||||
NSString *path=sender.identifier,*name=sender.displayName;BOOL closeAfter=sender.doubleClicked&&!_compactRecent;[self setStatus:[@"正在载入 " stringByAppendingString:name]];
|
||||
@@ -786,11 +828,132 @@ static NSButton *BrowserButton(NSString *title,id target,SEL action){NSButton *b
|
||||
_importing=YES;NSModalResponse response=[panel runModal];_importing=NO;
|
||||
if(response==NSModalResponseOK&&!_closed)[self importSelectedURLs:panel.URLs];
|
||||
}
|
||||
- (void)importFiles:(id)sender{[self importPanelForFolders:NO];}
|
||||
- (void)importFolder:(id)sender{[self importPanelForFolders:YES];}
|
||||
- (void)importFiles:(id)sender{if(_onlineMode)[self captureOnlineFrame];else [self importPanelForFolders:NO];}
|
||||
- (void)importFolder:(id)sender{if(_onlineMode)[DYOnlineLUTClient openAccount];else [self importPanelForFolders:YES];}
|
||||
- (void)revealLibrary:(id)sender{
|
||||
if(_onlineMode){if(_onlinePage*60<_onlineTotal){_onlinePage++;[self loadOnlineCatalog];}return;}
|
||||
NSError *error=nil;
|
||||
if(![[NSFileManager defaultManager]createDirectoryAtURL:_library.rootURL withIntermediateDirectories:YES attributes:nil error:&error]){[self showImportError:error];return;}
|
||||
if(![[NSWorkspace sharedWorkspace]openURL:_library.rootURL])[self setStatus:@"无法打开 LUT 文件夹"];
|
||||
}
|
||||
- (void)sourceChanged:(id)sender {
|
||||
BOOL online=_sourceMenu.indexOfSelectedItem==1;if(online==_onlineMode||_compactRecent)return;
|
||||
[self cancelOnlineWork];
|
||||
++_selectionGeneration;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil;
|
||||
if(online){[_localFolder release];_localFolder=[_folder copy];[_folder release];_folder=[@"*" copy];_onlinePage=1;}
|
||||
else {[_folder release];_folder=[(_localFolder?:@"*")copy];}
|
||||
_onlineMode=online;_importFiles.title=online?@"预览当前帧":@"导入文件…";_importFolder.title=online?@"登录 / 权限":@"导入文件夹…";_reveal.title=online?@"下一页":@"打开 LUT 文件夹";
|
||||
_search.stringValue=@"";[self invalidatePreviewImages];[self rebuildFolders];[self rebuildGrid];
|
||||
if(online)[self loadOnlineCatalog];else [self setStatus:@"单击缩略图应用 LUT"];
|
||||
}
|
||||
- (void)cancelOnlineWork {
|
||||
++_onlineCatalogGeneration;[_onlineCatalogTask cancel];[_onlineCatalogTask release];_onlineCatalogTask=nil;
|
||||
for(NSProgress *task in _onlineTransfers)[task cancel];[_onlineTransfers removeAllObjects];
|
||||
[_onlinePNG release];_onlinePNG=nil;[_onlineFrame release];_onlineFrame=nil;
|
||||
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(debouncedOnlineSearch) object:nil];
|
||||
}
|
||||
- (void)onlineIdentityChanged:(NSNotification *)notification {
|
||||
dispatch_async(dispatch_get_main_queue(),^{
|
||||
if(self->_closed)return;[self cancelOnlineWork];
|
||||
[self->_onlineEntries release];self->_onlineEntries=nil;[self->_onlineCategories release];self->_onlineCategories=nil;
|
||||
[self->_onlineSelectedPath release];self->_onlineSelectedPath=nil;
|
||||
[self invalidatePreviewImages];
|
||||
if(self->_onlineMode){[self rebuildFolders];[self rebuildGrid];[self loadOnlineCatalog];}
|
||||
});
|
||||
}
|
||||
- (void)previousOnlinePage:(id)sender {if(_onlineMode&&_onlinePage>1){_onlinePage--;[self loadOnlineCatalog];}}
|
||||
- (void)debouncedOnlineSearch {if(_onlineMode&&!_closed){_onlinePage=1;[self loadOnlineCatalog];}}
|
||||
- (void)loadOnlineCatalog {
|
||||
if(!_onlineMode||_closed)return;
|
||||
NSUInteger generation=++_onlineCatalogGeneration;[_onlineCatalogTask cancel];[_onlineCatalogTask release];_onlineCatalogTask=nil;
|
||||
[self setStatus:@"正在加载在线 LUT…"];_previousPage.enabled=NO;_reveal.enabled=NO;
|
||||
NSDictionary *body=@{@"page":@(_onlinePage),@"category":[_folder isEqual:@"*"]?@"":_folder,@"search":_search.stringValue?:@""};
|
||||
NSProgress *task=[DYOnlineLUTClient request:@"/dayu-color/v1/lut/catalog" body:body authenticated:YES completion:^(NSData *data,NSError *error){
|
||||
if(self->_closed||!self->_onlineMode||generation!=self->_onlineCatalogGeneration)return;
|
||||
[self->_onlineCatalogTask release];self->_onlineCatalogTask=nil;
|
||||
NSDictionary *value=[DYOnlineLUTClient JSON:data error:&error];
|
||||
if(error||![value[@"items"]isKindOfClass:NSArray.class]||![value[@"categories"]isKindOfClass:NSArray.class]){
|
||||
[self->_onlineEntries release];self->_onlineEntries=nil;[self rebuildGrid];[self setStatus:error.localizedDescription?:@"在线目录格式无效。"];self->_emptyLabel.stringValue=error.localizedDescription?:@"请刷新在线目录。";return;
|
||||
}
|
||||
NSMutableArray *entries=[NSMutableArray array],*categories=[NSMutableArray array];
|
||||
for(id category in value[@"categories"])if([category isKindOfClass:NSString.class]&&[category length]<=191)[categories addObject:category];
|
||||
for(id item in value[@"items"]){
|
||||
if(![item isKindOfClass:NSDictionary.class]||![item[@"id"]isKindOfClass:NSNumber.class]||[item[@"id"]longLongValue]<=0||![item[@"title"]isKindOfClass:NSString.class]||![item[@"category"]isKindOfClass:NSString.class]||![item[@"checksum"]isKindOfClass:NSString.class]||[item[@"checksum"]length]!=64||![item[@"file_size"]isKindOfClass:NSNumber.class]||[item[@"file_size"]longLongValue]<=0||[item[@"file_size"]longLongValue]>64*1024*1024)continue;
|
||||
NSMutableDictionary *entry=[NSMutableDictionary dictionaryWithDictionary:item];entry[@"path"]=[@"online:" stringByAppendingString:[item[@"id"]stringValue]];entry[@"name"]=item[@"title"];entry[@"relativeFolder"]=item[@"category"];entry[@"relativePath"]=[item[@"category"]stringByAppendingPathComponent:item[@"title"]];[entries addObject:entry];
|
||||
}
|
||||
[self->_onlineEntries release];self->_onlineEntries=[entries copy];[self->_onlineCategories release];self->_onlineCategories=[categories copy];
|
||||
self->_onlineTotal=[value[@"total"]isKindOfClass:NSNumber.class]?MAX(0,[value[@"total"]integerValue]):entries.count;
|
||||
self->_previousPage.enabled=self->_onlinePage>1;self->_reveal.enabled=self->_onlinePage*60<self->_onlineTotal;
|
||||
[self rebuildFolders];[self rebuildGrid];[self setStatus:@"点选下载并应用;预览当前帧可在线生成效果图。"];
|
||||
}];
|
||||
_onlineCatalogTask=[task retain];
|
||||
}
|
||||
- (NSDictionary *)onlineEntryForPath:(NSString *)path {
|
||||
for(NSDictionary *entry in _onlineEntries)if([entry[@"path"]isEqual:path])return entry;return nil;
|
||||
}
|
||||
- (void)captureOnlineFrame {
|
||||
if(!_onlineMode||_closed)return;
|
||||
NSString *quality=[self previewQualityForFrames:_previewFrames];NSData *pixels=_previewFrames[quality];NSValue *value=_previewFrames[[quality stringByAppendingString:@"Size"]];
|
||||
NSSize size=value?value.sizeValue:NSZeroSize;
|
||||
if(!pixels.length||size.width<1||size.height<1||pixels.length!=(NSUInteger)(size.width*size.height)*16){[self setStatus:@"暂无时间线帧,请先移动播放头或播放片段再重试。"];return;}
|
||||
[self invalidatePreviewImages];[_onlinePNG release];_onlinePNG=nil;[_onlineFrame release];_onlineFrame=[_previewFrames copy];
|
||||
DYBrowserWork *work=_work;[self setStatus:@"正在准备当前帧缩略图…"];
|
||||
dispatch_async(_previewQueue,^{@autoreleasepool{
|
||||
if(work.cancelled)return;NSError *error=nil;CGFloat scale=MIN(1.,sqrt(230400./(size.width*size.height)));
|
||||
NSSize output=NSMakeSize(MAX(1,floor(size.width*scale)),MAX(1,floor(size.height*scale)));
|
||||
NSImage *image=DYLUTThumbnail(nil,pixels,size.width,size.height,output,&error);
|
||||
NSBitmapImageRep *bitmap=(NSBitmapImageRep *)image.representations.firstObject;
|
||||
NSData *png=[bitmap isKindOfClass:NSBitmapImageRep.class]?[bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}]:nil;
|
||||
dispatch_async(dispatch_get_main_queue(),^{DYLUTBrowser *owner=work.owner;if(!owner||work.cancelled)return;
|
||||
if(!png||png.length>1500000){[owner setStatus:error.localizedDescription?:@"当前帧缩略图无法用于在线预览。"];return;}
|
||||
owner->_onlinePNG=[png copy];[owner setStatus:@"正在上传缩略图并生成在线效果预览…"];[owner generateVisibleThumbnails];[owner refreshComparison];
|
||||
});
|
||||
}});
|
||||
}
|
||||
- (void)requestOnlinePreview:(NSString *)path {
|
||||
if(!_onlinePNG||!_work||[_queuedPaths containsObject:path]||_onlineTransfers.count>=2)return;
|
||||
NSDictionary *entry=[self onlineEntryForPath:path];if(!entry)return;
|
||||
[_queuedPaths addObject:path];DYBrowserWork *work=_work;
|
||||
__block NSProgress *task=nil;
|
||||
task=[DYOnlineLUTClient request:[NSString stringWithFormat:@"/dayu-color/v1/lut/%@/preview",entry[@"id"]] body:@{@"frame_png":[_onlinePNG base64EncodedStringWithOptions:0]} authenticated:YES completion:^(NSData *data,NSError *error){
|
||||
DYLUTBrowser *owner=work.owner;if(!owner||work.cancelled)return;
|
||||
if(task)[owner->_onlineTransfers removeObject:task];[owner->_queuedPaths removeObject:path];
|
||||
NSImage *image=nil;
|
||||
if(!error&&data.length>24&&!memcmp(data.bytes,"\x89PNG\r\n\x1a\n",8)){
|
||||
uint32_t width=0,height=0;memcpy(&width,(const uint8_t *)data.bytes+16,4);memcpy(&height,(const uint8_t *)data.bytes+20,4);width=CFSwapInt32BigToHost(width);height=CFSwapInt32BigToHost(height);
|
||||
if(width&&height&&width<=640&&height<=640&&(uint64_t)width*height<=230400)image=[[[NSImage alloc]initWithData:data]autorelease];
|
||||
}
|
||||
NSDictionary *result=image?@{@"image":image}:@{@"error":error.localizedDescription?:@"服务器未返回有效的预览图。"};
|
||||
[owner->_thumbnailCache setObject:result forKey:path cost:image?data.length:128];
|
||||
DYBrowserTile *tile=owner->_tiles[path];if(tile)[owner displayPreviewResult:result inTile:tile];
|
||||
[owner refreshComparison];[owner generateVisibleThumbnails];
|
||||
if(error)[owner setStatus:error.localizedDescription];else [owner setStatus:@"在线预览已更新;点击 LUT 下载并应用。"];
|
||||
}];
|
||||
if(task)[_onlineTransfers addObject:task];
|
||||
}
|
||||
- (void)applyOnlineTile:(DYBrowserTile *)tile {
|
||||
NSDictionary *entry=[self onlineEntryForPath:tile.identifier];if(!entry||_closed)return;
|
||||
[_selectionTask cancel];[_selectionTask release];_selectionTask=nil;NSUInteger generation=++_selectionGeneration;
|
||||
NSString *onlinePath=entry[@"path"],*name=entry[@"name"];BOOL closeAfter=tile.doubleClicked;
|
||||
[self setStatus:[@"正在下载 " stringByAppendingString:name]];
|
||||
NSProgress *download=[DYOnlineLUTClient request:[NSString stringWithFormat:@"/dayu-color/v1/lut/%@/download",entry[@"id"]] body:@{} authenticated:YES completion:^(NSData *data,NSError *error){
|
||||
if(self->_closed||generation!=self->_selectionGeneration)return;[self->_selectionTask release];self->_selectionTask=nil;
|
||||
if(error||data.length!=[entry[@"file_size"]unsignedLongLongValue]){[self setStatus:error.localizedDescription?:@"下载大小与在线清单不一致,请刷新后重试。"];return;}
|
||||
[self setStatus:@"正在校验并保存在线 LUT…"];
|
||||
self->_selectionTask=[[self->_library importOnlineData:data identifier:entry[@"id"] name:name category:entry[@"category"] checksum:entry[@"checksum"] completion:^(NSString *path,NSError *failure){
|
||||
if(self->_closed||generation!=self->_selectionGeneration)return;[self->_selectionTask release];self->_selectionTask=nil;
|
||||
if(failure||!path){[self setStatus:failure.localizedDescription?:@"LUT 保存失败。"];return;}
|
||||
void (^applied)(NSError *)=^(NSError *applyError){
|
||||
if(self->_closed||generation!=self->_selectionGeneration)return;[self->_selectionTask release];self->_selectionTask=nil;
|
||||
if(applyError){[self setStatus:applyError.localizedDescription];return;}
|
||||
[self->_selectedPath release];self->_selectedPath=[path copy];[self->_library recordUsedPath:path];
|
||||
[self->_onlineSelectedPath release];self->_onlineSelectedPath=[onlinePath copy];
|
||||
[self->_selectionFrameTime release];self->_selectionFrameTime=[self->_previewFrames[@"time"]retain];
|
||||
for(DYBrowserTile *button in self->_tiles.allValues){button.chosen=[button.identifier isEqual:onlinePath];[button setNeedsDisplay:YES];}
|
||||
[self refreshComparison];[self setStatus:[@"已下载并应用 " stringByAppendingString:name]];if(closeAfter)[self close];
|
||||
};
|
||||
self->_selectionTask=[(self->_selection?self->_selection(path,applied):DYLUTPrepareAsync(path,applied))retain];
|
||||
}]retain];
|
||||
}];_selectionTask=[download retain];
|
||||
}
|
||||
@end
|
||||
@@ -42,6 +42,7 @@ FOUNDATION_EXPORT NSImage * _Nullable DYLUTThumbnail(NSString * _Nullable path,
|
||||
NSSize outputSize, NSError * _Nullable * _Nullable error);
|
||||
|
||||
@interface DYLUTLibrary : NSObject
|
||||
- (NSProgress *)importOnlineData:(NSData *)data identifier:(NSNumber *)identifier name:(NSString *)name category:(NSString *)category checksum:(NSString *)checksum completion:(void (^)(NSString *,NSError *))completion;
|
||||
@property(nonatomic,readonly,copy) NSURL *rootURL;
|
||||
/// Each item has name (without extension), path, relativeFolder, relativePath.
|
||||
@property(nonatomic,readonly,copy) NSArray<NSDictionary<NSString *,NSString *> *> *entries;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#import "DYLUTLibrary.h"
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
#include <string_view>
|
||||
@@ -530,6 +531,46 @@ static BOOL DYLUTEnsureDirectory(NSURL *directory,NSURL *root,NSError **error) {
|
||||
NSProgress *progress=[NSProgress discreteProgressWithTotalUnitCount:-1];progress.localizedDescription=@"正在查找 LUT 文件…";NSArray *sources=[[urls copy]autorelease];
|
||||
dispatch_async(_fileQueue,^{@autoreleasepool{NSError *error=nil;NSArray *imported=[self importURLs:sources progress:progress error:&error];dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(imported,error);});}});return progress;
|
||||
}
|
||||
- (NSProgress *)importOnlineData:(NSData *)data identifier:(NSNumber *)identifier name:(NSString *)name category:(NSString *)category checksum:(NSString *)checksum completion:(void (^)(NSString *,NSError *))completion {
|
||||
NSProgress *progress=[NSProgress progressWithTotalUnitCount:1];progress.localizedDescription=@"正在校验并保存在线 LUT…";
|
||||
dispatch_async(_fileQueue,^{@autoreleasepool{
|
||||
NSError *error=nil;NSString *saved=nil;
|
||||
@synchronized(self->_fileLock){
|
||||
auto safe=[](NSString *value)->NSString *{
|
||||
if(![value isKindOfClass:NSString.class])return @"未分类";
|
||||
NSCharacterSet *bad=[NSCharacterSet characterSetWithCharactersInString:@"/\\:\n\r\t"];
|
||||
NSString *text=[[[value componentsSeparatedByCharactersInSet:bad]componentsJoinedByString:@" "]stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
|
||||
while([text hasPrefix:@"."])text=[text substringFromIndex:1];
|
||||
return text.length?[text substringToIndex:MIN((NSUInteger)60,text.length)]:@"未分类";
|
||||
};
|
||||
unsigned char digest[CC_SHA256_DIGEST_LENGTH];CC_SHA256(data.bytes,(CC_LONG)data.length,digest);NSMutableString *hash=[NSMutableString string];for(unsigned char byte:digest)[hash appendFormat:@"%02x",byte];
|
||||
if(!data.length||data.length>64*1024*1024||identifier.longLongValue<=0||![checksum isKindOfClass:NSString.class]||![hash isEqual:checksum.lowercaseString])DYLUTFail(&error,@"在线 LUT 大小或 SHA-256 校验失败");
|
||||
NSURL *directory=[self->_rootURL URLByAppendingPathComponent:[@"在线 LUT/" stringByAppendingString:safe(category)] isDirectory:YES];
|
||||
NSString *filename=[NSString stringWithFormat:@"%@-%@-%@.cube",identifier,safe(name),[hash substringToIndex:12]];
|
||||
NSURL *destination=[directory URLByAppendingPathComponent:filename];NSURL *temporary=nil;
|
||||
if(!error&&!DYLUTCancelled(progress,&error)&&DYLUTEnsureDirectory(directory,self->_rootURL,&error)){
|
||||
NSFileManager *fm=NSFileManager.defaultManager;
|
||||
if([fm fileExistsAtPath:destination.path]){
|
||||
BOOL directory=NO;NSData *existing=nil;
|
||||
if(DYLUTOrdinaryURL(destination,&directory,&error)&&!directory)existing=[NSData dataWithContentsOfURL:destination options:NSDataReadingMappedIfSafe error:&error];
|
||||
if(directory)DYLUTFail(&error,@"在线 LUT 目标应为普通文件");
|
||||
if(existing&&![existing isEqualToData:data])DYLUTFail(&error,@"同名在线 LUT 内容不同,已保留现有文件");
|
||||
}else{
|
||||
temporary=[directory URLByAppendingPathComponent:[@".online-" stringByAppendingString:NSUUID.UUID.UUIDString]];
|
||||
if([data writeToURL:temporary options:NSDataWritingWithoutOverwriting error:&error]){
|
||||
std::vector<float> values;NSUInteger n=0;
|
||||
if(DYLUTReadCancellable(temporary.path,values,n,progress,&error)&&!DYLUTCancelled(progress,&error))
|
||||
[fm moveItemAtURL:temporary toURL:destination error:&error];
|
||||
}
|
||||
}
|
||||
if(!error){std::vector<float> values;NSUInteger n=0;if(DYLUTReadCancellable(destination.path,values,n,progress,&error)&&[self reload:&error])saved=destination.path;}
|
||||
if(temporary)[fm removeItemAtURL:temporary error:nil];
|
||||
}
|
||||
}
|
||||
progress.completedUnitCount=1;
|
||||
dispatch_async(dispatch_get_main_queue(),^{if(completion)completion(saved,error);});
|
||||
}});return progress;
|
||||
}
|
||||
- (BOOL)isFavoritePath:(NSString *)path {@synchronized(self){return [_favoritePaths containsObject:path];}}
|
||||
- (BOOL)setFavorite:(BOOL)favorite forPath:(NSString *)path error:(NSError **)error {@synchronized(self){
|
||||
NSString *prefix=[_rootURL.path stringByAppendingString:@"/"];
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#import <AppKit/AppKit.h>
|
||||
|
||||
FOUNDATION_EXPORT NSString *const DYOnlineLUTIdentityChanged;
|
||||
typedef void (^DYOnlineLUTReply)(NSData *, NSError *);
|
||||
@interface DYOnlineLUTClient : NSObject
|
||||
+ (NSDictionary *)credential;
|
||||
+ (BOOL)saveCredential:(NSDictionary *)value error:(NSError **)error;
|
||||
+ (BOOL)clearCredential:(NSError **)error;
|
||||
+ (NSString *)deviceUUID;
|
||||
+ (NSProgress *)request:(NSString *)path body:(NSDictionary *)body authenticated:(BOOL)authenticated completion:(DYOnlineLUTReply)completion;
|
||||
+ (NSDictionary *)JSON:(NSData *)data error:(NSError **)error;
|
||||
+ (void)openAccount;
|
||||
@end
|
||||
@@ -0,0 +1,129 @@
|
||||
#import "DYOnlineLUT.h"
|
||||
#import <Security/Security.h>
|
||||
#include <uuid/uuid.h>
|
||||
#include <unistd.h>
|
||||
|
||||
NSString *const DYOnlineLUTIdentityChanged=@"com.dayu.color.online-lut.identity-changed";
|
||||
static NSString *const DYOnlineLUTService=@"com.dayu.color.online-lut.session";
|
||||
static NSError *DYOnlineError(NSInteger code,NSString *message) {
|
||||
return [NSError errorWithDomain:@"com.dayu.color.online-lut" code:code userInfo:@{NSLocalizedDescriptionKey:message?:@"在线 LUT 暂不可用"}];
|
||||
}
|
||||
static NSDictionary *DYOnlineKeyQuery(void) {
|
||||
return @{(id)kSecClass:(id)kSecClassGenericPassword,(id)kSecAttrService:DYOnlineLUTService,(id)kSecAttrAccount:@"DayuColor"};
|
||||
}
|
||||
|
||||
@interface DYOnlineLUTTransfer : NSObject <NSURLSessionDataDelegate> {
|
||||
NSMutableData *_data;
|
||||
NSURLSession *_session;
|
||||
NSURLSessionDataTask *_task;
|
||||
NSProgress *_progress;
|
||||
DYOnlineLUTReply _reply;
|
||||
NSHTTPURLResponse *_response;
|
||||
NSError *_failure;
|
||||
NSUInteger _limit;
|
||||
}
|
||||
- (NSProgress *)start:(NSURLRequest *)request limit:(NSUInteger)limit completion:(DYOnlineLUTReply)completion;
|
||||
@end
|
||||
@implementation DYOnlineLUTTransfer
|
||||
- (void)dealloc {
|
||||
[_data release];[_task release];[_session release];[_progress release];[_reply release];[_response release];[_failure release];[super dealloc];
|
||||
}
|
||||
- (NSProgress *)start:(NSURLRequest *)request limit:(NSUInteger)limit completion:(DYOnlineLUTReply)completion {
|
||||
_limit=limit;_data=[NSMutableData new];_reply=[completion copy];_progress=[[NSProgress progressWithTotalUnitCount:1]retain];
|
||||
NSURLSessionConfiguration *config=NSURLSessionConfiguration.ephemeralSessionConfiguration;
|
||||
config.timeoutIntervalForRequest=20;config.timeoutIntervalForResource=45;config.HTTPShouldSetCookies=NO;config.URLCache=nil;
|
||||
_session=[[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]retain];
|
||||
_task=[[_session dataTaskWithRequest:request]retain];
|
||||
_progress.cancellationHandler=^{[self->_task cancel];};[_task resume];return _progress;
|
||||
}
|
||||
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completion { completion(nil); }
|
||||
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completion {
|
||||
_response=[(NSHTTPURLResponse *)response retain];
|
||||
if(![response isKindOfClass:NSHTTPURLResponse.class]||response.expectedContentLength>(int64_t)_limit) {
|
||||
_failure=[DYOnlineError(413,@"服务器响应过大,已停止下载。")retain];completion(NSURLSessionResponseCancel);return;
|
||||
}
|
||||
completion(NSURLSessionResponseAllow);
|
||||
}
|
||||
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveData:(NSData *)data {
|
||||
if(data.length>_limit-_data.length){_failure=[DYOnlineError(413,@"服务器响应超过限制。")retain];[task cancel];return;}
|
||||
[_data appendData:data];
|
||||
if(_response.expectedContentLength>0){_progress.totalUnitCount=_response.expectedContentLength;_progress.completedUnitCount=_data.length;}
|
||||
}
|
||||
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
|
||||
NSError *failure=_failure?:error;
|
||||
if(!failure&&(_response.statusCode<200||_response.statusCode>=300)) {
|
||||
NSDictionary *value=[NSJSONSerialization JSONObjectWithData:_data options:0 error:nil];
|
||||
NSString *message=[value isKindOfClass:NSDictionary.class]&&[value[@"message"]isKindOfClass:NSString.class]?value[@"message"]:@"在线服务暂不可用,请稍后重试。";
|
||||
failure=DYOnlineError(_response.statusCode,message);
|
||||
}
|
||||
_progress.cancellationHandler=nil;_progress.completedUnitCount=_progress.totalUnitCount;
|
||||
NSData *bytes=failure?nil:[NSData dataWithData:_data];
|
||||
dispatch_async(dispatch_get_main_queue(),^{if(self->_reply)self->_reply(bytes,failure);});
|
||||
[_session finishTasksAndInvalidate];
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation DYOnlineLUTClient
|
||||
+ (NSDictionary *)credential {
|
||||
NSMutableDictionary *query=[NSMutableDictionary dictionaryWithDictionary:DYOnlineKeyQuery()];
|
||||
query[(id)kSecReturnData]=@YES;query[(id)kSecMatchLimit]=(id)kSecMatchLimitOne;
|
||||
// Plugin windows never invoke a Keychain password dialog inside the host.
|
||||
if([NSBundle.mainBundle.bundleIdentifier isEqual:@"com.dayu.color.XPC"])query[(id)kSecUseAuthenticationUI]=(id)kSecUseAuthenticationUIFail;
|
||||
CFTypeRef result=NULL;OSStatus status=SecItemCopyMatching((CFDictionaryRef)query,&result);
|
||||
if(status!=errSecSuccess)return nil;
|
||||
NSData *data=[(NSData *)result autorelease];NSDictionary *value=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
|
||||
if(![value isKindOfClass:NSDictionary.class]||![value[@"token"]isKindOfClass:NSString.class]||[value[@"token"]length]!=64||[value[@"token"]rangeOfString:@"^[a-f0-9]{64}$" options:NSRegularExpressionSearch].location==NSNotFound||[value[@"expires_at"]doubleValue]<=NSDate.date.timeIntervalSince1970)return nil;
|
||||
return value;
|
||||
}
|
||||
+ (BOOL)saveCredential:(NSDictionary *)value error:(NSError **)error {
|
||||
if(![value[@"token"]isKindOfClass:NSString.class]||[value[@"token"]length]!=64){if(error)*error=DYOnlineError(401,@"登录凭据无效。");return NO;}
|
||||
NSData *data=[NSJSONSerialization dataWithJSONObject:value options:0 error:error];if(!data)return NO;
|
||||
OSStatus status=SecItemUpdate((CFDictionaryRef)DYOnlineKeyQuery(),(CFDictionaryRef)@{(id)kSecValueData:data});
|
||||
if(status==errSecItemNotFound) {
|
||||
NSMutableDictionary *query=[NSMutableDictionary dictionaryWithDictionary:DYOnlineKeyQuery()];query[(id)kSecValueData]=data;query[(id)kSecAttrLabel]=@"大鱼调色在线 LUT 登录";
|
||||
NSMutableArray *trusted=[NSMutableArray array];
|
||||
for(NSString *path in @[@"/Library/Plug-Ins/FxPlug/大鱼调色.app/Contents/MacOS/大鱼调色",@"/Library/Plug-Ins/FxPlug/大鱼调色.app/Contents/PlugIns/大鱼调色 XPC Service.pluginkit/Contents/MacOS/大鱼调色 XPC Service"]){
|
||||
SecTrustedApplicationRef application=NULL;
|
||||
if(SecTrustedApplicationCreateFromPath(path.fileSystemRepresentation,&application)==errSecSuccess){[trusted addObject:(id)application];CFRelease(application);}
|
||||
}
|
||||
SecAccessRef access=NULL;
|
||||
if(trusted.count!=2||SecAccessCreate(CFSTR("大鱼调色在线 LUT"),(CFArrayRef)trusted,&access)!=errSecSuccess){if(error)*error=DYOnlineError(401,@"无法为正式插件配置登录钥匙串访问。");return NO;}
|
||||
query[(id)kSecAttrAccess]=(id)access;status=SecItemAdd((CFDictionaryRef)query,NULL);CFRelease(access);
|
||||
}
|
||||
if(status!=errSecSuccess){if(error)*error=DYOnlineError(status,@"无法保存登录钥匙串,请允许大鱼调色访问。");return NO;}
|
||||
[NSDistributedNotificationCenter.defaultCenter postNotificationName:DYOnlineLUTIdentityChanged object:nil userInfo:nil deliverImmediately:YES];return YES;
|
||||
}
|
||||
+ (BOOL)clearCredential:(NSError **)error {
|
||||
OSStatus status=SecItemDelete((CFDictionaryRef)DYOnlineKeyQuery());
|
||||
if(status!=errSecSuccess&&status!=errSecItemNotFound){if(error)*error=DYOnlineError(status,@"无法移除登录钥匙串凭据。");return NO;}
|
||||
[NSDistributedNotificationCenter.defaultCenter postNotificationName:DYOnlineLUTIdentityChanged object:nil userInfo:nil deliverImmediately:YES];return YES;
|
||||
}
|
||||
+ (NSString *)deviceUUID {
|
||||
uuid_t uuid;struct timespec timeout={2,0};if(gethostuuid(uuid,&timeout)!=0)return nil;uuid_string_t text;uuid_unparse_upper(uuid,text);return [NSString stringWithUTF8String:text];
|
||||
}
|
||||
+ (NSDictionary *)JSON:(NSData *)data error:(NSError **)error {
|
||||
id value=data?[NSJSONSerialization JSONObjectWithData:data options:0 error:error]:nil;
|
||||
if(![value isKindOfClass:NSDictionary.class]){if(error&&!*error)*error=DYOnlineError(422,@"在线服务返回的数据无效。");return nil;}return value;
|
||||
}
|
||||
+ (NSProgress *)request:(NSString *)path body:(NSDictionary *)body authenticated:(BOOL)authenticated completion:(DYOnlineLUTReply)completion {
|
||||
BOOL login=[path isEqual:@"/dayu-app/v1/login/session"];
|
||||
if(!login&&![path hasPrefix:@"/dayu-color/v1/lut/"]){if(completion)completion(nil,DYOnlineError(400,@"请求地址无效。"));return nil;}
|
||||
NSDictionary *credential=authenticated?[self credential]:nil;
|
||||
if(authenticated&&!credential){if(completion)completion(nil,DYOnlineError(401,@"请先在大鱼调色主 APP 登录。"));return nil;}
|
||||
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[@"https://dayu.media/wp-json" stringByAppendingString:path]]];
|
||||
request.HTTPMethod=@"POST";request.cachePolicy=NSURLRequestReloadIgnoringLocalCacheData;
|
||||
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
|
||||
[request setValue:@"application/json, image/png, application/octet-stream" forHTTPHeaderField:@"Accept"];
|
||||
[request setValue:@"DayuColor-OnlineLUT/1.0" forHTTPHeaderField:@"User-Agent"];
|
||||
if(credential)[request setValue:[@"Bearer " stringByAppendingString:credential[@"token"]]forHTTPHeaderField:@"Authorization"];
|
||||
NSError *error=nil;request.HTTPBody=[NSJSONSerialization dataWithJSONObject:body?:@{} options:0 error:&error];
|
||||
if(!request.HTTPBody){if(completion)completion(nil,error);return nil;}
|
||||
NSUInteger limit=[path hasSuffix:@"/download"]?64*1024*1024:2*1024*1024;
|
||||
DYOnlineLUTTransfer *transfer=[[[DYOnlineLUTTransfer alloc]init]autorelease];return [transfer start:request limit:limit completion:completion];
|
||||
}
|
||||
+ (void)openAccount {
|
||||
NSURL *url=[NSURL fileURLWithPath:@"/Library/Plug-Ins/FxPlug/大鱼调色.app"];
|
||||
NSWorkspaceOpenConfiguration *configuration=NSWorkspaceOpenConfiguration.configuration;configuration.arguments=@[@"--online-lut-account"];
|
||||
[NSWorkspace.sharedWorkspace openApplicationAtURL:url configuration:configuration completionHandler:nil];
|
||||
}
|
||||
@end
|
||||
@@ -2,6 +2,7 @@
|
||||
#import "DYBetaUpdater.h"
|
||||
#import "../Shared/DYBetaDiagnostics.h"
|
||||
#import "../Shared/DYCodeIntegrity.h"
|
||||
#import "../Shared/DYOnlineLUT.h"
|
||||
|
||||
static NSString *const DYPluginID = @"com.dayu.color.XPC";
|
||||
static NSString *const DYReleaseAddress = @"https://dayu.media";
|
||||
@@ -132,6 +133,13 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
@property(retain) NSTimer *updateProgressTimer;
|
||||
@property BOOL updateCheckDone;
|
||||
@property BOOL integrityRejected;
|
||||
@property(assign) NSTextField *accountTitle,*accountDetail;
|
||||
@property(assign) DYActionButton *loginButton,*accessButton,*logoutButton;
|
||||
@property(retain) NSProgress *accountTask;
|
||||
@property(copy) NSString *loginSessionKey;
|
||||
@property(retain) NSTimer *loginTimer;
|
||||
@property NSUInteger accountGeneration;
|
||||
@property BOOL pollingLogin;
|
||||
@end
|
||||
|
||||
@implementation AppDelegate
|
||||
@@ -154,6 +162,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
[NSWorkspace.sharedWorkspace.notificationCenter addObserver:self selector:@selector(accessibilityChanged:)
|
||||
name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
|
||||
[self.window makeKeyAndOrderFront:nil]; [self refreshDiagnostics:nil]; [self checkRegistration:nil]; [self.updater check];
|
||||
[self refreshOnlineAccount:nil];
|
||||
// Explicit QA opt-in on the signed, installed wrapper only. Never stalls the host.
|
||||
if([NSProcessInfo.processInfo.arguments containsObject:@"--diagnostics-probe"])
|
||||
[self performSelector:@selector(runDiagnosticsProbe) withObject:nil afterDelay:5];
|
||||
@@ -246,6 +255,14 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
self.reportID,self.diagnosticDetail,self.sendSummaryButton],NSUserInterfaceLayoutOrientationVertical,10));
|
||||
NSStackView *beta=DYStack(@[updateCard,diagnosticCard],NSUserInterfaceLayoutOrientationHorizontal,14);
|
||||
[updateCard.heightAnchor constraintEqualToAnchor:diagnosticCard.heightAnchor].active=YES;
|
||||
self.accountTitle=DYLabel(@"在线 LUT",22,NSFontWeightSemibold,NSColor.whiteColor);
|
||||
self.accountDetail=DYLabel(@"在主 APP 登录后,即可在插件 LUT 浏览器中使用在线分类。",13,NSFontWeightRegular,DYSecondary());
|
||||
self.loginButton=DYButton(@"微信登录",DYBlue(),YES,self,@selector(loginOnlineAccount:));
|
||||
self.accessButton=DYButton(@"刷新权限",DYBlue(),NO,self,@selector(refreshOnlineAccount:));
|
||||
self.logoutButton=DYButton(@"退出登录",DYSecondary(),NO,self,@selector(logoutOnlineAccount:));
|
||||
DYSurface *accountCard=DYCard(DYBlue(),DYStack(@[DYHeading(@"person.crop.circle",@"大鱼账号 · 在线 LUT",DYBlue()),self.accountTitle,self.accountDetail,
|
||||
DYLabel(@"有效会员,或已购买文章 14421 / 15792,即可浏览和下载全部已发布在线 LUT。\n在插件中点击“在线预览当前帧”会发送当前帧缩略图到 dayu.media;服务器仅在本次请求中处理,不保存预览帧。",12,NSFontWeightRegular,DYSecondary()),
|
||||
DYStack(@[self.loginButton,self.accessButton,self.logoutButton],NSUserInterfaceLayoutOrientationHorizontal,8)],NSUserInterfaceLayoutOrientationVertical,12));
|
||||
NSArray *features = @[
|
||||
@[@"slider.horizontal.3",@"完整调色",@"精准还原,自由塑造",@"CST 色彩管理、光影与曲线\nHSL、色轮、蜘蛛盘与白平衡",DYBlue()],
|
||||
@[@"square.grid.2x2",@"LUT 与风格",@"灵感,所见即所得",@"LUT 缩略图浏览与实时预览\n快速收藏,管理常用风格",DYColor(.67,.59,1)],
|
||||
@@ -258,12 +275,74 @@ 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,beta,DYHeading(@"sparkles",@"一套工具,完成你的色彩表达",NSColor.whiteColor),row1,row2],NSUserInterfaceLayoutOrientationVertical,18);
|
||||
NSStackView *content = DYStack(@[website,hero,accountCard,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;
|
||||
}
|
||||
|
||||
- (void)stopAccountLogin {
|
||||
self.accountGeneration++;[self.accountTask cancel];self.accountTask=nil;
|
||||
[self.loginTimer invalidate];self.loginTimer=nil;self.loginSessionKey=nil;self.pollingLogin=NO;
|
||||
self.loginButton.enabled=YES;self.accessButton.enabled=YES;
|
||||
}
|
||||
- (void)refreshOnlineAccount:(id)sender {
|
||||
if(self.loginSessionKey.length)return;
|
||||
NSUInteger generation=++self.accountGeneration;[self.accountTask cancel];
|
||||
self.logoutButton.enabled=[DYOnlineLUTClient credential]!=nil;
|
||||
if(!self.logoutButton.enabled){self.accountTitle.stringValue=@"尚未登录";self.accountDetail.stringValue=@"点击微信登录,在浏览器中完成账号确认后自动返回。";return;}
|
||||
self.accountTitle.stringValue=@"正在验证在线 LUT 权限…";self.accessButton.enabled=NO;
|
||||
self.accountTask=[DYOnlineLUTClient request:@"/dayu-color/v1/lut/status" body:@{} authenticated:YES completion:^(NSData *data,NSError *error){
|
||||
if(generation!=self.accountGeneration)return;self.accountTask=nil;self.accessButton.enabled=YES;
|
||||
NSDictionary *value=[DYOnlineLUTClient JSON:data error:&error];
|
||||
if(error||!value){self.accountTitle.stringValue=@"暂时无法验证权限";self.accountDetail.stringValue=error.localizedDescription?:@"请稍后重试。";return;}
|
||||
BOOL allowed=[value[@"allowed"]isKindOfClass:NSNumber.class]&&[value[@"allowed"]boolValue];
|
||||
self.accountTitle.stringValue=allowed?@"在线 LUT 已开放":@"账号已登录,尚无在线 LUT 权限";
|
||||
NSString *name=[value[@"username"]isKindOfClass:NSString.class]?value[@"username"]:@"大鱼用户";
|
||||
self.accountDetail.stringValue=[NSString stringWithFormat:@"%@\n%@",name,allowed?@"在 FCP 的 LUT 浏览器切换“在线 LUT”即可使用。":@"需要有效会员,或购买文章 14421 / 15792。购买后点击刷新权限。"];
|
||||
}];
|
||||
}
|
||||
- (void)loginOnlineAccount:(id)sender {
|
||||
[self stopAccountLogin];NSUInteger generation=self.accountGeneration;
|
||||
NSString *device=[DYOnlineLUTClient deviceUUID];
|
||||
if(!device){self.accountDetail.stringValue=@"无法读取本机身份,请稍后重试。";return;}
|
||||
self.loginButton.enabled=NO;self.accessButton.enabled=NO;self.accountTitle.stringValue=@"正在创建微信登录…";
|
||||
NSDictionary *info=NSBundle.mainBundle.infoDictionary;
|
||||
self.accountTask=[DYOnlineLUTClient request:@"/dayu-app/v1/login/session" body:@{@"device_uuid":device,@"app_name":@"DayuColor",@"client_bundle":@"com.dayu.color",@"client_version":info[@"CFBundleShortVersionString"]?:@"",@"client_build":info[@"CFBundleVersion"]?:@"",@"client_platform":@"macOS"} authenticated:NO completion:^(NSData *data,NSError *error){
|
||||
if(generation!=self.accountGeneration)return;self.accountTask=nil;
|
||||
NSDictionary *value=[DYOnlineLUTClient JSON:data error:&error];
|
||||
NSString *key=[value[@"session_key"]isKindOfClass:NSString.class]?value[@"session_key"]:nil;
|
||||
NSURL *url=[value[@"login_url"]isKindOfClass:NSString.class]?[NSURL URLWithString:value[@"login_url"]]:nil;
|
||||
if(error||key.length<32||![url.scheme isEqual:@"https"]||![url.host.lowercaseString isEqual:@"dayu.media"]||![url.path isEqual:@"/oauth/weixin"]){
|
||||
[self stopAccountLogin];self.accountTitle.stringValue=@"登录未完成";self.accountDetail.stringValue=error.localizedDescription?:@"登录服务返回的地址无效。";return;
|
||||
}
|
||||
self.loginSessionKey=key;self.accountTitle.stringValue=@"请在浏览器中完成微信登录";self.accountDetail.stringValue=@"完成扫码和账号确认后,这里会自动验证在线 LUT 权限。";
|
||||
if(![NSWorkspace.sharedWorkspace openURL:url]){[self stopAccountLogin];self.accountDetail.stringValue=@"无法打开浏览器,请重试。";return;}
|
||||
self.loginTimer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(pollOnlineLogin:) userInfo:@{ @"started":NSDate.date } repeats:YES];
|
||||
}];
|
||||
}
|
||||
- (void)pollOnlineLogin:(NSTimer *)timer {
|
||||
if(self.pollingLogin||!self.loginSessionKey.length)return;
|
||||
if([timer.userInfo[@"started"]timeIntervalSinceNow]<-600){[self stopAccountLogin];self.accountDetail.stringValue=@"二维码已过期,请重新登录。";return;}
|
||||
NSUInteger generation=self.accountGeneration;self.pollingLogin=YES;
|
||||
self.accountTask=[DYOnlineLUTClient request:@"/dayu-color/v1/lut/session" body:@{@"session_key":self.loginSessionKey,@"device_uuid":[DYOnlineLUTClient deviceUUID]?:@""} authenticated:NO completion:^(NSData *data,NSError *error){
|
||||
if(generation!=self.accountGeneration)return;self.pollingLogin=NO;self.accountTask=nil;
|
||||
NSDictionary *value=[DYOnlineLUTClient JSON:data error:&error];
|
||||
if(error){if(error.code==401||error.code==400){[self stopAccountLogin];self.accountDetail.stringValue=error.localizedDescription;}return;}
|
||||
if(![value[@"status"]isEqual:@"approved"]){self.accountDetail.stringValue=[value[@"message"]isKindOfClass:NSString.class]?value[@"message"]:@"等待微信登录…";return;}
|
||||
if(![DYOnlineLUTClient saveCredential:value error:&error]){[self stopAccountLogin];self.accountDetail.stringValue=error.localizedDescription;return;}
|
||||
[self stopAccountLogin];[self refreshOnlineAccount:nil];
|
||||
}];
|
||||
}
|
||||
- (void)logoutOnlineAccount:(id)sender {
|
||||
[self stopAccountLogin];
|
||||
self.accountTask=[DYOnlineLUTClient request:@"/dayu-color/v1/lut/logout" body:@{} authenticated:YES completion:^(NSData *data,NSError *error){
|
||||
self.accountTask=nil;
|
||||
if(error&&error.code!=401){self.accountDetail.stringValue=@"暂时无法通知服务器退出,请联网后重试。";return;}
|
||||
NSError *local=nil;if(![DYOnlineLUTClient clearCredential:&local]){self.accountDetail.stringValue=local.localizedDescription;return;}[self refreshOnlineAccount:nil];
|
||||
}];
|
||||
}
|
||||
|
||||
// PluginKit runs on a worker queue. Arguments are never interpreted as shell commands.
|
||||
- (NSDictionary *)runPluginKit:(NSArray *)arguments {
|
||||
NSTask *task = [[[NSTask alloc] init] autorelease]; task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/pluginkit"]; task.arguments = arguments;
|
||||
@@ -501,6 +580,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
|
||||
- (void)accessibilityChanged:(NSNotification *)note { [self.window.contentView setNeedsDisplay:YES]; }
|
||||
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app { return NO; }
|
||||
- (void)applicationWillTerminate:(NSNotification *)note {
|
||||
[self stopAccountLogin];
|
||||
self.terminating = YES;
|
||||
[NSStatusBar.systemStatusBar removeStatusItem:self.statusItem];
|
||||
self.updater.changed=nil; [self.updater cancel];DYBetaStop();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## 2026-11-11 在线 LUT 下载可行性
|
||||
|
||||
后续用户已要求实际接入在线分类、主 APP 登录、14421/15792 任一购买或会员权限,以及时间线帧在线效果预览。实现与生产路径见[专项记录](research/OnlineLUTIntegration-20261111.md),接入前基线为 `5fae1150f4b7b6087f5da8298b5ac3ad8916e529`。以下保留此前可行性结论。
|
||||
后续用户已要求实际接入在线分类、主 APP 登录、14421/15792 任一购买或会员权限,以及时间线帧在线效果预览。实现与生产路径见[专项记录](research/OnlineLUTIntegration-20261111.md),接入前基线为 `5fae1150f4b7b6087f5da8298b5ac3ad8916e529`。首个实现检查点已包含后端、主 APP 登录和浏览器接入;Release 编译与隔离 PHP 合约通过,部署及正式交付仍待执行。以下保留此前可行性结论。
|
||||
|
||||
用户询问 LUT 浏览器能否联网下载预置 LUT,随后明确关心 FxPlug4 插件独立界面本身是否能够联网。核对当前源码、正式安装元数据及 Apple 官方文档;正式版本仍为 **1.21.8(126)**。首轮接手提交 `f554b11e6c17aaf38a7ae136787cdbb3eb9d45da` 与远端 `main` 一致,可行性记录已保存为 `995ac745d05fa0f5f1bbd142ae4ef6af45e281df`。两轮均未修改功能、运行宿主或发布新版本。
|
||||
|
||||
|
||||
在新工单中引用
屏蔽一个用户