-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
78 lines (50 loc) · 2.05 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const SpotifyAPI = require('spotify-web-api-node');
const YTMusic = require('ytmusic-api');
async function SpotifyToYouTubeMusic({ clientID, clientSecret, accessToken, ytMusicUrl }) {
// Check Client ID / Client Secret
if (!clientID) throw new Error('You need to provide a Client ID');
if (!clientSecret) throw new Error('You need to provide a Client Secret');
// Spotify API
const spotifyAPI = new SpotifyAPI({
clientId: clientID,
clientSecret: clientSecret
});
if (!accessToken || accessToken === '') spotifyAPI.setAccessToken((await spotifyAPI.clientCredentialsGrant()).body.access_token);
else spotifyAPI.setAccessToken(accessToken);
// YouTube Music API
const ytmusic = new YTMusic();
await ytmusic.initialize();
// Get All
return async function get(spotifyID) {
// Check ID
if (!spotifyID || spotifyID === '') throw new Error('You need to provide a Spotify Track!');
// Check Array
let isArray = true;
if (!Array.isArray(spotifyID)) {
spotifyID = [spotifyID];
isArray = false;
}
// Get Track(s)
const IDs = spotifyID.map(track => track
.replace('spotify:track:','')
.replace('https://open.spotify.com/track/','')
.replace('https://api.spotify.com/v1/tracks/',''))
.map(track => track.includes('?si=') ? track.split('?si=')[0] : track);
const { tracks } = (await spotifyAPI.getTracks(IDs)).body;
if (tracks[0] === null) throw new Error('Only Spotify Tracks are supported!');
// Get Song(s)
let ytList = [];
for (let i = 0; i < tracks.length; i++) {
// Search on YouTube Music
let track = tracks[i];
let content = await ytmusic.searchSongs(`${track.name} ${track.artists.map(artist => artist.name).join(' ')}`);
content = content.filter(song => song?.artist?.name === track.artists[0].name);
// Add YouTube URL
content.length === 0 ? ytList.push(null) : ytList.push(`https://${ytMusicUrl ? 'music.' : ''}youtube.com/watch?v=${content[0].videoId}`);
}
// Return Result(s)
ytList = isArray ? ytList : ytList[0];
return ytList;
};
}
module.exports = SpotifyToYouTubeMusic;