-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
221 lines (206 loc) · 7.79 KB
/
api.js
File metadata and controls
221 lines (206 loc) · 7.79 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
import COS from 'cos-nodejs-sdk-v5';
// 格式化文件大小
function formatSize(bytes) {
if (bytes >= 1073741824) {
return (bytes / 1073741824).toFixed(2) + ' GB';
} else if (bytes >= 1048576) {
return (bytes / 1048576).toFixed(2) + ' MB';
} else if (bytes >= 1024) {
return (bytes / 1024).toFixed(2) + ' KB';
} else if (bytes > 1) {
return bytes + ' B';
} else if (bytes === 1) {
return '1 B';
} else {
return '0 B';
}
}
// 创建COS API处理函数工厂
export function createCosApiHandler(config) {
// 创建COS客户端实例
const cosClient = new COS({
SecretId: config.cos.secretId,
SecretKey: config.cos.secretKey
});
// 列出对象
async function listObjects(bucket, path) {
return new Promise((resolve, reject) => {
cosClient.getBucket({
Bucket: bucket,
Region: config.cos.region,
Delimiter: '/',
Prefix: path.replace(/^\/+/, '')
}, (err, data) => {
if (err) {
reject(err);
} else {
const objects = [];
const folders = [];
// 处理目录
if (data.CommonPrefixes) {
data.CommonPrefixes.forEach(folder => {
const folderPath = folder.Prefix;
const folderName = folderPath.replace(path, '').replace(/\/$/, '');
folders.push({
name: folderName,
path: folderPath,
type: 'folder',
last_modified: ''
});
});
}
// 处理文件
if (data.Contents) {
data.Contents.forEach(file => {
if (file.Key === path) return;
const fileName = file.Key.replace(path, '');
if (!config.readmeFiles.includes(fileName)) {
objects.push({
name: fileName,
path: file.Key,
type: 'file',
size: formatSize(file.Size),
last_modified: file.LastModified
});
}
});
}
resolve({
path,
parent_path: path.replace(/\/[^\/]*\/?$/, '/'),
folders,
files: objects
});
}
});
});
}
// 获取README内容
async function getReadmeContent(bucket, path, readmeFiles) {
// 获取目录下所有对象
const objects = await new Promise((resolve, reject) => {
cosClient.getBucket({
Bucket: bucket,
Region: config.cos.region,
Delimiter: '/',
Prefix: path.replace(/^\/+/, '')
}, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data.Contents || []);
}
});
});
// 转换为小写的目标文件名列表
const lowerTargetFiles = readmeFiles.map(f => f.toLowerCase());
// 查找不区分大小写匹配的文件
for (const obj of objects) {
const fileName = obj.Key.split('/').pop();
if (lowerTargetFiles.includes(fileName.toLowerCase())) {
try {
const data = await new Promise((resolve, reject) => {
cosClient.getObject({
Bucket: bucket,
Region: config.cos.region,
Key: obj.Key
}, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
return {
exists: true,
content: data.Body.toString(),
file: fileName
};
} catch (e) {
continue;
}
}
}
return { exists: false };
}
// 下载文件
async function downloadFile(bucket, filePath, fileName = null) {
try {
filePath = filePath.replace(/^\/+/, '');
fileName = fileName || filePath.split('/').pop();
// 检查文件是否存在
await new Promise((resolve, reject) => {
cosClient.headObject({
Bucket: bucket,
Region: config.cos.region,
Key: filePath
}, (err, data) => {
if (err) {
reject(new Error("文件不存在或不可访问"));
} else {
resolve(data);
}
});
});
let signedUrl;
if (config.cos.customDomain) {
// 生成签名 URL
signedUrl = cosClient.getObjectUrl({
Bucket: bucket,
Region: config.cos.region,
Key: filePath,
Sign: true,
Expires: 600,
ResponseContentDisposition: `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,
ResponseContentType: 'application/octet-stream'
});
// 替换默认域名
signedUrl = signedUrl.replace(`https://${bucket}.cos.${config.cos.region}.myqcloud.com`, `https://${config.cos.customDomain}`);
} else {
signedUrl = cosClient.getObjectUrl({
Bucket: bucket,
Region: config.cos.region,
Key: filePath,
Sign: true,
Expires: 600,
ResponseContentDisposition: `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`
});
}
return signedUrl;
} catch (e) {
throw new Error(`文件下载失败: ${e.message}`);
}
}
// 处理API请求
return async function handleApiRequest(req, res, next) {
const action = req.query.action || '';
let path = req.query.path || config.defaultPath;
path = path.replace(/\/+$/, '/');
try {
switch (action) {
case 'list':
const result = await listObjects(config.cos.bucket, path);
res.json(result);
break;
case 'readme':
const readmeResult = await getReadmeContent(config.cos.bucket, path, config.readmeFiles);
res.json(readmeResult);
break;
case 'getSignedUrl':
const signedImageUrl = await downloadFile(config.cos.bucket, req.query.path, req.query.name);
res.json({ signedImageUrl });
break;
case 'download':
const signedUrl = await downloadFile(config.cos.bucket, req.query.path, req.query.name);
res.redirect(signedUrl);
break;
default:
res.status(400).json({ error: 'Invalid action' });
}
} catch (e) {
console.error('API error:', e);
res.status(500).json({ error: e.message || 'Internal server error' });
}
};
}