2023-08-01 15:48:57 +00:00
|
|
|
|
const fs = require('fs');
|
|
|
|
|
const request = require('request');
|
|
|
|
|
const _path = require("path");
|
|
|
|
|
|
|
|
|
|
//递归创建目录 同步方法
|
|
|
|
|
function mkdirsSync(dirname) {
|
|
|
|
|
//console.log(dirname);
|
|
|
|
|
if (fs.existsSync(dirname)) {
|
|
|
|
|
return true;
|
|
|
|
|
} else {
|
|
|
|
|
if (mkdirsSync(_path.dirname(dirname))) {
|
|
|
|
|
fs.mkdirSync(dirname);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function storeResource(path, url) {
|
2023-08-05 01:09:19 +00:00
|
|
|
|
path = handlePath(path);
|
2023-08-01 15:48:57 +00:00
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
mkdirsSync(_path.dirname(path));
|
|
|
|
|
const writeableStream = fs.createWriteStream(path);
|
2023-08-05 04:49:00 +00:00
|
|
|
|
request.get({ url: url, timeout: 20000 }).pipe(writeableStream).on('close', () => {
|
2023-08-01 15:48:57 +00:00
|
|
|
|
resolve(true);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function storeMusic(path, url) {
|
|
|
|
|
return await storeResource(path, url);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function storeLrc(path, content) {
|
2023-08-05 01:09:19 +00:00
|
|
|
|
path = handlePath(path);
|
2023-08-01 15:48:57 +00:00
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
mkdirsSync(_path.dirname(path));
|
|
|
|
|
fs.writeFileSync(path, content, { overwrite: true });
|
|
|
|
|
resolve(true);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function storePic(path, url) {
|
|
|
|
|
return await storeResource(path, url);
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-03 14:59:36 +00:00
|
|
|
|
function checkMusicExists(path) {
|
|
|
|
|
return fs.existsSync(path);
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-05 01:09:19 +00:00
|
|
|
|
function handlePath(path) {
|
|
|
|
|
// 必须保存到downloads目录,过滤关键字符防止目录穿越
|
|
|
|
|
if(path.indexOf('/downloads/') != 0) path = '/downloads/' + path;
|
|
|
|
|
return path.replace('..', '').replace(/\.+/g, '.').replace(/\/+/g, '/').replace(/\\+/g, '\\');
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-01 15:48:57 +00:00
|
|
|
|
module.exports = {
|
|
|
|
|
storeMusic,
|
|
|
|
|
storeLrc,
|
2023-08-03 14:59:36 +00:00
|
|
|
|
storePic,
|
|
|
|
|
checkMusicExists
|
2023-08-01 15:48:57 +00:00
|
|
|
|
}
|