102 lines
2.9 KiB
JavaScript
102 lines
2.9 KiB
JavaScript
const fs = require('fs');
|
||
const request = require('request');
|
||
const _path = require("path");
|
||
//var ffmetadata = require("ffmetadata");
|
||
const { exec } = require('child_process');
|
||
|
||
//递归创建目录 同步方法
|
||
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);
|
||
return new Promise((resolve, reject) => {
|
||
mkdirsSync(_path.dirname(path));
|
||
const writeableStream = fs.createWriteStream(path);
|
||
request.get({ url: url, timeout: 20000 }).pipe(writeableStream).on('close', () => {
|
||
resolve(true);
|
||
});
|
||
});
|
||
}
|
||
|
||
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);
|
||
// 要执行的命令行指令
|
||
const command = `mp3info -a "${info.author}" -t "${info.title}" "${path}"`;
|
||
|
||
exec(command, (error, stdout, stderr) => {
|
||
if (error) {
|
||
console.error(`修改mp3文件信息时发生错误:${error}`);
|
||
return;
|
||
}
|
||
|
||
console.log(`修改mp3文件信息:\n${stdout}`);
|
||
});
|
||
}
|
||
|
||
function storeLrc(path, content) {
|
||
path = handlePath(path);
|
||
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);
|
||
}
|
||
|
||
function checkMusicExists(path) {
|
||
return fs.existsSync(path);
|
||
}
|
||
|
||
function handlePath(path) {
|
||
// 必须保存到downloads目录,过滤关键字符防止目录穿越
|
||
if(path.indexOf('/downloads/') != 0) path = '/downloads/' + path;
|
||
path = path.replace('..', '').replace(/\.+/g, '.').replace(/\/+/g, '/').replace(/\\+/g, '\\');
|
||
if(process.cwd()[0] != '/') path = process.cwd()[0] + ':' + path; // 兼容windows盘符
|
||
return path;
|
||
}
|
||
|
||
module.exports = {
|
||
storeMusic,
|
||
storeLrc,
|
||
storePic,
|
||
checkMusicExists
|
||
} |