v4.3.19-19: 탐정 앱 hwp 파일 NextCloud/Collabora 실시간 편집 연동 + 지도탭 누락 커밋 반영

주요 변경:
- 탐정 앱의 .hwp 파일에 🌐 버튼 추가: 서버가 자동으로 hwp→odt 변환(host의
  h2orestart 필터 사용) → 사용자 소유 NextCloud(cloud.applecherry.net)의
  homeclaw-detective/{caseId}/ 폴더로 WebDAV 업로드 → Collabora Online
  편집화면으로 리다이렉트. 타이핑하는 대로 자동 저장, 다운로드/재업로드 불필요.
- NextCloud 앱 비밀번호는 vault에 저장(nextcloud.appPassword), config.json엔
  평문 없음.
- (부수적, 별도 이슈) Stirling-PDF는 이 사건의 원본 PDF가 실제 폼필드가
  없는 인쇄용 레이아웃이라 텍스트 스트림 편집이 계속 실패해서 우회 경로로
  채택함.

추가로 이전 세션에서 커밋 안 하고 넘어간 weather-app.html의 지도탭
자동전환 fix(processWindyUrl 이동 시 mapLat/mapLon 동기화 + switchCenterTab)도
같이 반영됨.
This commit is contained in:
kim committed 2026-07-27 22:56:45 +09:00
1 parent ebb605bc24
commit 6cfb2db5b1
6 files changed
+156

No files matched your search

