작업실 채팅 📷 팝업에 📱 폴드로 찍기 / 📱 최근 N장 버튼 — POST /api/workshop/phone-photo가 phone_photo 도구와 같은 함수(phonePhotoToProject, 셔터 1개씩 잠금)로 이 프로젝트 사진/에 저장하고, 화면은 '[첨부 사진: 사진/fold_…]'를 입력창에 넣음(기존 사진 첨부와 같은 흐름). 실패하면 원인을 팝업에 그대로 표시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e881853f16
commit
7a3d90465e
3 files changed
+102
-37
No files matched your search
@@ -20,6 +20,7 @@ import {
|
||||
listDeletedProjects, restoreFromHistory, readHistory, duplicateProject, genWorkshopId,
|
||||
} from './workshop-storage';
|
||||
import { searchDanawa } from '../../tools/danawa';
|
||||
import { phonePhotoToProject } from '../../tools/phone-photo';
|
||||
import { renderStlPng, dropStlToFloor, convertAsciiStlToBinary, runOpenscad } from '../../tools/stl-cad-core';
|
||||
import { scanScadModules, unassignedParts } from './workshop-assembly';
|
||||
import { renderAssemblyManual, readManifest, resolveScadPath, currentAssemblyHash, assemblyOutDir, ASSEMBLY_DIR_NAME, draftAssembly } from '../../tools/workshop-assembly-render';
|
||||
@@ -235,6 +236,20 @@ export function registerWorkshopRoutes(
|
||||
});
|
||||
});
|
||||
|
||||
// ── 폰(Z Fold 3) 촬영·최근 사진 → 이 프로젝트 사진/ (2026-10-25, 채팅 📷 팝업의 📱 버튼) ─────
|
||||
// 채팅 도구 phone_photo와 같은 함수(phonePhotoToProject)를 쓴다 — 결과 relPath를 클라이언트가
|
||||
// "[첨부 사진: …]"로 입력창에 넣는다. 셔터는 한 번에 하나씩(함수 안 잠금).
|
||||
app.post('/api/workshop/phone-photo', express.json(), async (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const projectId = String(req.body?.projectId || '');
|
||||
const action = String(req.body?.action || '');
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(projectId)) return res.status(400).json({ error: 'invalid projectId' });
|
||||
const r = await phonePhotoToProject(getUserWorkspace(session.username), projectId, action, Number(req.body?.count) || 1);
|
||||
if (!r.ok) return res.status(502).json({ error: r.error || '실패' });
|
||||
res.json({ files: r.saved.map(n => ({ name: n, relPath: `사진/${n}`, url: `/api/files/workshop/${projectId}/${encodeURIComponent('사진')}/${encodeURIComponent(n)}` })), failed: r.failed });
|
||||
});
|
||||
|
||||
// ── STL 썸네일 ───────────────────────────────────────────────────────────────
|
||||
// OpenSCAD로 렌더(stl_cad 도구와 같은 코어)해 캐시한다. 렌더가 무거워 한 번에 하나씩만 돌리고,
|
||||
// 실패(ASCII STL/너무 큼/렌더 오류)는 .fail 마커로 기억해 재시도 폭주를 막는다 — 클라이언트는
|
||||
|
||||
+59
-37
@@ -82,6 +82,55 @@ async function pullToProject(serial: string, files: string[], workspaceRoot: str
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
export interface PhonePhotoResult { ok: boolean; error?: string; saved: string[]; failed: string[]; projectId?: string; projectName?: string }
|
||||
|
||||
// 버튼(작업실 화면)과 채팅 도구가 동시에 셔터를 누르지 않게 한 번에 하나씩.
|
||||
let phoneLock: Promise<unknown> = Promise.resolve();
|
||||
|
||||
/** 폰으로 찍거나(capture) 최근 사진(fetch)을 projectId 프로젝트의 사진/ 폴더로 가져온다 — 도구와 작업실 버튼이 같이 쓴다. */
|
||||
export function phonePhotoToProject(workspaceRoot: string, projectId: string, action: string, count?: number): Promise<PhonePhotoResult> {
|
||||
const job = phoneLock.then(() => phonePhotoToProjectUnlocked(workspaceRoot, projectId, action, count));
|
||||
phoneLock = job.catch(() => undefined);
|
||||
return job;
|
||||
}
|
||||
|
||||
async function phonePhotoToProjectUnlocked(workspaceRoot: string, projectId: string, action: string, count?: number): Promise<PhonePhotoResult> {
|
||||
const none: PhonePhotoResult = { ok: false, saved: [], failed: [] };
|
||||
if (action !== 'capture' && action !== 'fetch') return { ...none, error: 'action은 capture 또는 fetch입니다.' };
|
||||
let project: { id: string; name: string } | undefined;
|
||||
try { project = loadWorkshop(workspaceRoot).projects.find((x) => x.id === projectId); } catch {}
|
||||
if (!project) return { ...none, error: '작업실 프로젝트를 찾지 못했습니다. 대시보드에서 프로젝트를 고른 뒤 다시 시도하세요.' };
|
||||
|
||||
const conn = await ensurePhone();
|
||||
if ('error' in conn) return { ...none, error: conn.error };
|
||||
const { serial } = conn;
|
||||
|
||||
let files: string[];
|
||||
if (action === 'capture') {
|
||||
const before = (await listCameraFiles(serial))[0] || '';
|
||||
await run('adb', ['-s', serial, 'shell', 'input', 'keyevent', 'KEYCODE_WAKEUP']);
|
||||
await run('adb', ['-s', serial, 'shell', 'am', 'start', '-a', 'android.media.action.STILL_IMAGE_CAMERA']);
|
||||
await sleep(3000);
|
||||
await run('adb', ['-s', serial, 'shell', 'input', 'keyevent', 'KEYCODE_CAMERA']);
|
||||
let newest = '';
|
||||
for (let i = 0; i < 12; i++) { // 저장까지 최대 약 6초
|
||||
await sleep(500);
|
||||
newest = (await listCameraFiles(serial))[0] || '';
|
||||
if (newest && newest !== before) break;
|
||||
}
|
||||
if (!newest || newest === before) return { ...none, error: '셔터를 눌렀지만 새 사진이 생기지 않았습니다(카메라 앱이 안 열렸거나 화면이 잠김). 폰 화면을 확인해 주세요.' };
|
||||
files = [newest];
|
||||
} else {
|
||||
const n = Math.max(1, Math.min(MAX_FETCH, Math.round(Number(count) || 1)));
|
||||
files = (await listCameraFiles(serial)).slice(0, n);
|
||||
if (!files.length) return { ...none, error: `폰 ${CAMERA_DIR}에 사진이 없습니다.` };
|
||||
}
|
||||
|
||||
const { saved, failed } = await pullToProject(serial, files, workspaceRoot, project.id);
|
||||
if (!saved.length) return { ...none, failed, error: `폰에서 사진을 받아오지 못했습니다(${failed.join(', ')}).` };
|
||||
return { ok: true, saved, failed, projectId: project.id, projectName: project.name };
|
||||
}
|
||||
|
||||
export const phonePhotoTool = {
|
||||
name: 'phone_photo',
|
||||
description: '작업실 전용: 측정용 Z Fold 3 폰(무선 ADB)으로 사진을 찍거나(action="capture"), 사용자가 폰으로 직접 찍은 최근 사진 N장을 가져온다(action="fetch", count). 사진은 지금 대시보드에 열린 작업실 프로젝트의 사진/ 폴더에 fold_<날짜_시각>.jpg로 저장되고 이미지가 바로 첨부되니, 실제로 보고 보이는 것만 말할 것. "폴드로 찍어", "방금 찍은 거 가져와", "최근 사진 3장" 같은 요청에 사용. 연결이 안 되면 오류 문구를 그대로 사용자에게 전할 것(찍었다고 말하지 말 것).',
|
||||
@@ -97,50 +146,23 @@ export const phonePhotoTool = {
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const action = String(args?.action || '').trim();
|
||||
if (action !== 'capture' && action !== 'fetch') return { success: false, error: 'action은 capture 또는 fetch입니다.' };
|
||||
const workspaceRoot = getWorkspacePath(args);
|
||||
const project = activeProject(workspaceRoot);
|
||||
if (!project) return { success: false, error: '열린 작업실 프로젝트를 찾지 못했습니다. 대시보드에서 프로젝트를 고른 뒤 다시 시도하세요.' };
|
||||
const active = activeProject(workspaceRoot);
|
||||
if (!active) return { success: false, error: '열린 작업실 프로젝트를 찾지 못했습니다. 대시보드에서 프로젝트를 고른 뒤 다시 시도하세요.' };
|
||||
const r = await phonePhotoToProject(workspaceRoot, active.id, action, args?.count);
|
||||
if (!r.ok) return { success: false, error: r.error || '실패' };
|
||||
|
||||
const conn = await ensurePhone();
|
||||
if ('error' in conn) return { success: false, error: conn.error };
|
||||
const { serial } = conn;
|
||||
|
||||
let files: string[];
|
||||
if (action === 'capture') {
|
||||
const before = (await listCameraFiles(serial))[0] || '';
|
||||
await run('adb', ['-s', serial, 'shell', 'input', 'keyevent', 'KEYCODE_WAKEUP']);
|
||||
await run('adb', ['-s', serial, 'shell', 'am', 'start', '-a', 'android.media.action.STILL_IMAGE_CAMERA']);
|
||||
await sleep(3000);
|
||||
await run('adb', ['-s', serial, 'shell', 'input', 'keyevent', 'KEYCODE_CAMERA']);
|
||||
let newest = '';
|
||||
for (let i = 0; i < 12; i++) { // 저장까지 최대 약 6초
|
||||
await sleep(500);
|
||||
newest = (await listCameraFiles(serial))[0] || '';
|
||||
if (newest && newest !== before) break;
|
||||
}
|
||||
if (!newest || newest === before) return { success: false, error: '셔터를 눌렀지만 새 사진이 생기지 않았습니다(카메라 앱이 안 열렸거나 화면이 잠김). 폰 화면을 확인해 달라고 하세요.' };
|
||||
files = [newest];
|
||||
} else {
|
||||
const n = Math.max(1, Math.min(MAX_FETCH, Math.round(Number(args?.count) || 1)));
|
||||
files = (await listCameraFiles(serial)).slice(0, n);
|
||||
if (!files.length) return { success: false, error: `폰 ${CAMERA_DIR}에 사진이 없습니다.` };
|
||||
}
|
||||
|
||||
const { saved, failed } = await pullToProject(serial, files, workspaceRoot, project.id);
|
||||
if (!saved.length) return { success: false, error: `폰에서 사진을 받아오지 못했습니다(${failed.join(', ')}).` };
|
||||
|
||||
const url = (name: string) => `/api/files/workshop/${project.id}/${encodeURIComponent('사진')}/${encodeURIComponent(name)}`;
|
||||
const shown = saved.slice(0, MAX_INLINE);
|
||||
const url = (name: string) => `/api/files/workshop/${r.projectId}/${encodeURIComponent('사진')}/${encodeURIComponent(name)}`;
|
||||
const shown = r.saved.slice(0, MAX_INLINE);
|
||||
const lines = [
|
||||
`[${project.name}] ${action === 'capture' ? 'Z Fold 3로 찍은 사진' : `Z Fold 3 최근 사진 ${saved.length}장`} → 사진/ 폴더에 저장: ${saved.join(', ')}`,
|
||||
...(failed.length ? [`받지 못한 파일: ${failed.join(', ')}`] : []),
|
||||
...(saved.length > shown.length ? [`(첨부는 앞의 ${shown.length}장만 — 나머지는 workshop_project view_image로 볼 수 있음)`] : []),
|
||||
`[${r.projectName}] ${action === 'capture' ? 'Z Fold 3로 찍은 사진' : `Z Fold 3 최근 사진 ${r.saved.length}장`} → 사진/ 폴더에 저장: ${r.saved.join(', ')}`,
|
||||
...(r.failed.length ? [`받지 못한 파일: ${r.failed.join(', ')}`] : []),
|
||||
...(r.saved.length > shown.length ? [`(첨부는 앞의 ${shown.length}장만 — 나머지는 workshop_project view_image로 볼 수 있음)`] : []),
|
||||
'',
|
||||
...shown.map((n) => `})`),
|
||||
'',
|
||||
'[중요] 위 사진을 실제로 보고, 보이는 것만 말할 것. 치수는 체커보드(칸 10mm)나 자가 함께 찍혀 있을 때만 대략으로 말하고 "사진 추정"이라고 밝힐 것.',
|
||||
];
|
||||
return { success: true, stdout: lines.join('\n'), data: { project: project.id, files: saved } };
|
||||
return { success: true, stdout: lines.join('\n'), data: { project: r.projectId, files: r.saved } };
|
||||
},
|
||||
};
|
||||
@@ -254,6 +254,10 @@ async function toggleAttachPop(ev){
|
||||
}catch{}
|
||||
const camOn=typeof window.cameraIsOn==='function'&&window.cameraIsOn();
|
||||
pop.innerHTML='<label class="rb-mini-btn" style="display:block;text-align:center;cursor:pointer">+ 새 사진 올려서 첨부<input type="file" accept="image/*" style="display:none" onchange="attachUpload(event)"></label>'
|
||||
+'<div style="display:flex;gap:6px;margin-top:6px">'
|
||||
+'<button class="rb-mini-btn" style="flex:1" onclick="phonePhotoAttach(\'capture\')" title="측정용 Z Fold 3로 지금 찍어서 이 프로젝트 사진 폴더에 저장·첨부">📱 폴드로 찍기</button>'
|
||||
+'<button class="rb-mini-btn" style="flex:1" onclick="phonePhotoAttach(\'fetch\')" title="Z Fold 3에서 직접 찍은 최근 사진을 가져와 저장·첨부">📱 최근 <select id="phone-count" onclick="event.stopPropagation()" style="background:none;color:inherit;border:none"><option>1</option><option>2</option><option>3</option><option>5</option></select>장</button>'
|
||||
+'</div><div id="phone-status" class="rb-empty" style="display:none;margin-top:4px"></div>'
|
||||
+(camOn
|
||||
?'<button class="rb-mini-btn" style="display:block;width:100%;margin-top:6px" onclick="saveCameraShot()">🎥 지금 카메라 화면을 사진으로 저장·첨부</button>'
|
||||
:'<div class="rb-empty" style="margin-top:6px">🎥로 카메라를 켜면 여기서 바로 찍어 저장할 수 있습니다.</div>')
|
||||
@@ -261,6 +265,30 @@ async function toggleAttachPop(ev){
|
||||
?'<div class="rb-attach-grid">'+photos.map(f=>'<img src="'+escAttr(f.url)+'" title="'+escAttr(f.relPath)+'" loading="lazy" onclick="attachPhoto(\''+escJs(f.relPath)+'\')">').join('')+'</div>'
|
||||
:'<div class="rb-empty">이 프로젝트에 올린 사진이 없습니다.</div>');
|
||||
}
|
||||
// 📱 측정용 Z Fold 3(무선 ADB) — 서버가 찍거나 최근 사진을 이 프로젝트 사진/에 저장하고, 여기서 입력창에 첨부한다.
|
||||
// 채팅 도구 phone_photo와 같은 서버 함수(/api/workshop/phone-photo). 실패하면 원인(무선 디버깅 꺼짐 등)을 그대로 보여 준다.
|
||||
async function phonePhotoAttach(action){
|
||||
const proj=currentProject();
|
||||
if(!proj)return;
|
||||
const st=document.getElementById('phone-status');
|
||||
const count=Number((document.getElementById('phone-count')||{}).value)||1;
|
||||
st.style.display='block';st.style.color='';
|
||||
st.textContent=action==='capture'?'폴드로 찍는 중… (약 6초)':'폴드에서 사진 가져오는 중…';
|
||||
try{
|
||||
const r=await fetch('/api/workshop/phone-photo',{method:'POST',headers:{...authH(),'Content-Type':'application/json'},body:JSON.stringify({projectId:proj.id,action,count})});
|
||||
const d=await r.json().catch(()=>({}));
|
||||
if(!r.ok||!d.files||!d.files.length)throw new Error(d.error||('HTTP '+r.status));
|
||||
const inp=document.getElementById('chat-input');
|
||||
for(const f of d.files)inp.value=(inp.value?inp.value.replace(/\s+$/,'')+' ':'')+'[첨부 사진: '+f.relPath+'] ';
|
||||
autoResize(inp);inp.focus();
|
||||
document.getElementById('attach-pop').classList.remove('open');
|
||||
const pane=document.getElementById('pane-files');
|
||||
if(pane&&pane.classList.contains('active'))loadFiles();
|
||||
}catch(e){
|
||||
st.style.color='#ef4444';
|
||||
st.textContent='📱 실패: '+(e.message||e);
|
||||
}
|
||||
}
|
||||
function attachPhoto(relPath){
|
||||
const inp=document.getElementById('chat-input');
|
||||
inp.value=(inp.value?inp.value.replace(/\s+$/,'')+' ':'')+'[첨부 사진: '+relPath+'] ';
|
||||
|
||||
Reference in new issue
Block a user