db_search.js
11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
'use strict'; class SubtitleDatabase {
constructor() { this.db = null; this.isLoading = false; this.isLoaded = false; this.loadPromise = null; this.progressCallback = null; this.version = "1.0.1" } async clearCache() { try { await dbStorage.removeItem("databases", "subtitleDB"); await dbStorage.setItem("databases", "version", this.version); this.db = null; this.isLoaded = false; this.isLoading = false; this.loadPromise = null; return true } catch (error) { throw error; } } getDebugInfo() {
return {
version: this.version, isLoaded: this.isLoaded, isLoading: this.isLoading,
recordCount: this.db ? this.db.length : 0, memoryUsage: this.db ? JSON.stringify(this.db).length : 0, cacheStatus: this.isLoaded ? "\u5df2\u52a0\u8f7d" : this.isLoading ? "\u52a0\u8f7d\u4e2d" : "\u672a\u52a0\u8f7d"
}
} printDebugInfo() { const info = this.getDebugInfo() } async checkVersion() {
try {
const storedVersion = await dbStorage.getItem("databases", "version"); if (!storedVersion) { await dbStorage.setItem("databases", "version", this.version); return false } if (storedVersion !== this.version) {
await this.clearCache(); await dbStorage.setItem("databases",
"version", this.version); return true
} return false
} catch (error) { return false }
} async load(progressCallback = null) {
if (this.isLoaded && this.db && this.db.length > 0) return true;
if (this.isLoading) return this.loadPromise;
this.isLoading = true;
this.progressCallback = progressCallback;
await this.checkVersion();
try {
const cachedDB = await dbStorage.getItem("databases", "subtitleDB");
if (cachedDB) {
if (Array.isArray(cachedDB) && cachedDB.length > 0) {
this.db = cachedDB;
this.isLoaded = true;
this.isLoading = false;
return true;
}
}
} catch (e) { }
this.loadPromise = new Promise(async (resolve, reject) => {
try {
const checkResponse = await fetch("https://vvdb.cicada000.work/subtitle_db", {
method: "HEAD",
referrerPolicy: 'no-referrer',
mode: 'cors',
credentials: 'omit'
});
if (!checkResponse.ok) throw new Error(`Database file not found: ${checkResponse.status}`);
const response = await fetch("https://vvdb.cicada000.work/subtitle_db", {
referrerPolicy: 'no-referrer',
mode: 'cors',
credentials: 'omit'
});
if (!response.ok) throw new Error(`Failed to load database: ${response.status}`);
const contentLength = response.headers.get("Content-Length");
const reader = response.body.getReader();
let receivedLength = 0;
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
receivedLength += value.length;
}
const chunksAll = new Uint8Array(receivedLength);
let position = 0;
for (const chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length
}
const ds =
new DecompressionStream("gzip");
const decompressedStream = (new Response(chunksAll)).body.pipeThrough(ds);
const decompressedData = await (new Response(decompressedStream)).text();
const parsedData = JSON.parse(decompressedData);
if (!parsedData || !Array.isArray(parsedData) || parsedData.length === 0) throw new Error("Invalid or empty database format");
this.db = parsedData;
this.isLoaded = true;
this.isLoading = false;
try { await dbStorage.setItem("databases", "subtitleDB", this.db) } catch (e) { }
if (window.subtitleDB !==
this) window.subtitleDB = this;
resolve(true)
} catch (error) {
this.isLoading = false;
this.isLoaded = false;
this.db = null;
reject(error)
}
});
return this.loadPromise
} lcsRatio(str1, str2) { str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); if (!str1 || !str2) return 0; const m = str1.length; const n = str2.length; const dp = Array(m + 1).fill().map(() => Array(n + 1).fill(0)); for (let i = 1; i <= m; i++)for (let j = 1; j <= n; j++)if (str1[i - 1] === str2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); return dp[m][n] / m * 100 } multiWordLcsRatio(queryWords,
text) {
text = text.toLowerCase(); const totalQueryLength = queryWords.reduce((sum, word) => sum + word.length, 0); const usedChars = (new Array(text.length)).fill(false); let totalMatched = 0; for (const word of queryWords) {
const wordLower = word.toLowerCase(); let foundMatch = false; let startPos = 0; while (true) {
const pos = text.indexOf(wordLower, startPos); if (pos === -1) break; const endPos = pos + wordLower.length; let canUse = true; for (let i = pos; i < endPos; i++)if (usedChars[i]) { canUse = false; break } if (canUse) {
for (let i = pos; i < endPos; i++)usedChars[i] =
true; totalMatched += wordLower.length; foundMatch = true; break
} startPos = pos + 1
}
} return totalMatched / totalQueryLength * 100
} search(query, minRatio = 50, minSimilarity = 0) {
if (!this.isLoaded || !this.db || this.db.length === 0) {
return {
status: "success",
data: [],
count: 0,
message: "数据库未加载或为空",
suggestions: [
"请等待数据库加载完成",
"如果问题持续,请刷新页面"
]
};
}
const startTime = performance.now();
query = query.toLowerCase();
const hasSpaces = query.includes(" ") || query.includes("%20");
const queryWords = hasSpaces ? query.replace(/%20/g, " ").split(/\s+/).filter(Boolean) : [query];
const filteredBySimiliarity = this.db.filter(item => item.s >= minSimilarity);
if (window.Worker && queryWords.length > 1) return new Promise(resolve => {
const worker = new Worker("search_worker.js");
worker.onmessage = e => {
const workerResults = e.data;
worker.terminate();
if (workerResults.status === "success") {
if (workerResults.data.length === 0) {
resolve({
status: "success",
data: [],
count: 0,
message: `未找到与 '${query}' 匹配的结果`,
suggestions: [
"检查输入是否正确",
`尝试降低最小匹配率(当前:${minRatio}%)`,
`尝试降低最小相似度(当前:${minSimilarity})`,
"尝试使用更简短的关键词"
]
});
} else {
resolve(workerResults);
}
} else {
resolve({
status: "error",
data: [],
count: 0,
message: workerResults.message || "搜索失败",
suggestions: ["请重试"]
});
}
};
worker.onerror = (error) => {
console.error("Worker error:", error);
resolve({
status: "error",
message: "Search failed",
data: [],
count: 0
});
};
worker.postMessage({ db: filteredBySimiliarity, queryWords, minRatio });
});
const results = filteredBySimiliarity.map(item => {
const matchRatio = hasSpaces ? this.multiWordLcsRatio(queryWords, item.x) : this.lcsRatio(query, item.x);
return {
matchRatio,
item,
exactMatch: queryWords.every(word => item.x.toLowerCase().includes(word))
};
}).filter(result => result.matchRatio >= minRatio);
results.sort((a, b) => {
if (b.matchRatio !== a.matchRatio) return b.matchRatio - a.matchRatio;
return b.exactMatch - a.exactMatch;
});
const apiResults = results.map(result => ({
filename: result.item.f,
timestamp: result.item.t,
similarity: result.item.s,
text: result.item.x,
match_ratio: result.matchRatio,
exact_match: result.exactMatch
}));
if (apiResults.length === 0) {
return {
status: "success",
data: [{ // 包装在数组中
status: "success",
data: [],
count: 0,
folder: "subtitle",
max_results: "unlimited",
message: `未找到与 '${query}' 匹配的结果`,
suggestions: [
"检查输入是否正确",
`尝试降低最小匹配率(当前:${minRatio}%)`,
`尝试降低最小相似度(当前:${minSimilarity})`,
"尝试使用更简短的关键词"
]
}],
count: 1 // 数组长度为1
};
}
return {
status: "success",
data: apiResults,
count: apiResults.length
};
}
}
window.dbDebug = { clearCache: async () => { try { await window.subtitleDB.clearCache() } catch (error) { } }, info: () => { window.subtitleDB.printDebugInfo() }, reload: async () => { try { await window.subtitleDB.load() } catch (error) { } }, help: () => { } }; window.subtitleDB = new SubtitleDatabase; fetch("https://vvdb.cicada000.work/subtitle_db", {
method: "HEAD",
referrerPolicy: 'no-referrer',
mode: 'cors',
credentials: 'omit'
}).then(response => {
if (response.ok) window.subtitleDB.load().catch(error => { })
}).catch(error => { });