🐞 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 plugin from "../../../lib/plugins/plugin.js";
import axios from "axios"; import axios from "axios";
import fs from "node:fs"; import fs from "node:fs";
import {segment} from "oicq"; import { segment } from "oicq";
import { import {
checkMusic, checkMusic,
getCookies, getCookies,
@ -13,9 +13,10 @@ import {
getSongDetail, getSongDetail,
getUserRecord, getUserRecord,
} from "../utils/netease.js"; } from "../utils/netease.js";
import {ha12store, store2ha1} from "../utils/encrypt.js"; import { ha12store, store2ha1 } from "../utils/encrypt.js";
import fetch from "node-fetch"; import fetch from "node-fetch";
import _ from "lodash"; import _ from "lodash";
import { mkdirsSync } from "../utils/file.js";
export class neteasepro extends plugin { export class neteasepro extends plugin {
constructor() { constructor() {
@ -112,7 +113,7 @@ export class neteasepro extends plugin {
user_id: e.user_id, 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)); await e.reply(await this.musicForwardPack(forwardMsg));
} }
@ -135,9 +136,9 @@ export class neteasepro extends plugin {
message: segment.json(await this.musicPack(song)), message: segment.json(await this.musicPack(song)),
nickname: e.sender.card || e.user_id, nickname: e.sender.card || e.user_id,
user_id: 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)); await e.reply(await this.musicForwardPack(forwardMsg));
} }
@ -294,41 +295,44 @@ export class neteasepro extends plugin {
const preview = song.al?.picUrl; const preview = song.al?.picUrl;
const musicUrl = `https://music.163.com/song/media/outer/url?id=${song.id}.mp3`; const musicUrl = `https://music.163.com/song/media/outer/url?id=${song.id}.mp3`;
return { return {
"app": "com.tencent.structmsg", app: "com.tencent.structmsg",
"desc": "音乐", desc: "音乐",
"view": "music", view: "music",
"ver": "0.0.0.1", ver: "0.0.0.1",
"prompt": "[分享]" + title + '-' + singer, prompt: "[分享]" + title + "-" + singer,
"meta": { meta: {
"music": { music: {
"app_type": 1, app_type: 1,
"appid": 100495085, appid: 100495085,
"desc": singer, desc: singer,
"jumpUrl": jumpUrl, jumpUrl: jumpUrl,
"musicUrl": musicUrl, musicUrl: musicUrl,
"preview": preview, preview: preview,
"sourceMsgId": "0", sourceMsgId: "0",
"source_icon": "https://i.gtimg.cn/open/app_icon/00/49/50/85/100495085_100_m.png", source_icon: "https://i.gtimg.cn/open/app_icon/00/49/50/85/100495085_100_m.png",
"source_url": "", source_url: "",
"tag": "网易云音乐", tag: "网易云音乐",
"title": title, 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 forwardMsg.data = forwardMsg.data
.replace('<?xml version="1.0" encoding="utf-8"?>', '<?xml version="1.0" encoding="utf-8" ?>') .replace(
.replace(/\n/g, '') '<?xml version="1.0" encoding="utf-8"?>',
.replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___') '<?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>`); .replace(/___+/, `<title color="#777777" size="26">${forwardMsgName}</title>`);
return forwardMsg return forwardMsg;
} }
/** /**
@ -346,7 +350,18 @@ export class neteasepro extends plugin {
responseType: "stream", responseType: "stream",
redirect: redirect, redirect: redirect,
}).then(res => { }).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); const fileStream = fs.createWriteStream(path);
res.body.pipe(fileStream); res.body.pipe(fileStream);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

View File

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

View File

@ -540,13 +540,13 @@ export class tools extends plugin {
e.msg, e.msg,
)[0]; )[0];
let id; let id;
if (msgUrl.includes('xhslink')) { if (msgUrl.includes("xhslink")) {
await fetch(msgUrl, { await fetch(msgUrl, {
redirect: 'follow', redirect: "follow",
}).then(resp => { }).then(resp => {
const uri = decodeURIComponent(resp.url) const uri = decodeURIComponent(resp.url);
id = /explore\/(\w+)/.exec(uri)[1]; id = /explore\/(\w+)/.exec(uri)[1];
}) });
} else { } else {
id = /explore\/(\w+)/.exec(msgUrl)[1]; id = /explore\/(\w+)/.exec(msgUrl)[1];
} }
@ -554,28 +554,29 @@ export class tools extends plugin {
// 获取信息 // 获取信息
fetch(`https://www.xiaohongshu.com/discovery/item/${id}`, { fetch(`https://www.xiaohongshu.com/discovery/item/${id}`, {
headers: { 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", "user-agent":
"cookie": Buffer.from(XHS_CK, 'base64').toString('utf-8') "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 => { }).then(async resp => {
const xhsHtml = await resp.text(); const xhsHtml = await resp.text();
const reg = /window.__INITIAL_STATE__=(.*?)<\/script>/ const reg = /window.__INITIAL_STATE__=(.*?)<\/script>/;
const resJson = xhsHtml.match(reg)[0] const resJson = xhsHtml.match(reg)[0];
const res = JSON.parse(resJson.match(reg)[1]); const res = JSON.parse(resJson.match(reg)[1]);
const noteData = res.noteData.data.noteData const noteData = res.noteData.data.noteData;
const { title, desc, type } = noteData const { title, desc, type } = noteData;
e.reply(`识别:小红书, ${title}\n${desc}`) e.reply(`识别:小红书, ${title}\n${desc}`);
let imgPromise = [] let imgPromise = [];
if (type === 'video') { if (type === "video") {
const url = noteData.video.url; const url = noteData.video.url;
this.downloadVideo(url).then(path => { this.downloadVideo(url).then(path => {
e.reply(segment.video(path + "/temp.mp4")); e.reply(segment.video(path + "/temp.mp4"));
}) });
return true; return true;
} else if (type === 'normal') { } else if (type === "normal") {
noteData.imageList.map (async (item, index) => { noteData.imageList.map(async (item, index) => {
imgPromise.push(this.downloadImg(item.url, downloadPath, index.toString())) imgPromise.push(this.downloadImg(item.url, downloadPath, index.toString()));
}) });
} }
let path = []; let path = [];
const images = await Promise.all(imgPromise).then(paths => { const images = await Promise.all(imgPromise).then(paths => {
@ -593,7 +594,7 @@ export class tools extends plugin {
path.forEach(item => { path.forEach(item => {
fs.unlinkSync(item); fs.unlinkSync(item);
}); });
}) });
return true; return true;
} }
@ -643,12 +644,15 @@ export class tools extends plugin {
const API = `https://xiaobai.klizi.cn/API/music/bodian.php?msg=${msg}&n=&max=`; const API = `https://xiaobai.klizi.cn/API/music/bodian.php?msg=${msg}&n=&max=`;
// 获取列表 // 获取列表
const thisMethod = this; const thisMethod = this;
await axios.get(API, { await axios
.get(API, {
headers: { headers: {
"HOST": "xiaobai.klizi.cn", 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", "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 => { },
})
.then(resp => {
e.reply("请选择一个要播放的视频:\n" + resp.data); e.reply("请选择一个要播放的视频:\n" + resp.data);
thisMethod.setContext("bodianMusicContext"); thisMethod.setContext("bodianMusicContext");
}); });
@ -669,12 +673,15 @@ export class tools extends plugin {
curMsg.msg, curMsg.msg,
)}&max=`; )}&max=`;
const thisMethod = this; const thisMethod = this;
axios.get(API, { axios
.get(API, {
headers: { headers: {
"HOST": "xiaobai.klizi.cn", 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", "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 => { },
})
.then(async res => {
// 如果没有,直接返回 // 如果没有,直接返回
if (res.data.lowUrl === null || res.data.highUrl === null) { if (res.data.lowUrl === null || res.data.highUrl === null) {
return; return;
@ -742,7 +749,7 @@ export class tools extends plugin {
* @param fileName * @param fileName
* @returns {Promise<unknown>} * @returns {Promise<unknown>}
*/ */
async downloadImg(img, dir, fileName='') { async downloadImg(img, dir, fileName = "") {
if (fileName === "") { if (fileName === "") {
fileName = img.split("/").pop(); fileName = img.split("/").pop();
} }