Search in sources :

Example 11 with Track

use of se.michaelthelin.spotify.model_objects.specification.Track in project spotifybot by NotEchoDE.

the class PlayAddCommand method exec.

@SneakyThrows
@Override
public void exec(String userName, String id, UserLevel userLevel, String[] args) {
    ModuleEntry sPlayAdd = getModule().getEntry("sPlayAdd");
    if (!userLevel.isHigherOrEquals(sPlayAdd.getUserLevel())) {
        sendMessage(getModule(ModuleType.SYSTEM).getEntry("noPerms"), "$USER", userName, "$ROLE", sPlayAdd.getUserLevel().getPrettyName());
        return;
    }
    StringBuilder searchQuery = new StringBuilder();
    if (args.length >= 1)
        for (int i = 0; i < args.length; i++) if (i != 0)
            searchQuery.append(" ");
        else
            searchQuery.append(args[i]);
    else {
        sendMessage(getModule(ModuleType.SYSTEM).getEntry("syntax"), "$USER", userName, "$USAGE", "!sPlayAdd [song]");
        return;
    }
    Paging<Track> search = getRoot().getSpotifyApi().searchTracks(searchQuery.toString()).build().execute();
    if (search.getTotal() == 0) {
        sendMessage(getModule(ModuleType.SONGREQUEST).getEntry("notFound"), "$USER", userName);
        return;
    }
    String uri = search.getItems()[0].getUri();
    CountryCode country = getRoot().getSpotifyApi().getCurrentUsersProfile().build().execute().getCountry();
    Track track = getRoot().getSpotifyApi().getTrack(uri.replace("spotify:track:", "")).build().execute();
    if (Arrays.stream(track.getAvailableMarkets()).noneMatch(countryCode -> countryCode.equals(CountryCode.DE))) {
        sendMessage(getModule(ModuleType.SONGREQUEST).getEntry("notAvailable"), "$USER", userName, "$SONG", track.getName());
        return;
    }
    getRoot().getSpotifyApi().addItemToUsersPlaybackQueue(uri).build().execute();
    sendMessage(sPlayAdd, "$USER", userName, "$SONG", track.getName());
}
Also used : ModuleEntry(de.notecho.spotify.database.user.entities.module.ModuleEntry) CountryCode(com.neovisionaries.i18n.CountryCode) Track(se.michaelthelin.spotify.model_objects.specification.Track) SneakyThrows(lombok.SneakyThrows)

Example 12 with Track

use of se.michaelthelin.spotify.model_objects.specification.Track in project spotifybot by NotEchoDE.

the class SongCommand method exec.

@Override
@SneakyThrows
public void exec(String userName, String id, UserLevel userLevel, String[] args) {
    CurrentlyPlaying currentlyPlaying = getRoot().getSpotifyApi().getUsersCurrentlyPlayingTrack().build().execute();
    if (!currentlyPlaying.getIs_playing()) {
        sendMessage(getModule().getEntry("notPlaying"), "$USER", userName);
        return;
    }
    String uri = SpotifyUtils.getUriFromJson(getRoot().getSpotifyApi().getUsersCurrentlyPlayingTrack().build().getJson());
    Track track = getRoot().getSpotifyApi().getTrack(SpotifyUtils.getIdFromUri(uri)).build().execute();
    sendMessage(getModule().getEntry("playingSong"), "$USER", userName, "$SONG", track.getName(), "$ARTISTS", SpotifyUtils.getArtists(track));
}
Also used : CurrentlyPlaying(se.michaelthelin.spotify.model_objects.miscellaneous.CurrentlyPlaying) Track(se.michaelthelin.spotify.model_objects.specification.Track) SneakyThrows(lombok.SneakyThrows)

Example 13 with Track

use of se.michaelthelin.spotify.model_objects.specification.Track in project aiode by robinfriedli.

the class SpotifyTrackResultHandler method getBestResult.

