@acanthis-dec/storage 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +64 -0
- package/README.zh-CN.md +64 -0
- package/dist/index.d.mts +1119 -0
- package/dist/index.mjs +860 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +48 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
import { cookieStoreSign, isCookiesStore, matchesDomain, matchesPath } from "@acanthis-dec/browser-fetch";
|
|
2
|
+
import { and, defineRelations, eq } from "drizzle-orm";
|
|
3
|
+
import { integer, primaryKey, sqliteTable, text, unique } from "drizzle-orm/sqlite-core";
|
|
4
|
+
import { existsSync, mkdirSync, rmSync, statSync } from "node:fs";
|
|
5
|
+
import { dirname, resolve } from "node:path";
|
|
6
|
+
import { createClient } from "@libsql/client";
|
|
7
|
+
import { drizzle } from "drizzle-orm/libsql";
|
|
8
|
+
import { migrate } from "drizzle-orm/libsql/migrator";
|
|
9
|
+
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { zstdCompress, zstdDecompress } from "node:zlib";
|
|
12
|
+
//#region src/table.ts
|
|
13
|
+
const novels = sqliteTable("novels", {
|
|
14
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
15
|
+
platform: text("platform").notNull(),
|
|
16
|
+
platformId: text("platform_id").notNull(),
|
|
17
|
+
name: text("name").notNull(),
|
|
18
|
+
author: text("author").notNull(),
|
|
19
|
+
summary: text("summary").notNull(),
|
|
20
|
+
coverUrl: text("cover_url").notNull(),
|
|
21
|
+
status: text("status", { enum: [
|
|
22
|
+
"ongoing",
|
|
23
|
+
"completed",
|
|
24
|
+
"unknown"
|
|
25
|
+
] }).notNull(),
|
|
26
|
+
updateAt: integer("update_at").notNull()
|
|
27
|
+
}, (table) => [unique("platform_and_pid_idx").on(table.platform, table.platformId)]);
|
|
28
|
+
const genres = sqliteTable("genres", {
|
|
29
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
30
|
+
name: text("name").notNull().unique()
|
|
31
|
+
});
|
|
32
|
+
const novelGenres = sqliteTable("novel_genres", {
|
|
33
|
+
novelId: integer("novel_id").notNull().references(() => novels.id, { onDelete: "cascade" }),
|
|
34
|
+
genreId: integer("genre_id").notNull().references(() => genres.id, { onDelete: "cascade" })
|
|
35
|
+
}, (table) => [primaryKey({ columns: [table.novelId, table.genreId] })]);
|
|
36
|
+
const volumes = sqliteTable("volumes", {
|
|
37
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
38
|
+
novelId: integer("novel_id").notNull().references(() => novels.id, { onDelete: "cascade" }),
|
|
39
|
+
name: text("name").notNull(),
|
|
40
|
+
platform: text("platform").notNull(),
|
|
41
|
+
platformId: text("platform_id").notNull(),
|
|
42
|
+
coverUrl: text("cover_url")
|
|
43
|
+
}, (table) => [unique("novel_and_pid_idx").on(table.novelId, table.platformId)]);
|
|
44
|
+
const chapters = sqliteTable("chapters", {
|
|
45
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
46
|
+
novelId: integer("novel_id").notNull().references(() => novels.id, { onDelete: "cascade" }),
|
|
47
|
+
volumeId: integer("volume_id").notNull().references(() => volumes.id, { onDelete: "cascade" }),
|
|
48
|
+
platform: text("platform").notNull(),
|
|
49
|
+
platformId: text("platform_id").notNull(),
|
|
50
|
+
contentHash: text("content_hash"),
|
|
51
|
+
name: text("name").notNull()
|
|
52
|
+
}, (table) => [unique("novel_and_pid_idx").on(table.novelId, table.platformId)]);
|
|
53
|
+
const keywordSearches = sqliteTable("keyword_searches", {
|
|
54
|
+
keyword: text("keyword").primaryKey(),
|
|
55
|
+
platform: text("platform").notNull(),
|
|
56
|
+
queryTime: integer("query_time").notNull(),
|
|
57
|
+
total: integer("total").notNull()
|
|
58
|
+
});
|
|
59
|
+
const keywordNovels = sqliteTable("keyword_novels", {
|
|
60
|
+
keyword: text("keyword").notNull().references(() => keywordSearches.keyword, { onDelete: "cascade" }),
|
|
61
|
+
novelId: integer("novel_id").notNull().references(() => novels.id, { onDelete: "cascade" })
|
|
62
|
+
}, (table) => [primaryKey({ columns: [table.keyword, table.novelId] })]);
|
|
63
|
+
const novelCoverMetadata = sqliteTable("novel_cover_metadata", {
|
|
64
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
65
|
+
hash: text("hash").notNull(),
|
|
66
|
+
contentType: text("content_type").notNull(),
|
|
67
|
+
originalUrl: text("original_url").notNull().unique(),
|
|
68
|
+
novelId: integer("novel_id").references(() => novels.id, { onDelete: "set null" })
|
|
69
|
+
});
|
|
70
|
+
const volumeCoverMetadata = sqliteTable("volume_cover_metadata", {
|
|
71
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
72
|
+
hash: text("hash").notNull(),
|
|
73
|
+
contentType: text("content_type").notNull(),
|
|
74
|
+
originalUrl: text("original_url").notNull().unique(),
|
|
75
|
+
volumeId: integer("volume_id").references(() => volumes.id, { onDelete: "set null" })
|
|
76
|
+
});
|
|
77
|
+
const cookies = sqliteTable("cookies", {
|
|
78
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
79
|
+
domain: text("domain").notNull(),
|
|
80
|
+
path: text("path").notNull(),
|
|
81
|
+
name: text("name").notNull(),
|
|
82
|
+
value: text("value").notNull(),
|
|
83
|
+
expires: integer("expires"),
|
|
84
|
+
maxAge: integer("max_age"),
|
|
85
|
+
secure: integer("secure", { mode: "boolean" }),
|
|
86
|
+
httpOnly: integer("http_only", { mode: "boolean" }),
|
|
87
|
+
sameSite: text("same_site", { enum: [
|
|
88
|
+
"Strict",
|
|
89
|
+
"Lax",
|
|
90
|
+
"None"
|
|
91
|
+
] }),
|
|
92
|
+
createdAt: integer("created_at").notNull(),
|
|
93
|
+
lastAccessedAt: integer("last_accessed_at").notNull()
|
|
94
|
+
}, (table) => [unique("cookie_unique_idx").on(table.domain, table.path, table.name)]);
|
|
95
|
+
const generalCache = sqliteTable("general_cache", {
|
|
96
|
+
key: text("key").primaryKey(),
|
|
97
|
+
value: text("value", { mode: "json" }).notNull()
|
|
98
|
+
});
|
|
99
|
+
const relations = defineRelations({
|
|
100
|
+
novels,
|
|
101
|
+
genres,
|
|
102
|
+
novelGenres,
|
|
103
|
+
volumes,
|
|
104
|
+
chapters,
|
|
105
|
+
keywordSearches,
|
|
106
|
+
keywordNovels,
|
|
107
|
+
novelCoverMetadata,
|
|
108
|
+
volumeCoverMetadata,
|
|
109
|
+
cookies,
|
|
110
|
+
generalCache
|
|
111
|
+
}, (r) => ({
|
|
112
|
+
novels: {
|
|
113
|
+
genres: r.many.genres({
|
|
114
|
+
from: r.novels.id.through(r.novelGenres.novelId),
|
|
115
|
+
to: r.genres.id.through(r.novelGenres.genreId)
|
|
116
|
+
}),
|
|
117
|
+
volumes: r.many.volumes({
|
|
118
|
+
from: r.novels.id,
|
|
119
|
+
to: r.volumes.novelId
|
|
120
|
+
}),
|
|
121
|
+
cover: r.one.novelCoverMetadata({
|
|
122
|
+
from: r.novels.id,
|
|
123
|
+
to: r.novelCoverMetadata.novelId
|
|
124
|
+
})
|
|
125
|
+
},
|
|
126
|
+
genres: { novels: r.many.novels() },
|
|
127
|
+
volumes: {
|
|
128
|
+
novel: r.one.novels(),
|
|
129
|
+
chapters: r.many.chapters({
|
|
130
|
+
from: r.volumes.id,
|
|
131
|
+
to: r.chapters.volumeId
|
|
132
|
+
}),
|
|
133
|
+
cover: r.one.volumeCoverMetadata({
|
|
134
|
+
from: r.volumes.id,
|
|
135
|
+
to: r.volumeCoverMetadata.volumeId
|
|
136
|
+
})
|
|
137
|
+
},
|
|
138
|
+
novelCoverMetadata: { novel: r.one.novels({
|
|
139
|
+
from: r.novelCoverMetadata.novelId,
|
|
140
|
+
to: r.novels.id
|
|
141
|
+
}) },
|
|
142
|
+
volumeCoverMetadata: { volume: r.one.volumes({
|
|
143
|
+
from: r.volumeCoverMetadata.volumeId,
|
|
144
|
+
to: r.volumes.id
|
|
145
|
+
}) },
|
|
146
|
+
chapters: {
|
|
147
|
+
novel: r.one.novels({
|
|
148
|
+
from: r.chapters.novelId,
|
|
149
|
+
to: r.novels.id
|
|
150
|
+
}),
|
|
151
|
+
volume: r.one.volumes()
|
|
152
|
+
},
|
|
153
|
+
keywordSearches: { novels: r.many.novels({
|
|
154
|
+
from: r.keywordSearches.keyword.through(r.keywordNovels.keyword),
|
|
155
|
+
to: r.novels.id.through(r.keywordNovels.novelId)
|
|
156
|
+
}) }
|
|
157
|
+
}));
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/cookies.ts
|
|
160
|
+
var DatabaseCookieStore = class {
|
|
161
|
+
db;
|
|
162
|
+
[cookieStoreSign] = true;
|
|
163
|
+
constructor(dbService) {
|
|
164
|
+
this.db = dbService.db;
|
|
165
|
+
}
|
|
166
|
+
async set(name, value, options) {
|
|
167
|
+
const cookie = {
|
|
168
|
+
name,
|
|
169
|
+
value,
|
|
170
|
+
domain: options?.domain ?? "",
|
|
171
|
+
path: options?.path ?? "/",
|
|
172
|
+
expires: options?.expires?.getTime() ?? null,
|
|
173
|
+
maxAge: options?.maxAge ?? null,
|
|
174
|
+
secure: options?.secure ?? false,
|
|
175
|
+
httpOnly: options?.httpOnly ?? false,
|
|
176
|
+
sameSite: options?.sameSite ?? "Lax",
|
|
177
|
+
createdAt: Date.now(),
|
|
178
|
+
lastAccessedAt: Date.now()
|
|
179
|
+
};
|
|
180
|
+
await this.db.insert(cookies).values(cookie).onConflictDoUpdate({
|
|
181
|
+
target: [
|
|
182
|
+
cookies.domain,
|
|
183
|
+
cookies.path,
|
|
184
|
+
cookies.name
|
|
185
|
+
],
|
|
186
|
+
set: {
|
|
187
|
+
value: cookie.value,
|
|
188
|
+
expires: cookie.expires,
|
|
189
|
+
maxAge: cookie.maxAge,
|
|
190
|
+
secure: cookie.secure,
|
|
191
|
+
httpOnly: cookie.httpOnly,
|
|
192
|
+
sameSite: cookie.sameSite,
|
|
193
|
+
createdAt: cookie.createdAt,
|
|
194
|
+
lastAccessedAt: Date.now()
|
|
195
|
+
}
|
|
196
|
+
}).run();
|
|
197
|
+
}
|
|
198
|
+
async get(name, domain, path) {
|
|
199
|
+
const result = await this.db.query.cookies.findFirst({ where: {
|
|
200
|
+
name,
|
|
201
|
+
domain: domain ?? "",
|
|
202
|
+
path: path ?? "/"
|
|
203
|
+
} });
|
|
204
|
+
if (result) {
|
|
205
|
+
await this.db.update(cookies).set({ lastAccessedAt: Date.now() }).where(eq(cookies.id, result.id)).run();
|
|
206
|
+
return result.value;
|
|
207
|
+
}
|
|
208
|
+
const hit = (await this.db.query.cookies.findMany({ where: { name } })).find((cookie) => {
|
|
209
|
+
if (domain && cookie.domain && !matchesDomain(cookie.domain, domain)) return false;
|
|
210
|
+
if (path && cookie.path && !matchesPath(cookie.path, path)) return false;
|
|
211
|
+
return true;
|
|
212
|
+
});
|
|
213
|
+
if (!hit) return null;
|
|
214
|
+
await this.db.update(cookies).set({ lastAccessedAt: Date.now() }).where(eq(cookies.id, hit.id)).run();
|
|
215
|
+
return hit.value;
|
|
216
|
+
}
|
|
217
|
+
async getCookie(name, domain, path) {
|
|
218
|
+
const result = await this.db.query.cookies.findFirst({ where: {
|
|
219
|
+
name,
|
|
220
|
+
domain: domain ?? "",
|
|
221
|
+
path: path ?? "/"
|
|
222
|
+
} });
|
|
223
|
+
if (result) {
|
|
224
|
+
await this.db.update(cookies).set({ lastAccessedAt: Date.now() }).where(eq(cookies.id, result.id)).run();
|
|
225
|
+
return {
|
|
226
|
+
name: result.name,
|
|
227
|
+
value: result.value,
|
|
228
|
+
domain: result.domain,
|
|
229
|
+
path: result.path,
|
|
230
|
+
expires: result.expires ? new Date(result.expires) : void 0,
|
|
231
|
+
maxAge: result.maxAge ?? void 0,
|
|
232
|
+
secure: result.secure ?? void 0,
|
|
233
|
+
httpOnly: result.httpOnly ?? void 0,
|
|
234
|
+
sameSite: result.sameSite ?? "Lax"
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
const hit = (await this.db.query.cookies.findMany({ where: { name } })).find((cookie) => {
|
|
238
|
+
if (domain && cookie.domain && !matchesDomain(cookie.domain, domain)) return false;
|
|
239
|
+
if (path && cookie.path && !matchesPath(cookie.path, path)) return false;
|
|
240
|
+
return true;
|
|
241
|
+
});
|
|
242
|
+
if (!hit) return null;
|
|
243
|
+
await this.db.update(cookies).set({ lastAccessedAt: Date.now() }).where(eq(cookies.id, hit.id)).run();
|
|
244
|
+
return {
|
|
245
|
+
name: hit.name,
|
|
246
|
+
value: hit.value,
|
|
247
|
+
domain: hit.domain,
|
|
248
|
+
path: hit.path,
|
|
249
|
+
expires: hit.expires ? new Date(hit.expires) : void 0,
|
|
250
|
+
maxAge: hit.maxAge ?? void 0,
|
|
251
|
+
secure: hit.secure ?? void 0,
|
|
252
|
+
httpOnly: hit.httpOnly ?? void 0,
|
|
253
|
+
sameSite: hit.sameSite ?? "Lax"
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
async delete(name, domain, path) {
|
|
257
|
+
const result = await this.db.query.cookies.findFirst({ where: {
|
|
258
|
+
name,
|
|
259
|
+
domain: domain ?? "",
|
|
260
|
+
path: path ?? "/"
|
|
261
|
+
} });
|
|
262
|
+
if (result) {
|
|
263
|
+
await this.db.delete(cookies).where(eq(cookies.id, result.id)).run();
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
const hit = (await this.db.query.cookies.findMany({ where: { name } })).find((cookie) => {
|
|
267
|
+
if (domain && cookie.domain && !matchesDomain(cookie.domain, domain)) return false;
|
|
268
|
+
if (path && cookie.path && !matchesPath(cookie.path, path)) return false;
|
|
269
|
+
return true;
|
|
270
|
+
});
|
|
271
|
+
if (!hit) return false;
|
|
272
|
+
await this.db.delete(cookies).where(eq(cookies.id, hit.id)).run();
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
async clear(domain, path) {
|
|
276
|
+
if (!domain && !path) {
|
|
277
|
+
await this.db.delete(cookies).run();
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
await this.db.transaction(async (tx) => {
|
|
281
|
+
const toDelete = (await tx.query.cookies.findMany()).filter((cookie) => {
|
|
282
|
+
if (domain && cookie.domain && !matchesDomain(cookie.domain, domain)) return false;
|
|
283
|
+
if (path && cookie.path && !matchesPath(cookie.path, path)) return false;
|
|
284
|
+
return true;
|
|
285
|
+
});
|
|
286
|
+
for (const cookie of toDelete) await tx.delete(cookies).where(eq(cookies.id, cookie.id)).run();
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
async has(name, domain, path) {
|
|
290
|
+
return await this.get(name, domain, path) !== null;
|
|
291
|
+
}
|
|
292
|
+
async getForUrl(url) {
|
|
293
|
+
const parsedUrl = typeof url === "string" ? new URL(url) : url;
|
|
294
|
+
const hostname = parsedUrl.hostname;
|
|
295
|
+
const pathname = parsedUrl.pathname;
|
|
296
|
+
const now = Date.now();
|
|
297
|
+
const secure = parsedUrl.protocol === "https:";
|
|
298
|
+
return (await this.db.query.cookies.findMany()).filter((cookie) => {
|
|
299
|
+
if (cookie.secure && !secure) return false;
|
|
300
|
+
if (cookie.domain && !matchesDomain(cookie.domain, hostname)) return false;
|
|
301
|
+
if (cookie.path && !matchesPath(cookie.path, pathname)) return false;
|
|
302
|
+
if (cookie.expires && cookie.expires < now) return false;
|
|
303
|
+
if (cookie.maxAge) {
|
|
304
|
+
if ((now - cookie.createdAt) / 1e3 > cookie.maxAge) return false;
|
|
305
|
+
}
|
|
306
|
+
return true;
|
|
307
|
+
}).map((cookie) => ({
|
|
308
|
+
name: cookie.name,
|
|
309
|
+
value: cookie.value,
|
|
310
|
+
domain: cookie.domain,
|
|
311
|
+
path: cookie.path,
|
|
312
|
+
expires: cookie.expires ? new Date(cookie.expires) : void 0,
|
|
313
|
+
maxAge: cookie.maxAge ?? void 0,
|
|
314
|
+
secure: cookie.secure ?? void 0,
|
|
315
|
+
httpOnly: cookie.httpOnly ?? void 0,
|
|
316
|
+
sameSite: cookie.sameSite ?? "Lax"
|
|
317
|
+
}));
|
|
318
|
+
}
|
|
319
|
+
async update(init) {
|
|
320
|
+
if (isCookiesStore(init)) for await (const cookie of init) await this.set(cookie.name, cookie.value, {
|
|
321
|
+
domain: cookie.domain,
|
|
322
|
+
path: cookie.path,
|
|
323
|
+
expires: cookie.expires,
|
|
324
|
+
maxAge: cookie.maxAge,
|
|
325
|
+
secure: cookie.secure,
|
|
326
|
+
httpOnly: cookie.httpOnly,
|
|
327
|
+
sameSite: cookie.sameSite ?? "Lax"
|
|
328
|
+
});
|
|
329
|
+
else if (Array.isArray(init)) for (const cookie of init) await this.set(cookie.name, cookie.value, {
|
|
330
|
+
domain: cookie.domain,
|
|
331
|
+
path: cookie.path,
|
|
332
|
+
expires: cookie.expires,
|
|
333
|
+
maxAge: cookie.maxAge,
|
|
334
|
+
secure: cookie.secure,
|
|
335
|
+
httpOnly: cookie.httpOnly,
|
|
336
|
+
sameSite: cookie.sameSite ?? "Lax"
|
|
337
|
+
});
|
|
338
|
+
else if (typeof init === "object") if (Symbol.iterator in init) for (const [name, value] of init) await this.set(name, value);
|
|
339
|
+
else for (const [name, value] of Object.entries(init)) await this.set(name, value);
|
|
340
|
+
}
|
|
341
|
+
[Symbol.asyncIterator]() {
|
|
342
|
+
const allCookies = this.db.query.cookies.findMany();
|
|
343
|
+
let index = 0;
|
|
344
|
+
return { next: async () => {
|
|
345
|
+
const cookies = await allCookies;
|
|
346
|
+
if (index < cookies.length) {
|
|
347
|
+
const cookie = cookies[index++];
|
|
348
|
+
return { value: {
|
|
349
|
+
name: cookie.name,
|
|
350
|
+
value: cookie.value,
|
|
351
|
+
domain: cookie.domain,
|
|
352
|
+
path: cookie.path,
|
|
353
|
+
expires: cookie.expires ? new Date(cookie.expires) : void 0,
|
|
354
|
+
maxAge: cookie.maxAge ?? void 0,
|
|
355
|
+
secure: cookie.secure ?? void 0,
|
|
356
|
+
httpOnly: cookie.httpOnly ?? void 0,
|
|
357
|
+
sameSite: cookie.sameSite ?? "Lax"
|
|
358
|
+
} };
|
|
359
|
+
}
|
|
360
|
+
return {
|
|
361
|
+
done: true,
|
|
362
|
+
value: void 0
|
|
363
|
+
};
|
|
364
|
+
} };
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
//#endregion
|
|
368
|
+
//#region src/db.ts
|
|
369
|
+
function getDrizzle(client) {
|
|
370
|
+
return drizzle({
|
|
371
|
+
client,
|
|
372
|
+
relations
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
var DatabaseService = class {
|
|
376
|
+
client;
|
|
377
|
+
db;
|
|
378
|
+
constructor(options) {
|
|
379
|
+
const parentDir = dirname(resolve(options.path));
|
|
380
|
+
if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true });
|
|
381
|
+
else if (existsSync(parentDir) && statSync(parentDir).isFile() === true) {
|
|
382
|
+
rmSync(parentDir);
|
|
383
|
+
mkdirSync(parentDir, { recursive: true });
|
|
384
|
+
}
|
|
385
|
+
this.client = createClient({ url: `file:${options.path}` });
|
|
386
|
+
this.client.execute("PRAGMA journal_mode = WAL;");
|
|
387
|
+
this.db = getDrizzle(this.client);
|
|
388
|
+
if (options.migrations?.enabled ?? true) this._migrate(options.migrations?.directory);
|
|
389
|
+
}
|
|
390
|
+
_migrate(directory) {
|
|
391
|
+
if (!this.db) throw new Error("Database not initialized");
|
|
392
|
+
migrate(this.db, { migrationsFolder: directory || "migrations" });
|
|
393
|
+
}
|
|
394
|
+
async addSearchResult(keyword, platform, results) {
|
|
395
|
+
await this.db.transaction(async (tx) => {
|
|
396
|
+
await tx.insert(keywordSearches).values({
|
|
397
|
+
keyword,
|
|
398
|
+
platform,
|
|
399
|
+
queryTime: Date.now(),
|
|
400
|
+
total: results.length
|
|
401
|
+
}).onConflictDoUpdate({
|
|
402
|
+
target: keywordSearches.keyword,
|
|
403
|
+
set: {
|
|
404
|
+
queryTime: Date.now(),
|
|
405
|
+
total: results.length
|
|
406
|
+
}
|
|
407
|
+
}).run();
|
|
408
|
+
for (const novel of results) {
|
|
409
|
+
const novelId = (await tx.insert(novels).values({
|
|
410
|
+
platform: novel.platform,
|
|
411
|
+
platformId: novel.id,
|
|
412
|
+
name: novel.title,
|
|
413
|
+
coverUrl: novel.coverUrl ?? "",
|
|
414
|
+
author: "",
|
|
415
|
+
summary: "",
|
|
416
|
+
status: "unknown",
|
|
417
|
+
updateAt: Date.now()
|
|
418
|
+
}).onConflictDoUpdate({
|
|
419
|
+
target: [novels.platform, novels.platformId],
|
|
420
|
+
set: {
|
|
421
|
+
name: novel.title,
|
|
422
|
+
coverUrl: novel.coverUrl ?? "",
|
|
423
|
+
updateAt: Date.now()
|
|
424
|
+
}
|
|
425
|
+
}).returning({ id: novels.id }).get()).id;
|
|
426
|
+
if (novelId) await tx.insert(keywordNovels).values({
|
|
427
|
+
novelId,
|
|
428
|
+
keyword
|
|
429
|
+
}).onConflictDoNothing().run();
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
async searchNovels(keyword, platform) {
|
|
434
|
+
const minQueryTime = Date.now() - 2880 * 60 * 1e3;
|
|
435
|
+
const searchRecord = await this.db.query.keywordSearches.findFirst({
|
|
436
|
+
where: {
|
|
437
|
+
keyword,
|
|
438
|
+
platform,
|
|
439
|
+
queryTime: { gte: minQueryTime }
|
|
440
|
+
},
|
|
441
|
+
with: { novels: { columns: {
|
|
442
|
+
platform: true,
|
|
443
|
+
platformId: true,
|
|
444
|
+
name: true,
|
|
445
|
+
coverUrl: true
|
|
446
|
+
} } }
|
|
447
|
+
}).execute();
|
|
448
|
+
return {
|
|
449
|
+
data: searchRecord?.novels.map((novel) => ({
|
|
450
|
+
platform: novel.platform,
|
|
451
|
+
id: novel.platformId,
|
|
452
|
+
title: novel.name,
|
|
453
|
+
coverUrl: novel.coverUrl
|
|
454
|
+
})) || void 0,
|
|
455
|
+
updatedAt: searchRecord?.queryTime || 0
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
async addNovelCache(novel) {
|
|
459
|
+
await this.db.transaction(async (tx) => {
|
|
460
|
+
const { id: novelId } = await tx.insert(novels).values({
|
|
461
|
+
platform: novel.platform,
|
|
462
|
+
platformId: novel.id,
|
|
463
|
+
name: novel.title,
|
|
464
|
+
coverUrl: novel.coverUrl ?? "",
|
|
465
|
+
author: novel.author ?? "",
|
|
466
|
+
summary: novel.summary ?? "",
|
|
467
|
+
status: novel.status ?? "unknown",
|
|
468
|
+
updateAt: Date.now()
|
|
469
|
+
}).onConflictDoUpdate({
|
|
470
|
+
target: [novels.platform, novels.platformId],
|
|
471
|
+
set: {
|
|
472
|
+
name: novel.title,
|
|
473
|
+
coverUrl: novel.coverUrl ?? "",
|
|
474
|
+
author: novel.author ?? "",
|
|
475
|
+
summary: novel.summary ?? "",
|
|
476
|
+
status: novel.status ?? "unknown",
|
|
477
|
+
updateAt: Date.now()
|
|
478
|
+
}
|
|
479
|
+
}).returning({ id: novels.id }).get();
|
|
480
|
+
for (const genre of novel.genres) {
|
|
481
|
+
const { id: genreId } = await tx.insert(genres).values({ name: genre }).onConflictDoUpdate({
|
|
482
|
+
target: genres.name,
|
|
483
|
+
set: { name: genre }
|
|
484
|
+
}).returning({ id: genres.id }).get();
|
|
485
|
+
await tx.insert(novelGenres).values({
|
|
486
|
+
novelId,
|
|
487
|
+
genreId
|
|
488
|
+
}).onConflictDoNothing().run();
|
|
489
|
+
}
|
|
490
|
+
for (const volume of novel.volumes) {
|
|
491
|
+
const { id: volumeId } = await tx.insert(volumes).values({
|
|
492
|
+
novelId,
|
|
493
|
+
name: volume.title,
|
|
494
|
+
platform: novel.platform,
|
|
495
|
+
platformId: volume.id,
|
|
496
|
+
coverUrl: volume.coverUrl ?? ""
|
|
497
|
+
}).onConflictDoUpdate({
|
|
498
|
+
target: [volumes.novelId, volumes.platformId],
|
|
499
|
+
set: {
|
|
500
|
+
name: volume.title,
|
|
501
|
+
coverUrl: volume.coverUrl ?? ""
|
|
502
|
+
}
|
|
503
|
+
}).returning({ id: volumes.id }).get();
|
|
504
|
+
for (const chapter of volume.chapters) await tx.insert(chapters).values({
|
|
505
|
+
novelId,
|
|
506
|
+
volumeId,
|
|
507
|
+
name: chapter.title,
|
|
508
|
+
platform: novel.platform,
|
|
509
|
+
platformId: chapter.id
|
|
510
|
+
}).onConflictDoUpdate({
|
|
511
|
+
target: [chapters.novelId, chapters.platformId],
|
|
512
|
+
set: { name: chapter.title }
|
|
513
|
+
}).run();
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
async getNovelCache(platform, platformId) {
|
|
518
|
+
const novelRecord = await this.db.query.novels.findFirst({
|
|
519
|
+
where: {
|
|
520
|
+
platform,
|
|
521
|
+
platformId
|
|
522
|
+
},
|
|
523
|
+
with: {
|
|
524
|
+
genres: true,
|
|
525
|
+
volumes: {
|
|
526
|
+
orderBy: { id: "asc" },
|
|
527
|
+
with: { chapters: { orderBy: { id: "asc" } } }
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}).execute();
|
|
531
|
+
if (!novelRecord) return {
|
|
532
|
+
data: null,
|
|
533
|
+
updatedAt: 0
|
|
534
|
+
};
|
|
535
|
+
return {
|
|
536
|
+
data: {
|
|
537
|
+
platform: novelRecord.platform,
|
|
538
|
+
id: novelRecord.platformId,
|
|
539
|
+
title: novelRecord.name,
|
|
540
|
+
coverUrl: novelRecord.coverUrl,
|
|
541
|
+
author: novelRecord.author,
|
|
542
|
+
summary: novelRecord.summary,
|
|
543
|
+
status: novelRecord.status,
|
|
544
|
+
genres: novelRecord.genres.map((g) => g.name),
|
|
545
|
+
volumes: novelRecord.volumes.map((v) => ({
|
|
546
|
+
id: v.platformId,
|
|
547
|
+
platform: novelRecord.platform,
|
|
548
|
+
title: v.name,
|
|
549
|
+
coverUrl: v.coverUrl ?? "",
|
|
550
|
+
novelId: novelRecord.platformId,
|
|
551
|
+
chapters: v.chapters.map((c) => ({
|
|
552
|
+
id: c.platformId,
|
|
553
|
+
platform: novelRecord.platform,
|
|
554
|
+
title: c.name
|
|
555
|
+
}))
|
|
556
|
+
}))
|
|
557
|
+
},
|
|
558
|
+
updatedAt: novelRecord.updateAt
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
async getVolumeMeta(platform, platformId) {
|
|
562
|
+
const volumeRecord = await this.db.query.volumes.findFirst({
|
|
563
|
+
where: {
|
|
564
|
+
platform,
|
|
565
|
+
platformId
|
|
566
|
+
},
|
|
567
|
+
with: {
|
|
568
|
+
novel: true,
|
|
569
|
+
chapters: { orderBy: { id: "asc" } }
|
|
570
|
+
},
|
|
571
|
+
orderBy: { id: "asc" }
|
|
572
|
+
}).execute();
|
|
573
|
+
if (!volumeRecord) return;
|
|
574
|
+
return {
|
|
575
|
+
id: volumeRecord.platformId,
|
|
576
|
+
platform: volumeRecord.platform,
|
|
577
|
+
title: volumeRecord.name,
|
|
578
|
+
novelId: volumeRecord.novel?.platformId ?? "",
|
|
579
|
+
coverUrl: volumeRecord.coverUrl ?? "",
|
|
580
|
+
chapters: []
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
async getChapterFromTitle(title) {
|
|
584
|
+
const chapterRecord = await this.db.query.chapters.findFirst({ where: { name: title } }).execute();
|
|
585
|
+
if (!chapterRecord) return;
|
|
586
|
+
return {
|
|
587
|
+
id: chapterRecord.platformId,
|
|
588
|
+
title: chapterRecord.name
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
async getChapterFromId(platform, platformId) {
|
|
592
|
+
const chapterRecord = await this.db.query.chapters.findFirst({
|
|
593
|
+
where: {
|
|
594
|
+
platformId,
|
|
595
|
+
novel: { platform }
|
|
596
|
+
},
|
|
597
|
+
with: {
|
|
598
|
+
novel: true,
|
|
599
|
+
volume: true
|
|
600
|
+
}
|
|
601
|
+
}).execute();
|
|
602
|
+
if (!chapterRecord) return;
|
|
603
|
+
return {
|
|
604
|
+
id: chapterRecord.platformId,
|
|
605
|
+
platform: chapterRecord.platform,
|
|
606
|
+
title: chapterRecord.name,
|
|
607
|
+
novelId: chapterRecord.novel?.platformId ?? "",
|
|
608
|
+
volumeId: chapterRecord.volume?.platformId ?? "",
|
|
609
|
+
contentHash: chapterRecord.contentHash ?? null
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
async addNovelContentHash(platform, chapterId, contentHash) {
|
|
613
|
+
await this.db.update(chapters).set({ contentHash }).where(and(eq(chapters.platformId, chapterId), eq(chapters.platform, platform))).run();
|
|
614
|
+
}
|
|
615
|
+
async getNovelCoverMetadata(platform, novelId) {
|
|
616
|
+
const queryResult = await this.db.query.novelCoverMetadata.findFirst({
|
|
617
|
+
where: { novel: {
|
|
618
|
+
platform,
|
|
619
|
+
platformId: novelId
|
|
620
|
+
} },
|
|
621
|
+
with: { novel: true }
|
|
622
|
+
}).execute();
|
|
623
|
+
if (!queryResult) return;
|
|
624
|
+
return {
|
|
625
|
+
platform: queryResult.novel?.platform ?? null,
|
|
626
|
+
novelId: queryResult.novel?.platformId ?? null,
|
|
627
|
+
hash: queryResult.hash ?? "",
|
|
628
|
+
contentType: queryResult.contentType ?? "",
|
|
629
|
+
originalUrl: queryResult.originalUrl ?? ""
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
async addNovelCoverMetadata(metadata) {
|
|
633
|
+
const novel = metadata.novelId && metadata.platform ? await this.db.query.novels.findFirst({ where: {
|
|
634
|
+
platform: metadata.platform,
|
|
635
|
+
platformId: metadata.novelId
|
|
636
|
+
} }).execute() : null;
|
|
637
|
+
await this.db.insert(novelCoverMetadata).values({
|
|
638
|
+
hash: metadata.hash,
|
|
639
|
+
contentType: metadata.contentType,
|
|
640
|
+
originalUrl: metadata.originalUrl,
|
|
641
|
+
novelId: novel?.id ?? null
|
|
642
|
+
}).run();
|
|
643
|
+
}
|
|
644
|
+
async getVolumeCoverMetadata(platform, volumeId) {
|
|
645
|
+
const queryResult = await this.db.query.volumeCoverMetadata.findFirst({
|
|
646
|
+
where: { volume: {
|
|
647
|
+
platform,
|
|
648
|
+
platformId: volumeId
|
|
649
|
+
} },
|
|
650
|
+
with: { volume: { with: { novel: true } } }
|
|
651
|
+
}).execute();
|
|
652
|
+
if (!queryResult) return;
|
|
653
|
+
return {
|
|
654
|
+
platform: queryResult.volume?.platform ?? null,
|
|
655
|
+
volumeId: queryResult.volume?.platformId ?? null,
|
|
656
|
+
hash: queryResult.hash ?? "",
|
|
657
|
+
contentType: queryResult.contentType ?? "",
|
|
658
|
+
originalUrl: queryResult.originalUrl ?? ""
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
async addVolumeCoverMetadata(metadata) {
|
|
662
|
+
const volume = metadata.volumeId && metadata.platform ? await this.db.query.volumes.findFirst({ where: {
|
|
663
|
+
platform: metadata.platform,
|
|
664
|
+
platformId: metadata.volumeId
|
|
665
|
+
} }).execute() : null;
|
|
666
|
+
await this.db.insert(volumeCoverMetadata).values({
|
|
667
|
+
hash: metadata.hash,
|
|
668
|
+
contentType: metadata.contentType,
|
|
669
|
+
originalUrl: metadata.originalUrl,
|
|
670
|
+
volumeId: volume?.id ?? null
|
|
671
|
+
}).run();
|
|
672
|
+
}
|
|
673
|
+
async getCache(key, schema) {
|
|
674
|
+
const record = await this.db.query.generalCache.findFirst({ where: { key } }).execute();
|
|
675
|
+
if (!record) return null;
|
|
676
|
+
const parsed = schema.safeParse(record.value);
|
|
677
|
+
return parsed.success ? parsed.data : null;
|
|
678
|
+
}
|
|
679
|
+
async setCache(key, value) {
|
|
680
|
+
await this.db.insert(generalCache).values({
|
|
681
|
+
key,
|
|
682
|
+
value
|
|
683
|
+
}).onConflictDoUpdate({
|
|
684
|
+
target: generalCache.key,
|
|
685
|
+
set: { value }
|
|
686
|
+
}).run();
|
|
687
|
+
}
|
|
688
|
+
async close(logger) {
|
|
689
|
+
try {
|
|
690
|
+
await this.client.execute("PRAGMA journal_mode = DELETE;");
|
|
691
|
+
logger?.("WAL写入盘完成,正在关闭数据库连接...");
|
|
692
|
+
} catch (error) {
|
|
693
|
+
logger?.(`执行WAL检查点时发生错误: ${error}`);
|
|
694
|
+
} finally {
|
|
695
|
+
this.client.close();
|
|
696
|
+
logger?.("数据库连接已关闭");
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
//#endregion
|
|
701
|
+
//#region src/utils.ts
|
|
702
|
+
const zstdCompress$1 = (data) => {
|
|
703
|
+
return new Promise((resolve, reject) => {
|
|
704
|
+
zstdCompress(data, (err, compressedData) => {
|
|
705
|
+
if (err) reject(err);
|
|
706
|
+
else resolve(compressedData);
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
};
|
|
710
|
+
const zstdDecompress$1 = (data) => {
|
|
711
|
+
return new Promise((resolve, reject) => {
|
|
712
|
+
zstdDecompress(data, (err, decompressedData) => {
|
|
713
|
+
if (err) reject(err);
|
|
714
|
+
else resolve(decompressedData);
|
|
715
|
+
});
|
|
716
|
+
});
|
|
717
|
+
};
|
|
718
|
+
function getCoverHash(data) {
|
|
719
|
+
return createHash("md5").update(data).digest("hex");
|
|
720
|
+
}
|
|
721
|
+
function getContentHash(content) {
|
|
722
|
+
return createHash("md5").update(content).digest("hex");
|
|
723
|
+
}
|
|
724
|
+
function getExtFromContentType(contentType) {
|
|
725
|
+
if (contentType.includes("jpeg") || contentType.includes("jpg")) return "jpg";
|
|
726
|
+
if (contentType.includes("png")) return "png";
|
|
727
|
+
if (contentType.includes("gif")) return "gif";
|
|
728
|
+
if (contentType.includes("webp")) return "webp";
|
|
729
|
+
if (contentType.includes("avif")) return "avif";
|
|
730
|
+
return "bin";
|
|
731
|
+
}
|
|
732
|
+
//#endregion
|
|
733
|
+
//#region src/files.ts
|
|
734
|
+
var FSStorageService = class {
|
|
735
|
+
basePath;
|
|
736
|
+
dbService;
|
|
737
|
+
constructor(basePath, dbService) {
|
|
738
|
+
this.basePath = basePath;
|
|
739
|
+
this.dbService = dbService;
|
|
740
|
+
}
|
|
741
|
+
async _initPath(path) {
|
|
742
|
+
if (!existsSync(path)) await mkdir(path, { recursive: true });
|
|
743
|
+
else if (existsSync(path) && !(await stat(path)).isDirectory()) {
|
|
744
|
+
await rm(path);
|
|
745
|
+
await mkdir(path, { recursive: true });
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
async getNovelContent(hash) {
|
|
749
|
+
const chapterFilePath = `${`${this.basePath}/novels/${hash.slice(0, 2)}`}/${hash}.zst`;
|
|
750
|
+
if (!existsSync(chapterFilePath)) return;
|
|
751
|
+
const decompressedData = await zstdDecompress$1(await readFile(chapterFilePath));
|
|
752
|
+
return new TextDecoder().decode(decompressedData);
|
|
753
|
+
}
|
|
754
|
+
async setNovelContent(content) {
|
|
755
|
+
const hash = getContentHash(content);
|
|
756
|
+
const novelCacheDir = `${this.basePath}/novels/${hash.slice(0, 2)}`;
|
|
757
|
+
await this._initPath(novelCacheDir);
|
|
758
|
+
await writeFile(`${novelCacheDir}/${hash}.zst`, await zstdCompress$1(Buffer.from(content, "utf-8")));
|
|
759
|
+
return hash;
|
|
760
|
+
}
|
|
761
|
+
async getCoverData(type, platform, platformId) {
|
|
762
|
+
let meta;
|
|
763
|
+
if (type === "novel") meta = await this.dbService.getNovelCoverMetadata(platform, platformId);
|
|
764
|
+
else if (type === "volume") meta = await this.dbService.getVolumeCoverMetadata(platform, platformId);
|
|
765
|
+
if (!meta) return;
|
|
766
|
+
const coverPath = `${this.basePath}/covers/${meta.hash.slice(0, 2)}/${meta.hash}.${getExtFromContentType(meta.contentType)}`;
|
|
767
|
+
if (!existsSync(coverPath)) return;
|
|
768
|
+
return {
|
|
769
|
+
data: await readFile(coverPath),
|
|
770
|
+
mimeType: meta.contentType
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
async setCoverData(type, url, platform, platformId, data, contentType) {
|
|
774
|
+
const coverHash = getCoverHash(data);
|
|
775
|
+
const ext = getExtFromContentType(contentType);
|
|
776
|
+
const coverDir = `${this.basePath}/covers/${coverHash.slice(0, 2)}`;
|
|
777
|
+
await this._initPath(coverDir);
|
|
778
|
+
await writeFile(`${coverDir}/${coverHash}.${ext}`, data);
|
|
779
|
+
if (type === "novel") await this.dbService.addNovelCoverMetadata({
|
|
780
|
+
platform,
|
|
781
|
+
novelId: platformId,
|
|
782
|
+
hash: coverHash,
|
|
783
|
+
contentType,
|
|
784
|
+
originalUrl: url
|
|
785
|
+
});
|
|
786
|
+
else if (type === "volume") await this.dbService.addVolumeCoverMetadata({
|
|
787
|
+
platform,
|
|
788
|
+
volumeId: platformId,
|
|
789
|
+
hash: coverHash,
|
|
790
|
+
contentType,
|
|
791
|
+
originalUrl: url
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
//#endregion
|
|
796
|
+
//#region src/service.ts
|
|
797
|
+
var StorageService = class {
|
|
798
|
+
db;
|
|
799
|
+
files;
|
|
800
|
+
cookieStore;
|
|
801
|
+
constructor(options) {
|
|
802
|
+
this.db = new DatabaseService(options.db);
|
|
803
|
+
this.files = new FSStorageService(options.dataDir ?? "", this.db);
|
|
804
|
+
this.cookieStore = new DatabaseCookieStore(this.db);
|
|
805
|
+
}
|
|
806
|
+
async getNovelContent(hash) {
|
|
807
|
+
return await this.files.getNovelContent(hash);
|
|
808
|
+
}
|
|
809
|
+
async setNovelContent(content) {
|
|
810
|
+
return await this.files.setNovelContent(content);
|
|
811
|
+
}
|
|
812
|
+
async getCoverData(type, platform, platformId) {
|
|
813
|
+
return await this.files.getCoverData(type, platform, platformId);
|
|
814
|
+
}
|
|
815
|
+
async setCoverData(type, url, data, contentType, platform, platformId) {
|
|
816
|
+
await this.files.setCoverData(type, url, platform, platformId, data, contentType);
|
|
817
|
+
}
|
|
818
|
+
async addSearchResult(keyword, platform, results) {
|
|
819
|
+
await this.db.addSearchResult(keyword, platform, results);
|
|
820
|
+
}
|
|
821
|
+
async searchNovels(keyword, platform) {
|
|
822
|
+
const data = await this.db.searchNovels(keyword, platform);
|
|
823
|
+
return data ? data.data : void 0;
|
|
824
|
+
}
|
|
825
|
+
async getNovelCache(platform, platformId) {
|
|
826
|
+
const data = await this.db.getNovelCache(platform, platformId);
|
|
827
|
+
return data ? data.data : void 0;
|
|
828
|
+
}
|
|
829
|
+
async addNovelCache(novel) {
|
|
830
|
+
await this.db.addNovelCache(novel);
|
|
831
|
+
}
|
|
832
|
+
async getVolumeMeta(platform, platformId) {
|
|
833
|
+
return await this.db.getVolumeMeta(platform, platformId);
|
|
834
|
+
}
|
|
835
|
+
async getChapterFromTitle(title) {
|
|
836
|
+
return await this.db.getChapterFromTitle(title);
|
|
837
|
+
}
|
|
838
|
+
async getChapterFromId(platform, platformId) {
|
|
839
|
+
return await this.db.getChapterFromId(platform, platformId);
|
|
840
|
+
}
|
|
841
|
+
async addNovelContentHash(platform, chapterId, contentHash) {
|
|
842
|
+
await this.db.addNovelContentHash(platform, chapterId, contentHash);
|
|
843
|
+
}
|
|
844
|
+
getCookieStore() {
|
|
845
|
+
return this.cookieStore;
|
|
846
|
+
}
|
|
847
|
+
async getCache(key, schema) {
|
|
848
|
+
return await this.db.getCache(key, schema);
|
|
849
|
+
}
|
|
850
|
+
async setCache(key, value) {
|
|
851
|
+
await this.db.setCache(key, value);
|
|
852
|
+
}
|
|
853
|
+
async close(logger) {
|
|
854
|
+
await this.db.close(logger);
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
//#endregion
|
|
858
|
+
export { DatabaseCookieStore, DatabaseService, FSStorageService, StorageService };
|
|
859
|
+
|
|
860
|
+
//# sourceMappingURL=index.mjs.map
|