file-handle 0.0.6 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/README.zh-CN.md +2 -2
- package/package.json +3 -2
- package/server/bin/cli.js +14 -5
- package/server/bin/fork.js +25 -22
- package/server/common/adapter.js +7 -6
- package/server/common/i18n.js +13 -7
- package/server/config.js +4 -1
- package/server/fh.app.dat +0 -0
- package/server/index.js +40 -21
- package/server/middlewares/upload.js +159 -8
- package/server/routes/api.js +38 -11
- package/server/routes/fh.js +3 -1
- package/server/routes/res.js +3 -2
- package/server/utils/Preview/Markdown/registrie.js +1 -1
- package/server/utils/Preview/Text/registrie.js +1 -1
- package/server/utils/discover.js +336 -0
package/README.md
CHANGED
package/README.zh-CN.md
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "file-handle",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"author": "jsonhandle@gmail.com",
|
|
5
5
|
"description": "A simple local web file server with a user-friendly interface, allowing easy file upload, download, preview, and management through a browser. \n一个简易的文件服务器,方便通过浏览器来浏览、上传或管理目录和文件. ",
|
|
6
6
|
"main": "server/index.js",
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
"upload",
|
|
13
13
|
"download",
|
|
14
14
|
"preview",
|
|
15
|
-
"
|
|
15
|
+
"transfer",
|
|
16
|
+
"share",
|
|
16
17
|
"serve",
|
|
17
18
|
"web-server",
|
|
18
19
|
"http-server"
|
package/server/bin/cli.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
2
5
|
import yargs from 'yargs';
|
|
3
6
|
import { hideBin } from 'yargs/helpers';
|
|
4
|
-
import
|
|
5
|
-
import { startServer } from "../index.js";
|
|
7
|
+
import { start } from './fork.js';
|
|
6
8
|
import { getText } from '../common/i18n.js';
|
|
7
|
-
import packageData from '../../package.json' with { type: "json" };
|
|
8
9
|
import { parseFileSize } from '../config.js';
|
|
9
10
|
const cmdConfig = loadCmdArgs(process.argv);
|
|
10
|
-
|
|
11
|
+
start(cmdConfig);
|
|
11
12
|
// 加载命令行参数
|
|
12
13
|
function loadCmdArgs(args) {
|
|
13
14
|
const lang = getText();
|
|
@@ -41,6 +42,11 @@ function loadCmdArgs(args) {
|
|
|
41
42
|
type: 'array',
|
|
42
43
|
description: lang.config.tlsDesc
|
|
43
44
|
},
|
|
45
|
+
't': {
|
|
46
|
+
alias: 'time',
|
|
47
|
+
type: 'number',
|
|
48
|
+
description: lang.config.timeDesc
|
|
49
|
+
},
|
|
44
50
|
'del': {
|
|
45
51
|
type: 'boolean',
|
|
46
52
|
description: lang.config.delDesc,
|
|
@@ -79,6 +85,8 @@ function loadCmdArgs(args) {
|
|
|
79
85
|
.help()
|
|
80
86
|
.argv;
|
|
81
87
|
if ('V' in argv || 'v' in argv) {
|
|
88
|
+
const mdDir = path.dirname(fileURLToPath(import.meta.url));
|
|
89
|
+
const packageData = JSON.parse(fs.readFileSync(path.join(mdDir, '../../package.json')).toString());
|
|
82
90
|
console.log(`v${packageData.version}`);
|
|
83
91
|
process.exit(0);
|
|
84
92
|
}
|
|
@@ -88,6 +96,7 @@ function loadCmdArgs(args) {
|
|
|
88
96
|
version: argv.version,
|
|
89
97
|
allowDelete: argv.del,
|
|
90
98
|
allowEdit: argv.edit,
|
|
99
|
+
time: argv.time,
|
|
91
100
|
writeLog: argv.log ? true : undefined,
|
|
92
101
|
password: argv.password,
|
|
93
102
|
uploadLimit: parseFileSize(argv.limit),
|
package/server/bin/fork.js
CHANGED
|
@@ -1,27 +1,30 @@
|
|
|
1
|
-
import { startServer } from
|
|
1
|
+
import { startServer } from '../index.js';
|
|
2
|
+
import { fork } from 'child_process';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { loadConfig } from '../config.js';
|
|
2
5
|
import Debug from 'debug';
|
|
3
6
|
const debug = Debug('FH fork');
|
|
7
|
+
const isDevelopment = process.env.NODE_ENV?.trim() === 'development';
|
|
4
8
|
process.on('message', (msg) => {
|
|
5
|
-
|
|
6
|
-
if (msg && msg.cmd) {
|
|
7
|
-
switch (msg.cmd) {
|
|
8
|
-
case 'startServer':
|
|
9
|
-
startServer(msg.data).then(config => {
|
|
10
|
-
if (process.send) {
|
|
11
|
-
process.send({ cmd: 'started', data: config });
|
|
12
|
-
}
|
|
13
|
-
}).catch(err => {
|
|
14
|
-
if (process.send) {
|
|
15
|
-
process.send({ cmd: 'error', data: err.message });
|
|
16
|
-
}
|
|
17
|
-
});
|
|
18
|
-
break;
|
|
19
|
-
default:
|
|
20
|
-
break;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
9
|
+
startServer(JSON.parse(msg.opt));
|
|
23
10
|
});
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
11
|
+
export function start(config) {
|
|
12
|
+
const env = loadConfig({ rootDir: process.cwd() });
|
|
13
|
+
debug('isDevelopment:', env.isDevelopment);
|
|
14
|
+
if (env.isDevelopment) {
|
|
15
|
+
startServer(config);
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
const forkEnter = path.join(env.mdDir, './bin/fork.js');
|
|
19
|
+
const child = fork(forkEnter, [], {
|
|
20
|
+
execArgv: ['--title=File-Handle-Server']
|
|
21
|
+
});
|
|
22
|
+
child.on('message', (msg) => {
|
|
23
|
+
debug('child:', msg);
|
|
24
|
+
});
|
|
25
|
+
child.send({ opt: JSON.stringify(config) });
|
|
26
|
+
child.on('exit', (code) => {
|
|
27
|
+
debug(`FH exited with code ${code}`);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
27
30
|
}
|
package/server/common/adapter.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createProxyMiddleware } from 'http-proxy-middleware';
|
|
2
2
|
import { resolve } from 'path';
|
|
3
|
-
import
|
|
3
|
+
import Debug from 'debug';
|
|
4
4
|
import mime from 'mime-types';
|
|
5
5
|
import unzip from 'unzipper';
|
|
6
|
-
const
|
|
6
|
+
const debug = Debug('FH adapter');
|
|
7
7
|
let resMap;
|
|
8
8
|
export function buildPreviewerHtml(html) {
|
|
9
9
|
const modifiedBody = html.replace('<base id="baseUrl" />', `<base id="baseUrl" href="/fh/" />`);
|
|
@@ -13,8 +13,9 @@ export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
|
13
13
|
const config = global.config;
|
|
14
14
|
// 获取node入口目录的绝对路径
|
|
15
15
|
const fhDir = config.mdDir;
|
|
16
|
+
debug('isDevelopment:', config.isDevelopment);
|
|
16
17
|
debug('sendFeReq uri: ' + uri + ' | path: ' + req.path);
|
|
17
|
-
if (!isDevelopment && !resMap) {
|
|
18
|
+
if (!config.isDevelopment && !resMap) {
|
|
18
19
|
resMap = await getRes(resolve(fhDir, './fh.app.dat'));
|
|
19
20
|
}
|
|
20
21
|
const bCb = !!sendBefore;
|
|
@@ -25,12 +26,12 @@ export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
|
25
26
|
changeOrigin: true,
|
|
26
27
|
ws: true,
|
|
27
28
|
pathRewrite: {
|
|
28
|
-
'^.*': '/res' + req.url
|
|
29
|
+
'^.*': '/___file-handle___/res' + req.url
|
|
29
30
|
}
|
|
30
31
|
};
|
|
31
32
|
if ({}.toString.call(uri) == '[object String]') {
|
|
32
33
|
opt.pathRewrite = {
|
|
33
|
-
'^.*': '/res/' + uri
|
|
34
|
+
'^.*': '/___file-handle___/res/' + uri
|
|
34
35
|
};
|
|
35
36
|
resFilePath = uri;
|
|
36
37
|
}
|
|
@@ -61,7 +62,7 @@ export async function sendFeReq(uri, req, res, next, sendBefore) {
|
|
|
61
62
|
}
|
|
62
63
|
};
|
|
63
64
|
}
|
|
64
|
-
if (isDevelopment) {
|
|
65
|
+
if (config.isDevelopment) {
|
|
65
66
|
createProxyMiddleware(opt)(req, res, next);
|
|
66
67
|
}
|
|
67
68
|
else {
|
package/server/common/i18n.js
CHANGED
|
@@ -7,15 +7,17 @@ const i18n = {
|
|
|
7
7
|
switchLang: 'Switch to English'
|
|
8
8
|
},
|
|
9
9
|
server: {
|
|
10
|
-
startingHttps: '正在启动HTTPS服务器...',
|
|
11
|
-
startingHttp: '正在启动HTTP服务器...',
|
|
10
|
+
startingHttps: '正在启动 FH HTTPS 服务器...',
|
|
11
|
+
startingHttp: '正在启动 FH HTTP 服务器...',
|
|
12
12
|
running: 'File-Handle Server正在运行,端口:',
|
|
13
13
|
rootDirectory: '根目录:',
|
|
14
14
|
accessibleAddresses: '可访问的地址:',
|
|
15
15
|
allowedIpsOnly: '仅允许指定IP访问',
|
|
16
16
|
localAndLanOnly: '仅允许本地和局域网访问',
|
|
17
17
|
loginPassword: '登录密码是:',
|
|
18
|
-
portInUse: '端口 {port} 正在使用中, 正在尝试下一个端口。'
|
|
18
|
+
portInUse: '端口 {port} 正在使用中, 正在尝试下一个端口。',
|
|
19
|
+
exitAfterTime: '服务器将在 {time} 秒后退出',
|
|
20
|
+
exitOutTime: '服务器到时退出'
|
|
19
21
|
},
|
|
20
22
|
config: {
|
|
21
23
|
allowWanDesc: '允许公网访问',
|
|
@@ -23,6 +25,7 @@ const i18n = {
|
|
|
23
25
|
portDesc: '指定服务器监听的端口号',
|
|
24
26
|
ipDesc: '指定服务器允许访问的IP地址,多个IP地址用逗号分隔',
|
|
25
27
|
tlsDesc: '启用HTTPS安全传输,需提供证书和密钥文件路径',
|
|
28
|
+
timeDesc: '启动多少秒后退出',
|
|
26
29
|
delDesc: '启用文件删除功能',
|
|
27
30
|
passwordDesc: '设置服务器访问的密码',
|
|
28
31
|
editDesc: '启用文件编辑修改功能',
|
|
@@ -39,15 +42,17 @@ const i18n = {
|
|
|
39
42
|
switchLang: '切换到中文'
|
|
40
43
|
},
|
|
41
44
|
server: {
|
|
42
|
-
startingHttps: 'Starting HTTPS server...',
|
|
43
|
-
startingHttp: 'Starting HTTP server...',
|
|
44
|
-
running: 'File-Handle Server is running on port',
|
|
45
|
+
startingHttps: 'Starting FH HTTPS server...',
|
|
46
|
+
startingHttp: 'Starting FH HTTP server...',
|
|
47
|
+
running: 'File-Handle Server is running on port: ',
|
|
45
48
|
rootDirectory: 'Root directory:',
|
|
46
49
|
accessibleAddresses: 'Accessible addresses:',
|
|
47
50
|
allowedIpsOnly: 'Only allowed IPs can access',
|
|
48
51
|
localAndLanOnly: 'Only local and LAN access allowed',
|
|
49
52
|
loginPassword: 'Login password is:',
|
|
50
|
-
portInUse: 'Port {port} is being used, trying next port...'
|
|
53
|
+
portInUse: 'Port {port} is being used, trying next port...',
|
|
54
|
+
exitAfterTime: 'Server will exit after {time} seconds',
|
|
55
|
+
exitOutTime: 'The server has expired and exited'
|
|
51
56
|
},
|
|
52
57
|
config: {
|
|
53
58
|
allowWanDesc: 'Allow public network access',
|
|
@@ -55,6 +60,7 @@ const i18n = {
|
|
|
55
60
|
portDesc: 'Specify server listening port',
|
|
56
61
|
ipDesc: 'Specify allowed IP addresses, separated by commas',
|
|
57
62
|
tlsDesc: 'Enable HTTPS secure transmission, requires certificate and key file paths',
|
|
63
|
+
timeDesc: 'How many seconds does it exit',
|
|
58
64
|
delDesc: 'Enable file deletion',
|
|
59
65
|
passwordDesc: 'Set server access password',
|
|
60
66
|
editDesc: 'Enable file editing',
|
package/server/config.js
CHANGED
|
@@ -28,6 +28,8 @@ global.config = global.config || {
|
|
|
28
28
|
writeLog: false,
|
|
29
29
|
uploadLimit: parseFileSize('3GB'),
|
|
30
30
|
allowWan: false,
|
|
31
|
+
isDevelopment: false,
|
|
32
|
+
ipList: ['127.0.0.1']
|
|
31
33
|
};
|
|
32
34
|
export function loadConfig(opt) {
|
|
33
35
|
if (!fs.existsSync(opt.rootDir)) {
|
|
@@ -41,8 +43,9 @@ export function loadConfig(opt) {
|
|
|
41
43
|
if (opt.password === '') {
|
|
42
44
|
opt.password = createRandomPassword(16);
|
|
43
45
|
}
|
|
46
|
+
opt.isDevelopment = opt.isDevelopment || process.env.NODE_ENV?.trim() === 'development';
|
|
44
47
|
global.config = opt;
|
|
45
|
-
createAppKey(global.config);
|
|
48
|
+
// createAppKey(global.config);
|
|
46
49
|
return opt;
|
|
47
50
|
}
|
|
48
51
|
export function getAppKeyPath() {
|
package/server/fh.app.dat
CHANGED
|
Binary file
|
package/server/index.js
CHANGED
|
@@ -34,18 +34,15 @@ export async function startServer(opt) {
|
|
|
34
34
|
next();
|
|
35
35
|
});
|
|
36
36
|
// app.use(corsMiddleware);
|
|
37
|
-
app.use('/app', createAppRouter(config));
|
|
38
37
|
app.use(validateIpAccess(config));
|
|
39
38
|
app.use(validatePassword(config));
|
|
40
39
|
app.use(validateFileOperation(config));
|
|
41
|
-
// 根路径重定向到文件系统
|
|
42
|
-
app.get('/', (req, res) => {
|
|
43
|
-
res.redirect('/fh/');
|
|
44
|
-
});
|
|
45
40
|
// 配置路由
|
|
46
|
-
app.use('/
|
|
47
|
-
app.use('/api', createApiRouter(config));
|
|
41
|
+
app.use('/___file-handle___/app', createAppRouter(config));
|
|
42
|
+
app.use('/___file-handle___/api', createApiRouter(config));
|
|
48
43
|
createResourcesRouter(app, config);
|
|
44
|
+
// 根到文件系统
|
|
45
|
+
app.get(/^\/(?!___file-handle___)/, createFileSystemRouter(config));
|
|
49
46
|
// 错误处理
|
|
50
47
|
app.use(handleUploadError);
|
|
51
48
|
app.use(errorHandler);
|
|
@@ -63,21 +60,25 @@ export async function startServer(opt) {
|
|
|
63
60
|
server = http.createServer(app);
|
|
64
61
|
info(lang.server.startingHttp);
|
|
65
62
|
}
|
|
63
|
+
// 大文件上传可能耗时较长,关闭服务器端的请求/连接超时,
|
|
64
|
+
// 避免上传过程中被 Node 默认超时(requestTimeout 默认 5 分钟)截断
|
|
65
|
+
server.timeout = 0; // 关闭 socket 空闲超时(默认即 0,显式声明)
|
|
66
|
+
server.requestTimeout = 0; // 关闭整体请求超时(默认 5 分钟,大文件会被截断)
|
|
66
67
|
const port = await findAvailablePort(config.port);
|
|
67
68
|
const localIPs = getLocalNetworkIPs();
|
|
68
69
|
global.config.port = port;
|
|
69
|
-
global.config = Object.freeze(global.config);
|
|
70
70
|
return new Promise((resolve, reject) => {
|
|
71
71
|
if (config.allowedIPs) {
|
|
72
72
|
// 如果指定了允许访问的IP地址,则只允许这些IP访问
|
|
73
73
|
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
74
74
|
info(lang.server.allowedIpsOnly);
|
|
75
|
-
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
76
|
-
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
75
|
+
info(`${lang.server.running} ${color.blueBright(port)}`);
|
|
76
|
+
info(`${lang.server.rootDirectory} ${color.yellow(config.rootDir)}`);
|
|
77
77
|
info(lang.server.accessibleAddresses);
|
|
78
|
-
info(color.green(`http://127.0.0.1:${port}
|
|
78
|
+
info(color.green(`http://127.0.0.1:${port}/`));
|
|
79
79
|
config.allowedIPs && config.allowedIPs.forEach(ip => {
|
|
80
|
-
info(color.green(`http://${ip}:${port}
|
|
80
|
+
info(color.green(`http://${ip}:${port}/`));
|
|
81
|
+
config.ipList?.push(ip);
|
|
81
82
|
});
|
|
82
83
|
info('\n\n');
|
|
83
84
|
});
|
|
@@ -86,12 +87,13 @@ export async function startServer(opt) {
|
|
|
86
87
|
// 如果存在局域网IP且未启用公网访问,则只监听局域网IP
|
|
87
88
|
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
88
89
|
info(lang.server.localAndLanOnly);
|
|
89
|
-
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
90
|
-
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
90
|
+
info(`${lang.server.running} ${color.blueBright(port)}`);
|
|
91
|
+
info(`${lang.server.rootDirectory} ${color.yellow(config.rootDir)}`);
|
|
91
92
|
info(lang.server.accessibleAddresses);
|
|
92
|
-
info(color.green(`http://127.0.0.1:${port}
|
|
93
|
+
info(color.green(`http://127.0.0.1:${port}/`));
|
|
93
94
|
localIPs.forEach(ip => {
|
|
94
|
-
info(color.green(`http://${ip}:${port}
|
|
95
|
+
info(color.green(`http://${ip}:${port}/`));
|
|
96
|
+
config.ipList?.push(ip);
|
|
95
97
|
});
|
|
96
98
|
info('\n\n');
|
|
97
99
|
});
|
|
@@ -99,16 +101,33 @@ export async function startServer(opt) {
|
|
|
99
101
|
else {
|
|
100
102
|
// 允许所有IP访问
|
|
101
103
|
server.once('listening', () => resolve(global.config)).listen(port, '0.0.0.0', () => {
|
|
102
|
-
info(`${lang.server.running}${color.blueBright(port)}`);
|
|
103
|
-
info(`${lang.server.rootDirectory}${color.yellow(config.rootDir)}`);
|
|
104
|
+
info(`${lang.server.running} ${color.blueBright(port)}`);
|
|
105
|
+
info(`${lang.server.rootDirectory} ${color.yellow(config.rootDir)}`);
|
|
104
106
|
info(lang.server.accessibleAddresses);
|
|
105
|
-
info(`http://0.0.0.0:${port}
|
|
106
|
-
info(color.green(`http://127.0.0.1:${port}
|
|
107
|
+
info(`http://0.0.0.0:${port}/`);
|
|
108
|
+
info(color.green(`http://127.0.0.1:${port}/`));
|
|
109
|
+
localIPs.forEach(ip => {
|
|
110
|
+
config.ipList?.push(ip);
|
|
111
|
+
});
|
|
107
112
|
info(`\n\n`);
|
|
108
113
|
});
|
|
109
114
|
}
|
|
110
115
|
if (config.password) {
|
|
111
|
-
info(`${lang.server.loginPassword}${color.green(config.password)}`);
|
|
116
|
+
info(`${lang.server.loginPassword} ${color.green(config.password)}`);
|
|
117
|
+
}
|
|
118
|
+
}).then(_ => {
|
|
119
|
+
// 对ipList进行去重
|
|
120
|
+
if (global.config.ipList) {
|
|
121
|
+
global.config.ipList = [...new Set(global.config.ipList)];
|
|
122
|
+
}
|
|
123
|
+
global.config = Object.freeze(global.config);
|
|
124
|
+
if (config.time) {
|
|
125
|
+
// @ts-ignore
|
|
126
|
+
info(lang.server.exitAfterTime.replace('{time}', color.red(config.time.toString())));
|
|
127
|
+
setTimeout(() => {
|
|
128
|
+
info(lang.server.exitOutTime);
|
|
129
|
+
process.exit(0);
|
|
130
|
+
}, config.time * 1000);
|
|
112
131
|
}
|
|
113
132
|
});
|
|
114
133
|
}
|
|
@@ -1,15 +1,145 @@
|
|
|
1
1
|
import multer from 'multer';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
import
|
|
3
|
+
import fs from 'fs/promises';
|
|
4
|
+
import { validateFileName, normalizePath } from '../utils/path.js';
|
|
4
5
|
import { FileOperationError } from '../types/index.js';
|
|
5
6
|
import { debug, error } from '../utils/logger.js';
|
|
7
|
+
// 内存中的上传会话表(uploadId -> session)
|
|
8
|
+
const uploadSessions = new Map();
|
|
9
|
+
export function getUploadSession(uploadId) {
|
|
10
|
+
return uploadSessions.get(uploadId);
|
|
11
|
+
}
|
|
12
|
+
// 解析客户端通过 header 传入的预期文件大小清单(x-upload-meta)
|
|
13
|
+
// 格式:encodeURIComponent(JSON.stringify([{ name, size }, ...]))
|
|
14
|
+
function parseExpectedMeta(req) {
|
|
15
|
+
const header = req.headers['x-upload-meta'];
|
|
16
|
+
if (!header)
|
|
17
|
+
return new Map();
|
|
18
|
+
try {
|
|
19
|
+
const json = JSON.parse(decodeURIComponent(header));
|
|
20
|
+
const map = new Map();
|
|
21
|
+
if (Array.isArray(json)) {
|
|
22
|
+
for (const item of json) {
|
|
23
|
+
if (item && item.name !== undefined && typeof item.size === 'number') {
|
|
24
|
+
map.set(item.name, item.size);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return map;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return new Map();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// 跟踪上传进度的中间件:统计已接收字节,写入会话表供状态接口查询
|
|
35
|
+
// 仅作用于上传路由,需在 multer 之前挂载
|
|
36
|
+
export function trackUpload(req, res, next) {
|
|
37
|
+
const uploadId = req.headers['x-upload-id'] || '';
|
|
38
|
+
if (uploadId) {
|
|
39
|
+
const total = Number(req.headers['content-length'] || 0) || 0;
|
|
40
|
+
const filenameHeader = req.headers['x-upload-filename'];
|
|
41
|
+
const filename = filenameHeader ? decodeURIComponent(filenameHeader) : '';
|
|
42
|
+
const session = {
|
|
43
|
+
uploadId,
|
|
44
|
+
filename,
|
|
45
|
+
received: 0,
|
|
46
|
+
total,
|
|
47
|
+
done: false,
|
|
48
|
+
error: null,
|
|
49
|
+
startedAt: Date.now(),
|
|
50
|
+
};
|
|
51
|
+
uploadSessions.set(uploadId, session);
|
|
52
|
+
// 统计流入字节('data' 监听不会阻止 busboy/multer 消费流)
|
|
53
|
+
req.on('data', (chunk) => {
|
|
54
|
+
session.received += chunk.length;
|
|
55
|
+
});
|
|
56
|
+
// 请求异常中断
|
|
57
|
+
req.on('aborted', () => {
|
|
58
|
+
if (!session.error)
|
|
59
|
+
session.error = 'aborted';
|
|
60
|
+
});
|
|
61
|
+
req.on('error', (err) => {
|
|
62
|
+
if (!session.error)
|
|
63
|
+
session.error = err.message || 'request error';
|
|
64
|
+
});
|
|
65
|
+
// 响应关闭(成功/失败/中断均触发):标记完成,延时清理会话
|
|
66
|
+
res.on('close', () => {
|
|
67
|
+
session.done = true;
|
|
68
|
+
if (!session.error && req.aborted) {
|
|
69
|
+
session.error = 'aborted';
|
|
70
|
+
}
|
|
71
|
+
setTimeout(() => {
|
|
72
|
+
uploadSessions.delete(uploadId);
|
|
73
|
+
}, 60000);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
next();
|
|
77
|
+
}
|
|
78
|
+
// 校验并清理不完整的上传文件
|
|
79
|
+
// 比对每个已开始写入的文件实际大小与客户端声明的预期大小;
|
|
80
|
+
// 不一致或缺失则删除残留,返回完整文件列表与被清理的文件名
|
|
81
|
+
export async function verifyAndCleanupUploads(req) {
|
|
82
|
+
const expected = parseExpectedMeta(req);
|
|
83
|
+
const started = req._uploadStarted || [];
|
|
84
|
+
const files = [];
|
|
85
|
+
const incomplete = [];
|
|
86
|
+
for (const f of started) {
|
|
87
|
+
let size = -1;
|
|
88
|
+
try {
|
|
89
|
+
const stat = await fs.stat(f.path);
|
|
90
|
+
size = stat.size;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
size = -1;
|
|
94
|
+
}
|
|
95
|
+
const expectedSize = expected.get(f.originalName);
|
|
96
|
+
if (expectedSize !== undefined && size !== expectedSize) {
|
|
97
|
+
// 大小不符:上传不完整,删除残留
|
|
98
|
+
try {
|
|
99
|
+
await fs.unlink(f.path);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// 删除失败忽略(文件可能已不存在)
|
|
103
|
+
}
|
|
104
|
+
incomplete.push(f.originalName);
|
|
105
|
+
}
|
|
106
|
+
else if (size < 0) {
|
|
107
|
+
// 文件不存在:记为不完整
|
|
108
|
+
incomplete.push(f.originalName);
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
files.push({ originalName: f.originalName, savedPath: f.path, size });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { files, incomplete };
|
|
115
|
+
}
|
|
6
116
|
// 创建文件上传配置
|
|
7
117
|
export function createUploadMiddleware(config) {
|
|
8
118
|
const storage = multer.diskStorage({
|
|
9
119
|
destination: (req, file, cb) => {
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
120
|
+
// 优先使用客户端显式传入的目标目录(?path=)
|
|
121
|
+
let uploadPath = req.query.path || '';
|
|
122
|
+
// 兼容未显式传 path 的调用:从 referer 中提取路径名,避免把完整 URL 当目录
|
|
123
|
+
if (!uploadPath) {
|
|
124
|
+
const referer = req.headers.referer;
|
|
125
|
+
if (referer) {
|
|
126
|
+
try {
|
|
127
|
+
uploadPath = decodeURIComponent(new URL(referer).pathname);
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
uploadPath = referer;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// 规范化并校验路径必须位于根目录内(防止路径穿越)
|
|
135
|
+
let targetDir;
|
|
136
|
+
try {
|
|
137
|
+
targetDir = normalizePath(uploadPath || '/', config.rootDir);
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
return cb(err, '');
|
|
141
|
+
}
|
|
142
|
+
req._uploadDir = targetDir;
|
|
13
143
|
cb(null, targetDir);
|
|
14
144
|
},
|
|
15
145
|
filename: (req, file, cb) => {
|
|
@@ -21,6 +151,13 @@ export function createUploadMiddleware(config) {
|
|
|
21
151
|
// 如果文件已存在,添加时间戳
|
|
22
152
|
const filename = decodedName;
|
|
23
153
|
debug(`Processing upload: ${filename}`);
|
|
154
|
+
// 记录已开始写入的文件路径,便于中断后校验与清理残留
|
|
155
|
+
const dir = req._uploadDir;
|
|
156
|
+
if (dir) {
|
|
157
|
+
if (!req._uploadStarted)
|
|
158
|
+
req._uploadStarted = [];
|
|
159
|
+
req._uploadStarted.push({ originalName: decodedName, path: path.join(dir, filename) });
|
|
160
|
+
}
|
|
24
161
|
cb(null, filename);
|
|
25
162
|
}
|
|
26
163
|
});
|
|
@@ -43,15 +180,29 @@ export function createUploadMiddleware(config) {
|
|
|
43
180
|
}
|
|
44
181
|
});
|
|
45
182
|
}
|
|
46
|
-
//
|
|
47
|
-
|
|
183
|
+
// 错误处理中间件(含上传中断/超限等)
|
|
184
|
+
// 任何上传错误都先清理不完整的残留文件,再返回错误响应
|
|
185
|
+
export async function handleUploadError(err, req, res, next) {
|
|
186
|
+
// 清理不完整上传残留(对非上传请求为空操作)
|
|
187
|
+
try {
|
|
188
|
+
await verifyAndCleanupUploads(req);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// 清理失败不应影响错误响应
|
|
192
|
+
}
|
|
48
193
|
if (err instanceof multer.MulterError) {
|
|
49
194
|
if (err.code === 'LIMIT_FILE_SIZE') {
|
|
50
195
|
return res.status(413).json({
|
|
51
|
-
|
|
52
|
-
|
|
196
|
+
code: -413,
|
|
197
|
+
msg: 'File too large',
|
|
198
|
+
data: null
|
|
53
199
|
});
|
|
54
200
|
}
|
|
201
|
+
return res.status(400).json({
|
|
202
|
+
code: -400,
|
|
203
|
+
msg: err.message,
|
|
204
|
+
data: null
|
|
205
|
+
});
|
|
55
206
|
}
|
|
56
207
|
next(err);
|
|
57
208
|
}
|
package/server/routes/api.js
CHANGED
|
@@ -4,22 +4,49 @@ import path from 'path';
|
|
|
4
4
|
import { ApiResponseBuilder } from '../types/response.js';
|
|
5
5
|
import { normalizePath, validateFileName } from '../utils/path.js';
|
|
6
6
|
import { isEditorAble, isPreviewAble, getMime, extname } from '../types/index.js';
|
|
7
|
-
import { createUploadMiddleware } from '../middlewares/upload.js';
|
|
8
|
-
import { info } from '../utils/logger.js';
|
|
7
|
+
import { createUploadMiddleware, trackUpload, verifyAndCleanupUploads, getUploadSession } from '../middlewares/upload.js';
|
|
8
|
+
import { info, warn } from '../utils/logger.js';
|
|
9
9
|
export function createApiRouter(config) {
|
|
10
10
|
const router = Router();
|
|
11
11
|
const upload = createUploadMiddleware(config);
|
|
12
12
|
// 配置文件上传路由
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
// trackUpload 在 multer 之前挂载,统计已接收字节供 /upload/status 查询
|
|
14
|
+
router.post('/upload', trackUpload, upload.array('files'), async (req, res, next) => {
|
|
15
|
+
try {
|
|
16
|
+
// 上传完成后校验文件完整性,删除不完整残留
|
|
17
|
+
const { files, incomplete } = await verifyAndCleanupUploads(req);
|
|
18
|
+
if (incomplete.length > 0) {
|
|
19
|
+
warn(`Incomplete upload removed: ${incomplete.join(', ')}`);
|
|
20
|
+
return res.json({
|
|
21
|
+
code: -1,
|
|
22
|
+
msg: `Incomplete upload: ${incomplete.join(', ')}`,
|
|
23
|
+
data: { files, incomplete }
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
res.json(ApiResponseBuilder.success({
|
|
27
|
+
files
|
|
28
|
+
}, 'Files uploaded successfully'));
|
|
29
|
+
info(`Uploaded: ${files.length} files`);
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
next(err);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
// 查询某次上传的实时进度
|
|
36
|
+
router.get('/upload/status', (req, res) => {
|
|
37
|
+
const uploadId = req.query.uploadId || '';
|
|
38
|
+
const session = uploadId ? getUploadSession(uploadId) : undefined;
|
|
39
|
+
if (!session) {
|
|
40
|
+
return res.json(ApiResponseBuilder.success(null));
|
|
41
|
+
}
|
|
19
42
|
res.json(ApiResponseBuilder.success({
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
43
|
+
uploadId: session.uploadId,
|
|
44
|
+
filename: session.filename,
|
|
45
|
+
received: session.received,
|
|
46
|
+
total: session.total,
|
|
47
|
+
done: session.done,
|
|
48
|
+
error: session.error
|
|
49
|
+
}));
|
|
23
50
|
});
|
|
24
51
|
router.post('/create', async (req, res, next) => {
|
|
25
52
|
try {
|
package/server/routes/fh.js
CHANGED
|
@@ -3,7 +3,7 @@ import { getMime } from '../types/index.js';
|
|
|
3
3
|
import { normalizePath } from '../utils/path.js';
|
|
4
4
|
import { sendFeReq } from "../common/adapter.js";
|
|
5
5
|
import fs from 'fs/promises';
|
|
6
|
-
import { info } from '../utils/logger.js';
|
|
6
|
+
import { debug, info } from '../utils/logger.js';
|
|
7
7
|
import path from 'path';
|
|
8
8
|
import archiver from 'archiver';
|
|
9
9
|
export function createFileSystemRouter(config) {
|
|
@@ -13,6 +13,7 @@ export function createFileSystemRouter(config) {
|
|
|
13
13
|
sendFeReq('index.html', req, res, next);
|
|
14
14
|
};
|
|
15
15
|
router.get('/*', async (req, res, next) => {
|
|
16
|
+
debug('router:/ ');
|
|
16
17
|
try {
|
|
17
18
|
const downloadFlag = req.query.download === 'true';
|
|
18
19
|
const viewFlag = req.query.view;
|
|
@@ -20,6 +21,7 @@ export function createFileSystemRouter(config) {
|
|
|
20
21
|
const requestPath = req.params[0]?.replace(/^fh\//, '') || '';
|
|
21
22
|
const fullPath = normalizePath(requestPath, config.rootDir);
|
|
22
23
|
const stats = await fs.stat(fullPath);
|
|
24
|
+
debug('fullPath: ' + fullPath);
|
|
23
25
|
if (stats.isDirectory()) {
|
|
24
26
|
if (downloadFlag) {
|
|
25
27
|
// 创建zip压缩包
|
package/server/routes/res.js
CHANGED
|
@@ -3,9 +3,10 @@ import { buildPreviewerHtml, sendFeReq } from "../common/adapter.js";
|
|
|
3
3
|
export function createResourcesRouter(app, config) {
|
|
4
4
|
const routerRes = Router();
|
|
5
5
|
routerRes.get('/*', (req, res, next) => {
|
|
6
|
+
debugger;
|
|
6
7
|
sendFeReq(null, req, res, next);
|
|
7
8
|
});
|
|
8
|
-
app.use('/res', routerRes);
|
|
9
|
+
app.use('/___file-handle___/res', routerRes);
|
|
9
10
|
const routerPreview = Router();
|
|
10
11
|
routerPreview.get('/*', (req, res, next) => {
|
|
11
12
|
sendFeReq({
|
|
@@ -14,5 +15,5 @@ export function createResourcesRouter(app, config) {
|
|
|
14
15
|
return buildPreviewerHtml(content);
|
|
15
16
|
});
|
|
16
17
|
});
|
|
17
|
-
app.use('/previewer', routerRes);
|
|
18
|
+
app.use('/___file-handle___/previewer', routerRes);
|
|
18
19
|
}
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import exhaust from 'exhaust';
|
|
2
|
+
// 36进制字符集
|
|
3
|
+
const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
4
|
+
const oIndexs = {
|
|
5
|
+
1: () => {
|
|
6
|
+
// 18, 2, 1
|
|
7
|
+
const r = oIndexs.build([buildArrFrom(0, 17), [0, 1], [6688]]);
|
|
8
|
+
oIndexs[1] = () => r;
|
|
9
|
+
return r;
|
|
10
|
+
},
|
|
11
|
+
2: (p) => {
|
|
12
|
+
// 7, 3, 1
|
|
13
|
+
// 25, 5, 2
|
|
14
|
+
const r = oIndexs.build([buildArrFrom(18, 24), [2, 3, 4], [6689]], p);
|
|
15
|
+
oIndexs[2] = () => r;
|
|
16
|
+
return r;
|
|
17
|
+
},
|
|
18
|
+
3: (p) => {
|
|
19
|
+
// 13, 4, 1
|
|
20
|
+
// 48, 9, 3
|
|
21
|
+
const r = oIndexs.build([buildArrFrom(25, 47), buildArrFrom(5, 8), [6690]], p);
|
|
22
|
+
oIndexs[3] = () => r;
|
|
23
|
+
return r;
|
|
24
|
+
},
|
|
25
|
+
4: (p) => {
|
|
26
|
+
// 13, 36, 1
|
|
27
|
+
// 255, 45, 4
|
|
28
|
+
const r = oIndexs.build([buildArrFrom(48, 255), buildArrFrom(9, 24).concat([30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 253, 254]), [6691]], p);
|
|
29
|
+
oIndexs[4] = () => r;
|
|
30
|
+
return r;
|
|
31
|
+
},
|
|
32
|
+
5: () => {
|
|
33
|
+
},
|
|
34
|
+
build: (rangs, p) => {
|
|
35
|
+
let oIndex = {};
|
|
36
|
+
let i = 0;
|
|
37
|
+
if (p) {
|
|
38
|
+
i = p.oIndex.lastIndex + 1;
|
|
39
|
+
oIndex = Object.create(p.oIndex);
|
|
40
|
+
}
|
|
41
|
+
exhaust((may) => `${may(rangs[0])},${may(rangs[1])},${may(rangs[2])}`).forEach((s) => {
|
|
42
|
+
oIndex[s] = i++;
|
|
43
|
+
});
|
|
44
|
+
let mergeRangs = rangs;
|
|
45
|
+
if (p) {
|
|
46
|
+
let [a1, a2, a3] = p.rangs;
|
|
47
|
+
const [b1, b2, b3] = rangs;
|
|
48
|
+
mergeRangs = [a1.concat(b1), a2.concat(b2), a3.concat(b3)];
|
|
49
|
+
exhaust((may) => `${may(mergeRangs[0])},${may(mergeRangs[1])},${may(mergeRangs[2])}`).forEach((s) => {
|
|
50
|
+
if (!(s in oIndex)) {
|
|
51
|
+
oIndex[s] = i++;
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
oIndex.lastIndex = i - 1;
|
|
56
|
+
const r = {
|
|
57
|
+
rangs: mergeRangs,
|
|
58
|
+
oIndex,
|
|
59
|
+
check: (a, b, c) => {
|
|
60
|
+
return mergeRangs[0].includes(a) && mergeRangs[1].includes(b) && mergeRangs[2].includes(c);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
return r;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
function buideIndex(lv) {
|
|
67
|
+
let oIndex = oIndexs[1]();
|
|
68
|
+
for (let i = 2; i <= lv; i++) {
|
|
69
|
+
oIndex = oIndexs[i](oIndex);
|
|
70
|
+
}
|
|
71
|
+
return oIndex;
|
|
72
|
+
}
|
|
73
|
+
function encode(a, b, c) {
|
|
74
|
+
// 检查输入范围
|
|
75
|
+
if (a < 0 || a > 255 || b < 0 || b > 255 || c < 1 || c > 65536) {
|
|
76
|
+
throw new Error('输入数值超出范围');
|
|
77
|
+
}
|
|
78
|
+
// 高频区域: 1个字符
|
|
79
|
+
let oIndexConfig = buideIndex(1);
|
|
80
|
+
if (oIndexConfig.check(a, b, c)) {
|
|
81
|
+
const index = oIndexConfig.oIndex[[a, b, c].toString()];
|
|
82
|
+
return numToCode(index);
|
|
83
|
+
}
|
|
84
|
+
// 中频区域: 2个字符
|
|
85
|
+
oIndexConfig = buideIndex(2);
|
|
86
|
+
if (oIndexConfig.check(a, b, c)) {
|
|
87
|
+
const index = oIndexConfig.oIndex[[a, b, c].toString()];
|
|
88
|
+
return numToCode(index);
|
|
89
|
+
}
|
|
90
|
+
// 低频区域: 2个字符
|
|
91
|
+
oIndexConfig = buideIndex(3);
|
|
92
|
+
if (oIndexConfig.check(a, b, c)) {
|
|
93
|
+
const index = oIndexConfig.oIndex[[a, b, c].toString()];
|
|
94
|
+
return numToCode(index);
|
|
95
|
+
}
|
|
96
|
+
// 罕见区域: 3个字符
|
|
97
|
+
oIndexConfig = buideIndex(4);
|
|
98
|
+
if (oIndexConfig.check(a, b, c)) {
|
|
99
|
+
const index = oIndexConfig.oIndex[[a, b, c].toString()];
|
|
100
|
+
return numToCode(index);
|
|
101
|
+
}
|
|
102
|
+
return encodeBig(a, b, c);
|
|
103
|
+
}
|
|
104
|
+
function decode(str) {
|
|
105
|
+
if (!str || str.length === 0) {
|
|
106
|
+
throw new Error('输入字符串不能为空');
|
|
107
|
+
}
|
|
108
|
+
if (!/^[0-9A-Z]+$/.test(str)) {
|
|
109
|
+
throw new Error('无效的编码字符串 of [0-9A-Z]');
|
|
110
|
+
}
|
|
111
|
+
const index = codeToNum(str);
|
|
112
|
+
// 高频区域: 1个字符
|
|
113
|
+
if (str.length < 3) {
|
|
114
|
+
const oIndex = buideIndex(2).oIndex;
|
|
115
|
+
for (const key in oIndex) {
|
|
116
|
+
if (oIndex[key] === index) {
|
|
117
|
+
return key.split(',').map(Number);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// 中低频区域: 2个字符
|
|
122
|
+
if (str.length < 3) {
|
|
123
|
+
const oIndex = buideIndex(3).oIndex;
|
|
124
|
+
for (const key in oIndex) {
|
|
125
|
+
if (oIndex[key] === index) {
|
|
126
|
+
return key.split(',').map(Number);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// 罕见区域: 3个字符
|
|
131
|
+
if (str.length < 4) {
|
|
132
|
+
const oIndex = buideIndex(4).oIndex;
|
|
133
|
+
for (const key in oIndex) {
|
|
134
|
+
if (oIndex[key] === index) {
|
|
135
|
+
return key.split(',').map(Number);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return decodeBig(str);
|
|
140
|
+
}
|
|
141
|
+
function encodeBig(a, b, c) {
|
|
142
|
+
// 验证输入范围
|
|
143
|
+
if (a < 0 || a > 255 || b < 0 || b > 255 || c < 1 || c > 65536) {
|
|
144
|
+
throw new Error('Invalid input parameters. Expected a:0-255, b:0-255, c:1-65536');
|
|
145
|
+
}
|
|
146
|
+
// 计算组合值
|
|
147
|
+
const combined = a * 0x1000000 + b * 0x10000 + (c - 1);
|
|
148
|
+
// 转换为36进制并大写,补齐7位
|
|
149
|
+
return combined.toString(36).toUpperCase().padStart(7, '0');
|
|
150
|
+
}
|
|
151
|
+
function decodeBig(str) {
|
|
152
|
+
// 验证输入字符串
|
|
153
|
+
if (!str || str.length !== 7 || !/^[0-9A-Z]+$/.test(str)) {
|
|
154
|
+
throw new Error('Invalid encoded string: must be 7 characters of [0-9A-Z]');
|
|
155
|
+
}
|
|
156
|
+
// 转换为小写并解析
|
|
157
|
+
const combined = parseInt(str.toLowerCase(), 36);
|
|
158
|
+
if (isNaN(combined)) {
|
|
159
|
+
throw new Error('Invalid encoded string');
|
|
160
|
+
}
|
|
161
|
+
// 验证组合值范围
|
|
162
|
+
if (combined < 0 || combined > 0xFFFFFFFF) {
|
|
163
|
+
throw new Error('Encoded value out of valid range');
|
|
164
|
+
}
|
|
165
|
+
// 分解各部分的数值
|
|
166
|
+
const a = (combined >>> 24) & 0xFF;
|
|
167
|
+
const b = (combined >>> 16) & 0xFF;
|
|
168
|
+
const c = (combined & 0xFFFF) + 1; // 恢复c的原始值
|
|
169
|
+
// 验证分解后的参数范围
|
|
170
|
+
if (a < 0 || a > 255 || b < 0 || b > 255 || c < 1 || c > 65536) {
|
|
171
|
+
throw new Error('Decoded values out of range');
|
|
172
|
+
}
|
|
173
|
+
return [a, b, c];
|
|
174
|
+
}
|
|
175
|
+
// 将十进制数转换为36进制字符串
|
|
176
|
+
function numToCode(num) {
|
|
177
|
+
let result = '';
|
|
178
|
+
if (num === 0) {
|
|
179
|
+
return '0';
|
|
180
|
+
}
|
|
181
|
+
while (num > 0) {
|
|
182
|
+
const remainder = num % 36;
|
|
183
|
+
result = CHARS[remainder] + result;
|
|
184
|
+
num = Math.floor(num / 36);
|
|
185
|
+
}
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
// 将36进制字符串转换为十进制数
|
|
189
|
+
function codeToNum(code) {
|
|
190
|
+
let result = 0;
|
|
191
|
+
for (let i = 0; i < code.length; i++) {
|
|
192
|
+
const char = code[i];
|
|
193
|
+
const value = CHARS.indexOf(char);
|
|
194
|
+
result = result * 36 + value;
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
}
|
|
198
|
+
// 生成一个范围数组
|
|
199
|
+
function buildArrFrom(start, end) {
|
|
200
|
+
const arr = [];
|
|
201
|
+
for (let i = start; i <= end; i++) {
|
|
202
|
+
arr.push(i);
|
|
203
|
+
}
|
|
204
|
+
return arr;
|
|
205
|
+
}
|
|
206
|
+
/*
|
|
207
|
+
// 测试代码
|
|
208
|
+
function test() {
|
|
209
|
+
describe('编码解码测试', () => {
|
|
210
|
+
// 高频区域测试
|
|
211
|
+
it('高频区域编码解码', () => {
|
|
212
|
+
// 测试边界值
|
|
213
|
+
const testCases = [
|
|
214
|
+
[ 0, 0, 6688 ],
|
|
215
|
+
[ 1, 0, 6688 ],
|
|
216
|
+
[ 0, 1, 6688 ],
|
|
217
|
+
[ 1, 1, 6688 ],
|
|
218
|
+
[ 3, 1, 6688 ],
|
|
219
|
+
[ 4, 1, 6688 ],
|
|
220
|
+
[ 5, 1, 6688 ],
|
|
221
|
+
[ 6, 1, 6688 ],
|
|
222
|
+
[ 7, 1, 6688 ]
|
|
223
|
+
];
|
|
224
|
+
|
|
225
|
+
testCases.forEach(([ a, b, c ]) => {
|
|
226
|
+
const encoded = encode(a, b, c);
|
|
227
|
+
assert.strictEqual(encoded.length, 1, '高频区域编码应为1个字符');
|
|
228
|
+
const decoded = decode(encoded);
|
|
229
|
+
assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// 中频区域测试
|
|
234
|
+
it('中频区域编码解码', () => {
|
|
235
|
+
const testCases = [
|
|
236
|
+
[ 19, 3, 6688 ],
|
|
237
|
+
[ 1, 0, 6689 ],
|
|
238
|
+
[ 0, 3, 6689 ],
|
|
239
|
+
[ 20, 4, 6689 ],
|
|
240
|
+
[ 5, 1, 6689 ],
|
|
241
|
+
[ 0, 4, 6688 ]
|
|
242
|
+
];
|
|
243
|
+
|
|
244
|
+
testCases.forEach(([ a, b, c ]) => {
|
|
245
|
+
const encoded = encode(a, b, c);
|
|
246
|
+
assert.strictEqual(encoded.length, 2, '中频区域编码应为2个字符');
|
|
247
|
+
const decoded = decode(encoded);
|
|
248
|
+
assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// 低频区域测试
|
|
253
|
+
it('低频区域编码解码', () => {
|
|
254
|
+
const testCases = [
|
|
255
|
+
[ 19, 5, 6688 ],
|
|
256
|
+
[ 28, 0, 6689 ],
|
|
257
|
+
[ 0, 7, 6689 ],
|
|
258
|
+
[ 28, 5, 6689 ],
|
|
259
|
+
[ 5, 1, 6690 ],
|
|
260
|
+
[ 1, 1, 6690 ]
|
|
261
|
+
];
|
|
262
|
+
|
|
263
|
+
testCases.forEach(([ a, b, c ]) => {
|
|
264
|
+
const encoded = encode(a, b, c);
|
|
265
|
+
assert.strictEqual(encoded.length, 2, '低频区域编码应为2个字符');
|
|
266
|
+
const decoded = decode(encoded);
|
|
267
|
+
assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
// 罕见区域测试
|
|
272
|
+
it('罕见区域编码解码', () => {
|
|
273
|
+
const testCases = [
|
|
274
|
+
[ 49, 5, 6688 ],
|
|
275
|
+
[ 28, 9, 6689 ],
|
|
276
|
+
[ 232, 13, 6689 ],
|
|
277
|
+
[ 28, 150, 6689 ],
|
|
278
|
+
[ 5, 1, 6691 ],
|
|
279
|
+
[ 111, 254, 6691 ]
|
|
280
|
+
];
|
|
281
|
+
|
|
282
|
+
testCases.forEach(([ a, b, c ]) => {
|
|
283
|
+
const encoded = encode(a, b, c);
|
|
284
|
+
assert.strictEqual(encoded.length, 3, '罕见区域编码应为3个字符');
|
|
285
|
+
const decoded = decode(encoded);
|
|
286
|
+
assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
// 其它区域测试
|
|
291
|
+
it('其它区域编码解码', () => {
|
|
292
|
+
const testCases = [
|
|
293
|
+
[ 49, 5, 8688 ],
|
|
294
|
+
[ 28, 191, 8689 ],
|
|
295
|
+
[ 232, 188, 6689 ],
|
|
296
|
+
[ 28, 150, 3689 ],
|
|
297
|
+
[ 5, 1, 691 ],
|
|
298
|
+
[ 111, 121, 16691 ]
|
|
299
|
+
];
|
|
300
|
+
|
|
301
|
+
testCases.forEach(([ a, b, c ]) => {
|
|
302
|
+
const encoded = encode(a, b, c);
|
|
303
|
+
assert.strictEqual(encoded.length, 7, '其它区域编码应为7个字符');
|
|
304
|
+
const decoded = decode(encoded);
|
|
305
|
+
assert.deepStrictEqual(decoded, [ a, b, c ], '解码结果应与原始输入匹配');
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// 边界条件测试
|
|
310
|
+
it('输入范围验证', () => {
|
|
311
|
+
assert.throws(() => encode(-1, 0, 1), Error, '应当检测到负数输入');
|
|
312
|
+
assert.throws(() => encode(256, 0, 1), Error, '应当检测到a超出范围');
|
|
313
|
+
assert.throws(() => encode(0, 256, 1), Error, '应当检测到b超出范围');
|
|
314
|
+
assert.throws(() => encode(0, 0, 0), Error, '应当检测到c小于1');
|
|
315
|
+
assert.throws(() => encode(0, 0, 65537), Error, '应当检测到c超出范围');
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
// 解码异常测试
|
|
319
|
+
it('解码异常验证', () => {
|
|
320
|
+
assert.throws(() => decode(''), Error, '应当检测到空字符串');
|
|
321
|
+
assert.throws(() => decode('Q-'), Error, '应当检测到无效的编码字符串');
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
function describe(title:string, fun:Function) {
|
|
328
|
+
console.log(title, '\n开始测试...\n');
|
|
329
|
+
fun();
|
|
330
|
+
console.log(title, '测试完成\n');
|
|
331
|
+
}
|
|
332
|
+
const it = describe;
|
|
333
|
+
|
|
334
|
+
test();
|
|
335
|
+
|
|
336
|
+
*/
|