@SuppressWarnings("OptionalGetWithoutIsPresent")
public Track getBestResult(String searchTerm, Collection<Track> tracks) {
    Map<String, Long> playbackCountWithArtistId = getPlaybackCountForArtists(tracks);
    String trackName = extractSearchedTrackName(searchTerm, tracks).toLowerCase();
    LevenshteinDistance levenshteinDistance = LevenshteinDistance.getDefaultInstance();
    long bestArtistScore = playbackCountWithArtistId.values().stream().mapToLong(l -> l).max().orElse(0);
    int bestPopularity = tracks.stream().mapToInt(Track::getPopularity).max().orElse(0);
    int maxEditDistance = tracks.stream().mapToInt(t -> levenshteinDistance.apply(trackName, t.getName().toLowerCase())).max().orElse(0);
    // the importance of the artist score should be lower if the best artist was only played a few times
    int maxArtistScore = bestArtistScore > 100 ? 10 : (int) (bestArtistScore * 10 / 100);
    Multimap<Integer, Track> tracksByScore = HashMultimap.create();
    for (Track track : tracks) {
        long maxArtistCount = Arrays.stream(track.getArtists()).mapToLong(a -> {
            Long artistCount = playbackCountWithArtistId.get(a.getId());
            return artistCount != null ? artistCount : 0;
        }).max().orElse(0);
        int artistScore = bestArtistScore == 0 ? maxArtistScore : (int) (maxArtistCount * maxArtistScore / bestArtistScore);
        int popularityScore = bestPopularity == 0 ? 10 : track.getPopularity() * 10 / bestPopularity;
        String name = track.getName().toLowerCase();
        int editDistance = levenshteinDistance.apply(trackName, name);
        int editDistanceScore = maxEditDistance == 0 ? 10 : 10 - (editDistance * 10 / maxEditDistance);
        if (name.contains(trackName) || trackName.contains(name)) {
            editDistanceScore += 10;
        }
        int totalScore = artistScore + popularityScore + editDistanceScore;
        tracksByScore.put(totalScore, track);
    }
    int bestScore = tracksByScore.keySet().stream().mapToInt(k -> k).max().getAsInt();
    return tracksByScore.get(bestScore).stream().max(Comparator.comparing(Track::getPopularity)).get();
}
Also used : BigInteger(java.math.BigInteger) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) Track(se.michaelthelin.spotify.model_objects.specification.Track)

Example 14 with Track

use of se.michaelthelin.spotify.model_objects.specification.Track in project aiode by robinfriedli.

the class SetRedirectedSpotifyTrackNameTask method migrate.

