v4.3.38: 법률 어시스턴트 앱에 사건(사건 기록) 관리 기능 추가
- 채팅창 파일 첨부 버튼 추가 (PDF/TXT, 회계사 앱과 같은 /api/upload/file 재사용, pdf_read로 계약서 분석 — 스킬 프롬프트엔 이미 방법론이 있었는데 버튼만 없었음) - 탐정 앱의 "사건" 관리를 법률 앱에 이식: 사건 목록(검색/정렬) + 사건별 메모· 체크리스트·타임라인·첨부자료·제출서류 탭 + 사건별 독립 AI 대화 세션 (다른 사건 컨텍스트가 안 섞임, 탐정 앱과 동일 패턴) - PDF 편집기(Stirling-PDF)·Collabora 문서 편집 연동도 그대로 이식 — 사건 폴더에 자동 저장됨 - 백엔드는 탐정 앱 기존 코드를 건드리지 않고 새 공용 모듈(case-storage.ts)로 일반화 — appType 파라미터로 detective/lawyer 둘 다 같은 로직 재사용, 탐정 앱 데이터·동작은 그대로 유지(회귀 테스트로 확인) - 사진 자동 날짜인식(탐정 앱 전용, 카톡 캡처 등에서 날짜 추출) 등 법률 사건과 무관한 기능은 이식 범위에서 제외 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b61fcd1889
commit
1c2c5e23bc
4 files changed
+1421
-24
No files matched your search
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* case-storage.ts
|
||||
* Generic per-user "case" (사건) storage shared by any app that needs a list of
|
||||
* named cases each with its own attached-file folder — detective and lawyer so
|
||||
* far. Detective's own routes-detective.ts keeps its original, untouched
|
||||
* internal copies of this logic (no behavior change to an already-shipping
|
||||
* feature); this module exists so a SECOND app doesn't have to duplicate it
|
||||
* again — new case-backed apps should import from here instead of copying
|
||||
* routes-detective.ts a third time.
|
||||
*
|
||||
* Storage layout (identical shape to detective's, parameterized by appType):
|
||||
* cases list: <user-workspace>/.smallclaw/<appType>-cases.json
|
||||
* case files: <user-workspace>/<appType>/<caseId>/
|
||||
*/
|
||||
import express from 'express';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import { getUserWorkspace } from '../../config/config';
|
||||
|
||||
export function casesPath(username: string, appType: string): string {
|
||||
return path.join(getUserWorkspace(username), '.smallclaw', `${appType}-cases.json`);
|
||||
}
|
||||
|
||||
export function caseFilesDir(username: string, appType: string, caseId: string): string {
|
||||
return path.join(getUserWorkspace(username), appType, caseId);
|
||||
}
|
||||
|
||||
export function sanitizePathSegment(seg: string): string {
|
||||
const s = seg.replace(/[\x00-\x1f\x7f:*?"<>|]/g, '_').trim();
|
||||
if (!s || s === '.' || s === '..') return '_';
|
||||
return s;
|
||||
}
|
||||
|
||||
// Folder uploads send a relative path (e.g. "2024/contract.pdf") as the filename.
|
||||
// Each segment is sanitized and the real directory structure recreated under the
|
||||
// case folder, so a whole subfolder can later be deleted/downloaded as a unit.
|
||||
export function resolveUploadPath(baseDir: string, originalName: string): { relPath: string; absPath: string } {
|
||||
const rawSegments = String(originalName || 'upload').split(/[\\/]+/).filter(Boolean);
|
||||
const segments = (rawSegments.length ? rawSegments : ['upload']).map(sanitizePathSegment);
|
||||
const folderSegs = segments.slice(0, -1);
|
||||
let fileSeg = segments[segments.length - 1] || 'upload';
|
||||
const dir = path.join(baseDir, ...folderSegs);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
if (fs.existsSync(path.join(dir, fileSeg))) {
|
||||
const ext = path.extname(fileSeg);
|
||||
const stem = path.basename(fileSeg, ext);
|
||||
fileSeg = `${stem}_${Date.now()}${ext}`;
|
||||
}
|
||||
const relPath = [...folderSegs, fileSeg].join('/');
|
||||
return { relPath, absPath: path.join(dir, fileSeg) };
|
||||
}
|
||||
|
||||
export function walkCaseFiles(dir: string, relBase = ''): Array<{ relPath: string; name: string; size: number; mtime: string }> {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
const out: Array<{ relPath: string; name: string; size: number; mtime: string }> = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const abs = path.join(dir, entry.name);
|
||||
const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) {
|
||||
out.push(...walkCaseFiles(abs, rel));
|
||||
} else if (entry.isFile()) {
|
||||
const stat = fs.statSync(abs);
|
||||
out.push({ relPath: rel, name: entry.name, size: stat.size, mtime: stat.mtime.toISOString() });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const FILE_CATEGORIES: Record<string, string> = {
|
||||
jpg: 'photo', jpeg: 'photo', png: 'photo', gif: 'photo', webp: 'photo', bmp: 'photo', heic: 'photo', heif: 'photo', tiff: 'photo',
|
||||
mp4: 'video', mov: 'video', avi: 'video', mkv: 'video', webm: 'video', m4v: 'video', wmv: 'video',
|
||||
pdf: 'document', doc: 'document', docx: 'document', xls: 'document', xlsx: 'document', ppt: 'document', pptx: 'document', txt: 'document', hwp: 'document', hwpx: 'document',
|
||||
};
|
||||
export function fileCategory(name: string): string {
|
||||
const ext = path.extname(name).slice(1).toLowerCase();
|
||||
return FILE_CATEGORIES[ext] || 'other';
|
||||
}
|
||||
|
||||
// ── Shared WOPI token store (Collabora editor callbacks) ──────────────────────
|
||||
// Tokens are ephemeral, in-memory, and keyed only by a random string — the app
|
||||
// that minted a token doesn't matter to the callback routes below, since they
|
||||
// only ever look up entry.absPath. One map covers every case-backed app.
|
||||
export interface WopiTokenEntry {
|
||||
username: string;
|
||||
absPath: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
export const wopiTokens = new Map<string, WopiTokenEntry>();
|
||||
export const WOPI_TOKEN_TTL_MS = 8 * 60 * 60 * 1000; // 8h — generous for a long editing session
|
||||
|
||||
export function wopiCleanupExpired(): void {
|
||||
const now = Date.now();
|
||||
for (const [token, entry] of wopiTokens) {
|
||||
if (entry.expiresAt < now) wopiTokens.delete(token);
|
||||
}
|
||||
}
|
||||
|
||||
export function mintWopiToken(username: string, absPath: string): string {
|
||||
wopiCleanupExpired();
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
wopiTokens.set(token, { username, absPath, expiresAt: Date.now() + WOPI_TOKEN_TTL_MS });
|
||||
return token;
|
||||
}
|
||||
|
||||
// Registers the 3 WOPI callback routes Collabora calls directly (no session
|
||||
// cookie — the token itself is the auth) under the given prefix, e.g.
|
||||
// registerWopiRoutes(app, '/api/lawyer') → /api/lawyer/wopi/files/:token etc.
|
||||
// Both detective's and lawyer's collabora-open handlers mint tokens into the
|
||||
// same wopiTokens map above, so either prefix's callbacks work regardless of
|
||||
// which app opened the editor.
|
||||
export function registerWopiRoutes(app: express.Application, prefix: string): void {
|
||||
app.get(`${prefix}/wopi/files/:token`, (req, res) => {
|
||||
const entry = wopiTokens.get(req.params.token);
|
||||
if (!entry || entry.expiresAt < Date.now()) return res.status(404).json({ error: 'Unknown or expired token' });
|
||||
if (!fs.existsSync(entry.absPath)) return res.status(404).json({ error: 'File not found' });
|
||||
const stat = fs.statSync(entry.absPath);
|
||||
res.json({
|
||||
BaseFileName: path.basename(entry.absPath),
|
||||
Size: stat.size,
|
||||
UserId: entry.username,
|
||||
OwnerId: entry.username,
|
||||
UserCanWrite: true,
|
||||
UserFriendlyName: entry.username,
|
||||
});
|
||||
});
|
||||
app.get(`${prefix}/wopi/files/:token/contents`, (req, res) => {
|
||||
const entry = wopiTokens.get(req.params.token);
|
||||
if (!entry || entry.expiresAt < Date.now()) return res.status(404).end();
|
||||
if (!fs.existsSync(entry.absPath)) return res.status(404).end();
|
||||
const stream = fs.createReadStream(entry.absPath);
|
||||
stream.on('error', () => { if (!res.headersSent) res.status(500).end(); });
|
||||
stream.pipe(res);
|
||||
});
|
||||
app.post(`${prefix}/wopi/files/:token/contents`, express.raw({ type: '*/*', limit: '200mb' }), (req: any, res: any) => {
|
||||
const entry = wopiTokens.get(req.params.token);
|
||||
if (!entry || entry.expiresAt < Date.now()) return res.status(404).json({ error: 'Unknown or expired token' });
|
||||
try {
|
||||
fs.writeFileSync(entry.absPath, req.body);
|
||||
res.json({ LastModifiedTime: new Date().toISOString() });
|
||||
} catch (e: any) {
|
||||
res.status(500).json({ error: String(e?.message || e) });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
/**
|
||||
* routes-lawyer-cases.ts
|
||||
* Lawyer app: case (사건) list + per-case attached documents, mirroring
|
||||
* detective-app's case management (case-storage.ts holds the shared logic —
|
||||
* see that file's header for why detective's own copy was left untouched
|
||||
* rather than refactored in place).
|
||||
*
|
||||
* In scope: case CRUD, file upload/list/delete/download, PDF edit (Stirling-PDF,
|
||||
* shared with detective — see server.ts's /pdf-editor proxy) and Collabora edit
|
||||
* for docx/hwp. Out of scope: detective's EXIF/vision-based auto date-recognition
|
||||
* (routes-detective-dates.ts) — that pipeline is built around recognizing dates
|
||||
* inside evidence photos (KakaoTalk screenshots, receipts), which doesn't map to
|
||||
* legal-case timelines where dates are typed in directly, not extracted from photos.
|
||||
*/
|
||||
import express from 'express';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import archiver from 'archiver';
|
||||
import { execFile } from 'child_process';
|
||||
import { getConfig } from '../../config/config';
|
||||
import {
|
||||
casesPath, caseFilesDir, resolveUploadPath, walkCaseFiles, fileCategory, mintWopiToken,
|
||||
} from './case-storage';
|
||||
|
||||
const APP_TYPE = 'lawyer';
|
||||
|
||||
export function registerLawyerCaseRoutes(
|
||||
app: express.Application,
|
||||
getSessionUser: (req: express.Request) => any,
|
||||
isPathInsideDir: (base: string, target: string) => boolean,
|
||||
): void {
|
||||
|
||||
app.get('/api/lawyer/cases', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const p = casesPath(session.username, APP_TYPE);
|
||||
if (!fs.existsSync(p)) return res.json({ cases: [] });
|
||||
try { res.json(JSON.parse(fs.readFileSync(p, 'utf-8'))); } catch { res.json({ cases: [] }); }
|
||||
});
|
||||
|
||||
app.put('/api/lawyer/cases', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const { cases } = req.body || {};
|
||||
if (!Array.isArray(cases)) return res.status(400).json({ error: 'cases array required' });
|
||||
const p = casesPath(session.username, APP_TYPE);
|
||||
fs.mkdirSync(path.dirname(p), { recursive: true });
|
||||
const tmp = `${p}.tmp`;
|
||||
fs.writeFileSync(tmp, JSON.stringify({ cases }, null, 2), 'utf-8');
|
||||
fs.renameSync(tmp, p);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
app.get('/api/lawyer/files', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const caseId = String(req.query.caseId || '');
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(caseId)) return res.status(400).json({ error: 'invalid caseId' });
|
||||
const dir = caseFilesDir(session.username, APP_TYPE, caseId);
|
||||
const files = walkCaseFiles(dir).map(e => {
|
||||
const segs = e.relPath.split('/');
|
||||
return {
|
||||
name: e.name,
|
||||
relPath: e.relPath,
|
||||
folder: segs.length > 1 ? segs[0] : '',
|
||||
size: e.size,
|
||||
mtime: e.mtime,
|
||||
url: `/api/files/${APP_TYPE}/${caseId}/${segs.map(encodeURIComponent).join('/')}`,
|
||||
category: fileCategory(e.name),
|
||||
};
|
||||
});
|
||||
res.json({ files });
|
||||
});
|
||||
|
||||
app.post('/api/lawyer/upload', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) { res.status(401).json({ success: false, error: 'Unauthorized' }); return; }
|
||||
const caseId = String(req.query.caseId || '');
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(caseId)) { res.status(400).json({ success: false, error: 'invalid caseId' }); return; }
|
||||
const contentType = String(req.headers['content-type'] || '');
|
||||
if (!contentType.includes('multipart/form-data')) {
|
||||
res.status(400).json({ success: false, error: 'Content-Type must be multipart/form-data' }); return;
|
||||
}
|
||||
const boundary = contentType.split('boundary=')[1];
|
||||
if (!boundary) { res.status(400).json({ success: false, error: 'Missing boundary' }); return; }
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
req.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
req.on('end', () => {
|
||||
const raw = Buffer.concat(chunks).toString('binary');
|
||||
const boundaryDelim = '--' + boundary;
|
||||
|
||||
let filename = 'upload.bin';
|
||||
let filetype = 'application/octet-stream';
|
||||
let fileData: Buffer | null = null;
|
||||
|
||||
const parts = raw.split(boundaryDelim);
|
||||
for (const part of parts) {
|
||||
if (!part || part.trim() === '--' || part.trim() === '') continue;
|
||||
const headerEnd = part.indexOf('\r\n\r\n');
|
||||
if (headerEnd === -1) continue;
|
||||
const header = part.substring(0, headerEnd);
|
||||
if (!header.includes('name="file"')) continue;
|
||||
|
||||
const fnMatch = header.match(/filename\*=UTF-8''([^\r\n]+)/i)
|
||||
?? header.match(/filename="([^"]+)"/);
|
||||
if (fnMatch) {
|
||||
const raw8 = decodeURIComponent(fnMatch[1]) === fnMatch[1]
|
||||
? Buffer.from(fnMatch[1], 'binary').toString('utf-8')
|
||||
: decodeURIComponent(fnMatch[1]);
|
||||
filename = raw8;
|
||||
}
|
||||
const ctMatch = header.match(/Content-Type:\s*([^\r\n]+)/i);
|
||||
if (ctMatch) filetype = ctMatch[1].trim();
|
||||
|
||||
const bodyStart = headerEnd + 4;
|
||||
const bodyEnd = part.lastIndexOf('\r\n');
|
||||
if (bodyEnd <= bodyStart) continue;
|
||||
|
||||
fileData = Buffer.from(part.substring(bodyStart, bodyEnd), 'binary');
|
||||
break;
|
||||
}
|
||||
|
||||
if (!fileData) { res.status(400).json({ success: false, error: 'No file found in upload' }); return; }
|
||||
if (fileData.length > 50 * 1024 * 1024) { res.status(400).json({ success: false, error: 'File too large (max 50MB)' }); return; }
|
||||
|
||||
const dir = caseFilesDir(session.username, APP_TYPE, caseId);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const { relPath, absPath } = resolveUploadPath(dir, filename);
|
||||
fs.writeFileSync(absPath, fileData);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
name: path.basename(relPath),
|
||||
relPath,
|
||||
size: fileData.length,
|
||||
type: filetype,
|
||||
url: `/api/files/${APP_TYPE}/${caseId}/${relPath.split('/').map(encodeURIComponent).join('/')}`,
|
||||
category: fileCategory(relPath),
|
||||
});
|
||||
});
|
||||
req.on('error', (err: any) => { res.status(500).json({ success: false, error: String(err?.message || err) }); });
|
||||
});
|
||||
|
||||
app.delete('/api/lawyer/files', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const caseId = String(req.body?.caseId || '');
|
||||
const relPath = String(req.body?.relPath || req.body?.name || '');
|
||||
const segments = relPath.split('/').filter(Boolean);
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(caseId) || !segments.length || segments.some(s => s === '..' || s === '.')) {
|
||||
return res.status(400).json({ error: 'invalid' });
|
||||
}
|
||||
const dir = caseFilesDir(session.username, APP_TYPE, caseId);
|
||||
const targetPath = path.join(dir, ...segments);
|
||||
if (!isPathInsideDir(dir, targetPath)) return res.status(403).json({ error: 'Forbidden' });
|
||||
if (!fs.existsSync(targetPath)) { res.json({ success: true, alreadyGone: true }); return; }
|
||||
try {
|
||||
const stat = fs.statSync(targetPath);
|
||||
if (stat.isDirectory()) fs.rmSync(targetPath, { recursive: true, force: true });
|
||||
else fs.unlinkSync(targetPath);
|
||||
} catch (e: any) {
|
||||
res.status(500).json({ success: false, error: String(e?.message || e) }); return;
|
||||
}
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
app.get('/api/lawyer/files/download-folder', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) { res.status(401).json({ error: 'Unauthorized' }); return; }
|
||||
const caseId = String(req.query.caseId || '');
|
||||
const folder = String(req.query.folder || '');
|
||||
const segments = folder.split('/').filter(Boolean);
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(caseId) || !segments.length || segments.some(s => s === '..' || s === '.')) {
|
||||
res.status(400).json({ error: 'invalid' }); return;
|
||||
}
|
||||
const dir = caseFilesDir(session.username, APP_TYPE, caseId);
|
||||
const targetPath = path.join(dir, ...segments);
|
||||
if (!isPathInsideDir(dir, targetPath)) { res.status(403).json({ error: 'Forbidden' }); return; }
|
||||
if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
|
||||
res.status(404).json({ error: 'Folder not found' }); return;
|
||||
}
|
||||
const zipName = `${segments[segments.length - 1]}.zip`;
|
||||
const encodedName = encodeURIComponent(zipName);
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${encodedName}"; filename*=UTF-8''${encodedName}`);
|
||||
const archive = archiver('zip', { zlib: { level: 9 } });
|
||||
archive.on('error', (err: Error) => {
|
||||
if (!res.headersSent) res.status(500).json({ error: String(err.message || err) });
|
||||
});
|
||||
archive.pipe(res);
|
||||
archive.directory(targetPath, false);
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
// Overwrites a text document (.txt/.md/.csv) with UTF-8 content — same
|
||||
// encoding-normalization use case as detective's version.
|
||||
app.put('/api/lawyer/files/content', (req, res) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) return res.status(401).json({ error: 'Unauthorized' });
|
||||
const caseId = String(req.body?.caseId || '');
|
||||
const relPath = String(req.body?.relPath || '');
|
||||
const content = req.body?.content;
|
||||
const segments = relPath.split('/').filter(Boolean);
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(caseId) || !segments.length || segments.some(s => s === '..' || s === '.') || typeof content !== 'string') {
|
||||
return res.status(400).json({ error: 'invalid' });
|
||||
}
|
||||
const dir = caseFilesDir(session.username, APP_TYPE, caseId);
|
||||
const targetPath = path.join(dir, ...segments);
|
||||
if (!isPathInsideDir(dir, targetPath)) return res.status(403).json({ error: 'Forbidden' });
|
||||
if (!fs.existsSync(targetPath)) return res.status(404).json({ error: 'File not found' });
|
||||
try {
|
||||
fs.writeFileSync(targetPath, content, 'utf-8');
|
||||
const stat = fs.statSync(targetPath);
|
||||
res.json({ success: true, size: stat.size, mtime: stat.mtime.toISOString() });
|
||||
} catch (e: any) {
|
||||
res.status(500).json({ error: String(e?.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
// Opens a case file in Collabora directly (no NextCloud) — same WOPI-host
|
||||
// approach as detective's collabora-open, sharing the same token map so
|
||||
// either app's callback prefix works. .hwp is converted to .odt once
|
||||
// (Collabora has no HWP filter); .odt opens as-is.
|
||||
app.get('/api/lawyer/collabora-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 = caseFilesDir(session.username, APP_TYPE, caseId);
|
||||
const srcPath = path.join(dir, ...segments);
|
||||
if (!isPathInsideDir(dir, srcPath) || !fs.existsSync(srcPath)) return res.status(404).send('File not found');
|
||||
|
||||
const collaboraCfg = (getConfig().getConfig() as any).collabora || {};
|
||||
if (!collaboraCfg.baseUrl || !collaboraCfg.publicUrl) {
|
||||
return res.status(500).send('Collabora is not configured (collabora.baseUrl/publicUrl)');
|
||||
}
|
||||
|
||||
try {
|
||||
let editPath = srcPath;
|
||||
if (/\.hwp$/i.test(srcPath)) {
|
||||
const outDir = path.dirname(srcPath);
|
||||
const base = path.basename(srcPath, path.extname(srcPath));
|
||||
const odtPath = path.join(outDir, `${base}.odt`);
|
||||
if (!fs.existsSync(odtPath)) {
|
||||
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();
|
||||
});
|
||||
});
|
||||
if (!fs.existsSync(odtPath)) throw new Error('hwp → odt 변환 결과물이 없습니다');
|
||||
}
|
||||
editPath = odtPath;
|
||||
}
|
||||
|
||||
const token = mintWopiToken(session.username, editPath);
|
||||
const wopiSrc = `${collaboraCfg.publicUrl.replace(/\/+$/, '')}/api/lawyer/wopi/files/${token}`;
|
||||
const editorUrl = `${collaboraCfg.baseUrl.replace(/\/+$/, '')}/browser/dist/cool.html?WOPISrc=${encodeURIComponent(wopiSrc)}&access_token=${token}`;
|
||||
res.redirect(editorUrl);
|
||||
} catch (e: any) {
|
||||
res.status(502).send('Collabora open failed: ' + String(e?.message || e));
|
||||
}
|
||||
});
|
||||
}
|
||||
+19
-7
@@ -81,7 +81,7 @@ import { registerUserAppSessionRoutes } from './routes/routes-user-app-sessions'
|
||||
import { registerChannelMappingRoutes } from './routes/routes-channel-mappings';
|
||||
import { registerAdminSessionRoutes } from './routes/routes-admin-sessions';
|
||||
import { registerUserRoutes } from './routes/routes-users';
|
||||
import { registerDetectiveRoutes, detectiveFilesDir, resolveDetectiveUploadPath } from './routes/routes-detective';
|
||||
import { registerDetectiveRoutes } from './routes/routes-detective';
|
||||
import { registerPptxRoutes } from './routes/routes-pptx';
|
||||
import { registerVoiceRoutes } from './routes/routes-voice';
|
||||
import { registerVoiceRealtimeRoutes, attachVoiceRealtimeWsProxy } from './routes/routes-voice-realtime';
|
||||
@@ -91,6 +91,8 @@ import { registerLanguageRoutes } from './routes/routes-language';
|
||||
import { registerWriterRoutes } from './routes/routes-writer';
|
||||
import { registerDentalRoutes } from './routes/routes-dental';
|
||||
import { registerDetectiveDateRoutes } from './routes/routes-detective-dates';
|
||||
import { registerLawyerCaseRoutes } from './routes/routes-lawyer-cases';
|
||||
import { caseFilesDir, resolveUploadPath, registerWopiRoutes } from './routes/case-storage';
|
||||
import {
|
||||
getConfig,
|
||||
getAgents,
|
||||
@@ -2676,12 +2678,16 @@ app.use('/wavacity', express.static(path.join(webUiPath, 'wavacity'), {
|
||||
// URL with no query string. (Stirling-PDF's root path has a bug where a
|
||||
// query string on the bare context-path root causes a broken redirect —
|
||||
// see /pdf-editor below — so the case id is never sent in that request.)
|
||||
// Cookie value is "<appType>:<caseId>" so the same Stirling-PDF instance and
|
||||
// auto-save logic serve any case-backed app (detective, lawyer, ...) — app
|
||||
// defaults to 'detective' when omitted, for links that predate the lawyer app.
|
||||
app.get('/pdf-editor-open', (req: express.Request, res: express.Response) => {
|
||||
const session = getSessionUser(req);
|
||||
if (!session) { res.redirect('/html/login.html'); return; }
|
||||
const caseId = String(req.query.caseId || '');
|
||||
if (/^[a-zA-Z0-9_-]+$/.test(caseId)) {
|
||||
res.setHeader('Set-Cookie', `dt_pdf_case=${caseId}; Path=/pdf-editor; HttpOnly; SameSite=Lax; Max-Age=3600`);
|
||||
const appType = String(req.query.app || 'detective');
|
||||
if (/^[a-zA-Z0-9_-]+$/.test(caseId) && /^[a-z]+$/.test(appType)) {
|
||||
res.setHeader('Set-Cookie', `dt_pdf_case=${appType}:${caseId}; Path=/pdf-editor; HttpOnly; SameSite=Lax; Max-Age=3600`);
|
||||
}
|
||||
res.redirect('/pdf-editor/');
|
||||
});
|
||||
@@ -2697,7 +2703,11 @@ app.get('/pdf-editor-open', (req: express.Request, res: express.Response) => {
|
||||
// the browser as normal, so "download" in the editor also lands in the case.
|
||||
app.use('/pdf-editor', (req: express.Request, res: express.Response) => {
|
||||
const cookies = parseCookies(req);
|
||||
const caseId = cookies['dt_pdf_case'] || '';
|
||||
const rawCookie = cookies['dt_pdf_case'] || '';
|
||||
const colonIdx = rawCookie.indexOf(':');
|
||||
// No colon = old-format cookie set before app-scoping existed — treat as detective.
|
||||
const appType = colonIdx >= 0 ? rawCookie.slice(0, colonIdx) : 'detective';
|
||||
const caseId = colonIdx >= 0 ? rawCookie.slice(colonIdx + 1) : rawCookie;
|
||||
const session = getSessionUser(req);
|
||||
|
||||
const proxyReq = http.request({
|
||||
@@ -2721,16 +2731,16 @@ app.use('/pdf-editor', (req: express.Request, res: express.Response) => {
|
||||
proxyRes.on('end', () => {
|
||||
const body = Buffer.concat(chunks);
|
||||
try {
|
||||
const dir = detectiveFilesDir(session!.username, caseId);
|
||||
const dir = caseFilesDir(session!.username, appType, caseId);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
let filename = 'edited.pdf';
|
||||
const fnStar = cd.match(/filename\*=UTF-8''([^;]+)/i);
|
||||
const fnPlain = cd.match(/filename="?([^";]+)"?/i);
|
||||
if (fnStar) { try { filename = decodeURIComponent(fnStar[1]); } catch {} }
|
||||
else if (fnPlain) filename = fnPlain[1];
|
||||
const { relPath, absPath } = resolveDetectiveUploadPath(dir, filename);
|
||||
const { relPath, absPath } = resolveUploadPath(dir, filename);
|
||||
fs.writeFileSync(absPath, body);
|
||||
console.log(`[pdf-editor] saved result to case ${caseId}: ${relPath}`);
|
||||
console.log(`[pdf-editor] saved result to ${appType} case ${caseId}: ${relPath}`);
|
||||
} catch (err) {
|
||||
console.error('[pdf-editor] auto-save failed:', err);
|
||||
}
|
||||
@@ -4357,6 +4367,8 @@ registerUserRoutes(app, {
|
||||
CONFIG_DIR_PATH,
|
||||
});
|
||||
registerDetectiveRoutes(app, getSessionUser, isPathInsideDir, CONFIG_DIR_PATH);
|
||||
registerLawyerCaseRoutes(app, getSessionUser, isPathInsideDir);
|
||||
registerWopiRoutes(app, '/api/lawyer');
|
||||
|
||||
|
||||
// Redirect legacy top-level HTML routes into /html/ after web-ui reorganization.
|
||||
|
||||
+989
-17
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user