Skip to content

Commit

Permalink
Merge pull request #6 from Kshitiz1403:feature/improved-search
Browse files Browse the repository at this point in the history
feature(spotify): improved spotify to yt search
  • Loading branch information
Kshitiz1403 authored Feb 12, 2024
2 parents c791822 + 0ff15a9 commit 5470e9c
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions src/utils/spotify/trackService.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import playdl, { Spotify, SpotifyPlaylist, SpotifyTrack } from "play-dl";
import playdl from "play-dl";
import { getVideo } from "../youtube/videoService";
import spotifyApi from "./spotifyAPI";
import { ITrack, TypeTrack } from "../../interfaces/spotify/ITrack";
import { IPlaylist, TypePlaylist } from "../../interfaces/spotify/IPlaylist";

const getTrackSearchName = (track: SpotifyApi.SingleTrackResponse) => {
const trackName = track.name;
const artists = track.artists.map((artist) => artist.name).join(", ");
return `${trackName} ${artists}`;
};

const trackToYT = async (trackName: string): Promise<ITrack> => {
const ytSearched = await playdl.search(trackName, { limit: 1 });
const ytURL = ytSearched[0].url;
Expand All @@ -21,6 +27,27 @@ const trackToYT = async (trackName: string): Promise<ITrack> => {
};
};

const trackToYTByID = async (trackID: string): Promise<ITrack> => {
const track = (await spotifyApi.getTrack(trackID)).body;

const ytSearched = await playdl.search(getTrackSearchName(track), {
limit: 1,
});
const ytURL = ytSearched[0].url;
const videoId = ytSearched[0].id;
const videoInfo = await getVideo(videoId);

return {
youtube_url: ytURL,
options: {
videoId,
title: videoInfo.title,
duration: videoInfo.duration,
description: videoInfo.description,
},
};
};

const playlistToYT = async (playlistID: string): Promise<IPlaylist> => {
const tracks = (
await spotifyApi.getPlaylistTracks(playlistID, {
Expand All @@ -30,7 +57,9 @@ const playlistToYT = async (playlistID: string): Promise<IPlaylist> => {
).body;

const promises = [];
tracks.items.map(({ track }) => promises.push(trackToYT(track.name)));
tracks.items.map(({ track }) =>
promises.push(trackToYT(getTrackSearchName(track)))
);

const videos = await Promise.all(promises);

Expand All @@ -44,7 +73,7 @@ const spotifyToYT = async (spotifyURL: string) => {

switch (spotifyResponse.type) {
case "track": {
const track = await trackToYT(spotifyResponse.name);
const track = await trackToYTByID(spotifyResponse.id);
return { type: "VIDEO", ...track } as TypeTrack;
}
case "playlist": {
Expand Down

0 comments on commit 5470e9c

Please sign in to comment.