music-downloader/app/model/StoreModel.js

102 lines
2.8 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");
2024-02-18 06:25:45 +00:00
//var ffmetadata = require("ffmetadata");
const { exec } = require('child_process');
2023-08-01 15:48:57 +00:00
//递归创建目录 同步方法
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);
});
});
}
2024-02-18 06:25:45 +00:00
async function storeMusic(path, url, info) {
await storeResource(path, url);
if(info.extension == 'mp3') {
await modifyMP3Info2(path, info);
}
}
// async function modifyMP3Info(path, info) {
// path = handlePath(path);
// // Read song.mp3 metadata
// ffmetadata.read(path, function(err, data) {
// if (err) console.error("Error reading metadata", err);
// else console.log(data);
// });
// // Set the artist for song.mp3
// var data = {
// title: info.title,
// artist: info.author
// };
// ffmetadata.write(path, data, function(err) {
// if (err) console.error("Error writing metadata", err);
// else console.log("Data written");
// });
// }
async function modifyMP3Info2(path, info) {
path = handlePath(path);
// 要执行的命令行指令
2024-02-18 06:45:40 +00:00
const command = `mp3info -a "${info.author}" -t "${info.title}" "${path}"`;
2024-02-18 06:25:45 +00:00
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`修改mp3文件信息时发生错误${error}`);
return;
}
console.log(`修改mp3文件信息\n${stdout}`);
});
2023-08-01 15:48:57 +00:00
}
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;
2024-02-18 06:25:45 +00:00
path = path.replace('..', '').replace(/\.+/g, '.').replace(/\/+/g, '/').replace(/\\+/g, '\\');
if(process.cwd()[0] != '/') path = process.cwd()[0] + ':' + path; // 兼容windows盘符
return path;
}
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
}