music-downloader/app/model/StoreModel.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

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) {
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) {
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);
}
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
}