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());
}
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));
}
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();
}
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());
}
}
}
}
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(", "));
}
}
Aggregations