feat(slicer): 💾 프로젝트에 저장 — 슬라이싱 결과 gcode를 작업실 프로젝트 출력/ 폴더에 읽을 수 있는 이름으로 복사(원본 유지, 중복 이름은 시각 부착), 파일 탭 자동 새로고침
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a35f811d36
commit
d19a6b6b06
4 files changed
+115
-3
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import express, { Express, Request, Response } from 'express';
|
||||
import { PRINT3D_DIRS } from './workshop-layout';
|
||||
import { PRINT3D_DIRS, saveDirs, projectDir } from './workshop-layout';
|
||||
import { sanitizePathSegment } from './case-storage';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
@@ -54,6 +55,32 @@ export function gcodePath(workspacePath: string, filename: string): string {
|
||||
return candidates[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 슬라이싱 결과 gcode를 작업실 프로젝트의 출력/ 폴더에 사본으로 저장한다(2026-09-30).
|
||||
* 웹 슬라이서 결과는 print3d/K2웹슬라이서/k2ui_<숫자>.gcode 라는 임시 이름이라 어느 부품의 출력인지
|
||||
* 알 수 없고 작업실 파일 탭에도 안 보인다. 프로젝트 출력/ 에 읽을 수 있는 이름으로 남기면 파일 탭에서
|
||||
* 보이고 부품과 함께 관리된다. 원본은 그대로 둔다(복사). 같은 이름이 있으면 덮어쓰지 않고 시각을 붙인다.
|
||||
*/
|
||||
export function saveGcodeToProject(
|
||||
workspacePath: string, filename: string, projectId: string, name?: string, now = Date.now(),
|
||||
): { ok: true; relPath: string; name: string } | { ok: false; status: number; error: string } {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(projectId)) return { ok: false, status: 400, error: '잘못된 projectId.' };
|
||||
let src: string;
|
||||
try { src = gcodePath(workspacePath, filename); } catch (e: any) { return { ok: false, status: 400, error: String(e?.message || e) }; }
|
||||
if (!fs.existsSync(src)) return { ok: false, status: 404, error: 'gcode 파일이 없습니다.' };
|
||||
if (!fs.existsSync(projectDir(workspacePath, projectId))) return { ok: false, status: 404, error: '프로젝트 폴더가 없습니다.' };
|
||||
|
||||
// 빈 이름은 sanitizePathSegment가 '_'로 바꿔 버려서 || 폴백이 안 통한다 — 먼저 비었는지 본다.
|
||||
const cleaned = String(name || '').trim().replace(/\.gcode$/i, '').replace(/[\\/]+/g, '_');
|
||||
const stem = cleaned ? sanitizePathSegment(cleaned) : filename.replace(/\.gcode$/i, '');
|
||||
const outDir = saveDirs(workspacePath, projectId).outDir;
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
let fileName = `${stem}.gcode`;
|
||||
if (fs.existsSync(path.join(outDir, fileName))) fileName = `${stem}_${now}.gcode`;
|
||||
fs.copyFileSync(src, path.join(outDir, fileName));
|
||||
return { ok: true, relPath: `출력/${fileName}`, name: fileName };
|
||||
}
|
||||
|
||||
export function registerK2Routes(app: Express): void {
|
||||
// Moonraker 상태(print_stats/virtual_sdcard)를 대시보드 위젯용으로 요약해서 반환 —
|
||||
// 브라우저가 K2 LAN IP를 직접 못 치니(HTTPS 페이지에서 mixed-content) 서버가 대신 조회.
|
||||
@@ -301,6 +328,20 @@ export function registerK2Routes(app: Express): void {
|
||||
}
|
||||
});
|
||||
|
||||
// 슬라이싱 결과 gcode를 작업실 프로젝트의 출력/ 폴더에 사본으로 저장.
|
||||
app.post('/api/k2/save-to-project', express.json(), (req: Request, res: Response) => {
|
||||
const user = (req as any).user;
|
||||
if (!user) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const r = saveGcodeToProject(
|
||||
getUserWorkspace(user.username),
|
||||
String(req.body?.filename || '').trim(),
|
||||
String(req.body?.projectId || '').trim(),
|
||||
req.body?.name === undefined ? undefined : String(req.body.name),
|
||||
);
|
||||
if (!r.ok) return res.status(r.status).json({ error: r.error });
|
||||
res.json({ success: true, relPath: r.relPath, name: r.name });
|
||||
});
|
||||
|
||||
// 생성된 gcode를 Moonraker에 업로드(슬라이스와 분리된 명시적 전송 단계).
|
||||
app.post('/api/k2/upload', express.json(), async (req: Request, res: Response) => {
|
||||
const user = (req as any).user;
|
||||
|
||||
@@ -45,3 +45,41 @@ describe('gcodePath', () => {
|
||||
assert.throws(() => gcodePath(ws, 'x.txt'), /잘못된 gcode 파일명/);
|
||||
});
|
||||
});
|
||||
|
||||
import { saveGcodeToProject } from '../src/gateway/routes/routes-k2';
|
||||
|
||||
describe('saveGcodeToProject — 슬라이싱 결과를 프로젝트 출력/ 폴더로 복사', () => {
|
||||
const proj = path.join(ws, 'workshop', 'proj_abc');
|
||||
fs.mkdirSync(proj, { recursive: true });
|
||||
fs.writeFileSync(path.join(newDir, 'k2ui_10.gcode'), 'G1 X1');
|
||||
|
||||
test('읽을 수 있는 이름으로 출력/ 에 복사하고 원본은 남긴다', () => {
|
||||
const r = saveGcodeToProject(ws, 'k2ui_10.gcode', 'proj_abc', 'body_a_서포트');
|
||||
assert.equal(r.ok, true);
|
||||
if (r.ok) {
|
||||
assert.equal(r.relPath, '출력/body_a_서포트.gcode');
|
||||
assert.equal(fs.readFileSync(path.join(proj, '출력', 'body_a_서포트.gcode'), 'utf8'), 'G1 X1');
|
||||
}
|
||||
assert.equal(fs.existsSync(path.join(newDir, 'k2ui_10.gcode')), true);
|
||||
});
|
||||
|
||||
test('같은 이름이면 덮어쓰지 않고 시각을 붙인다', () => {
|
||||
const r = saveGcodeToProject(ws, 'k2ui_10.gcode', 'proj_abc', 'body_a_서포트', 111);
|
||||
assert.equal(r.ok && r.name, 'body_a_서포트_111.gcode');
|
||||
});
|
||||
|
||||
test('이름이 비었거나 .gcode·경로 문자가 섞여도 안전한 이름으로 만든다', () => {
|
||||
const empty = saveGcodeToProject(ws, 'k2ui_10.gcode', 'proj_abc', ' ');
|
||||
assert.equal(empty.ok && empty.name, 'k2ui_10.gcode');
|
||||
const evil = saveGcodeToProject(ws, 'k2ui_10.gcode', 'proj_abc', '../../etc/x.gcode');
|
||||
assert.equal(evil.ok, true);
|
||||
if (evil.ok) assert.equal(evil.name.includes('/'), false);
|
||||
});
|
||||
|
||||
test('없는 gcode·없는 프로젝트·잘못된 id는 거부한다', () => {
|
||||
const a = saveGcodeToProject(ws, 'k2ui_nope.gcode', 'proj_abc', 'x'); assert.equal(!a.ok && a.status, 404);
|
||||
const b = saveGcodeToProject(ws, 'k2ui_10.gcode', 'proj_none', 'x'); assert.equal(!b.ok && b.status, 404);
|
||||
const c = saveGcodeToProject(ws, 'k2ui_10.gcode', '../x', 'x'); assert.equal(!c.ok && c.status, 400);
|
||||
const d = saveGcodeToProject(ws, '../k2ui_10.gcode', 'proj_abc', 'x'); assert.equal(!d.ok && d.status, 400);
|
||||
});
|
||||
});
|
||||
@@ -48,7 +48,7 @@ function syncFilesSoon(){
|
||||
}
|
||||
try{
|
||||
const _bc=new BroadcastChannel('workshop-files');
|
||||
_bc.onmessage=(e)=>{if(e.data&&e.data.type==='stl-saved'){_filesSyncAt=0;syncFilesSoon();}};
|
||||
_bc.onmessage=(e)=>{if(e.data&&(e.data.type==='stl-saved'||e.data.type==='gcode-saved')){_filesSyncAt=0;syncFilesSoon();}};
|
||||
}catch{/* BroadcastChannel 미지원 */}
|
||||
window.addEventListener('focus',syncFilesSoon);
|
||||
document.addEventListener('visibilitychange',()=>{if(!document.hidden)syncFilesSoon();});
|
||||
|
||||
@@ -910,7 +910,8 @@
|
||||
`✅ 슬라이스 완료: <b>${curGcodeFile}</b><br>` +
|
||||
`예상 시간 <b>${fmtDuration(d.printTimeSec)}</b> · 필라멘트 <b>${filamentStr}</b> · <b>${layers.length}</b>층 · 모델 <b>${models.length}</b>종 · 인스턴스 <b>${instances.length}</b>개 · 소재 ${d.material}<br>` +
|
||||
`<button class="sv-btn green" id="sv-upload-btn" onclick="window.__slicerUpload()">📤 K2 업로드</button> ` +
|
||||
`<button class="sv-btn" id="sv-print-btn" onclick="window.__slicerPrint()" disabled>🖨️ 출력 시작</button>`
|
||||
`<button class="sv-btn" id="sv-print-btn" onclick="window.__slicerPrint()" disabled>🖨️ 출력 시작</button>` +
|
||||
(workshopProjectId ? ` <button class="sv-btn" id="sv-save-btn" onclick="window.__slicerSaveProject()">💾 프로젝트에 저장</button>` : '')
|
||||
);
|
||||
} catch (e) {
|
||||
setErr('실패: ' + e.message);
|
||||
@@ -931,6 +932,25 @@
|
||||
} catch (e) { setErr('업로드 실패: ' + e.message); }
|
||||
}
|
||||
|
||||
// 슬라이싱 결과를 작업실 프로젝트의 출력/ 폴더에 읽을 수 있는 이름으로 복사한다.
|
||||
async function saveGcodeToProject() {
|
||||
if (!curGcodeFile || !workshopProjectId) return;
|
||||
setErr('');
|
||||
const stamp = new Date().toISOString().slice(0, 16).replace('T', '_').replace(':', '');
|
||||
const base = loadedModelNames.length > 1 ? `${loadedModelNames[0]}_외${loadedModelNames.length - 1}` : (loadedModelNames[0] || 'plate');
|
||||
const name = prompt('프로젝트 출력 폴더에 저장할 G-code 이름 (.gcode는 자동)', `${base}_${stamp}`);
|
||||
if (name === null) return;
|
||||
try {
|
||||
const r = await fetch('/api/k2/save-to-project', { method: 'POST', headers: { 'Content-Type': 'application/json', ...authH() }, body: JSON.stringify({ filename: curGcodeFile, projectId: workshopProjectId, name }) });
|
||||
const d = await r.json();
|
||||
if (!r.ok || !d.success) throw new Error(d.error || ('HTTP ' + r.status));
|
||||
const btn = barEl.querySelector('#sv-save-btn');
|
||||
if (btn) { btn.textContent = '✅ 저장됨: ' + d.relPath; btn.disabled = true; }
|
||||
// 작업실 파일 탭이 열려 있으면 목록을 새로고침하게 알린다(STL 저장과 같은 채널).
|
||||
try { const bc = new BroadcastChannel('workshop-files'); bc.postMessage({ type: 'gcode-saved', path: d.relPath }); bc.close(); } catch { /* noop */ }
|
||||
} catch (e) { setErr('프로젝트 저장 실패: ' + e.message); }
|
||||
}
|
||||
|
||||
function prevInfoWithUploaded() {
|
||||
const info = barEl.querySelector('#sv-info');
|
||||
let html = info.innerHTML;
|
||||
@@ -1160,6 +1180,17 @@
|
||||
// 깨지므로. JSON이 아니면 예전 형식(쉼표 join)으로 폴백 해석해 옛 링크도 유지.
|
||||
// /api/cad/file?path= 로 다운로드해 loadModel()에 그대로 넣는다 —
|
||||
// 파일 input change 핸들러(1013줄 근처)와 배치 로직을 공유.
|
||||
// 작업실에서 열렸을 때의 프로젝트 문맥(2026-09-30) — 슬라이싱 결과를 그 프로젝트 출력/ 폴더에 저장하는 버튼용.
|
||||
let workshopProjectId = '';
|
||||
let loadedModelNames = [];
|
||||
function noteWorkshopContext(paths) {
|
||||
for (const p of paths) {
|
||||
const m = /^workshop\/([A-Za-z0-9_-]+)\//.exec(p);
|
||||
if (m) { workshopProjectId = m[1]; break; }
|
||||
}
|
||||
loadedModelNames = paths.map((p) => (p.split('/').pop() || p).replace(/\.(stl|3mf)$/i, ''));
|
||||
}
|
||||
|
||||
async function loadFromUrlParams() {
|
||||
const loadParam = new URLSearchParams(location.search).get('load');
|
||||
if (!loadParam) return;
|
||||
@@ -1170,6 +1201,7 @@
|
||||
} catch { paths = null; }
|
||||
if (!paths) paths = loadParam.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
if (!paths.length) return;
|
||||
noteWorkshopContext(paths);
|
||||
setInfo(`📂 서버에서 ${paths.length}개 파일 불러오는 중…`);
|
||||
let placed = 0;
|
||||
for (const p of paths) {
|
||||
@@ -1203,6 +1235,7 @@
|
||||
// 슬라이더/버튼/배치 콜백을 글로벌로 노출(인라인 onclick 호환).
|
||||
window.__slicerSlice = runSlice;
|
||||
window.__slicerUpload = uploadGcode;
|
||||
window.__slicerSaveProject = saveGcodeToProject;
|
||||
window.__slicerPrint = startPrint;
|
||||
window.__slicerLayer = (v) => {
|
||||
const n = Number(v);
|
||||
|
||||
Reference in new issue
Block a user