Repository navigation
Expand file tree
/
Copy pathindex-example.js
More file actions
2881 lines (2720 loc) · 124 KB
/
Copy pathindex-example.js
File metadata and controls
2881 lines (2720 loc) · 124 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
#!/usr/bin/env node
const path = require('path');
const util = require('util');
const ejs = require('ejs');
const renderFile = util.promisify(ejs.renderFile);
const axios = require('axios');
var qs = require('qs');
const cheerio = require('cheerio');
const exec = util.promisify(require('child_process').exec); // exec 返回Promise对象
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// const https = require('https');
const session = require('express-session');
const sharedSession = require('express-socket.io-session');
const fs = require('fs');
const schedule = require('node-schedule');
// 服务器网页端口
const port = 3010; // https port
const httpPort = 3000;
// Mikan的域名 如果使用反代服务器则改为反代服务器域名
const mikanHost = "https://mikanani.me";
// 代理服务器地址
// TODO: 不使用代理服务器
const proxyConfig = {
host: 'localhost',
port: 4780, // [请自行修改]
};
// 动漫视频文件存放路径
const animePath = path.join('D:', 'anime'); // [请自行修改]
// 数据库设置
const dbConfig = {
host: 'localhost',
user: '', // [请自行修改]
password: '', // [请自行修改]
database: '' // [请自行修改]
};
// qbittorrent 配置 账号密码无实际作用, 请在qbittorrent里允许本地用户绕过验证
const qbittorrentConfig = {
host: 'http://localhost:8080',
username: '',
password: ''
};
// ffmpeg路径 如果添加了环境变量直接使用ffmpeg就可以 否则输入完整路径 路径里有空格请加上引号
const ffmpegPath = `ffmpeg`;
// ffmpeg视频编码设置 [请自行选择]
const ffmpegEncoding = "libx264"; // 速度较低
// const ffmpegEncoding = "h264_amf"; // 备用 AMD 加速
// const ffmpegEncoding = "h264_nvenc"; // 备用 NVIDIA 加速
const ffmpegExtra = "-tune animation -crf 20"; // 额外参数
// 读取 SSL 证书和私钥文件
const SSLOptions = {
key: fs.readFileSync('./nekoneko.site.key'), // [请自行修改]
cert: fs.readFileSync('./nekoneko.site.crt') // [请自行修改]
};
const defaultUserPerm = 9999; // 用户默认权限
// 获取格式化时间字符串
function getFormattedTimestamp() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
}
// 格式化时间
function formatDate(maxDate) {
const formattedDate = `${maxDate.getFullYear()}/${String(maxDate.getMonth() + 1).padStart(2, '0')}/${String(maxDate.getDate()).padStart(2, '0')} ${String(maxDate.getHours()).padStart(2, '0')}:${String(maxDate.getMinutes()).padStart(2, '0')}:${String(maxDate.getSeconds()).padStart(2, '0')}`;
return formattedDate;
}
// 格式化时间
function formatDay(maxDate) {
const formattedDate = `${maxDate.getFullYear()}/${String(maxDate.getMonth() + 1).padStart(2, '0')}/${String(maxDate.getDate()).padStart(2, '0')}`;
return formattedDate;
}
// 文件大小字符串转为字节数
function parseFileSize(fileSizeStr) {
const units = {
B: 1,
KB: 1024,
MB: 1024 * 1024,
GB: 1024 * 1024 * 1024,
TB: 1024 * 1024 * 1024 * 1024,
};
const sizeRegex = /^(\d+(\.\d+)?)\s*([BKMGT]?B)$/i;
const match = fileSizeStr.match(sizeRegex);
if (match && match.length === 4) {
const value = parseFloat(match[1]);
const unit = match[3].toUpperCase();
if (units.hasOwnProperty(unit)) {
return Math.floor(value * units[unit]);
}
}
return NaN; // 表示解析失败
}
// 字节数转文本
function formatFileSize(bytes) {
const units = ["B", "KB", "MB", "GB", "TB"];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
}
// 检查是不是只有数字
function isdig(str) {
const digitsPattern = /^\d+$/;
return digitsPattern.test(str);
}
// 判断文件或者目录
function checkPathType(path) {
try {
const stats = fs.statSync(path);
if (stats.isFile()) {
// 是文件路径
return 1;
} else if (stats.isDirectory()) {
// 是目录路径
return 0;
} else {
// 其他情况
return -1;
}
} catch (err) {
// 发生错误,路径不存在或其他异常
return -1;
}
}
// 替换路径
function isPathInsideDirectory(filePath, directoryPath, replacement) {
const normalizedFilePath = path.normalize(filePath);
const normalizedDirectoryPath = path.normalize(directoryPath);
if (!normalizedFilePath.startsWith(normalizedDirectoryPath + path.sep)) {
return false;
}
const relativePath = normalizedFilePath.slice(normalizedDirectoryPath.length + 1);
const result = path.join(replacement, relativePath);
return result;
}
// 列表随机选择
function randomChoice(arr) {
const randomIndex = Math.round(Math.random() * (arr.length - 1));
return arr[randomIndex];
}
// 随机选多个
function randomSample(elements, count) {
var randomElements = [];
// 确保要选取的数量不超过列表长度
count = Math.min(count, elements.length);
// 使用while循环随机选取元素
while (randomElements.length < count) {
var randomIndex = Math.floor(Math.random() * elements.length);
// 确保不重复选取元素
if (randomElements.indexOf(elements[randomIndex]) === -1) {
randomElements.push(elements[randomIndex]);
}
}
return randomElements;
}
// 提取字符串列表的正则表达式
function generateRegex(stringList) {
if (stringList.length === 1) {
return new RegExp(`^(.*?)$`);
}
let commonPrefix = stringList[0];
let commonSuffix = stringList[0];
for (const str of stringList) {
let i = 0;
while (i < commonPrefix.length && commonPrefix[i] === str[i]) {
i++;
}
commonPrefix = commonPrefix.slice(0, i);
i = 0;
while (i < commonSuffix.length && commonSuffix[commonSuffix.length - 1 - i] === str[str.length - 1 - i]) {
i++;
}
commonSuffix = commonSuffix.slice(-i);
}
const regexPattern = `^${commonPrefix}(.*?)${commonSuffix}$`;
return new RegExp(regexPattern);
}
// 加载public目录下的静态文件
// app.get('/public/style.css', (req, res) => { res.sendFile(__dirname + '/public/style.css'); });
// app.get('/public/header.css', (req, res) => { res.sendFile(__dirname + '/public/header.css'); });
// app.get('/public/index.css', (req, res) => { res.sendFile(__dirname + '/public/index.css'); });
// app.get('/public/animeindex.css', (req, res) => { res.sendFile(__dirname + '/public/animeindex.css'); });
// app.get('/public/animeplayer.css', (req, res) => { res.sendFile(__dirname + '/public/animeplayer.css'); });
// app.get('/public/animeconsole.css', (req, res) => { res.sendFile(__dirname + '/public/animeconsole.css'); });
// app.get('/public/auth.css', (req, res) => { res.sendFile(__dirname + '/public/auth.css'); });
// app.get('/public/animeindex.js', (req, res) => { res.sendFile(__dirname + '/public/animeindex.js'); });
// app.get('/public/animeplayer.js', (req, res) => { res.sendFile(__dirname + '/public/animeplayer.js'); });
// app.get('/public/animeplayer-v2.js', (req, res) => { res.sendFile(__dirname + '/public/animeplayer-v2.js'); });
// app.get('/public/animeconsole.js', (req, res) => { res.sendFile(__dirname + '/public/animeconsole.js'); });
// app.get('/public/main.js', (req, res) => { res.sendFile(__dirname + '/public/main.js'); });
// app.get('/public/imgascii.js', (req, res) => { res.sendFile(__dirname + '/public/imgascii.js'); });
// app.get('/public/randomw.js', (req, res) => { res.sendFile(__dirname + '/public/randomw.js'); });
// app.get('/public/randomw.css', (req, res) => { res.sendFile(__dirname + '/public/randomw.css'); });
// app.get('/public/jquery-3.6.0.min.js', (req, res) => { res.sendFile(__dirname + '/public/jquery-3.6.0.min.js'); });
// app.get('/public/plyr_3.7.8.js', (req, res) => { res.sendFile(__dirname + '/public/plyr_3.7.8.js'); });
// app.get('/public/plyr_3.7.8.css', (req, res) => { res.sendFile(__dirname + '/public/plyr_3.7.8.css'); });
// app.get('/public/placeholder.min.mp4', (req, res) => { res.sendFile(__dirname + '/public/placeholder.min.mp4'); });
// app.get('/public/placeholder.min.jpg', (req, res) => { res.sendFile(__dirname + '/public/placeholder.min.jpg'); });
// app.get('/public/mdui.min.css', (req, res) => { res.sendFile(__dirname + '/public/mdui.min.css'); });
// app.get('/public/mdui.min.js', (req, res) => { res.sendFile(__dirname + '/public/mdui.min.js'); });
// app.get('/public/class_schedule.css', (req, res) => { res.sendFile(__dirname + '/public/class_schedule.css'); });
// app.get('/public/index.74ecf734.js', (req, res) => { res.sendFile(__dirname + '/public/index.74ecf734.js'); });
// let server = undefined;
// if (useSSL) {
// const https = require('https');
// server = https.createServer(SSLOptions, app);
// } else {
// const http = require('http');
// server = http.createServer(app);
// }
// 创建目录
const pathList = [
'/animes',
'/animes/cover',
'/downloads',
];
function createDirectoryRecursively(dirPath) {
const normalizedPath = path.normalize(dirPath);
if (!fs.existsSync(normalizedPath)) {
// 如果路径不存在,创建它
fs.mkdirSync(normalizedPath, { recursive: true });
console.log(`已创建目录:${normalizedPath}`);
} else {
console.log(`目录已存在:${normalizedPath}`);
}
}
// 递归的创建目录
pathList.forEach((dirPath) => {
createDirectoryRecursively(dirPath);
});
const https = require('https');
const http = require('http');
const server = https.createServer(SSLOptions, app);
const httpServer = http.createServer(app);
//const server = http.createServer({}, app);
const io = require('socket.io')(server);
const mysql = require('mysql');
const tunnel = require('tunnel');
const httpProxy = tunnel.httpsOverHttp({
proxy: proxyConfig
});
// 设置模板引擎
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.set('ejs', require('ejs').__express);
// app.use((req, res, next) => {
// if (req.protocol === 'http') {
// const httpsUrl = `https://${req.headers.host}${req.originalUrl}`;
// return res.redirect(httpsUrl);
// }
// next();
// });
// 设置中间件
app.use(express.urlencoded({ extended: false }));
// 创建会话
const expressSession = session({
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 180 * 24 * 60 * 60 * 1000 }
});
app.use(expressSession);
// 在Socket.IO中使用Express会话
// TODO: 好像不起作用
io.use(sharedSession(expressSession, {
autoSave: true
}));
// 以系统的名义在聊天室发送消息
function sendSystemMessage(msg) {
const message = `[${getFormattedTimestamp()}]${msg}`;
const systemMessage = { nickname: '系统', message };
// 将系统消息保存到数据库
db.query('INSERT INTO messages (nickname, message) VALUES (?, ?)', ['系统', message], (err) => {
if (err) {
console.error(err);
}
});
// 广播系统消息给所有连接的客户端
io.emit('chatMessage', systemMessage);
}
// 创建数据库连接
const db = mysql.createConnection(dbConfig);
// 连接数据库
db.connect((err) => {
if (err) {
throw err;
}
console.log(`[${getFormattedTimestamp()}][系统]连接到数据库成功`);
});
// 每半小时执行一次查询 避免断开连接
setInterval(() => {
db.query('SELECT * FROM messages ORDER BY id DESC LIMIT 1', (error, results) => {
if (error) {
console.error('自动查询出错:', error);
} else {
console.log(`[${getFormattedTimestamp()}][系统]自动查询完成`);
}
});
}, 30 * 60 * 1000); // 30 分钟
// 监听 "error" 事件,在连接断开时进行重新连接
// TODO: 不知道能不能生效
db.on('error', (err) => {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.log(`[${getFormattedTimestamp()}][系统]与数据库的连接已断开,正在尝试重新连接...`);
handleReconnect();
} else {
throw err;
}
});
// 重新连接逻辑
function handleReconnect() {
// 延迟一段时间后尝试重新连接
setTimeout(() => {
db.connect((err) => {
if (err) {
handleReconnect();
} else {
console.log(`[${getFormattedTimestamp()}][系统]已重新连接到数据库`);
}
});
}, 1000); // 1 秒后进行重新连接
}
// 创建数据表
if (1) {
// 创建聊天记录表
db.query(`
CREATE TABLE IF NOT EXISTS messages (
id INT AUTO_INCREMENT PRIMARY KEY,
nickname VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建用户信息表
db.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
nickname VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
perm INT
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建字幕组
db.query(`
CREATE TABLE IF NOT EXISTS stg (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE,
url VARCHAR(255) UNIQUE,
stgid INT UNIQUE
);
`, (err) => {
if (err) {
throw err;
}
});
// 创建动漫表
db.query(`
CREATE TABLE IF NOT EXISTS animes (
id INT AUTO_INCREMENT PRIMARY KEY,
animename VARCHAR(255) UNIQUE,
coverurl VARCHAR(255),
start_date DATE,
last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
file_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
mkid VARCHAR(255) UNIQUE,
bgmid VARCHAR(255) UNIQUE,
stgid INT,
finished TINYINT DEFAULT '0',
torrentreg VARCHAR(255) DEFAULT '',
filereg VARCHAR(255) DEFAULT '',
maxep INT,
filecount INT,
bittorrentcount INT,
FOREIGN KEY (stgid) REFERENCES stg(id)
);
`, (err) => {
if (err) {
throw err;
}
});
// 创建字幕组 动漫关联表
db.query(`
CREATE TABLE IF NOT EXISTS animestg (
id INT AUTO_INCREMENT PRIMARY KEY,
anime_id INT,
stg_id INT,
files TEXT,
FOREIGN KEY (anime_id) REFERENCES animes(id),
FOREIGN KEY (stg_id) REFERENCES stg(id),
UNIQUE KEY unique_ab (anime_id, stg_id)
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建动漫别称表
db.query(`
CREATE TABLE IF NOT EXISTS animealias (
id INT AUTO_INCREMENT PRIMARY KEY,
alias VARCHAR(255) NOT NULL,
anime_id INT,
user_id INT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (anime_id) REFERENCES animes(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建文件表
db.query(`
CREATE TABLE IF NOT EXISTS files (
id INT AUTO_INCREMENT PRIMARY KEY,
path VARCHAR(255) UNIQUE,
localpath VARCHAR(255) UNIQUE,
anime_id INT,
ep VARCHAR(255),
ok TINYINT DEFAULT '0',
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (anime_id) REFERENCES animes(id)
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建播放记录表
db.query(`
CREATE TABLE IF NOT EXISTS playlogs (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
anime_id INT,
file_id INT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (anime_id) REFERENCES animes(id),
FOREIGN KEY (file_id) REFERENCES files(id)
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建播放记录表
db.query(`
CREATE TABLE IF NOT EXISTS animelogs (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
anime_id INT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (anime_id) REFERENCES animes(id),
UNIQUE KEY unique_userid_animeid (user_id, anime_id)
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建动漫评论表
db.query(`
CREATE TABLE IF NOT EXISTS animecomments (
id INT AUTO_INCREMENT PRIMARY KEY,
comment TEXT NOT NULL,
anime_id INT,
user_id INT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_delete TINYINT,
delete_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (anime_id) REFERENCES animes(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
`, (err) => {
if (err) {
throw err;
}
});
// 创建种子表
db.query(`
CREATE TABLE IF NOT EXISTS bittorrent (
xt varchar(255) NOT NULL PRIMARY KEY,
anime_id int(11) DEFAULT NULL,
filename varchar(255) DEFAULT NULL,
download_link varchar(255) DEFAULT NULL,
update_date timestamp NOT NULL DEFAULT current_timestamp(),
filesize bigint(20) DEFAULT NULL,
state tinyint(4) DEFAULT NULL,
progress float DEFAULT NULL,
path varchar(255) DEFAULT NULL,
FOREIGN KEY (anime_id) REFERENCES animes(id)
);
`, (err) => {
if (err) {
throw err;
}
});
}
// 文章 主题 内容 次数
// 用户-选择的文章
if (1) {
db.query(`
CREATE TABLE IF NOT EXISTS texts_texts (
id INT AUTO_INCREMENT PRIMARY KEY,
theme VARCHAR(255),
content TEXT,
used INT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ok TINYINT DEFAULT '1'
)
`, (err) => {
if (err) {
throw err;
}
});
db.query(`
CREATE TABLE IF NOT EXISTS texts_usertexts (
id INT AUTO_INCREMENT PRIMARY KEY,
texts_id INT,
user_id INT,
FOREIGN KEY (texts_id) REFERENCES texts_texts(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
`, (err) => {
if (err) {
throw err;
}
});
}
// 聊天室人数计数
let onlineCount = 0;
// 解析json中间件
app.use(bodyParser.json());
// 图标
app.get('/favicon.ico', (req, res) => {
res.sendFile(path.join(__dirname, 'favicon.ico'))
});
// 图片资源
// TODO: 整理目录结构
app.use('/animes', (req, res, next) => {
if (req.session.loggedin) {
next();
} else {
res.status(403).json({ error: '无权限' });
}
}, express.static(path.join(__dirname, 'animes')));
app.use('/cover', (req, res, next) => {
if (req.session.loggedin) {
next();
} else {
res.status(403).json({ error: '无权限' });
}
}, express.static(path.join(__dirname, 'animes', 'cover')));
app.use('/upload', (req, res, next) => {
if (1) {
next();
} else {
res.status(403).json({ error: '无权限' });
}
}, express.static(path.join(__dirname, 'upload')));
// 文件资源
app.use('/file', (req, res, next) => {
if (1) {
next();
} else {
res.status(403).json({ error: '无权限' });
}
}, express.static(path.join(animePath, "files")));
// 视频资源
app.use('/a', (req, res, next) => {
if (req.session.loggedin) {
next();
} else {
res.status(403).json({ error: '无权限' });
}
}, express.static(animePath));
app.use('/public', (req, res, next) => {
next();
}, express.static(path.join(__dirname, 'public')));
app.use('/score', (req, res, next) => {
const pwd = req.query.pwd;
if (pwd == "Lp7Tz9QxYw2RvE4F6NtG8HbJy5UdWzArX1Vc3M") {
next();
} else {
res.status(500).send("无权限");
}
}, express.static(path.join(__dirname, 'scores')));
// 种子目录
// TODO: 整理目录结构
app.use('/bittorrent', (req, res, next) => {
if (1) {
next();
} else {
res.status(403).json({ error: '无权限' });
}
}, express.static(path.join(__dirname, 'downloads')));
// 首页路由
app.get('/', (req, res) => {
if (req.session.loggedin) {
if (req.session.target) {
const target = req.session.target;
req.session.target = undefined;
res.redirect(target);
} else {
res.render('index', { nickname: req.session.nickname, perm: req.session.perm });
}
} else {
res.redirect('/login');
}
});
// 隐私声明
app.get('/privacystatement', (req, res) => {
res.send('本网站仅作学习用途');
});
// chatroom 页面
app.get('/chatroom', (req, res) => {
if (req.session.loggedin) {
res.render('chatroom', { nickname: req.session.nickname });
} else {
req.session.target = '/chatroom';
res.redirect('/login');
}
});
// anime 索引页面
app.get('/animeindex', (req, res) => {
if (req.session.loggedin) {
res.render('animeindex', { nickname: req.session.nickname });
} else {
req.session.target = '/animeindex'
res.redirect('/login');
}
});
// anime 查看所有动漫 ?page=
app.get('/anime-search-all', (req, res) => {
if (req.session.loggedin) {
const page = req.query.page || 1;
const limit = 20;
const offset = (page - 1) * limit;
const query = 'SELECT * FROM animes ORDER BY start_date DESC LIMIT ? OFFSET ?';
db.query(query, [limit, offset], (error, results) => {
if (error) {
console.error('查询数据库时发生错误:', error);
res.status(500).json({ error: '无法获取数据' });
} else {
res.json(results);
}
});
} else {
res.status(403).json({ error: '无权限' });
}
})
// anime 搜索最近播放
app.get('/anime-search-r', (req, res) => {
if (req.session.loggedin && isdig(req.query.page)) {
const page = req.query.page || 1;
const limit = 10;
const offset = (page - 1) * limit;
const userid = req.session.userid;
const query = `
SELECT a.* FROM animelogs AS l JOIN animes AS a ON l.anime_id = a.id
WHERE user_id = ? ORDER BY date DESC LIMIT ? OFFSET ?`;
db.query(query, [userid, limit, offset], (error, results) => {
if (error) {
console.error('查询数据库时发生错误:', error);
res.status(500).json({ error: '无法获取数据' });
} else {
res.json(results);
}
});
} else {
res.status(403).json({ error: '无权限' });
}
});
// anime 关键字搜索动漫 ?searchstr=&re=true
app.get('/anime-search-s', (req, res) => {
if (req.session.loggedin) {
const searchstr = decodeURIComponent(req.query.searchstr);
if (req.query.re == 'true') {
const query = `SELECT * FROM animes WHERE animename REGEXP ? LIMIT 50;`;
db.query(query, [searchstr], (err, results) => {
if (err) {
console.error(req.session.nickname, '查询数据库时发生错误:', err, '语句', query);
res.status(500).json({ error: '无法获取数据', msg: err, query: query });
} else {
const queryA = `
SELECT a.* FROM animealias AS l JOIN animes AS a ON l.anime_id = a.id
WHERE alias REGEXP ? LIMIT 50`;
db.query(queryA, [searchstr], (errA, resultsA) => {
if (err) {
console.error(req.session.nickname, '查询数据库时发生错误:', errA, '语句', queryA);
res.status(500).json({ error: '无法获取数据', msg: err, query: query });
} else {
const mergedResults = results.concat(resultsA);
const uniqueResults = mergedResults.reduce((acc, currentItem) => {
const foundItem = acc.find(item => item.id === currentItem.id);
if (!foundItem) { acc.push(currentItem); }
return acc;
}, []);
res.json(uniqueResults);
}
})
}
})
} else {
const query = `SELECT * FROM animes WHERE animename LIKE ? LIMIT 5;`;
db.query(query, [searchstr], (err, results) => {
if (err) {
console.error(req.session.nickname, '查询数据库时发生错误:', err, '语句', query);
res.status(500).json({ error: '无法获取数据' });
} else {
const queryA = `
SELECT a.* FROM animealias AS l JOIN animes AS a ON l.anime_id = a.id
WHERE alias LIKE ? LIMIT 20`;
db.query(queryA, [searchstr], (errA, resultsA) => {
if (err) {
console.error(req.session.nickname, '查询数据库时发生错误:', errA, '语句', queryA);
res.status(500).json({ error: '无法获取数据' });
} else {
const queryM = `SELECT * FROM animes WHERE animename LIKE ? LIMIT 40;`;
db.query(queryM, [`%${searchstr}%`], (errM, resultsM) => {
if (errM) {
console.error(req.session.nickname, '查询数据库时发生错误:', errM, '语句', queryM);
res.status(500).json({ error: '无法获取数据' });
} else {
const queryAM = `
SELECT a.* FROM animealias AS l JOIN animes AS a ON l.anime_id = a.id
WHERE alias LIKE ? LIMIT 50`;
db.query(queryAM, [`%${searchstr}%`], (errAM, resultsAM) => {
if (errAM) {
console.error(req.session.nickname, '查询数据库时发生错误:', errAM, '语句', queryAM);
res.status(500).json({ error: '无法获取数据' });
} else {
const mergedResults = results.concat(resultsA).concat(resultsM).concat(resultsAM);
const uniqueResults = mergedResults.reduce((acc, currentItem) => {
const foundItem = acc.find(item => item.id === currentItem.id);
if (!foundItem) { acc.push(currentItem); }
return acc;
}, []);
res.json(uniqueResults);
}
})
}
})
}
})
}
})
}
} else {
res.status(403).json({ error: '无权限' });
}
});
// anime 获取动漫数据 animename 和eps
app.get('/anime-get-data', (req, res) => {
if (req.session.loggedin) {
const animeid = req.query.id;
let query = `SELECT animename FROM animes WHERE id = ?;`;
if (req.session.perm >= 9000) {
query = `SELECT animename, torrentreg FROM animes WHERE id = ?;`;
}
db.query(query, [animeid], (error, results) => {
if (error) {
res.json({ state: 'error', message: `Error fetching data ${error}` });
} else {
if (results.length > 0) {
const animename = results[0].animename;
const torrentreg = results[0].torrentreg;
const query_ep = `SELECT id, ep, path, ok FROM files WHERE anime_id = ?;`
db.query(query_ep, [animeid], (error, results) => {
if (error) {
res.json({ state: 'error', message: `Error fetching data ${error}` });
} else {
const episodes = results;
const responseData = {
state: 'ok',
data: {
animename: animename,
eps: episodes,
torrentreg: torrentreg
},
};
res.json(responseData);
console.log(`[${getFormattedTimestamp()}][${req.session.nickname}]查询动漫数据: ${animename}`);
}
})
} else {
res.status(404).json({ error: '没有对应的动漫' });
}
}
});
} else {
res.status(403).json({ error: '无权限' });
}
});
// anime 获取动漫别称
app.get('/anime-get-alias', (req, res) => {
if (req.session.loggedin) {
const animeid = req.query.id;
const query = `SELECT alias FROM animealias WHERE anime_id = ?;`;
db.query(query, [animeid], (error, results) => {
if (error) {
res.json({ state: 'error', message: `Error fetching data ${error}` });
} else {
res.json({ results: results, perm: req.session.perm >= 11 });
}
})
} else {
res.status(403).json({ error: '无权限' });
}
});
// anime 添加动漫别称 需要权限10
app.get('/anime-add-alias', (req, res) => {
if (req.session.loggedin) {
if (req.session.perm >= 10) {
const animeid = req.query.id;
const uid = req.session.userid;
const alias = decodeURIComponent(req.query.alias);
if (alias) {
const queryA = `SELECT id FROM animealias WHERE anime_id = ? AND alias = ?;`;
db.query(queryA, [animeid, alias], (error, results) => {
if (error) {
res.json({ state: 'error', message: `Error fetching data ${error}` });
} else {
if (results.length == 0) {
const query = `INSERT INTO animealias (alias, anime_id, user_id) VALUES (?, ?, ?);`;
db.query(query, [alias, animeid, uid], (error, results) => {
if (error) {
res.json({ state: 'DB error', error: `Error fetching data ${error}` });
} else {
res.json({ state: 'ok' });
}
})
} else {
res.json({ error: '别称已存在' });
}
}
})
} else {
res.json({ error: '别称不能为空' });
}
} else {
res.status(403).json({ error: '无权限' });
}
} else {
res.status(403).json({ error: '无权限' });
}
});
// anime 删除动漫别称 需要权限11
app.get('/anime-rm-alias', (req, res) => {
if (req.session.loggedin) {
if (req.session.perm >= 11) {
const animeid = req.query.id;
const uid = req.session.userid;
const alias = decodeURIComponent(req.query.alias);
if (alias) {
const queryA = `DELETE FROM animealias WHERE anime_id = ? AND alias = ?;`;
db.query(queryA, [animeid, alias], (error, results) => {
if (error) {
res.json({ state: 'error', message: `Error fetching data ${error}` });
} else {
res.json({ state: 'ok' });
}
})
} else {
res.json({ error: '别称不能为空' });
}
} else {
res.status(403).json({ error: '无权限' });
}
} else {
res.status(403).json({ error: '无权限' });
}
});
// anime 根据mikan和bgm来更新别称 需要权限9000
app.get('/anime-update-alias', (req, res) => {
const uid = req.session.userid;
function updateAliasByBgmId(bgmid, animeid, res, msg = '') {
axios.get(`https://bgm.tv/subject/${bgmid}`, { httpsAgent: httpProxy }).then(response => {
const $ = cheerio.load(response.data);
const liElements = $("#infobox li");
const aliasList = [];
liElements.each((index, element) => {
const spanContent = $(element).find("span").text();
if (spanContent === "别名: ") {
const listItemContent = $(element).text().replace("别名: ", "").trim();
aliasList.push(listItemContent);
const query = `SELECT id FROM animealias WHERE anime_id = ? AND alias = ?;`;
db.query(query, [animeid, listItemContent], (err, result) => {
if (err) {
res.json({ state: 'error', message: `Error fetching data ${err}` });
} else {
if (result.length == 0) {
const query = `INSERT INTO animealias (alias, anime_id, user_id) VALUES (?, ?, ?);`;
db.query(query, [listItemContent, animeid, uid], (error, results) => {
if (error) {