-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (86 loc) · 2.58 KB
/
index.js
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
const express = require("express");
const AWS = require("aws-sdk");
require("aws-sdk/lib/maintenance_mode_message").suppress = true;
const fs = require("fs");
const path = require("path");
const { DateTime } = require("luxon");
const app = express();
const config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
// 配置S3
AWS.config.update({
accessKeyId: config.s3.accessKeyId,
secretAccessKey: config.s3.secretAccessKey,
region: config.s3.region,
});
const s3 = new AWS.S3({ endpoint: config.s3.endpoint });
// 确保日志文件目录存在
if (!fs.existsSync("logs")) {
fs.mkdirSync("logs");
}
// 添加控制台和文件日志记录
function log(message) {
// 定义日志文件路径
const logFile = path.join(
"logs",
`${DateTime.now().toFormat("yyyy-MM-dd")}.log`
);
console.log(
`${DateTime.now().toFormat("yyyy-MM-dd HH:mm:ss")} - ${message}`
);
fs.appendFileSync(
logFile,
`${DateTime.now().toFormat("yyyy-MM-dd HH:mm:ss")} - ${message}\n`
);
}
// 处理下载文件请求
app.get("*", (req, res) => {
const config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
const filePath = req.url.replace("/", "");
const downloadPath = config.routing[filePath];
if (!downloadPath) {
const statusCode = 404;
log(
"Status Code: " +
statusCode +
", Request URL: " +
req.url +
", Target URL: " +
"Request URL Not Found"
);
return res.status(statusCode).send("File not found");
}
const s3Params = {
Bucket: config.s3.bucket,
Key: downloadPath,
};
s3.getObject(s3Params, (err, data) => {
if (err) {
console.error("Failed to download file:", err);
const statusCode = 500;
log(
"Status Code: " +
statusCode +
", Request URL: " +
req.url +
", Target URL: " +
downloadPath
);
return res.status(statusCode).send("Failed to download file");
}
const statusCode = 200;
log(
"Status Code: " +
statusCode +
", Request URL: " +
req.url +
", Target URL: " +
downloadPath
);
res.attachment(downloadPath);
res.send(data.Body);
});
});
// 启动服务器
app.listen(config.port, () => {
console.log(`Server listening on port ${config.port}`);
});