refactor: split downloader into modules
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
const { API } = require('./config');
|
||||
const { fetchJSON } = require('./network');
|
||||
|
||||
async function searchSongs(keyword, limit = 10) {
|
||||
const res = await fetchJSON(`${API.search}?keyword=${encodeURIComponent(keyword)}&limit=${limit}`);
|
||||
if (res.code !== 200) {
|
||||
console.log('❌ 搜索无结果');
|
||||
return [];
|
||||
}
|
||||
const songs = Array.isArray(res.data) ? res.data : (res.data?.songs || []);
|
||||
if (!songs.length) console.log('❌ 搜索无结果');
|
||||
return songs;
|
||||
}
|
||||
|
||||
async function interactiveSearch(rl, ask) {
|
||||
const keyword = await ask('🔍 搜索关键词: ');
|
||||
if (!keyword.trim()) return null;
|
||||
const results = await searchSongs(keyword.trim(), 10);
|
||||
if (!results.length) return null;
|
||||
|
||||
console.log('\n # 歌曲名 歌手 专辑');
|
||||
console.log(' ' + '─'.repeat(70));
|
||||
results.forEach((song, index) => {
|
||||
const num = String(index + 1).padStart(2);
|
||||
const name = song.name.slice(0, 20).padEnd(22);
|
||||
const artist = song.artists.slice(0, 16).padEnd(18);
|
||||
console.log(` ${num} ${name} ${artist} ${song.album}`);
|
||||
});
|
||||
|
||||
const pick = await ask('\n选择序号 (多个用逗号分隔, 0=取消): ');
|
||||
if (!pick.trim() || pick.trim() === '0') return null;
|
||||
return pick.split(/[,,\s]+/)
|
||||
.map(value => parseInt(value, 10))
|
||||
.filter(value => value >= 1 && value <= results.length)
|
||||
.map(value => results[value - 1]);
|
||||
}
|
||||
|
||||
async function fetchPlaylist(playlistId) {
|
||||
const res = await fetchJSON(`${API.playlist}?id=${playlistId}`);
|
||||
if (!res.data?.tracks?.length) {
|
||||
console.log('❌ 歌单获取失败或为空');
|
||||
return null;
|
||||
}
|
||||
return res.data;
|
||||
}
|
||||
|
||||
module.exports = { searchSongs, interactiveSearch, fetchPlaylist };
|
||||
Reference in New Issue
Block a user