🐞 fix: 修复网易云解析第一次无法创建文件夹问题[#I6OENE] & 美化代码

This commit is contained in:
zhiyu1998 2023-03-21 00:32:01 +08:00
parent 5b48d78da3
commit d6f2b0be30
3 changed files with 112 additions and 91 deletions

View File

@ -1,7 +1,7 @@
import plugin from "../../../lib/plugins/plugin.js";
import axios from "axios";
import fs from "node:fs";
import {segment} from "oicq";
import { segment } from "oicq";
import {
checkMusic,
getCookies,
@ -13,9 +13,10 @@ import {
getSongDetail,
getUserRecord,
} from "../utils/netease.js";
import {ha12store, store2ha1} from "../utils/encrypt.js";
import { ha12store, store2ha1 } from "../utils/encrypt.js";
import fetch from "node-fetch";
import _ from "lodash";
import { mkdirsSync } from "../utils/file.js";
export class neteasepro extends plugin {
constructor() {
@ -112,7 +113,7 @@ export class neteasepro extends plugin {
user_id: e.user_id,
};
});
let forwardMsg = await Bot.makeForwardMsg(await Promise.all(combineMsg))
let forwardMsg = await Bot.makeForwardMsg(await Promise.all(combineMsg));
await e.reply(await this.musicForwardPack(forwardMsg));
}
@ -135,9 +136,9 @@ export class neteasepro extends plugin {
message: segment.json(await this.musicPack(song)),
nickname: e.sender.card || e.user_id,
user_id: e.user_id,
}
};
});
let forwardMsg = await Bot.makeForwardMsg(await Promise.all(rank))
let forwardMsg = await Bot.makeForwardMsg(await Promise.all(rank));
await e.reply(await this.musicForwardPack(forwardMsg));
}
@ -294,41 +295,44 @@ export class neteasepro extends plugin {
const preview = song.al?.picUrl;
const musicUrl = `https://music.163.com/song/media/outer/url?id=${song.id}.mp3`;
return {
"app": "com.tencent.structmsg",
"desc": "音乐",
"view": "music",
"ver": "0.0.0.1",
"prompt": "[分享]" + title + '-' + singer,
"meta": {
"music": {
"app_type": 1,
"appid": 100495085,
"desc": singer,
"jumpUrl": jumpUrl,
"musicUrl": musicUrl,
"preview": preview,
"sourceMsgId": "0",
"source_icon": "https://i.gtimg.cn/open/app_icon/00/49/50/85/100495085_100_m.png",
"source_url": "",
"tag": "网易云音乐",
"title": title,
}
app: "com.tencent.structmsg",
desc: "音乐",
view: "music",
ver: "0.0.0.1",
prompt: "[分享]" + title + "-" + singer,
meta: {
music: {
app_type: 1,
appid: 100495085,
desc: singer,
jumpUrl: jumpUrl,
musicUrl: musicUrl,
preview: preview,
sourceMsgId: "0",
source_icon: "https://i.gtimg.cn/open/app_icon/00/49/50/85/100495085_100_m.png",
source_url: "",
tag: "网易云音乐",
title: title,
},
},
config: {
type: "normal",
forward: true,
ctime: Date.now(),
},
"config": {
"type": "normal",
"forward": true,
"ctime": Date.now(),
}
};
}
async musicForwardPack(forwardMsg, forwardMsgName="R插件消息") {
async musicForwardPack(forwardMsg, forwardMsgName = "R插件消息") {
forwardMsg.data = forwardMsg.data
.replace('<?xml version="1.0" encoding="utf-8"?>', '<?xml version="1.0" encoding="utf-8" ?>')
.replace(/\n/g, '')
.replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
.replace(
'<?xml version="1.0" encoding="utf-8"?>',
'<?xml version="1.0" encoding="utf-8" ?>',
)
.replace(/\n/g, "")
.replace(/<title color="#777777" size="26">(.+?)<\/title>/g, "___")
.replace(/___+/, `<title color="#777777" size="26">${forwardMsgName}</title>`);
return forwardMsg
return forwardMsg;
}
/**
@ -346,7 +350,18 @@ export class neteasepro extends plugin {
responseType: "stream",
redirect: redirect,
}).then(res => {
const path = `./data/rcmp4/${this.e.group_id || this.e.user_id}/temp.mp3`;
let path = `./data/rcmp4/${this.e.group_id || this.e.user_id}`;
// 如果没有目录就创建一个
if (!fs.existsSync(path)) {
mkdirsSync(path);
}
// 补充保存文件名
path += "/temp.mp3";
if (fs.existsSync(path)) {
console.log(`视频已存在`);
fs.unlinkSync(path);
}
// 开始下载
const fileStream = fs.createWriteStream(path);
res.body.pipe(fileStream);
return new Promise((resolve, reject) => {

View File

@ -173,7 +173,6 @@ export class query extends plugin {
.then(resp => resp.json())
.catch(err => logger.error(err)),
];
console.log(res);
// 时间复杂度(n^2) 待优化
const msg = res.map(async recommend => {
return recommend.data.list.map(element => {

View File

@ -540,13 +540,13 @@ export class tools extends plugin {
e.msg,
)[0];
let id;
if (msgUrl.includes('xhslink')) {
if (msgUrl.includes("xhslink")) {
await fetch(msgUrl, {
redirect: 'follow',
redirect: "follow",
}).then(resp => {
const uri = decodeURIComponent(resp.url)
const uri = decodeURIComponent(resp.url);
id = /explore\/(\w+)/.exec(uri)[1];
})
});
} else {
id = /explore\/(\w+)/.exec(msgUrl)[1];
}
@ -554,28 +554,29 @@ export class tools extends plugin {
// 获取信息
fetch(`https://www.xiaohongshu.com/discovery/item/${id}`, {
headers: {
"user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/110.0.0.0",
"cookie": Buffer.from(XHS_CK, 'base64').toString('utf-8')
}
"user-agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/110.0.0.0",
cookie: Buffer.from(XHS_CK, "base64").toString("utf-8"),
},
}).then(async resp => {
const xhsHtml = await resp.text();
const reg = /window.__INITIAL_STATE__=(.*?)<\/script>/
const resJson = xhsHtml.match(reg)[0]
const reg = /window.__INITIAL_STATE__=(.*?)<\/script>/;
const resJson = xhsHtml.match(reg)[0];
const res = JSON.parse(resJson.match(reg)[1]);
const noteData = res.noteData.data.noteData
const { title, desc, type } = noteData
e.reply(`识别:小红书, ${title}\n${desc}`)
let imgPromise = []
if (type === 'video') {
const noteData = res.noteData.data.noteData;
const { title, desc, type } = noteData;
e.reply(`识别:小红书, ${title}\n${desc}`);
let imgPromise = [];
if (type === "video") {
const url = noteData.video.url;
this.downloadVideo(url).then(path => {
e.reply(segment.video(path + "/temp.mp4"));
})
});
return true;
} else if (type === 'normal') {
noteData.imageList.map (async (item, index) => {
imgPromise.push(this.downloadImg(item.url, downloadPath, index.toString()))
})
} else if (type === "normal") {
noteData.imageList.map(async (item, index) => {
imgPromise.push(this.downloadImg(item.url, downloadPath, index.toString()));
});
}
let path = [];
const images = await Promise.all(imgPromise).then(paths => {
@ -593,7 +594,7 @@ export class tools extends plugin {
path.forEach(item => {
fs.unlinkSync(item);
});
})
});
return true;
}
@ -643,15 +644,18 @@ export class tools extends plugin {
const API = `https://xiaobai.klizi.cn/API/music/bodian.php?msg=${msg}&n=&max=`;
// 获取列表
const thisMethod = this;
await axios.get(API, {
headers: {
"HOST": "xiaobai.klizi.cn",
"User-Agent": "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Mobile Safari/537.36",
}
}).then(resp => {
e.reply("请选择一个要播放的视频:\n" + resp.data);
thisMethod.setContext("bodianMusicContext");
});
await axios
.get(API, {
headers: {
HOST: "xiaobai.klizi.cn",
"User-Agent":
"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Mobile Safari/537.36",
},
})
.then(resp => {
e.reply("请选择一个要播放的视频:\n" + resp.data);
thisMethod.setContext("bodianMusicContext");
});
return true;
}
@ -669,31 +673,34 @@ export class tools extends plugin {
curMsg.msg,
)}&max=`;
const thisMethod = this;
axios.get(API, {
headers: {
"HOST": "xiaobai.klizi.cn",
"User-Agent": "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Mobile Safari/537.36",
}
}).then(async res => {
// 如果没有,直接返回
if (res.data.lowUrl === null || res.data.highUrl === null) {
return;
}
// 捕获一些未知错误
try {
// 波点音乐信息
const { songName, artist, coverUrl, highUrl, lowUrl, shortLowUrl } = res.data;
curMsg.reply([`${songName}-${artist}\n`, segment.image(coverUrl)]);
// 下载 && 发送
await thisMethod.downloadVideo(lowUrl).then(path => {
curMsg.reply(segment.video(path + "/temp.mp4"));
});
} catch (err) {
curMsg.reply("发生网络错误,请重新发送!");
} finally {
thisMethod.finish("bodianMusicContext");
}
});
axios
.get(API, {
headers: {
HOST: "xiaobai.klizi.cn",
"User-Agent":
"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Mobile Safari/537.36",
},
})
.then(async res => {
// 如果没有,直接返回
if (res.data.lowUrl === null || res.data.highUrl === null) {
return;
}
// 捕获一些未知错误
try {
// 波点音乐信息
const { songName, artist, coverUrl, highUrl, lowUrl, shortLowUrl } = res.data;
curMsg.reply([`${songName}-${artist}\n`, segment.image(coverUrl)]);
// 下载 && 发送
await thisMethod.downloadVideo(lowUrl).then(path => {
curMsg.reply(segment.video(path + "/temp.mp4"));
});
} catch (err) {
curMsg.reply("发生网络错误,请重新发送!");
} finally {
thisMethod.finish("bodianMusicContext");
}
});
this.finish("bodianMusicContext");
}
@ -742,7 +749,7 @@ export class tools extends plugin {
* @param fileName
* @returns {Promise<unknown>}
*/
async downloadImg(img, dir, fileName='') {
async downloadImg(img, dir, fileName = "") {
if (fileName === "") {
fileName = img.split("/").pop();
}