vk-music-dl/index.js

107 lines
3.8 KiB
JavaScript
Raw Normal View History

2020-07-01 22:22:11 +02:00
const Cheerio = require('cheerio');
const { promises: fs, createWriteStream } = require('fs');
2020-07-01 22:22:11 +02:00
const debug = require('debug')('vk-music-dl');
const vm = require('vm');
2020-07-01 22:23:59 +02:00
const Promise = require('bluebird');
const _ = require('lodash');
const leven = require('leven');
const { URL, URLSearchParams } = require('url');
const fetch = require('node-fetch');
const m3u = require('m3u');
2020-07-01 22:22:11 +02:00
require('dotenv').config();
async function getSpotifyPlaylist(){
const spotifyPlaylistPageContent = await fs.readFile('./test.html');
const $ = Cheerio.load(spotifyPlaylistPageContent);
let playlist;
$('script').each(function(i, elem){
const content = $(this).html();
if(/Spotify.Entity/.test(content)){
playlist = vm.runInNewContext(content);
}
});
return playlist;
}
2020-07-01 22:23:59 +02:00
async function searchOnVkMusic(query){
const url = new URL('https://api.vk.com/method/audio.search');
url.search = new URLSearchParams({
v: '5.71',
access_token: process.env.ACCESS_TOKEN,
q: query,
count: 200,
}).toString();
return await fetch(url, {
2020-07-01 22:22:11 +02:00
headers: {
'User-Agent': 'KateMobileAndroid/48.2 lite-433 (Android 8.1.0; SDK 27; arm64-v8a; Google Pixel 2 XL; en)',
}
})
.then(res => res.json())
.then(responseBody => {
if(responseBody.error){
throw _.assign(responseBody.error, new Error(responseBody.error.error_msg));
} else {
return responseBody;
}
2020-07-01 22:22:11 +02:00
});
}
2020-07-01 22:23:59 +02:00
function matchScore(spotifyMetas, vkmusicMetas){
const originalArtistNames = _.map(spotifyMetas.artists, 'name').join(', ').toLowerCase();
const originalTitle = spotifyMetas.name.toLowerCase();
const originalDuration = Math.round(spotifyMetas.duration_ms/1000);
const matchArtistScore = 1 - (leven(originalArtistNames, vkmusicMetas.artist.toLowerCase()) / Math.max(originalArtistNames.length, vkmusicMetas.artist.length));
const matchTitleScore = 1 - (leven(originalTitle, vkmusicMetas.title.toLowerCase()) / Math.max(originalTitle.length, vkmusicMetas.title.length));
const matchDurationScore = 1 - (Math.abs(originalDuration - vkmusicMetas.duration) / originalDuration); // TODO this can return more than 1 or less than 0
2020-07-01 22:23:59 +02:00
debug('matchArtistScore=%f matchTitleScore=%f matchDurationScore=%f', matchArtistScore, matchTitleScore, matchDurationScore);
return matchArtistScore + matchTitleScore + matchDurationScore;
}
async function generateM3U8Playlist(filesWithMetas){
const m3uWriter = m3u.extendedWriter();
filesWithMetas.forEach(fileWithMetas => m3uWriter.file(fileWithMetas.path, fileWithMetas.duration, `${fileWithMetas.artist} - ${fileWithMetas.title}`));
await fs.writeFile(`playlist.m3u8`, m3uWriter.toString());
}
async function main(){
2020-07-01 22:23:59 +02:00
const playlist = await getSpotifyPlaylist();
const vkPlaylist = await Promise.map(playlist.tracks.items, async ({track}) => {
2020-07-01 22:23:59 +02:00
const artistNames = _.map(track.artists, 'name').join(', ');
debug('%s - %s', track.name, artistNames);
const { response } = await searchOnVkMusic(`${artistNames} ${track.name}`);
debug('response=%O', response);
const bestMatch = _.chain(response.items).map((item) => {
item.score = matchScore(track, item);
return item;
}).sortBy('score').last().value();
debug('bestMatch=%O', bestMatch);
if(!bestMatch){
console.log(`You are on your own for ${track.name} - ${artistNames}`);
return;
}
bestMatch.path = `${bestMatch.artist} - ${bestMatch.title}.mp3`;
await fs.access(bestMatch.path).catch(async () => {
await fetch(bestMatch.url).then(res => {
res.body.pipe(createWriteStream(bestMatch.path));
});
debug('Done downloading');
});
return bestMatch;
}, {concurrency: 1});
await generateM3U8Playlist(_.compact(vkPlaylist));
}
//main().catch(err => console.error(err));
async function test(query){
const { response } = await searchOnVkMusic(query);
console.log(response);
2020-07-01 22:22:11 +02:00
}
test(process.argv[2]);