-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.ts
1668 lines (1665 loc) · 51.9 KB
/
db.ts
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Db, QueryParameter } from "./utils/db_interface.ts";
import {
compare as compare_ver,
format as format_ver,
parse as parse_ver,
} from "@std/semver";
import { unescape } from "@std/html";
import { join, resolve } from "@std/path";
import { SqliteError } from "sqlite/mod.ts";
import { SqliteError as Sqlite3Error } from "sqlite3";
import { Status } from "sqlite/src/constants.ts";
import {
parse_bool,
sleep,
sure_dir_sync,
toJSON,
try_remove_sync,
} from "./utils.ts";
import { Task, TaskType } from "./task.ts";
import { generate as randomstring } from "randomstring";
import type { GalleryMetadataSingle } from "./page/GalleryMetadata.ts";
type SqliteMaster = {
type: string;
name: string;
tbl_name: string;
rootpage: number;
sql: string;
};
export enum SqliteTransactionType {
DEFERRED = "DEFERRED",
IMMEDIATE = "IMMEDIATE",
EXCLUSIVE = "EXCLUSIVE",
}
export type GMeta = {
gid: number | bigint;
token: string;
title: string;
title_jpn: string;
category: string;
uploader: string;
posted: number | bigint;
filecount: number | bigint;
filesize: number | bigint;
expunged: boolean;
rating: number | bigint;
parent_gid: number | bigint | null;
parent_key: string | null;
first_gid: number | bigint | null;
first_key: string | null;
};
export type GMetaRaw = {
gid: number | bigint;
token: string;
title: string;
title_jpn: string;
category: string;
uploader: string;
posted: number | bigint;
filecount: number | bigint;
filesize: number | bigint;
expunged: number | bigint;
rating: number | bigint;
parent_gid: number | bigint | null;
parent_key: string | null;
first_gid: number | bigint | null;
first_key: string | null;
};
export type PMeta = {
gid: number | bigint;
index: number | bigint;
token: string;
name: string;
width: number | bigint;
height: number | bigint;
};
export type ExtendedPMeta = {
gid: number | bigint;
index: number | bigint;
token: string;
name: string;
width: number | bigint;
height: number | bigint;
is_nsfw: boolean;
is_ad: boolean;
};
export type ExtendedPMetaRaw = {
gid: number | bigint;
index: number | bigint;
token: string;
name: string;
width: number | bigint;
height: number | bigint;
is_nsfw: number | bigint | null;
is_ad: number | bigint | null;
};
export type Tag = {
id: number | bigint;
tag: string;
translated: string | undefined;
intro: string | undefined;
};
export type EhFile = {
id: number | bigint;
token: string;
path: string;
width: number | bigint;
height: number | bigint;
is_original: boolean;
};
type EhFileRawV1 = {
id: number | bigint;
gid: number | bigint;
token: string;
path: string;
width: number | bigint;
height: number | bigint;
is_original: number | bigint;
};
export type EhFileRaw = {
id: number | bigint;
token: string;
path: string;
width: number | bigint;
height: number | bigint;
is_original: number | bigint;
};
export type EhFileMeta = {
token: string;
is_nsfw: boolean;
is_ad: boolean;
};
export type EhFileMetaRaw = {
token: string;
is_nsfw: number | bigint;
is_ad: number | bigint;
};
export enum UserPermission {
None = 0,
ReadGallery = 1 << 0,
EditGallery = 1 << 1,
DeleteGallery = 1 << 2,
ManageTasks = 1 << 3,
ShareGallery = 1 << 4,
All = ~(~0 << 5),
}
export type User = {
id: number | bigint;
username: string;
password: Uint8Array;
is_admin: boolean;
permissions: UserPermission;
};
type UserRaw = {
id: number | bigint;
username: string;
password: Uint8Array;
is_admin: number | bigint;
permissions: UserPermission;
};
export type Token = {
id: number | bigint;
uid: number | bigint;
token: string;
expired: Date;
http_only: boolean;
secure: boolean;
last_used: Date;
client: string | null;
device: string | null;
client_version: string | null;
client_platform: string | null;
};
type TokenRaw = {
id: number | bigint;
uid: number | bigint;
token: string;
expired: string;
http_only: number | bigint;
secure: number | bigint;
last_used: string;
client: string | null;
device: string | null;
client_version: string | null;
client_platform: string | null;
};
export type ClientConfig = {
uid: number | bigint;
client: string;
name: string;
data: string;
};
export enum SharedTokenType {
Gallery,
}
export type GallerySharedTokenInfo = {
gid: number | bigint;
};
type SharedTokenTypeMap = {
[SharedTokenType.Gallery]: GallerySharedTokenInfo;
};
export type SharedToken<T extends SharedTokenType = SharedTokenType> = {
id: number | bigint;
token: string;
expired: Date | null;
type: T;
info: SharedTokenTypeMap[T];
};
type SharedTokenRaw = {
id: number | bigint;
token: string;
expired: Date | null;
type: SharedTokenType;
info: string;
};
const ALL_TABLES = [
"version",
"task",
"gmeta",
"pmeta",
"tag",
"gtag",
"file",
"filemeta",
"user",
"token",
"ehmeta",
"client_config",
"shared_token",
];
const VERSION_TABLE = `CREATE TABLE version (
id TEXT,
ver TEXT,
PRIMARY KEY (id)
);`;
const TASK_TABLE = `CREATE TABLE task (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type INT,
gid INT,
token TEXT,
pid INT,
details TEXT
);`;
const GMETA_TABLE = `CREATE TABLE gmeta (
gid INT,
token TEXT,
title TEXT,
title_jpn TEXT,
category TEXT,
uploader TEXT,
posted INT,
filecount INT,
filesize INT,
expunged BOOLEAN,
rating REAL,
parent_gid INT,
parent_key TEXT,
first_gid INT,
first_key TEXT,
PRIMARY KEY (gid)
);`;
const PMETA_TABLE = `CREATE TABLE pmeta (
gid INT,
"index" INT,
token TEXT,
name TEXT,
width INT,
height INT,
PRIMARY KEY (gid, "index")
);`;
const PMETA_INDEX = `CREATE INDEX pmeta_token ON pmeta (token);`;
const TAG_TABLE = `CREATE TABLE tag (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT,
translated TEXT,
intro TEXT
);`;
const GTAG_TABLE = `CREATE TABLE gtag (
gid INT,
id INT,
PRIMARY KEY (gid, id)
);`;
const FILE_TABLE = `CREATE TABLE file (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token TEXT,
path TEXT,
width INT,
height INT,
is_original BOOLEAN
);`;
const FILE_INDEX = `CREATE INDEX file_token ON file (token);`;
const FILEMETA_TABLE = `CREATE TABLE filemeta (
token TEXT,
is_nsfw BOOLEAN,
is_ad BOOLEAN,
PRIMARY KEY (token)
);`;
const USER_TABLE = `CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
password BLOB,
is_admin BOOLEAN,
permissions INT
);`;
const TOKEN_TABLE = `CREATE TABLE token (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid INT,
token TEXT,
expired TEXT,
http_only BOOLEAN,
secure BOOLEAN,
last_used TEXT,
client TEXT,
device TEXT,
client_version TEXT,
client_platform TEXT
);`;
const EHMETA_TABLE = `CREATE TABLE ehmeta (
gid INT,
data TEXT,
cached_time TEXT,
PRIMARY KEY (gid)
);`;
const CLIENT_CONFIG_TABLE = `CREATE TABLE client_config (
uid INT,
client TEXT,
name TEXT,
data TEXT,
PRIMARY KEY (uid, client, name)
);`;
const SHARED_TOKEN_TABLE = `CREATE TABLE shared_token (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token TEXT,
expired TEXT,
type INT,
info TEXT
);`;
function escape_fields(fields: string, namespace: string) {
const fs = fields.split(",");
return fs.map((f) => {
return `${namespace}.${f.trim()}`;
}).join(",");
}
export class EhDb {
// @ts-ignore Ignore
db: Db;
#file: Deno.FsFile | undefined;
#dblock: Deno.FsFile | undefined;
#exist_table: Set<string> = new Set();
#lock_file: string | undefined;
#dblock_file: string | undefined;
#_tags: Map<string, number | bigint> | undefined;
#base_path: string;
#db_path: string;
#use_ffi = false;
readonly version = parse_ver("1.0.0-14");
constructor(base_path: string) {
this.#base_path = base_path;
this.#db_path = join(base_path, "data.db");
sure_dir_sync(base_path);
}
async init() {
this.#use_ffi = parse_bool(Deno.env.get("DB_USE_FFI") ?? "false");
if (this.#use_ffi) {
const DB = (await import("./utils/db_ffi.ts")).DbFfi;
this.db = new DB(this.#db_path, { int64: true });
} else {
const DB = (await import("./utils/db_wasm.ts")).DbWasm;
this.db = new DB(this.#db_path);
}
if (!this.#check_database()) this.#create_table();
if (!this.#use_ffi) {
this.#lock_file = join(this.#base_path, "db.lock");
this.#dblock_file = join(this.#base_path, "eh.locked");
this.#file = Deno.openSync(this.#lock_file, {
create: true,
write: true,
});
this.#dblock = Deno.openSync(this.#dblock_file, {
create: true,
write: true,
});
this.dblock();
}
this.remove_expired_token();
}
#add_tag(s: string) {
return this.transaction(() => {
this.db.query("INSERT INTO tag (tag) VALUES (?);", [s]);
const r = this.db.queryEntries<Tag>(
"SELECT * FROM tag WHERE tag = ?;",
[s],
);
this.#tags.set(s, r[0].id);
return r[0].id;
});
}
#check_database() {
this.#updateExistsTable();
const v = this.#read_version();
if (!v) return false;
if (compare_ver(v, this.version) === -1) {
let need_optimize = false;
if (compare_ver(v, parse_ver("1.0.0-1")) === -1) {
this.db.execute("ALTER TABLE tag ADD translated TEXT;");
this.db.execute("ALTER TABLE tag ADD intro TEXT;");
}
if (compare_ver(v, parse_ver("1.0.0-2")) === -1) {
this.convert_file(
this.db.queryEntries<EhFileRaw>("SELECT * FROM file;"),
).forEach((f) => {
f.path = resolve(f.path);
this.add_file(f, false);
});
}
if (compare_ver(v, parse_ver("1.0.0-3")) === -1) {
this.db.execute("ALTER TABLE task ADD details TEXT;");
}
if (compare_ver(v, parse_ver("1.0.0-4")) === -1) {
this.db.execute("ALTER TABLE pmeta RENAME TO pmeta_origin;");
this.db.execute(PMETA_TABLE);
this.db.execute(
'INSERT INTO pmeta (gid, "index", token, name, width, height) SELECT gid, "index", token, name, width, height FROM pmeta_origin;',
);
this.db.execute("DROP TABLE pmeta_origin;");
need_optimize = true;
}
if (compare_ver(v, parse_ver("1.0.0-5")) === -1) {
this.db.execute("ALTER TABLE task DROP pn;");
}
if (compare_ver(v, parse_ver("1.0.0-6")) === -1) {
let offset = 0;
let tasks = this.convert_gmeta(
this.db.queryEntries<GMetaRaw>(
"SELECT * FROM gmeta LIMIT 20 OFFSET 0;",
),
);
while (tasks.length) {
tasks.forEach((t) => {
t.title = unescape(t.title);
t.title_jpn = unescape(t.title_jpn);
t.uploader = unescape(t.uploader);
this.add_gmeta(t);
});
offset += tasks.length;
tasks = this.convert_gmeta(
this.db.queryEntries<GMetaRaw>(
"SELECT * FROM gmeta LIMIT 20 OFFSET ?;",
[offset],
),
);
}
}
if (compare_ver(v, parse_ver("1.0.0-7")) === -1) {
this.db.execute("ALTER TABLE file RENAME TO file_origin;");
this.db.execute(FILE_TABLE);
let offset = 0;
let files = this.db.queryEntries<EhFileRawV1>(
"SELECT * FROM file_origin LIMIT 20 OFFSET 0;",
);
const d: string[] = [];
while (files.length) {
files.forEach((f) => {
if (!d.includes(f.token)) {
d.push(f.token);
const g: Record<string, unknown> = f;
delete g["gid"];
this.add_file(g as EhFile, false);
} else {
try_remove_sync(f.path);
console.log("Deleted ", f.path);
}
});
offset += files.length;
files = this.db.queryEntries<EhFileRawV1>(
"SELECT * FROM file_origin LIMIT 20 OFFSET ?;",
[offset],
);
}
this.db.execute("DROP TABLE file_origin;");
need_optimize = true;
}
if (compare_ver(v, parse_ver("1.0.0-8")) === -1) {
this.db.execute("DROP TABLE token;");
this.db.execute(`CREATE TABLE token (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid INT,
token TEXT,
expired TEXT);`);
}
if (compare_ver(v, parse_ver("1.0.0-9")) === -1) {
this.db.execute("ALTER TABLE token ADD http_only BOOLEAN;");
this.db.execute("ALTER TABLE token ADD secure BOOLEAN;");
this.db.execute("UPDATE token SET http_only = 1, secure = 0;");
}
if (compare_ver(v, parse_ver("1.0.0-10")) === -1) {
this.db.execute(FILE_INDEX);
}
if (compare_ver(v, parse_ver("1.0.0-11")) === -1) {
this.db.execute("ALTER TABLE token ADD last_used TEXT;");
this.db.execute(
"UPDATE token SET last_used = '1970-01-01T00:00:00.000Z';",
);
}
if (compare_ver(v, parse_ver("1.0.0-12")) === -1) {
this.db.execute("ALTER TABLE token ADD client TEXT;");
this.db.execute("ALTER TABLE token ADD device TEXT;");
this.db.execute("ALTER TABLE token ADD client_version TEXT;");
this.db.execute("ALTER TABLE token ADD client_platform TEXT;");
}
if (compare_ver(v, parse_ver("1.0.0-14")) === -1) {
this.db.execute(PMETA_INDEX);
}
this.#write_version();
if (need_optimize) this.optimize();
}
if (
ALL_TABLES.length !== this.#exist_table.size ||
!ALL_TABLES.every((x) => this.#exist_table.has(x))
) return false;
return true;
}
#create_table() {
if (!this.#exist_table.has("version")) {
this.db.execute(VERSION_TABLE);
this.#write_version();
}
if (!this.#exist_table.has("task")) {
this.db.execute(TASK_TABLE);
}
if (!this.#exist_table.has("gmeta")) {
this.db.execute(GMETA_TABLE);
}
if (!this.#exist_table.has("pmeta")) {
this.db.execute(PMETA_TABLE);
}
if (!this.#exist_table.has("tag")) {
this.db.execute(TAG_TABLE);
}
if (!this.#exist_table.has("gtag")) {
this.db.execute(GTAG_TABLE);
}
if (!this.#exist_table.has("file")) {
this.db.execute(FILE_TABLE);
this.db.execute(FILE_INDEX);
}
if (!this.#exist_table.has("filemeta")) {
this.db.execute(FILEMETA_TABLE);
}
if (!this.#exist_table.has("user")) {
this.db.execute(USER_TABLE);
}
if (!this.#exist_table.has("token")) {
this.db.execute(TOKEN_TABLE);
}
if (!this.#exist_table.has("ehmeta")) {
this.db.execute(EHMETA_TABLE);
}
if (!this.#exist_table.has("client_config")) {
this.db.execute(CLIENT_CONFIG_TABLE);
}
if (!this.#exist_table.has("shared_token")) {
this.db.execute(SHARED_TOKEN_TABLE);
}
this.#updateExistsTable();
}
#read_version() {
if (!this.#exist_table.has("version")) return null;
const cur = this.db.query<[string]>(
"SELECT ver FROM version WHERE id = ?;",
["eh"],
);
for (const i of cur) {
return parse_ver(i[0]);
}
return null;
}
get #tags() {
if (this.#_tags === undefined) {
const tags = this.db.queryEntries<Tag>("SELECT * FROM tag;");
const re = new Map<string, number | bigint>();
tags.forEach((v) => re.set(v.tag, v.id));
this.#_tags = re;
return re;
} else return this.#_tags;
}
#updateExistsTable() {
const cur = this.db.queryEntries<SqliteMaster>(
"SELECT * FROM main.sqlite_master;",
);
this.#exist_table.clear();
for (const i of cur) {
if (i.type == "table") {
this.#exist_table.add(i.name);
}
}
}
#write_version() {
this.db.transaction(() => {
this.db.query("INSERT OR REPLACE INTO version VALUES (?, ?);", [
"eh",
format_ver(this.version),
]);
});
}
add_client_config(config: ClientConfig) {
this.db.queryEntries(
"INSERT OR REPLACE INTO client_config VALUES (:uid, :client, :name, :data);",
config,
);
}
add_ehmeta(data: GalleryMetadataSingle) {
this.db.query(
"INSERT OR REPLACE INTO ehmeta VALUES (?, ?, ?);",
[data.gid, toJSON(data), new Date()],
);
}
add_gmeta(gmeta: GMeta) {
this.db.queryEntries(
"INSERT OR REPLACE INTO gmeta VALUES (:gid, :token, :title, :title_jpn, :category, :uploader, :posted, :filecount, :filesize, :expunged, :rating, :parent_gid, :parent_key, :first_gid, :first_key);",
gmeta,
);
}
async add_gtag(gid: number | bigint, tags: Set<string>) {
const otags = this.get_gtags(gid);
const deleted: string[] = [];
const added: string[] = [];
for (const o of otags) {
if (!tags.has(o)) deleted.push(o);
}
for (const o of tags) {
if (!otags.has(o)) added.push(o);
}
for (const d of deleted) {
const id = this.#tags.get(d);
if (id === undefined) throw Error("id not found.");
this.db.query("DELETE FROM gtag WHERE gid = ? AND id = ?;", [
gid,
id,
]);
}
for (const a of added) {
let id = this.#tags.get(a);
if (id === undefined) id = await this.#add_tag(a);
this.db.query("INSERT INTO gtag VALUES (?, ?);", [gid, id]);
}
}
add_file(f: EhFile, overwrite = true): EhFile {
if (overwrite) {
const ofiles = this.get_files(f.token);
if (ofiles.length) {
const o = ofiles[0];
f.id = o.id;
ofiles.slice(1).forEach((o) => {
this.delete_file(o);
});
ofiles.forEach((o) => {
if (o.path !== f.path) {
try_remove_sync(o.path);
console.log("Deleted ", o.path);
}
});
}
}
if (f.id) {
this.db.query(
"INSERT OR REPLACE INTO file VALUES (:id, :token, :path, :width, :height, :is_original);",
f,
);
return structuredClone(f);
} else {
this.db.query(
"INSERT INTO file (token, path, width, height, is_original) VALUES (?, ?, ?, ?, ?);",
[f.token, f.path, f.width, f.height, f.is_original],
);
const s = this.get_files(f.token);
return s[s.length - 1];
}
}
add_filemeta(m: EhFileMeta) {
this.db.query(
"INSERT OR REPLACE INTO filemeta VALUES (:token, :is_nsfw, :is_ad);",
m,
);
}
add_pmeta(pmeta: PMeta) {
this.db.queryEntries(
"INSERT OR REPLACE INTO pmeta VALUES (:gid, :index, :token, :name, :width, :height)",
pmeta,
);
}
add_root_user(username: string, password: Uint8Array) {
this.db.query("INSERT OR REPLACE INTO user VALUES (?, ?, ?, ?, ?);", [
0,
username,
password,
true,
UserPermission.All,
]);
}
add_shared_token<T extends SharedTokenType = SharedTokenType>(
type: T,
info: SharedTokenTypeMap[T],
expired: Date | null = null,
) {
let token = randomstring();
while (this.get_token(token) || this.get_shared_token(token)) {
token = randomstring();
}
this.db.query(
"INSERT INTO shared_token (token, expired, type, info) VALUES (?, ?, ?, ?);",
[token, expired, type, toJSON(info)],
);
const t = this.get_shared_token(token);
if (!t) throw Error("Failed to add shared token");
return t;
}
add_task(task: Task) {
return this.transaction(() => {
this.db.query(
"INSERT INTO task (type, gid, token, pid, details) VALUES (?, ?, ?, ?, ?);",
[
task.type,
task.gid,
task.token,
task.pid,
task.details,
],
);
if (task.details === null) {
return this.db.queryEntries<Task>(
"SELECT * FROM task WHERE type = ? AND gid = ? AND token = ? AND pid = ?;",
[
task.type,
task.gid,
task.token,
task.pid,
],
)[0];
}
return this.db.queryEntries<Task>(
"SELECT * FROM task WHERE type = ? AND gid = ? AND token = ? AND pid = ? AND details = ?;",
[
task.type,
task.gid,
task.token,
task.pid,
task.details,
],
)[0];
});
}
add_token(
uid: number | bigint,
added: number,
http_only: boolean,
secure: boolean,
client: string | null,
device: string | null,
client_version: string | null,
client_platform: string | null,
): Token {
let token = randomstring();
while (this.get_token(token) || this.get_shared_token(token)) {
token = randomstring();
}
this.db.query(
"INSERT INTO token (uid, token, expired, http_only, secure, last_used, client, device, client_version, client_platform) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",
[
uid,
token,
new Date(added + 2592000000),
http_only,
secure,
new Date(added),
client,
device,
client_version,
client_platform,
],
);
const t = this.get_token(token);
if (!t) throw Error("Failed to add token.");
return t;
}
add_user(user: User) {
if (user.id === 0 || user.id === 0n) {
this.db.query(
"INSERT INTO user (username, password, is_admin, permissions) VALUES (?, ?, ?, ?);",
[
user.username,
user.password,
user.is_admin,
user.permissions,
],
);
} else {
this.db.query(
"INSERT OR REPLACE INTO user VALUES (?, ?, ?, ?, ?);",
[
user.id,
user.username,
user.password,
user.is_admin,
user.permissions,
],
);
}
const u = this.get_user_by_name(user.username);
if (!u) throw Error("Failed to add/update user.");
return u;
}
begin(type: SqliteTransactionType) {
try {
this.db.execute(`BEGIN ${type} TRANSACTION;`);
return true;
} catch (e) {
if (e instanceof SqliteError) {
if (e.code == Status.SqliteBusy) return false;
}
if (e instanceof Sqlite3Error) {
// SQLITE_BUSY
if (e.code == 5) return false;
}
throw e;
}
}
better_optimize() {
const d = this.db.query<[string, number | bigint]>(
"SELECT * FROM main.sqlite_sequence",
);
d.forEach(([name, count]) => {
const c = this.db.query<[number | bigint]>(
`SELECT COUNT(*) FROM "${name}";`,
)[0][0];
if (c != count) {
const d = this.db.query<[number | bigint]>(
`SELECT id FROM "${name}";`,
);
d.forEach((d, i) => {
const r = i + 1;
if (d[0] != r) {
this.db.query(
`UPDATE "${name}" SET id = ? WHERE id = ?;`,
[r, d[0]],
);
if (name === "tag") {
this.db.query(
"UPDATE gtag SET id = ? WHERE id = ?;",
[r, d[0]],
);
}
}
});
this.db.query(
"UPDATE sqlite_sequence SET seq = ? WHERE name = ?;",
[c, name],
);
}
});
}
check_download_task(gid: number | bigint, token: string) {
return this.transaction(() => {
const r = this.db.queryEntries<Task>(
"SELECT * FROM task WHERE (type = ? OR type = ?) AND gid = ? AND token = ?;",
[TaskType.Download, TaskType.Import, gid, token],
);
return r.length ? r[0] : undefined;
});
}
check_fix_gallery_page_task() {
return this.transaction(() => {
const r = this.db.queryEntries<Task>(
"SELECT * FROM task WHERE type = ?;",
[TaskType.FixGalleryPage],
);
return r.length ? r[0] : undefined;
});
}
check_onetime_task() {
return this.transaction(() => {
const r = this.db.queryEntries<Task>(
"SELECT * FROM task WHERE type = ? OR type = ? OR type = ?;",
[
TaskType.UpdateMeiliSearchData,
TaskType.FixGalleryPage,
TaskType.UpdateTagTranslation,
],
);
return r;
});
}
check_update_meili_search_data_task(gid?: number | bigint) {
const args: QueryParameter[] = [TaskType.UpdateMeiliSearchData];
let wsql = "";
if (gid !== undefined) {
wsql = " AND gid = ?";
args.push(gid);
}
return this.transaction(() => {
const r = this.db.queryEntries<Task>(
`SELECT * FROM task WHERE type = ?${wsql};`,
args,
);
return r.length ? r[0] : undefined;
});
}
check_update_tag_translation_task() {
return this.transaction(() => {
const r = this.db.queryEntries<Task>(
"SELECT * FROM task WHERE type = ?;",
[TaskType.UpdateTagTranslation],
);
return r.length ? r[0] : undefined;
});
}
close() {
this.db.close();
if (this.#file) {
this.#file.close();
}
if (this.#dblock) {
this.dbunlock();
this.#dblock.close();
}
}
async commit() {
while (1) {
try {
this.db.execute("COMMIT TRANSACTION;");
break;
} catch (e) {
if (e instanceof SqliteError) {
if (e.code == Status.SqliteBusy) {
await sleep(1000);
continue;
}
}
throw e;
}
}
}
convert_extended_pmeta(m: ExtendedPMetaRaw[]) {
return m.map((m) => {
const n = m.is_nsfw ? true : false;
const a = m.is_ad ? true : false;
const t = <ExtendedPMeta> <unknown> m;
t.is_nsfw = n;
t.is_ad = a;
return t;
});
}
convert_file(f: EhFileRaw[]) {
return f.map((m) => {
const b = m.is_original != 0;
const t = <EhFile> <unknown> m;
t.is_original = b;
return t;
});
}
convert_filemeta(m: EhFileMetaRaw[]) {
return m.map((m) => {
const n = m.is_nsfw != 0;
const a = m.is_ad != 0;
const t = <EhFileMeta> <unknown> m;
t.is_nsfw = n;
t.is_ad = a;
return t;
});
}
convert_gmeta(m: GMetaRaw[]): GMeta[] {
return m.map((m) => {
if (m.expunged === undefined) return <GMeta> <unknown> m;
const b = m.expunged != 0;
const t = <GMeta> <unknown> m;
t.expunged = b;
return t;
});
}
convert_shared_token(m: SharedTokenRaw[]) {
return m.map((m) => {
const e = m.expired ? new Date(m.expired) : null;
const t = <SharedToken> <unknown> m;
t.expired = e;
t.info = JSON.parse(m.info);
return t;
});
}
convert_token(m: TokenRaw[]) {
return m.map((m) => {
const e = new Date(m.expired);
const h = m.http_only != 0;
const s = m.secure != 0;
const t = <Token> <unknown> m;
const l = new Date(m.last_used);
t.expired = e;
t.http_only = h;
t.secure = s;