22 lines
2.7 KiB
TypeScript
22 lines
2.7 KiB
TypeScript
import { useEffect,useState } from 'react';
|
||
import type { InputAttachment } from '../types';
|
||
import { MobileError } from './api';
|
||
|
||
async function readImage(sessionId:string,image:InputAttachment,original=false){
|
||
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);
|
||
try{
|
||
const response=await fetch('/mobile-api/sessions/'+sessionId+'/input-attachments/'+image.id+'/'+(original?'original':'image'),{credentials:'same-origin',cache:'no-store',signal:controller.signal});
|
||
if(!response.ok){const value=await response.json().catch(()=>({}));throw new MobileError(value.error||'截图读取失败。',response.status);}
|
||
const bytes=await response.arrayBuffer();if(bytes.byteLength>(original?2*1024*1024:768*1024))throw new MobileError('截图超出允许大小。');
|
||
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),value=>value.toString(16).padStart(2,'0')).join('');
|
||
if(digest!==(original?image.sha256:image.sentSha256))throw new MobileError('截图SHA-256核对失败,请在电脑核对。');
|
||
return new Blob([bytes],{type:original?image.mediaType:'image/png'});
|
||
}finally{clearTimeout(timer);}
|
||
}
|
||
export function MobileInputImage({sessionId,image,onError}:{sessionId:string;image:InputAttachment;onError:(cause:unknown)=>void}){
|
||
const [url,setUrl]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||
useEffect(()=>{let alive=true,objectUrl='';setUrl('');setError('');void readImage(sessionId,image).then(blob=>{if(alive){objectUrl=URL.createObjectURL(blob);setUrl(objectUrl);}}).catch(cause=>{if(alive){setError(cause.message);onError(cause);}});return()=>{alive=false;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[sessionId,image.id,image.sentSha256]);
|
||
async function download(){setBusy(true);try{const blob=await readImage(sessionId,image,true),href=URL.createObjectURL(blob),link=document.createElement('a');link.href=href;link.download=image.name;link.click();setTimeout(()=>URL.revokeObjectURL(href),1000);}catch(cause){onError(cause);}finally{setBusy(false);}}
|
||
return <section className="mobile-input-image"><h2>本任务截图</h2><strong>{image.name}</strong><p>{url?'SHA-256 已核对':error||'正在核对截图…'} · 发送副本 {image.sentWidth} × {image.sentHeight}</p>{url&&<details><summary>查看发送给模型的截图</summary><img src={url} alt={image.name}/><code>{image.sentSha256}</code></details>}<button disabled={busy||!url} onClick={()=>void download()}>核对并下载原图</button><p className="mobile-muted">原图 {image.width} × {image.height}。手机按现有项目观察权限读取;添加截图与预算续接在电脑操作。</p></section>;
|
||
}
|