🌈 style: 代码格式化

This commit is contained in:
zhiyu1998 2023-03-15 23:46:38 +08:00
parent cec0f2da03
commit 8426215d5f

View File

@ -1,50 +1,58 @@
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 {getQrCode, getKey, getLoginStatus, getDailyRecommend, getCookies, getUserRecord, checkMusic, getSong} from '../utils/netease.js'; import {
import {ha12store, store2ha1} from '../utils/encrypt.js'; getQrCode,
getKey,
getLoginStatus,
getDailyRecommend,
getCookies,
getUserRecord,
checkMusic,
getSong,
} from "../utils/netease.js";
import { ha12store, store2ha1 } from "../utils/encrypt.js";
import fetch from "node-fetch"; import fetch from "node-fetch";
export class neteasepro extends plugin { export class neteasepro extends plugin {
constructor() { constructor() {
super({ super({
/** 功能名称 */ /** 功能名称 */
name: 'R插件网易云音乐解析', name: "R插件网易云音乐解析",
/** 功能描述 */ /** 功能描述 */
dsc: '网易云音乐解析Pro', dsc: "网易云音乐解析Pro",
/** https://oicqjs.github.io/oicq/#events */ /** https://oicqjs.github.io/oicq/#events */
event: 'message', event: "message",
/** 优先级,数字越小等级越高 */ /** 优先级,数字越小等级越高 */
priority: 1, priority: 1,
rule: [ rule: [
{ {
/** 命令正则匹配 */ /** 命令正则匹配 */
reg: '#网易云登陆', reg: "#网易云登陆",
/** 执行方法 */ /** 执行方法 */
fnc: 'neteaseCloudLogin' fnc: "neteaseCloudLogin",
}, },
{ {
reg: '#网易云每日推荐', reg: "#网易云每日推荐",
fnc: 'neteaseDailyRecommend' fnc: "neteaseDailyRecommend",
}, },
{ {
reg: '#网易云听歌排行', reg: "#网易云听歌排行",
fnc: 'neteaseListenRank' fnc: "neteaseListenRank",
}, },
{ {
reg: "music.163.com", reg: "music.163.com",
fnc: "netease", fnc: "netease",
}, },
] ],
}) });
} }
async neteaseCloudLogin(e) { async neteaseCloudLogin(e) {
let neteaseCookie; let neteaseCookie;
// 如果不存在cookie // 如果不存在cookie
if (!await redis.exists(await this.getRedisKey(e.user_id))) { if (!(await redis.exists(await this.getRedisKey(e.user_id)))) {
// 获取密钥 // 获取密钥
const key = await getKey(); const key = await getKey();
// console.log(key); // console.log(key);
@ -53,28 +61,33 @@ export class neteasepro extends plugin {
// 下载qrcode // 下载qrcode
await this.downloadQrCode(qrPic).then(path => { await this.downloadQrCode(qrPic).then(path => {
// 发送二维码 // 发送二维码
e.reply(segment.image(fs.readFileSync(path))) e.reply(segment.image(fs.readFileSync(path)));
}) });
// 定时轮询 // 定时轮询
await this.poll(key).then(async cookie => { await this.poll(key).then(async cookie => {
// 存放到redis // 存放到redis
neteaseCookie = cookie neteaseCookie = cookie;
}); });
} else { } else {
// 已经登陆过的直接从redis取出 // 已经登陆过的直接从redis取出
neteaseCookie = await store2ha1(JSON.parse(await redis.get(await this.getRedisKey(e.user_id))).cookie) neteaseCookie = await store2ha1(
JSON.parse(await redis.get(await this.getRedisKey(e.user_id))).cookie,
);
} }
// 获取用户信息 // 获取用户信息
const userInfo = await getLoginStatus(neteaseCookie); const userInfo = await getLoginStatus(neteaseCookie);
// 提取信息 // 提取信息
const {userId, nickname, avatarUrl} = userInfo.profile; const { userId, nickname, avatarUrl } = userInfo.profile;
e.reply(["欢迎使用 🎶网易云音乐 🎶," + nickname, segment.image(avatarUrl)]) e.reply(["欢迎使用 🎶网易云音乐 🎶," + nickname, segment.image(avatarUrl)]);
// 重组后存放到redis {uid, cookie} // 重组后存放到redis {uid, cookie}
await redis.set(await this.getRedisKey(e.user_id), JSON.stringify({ await redis.set(
uid: userId, await this.getRedisKey(e.user_id),
cookie: (await ha12store(neteaseCookie)) JSON.stringify({
})); uid: userId,
return true cookie: await ha12store(neteaseCookie),
}),
);
return true;
} }
async neteaseDailyRecommend(e) { async neteaseDailyRecommend(e) {
@ -88,17 +101,21 @@ export class neteasepro extends plugin {
const combineMsg = await dailyRecommend.dailySongs.slice(0, 10).map(item => { const combineMsg = await dailyRecommend.dailySongs.slice(0, 10).map(item => {
// 组合数据 // 组合数据
return { return {
message: [segment.text(`${item?.id}: ${item?.name}-${item?.ar?.[0].name}-${item?.al?.name}`) message: [
, segment.image(item?.al?.picUrl)], segment.text(
`${item?.id}: ${item?.name}-${item?.ar?.[0].name}-${item?.al?.name}`,
),
segment.image(item?.al?.picUrl),
],
nickname: e.sender.card || e.user_id, nickname: e.sender.card || e.user_id,
user_id: e.user_id, user_id: e.user_id,
} };
}) });
await e.reply(await Bot.makeForwardMsg(combineMsg)); await e.reply(await Bot.makeForwardMsg(combineMsg));
} }
async neteaseListenRank(e) { async neteaseListenRank(e) {
const userInfo = await this.aopBefore(e) const userInfo = await this.aopBefore(e);
const realCookie = userInfo.cookie; const realCookie = userInfo.cookie;
if (realCookie === "") { if (realCookie === "") {
return true; return true;
@ -106,37 +123,50 @@ export class neteasepro extends plugin {
// 获取用户id // 获取用户id
const uid = userInfo.uid; const uid = userInfo.uid;
// 获取听歌排行榜 // 获取听歌排行榜
const userRecord = await getUserRecord(uid) const userRecord = await getUserRecord(uid);
let rankId = 0; let rankId = 0;
e.reply(" 😘亲这是你的听歌排行榜Top10") e.reply(" 😘亲这是你的听歌排行榜Top10");
const rank = userRecord.weekData.slice(0, 10).map(item => { const rank = userRecord.weekData.slice(0, 10).map(item => {
// 组合数据 // 组合数据
const song = item.song; const song = item.song;
rankId++; rankId++;
return { return {
message: [segment.text(`No.${rankId} ${song?.id}: ${song?.name}-${song?.ar?.[0].name}-${song?.al?.name}`) message: [
, segment.image(song?.al?.picUrl)], segment.text(
`No.${rankId} ${song?.id}: ${song?.name}-${song?.ar?.[0].name}-${song?.al?.name}`,
),
segment.image(song?.al?.picUrl),
],
nickname: e.sender.card || e.user_id, nickname: e.sender.card || e.user_id,
user_id: e.user_id, user_id: e.user_id,
} };
}) });
await e.reply(await Bot.makeForwardMsg(rank)); await e.reply(await Bot.makeForwardMsg(rank));
} }
async netease(e) { async netease(e) {
const message = e.msg === undefined ? e.message.shift().data.replaceAll("\\", "") : e.msg.trim(); const message =
e.msg === undefined ? e.message.shift().data.replaceAll("\\", "") : e.msg.trim();
const musicUrlReg = /(http:|https:)\/\/music.163.com\/song\/media\/outer\/url\?id=(\d+)/; const musicUrlReg = /(http:|https:)\/\/music.163.com\/song\/media\/outer\/url\?id=(\d+)/;
const musicUrlReg2 = /(http:|https:)\/\/y.music.163.com\/m\/song\?(.*)&id=(\d+)/; const musicUrlReg2 = /(http:|https:)\/\/y.music.163.com\/m\/song\?(.*)&id=(\d+)/;
const id = musicUrlReg2.exec(message)[3] || musicUrlReg.exec(message)[2] || /id=(\d+)/.exec(message)[1]; const id =
const musicJson = JSON.parse(message) musicUrlReg2.exec(message)[3] ||
const {musicUrl, preview, title, desc} = musicJson.meta.music || musicJson.meta.news; musicUrlReg.exec(message)[2] ||
console.log(musicUrl, preview, title, desc) /id=(\d+)/.exec(message)[1];
const musicJson = JSON.parse(message);
const { musicUrl, preview, title, desc } = musicJson.meta.music || musicJson.meta.news;
console.log(musicUrl, preview, title, desc);
// 如果没有登陆,就使用官方接口 // 如果没有登陆,就使用官方接口
e.reply([`识别:网易云音乐,${title}--${desc}`, segment.image(preview)]); e.reply([`识别:网易云音乐,${title}--${desc}`, segment.image(preview)]);
if (!await redis.exists(await this.getRedisKey(e.user_id))) { if (!(await redis.exists(await this.getRedisKey(e.user_id)))) {
this.downloadMp3(`music.163.com/song/media/outer/url?id=${id}`, 'follow').then(path => { this.downloadMp3(`music.163.com/song/media/outer/url?id=${id}`, "follow")
Bot.acquireGfs(e.group_id).upload(fs.readFileSync(path), '/', `${title.replace(/[\/\?<>\\:\*\|".… ]/g, '')}.mp3`) .then(path => {
}) Bot.acquireGfs(e.group_id).upload(
fs.readFileSync(path),
"/",
`${title.replace(/[\/\?<>\\:\*\|".… ]/g, "")}.mp3`,
);
})
.catch(err => { .catch(err => {
console.error(`下载音乐失败,错误信息为: ${err.message}`); console.error(`下载音乐失败,错误信息为: ${err.message}`);
}); });
@ -144,16 +174,21 @@ export class neteasepro extends plugin {
} }
// 检查当前歌曲是否可用 // 检查当前歌曲是否可用
const checkOne = await checkMusic(id); const checkOne = await checkMusic(id);
if (checkOne.success === 'false') { if (checkOne.success === "false") {
e.reply(checkOne.message); e.reply(checkOne.message);
return true; return true;
} }
const userInfo = await this.aopBefore(e) const userInfo = await this.aopBefore(e);
// 可用,开始下载 // 可用,开始下载
const userDownloadUrl = (await getSong(id, await userInfo.cookie))[0].url const userDownloadUrl = (await getSong(id, await userInfo.cookie))[0].url;
await this.downloadMp3(userDownloadUrl).then(path => { await this.downloadMp3(userDownloadUrl)
Bot.acquireGfs(e.group_id).upload(fs.readFileSync(path), '/', `${title.replace(/[\/\?<>\\:\*\|".… ]/g, '')}.mp3`) .then(path => {
}) Bot.acquireGfs(e.group_id).upload(
fs.readFileSync(path),
"/",
`${title.replace(/[\/\?<>\\:\*\|".… ]/g, "")}.mp3`,
);
})
.catch(err => { .catch(err => {
console.error(`下载音乐失败,错误信息为: ${err.message}`); console.error(`下载音乐失败,错误信息为: ${err.message}`);
}); });
@ -171,7 +206,7 @@ export class neteasepro extends plugin {
return ""; return "";
} }
// 解析cookie // 解析cookie
userInfo.cookie = store2ha1(cookie) userInfo.cookie = store2ha1(cookie);
return userInfo; return userInfo;
} }
@ -185,7 +220,7 @@ export class neteasepro extends plugin {
}, },
responseType: "stream", responseType: "stream",
}) })
.then((resp) => { .then(resp => {
const filepath = "./netease_qr.jpg"; const filepath = "./netease_qr.jpg";
const writer = fs.createWriteStream(filepath); const writer = fs.createWriteStream(filepath);
resp.data.pipe(writer); resp.data.pipe(writer);
@ -201,19 +236,21 @@ export class neteasepro extends plugin {
let timer; let timer;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
timer = setInterval(async () => { timer = setInterval(async () => {
const statusRes = await getCookies(key) const statusRes = await getCookies(key);
console.log(statusRes) console.log(statusRes);
if (statusRes.code === 800) { if (statusRes.code === 800) {
clearInterval(timer) clearInterval(timer);
reject('二维码已过期,请重新获取') reject("二维码已过期,请重新获取");
} }
if (statusRes.code === 803) { if (statusRes.code === 803) {
// 这一步会返回cookie // 这一步会返回cookie
clearInterval(timer) clearInterval(timer);
const cookie = statusRes.cookie; const cookie = statusRes.cookie;
resolve(/__csrf=[0-9a-z]+;/.exec(cookie)[0] + /MUSIC_U=[0-9a-z]+;/.exec(cookie)[0]); resolve(
/__csrf=[0-9a-z]+;/.exec(cookie)[0] + /MUSIC_U=[0-9a-z]+;/.exec(cookie)[0],
);
} }
}, 3000) }, 3000);
}); });
} }
@ -223,32 +260,31 @@ export class neteasepro extends plugin {
* @param redirect * @param redirect
* @returns {Promise<unknown>} * @returns {Promise<unknown>}
*/ */
async downloadMp3(mp3Url, redirect='manual') { async downloadMp3(mp3Url, redirect = "manual") {
return fetch(mp3Url, { return fetch(mp3Url, {
headers: { headers: {
"User-Agent": "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", "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",
}, },
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`;
const path = `./data/rcmp4/${this.e.group_id || this.e.user_id}/temp.mp3` 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) => { fileStream.on("finish", () => {
fileStream.on("finish", () => { fileStream.close(() => {
fileStream.close(() => { resolve(path);
resolve(path);
});
});
fileStream.on("error", err => {
fs.unlink(path, () => {
reject(err);
});
}); });
}); });
}) fileStream.on("error", err => {
fs.unlink(path, () => {
reject(err);
});
});
});
});
} }
// 获取redis的key // 获取redis的key