private void migrate(Context context, SpotifyApi spotifyApi) throws IOException, SpotifyWebApiException, ParseException {
    for (XmlElement playlist : context.query(tagName("playlist")).collect()) {
        Map<String, XmlElement> itemsToMigrate = new HashMap<>();
        for (XmlElement playlistItem : playlist.getSubElements()) {
            if (playlistItem.hasAttribute("redirectedSpotifyId") && !playlistItem.hasAttribute("spotifyTrackName")) {
                String trackId = playlistItem.getAttribute("redirectedSpotifyId").getValue();
                itemsToMigrate.put(trackId, playlistItem);
            }
        }
        List<List<String>> batches = Lists.partition(Lists.newArrayList(itemsToMigrate.keySet()), 50);
        for (List<String> batch : batches) {
            Track[] tracks = spotifyApi.getSeveralTracks(batch.toArray(new String[0])).build().execute();
            for (Track track : tracks) {
                XmlElement playlistItem = itemsToMigrate.get(track.getId());
                playlistItem.setAttribute("spotifyTrackName", track.getName());
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) XmlElement(net.robinfriedli.jxp.api.XmlElement) List(java.util.List) Track(se.michaelthelin.spotify.model_objects.specification.Track)

Example 15 with Track

use of se.michaelthelin.spotify.model_objects.specification.Track in project aiode by robinfriedli.

the class AbstractPlayableLoadingCommand method loadSpotifyAlbum.

private void loadSpotifyAlbum(AudioManager audioManager) throws Exception {
    int limit = getArgumentValueWithTypeOrElse("select", Integer.class, 20);
    Callable<List<AlbumSimplified>> albumLoadCallable = () -> getSpotifyService().searchAlbum(getCommandInput(), argumentSet("own"), limit);
    List<AlbumSimplified> albums;
    if (argumentSet("own")) {
        albums = runWithLogin(albumLoadCallable);
    } else {
        albums = runWithCredentials(albumLoadCallable);
    }
    if (albums.size() == 1) {
        AlbumSimplified album = albums.get(0);
        List<Track> tracks = runWithCredentials(() -> getSpotifyService().getAlbumTracks(album.getId()));
        PlayableFactory playableFactory = audioManager.createPlayableFactory(getSpotifyService(), trackLoadingExecutor);
        List<Playable> playables = playableFactory.createPlayables(shouldRedirectSpotify(), tracks);
        handleResults(playables);
        loadedAlbum = album;
    } else if (albums.isEmpty()) {
        throw new NoSpotifyResultsFoundException(String.format("No albums found for '%s'", getCommandInput()));
    } else {
        askQuestion(albums, AlbumSimplified::getName, album -> StringList.create(album.getArtists(), ArtistSimplified::getName).toSeparatedString(", "));
    }
}
Also used : StringList(net.robinfriedli.stringlist.StringList) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) PlayableFactory(net.robinfriedli.aiode.audio.PlayableFactory) UrlPlayable(net.robinfriedli.aiode.audio.UrlPlayable) YouTubePlaylist(net.robinfriedli.aiode.audio.youtube.YouTubePlaylist) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) Playable(net.robinfriedli.aiode.audio.Playable) Episode(se.michaelthelin.spotify.model_objects.specification.Episode) Callable(java.util.concurrent.Callable) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) Lists(com.google.common.collect.Lists) Playlist(net.robinfriedli.aiode.entities.Playlist) YouTubeVideo(net.robinfriedli.aiode.audio.youtube.YouTubeVideo) SearchEngine(net.robinfriedli.aiode.util.SearchEngine) Track(se.michaelthelin.spotify.model_objects.specification.Track) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) SpotifyUri(net.robinfriedli.aiode.audio.spotify.SpotifyUri) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) ArtistSimplified(se.michaelthelin.spotify.model_objects.specification.ArtistSimplified) CommandManager(net.robinfriedli.aiode.command.CommandManager) AudioPlayback(net.robinfriedli.aiode.audio.AudioPlayback) IOException(java.io.IOException) AudioManager(net.robinfriedli.aiode.audio.AudioManager) NoSpotifyResultsFoundException(net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) UrlValidator(org.apache.commons.validator.routines.UrlValidator) Aiode(net.robinfriedli.aiode.Aiode) ShowSimplified(se.michaelthelin.spotify.model_objects.specification.ShowSimplified) List(java.util.List) AudioTrackLoader(net.robinfriedli.aiode.audio.AudioTrackLoader) SpotifyTrackResultHandler(net.robinfriedli.aiode.audio.spotify.SpotifyTrackResultHandler) SpotifyService(net.robinfriedli.aiode.audio.spotify.SpotifyService) CommandContext(net.robinfriedli.aiode.command.CommandContext) PlaylistSimplified(se.michaelthelin.spotify.model_objects.specification.PlaylistSimplified) AlbumSimplified(se.michaelthelin.spotify.model_objects.specification.AlbumSimplified) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) TrackLoadingExecutor(net.robinfriedli.aiode.audio.exec.TrackLoadingExecutor) YouTubeService(net.robinfriedli.aiode.audio.youtube.YouTubeService) PlayableFactory(net.robinfriedli.aiode.audio.PlayableFactory) UrlPlayable(net.robinfriedli.aiode.audio.UrlPlayable) Playable(net.robinfriedli.aiode.audio.Playable) AlbumSimplified(se.michaelthelin.spotify.model_objects.specification.AlbumSimplified) StringList(net.robinfriedli.stringlist.StringList) List(java.util.List) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) Track(se.michaelthelin.spotify.model_objects.specification.Track) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) NoSpotifyResultsFoundException(net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException)

Aggregations

Track (se.michaelthelin.spotify.model_objects.specification.Track)17 List (java.util.List)8 SpotifyTrack (net.robinfriedli.aiode.audio.spotify.SpotifyTrack)8 IOException (java.io.IOException)7 StringList (net.robinfriedli.stringlist.StringList)7 Episode (se.michaelthelin.spotify.model_objects.specification.Episode)7 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)6 YouTubePlaylist (net.robinfriedli.aiode.audio.youtube.YouTubePlaylist)6 AlbumSimplified (se.michaelthelin.spotify.model_objects.specification.AlbumSimplified)6 PlaylistSimplified (se.michaelthelin.spotify.model_objects.specification.PlaylistSimplified)6 AudioPlaylist (com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)5 SneakyThrows (lombok.SneakyThrows)5 YouTubeVideo (net.robinfriedli.aiode.audio.youtube.YouTubeVideo)5 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)5 NoResultsFoundException (net.robinfriedli.aiode.exceptions.NoResultsFoundException)5 AudioItem (com.sedmelluq.discord.lavaplayer.track.AudioItem)4 YouTubeService (net.robinfriedli.aiode.audio.youtube.YouTubeService)4 NoSpotifyResultsFoundException (net.robinfriedli.aiode.exceptions.NoSpotifyResultsFoundException)4 ParseException (org.apache.hc.core5.http.ParseException)4 SpotifyWebApiException (se.michaelthelin.spotify.exceptions.SpotifyWebApiException)4