d3ro-voice/apps/desktop/src/main/services/DictionaryService.ts

484 lines
16 KiB
TypeScript

// src/main/services/DictionaryService.ts
// 사용자 커스텀 단어 사전. 설계서 01/03 IDictionaryService 구현.
import { eq, desc, count, sql } from 'drizzle-orm'
import path from 'path'
import fs from 'fs'
import { app, dialog } from 'electron'
import { getDatabase } from '../db'
import { dictionary } from '../db/schema'
import type { Dictionary, NewDictionary } from '../db/schema'
import { getLogger } from './LoggerService'
import { getCloudSyncService } from './CloudSyncService'
import { getMainWindow } from '../windows/WindowManager'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { containsPattern } from '../db/like-pattern'
import {
buildDictionaryUpdatePatch,
dictionaryIdentityKey,
dictionaryWriteProblemError,
findDictionaryIdentityConflict,
isUniqueConstraintViolation,
validateDictionaryDraft
} from '@d3ro/core/dictionary-policy'
import {
parseDictionaryFile,
serializeDictionary,
toDictionaryImportRow
} from './dictionary/dictionary-file-codec'
import type {
DictionaryEntry,
DictionaryQueryParams,
DictionaryPage,
DictionaryAddParams,
DictionaryUpdateParams,
DictionarySearchParams,
DictionaryImportParams,
DictionaryImportResult,
DictionaryExportParams
} from '@d3ro/core/types'
const logger = getLogger('DictionaryService')
let isShowingDictionarySaveDialog = false
type DictionaryDb = Pick<ReturnType<typeof getDatabase>, 'select'>
/**
* 같은 카테고리에 대소문자·앞뒤 공백만 다른 단어가 있으면 그 행. 서버 유일성(lower(btrim(word)))과 같은
* 기준으로 로컬 입력 단계에서 거절한다 — 로컬 인덱스는 대소문자를 구분해 그대로 받아들이고, 동기화가
* 나중에 사용자의 항목을 서버 행으로 조용히 대체했다. (Unicode 대소문자까지 JS 로 비교한다)
*/
function findCaseInsensitiveDuplicate(
db: DictionaryDb,
word: string,
category: DictionaryEntry['category'],
excludeId?: string
): { id: string; word: string } | null {
const candidates = db
.select({ id: dictionary.id, word: dictionary.word })
.from(dictionary)
.where(eq(dictionary.category, category))
.all()
return findDictionaryIdentityConflict(word, candidates, excludeId)
}
/**
* 가져오기용 식별 키 집합 `${category}|${dictionaryIdentityKey(word)}` — 가져오기 시작 때 한 번 읽는다.
* SQL lower() 는 ASCII 만 접어 'Äpfel'/'äpfel' 이 따로 들어갔고, 동기화 때 서버 유일 인덱스와 부딪혀
* 한쪽 표기가 조용히 덮였다. 추가·수정 경로와 같은 JS 기준으로 비교한다.
*/
function importIdentityKey(word: string, category: DictionaryEntry['category']): string {
return `${category}|${dictionaryIdentityKey(word)}`
}
function loadImportIdentities(db: DictionaryDb): Set<string> {
const rows = db.select({ word: dictionary.word, category: dictionary.category }).from(dictionary).all()
return new Set(rows.map((r) => importIdentityKey(r.word, r.category)))
}
class DictionaryService {
add(params: DictionaryAddParams): DictionaryEntry {
// 빈 단어·서버 길이 제한(단어 120·발음 200자) 초과는 저장 전에 거부한다 — 받아들이면 로컬에만 남고
// 서버가 22023 으로 거부해 아웃박스에 영구 보류된다(다른 기기로 동기화되지 않음).
const validated = validateDictionaryDraft(params)
if (!validated.ok) throw dictionaryWriteProblemError(validated)
const { word, pronunciation } = validated.draft
const db = getDatabase()
const now = Date.now()
const id = crypto.randomUUID()
const category = params.category ?? 'user'
const duplicate = findCaseInsensitiveDuplicate(db, word, category)
if (duplicate) {
throw new D3ROError(ErrorCode.DictionaryDuplicate, `Duplicate word: ${word} (existing: ${duplicate.word})`)
}
const entry: NewDictionary = {
id,
word,
pronunciation,
category,
usageCount: 0,
lastUsedAt: null,
createdAt: now,
updatedAt: now
}
try {
db.insert(dictionary).values(entry).run()
} catch (err) {
if (isUniqueConstraintViolation(err)) {
throw new D3ROError(ErrorCode.DictionaryDuplicate, `Duplicate word: ${word}`)
}
throw err
}
logger.info(`Dictionary entry added: "${word}"`)
// Phase 3.3: 자동 push (fire-and-forget)
void getCloudSyncService().pushOne('dictionary', id)
return this._toEntry(entry as Dictionary)
}
update(params: DictionaryUpdateParams): DictionaryEntry | null {
const result = buildDictionaryUpdatePatch(params)
if (!result.ok) throw dictionaryWriteProblemError(result)
const db = getDatabase()
const existing = db.select().from(dictionary).where(eq(dictionary.id, params.id)).get()
if (!existing) return null
if (result.patch.word !== undefined || result.patch.category !== undefined) {
const nextWord = result.patch.word ?? existing.word
const nextCategory = result.patch.category ?? (existing.category as DictionaryEntry['category'])
const duplicate = findCaseInsensitiveDuplicate(db, nextWord, nextCategory, existing.id)
if (duplicate) {
throw new D3ROError(ErrorCode.DictionaryDuplicate, `Duplicate word: ${nextWord} (existing: ${duplicate.word})`)
}
}
const updates: Partial<NewDictionary> = { ...result.patch, updatedAt: Date.now() }
try {
db.update(dictionary).set(updates).where(eq(dictionary.id, params.id)).run()
} catch (err) {
if (isUniqueConstraintViolation(err)) {
throw new D3ROError(
ErrorCode.DictionaryDuplicate,
`Duplicate word: ${result.patch.word ?? existing.word}`
)
}
throw err
}
const updated = db.select().from(dictionary).where(eq(dictionary.id, params.id)).get()
// Phase 3.3: 자동 push (fire-and-forget)
void getCloudSyncService().pushOne('dictionary', params.id)
return updated ? this._toEntry(updated) : null
}
delete(id: string): boolean {
const db = getDatabase()
const result = db.delete(dictionary).where(eq(dictionary.id, id)).run()
if (result.changes > 0) getCloudSyncService().pushDelete('dictionary', id)
return result.changes > 0
}
list(params: DictionaryQueryParams): DictionaryPage {
const db = getDatabase()
const { page, pageSize } = params
const totalResult = db.select({ count: count() }).from(dictionary).get()
const total = totalResult?.count ?? 0
const entries = db
.select()
.from(dictionary)
.orderBy(desc(dictionary.createdAt))
.limit(pageSize)
.offset(page * pageSize)
.all()
return {
entries: entries.map((e) => this._toEntry(e)),
total,
page,
pageSize,
totalPages: Math.ceil(total / pageSize)
}
}
search(params: DictionarySearchParams): DictionaryPage {
const db = getDatabase()
const { query, page, pageSize } = params
// 검색어의 %·_ 는 글자 그대로 찾는다(와일드카드로 해석하지 않는다)
const condition = containsPattern(query).match(dictionary.word)
const totalResult = db
.select({ count: count() })
.from(dictionary)
.where(condition)
.get()
const total = totalResult?.count ?? 0
const entries = db
.select()
.from(dictionary)
.where(condition)
.orderBy(desc(dictionary.usageCount))
.limit(pageSize)
.offset(page * pageSize)
.all()
return {
entries: entries.map((e) => this._toEntry(e)),
total,
page,
pageSize,
totalPages: Math.ceil(total / pageSize)
}
}
incrementUsage(id: string): void {
const db = getDatabase()
db.update(dictionary)
.set({
usageCount: sql`usage_count + 1`,
lastUsedAt: Date.now()
})
.where(eq(dictionary.id, id))
.run()
}
/**
* 사전 단어 목록을 STT initialPrompt 형태로 반환한다.
* 발음(pronunciation)이 등록된 항목은 인식 힌트로 함께 포함한다.
*/
getPromptHints(limit = 50): string {
const db = getDatabase()
const words = db
.select({ word: dictionary.word, pronunciation: dictionary.pronunciation })
.from(dictionary)
.orderBy(desc(dictionary.usageCount))
.limit(limit)
.all()
return words
.map((w) => {
const pron = typeof w.pronunciation === 'string' ? w.pronunciation.trim() : ''
return pron ? `${w.word} (${pron})` : w.word
})
.join(', ')
}
getPromptHint(limit = 50): string {
return this.getPromptHints(limit)
}
/**
* 전사 텍스트에서 사전 단어 또는 발음(pronunciation) 변형을 찾아 표준 단어로 치환하고
* 매칭된 사전 항목의 사용 횟수(usageCount)를 증가시킨다.
*/
applyDictionaryCorrections(text: string): { text: string; matchedIds: string[] } {
if (!text || text.trim().length === 0) {
return { text, matchedIds: [] }
}
const db = getDatabase()
const entries = db
.select({
id: dictionary.id,
word: dictionary.word,
pronunciation: dictionary.pronunciation
})
.from(dictionary)
.orderBy(desc(dictionary.usageCount))
.all()
if (!entries || entries.length === 0) {
return { text, matchedIds: [] }
}
let currentText = text
const matchedIds: string[] = []
const escapeRegExp = (str: string): string => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const isAsciiWordChar = (ch: string | undefined): boolean => Boolean(ch && /[A-Za-z0-9]/.test(ch))
const buildTokenRegex = (token: string): RegExp => {
const escaped = escapeRegExp(token)
const prefix = isAsciiWordChar(token[0]) ? '(?<![A-Za-z0-9])' : ''
const suffix = isAsciiWordChar(token[token.length - 1]) ? '(?![A-Za-z0-9])' : ''
return new RegExp(`${prefix}${escaped}${suffix}`, 'gi')
}
for (const entry of entries) {
const canonicalWord = entry.word?.trim()
if (!canonicalWord) continue
let matched = false
const rawPron = typeof entry.pronunciation === 'string' ? entry.pronunciation.trim() : ''
if (rawPron.length > 0) {
const variants = Array.from(
new Set(
[rawPron, ...rawPron.split(/[,/;]+/)]
.map((v) => v.trim())
.filter((v) => v.length > 0 && v.toLowerCase() !== canonicalWord.toLowerCase())
)
).sort((a, b) => b.length - a.length)
for (const variant of variants) {
const regex = buildTokenRegex(variant)
if (regex.test(currentText)) {
matched = true
currentText = currentText.replace(buildTokenRegex(variant), canonicalWord)
}
}
}
const wordRegex = buildTokenRegex(canonicalWord)
if (wordRegex.test(currentText)) {
matched = true
currentText = currentText.replace(buildTokenRegex(canonicalWord), canonicalWord)
}
if (matched) {
matchedIds.push(entry.id)
this.incrementUsage(entry.id)
}
}
return { text: currentText, matchedIds }
}
async exportDictionary(params: DictionaryExportParams): Promise<string> {
const db = getDatabase()
const entries = db
.select()
.from(dictionary)
.orderBy(desc(dictionary.createdAt))
.all()
.map((row) => this._toEntry(row))
const content = serializeDictionary(entries, params.format)
const defaultName = `d3ro-dictionary-${new Date().toISOString().slice(0, 10)}.${params.format}`
if (isShowingDictionarySaveDialog) {
throw new D3ROError(ErrorCode.DictionaryExportFailed, 'Export dialog already active')
}
isShowingDictionarySaveDialog = true
let result: Electron.SaveDialogReturnValue
try {
const mainWindow = getMainWindow()
const dialogOptions = {
defaultPath: path.join(app.getPath('documents'), defaultName),
filters: [
params.format === 'csv'
? { name: 'CSV', extensions: ['csv'] }
: { name: 'JSON', extensions: ['json'] }
]
}
result = mainWindow
? await dialog.showSaveDialog(mainWindow, dialogOptions)
: await dialog.showSaveDialog(dialogOptions)
} finally {
isShowingDictionarySaveDialog = false
}
if (result.canceled || !result.filePath) {
throw new D3ROError(ErrorCode.DictionaryExportFailed, 'Export cancelled')
}
try {
fs.writeFileSync(result.filePath, content, 'utf-8')
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
throw new D3ROError(
ErrorCode.DictionaryExportFailed,
`Failed to write dictionary export: ${message}`
)
}
logger.info(`Dictionary exported (${entries.length} entries, ${params.format})`)
return result.filePath
}
importDictionary(params: DictionaryImportParams): DictionaryImportResult {
if (params.format !== 'json' && params.format !== 'csv') {
throw new D3ROError(
ErrorCode.DictionaryImportInvalidFormat,
`Unsupported dictionary format: ${String(params.format)}`
)
}
let raw: string
try {
raw = fs.readFileSync(params.filePath, 'utf-8')
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
throw new D3ROError(
ErrorCode.DictionaryImportFailed,
`Failed to read dictionary file: ${message}`
)
}
let parsed: Array<Record<string, unknown>>
try {
parsed = parseDictionaryFile(raw, params.format)
} catch (err) {
if (err instanceof D3ROError) throw err
const message = err instanceof Error ? err.message : String(err)
throw new D3ROError(
ErrorCode.DictionaryImportInvalidFormat,
`Invalid dictionary file: ${message}`
)
}
const db = getDatabase()
const now = Date.now()
const outcome: DictionaryImportResult = { imported: 0, skipped: 0, errors: 0 }
db.transaction((tx) => {
const known = loadImportIdentities(tx)
for (const record of parsed) {
// 빈 단어·서버 길이 제한 초과 행은 오류로 센다 — 로컬에만 남고 동기화되지 않는 항목을 만들지 않는다
const candidate = toDictionaryImportRow(record, now)
if (!candidate.ok) {
outcome.errors += 1
continue
}
const { row } = candidate
// 대소문자만 다른 단어도 같은 단어로 본다(서버 유일성과 같은 기준)
const key = importIdentityKey(row.word, row.category)
if (known.has(key)) {
outcome.skipped += 1
continue
}
const id = crypto.randomUUID()
try {
tx.insert(dictionary)
.values({ id, ...row })
.run()
outcome.imported += 1
known.add(key)
void getCloudSyncService().pushOne('dictionary', id)
} catch {
outcome.skipped += 1
}
}
})
logger.info(
`Dictionary import: ${outcome.imported} imported, ${outcome.skipped} skipped, ${outcome.errors} errors`
)
return outcome
}
dispose(): void {
logger.info('DictionaryService disposed')
}
private _toEntry(row: Dictionary): DictionaryEntry {
return {
id: row.id,
word: row.word,
pronunciation: row.pronunciation,
category: row.category as DictionaryEntry['category'],
usageCount: row.usageCount,
lastUsedAt: row.lastUsedAt,
createdAt: row.createdAt,
updatedAt: row.updatedAt
}
}
}
let instance: DictionaryService | null = null
export function getDictionaryService(): DictionaryService {
if (!instance) {
instance = new DictionaryService()
}
return instance
}
export function resetDictionaryServiceForTests(): void {
instance = null
}