forked from genz27/SanHub
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
3617 lines (3209 loc) · 114 KB
/
Copy pathdb.ts
File metadata and controls
3617 lines (3209 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
/* eslint-disable no-console */
import type { User, Generation, SystemConfig, SafeUser, PricingConfig, ChatModel, ChatSession, ChatMessage, CharacterCard, Workspace, WorkspaceData, WorkspaceSummary, ImageBucketConfig, ImageStorageConfig } from '@/types';
import { generateId } from './utils';
import bcrypt from 'bcryptjs';
import { createDatabaseAdapter, type DatabaseAdapter } from './db-adapter';
import { cache, CacheKeys, CacheTTL, withCache } from './cache';
import { buildSafeVideoModels } from './video-model-normalizer';
// ========================================
// 数据库连接(支持 SQLite �?MySQL�?
// ========================================
let adapter: DatabaseAdapter | null = null;
function getAdapter(): DatabaseAdapter {
if (!adapter) {
adapter = createDatabaseAdapter();
console.log(`[DB] 使用数据库类�? ${process.env.DB_TYPE || 'sqlite'}`);
}
return adapter;
}
// ========================================
// 数据库初始化
// ========================================
const CREATE_TABLES_SQL = `
-- 用户表
CREATE TABLE IF NOT EXISTS users (
id VARCHAR(36) PRIMARY KEY,
email VARCHAR(191) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(100) NOT NULL,
role ENUM('user', 'admin', 'moderator') DEFAULT 'user',
balance INT DEFAULT 100,
disabled TINYINT(1) DEFAULT 0,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
INDEX idx_email (email)
);
-- 生成记录表
CREATE TABLE IF NOT EXISTS generations (
id VARCHAR(36) PRIMARY KEY,
user_id VARCHAR(36) NOT NULL,
type ENUM('sora-video', 'sora-image', 'gemini-image', 'zimage-image', 'gitee-image') NOT NULL,
prompt TEXT,
params TEXT,
result_url LONGTEXT,
cost INT DEFAULT 0,
balance_precharged TINYINT(1) DEFAULT 0,
balance_refunded TINYINT(1) DEFAULT 0,
status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending',
error_message TEXT,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
INDEX idx_user_id (user_id),
INDEX idx_created_at (created_at),
INDEX idx_status (status)
);
-- 系统配置表
CREATE TABLE IF NOT EXISTS system_config (
id INT PRIMARY KEY DEFAULT 1,
sora_api_key VARCHAR(500) DEFAULT '',
sora_base_url VARCHAR(500) DEFAULT 'http://localhost:8000',
gemini_api_key VARCHAR(500) DEFAULT '',
gemini_base_url VARCHAR(500) DEFAULT 'https://generativelanguage.googleapis.com',
zimage_api_key VARCHAR(500) DEFAULT '',
zimage_base_url VARCHAR(500) DEFAULT 'https://api-inference.modelscope.cn/',
gitee_api_key TEXT,
gitee_free_api_key TEXT,
gitee_base_url VARCHAR(500) DEFAULT 'https://ai.gitee.com/',
picui_api_key VARCHAR(500) DEFAULT '',
picui_base_url VARCHAR(500) DEFAULT 'https://picui.cn/api/v1',
square_enabled TINYINT(1) DEFAULT 1,
gacha_enabled TINYINT(1) DEFAULT 1,
character_card_enabled TINYINT(1) DEFAULT 1,
invite_enabled TINYINT(1) DEFAULT 1,
invite_reward_enabled TINYINT(1) DEFAULT 1,
invite_invitee_bonus INT DEFAULT 100,
invite_inviter_bonus INT DEFAULT 50,
image_storage_buckets LONGTEXT,
image_storage_default_bucket_id VARCHAR(64) DEFAULT '',
sora_backend_url VARCHAR(500) DEFAULT '',
sora_backend_username VARCHAR(100) DEFAULT '',
sora_backend_password VARCHAR(100) DEFAULT '',
sora_backend_token VARCHAR(500) DEFAULT '',
pricing_sora_video_10s INT DEFAULT 100,
pricing_sora_video_15s INT DEFAULT 150,
pricing_sora_video_25s INT DEFAULT 200,
pricing_sora_image INT DEFAULT 50,
pricing_gemini_nano INT DEFAULT 10,
pricing_gemini_pro INT DEFAULT 30,
pricing_zimage_image INT DEFAULT 30,
pricing_gitee_image INT DEFAULT 30,
pricing_chat INT DEFAULT 1,
register_enabled TINYINT(1) DEFAULT 1,
default_balance INT DEFAULT 100,
prompt_filter_enabled TINYINT(1) DEFAULT 0,
prompt_filter_model_id VARCHAR(36) DEFAULT '',
prompt_filter_prompt TEXT,
prompt_translate_enabled TINYINT(1) DEFAULT 0,
prompt_translate_model_id VARCHAR(36) DEFAULT '',
prompt_translate_prompt TEXT,
prompt_blocklist_enabled TINYINT(1) DEFAULT 0,
prompt_blocklist_words TEXT,
rate_limit_image_max_requests INT DEFAULT 30,
rate_limit_image_window_seconds INT DEFAULT 60,
rate_limit_video_max_requests INT DEFAULT 30,
rate_limit_video_window_seconds INT DEFAULT 60
);
-- 聊天模型表
CREATE TABLE IF NOT EXISTS chat_models (
id VARCHAR(36) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
api_url VARCHAR(500) NOT NULL,
api_key VARCHAR(500) NOT NULL,
model_id VARCHAR(100) NOT NULL,
supports_vision TINYINT(1) DEFAULT 0,
max_tokens INT DEFAULT 128000,
enabled TINYINT(1) DEFAULT 1,
cost_per_message INT DEFAULT 1,
created_at BIGINT NOT NULL,
INDEX idx_enabled (enabled)
);
-- 聊天会话表
CREATE TABLE IF NOT EXISTS chat_sessions (
id VARCHAR(36) PRIMARY KEY,
user_id VARCHAR(36) NOT NULL,
title VARCHAR(200) DEFAULT '新对话',
model_id VARCHAR(36) NOT NULL,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
INDEX idx_user_id (user_id),
INDEX idx_updated_at (updated_at)
);
-- 聊天消息表
CREATE TABLE IF NOT EXISTS chat_messages (
id VARCHAR(36) PRIMARY KEY,
session_id VARCHAR(36) NOT NULL,
role ENUM('user', 'assistant', 'system') NOT NULL,
content LONGTEXT NOT NULL,
images TEXT,
token_count INT DEFAULT 0,
created_at BIGINT NOT NULL,
INDEX idx_session_id (session_id),
INDEX idx_created_at (created_at)
);
-- 角色卡表
CREATE TABLE IF NOT EXISTS character_cards (
id VARCHAR(36) PRIMARY KEY,
user_id VARCHAR(36) NOT NULL,
character_name VARCHAR(200) DEFAULT '',
avatar_url LONGTEXT,
source_video_url TEXT,
status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending',
error_message TEXT,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
INDEX idx_user_id (user_id),
INDEX idx_created_at (created_at)
);
-- workspaces table
CREATE TABLE IF NOT EXISTS workspaces (
id VARCHAR(36) PRIMARY KEY,
user_id VARCHAR(36) NOT NULL,
name VARCHAR(200) NOT NULL,
data LONGTEXT,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
INDEX idx_user_id (user_id),
INDEX idx_updated_at (updated_at),
INDEX idx_name (name)
);
`;
let initialized = false;
export async function initializeDatabase(): Promise<void> {
const db = getAdapter();
// 渠道表始终尝试创建(幂等操作,确保新表被创建)
await initializeImageChannelsTablesInternal(db);
await initializeVideoChannelsTablesInternal(db);
if (initialized) return;
const statements = CREATE_TABLES_SQL.split(';').filter((s) => s.trim());
for (const statement of statements) {
if (statement.trim()) {
await db.execute(statement);
}
}
const dbType = process.env.DB_TYPE || 'sqlite';
// 迁移:确保 avatar_url 列是 LONGTEXT(仅 MySQL 需要,SQLite 不支持 MODIFY COLUMN)
if (dbType === 'mysql') {
try {
await db.execute(`
ALTER TABLE character_cards MODIFY COLUMN avatar_url LONGTEXT
`);
} catch (e) {
// 忽略错误(列可能已经是正确类型或表不存在)
}
}
// 初始化系统配置(如果不存在)
const [configRows] = await db.execute('SELECT id FROM system_config WHERE id = 1');
if ((configRows as unknown[]).length === 0) {
await db.execute(`
INSERT INTO system_config (id, sora_api_key, sora_base_url, gemini_api_key, gemini_base_url)
VALUES (1, ?, ?, ?, ?)
`, [
process.env.SORA_API_KEY || '',
process.env.SORA_BASE_URL || 'http://localhost:8000',
process.env.GEMINI_API_KEY || '',
process.env.GEMINI_BASE_URL || 'https://generativelanguage.googleapis.com',
]);
}
// 初始化管理员账号
await initializeAdmin();
// 添加 disabled 字段(如果不存在�?
try {
await db.execute('ALTER TABLE users ADD COLUMN disabled BOOLEAN DEFAULT FALSE');
} catch {
// 字段已存在,忽略错误
}
// 添加 generations 表的新字段(如果不存在)
try {
if (dbType === 'mysql') {
await db.execute("ALTER TABLE generations ADD COLUMN status ENUM('pending', 'processing', 'completed', 'failed') DEFAULT 'pending'");
} else {
// SQLite: ENUM 转为 TEXT
await db.execute("ALTER TABLE generations ADD COLUMN status TEXT DEFAULT 'pending'");
}
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute('ALTER TABLE generations ADD COLUMN error_message TEXT');
} catch {
// 字段已存在,忽略错误
}
// 添加余额预扣/退款标记字段(如果不存在)
try {
await db.execute('ALTER TABLE generations ADD COLUMN balance_precharged TINYINT(1) DEFAULT 0');
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute('ALTER TABLE generations ADD COLUMN balance_refunded TINYINT(1) DEFAULT 0');
} catch {
// 字段已存在,忽略错误
}
// 确保 generations.params 列存在(用于存储 permalink / revised_prompt 等扩展信息)
try {
if (dbType === 'mysql') {
await db.execute('ALTER TABLE generations ADD COLUMN params TEXT');
} else {
await db.execute('ALTER TABLE generations ADD COLUMN params TEXT');
}
} catch {
// 字段已存在,忽略错误
}
try {
if (dbType === 'mysql') {
await db.execute('ALTER TABLE generations ADD COLUMN updated_at BIGINT NOT NULL DEFAULT 0');
} else {
// SQLite: 不支持 NOT NULL 和 DEFAULT 同时使用在 ALTER TABLE 中
await db.execute('ALTER TABLE generations ADD COLUMN updated_at INTEGER DEFAULT 0');
}
} catch {
// 字段已存在,忽略错误
}
// 为已存在的记录设置默认值
try {
await db.execute("UPDATE generations SET status = 'completed' WHERE status IS NULL OR status = ''");
await db.execute('UPDATE generations SET updated_at = created_at WHERE updated_at = 0 OR updated_at IS NULL');
await db.execute("UPDATE generations SET params = '{}' WHERE params IS NULL OR params = ''");
} catch {
// 忽略错误
}
// 添加 Z-Image 配置字段(如果不存在)
try {
await db.execute("ALTER TABLE system_config ADD COLUMN zimage_api_key VARCHAR(500) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN zimage_base_url VARCHAR(500) DEFAULT 'https://api-inference.modelscope.cn/'");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute('ALTER TABLE system_config ADD COLUMN pricing_zimage_image INT DEFAULT 30');
} catch {
// 字段已存在,忽略错误
}
// 添加 Gitee 配置字段(如果不存在)
try {
await db.execute('ALTER TABLE system_config ADD COLUMN gitee_api_key TEXT');
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute('ALTER TABLE system_config ADD COLUMN gitee_free_api_key TEXT');
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN gitee_base_url VARCHAR(500) DEFAULT 'https://ai.gitee.com/'");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute('ALTER TABLE system_config ADD COLUMN pricing_gitee_image INT DEFAULT 30');
} catch {
// 字段已存在,忽略错误
}
// 添加 25s 视频定价字段
try {
await db.execute('ALTER TABLE system_config ADD COLUMN pricing_sora_video_25s INT DEFAULT 200');
} catch {
// 字段已存在,忽略错误
}
// 添加 SORA 后台配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN sora_backend_url VARCHAR(500) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN sora_backend_username VARCHAR(100) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN sora_backend_password VARCHAR(100) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN sora_backend_token VARCHAR(500) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
// 添加公告配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN announcement_title VARCHAR(200) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN announcement_content TEXT");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN announcement_enabled TINYINT(1) DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN announcement_updated_at BIGINT DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
// 添加 PicUI 图床配置字段(如果不存在)
try {
await db.execute("ALTER TABLE system_config ADD COLUMN picui_api_key VARCHAR(500) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN picui_base_url VARCHAR(500) DEFAULT 'https://picui.cn/api/v1'");
} catch {
// 字段已存在,忽略错误
}
// 添加功能开关与邀请码配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN square_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN gacha_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN character_card_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN invite_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN invite_reward_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN invite_invitee_bonus INT DEFAULT 100");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN invite_inviter_bonus INT DEFAULT 50");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN image_storage_buckets LONGTEXT");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN image_storage_default_bucket_id VARCHAR(64) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
// 添加渠道启用配置字段(如果不存在)
try {
await db.execute("ALTER TABLE system_config ADD COLUMN channel_sora_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN channel_gemini_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN channel_zimage_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN channel_gitee_enabled TINYINT(1) DEFAULT 1");
} catch {
// 字段已存在,忽略错误
}
// 添加每日请求限制配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN daily_limit_image INT DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN daily_limit_video INT DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN daily_limit_character_card INT DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
// 添加网站配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN site_name VARCHAR(100) DEFAULT 'SANHUB'");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN site_tagline VARCHAR(200) DEFAULT 'Let Imagination Come Alive'");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN site_description TEXT");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN site_sub_description TEXT");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN contact_email VARCHAR(200) DEFAULT 'support@sanhub.com'");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN site_copyright VARCHAR(200) DEFAULT 'Copyright © 2025 SANHUB'");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN site_powered_by VARCHAR(200) DEFAULT 'Powered by OpenAI Sora & Google Gemini'");
} catch {
// 字段已存在,忽略错误
}
// 添加模型禁用配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN disabled_image_models TEXT");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN disabled_video_models TEXT");
} catch {
// 字段已存在,忽略错误
}
// 添加视频加速配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN video_proxy_enabled TINYINT(1) DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN video_proxy_base_url VARCHAR(500) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
// 添加提示词处理配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_filter_enabled TINYINT(1) DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_filter_model_id VARCHAR(36) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_filter_prompt TEXT");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_translate_enabled TINYINT(1) DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_translate_model_id VARCHAR(36) DEFAULT ''");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_translate_prompt TEXT");
} catch {
// 字段已存在,忽略错误
}
// 添加提示词敏感词拦截配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_blocklist_enabled TINYINT(1) DEFAULT 0");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN prompt_blocklist_words TEXT");
} catch {
// 字段已存在,忽略错误
}
// 添加生成限流配置字段
try {
await db.execute("ALTER TABLE system_config ADD COLUMN rate_limit_image_max_requests INT DEFAULT 30");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN rate_limit_image_window_seconds INT DEFAULT 60");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN rate_limit_video_max_requests INT DEFAULT 30");
} catch {
// 字段已存在,忽略错误
}
try {
await db.execute("ALTER TABLE system_config ADD COLUMN rate_limit_video_window_seconds INT DEFAULT 60");
} catch {
// 字段已存在,忽略错误
}
// 更新 generations 表的 type 字段以支持 gitee-image(MySQL 需要修改 ENUM)
if (dbType === 'mysql') {
try {
await db.execute("ALTER TABLE generations MODIFY COLUMN type ENUM('sora-video', 'sora-image', 'gemini-image', 'zimage-image', 'gitee-image') NOT NULL");
} catch {
// 忽略错误
}
}
// 更新 generations 表的 status 字段以支持 cancelled(MySQL 需要修改 ENUM)
if (dbType === 'mysql') {
try {
await db.execute("ALTER TABLE generations MODIFY COLUMN status ENUM('pending', 'processing', 'completed', 'failed', 'cancelled') DEFAULT 'pending'");
} catch {
// 忽略错误
}
}
// 更新 users 表的 role 字段以支持 moderator(MySQL 需要修改 ENUM)
if (dbType === 'mysql') {
try {
await db.execute("ALTER TABLE users MODIFY COLUMN role ENUM('user', 'admin', 'moderator') DEFAULT 'user'");
} catch {
// 忽略错误
}
}
initialized = true;
console.log('Database initialized successfully');
}
// ========================================
// 用户操作
// ========================================
export async function createUser(
email: string,
password: string,
name: string,
role: 'user' | 'admin' = 'user',
balance?: number
): Promise<User> {
await initializeDatabase();
const db = getAdapter();
// 检查邮箱是否已存在
const [existing] = await db.execute(
'SELECT id FROM users WHERE email = ?',
[email]
);
if ((existing as unknown[]).length > 0) {
throw new Error('该邮箱已被注册');
}
const config = await getSystemConfig();
const hashedPassword = await bcrypt.hash(password, 10);
const now = Date.now();
const user: User = {
id: generateId(),
email,
password: hashedPassword,
name,
role,
balance: balance ?? config.defaultBalance,
disabled: false,
createdAt: now,
updatedAt: now,
};
await db.execute(
`INSERT INTO users (id, email, password, name, role, balance, disabled, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[user.id, user.email, user.password, user.name, user.role, user.balance, user.disabled, user.createdAt, user.updatedAt]
);
return user;
}
export async function getUserById(id: string): Promise<User | null> {
await initializeDatabase();
const db = getAdapter();
const [rows] = await db.execute(
'SELECT * FROM users WHERE id = ?',
[id]
);
const users = rows as any[];
if (users.length === 0) return null;
const row = users[0];
return {
id: row.id,
email: row.email,
password: row.password,
name: row.name,
role: row.role,
balance: row.balance,
disabled: Boolean(row.disabled),
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
};
}
export async function getUserByEmail(email: string): Promise<User | null> {
await initializeDatabase();
const db = getAdapter();
const [rows] = await db.execute(
'SELECT * FROM users WHERE email = ?',
[email]
);
const users = rows as any[];
if (users.length === 0) return null;
const row = users[0];
return {
id: row.id,
email: row.email,
password: row.password,
name: row.name,
role: row.role,
balance: row.balance,
disabled: Boolean(row.disabled),
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
};
}
export async function verifyPassword(
email: string,
password: string
): Promise<User | null> {
const user = await getUserByEmail(email);
if (!user) return null;
// Disabled users cannot login - throw explicit error
if (user.disabled) {
throw new Error('账号已被禁用,请联系管理员');
}
const valid = await bcrypt.compare(password, user.password);
if (!valid) return null;
return user;
}
export async function updateUser(
id: string,
updates: Partial<Omit<User, 'id' | 'email' | 'createdAt'>>
): Promise<User | null> {
await initializeDatabase();
const db = getAdapter();
const user = await getUserById(id);
if (!user) return null;
const fields: string[] = [];
const values: unknown[] = [];
if (updates.name !== undefined) {
fields.push('name = ?');
values.push(updates.name);
}
if (updates.password !== undefined) {
fields.push('password = ?');
values.push(await bcrypt.hash(updates.password, 10));
}
if (updates.role !== undefined) {
fields.push('role = ?');
values.push(updates.role);
}
if (updates.balance !== undefined) {
fields.push('balance = ?');
values.push(updates.balance);
}
if (updates.disabled !== undefined) {
fields.push('disabled = ?');
values.push(updates.disabled);
}
if (fields.length === 0) return user;
fields.push('updated_at = ?');
values.push(Date.now());
values.push(id);
await db.execute(
`UPDATE users SET ${fields.join(', ')} WHERE id = ?`,
values
);
return getUserById(id);
}
export type BalanceUpdateMode = 'strict' | 'clamp';
export async function updateUserBalance(
id: string,
delta: number,
mode: BalanceUpdateMode = 'strict'
): Promise<number> {
await initializeDatabase();
const db = getAdapter();
const safeDelta = Number(delta);
if (!Number.isFinite(safeDelta)) {
throw new Error('Invalid balance delta');
}
const now = Date.now();
if (mode === 'clamp') {
const [result] = await db.execute(
'UPDATE users SET balance = CASE WHEN balance + ? < 0 THEN 0 ELSE balance + ? END, updated_at = ? WHERE id = ?',
[safeDelta, safeDelta, now, id]
);
if (!(result as any).affectedRows) {
throw new Error('User not found');
}
const user = await getUserById(id);
if (!user) throw new Error('User not found');
return user.balance;
}
const [result] = await db.execute(
'UPDATE users SET balance = balance + ?, updated_at = ? WHERE id = ? AND balance + ? >= 0',
[safeDelta, now, id, safeDelta]
);
if (!(result as any).affectedRows) {
const user = await getUserById(id);
if (!user) throw new Error('User not found');
throw new Error('Insufficient balance');
}
const user = await getUserById(id);
if (!user) throw new Error('User not found');
return user.balance;
}
export async function getAllUsers(options: {
limit?: number;
offset?: number;
search?: string;
} = {}): Promise<SafeUser[]> {
await initializeDatabase();
const db = getAdapter();
const limit = Math.max(Number(options.limit) || 200, 1);
const offset = Math.max(Number(options.offset) || 0, 0);
const search = options.search?.trim();
let sql = 'SELECT id, email, name, role, balance, disabled, created_at FROM users';
const params: unknown[] = [];
if (search) {
sql += ' WHERE email LIKE ? OR name LIKE ?';
const term = `%${search}%`;
params.push(term, term);
}
sql += ` ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`;
const [rows] = await db.execute(sql, params);
return (rows as any[]).map((row) => ({
id: row.id,
email: row.email,
name: row.name,
role: row.role,
balance: row.balance,
disabled: Boolean(row.disabled),
createdAt: Number(row.created_at),
}));
}
export async function getUsersCount(search?: string): Promise<number> {
await initializeDatabase();
const db = getAdapter();
const term = search?.trim();
let sql = 'SELECT COUNT(1) as count FROM users';
const params: unknown[] = [];
if (term) {
sql += ' WHERE email LIKE ? OR name LIKE ?';
const like = `%${term}%`;
params.push(like, like);
}
const [rows] = await db.execute(sql, params);
const row = (rows as any[])[0];
return Number(row?.count || 0);
}
export async function deleteUser(id: string): Promise<boolean> {
await initializeDatabase();
const db = getAdapter();
const [result] = await db.execute('DELETE FROM users WHERE id = ?', [id]);
return (result as any).affectedRows > 0;
}
// ========================================
// 生成记录操作
// ========================================
export async function saveGeneration(
generation: Omit<Generation, 'id' | 'createdAt' | 'updatedAt'>
): Promise<Generation> {
await initializeDatabase();
const db = getAdapter();
const now = Date.now();
const gen: Generation = {
...generation,
id: generateId(),
createdAt: now,
updatedAt: now,
balancePrecharged: generation.balancePrecharged ?? false,
balanceRefunded: generation.balanceRefunded ?? false,
};
await db.execute(
`INSERT INTO generations (id, user_id, type, prompt, params, result_url, cost, balance_precharged, balance_refunded, status, error_message, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
gen.id,
gen.userId,
gen.type,
gen.prompt,
JSON.stringify(gen.params),
gen.resultUrl,
gen.cost,
gen.balancePrecharged ? 1 : 0,
gen.balanceRefunded ? 1 : 0,
gen.status,
gen.errorMessage || null,
gen.createdAt,
gen.updatedAt,
]
);
return gen;
}
export async function getGenerationByClientRequestId(
userId: string,
clientRequestId: string
): Promise<Generation | null> {
await initializeDatabase();
const db = getAdapter();
const [rows] = await db.execute(
`SELECT * FROM generations
WHERE user_id = ? AND params LIKE ?
ORDER BY created_at DESC LIMIT 10`,
[userId, `%"clientRequestId":"${clientRequestId}"%`]
);
for (const row of rows as any[]) {
const params = typeof row.params === 'string' ? JSON.parse(row.params) : row.params;
if (params?.clientRequestId !== clientRequestId) {
continue;
}
return {
id: row.id,
userId: row.user_id,
type: row.type,
prompt: row.prompt,
params,
resultUrl: row.result_url,
cost: row.cost,
status: row.status || 'completed',
balancePrecharged: Boolean(row.balance_precharged),
balanceRefunded: Boolean(row.balance_refunded),
errorMessage: row.error_message || undefined,
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at || row.created_at),
};
}
return null;
}