+1
View File
@@ -327,6 +327,7 @@ const SECRET_FIELD_MAP: Array<[string[], string]> = [
[['ppt', 'pexels_key'], 'ppt.pexels_key'],
[['ppt', 'pixabay_key'], 'ppt.pixabay_key'],
[['openweather', 'api_key'], 'openweather.api_key'],
[['nextcloud', 'appPassword'], 'nextcloud.appPassword'],
[['weather', 'api_key'], 'weather.api_key'],
[['news', 'newsdata_api_key'], 'news.newsdata_api_key'],
[['nvr', 'password'], 'nvr.password'],
+110
View File
@@ -0,0 +1,110 @@
import https from 'https';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { execFile } from 'child_process';
import { getConfig } from '../../config/config';
// ─── NextCloud WebDAV upload + Collabora deep-link ────────────────────────────
// Used by the detective app's "web editor" button: uploads a case file into a
// dedicated NextCloud folder, then returns a direct-open URL. NextCloud's
// richdocuments app (already installed, wired to the Collabora container at
// col.applecherry.net) auto-opens office-type files in the browser editor —
// no query-param file-preload hacking needed, unlike Stirling-PDF.
function nextcloudCreds() {
const cfg = getConfig().getConfig().nextcloud;
if (!cfg?.baseUrl || !cfg.username || !cfg.appPassword) {
throw new Error('NextCloud is not configured (nextcloud.baseUrl/username/appPassword)');
}
const password = getConfig().resolveSecret(cfg.appPassword);
if (!password) throw new Error('NextCloud app password could not be resolved from vault');
return { baseUrl: cfg.baseUrl.replace(/\/+$/, ''), username: cfg.username, password };
}
function davRequest(method: string, davPath: string, opts: { body?: Buffer; headers?: Record<string, string> } = {}): Promise<{ status: number; body: Buffer }> {
const { baseUrl, username, password } = nextcloudCreds();
const encodedPath = davPath.split('/').map(encodeURIComponent).join('/');
const url = new URL(`/remote.php/dav/files/${encodeURIComponent(username)}/${encodedPath}`, baseUrl);
const auth = Buffer.from(`${username}:${password}`).toString('base64');
return new Promise((resolve, reject) => {
const req = https.request(url, {
method,
headers: { Authorization: `Basic ${auth}`, ...(opts.headers || {}) },
timeout: 30_000,
}, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c: Buffer) => chunks.push(c));
res.on('end', () => resolve({ status: res.statusCode || 0, body: Buffer.concat(chunks) }));
});
req.on('timeout', () => { req.destroy(); reject(new Error('WebDAV request timed out')); });
req.on('error', reject);
if (opts.body) req.end(opts.body); else req.end();
});
}
// MKCOL is not recursive in WebDAV — create each path segment in order.
// 405 (already exists) and 409 (parent race) are both treated as success.
async function ensureRemoteDir(segments: string[]): Promise<void> {
let cur = '';
for (const seg of segments) {
cur = cur ? `${cur}/${seg}` : seg;
const r = await davRequest('MKCOL', cur);
if (r.status !== 201 && r.status !== 405) {
throw new Error(`MKCOL ${cur} failed: HTTP ${r.status}`);
}
}
}
async function hwpToOdt(srcPath: string): Promise<{ path: string; cleanup: () => void }> {
const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hwp2odt-'));
await new Promise<void>((resolve, reject) => {
execFile('soffice', ['--headless', '--convert-to', 'odt', '--outdir', outDir, srcPath], { timeout: 60_000 }, (err) => {
if (err) reject(err); else resolve();
});
});
const base = path.basename(srcPath, path.extname(srcPath));
const outPath = path.join(outDir, `${base}.odt`);
if (!fs.existsSync(outPath)) throw new Error('hwp → odt conversion produced no output');
return { path: outPath, cleanup: () => fs.rmSync(outDir, { recursive: true, force: true }) };
}
async function getFileId(remotePath: string): Promise<string> {
const propBody = Buffer.from(
`<?xml version="1.0"?><d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:prop><oc:fileid/></d:prop></d:propfind>`,
);
const r = await davRequest('PROPFIND', remotePath, { body: propBody, headers: { Depth: '0', 'Content-Type': 'text/xml' } });
if (r.status !== 207) throw new Error(`PROPFIND failed: HTTP ${r.status}`);
const m = r.body.toString('utf-8').match(/<oc:fileid>(\d+)<\/oc:fileid>/);
if (!m) throw new Error('fileid not found in PROPFIND response');
return m[1];
}
// Uploads srcPath (converting .hwp -> .odt first, since Collabora has no HWP
// filter and installing one requires a JRE the container image doesn't ship)
// into /homeclaw-detective/{caseId}/ and returns the NextCloud direct-open URL.
export async function openInNextcloudEditor(srcPath: string, caseId: string): Promise<string> {
const { baseUrl } = nextcloudCreds();
let uploadPath = srcPath;
let cleanup: (() => void) | null = null;
if (/\.hwp$/i.test(srcPath)) {
const converted = await hwpToOdt(srcPath);
uploadPath = converted.path;
cleanup = converted.cleanup;
}
try {
const filename = path.basename(uploadPath);
const remoteDir = ['homeclaw-detective', caseId];
await ensureRemoteDir(remoteDir);
const remotePath = `${remoteDir.join('/')}/${filename}`;
const data = fs.readFileSync(uploadPath);
const putRes = await davRequest('PUT', remotePath, { body: data });
if (putRes.status !== 201 && putRes.status !== 204) {
throw new Error(`Upload failed: HTTP ${putRes.status}`);
}
const fileId = await getFileId(remotePath);
return `${baseUrl}/index.php/f/${fileId}`;
} finally {
cleanup?.();
}
}
+26
View File
@@ -2,6 +2,7 @@ import express from 'express';
import fs from 'fs';
import path from 'path';
import { getUserWorkspace } from '../../config/config';
import { openInNextcloudEditor } from './nextcloud-webdav';
// ─── Per-user Detective Cases ─────────────────────────────────────────────────
// Stored at <user-workspace>/.smallclaw/detective-cases.json
@@ -260,6 +261,31 @@ export function registerDetectiveRoutes(
}
});
// Uploads a case file into NextCloud (converting .hwp -> .odt first, since
// Collabora has no HWP filter) and redirects to its direct-open URL, which
// richdocuments auto-opens in the browser-based Collabora editor. Chosen
// over Stirling-PDF for documents like 고소장.hwp because it saves live
// (no download/re-upload dance) and handles the source .hwp natively.
app.get('/api/detective/nextcloud-open', async (req, res) => {
const session = getSessionUser(req);
if (!session) return res.status(401).send('Unauthorized');
const caseId = String(req.query.caseId || '');
const relPath = String(req.query.relPath || '');
const segments = relPath.split('/').filter(Boolean);
if (!/^[a-zA-Z0-9_-]+$/.test(caseId) || !segments.length || segments.some(s => s === '..' || s === '.')) {
return res.status(400).send('invalid');
}
const dir = detectiveFilesDir(session.username, caseId);
const srcPath = path.join(dir, ...segments);
if (!isPathInsideDir(dir, srcPath) || !fs.existsSync(srcPath)) return res.status(404).send('File not found');
try {
const url = await openInNextcloudEditor(srcPath, caseId);
res.redirect(url);
} catch (e: any) {
res.status(502).send('NextCloud open failed: ' + String(e?.message || e));
}
});
// ─── Network recon tools (mtr/dig/whois/openssl/nmap/nikto/gobuster/nc/NVD) ──
// Traceroute (mtr)
+5
View File
@@ -393,6 +393,11 @@ export interface SmallClawConfig {
openweather?: {
api_key?: string;
};
nextcloud?: {
baseUrl?: string;
username?: string;
appPassword?: string;
};
weather?: {
api_key?: string;
};
+2
View File
@@ -1323,6 +1323,7 @@ function onEvidenceSortChange(){
// structure stays visible instead of being flattened away.
function renderFileRow(f,name){
const isPdf=/\.pdf$/i.test(f.name);
const isHwp=/\.hwp$/i.test(f.name);
const isText=DT_TEXT_EDIT_EXTS.test(f.name);
const icon=EVIDENCE_CATEGORY_ICONS[f.category]||'📦';
const nameHtml=isText
@@ -1333,6 +1334,7 @@ function renderFileRow(f,name){
${nameHtml}
<span style="font-size:10px;color:var(--muted);flex-shrink:0">${fmtFileSize(f.size)}</span>
${isPdf?`<a href="/pdf-editor-open?caseId=${encodeURIComponent(currentCaseId)}" target="_blank" class="dt-cl-del" style="opacity:.7" title="PDF 편집기를 새 창에서 엽니다. 이 파일은 자동으로 열리지 않으니(외부 편집기 한계), 편집기의 업로드 버튼에서 이 파일을 직접 선택하세요. 수정 후 다운로드하면 사건 폴더에 자동 저장됩니다.">✏️</a>`:''}
${isHwp?`<a href="/api/detective/nextcloud-open?caseId=${encodeURIComponent(currentCaseId)}&relPath=${encodeURIComponent(f.relPath)}" target="_blank" class="dt-cl-del" style="opacity:.7" title="NextCloud(Collabora)에서 바로 편집합니다. 새 창이 열리면 그 문서에 즉시 편집 가능하고, 입력하는 대로 자동 저장됩니다(다운로드 불필요).">🌐</a>`:''}
${(f.category==='photo'||isText)?`<button class="dt-cl-del" onclick="dtQuickAddToTimeline('${escJsAttr(f.relPath)}',this)" title="날짜 인식 (타임라인 탭에서 확인 후 추가)">🕐+</button>
<button class="dt-cl-del" onclick="dtManualDateSuggest('${escJsAttr(f.relPath)}',this)" title="날짜 인식">📅</button>`:''}
<button class="dt-cl-del" onclick="deleteFile('${escJsAttr(f.relPath)}')" title="삭제">✕</button>
+12
View File
@@ -699,8 +699,20 @@ function processWindyUrl(text){
mapOverlay=ovM[1];
document.querySelectorAll('.wt-ov').forEach(b=>b.classList.toggle('active',b.dataset.ov===mapOverlay));
}
// Keep mapLat/mapLon/mapZoom/search-bar in sync so the move actually sticks
// (otherwise a reload snaps back to the old default, looking like it "undid" itself).
const latM=url.match(/[?&]lat=(-?[\d.]+)/),lonM=url.match(/[?&]lon=(-?[\d.]+)/),zoomM=url.match(/[?&]zoom=(-?[\d.]+)/);
if(latM&&lonM){
mapLat=parseFloat(latM[1]);mapLon=parseFloat(lonM[1]);
if(zoomM)mapZoom=parseFloat(zoomM[1]);
const locInput=document.getElementById('map-loc');
if(locInput)locInput.value=`${mapLat},${mapLon}`;
}
document.getElementById('map-loading').classList.remove('hidden');
document.getElementById('windy-frame').src=url;
// A "move the map" reply is pointless if the user is still looking at a photo tab —
// switch them to the map tab so the move is actually visible, not just described in text.
switchCenterTab('map');
return true;
}