|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const sqlite3 = require('sqlite3').verbose(); |
| 6 | +const chatStore = require('./chatStore.js'); |
| 7 | + |
| 8 | +const DATA_DIR = path.join(__dirname, '..', 'data'); |
| 9 | +const CHATS_DIR = path.join(DATA_DIR, 'chats'); |
| 10 | +const DB_PATH = path.join(DATA_DIR, 'chat_history_fts.db'); |
| 11 | + |
| 12 | +const MAX_BODY = 12000; |
| 13 | +const SNIPPET = 320; |
| 14 | + |
| 15 | +let dbPromise = null; |
| 16 | + |
| 17 | +function ensureDataDir() { |
| 18 | + if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true }); |
| 19 | +} |
| 20 | + |
| 21 | +function openDb() { |
| 22 | + ensureDataDir(); |
| 23 | + return new Promise((resolve, reject) => { |
| 24 | + const db = new sqlite3.Database(DB_PATH, (err) => { |
| 25 | + if (err) return reject(err); |
| 26 | + db.serialize(() => { |
| 27 | + db.run( |
| 28 | + `CREATE VIRTUAL TABLE IF NOT EXISTS chat_hist_fts USING fts5( |
| 29 | + username UNINDEXED, |
| 30 | + chat_id UNINDEXED, |
| 31 | + msg_idx UNINDEXED, |
| 32 | + role UNINDEXED, |
| 33 | + chat_title, |
| 34 | + body, |
| 35 | + tokenize = 'porter unicode61' |
| 36 | + )`, |
| 37 | + (e2) => { |
| 38 | + if (e2) return reject(e2); |
| 39 | + resolve(db); |
| 40 | + } |
| 41 | + ); |
| 42 | + }); |
| 43 | + }); |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +function getDb() { |
| 48 | + if (!dbPromise) dbPromise = openDb(); |
| 49 | + return dbPromise; |
| 50 | +} |
| 51 | + |
| 52 | +function run(db, sql, params = []) { |
| 53 | + return new Promise((resolve, reject) => { |
| 54 | + db.run(sql, params, function (err) { |
| 55 | + if (err) return reject(err); |
| 56 | + resolve(this); |
| 57 | + }); |
| 58 | + }); |
| 59 | +} |
| 60 | + |
| 61 | +function all(db, sql, params = []) { |
| 62 | + return new Promise((resolve, reject) => { |
| 63 | + db.all(sql, params, (err, rows) => { |
| 64 | + if (err) return reject(err); |
| 65 | + resolve(rows || []); |
| 66 | + }); |
| 67 | + }); |
| 68 | +} |
| 69 | + |
| 70 | +/** Build a safe FTS5 MATCH string from user input (token AND). */ |
| 71 | +function ftsMatchQuery(raw) { |
| 72 | + const s = String(raw || '').trim().slice(0, 400); |
| 73 | + if (!s) return ''; |
| 74 | + const parts = s.split(/\s+/).filter(Boolean).slice(0, 14); |
| 75 | + if (parts.length === 0) return ''; |
| 76 | + return parts |
| 77 | + .map((p) => { |
| 78 | + const esc = p.replace(/"/g, '""'); |
| 79 | + return `body : "${esc}"`; |
| 80 | + }) |
| 81 | + .join(' AND '); |
| 82 | +} |
| 83 | + |
| 84 | +function normalizeUsername(u) { |
| 85 | + return chatStore.safeUsername(u); |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Replace FTS rows for one chat with current messages. |
| 90 | + */ |
| 91 | +async function reindexChat(username, chatId) { |
| 92 | + const user = normalizeUsername(username); |
| 93 | + const chat = chatStore.getChat(user, chatId); |
| 94 | + if (!chat) return; |
| 95 | + const db = await getDb(); |
| 96 | + await run(db, 'DELETE FROM chat_hist_fts WHERE username = ? AND chat_id = ?', [user, chatId]); |
| 97 | + const title = String(chat.title || 'Chat').slice(0, 200); |
| 98 | + const messages = Array.isArray(chat.messages) ? chat.messages : []; |
| 99 | + let idx = 0; |
| 100 | + for (const m of messages) { |
| 101 | + const role = String(m && m.role ? m.role : '').slice(0, 32); |
| 102 | + const body = String(m && m.content != null ? m.content : '').slice(0, MAX_BODY); |
| 103 | + if (!body.trim()) { |
| 104 | + idx++; |
| 105 | + continue; |
| 106 | + } |
| 107 | + await run( |
| 108 | + db, |
| 109 | + `INSERT INTO chat_hist_fts (username, chat_id, msg_idx, role, chat_title, body) VALUES (?, ?, ?, ?, ?, ?)`, |
| 110 | + [user, chatId, idx, role, title, body] |
| 111 | + ); |
| 112 | + idx++; |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +async function removeChat(username, chatId) { |
| 117 | + const user = normalizeUsername(username); |
| 118 | + const db = await getDb(); |
| 119 | + await run(db, 'DELETE FROM chat_hist_fts WHERE username = ? AND chat_id = ?', [user, chatId]); |
| 120 | +} |
| 121 | + |
| 122 | +/** |
| 123 | + * @param {string} username - chat store user id |
| 124 | + * @param {string} query |
| 125 | + * @param {{ limit?: number, chatId?: string }} [opts] |
| 126 | + * @returns {Promise<Array<{ chatId: string, chatTitle: string, role: string, msgIdx: number, snippet: string }>>} |
| 127 | + */ |
| 128 | +async function search(username, query, opts = {}) { |
| 129 | + const user = normalizeUsername(username); |
| 130 | + const match = ftsMatchQuery(query); |
| 131 | + if (!match) return []; |
| 132 | + const limit = Math.min(40, Math.max(1, Number(opts.limit) || 15)); |
| 133 | + const db = await getDb(); |
| 134 | + const chatId = opts.chatId ? String(opts.chatId).trim() : ''; |
| 135 | + const sql = chatId |
| 136 | + ? `SELECT username, chat_id, msg_idx, role, chat_title, body FROM chat_hist_fts WHERE chat_hist_fts MATCH ? AND username = ? AND chat_id = ? LIMIT ?` |
| 137 | + : `SELECT username, chat_id, msg_idx, role, chat_title, body FROM chat_hist_fts WHERE chat_hist_fts MATCH ? AND username = ? LIMIT ?`; |
| 138 | + const params = chatId ? [match, user, chatId, limit] : [match, user, limit]; |
| 139 | + const rows = await all(db, sql, params); |
| 140 | + return rows.map((r) => ({ |
| 141 | + chatId: r.chat_id, |
| 142 | + chatTitle: r.chat_title || 'Chat', |
| 143 | + role: r.role || '', |
| 144 | + msgIdx: Number(r.msg_idx) || 0, |
| 145 | + snippet: String(r.body || '').replace(/\s+/g, ' ').trim().slice(0, SNIPPET) |
| 146 | + })); |
| 147 | +} |
| 148 | + |
| 149 | +async function reindexAllUsers() { |
| 150 | + ensureDataDir(); |
| 151 | + if (!fs.existsSync(CHATS_DIR)) return; |
| 152 | + const files = fs.readdirSync(CHATS_DIR).filter((f) => f.endsWith('.json')); |
| 153 | + for (const file of files) { |
| 154 | + const safeName = file.slice(0, -5); |
| 155 | + let data; |
| 156 | + try { |
| 157 | + data = JSON.parse(fs.readFileSync(path.join(CHATS_DIR, file), 'utf8')); |
| 158 | + } catch (_) { |
| 159 | + continue; |
| 160 | + } |
| 161 | + if (!data || !Array.isArray(data.chats)) continue; |
| 162 | + for (const c of data.chats) { |
| 163 | + if (c && c.id) { |
| 164 | + try { |
| 165 | + await reindexChat(safeName, c.id); |
| 166 | + } catch (e) { |
| 167 | + /* ignore per-chat errors */ |
| 168 | + } |
| 169 | + } |
| 170 | + } |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +module.exports = { |
| 175 | + search, |
| 176 | + reindexChat, |
| 177 | + removeChat, |
| 178 | + reindexAllUsers, |
| 179 | + ftsMatchQuery |
| 180 | +}; |
0 commit comments