@acanthis-dec/storage 1.0.7 → 1.1.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/dist/index.d.mts +606 -35
- package/dist/index.mjs +448 -68
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -11
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
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";
|
|
2
|
+
import { and, count, defineRelations, desc, eq, gt, inArray, isNull, max, ne, notInArray } from "drizzle-orm";
|
|
3
|
+
import { integer, primaryKey, sqliteTable, text, unique, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
4
4
|
import { existsSync, mkdirSync, rmSync, statSync } from "node:fs";
|
|
5
5
|
import { dirname, resolve } from "node:path";
|
|
6
6
|
import { createClient } from "@libsql/client";
|
|
7
7
|
import { drizzle } from "drizzle-orm/libsql";
|
|
8
8
|
import { migrate } from "drizzle-orm/libsql/migrator";
|
|
9
|
-
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
10
9
|
import { createHash } from "node:crypto";
|
|
11
|
-
import { zstdCompress, zstdDecompress } from "node:zlib";
|
|
12
|
-
|
|
10
|
+
import { zstdCompress as zstdCompress$1, zstdDecompress as zstdDecompress$1 } from "node:zlib";
|
|
11
|
+
import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
12
|
+
// src/table.ts
|
|
13
13
|
const novels = sqliteTable("novels", {
|
|
14
14
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
15
15
|
platform: text("platform").notNull(),
|
|
@@ -96,6 +96,43 @@ const generalCache = sqliteTable("general_cache", {
|
|
|
96
96
|
key: text("key").primaryKey(),
|
|
97
97
|
value: text("value", { mode: "json" }).notNull()
|
|
98
98
|
});
|
|
99
|
+
const illustrationMetadata = sqliteTable("illustration_metadata", {
|
|
100
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
101
|
+
platform: text("platform").notNull(),
|
|
102
|
+
urlHash: text("url_hash").notNull(),
|
|
103
|
+
originalUrl: text("original_url").notNull(),
|
|
104
|
+
fileHash: text("file_hash"),
|
|
105
|
+
contentType: text("content_type"),
|
|
106
|
+
createdAt: integer("created_at").notNull()
|
|
107
|
+
}, (table) => [uniqueIndex("illustration_platform_url_hash_idx").on(table.platform, table.urlHash)]);
|
|
108
|
+
const bookshelfItems = sqliteTable("bookshelf_items", {
|
|
109
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
110
|
+
platform: text("platform").notNull(),
|
|
111
|
+
novelId: text("novel_id").notNull(),
|
|
112
|
+
title: text("title").notNull(),
|
|
113
|
+
author: text("author").notNull(),
|
|
114
|
+
coverUrl: text("cover_url").notNull(),
|
|
115
|
+
addedAt: integer("added_at").notNull(),
|
|
116
|
+
updatedAt: integer("updated_at").notNull(),
|
|
117
|
+
serverUpdatedAt: integer("server_updated_at").notNull(),
|
|
118
|
+
deletedAt: integer("deleted_at")
|
|
119
|
+
}, (table) => [uniqueIndex("bookshelf_platform_novel_idx").on(table.platform, table.novelId)]);
|
|
120
|
+
const readingProgress = sqliteTable("reading_progress", {
|
|
121
|
+
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
122
|
+
platform: text("platform").notNull(),
|
|
123
|
+
novelId: text("novel_id").notNull(),
|
|
124
|
+
novelTitle: text("novel_title").notNull(),
|
|
125
|
+
coverUrl: text("cover_url").notNull(),
|
|
126
|
+
volumeId: text("volume_id").notNull(),
|
|
127
|
+
volumeTitle: text("volume_title").notNull(),
|
|
128
|
+
chapterId: text("chapter_id").notNull(),
|
|
129
|
+
chapterTitle: text("chapter_title").notNull(),
|
|
130
|
+
paragraphIndex: integer("paragraph_index").notNull(),
|
|
131
|
+
totalParagraphs: integer("total_paragraphs").notNull(),
|
|
132
|
+
deviceLabel: text("device_label").notNull(),
|
|
133
|
+
updatedAt: integer("updated_at").notNull(),
|
|
134
|
+
serverUpdatedAt: integer("server_updated_at").notNull()
|
|
135
|
+
}, (table) => [uniqueIndex("reading_progress_platform_novel_idx").on(table.platform, table.novelId)]);
|
|
99
136
|
const relations = defineRelations({
|
|
100
137
|
novels,
|
|
101
138
|
genres,
|
|
@@ -107,7 +144,10 @@ const relations = defineRelations({
|
|
|
107
144
|
novelCoverMetadata,
|
|
108
145
|
volumeCoverMetadata,
|
|
109
146
|
cookies,
|
|
110
|
-
generalCache
|
|
147
|
+
generalCache,
|
|
148
|
+
illustrationMetadata,
|
|
149
|
+
bookshelfItems,
|
|
150
|
+
readingProgress
|
|
111
151
|
}, (r) => ({
|
|
112
152
|
novels: {
|
|
113
153
|
genres: r.many.genres({
|
|
@@ -155,8 +195,7 @@ const relations = defineRelations({
|
|
|
155
195
|
to: r.novels.id.through(r.keywordNovels.novelId)
|
|
156
196
|
}) }
|
|
157
197
|
}));
|
|
158
|
-
|
|
159
|
-
//#region src/cookies.ts
|
|
198
|
+
// src/cookies.ts
|
|
160
199
|
var DatabaseCookieStore = class {
|
|
161
200
|
db;
|
|
162
201
|
[cookieStoreSign] = true;
|
|
@@ -335,8 +374,10 @@ var DatabaseCookieStore = class {
|
|
|
335
374
|
httpOnly: cookie.httpOnly,
|
|
336
375
|
sameSite: cookie.sameSite ?? "Lax"
|
|
337
376
|
});
|
|
338
|
-
else if (typeof init === "object")
|
|
339
|
-
|
|
377
|
+
else if (typeof init === "object") {
|
|
378
|
+
if (Symbol.iterator in init) for (const [name, value] of init) await this.set(name, value);
|
|
379
|
+
else for (const [name, value] of Object.entries(init)) await this.set(name, value);
|
|
380
|
+
}
|
|
340
381
|
}
|
|
341
382
|
[Symbol.asyncIterator]() {
|
|
342
383
|
const allCookies = this.db.query.cookies.findMany();
|
|
@@ -364,16 +405,79 @@ var DatabaseCookieStore = class {
|
|
|
364
405
|
} };
|
|
365
406
|
}
|
|
366
407
|
};
|
|
367
|
-
|
|
368
|
-
|
|
408
|
+
// src/utils.ts
|
|
409
|
+
const zstdCompress = (data) => {
|
|
410
|
+
return new Promise((resolve, reject) => {
|
|
411
|
+
zstdCompress$1(data, (err, compressedData) => {
|
|
412
|
+
if (err) reject(err);
|
|
413
|
+
else resolve(compressedData);
|
|
414
|
+
});
|
|
415
|
+
});
|
|
416
|
+
};
|
|
417
|
+
const zstdDecompress = (data) => {
|
|
418
|
+
return new Promise((resolve, reject) => {
|
|
419
|
+
zstdDecompress$1(data, (err, decompressedData) => {
|
|
420
|
+
if (err) reject(err);
|
|
421
|
+
else resolve(decompressedData);
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
};
|
|
425
|
+
function getCoverHash(data) {
|
|
426
|
+
return createHash("md5").update(data).digest("hex");
|
|
427
|
+
}
|
|
428
|
+
function getContentHash(content) {
|
|
429
|
+
return createHash("md5").update(content).digest("hex");
|
|
430
|
+
}
|
|
431
|
+
function getUrlHash(url) {
|
|
432
|
+
return createHash("md5").update(url).digest("hex");
|
|
433
|
+
}
|
|
434
|
+
function getExtFromContentType(contentType) {
|
|
435
|
+
if (contentType.includes("jpeg") || contentType.includes("jpg")) return "jpg";
|
|
436
|
+
if (contentType.includes("png")) return "png";
|
|
437
|
+
if (contentType.includes("gif")) return "gif";
|
|
438
|
+
if (contentType.includes("webp")) return "webp";
|
|
439
|
+
if (contentType.includes("avif")) return "avif";
|
|
440
|
+
return "bin";
|
|
441
|
+
}
|
|
442
|
+
// src/db.ts
|
|
369
443
|
function getDrizzle(client) {
|
|
370
444
|
return drizzle({
|
|
371
445
|
client,
|
|
372
446
|
relations
|
|
373
447
|
});
|
|
374
448
|
}
|
|
449
|
+
const CLOCK_SKEW_TOLERANCE_MS = 6e4;
|
|
450
|
+
function toBookshelfItem(row) {
|
|
451
|
+
return {
|
|
452
|
+
platform: row.platform,
|
|
453
|
+
novelId: row.novelId,
|
|
454
|
+
title: row.title,
|
|
455
|
+
author: row.author,
|
|
456
|
+
coverUrl: row.coverUrl,
|
|
457
|
+
addedAt: row.addedAt,
|
|
458
|
+
updatedAt: row.updatedAt,
|
|
459
|
+
deletedAt: row.deletedAt
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function toReadingProgress(row) {
|
|
463
|
+
return {
|
|
464
|
+
platform: row.platform,
|
|
465
|
+
novelId: row.novelId,
|
|
466
|
+
novelTitle: row.novelTitle,
|
|
467
|
+
coverUrl: row.coverUrl,
|
|
468
|
+
volumeId: row.volumeId,
|
|
469
|
+
volumeTitle: row.volumeTitle,
|
|
470
|
+
chapterId: row.chapterId,
|
|
471
|
+
chapterTitle: row.chapterTitle,
|
|
472
|
+
paragraphIndex: row.paragraphIndex,
|
|
473
|
+
totalParagraphs: row.totalParagraphs,
|
|
474
|
+
deviceLabel: row.deviceLabel,
|
|
475
|
+
updatedAt: row.updatedAt
|
|
476
|
+
};
|
|
477
|
+
}
|
|
375
478
|
var DatabaseService = class {
|
|
376
479
|
client;
|
|
480
|
+
readyPromise;
|
|
377
481
|
db;
|
|
378
482
|
constructor(options) {
|
|
379
483
|
const parentDir = dirname(resolve(options.path));
|
|
@@ -383,15 +487,22 @@ var DatabaseService = class {
|
|
|
383
487
|
mkdirSync(parentDir, { recursive: true });
|
|
384
488
|
}
|
|
385
489
|
this.client = createClient({ url: `file:${options.path}` });
|
|
386
|
-
this.client.execute("PRAGMA journal_mode = WAL;");
|
|
387
490
|
this.db = getDrizzle(this.client);
|
|
388
|
-
|
|
491
|
+
this.readyPromise = this._init(options);
|
|
492
|
+
}
|
|
493
|
+
async _init(options) {
|
|
494
|
+
await this.client.execute("PRAGMA journal_mode = WAL;");
|
|
495
|
+
if (options.migrations?.enabled ?? true) await this._migrate(options.migrations?.directory);
|
|
389
496
|
}
|
|
390
|
-
_migrate(directory) {
|
|
497
|
+
async _migrate(directory) {
|
|
391
498
|
if (!this.db) throw new Error("Database not initialized");
|
|
392
|
-
migrate(this.db, { migrationsFolder: directory || "migrations" });
|
|
499
|
+
await migrate(this.db, { migrationsFolder: directory || "migrations" });
|
|
500
|
+
}
|
|
501
|
+
async ensureReady() {
|
|
502
|
+
await this.readyPromise;
|
|
393
503
|
}
|
|
394
504
|
async addSearchResult(keyword, platform, results) {
|
|
505
|
+
await this.ensureReady();
|
|
395
506
|
await this.db.transaction(async (tx) => {
|
|
396
507
|
await tx.insert(keywordSearches).values({
|
|
397
508
|
keyword,
|
|
@@ -431,7 +542,8 @@ var DatabaseService = class {
|
|
|
431
542
|
});
|
|
432
543
|
}
|
|
433
544
|
async searchNovels(keyword, platform) {
|
|
434
|
-
|
|
545
|
+
await this.ensureReady();
|
|
546
|
+
const minQueryTime = Date.now() - 1728e5;
|
|
435
547
|
const searchRecord = await this.db.query.keywordSearches.findFirst({
|
|
436
548
|
where: {
|
|
437
549
|
keyword,
|
|
@@ -456,6 +568,7 @@ var DatabaseService = class {
|
|
|
456
568
|
};
|
|
457
569
|
}
|
|
458
570
|
async addNovelCache(novel) {
|
|
571
|
+
await this.ensureReady();
|
|
459
572
|
await this.db.transaction(async (tx) => {
|
|
460
573
|
const { id: novelId } = await tx.insert(novels).values({
|
|
461
574
|
platform: novel.platform,
|
|
@@ -487,7 +600,10 @@ var DatabaseService = class {
|
|
|
487
600
|
genreId
|
|
488
601
|
}).onConflictDoNothing().run();
|
|
489
602
|
}
|
|
603
|
+
const volumePlatformIds = [];
|
|
604
|
+
const chapterPlatformIds = [];
|
|
490
605
|
for (const volume of novel.volumes) {
|
|
606
|
+
volumePlatformIds.push(volume.id);
|
|
491
607
|
const { id: volumeId } = await tx.insert(volumes).values({
|
|
492
608
|
novelId,
|
|
493
609
|
name: volume.title,
|
|
@@ -501,20 +617,31 @@ var DatabaseService = class {
|
|
|
501
617
|
coverUrl: volume.coverUrl ?? ""
|
|
502
618
|
}
|
|
503
619
|
}).returning({ id: volumes.id }).get();
|
|
504
|
-
for (const chapter of volume.chapters)
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
620
|
+
for (const chapter of volume.chapters) {
|
|
621
|
+
chapterPlatformIds.push(chapter.id);
|
|
622
|
+
await tx.insert(chapters).values({
|
|
623
|
+
novelId,
|
|
624
|
+
volumeId,
|
|
625
|
+
name: chapter.title,
|
|
626
|
+
platform: novel.platform,
|
|
627
|
+
platformId: chapter.id
|
|
628
|
+
}).onConflictDoUpdate({
|
|
629
|
+
target: [chapters.novelId, chapters.platformId],
|
|
630
|
+
set: {
|
|
631
|
+
volumeId,
|
|
632
|
+
name: chapter.title
|
|
633
|
+
}
|
|
634
|
+
}).run();
|
|
635
|
+
}
|
|
514
636
|
}
|
|
637
|
+
if (chapterPlatformIds.length > 0) await tx.delete(chapters).where(and(eq(chapters.novelId, novelId), notInArray(chapters.platformId, chapterPlatformIds))).run();
|
|
638
|
+
else await tx.delete(chapters).where(eq(chapters.novelId, novelId)).run();
|
|
639
|
+
if (volumePlatformIds.length > 0) await tx.delete(volumes).where(and(eq(volumes.novelId, novelId), notInArray(volumes.platformId, volumePlatformIds))).run();
|
|
640
|
+
else await tx.delete(volumes).where(eq(volumes.novelId, novelId)).run();
|
|
515
641
|
});
|
|
516
642
|
}
|
|
517
643
|
async getNovelCache(platform, platformId) {
|
|
644
|
+
await this.ensureReady();
|
|
518
645
|
const novelRecord = await this.db.query.novels.findFirst({
|
|
519
646
|
where: {
|
|
520
647
|
platform,
|
|
@@ -559,6 +686,7 @@ var DatabaseService = class {
|
|
|
559
686
|
};
|
|
560
687
|
}
|
|
561
688
|
async getVolumeMeta(platform, platformId) {
|
|
689
|
+
await this.ensureReady();
|
|
562
690
|
const volumeRecord = await this.db.query.volumes.findFirst({
|
|
563
691
|
where: {
|
|
564
692
|
platform,
|
|
@@ -581,6 +709,7 @@ var DatabaseService = class {
|
|
|
581
709
|
};
|
|
582
710
|
}
|
|
583
711
|
async getChapterFromTitle(title) {
|
|
712
|
+
await this.ensureReady();
|
|
584
713
|
const chapterRecord = await this.db.query.chapters.findFirst({ where: { name: title } }).execute();
|
|
585
714
|
if (!chapterRecord) return;
|
|
586
715
|
return {
|
|
@@ -589,6 +718,7 @@ var DatabaseService = class {
|
|
|
589
718
|
};
|
|
590
719
|
}
|
|
591
720
|
async getChapterFromId(platform, platformId) {
|
|
721
|
+
await this.ensureReady();
|
|
592
722
|
const chapterRecord = await this.db.query.chapters.findFirst({
|
|
593
723
|
where: {
|
|
594
724
|
platformId,
|
|
@@ -610,9 +740,11 @@ var DatabaseService = class {
|
|
|
610
740
|
};
|
|
611
741
|
}
|
|
612
742
|
async addNovelContentHash(platform, chapterId, contentHash) {
|
|
743
|
+
await this.ensureReady();
|
|
613
744
|
await this.db.update(chapters).set({ contentHash }).where(and(eq(chapters.platformId, chapterId), eq(chapters.platform, platform))).run();
|
|
614
745
|
}
|
|
615
746
|
async getNovelCoverMetadata(platform, novelId) {
|
|
747
|
+
await this.ensureReady();
|
|
616
748
|
const queryResult = await this.db.query.novelCoverMetadata.findFirst({
|
|
617
749
|
where: { novel: {
|
|
618
750
|
platform,
|
|
@@ -630,6 +762,7 @@ var DatabaseService = class {
|
|
|
630
762
|
};
|
|
631
763
|
}
|
|
632
764
|
async addNovelCoverMetadata(metadata) {
|
|
765
|
+
await this.ensureReady();
|
|
633
766
|
const novel = metadata.novelId && metadata.platform ? await this.db.query.novels.findFirst({ where: {
|
|
634
767
|
platform: metadata.platform,
|
|
635
768
|
platformId: metadata.novelId
|
|
@@ -653,6 +786,7 @@ var DatabaseService = class {
|
|
|
653
786
|
}).onConflictDoNothing().run();
|
|
654
787
|
}
|
|
655
788
|
async getVolumeCoverMetadata(platform, volumeId) {
|
|
789
|
+
await this.ensureReady();
|
|
656
790
|
const queryResult = await this.db.query.volumeCoverMetadata.findFirst({
|
|
657
791
|
where: { volume: {
|
|
658
792
|
platform,
|
|
@@ -670,6 +804,7 @@ var DatabaseService = class {
|
|
|
670
804
|
};
|
|
671
805
|
}
|
|
672
806
|
async addVolumeCoverMetadata(metadata) {
|
|
807
|
+
await this.ensureReady();
|
|
673
808
|
const volume = metadata.volumeId && metadata.platform ? await this.db.query.volumes.findFirst({ where: {
|
|
674
809
|
platform: metadata.platform,
|
|
675
810
|
platformId: metadata.volumeId
|
|
@@ -682,12 +817,14 @@ var DatabaseService = class {
|
|
|
682
817
|
}).onConflictDoNothing().run();
|
|
683
818
|
}
|
|
684
819
|
async getCache(key, schema) {
|
|
820
|
+
await this.ensureReady();
|
|
685
821
|
const record = await this.db.query.generalCache.findFirst({ where: { key } }).execute();
|
|
686
822
|
if (!record) return null;
|
|
687
823
|
const parsed = schema.safeParse(record.value);
|
|
688
824
|
return parsed.success ? parsed.data : null;
|
|
689
825
|
}
|
|
690
826
|
async setCache(key, value) {
|
|
827
|
+
await this.ensureReady();
|
|
691
828
|
await this.db.insert(generalCache).values({
|
|
692
829
|
key,
|
|
693
830
|
value
|
|
@@ -696,8 +833,241 @@ var DatabaseService = class {
|
|
|
696
833
|
set: { value }
|
|
697
834
|
}).run();
|
|
698
835
|
}
|
|
836
|
+
async registerIllustrations(platform, items) {
|
|
837
|
+
await this.ensureReady();
|
|
838
|
+
const uniqueItems = /* @__PURE__ */ new Map();
|
|
839
|
+
for (const item of items) if (typeof item === "string") {
|
|
840
|
+
const trimmed = item.trim();
|
|
841
|
+
if (!trimmed) continue;
|
|
842
|
+
const urlHash = getUrlHash(trimmed);
|
|
843
|
+
if (!uniqueItems.has(urlHash)) uniqueItems.set(urlHash, {
|
|
844
|
+
urlHash,
|
|
845
|
+
originalUrl: trimmed
|
|
846
|
+
});
|
|
847
|
+
} else {
|
|
848
|
+
const urlHash = item.urlHash.trim();
|
|
849
|
+
const originalUrl = item.originalUrl.trim();
|
|
850
|
+
if (!urlHash || !originalUrl) continue;
|
|
851
|
+
if (!uniqueItems.has(urlHash)) uniqueItems.set(urlHash, {
|
|
852
|
+
urlHash,
|
|
853
|
+
originalUrl
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
if (uniqueItems.size === 0) return;
|
|
857
|
+
const createdAt = Date.now();
|
|
858
|
+
const rows = Array.from(uniqueItems.values()).map((entry) => ({
|
|
859
|
+
platform,
|
|
860
|
+
urlHash: entry.urlHash,
|
|
861
|
+
originalUrl: entry.originalUrl,
|
|
862
|
+
createdAt
|
|
863
|
+
}));
|
|
864
|
+
const chunkSize = 200;
|
|
865
|
+
await this.db.transaction(async (tx) => {
|
|
866
|
+
for (let i = 0; i < rows.length; i += chunkSize) {
|
|
867
|
+
const chunk = rows.slice(i, i + chunkSize);
|
|
868
|
+
await tx.insert(illustrationMetadata).values(chunk).onConflictDoNothing({ target: [illustrationMetadata.platform, illustrationMetadata.urlHash] }).run();
|
|
869
|
+
}
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
async getIllustrationSourceUrl(platform, urlHash) {
|
|
873
|
+
await this.ensureReady();
|
|
874
|
+
return (await this.db.select({ originalUrl: illustrationMetadata.originalUrl }).from(illustrationMetadata).where(and(eq(illustrationMetadata.platform, platform), eq(illustrationMetadata.urlHash, urlHash))).get())?.originalUrl;
|
|
875
|
+
}
|
|
876
|
+
async getIllustrationMetadata(platform, urlHash) {
|
|
877
|
+
await this.ensureReady();
|
|
878
|
+
return await this.db.select({
|
|
879
|
+
originalUrl: illustrationMetadata.originalUrl,
|
|
880
|
+
fileHash: illustrationMetadata.fileHash,
|
|
881
|
+
contentType: illustrationMetadata.contentType
|
|
882
|
+
}).from(illustrationMetadata).where(and(eq(illustrationMetadata.platform, platform), eq(illustrationMetadata.urlHash, urlHash))).get();
|
|
883
|
+
}
|
|
884
|
+
async updateIllustrationFileInfo(platform, urlHash, fileHash, contentType) {
|
|
885
|
+
await this.ensureReady();
|
|
886
|
+
await this.db.update(illustrationMetadata).set({
|
|
887
|
+
fileHash,
|
|
888
|
+
contentType
|
|
889
|
+
}).where(and(eq(illustrationMetadata.platform, platform), eq(illustrationMetadata.urlHash, urlHash))).run();
|
|
890
|
+
}
|
|
891
|
+
async listCachedNovels(platform, options) {
|
|
892
|
+
await this.ensureReady();
|
|
893
|
+
const page = Math.max(1, Math.trunc(options.page));
|
|
894
|
+
const pageSize = Math.max(1, Math.trunc(options.pageSize));
|
|
895
|
+
const offset = (page - 1) * pageSize;
|
|
896
|
+
const whereClause = and(eq(novels.platform, platform), ne(novels.status, "unknown"), ne(novels.author, ""), ne(novels.name, ""));
|
|
897
|
+
const total = (await this.db.select({ value: count() }).from(novels).where(whereClause).get())?.value ?? 0;
|
|
898
|
+
if (total === 0) return {
|
|
899
|
+
items: [],
|
|
900
|
+
total: 0,
|
|
901
|
+
page,
|
|
902
|
+
pageSize
|
|
903
|
+
};
|
|
904
|
+
const novelRows = await this.db.select({
|
|
905
|
+
id: novels.id,
|
|
906
|
+
platform: novels.platform,
|
|
907
|
+
platformId: novels.platformId,
|
|
908
|
+
name: novels.name,
|
|
909
|
+
coverUrl: novels.coverUrl,
|
|
910
|
+
author: novels.author,
|
|
911
|
+
summary: novels.summary,
|
|
912
|
+
status: novels.status
|
|
913
|
+
}).from(novels).where(whereClause).orderBy(desc(novels.updateAt), desc(novels.id)).limit(pageSize).offset(offset).all();
|
|
914
|
+
if (novelRows.length === 0) return {
|
|
915
|
+
items: [],
|
|
916
|
+
total,
|
|
917
|
+
page,
|
|
918
|
+
pageSize
|
|
919
|
+
};
|
|
920
|
+
const novelIds = novelRows.map((row) => row.id);
|
|
921
|
+
const genreRows = await this.db.select({
|
|
922
|
+
novelId: novelGenres.novelId,
|
|
923
|
+
genreName: genres.name
|
|
924
|
+
}).from(novelGenres).innerJoin(genres, eq(novelGenres.genreId, genres.id)).where(inArray(novelGenres.novelId, novelIds)).all();
|
|
925
|
+
const genresByNovelId = /* @__PURE__ */ new Map();
|
|
926
|
+
for (const row of genreRows) {
|
|
927
|
+
const existing = genresByNovelId.get(row.novelId);
|
|
928
|
+
if (existing) existing.push(row.genreName);
|
|
929
|
+
else genresByNovelId.set(row.novelId, [row.genreName]);
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
items: novelRows.map((row) => ({
|
|
933
|
+
id: row.platformId,
|
|
934
|
+
platform: row.platform,
|
|
935
|
+
title: row.name,
|
|
936
|
+
coverUrl: row.coverUrl,
|
|
937
|
+
author: row.author,
|
|
938
|
+
summary: row.summary,
|
|
939
|
+
status: row.status,
|
|
940
|
+
genres: genresByNovelId.get(row.id) ?? []
|
|
941
|
+
})),
|
|
942
|
+
total,
|
|
943
|
+
page,
|
|
944
|
+
pageSize
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
async getMaxSyncCursor(executor) {
|
|
948
|
+
const bookshelfMaxRow = await executor.select({ value: max(bookshelfItems.serverUpdatedAt) }).from(bookshelfItems).get();
|
|
949
|
+
const progressMaxRow = await executor.select({ value: max(readingProgress.serverUpdatedAt) }).from(readingProgress).get();
|
|
950
|
+
const bookshelfMax = Number(bookshelfMaxRow?.value ?? 0);
|
|
951
|
+
const progressMax = Number(progressMaxRow?.value ?? 0);
|
|
952
|
+
return Math.max(bookshelfMax, progressMax);
|
|
953
|
+
}
|
|
954
|
+
async getSyncState(since) {
|
|
955
|
+
await this.ensureReady();
|
|
956
|
+
return await this.db.transaction(async (tx) => {
|
|
957
|
+
const maxCursor = await this.getMaxSyncCursor(tx);
|
|
958
|
+
if (since === void 0 || since <= 0) {
|
|
959
|
+
const bookshelfRows = await tx.select().from(bookshelfItems).where(isNull(bookshelfItems.deletedAt)).all();
|
|
960
|
+
const progressRows = await tx.select().from(readingProgress).all();
|
|
961
|
+
return {
|
|
962
|
+
bookshelf: bookshelfRows.map(toBookshelfItem),
|
|
963
|
+
progress: progressRows.map(toReadingProgress),
|
|
964
|
+
cursor: maxCursor
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
const bookshelfRows = await tx.select().from(bookshelfItems).where(gt(bookshelfItems.serverUpdatedAt, since)).all();
|
|
968
|
+
const progressRows = await tx.select().from(readingProgress).where(gt(readingProgress.serverUpdatedAt, since)).all();
|
|
969
|
+
return {
|
|
970
|
+
bookshelf: bookshelfRows.map(toBookshelfItem),
|
|
971
|
+
progress: progressRows.map(toReadingProgress),
|
|
972
|
+
cursor: Math.max(since, maxCursor)
|
|
973
|
+
};
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
async mergeSyncState(input) {
|
|
977
|
+
await this.ensureReady();
|
|
978
|
+
return await this.db.transaction(async (tx) => {
|
|
979
|
+
let lastCursor = await this.getMaxSyncCursor(tx);
|
|
980
|
+
const nextCursor = () => {
|
|
981
|
+
lastCursor = Math.max(Date.now(), lastCursor + 1);
|
|
982
|
+
return lastCursor;
|
|
983
|
+
};
|
|
984
|
+
const bookshelfMap = /* @__PURE__ */ new Map();
|
|
985
|
+
const progressMap = /* @__PURE__ */ new Map();
|
|
986
|
+
for (const item of input.bookshelf ?? []) {
|
|
987
|
+
const key = `${item.platform}\0${item.novelId}`;
|
|
988
|
+
const effectiveUpdatedAt = Math.min(item.updatedAt, Date.now() + CLOCK_SKEW_TOLERANCE_MS);
|
|
989
|
+
const existing = await tx.select().from(bookshelfItems).where(and(eq(bookshelfItems.platform, item.platform), eq(bookshelfItems.novelId, item.novelId))).get();
|
|
990
|
+
if (!existing) {
|
|
991
|
+
const serverUpdatedAt = nextCursor();
|
|
992
|
+
const inserted = await tx.insert(bookshelfItems).values({
|
|
993
|
+
platform: item.platform,
|
|
994
|
+
novelId: item.novelId,
|
|
995
|
+
title: item.title,
|
|
996
|
+
author: item.author,
|
|
997
|
+
coverUrl: item.coverUrl,
|
|
998
|
+
addedAt: item.addedAt,
|
|
999
|
+
updatedAt: effectiveUpdatedAt,
|
|
1000
|
+
serverUpdatedAt,
|
|
1001
|
+
deletedAt: item.deletedAt
|
|
1002
|
+
}).returning().get();
|
|
1003
|
+
bookshelfMap.set(key, toBookshelfItem(inserted));
|
|
1004
|
+
} else if (effectiveUpdatedAt >= existing.updatedAt) {
|
|
1005
|
+
const serverUpdatedAt = nextCursor();
|
|
1006
|
+
const updated = await tx.update(bookshelfItems).set({
|
|
1007
|
+
title: item.title,
|
|
1008
|
+
author: item.author,
|
|
1009
|
+
coverUrl: item.coverUrl,
|
|
1010
|
+
addedAt: item.addedAt,
|
|
1011
|
+
updatedAt: effectiveUpdatedAt,
|
|
1012
|
+
serverUpdatedAt,
|
|
1013
|
+
deletedAt: item.deletedAt
|
|
1014
|
+
}).where(eq(bookshelfItems.id, existing.id)).returning().get();
|
|
1015
|
+
if (!updated) throw new Error(`Failed to update bookshelf item: ${item.platform}/${item.novelId}`);
|
|
1016
|
+
bookshelfMap.set(key, toBookshelfItem(updated));
|
|
1017
|
+
} else bookshelfMap.set(key, toBookshelfItem(existing));
|
|
1018
|
+
}
|
|
1019
|
+
for (const item of input.progress ?? []) {
|
|
1020
|
+
const key = `${item.platform}\0${item.novelId}`;
|
|
1021
|
+
const effectiveUpdatedAt = Math.min(item.updatedAt, Date.now() + CLOCK_SKEW_TOLERANCE_MS);
|
|
1022
|
+
const existing = await tx.select().from(readingProgress).where(and(eq(readingProgress.platform, item.platform), eq(readingProgress.novelId, item.novelId))).get();
|
|
1023
|
+
if (!existing) {
|
|
1024
|
+
const serverUpdatedAt = nextCursor();
|
|
1025
|
+
const inserted = await tx.insert(readingProgress).values({
|
|
1026
|
+
platform: item.platform,
|
|
1027
|
+
novelId: item.novelId,
|
|
1028
|
+
novelTitle: item.novelTitle,
|
|
1029
|
+
coverUrl: item.coverUrl,
|
|
1030
|
+
volumeId: item.volumeId,
|
|
1031
|
+
volumeTitle: item.volumeTitle,
|
|
1032
|
+
chapterId: item.chapterId,
|
|
1033
|
+
chapterTitle: item.chapterTitle,
|
|
1034
|
+
paragraphIndex: item.paragraphIndex,
|
|
1035
|
+
totalParagraphs: item.totalParagraphs,
|
|
1036
|
+
deviceLabel: item.deviceLabel,
|
|
1037
|
+
updatedAt: effectiveUpdatedAt,
|
|
1038
|
+
serverUpdatedAt
|
|
1039
|
+
}).returning().get();
|
|
1040
|
+
progressMap.set(key, toReadingProgress(inserted));
|
|
1041
|
+
} else if (effectiveUpdatedAt >= existing.updatedAt) {
|
|
1042
|
+
const serverUpdatedAt = nextCursor();
|
|
1043
|
+
const updated = await tx.update(readingProgress).set({
|
|
1044
|
+
novelTitle: item.novelTitle,
|
|
1045
|
+
coverUrl: item.coverUrl,
|
|
1046
|
+
volumeId: item.volumeId,
|
|
1047
|
+
volumeTitle: item.volumeTitle,
|
|
1048
|
+
chapterId: item.chapterId,
|
|
1049
|
+
chapterTitle: item.chapterTitle,
|
|
1050
|
+
paragraphIndex: item.paragraphIndex,
|
|
1051
|
+
totalParagraphs: item.totalParagraphs,
|
|
1052
|
+
deviceLabel: item.deviceLabel,
|
|
1053
|
+
updatedAt: effectiveUpdatedAt,
|
|
1054
|
+
serverUpdatedAt
|
|
1055
|
+
}).where(eq(readingProgress.id, existing.id)).returning().get();
|
|
1056
|
+
if (!updated) throw new Error(`Failed to update reading progress: ${item.platform}/${item.novelId}`);
|
|
1057
|
+
progressMap.set(key, toReadingProgress(updated));
|
|
1058
|
+
} else progressMap.set(key, toReadingProgress(existing));
|
|
1059
|
+
}
|
|
1060
|
+
const serverTime = Math.max(Date.now(), lastCursor);
|
|
1061
|
+
return {
|
|
1062
|
+
bookshelf: Array.from(bookshelfMap.values()),
|
|
1063
|
+
progress: Array.from(progressMap.values()),
|
|
1064
|
+
serverTime
|
|
1065
|
+
};
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
699
1068
|
async close(logger) {
|
|
700
1069
|
try {
|
|
1070
|
+
await this.ensureReady().catch(() => {});
|
|
701
1071
|
await this.client.execute("PRAGMA journal_mode = DELETE;");
|
|
702
1072
|
logger?.("WAL写入盘完成,正在关闭数据库连接...");
|
|
703
1073
|
} catch (error) {
|
|
@@ -708,40 +1078,7 @@ var DatabaseService = class {
|
|
|
708
1078
|
}
|
|
709
1079
|
}
|
|
710
1080
|
};
|
|
711
|
-
|
|
712
|
-
//#region src/utils.ts
|
|
713
|
-
const zstdCompress$1 = (data) => {
|
|
714
|
-
return new Promise((resolve, reject) => {
|
|
715
|
-
zstdCompress(data, (err, compressedData) => {
|
|
716
|
-
if (err) reject(err);
|
|
717
|
-
else resolve(compressedData);
|
|
718
|
-
});
|
|
719
|
-
});
|
|
720
|
-
};
|
|
721
|
-
const zstdDecompress$1 = (data) => {
|
|
722
|
-
return new Promise((resolve, reject) => {
|
|
723
|
-
zstdDecompress(data, (err, decompressedData) => {
|
|
724
|
-
if (err) reject(err);
|
|
725
|
-
else resolve(decompressedData);
|
|
726
|
-
});
|
|
727
|
-
});
|
|
728
|
-
};
|
|
729
|
-
function getCoverHash(data) {
|
|
730
|
-
return createHash("md5").update(data).digest("hex");
|
|
731
|
-
}
|
|
732
|
-
function getContentHash(content) {
|
|
733
|
-
return createHash("md5").update(content).digest("hex");
|
|
734
|
-
}
|
|
735
|
-
function getExtFromContentType(contentType) {
|
|
736
|
-
if (contentType.includes("jpeg") || contentType.includes("jpg")) return "jpg";
|
|
737
|
-
if (contentType.includes("png")) return "png";
|
|
738
|
-
if (contentType.includes("gif")) return "gif";
|
|
739
|
-
if (contentType.includes("webp")) return "webp";
|
|
740
|
-
if (contentType.includes("avif")) return "avif";
|
|
741
|
-
return "bin";
|
|
742
|
-
}
|
|
743
|
-
//#endregion
|
|
744
|
-
//#region src/files.ts
|
|
1081
|
+
// src/files.ts
|
|
745
1082
|
var FSStorageService = class {
|
|
746
1083
|
basePath;
|
|
747
1084
|
dbService;
|
|
@@ -759,14 +1096,17 @@ var FSStorageService = class {
|
|
|
759
1096
|
async getNovelContent(hash) {
|
|
760
1097
|
const chapterFilePath = `${`${this.basePath}/novels/${hash.slice(0, 2)}`}/${hash}.zst`;
|
|
761
1098
|
if (!existsSync(chapterFilePath)) return;
|
|
762
|
-
const
|
|
1099
|
+
const compressedData = await readFile(chapterFilePath);
|
|
1100
|
+
const decompressedData = await zstdDecompress(compressedData);
|
|
763
1101
|
return new TextDecoder().decode(decompressedData);
|
|
764
1102
|
}
|
|
765
1103
|
async setNovelContent(content) {
|
|
766
1104
|
const hash = getContentHash(content);
|
|
767
1105
|
const novelCacheDir = `${this.basePath}/novels/${hash.slice(0, 2)}`;
|
|
768
1106
|
await this._initPath(novelCacheDir);
|
|
769
|
-
|
|
1107
|
+
const chapterFilePath = `${novelCacheDir}/${hash}.zst`;
|
|
1108
|
+
const compressedData = await zstdCompress(Buffer.from(content, "utf-8"));
|
|
1109
|
+
await writeFile(chapterFilePath, compressedData);
|
|
770
1110
|
return hash;
|
|
771
1111
|
}
|
|
772
1112
|
async getCoverData(type, platform, platformId) {
|
|
@@ -786,7 +1126,8 @@ var FSStorageService = class {
|
|
|
786
1126
|
const ext = getExtFromContentType(contentType);
|
|
787
1127
|
const coverDir = `${this.basePath}/covers/${coverHash.slice(0, 2)}`;
|
|
788
1128
|
await this._initPath(coverDir);
|
|
789
|
-
|
|
1129
|
+
const coverPath = `${coverDir}/${coverHash}.${ext}`;
|
|
1130
|
+
await writeFile(coverPath, data);
|
|
790
1131
|
if (type === "novel") await this.dbService.addNovelCoverMetadata({
|
|
791
1132
|
platform,
|
|
792
1133
|
novelId: platformId,
|
|
@@ -802,9 +1143,28 @@ var FSStorageService = class {
|
|
|
802
1143
|
originalUrl: url
|
|
803
1144
|
});
|
|
804
1145
|
}
|
|
1146
|
+
async getIllustrationData(platform, urlHash) {
|
|
1147
|
+
const meta = await this.dbService.getIllustrationMetadata(platform, urlHash);
|
|
1148
|
+
if (!meta?.fileHash || !meta?.contentType) return;
|
|
1149
|
+
const ext = getExtFromContentType(meta.contentType);
|
|
1150
|
+
const illustrationPath = `${this.basePath}/illustrations/${meta.fileHash.slice(0, 2)}/${meta.fileHash}.${ext}`;
|
|
1151
|
+
if (!existsSync(illustrationPath)) return;
|
|
1152
|
+
return {
|
|
1153
|
+
data: await readFile(illustrationPath),
|
|
1154
|
+
mimeType: meta.contentType
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
async setIllustrationData(platform, urlHash, data, contentType) {
|
|
1158
|
+
const fileHash = getCoverHash(data);
|
|
1159
|
+
const ext = getExtFromContentType(contentType);
|
|
1160
|
+
const illustrationDir = `${this.basePath}/illustrations/${fileHash.slice(0, 2)}`;
|
|
1161
|
+
await this._initPath(illustrationDir);
|
|
1162
|
+
const illustrationPath = `${illustrationDir}/${fileHash}.${ext}`;
|
|
1163
|
+
await writeFile(illustrationPath, data);
|
|
1164
|
+
await this.dbService.updateIllustrationFileInfo(platform, urlHash, fileHash, contentType);
|
|
1165
|
+
}
|
|
805
1166
|
};
|
|
806
|
-
|
|
807
|
-
//#region src/service.ts
|
|
1167
|
+
// src/service.ts
|
|
808
1168
|
var StorageService = class {
|
|
809
1169
|
db;
|
|
810
1170
|
files;
|
|
@@ -861,11 +1221,31 @@ var StorageService = class {
|
|
|
861
1221
|
async setCache(key, value) {
|
|
862
1222
|
await this.db.setCache(key, value);
|
|
863
1223
|
}
|
|
1224
|
+
async registerIllustrations(platform, urls) {
|
|
1225
|
+
await this.db.registerIllustrations(platform, urls);
|
|
1226
|
+
}
|
|
1227
|
+
async getIllustrationSourceUrl(platform, urlHash) {
|
|
1228
|
+
return await this.db.getIllustrationSourceUrl(platform, urlHash);
|
|
1229
|
+
}
|
|
1230
|
+
async getIllustrationData(platform, urlHash) {
|
|
1231
|
+
return await this.files.getIllustrationData(platform, urlHash);
|
|
1232
|
+
}
|
|
1233
|
+
async setIllustrationData(platform, urlHash, data, contentType) {
|
|
1234
|
+
await this.files.setIllustrationData(platform, urlHash, data, contentType);
|
|
1235
|
+
}
|
|
1236
|
+
async listCachedNovels(platform, options) {
|
|
1237
|
+
return await this.db.listCachedNovels(platform, options);
|
|
1238
|
+
}
|
|
1239
|
+
async getSyncState(since) {
|
|
1240
|
+
return await this.db.getSyncState(since);
|
|
1241
|
+
}
|
|
1242
|
+
async mergeSyncState(input) {
|
|
1243
|
+
return await this.db.mergeSyncState(input);
|
|
1244
|
+
}
|
|
864
1245
|
async close(logger) {
|
|
865
1246
|
await this.db.close(logger);
|
|
866
1247
|
}
|
|
867
1248
|
};
|
|
868
|
-
|
|
869
|
-
export { DatabaseCookieStore, DatabaseService, FSStorageService, StorageService };
|
|
1249
|
+
export { DatabaseCookieStore, DatabaseService, FSStorageService, StorageService, getUrlHash };
|
|
870
1250
|
|
|
871
1251
|
//# sourceMappingURL=index.mjs.map
|