Search in sources :

Example 1 with StringList

use of net.robinfriedli.stringlist.StringList in project aiode by robinfriedli.

the class MessageService method separateMessage.

private List<String> separateMessage(String message) {
    List<String> outputParts = Lists.newArrayList();
    StringList paragraphs = StringList.separateString(message, "\n");
    for (int i = 0; i < paragraphs.size(); i++) {
        String paragraph = paragraphs.get(i);
        if (paragraph.length() + System.lineSeparator().length() < limit) {
            // check that paragraph is not an empty line
            if (!paragraph.isBlank()) {
                if (i < paragraphs.size() - 1)
                    paragraph = paragraph + System.lineSeparator();
                fillPart(outputParts, paragraph);
            }
        } else {
            // if the paragraph is too long separate into sentences
            StringList sentences = StringList.separateString(paragraph, "\\. ");
            for (String sentence : sentences) {
                if (sentence.length() < limit) {
                    fillPart(outputParts, sentence);
                } else {
                    // if the sentence is too long split into words
                    StringList words = StringList.separateString(sentence, " ");
                    for (String word : words) {
                        if (word.length() < limit) {
                            fillPart(outputParts, word);
                        } else {
                            StringList chars = StringList.splitChars(word);
                            for (String charString : chars) {
                                fillPart(outputParts, charString);
                            }
                        }
                    }
                }
            }
        }
    }
    return outputParts;
}
Also used : StringList(net.robinfriedli.stringlist.StringList)

Example 2 with StringList

use of net.robinfriedli.stringlist.StringList in project aiode by robinfriedli.

the class UpdateCommand method getInputStreamString.

private String getInputStreamString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringList lineList = StringList.create();
    String s;
    while ((s = bufferedReader.readLine()) != null) {
        lineList.add(s);
    }
    return lineList.toSeparatedString(System.lineSeparator());
}
Also used : InputStreamReader(java.io.InputStreamReader) StringList(net.robinfriedli.stringlist.StringList) BufferedReader(java.io.BufferedReader)

Example 3 with StringList

use of net.robinfriedli.stringlist.StringList in project aiode by robinfriedli.

the class AbstractCommand method splitInlineArgument.

@Deprecated
protected Pair<String, String> splitInlineArgument(String part, String argument) {
    StringList words = StringList.createWithRegex(part, " ");
    List<Integer> positions = words.findPositionsOf("$" + argument, true);
    if (positions.isEmpty()) {
        throw new InvalidCommandException("Expected inline argument: " + argument);
    }
    int position = positions.get(0);
    if (position == 0 || position == words.size() - 1) {
        throw new InvalidCommandException("No input before or after inline argument: " + argument);
    }
    String left = words.subList(0, position).toSeparatedString(" ");
    String right = words.subList(position + 1, words.size()).toSeparatedString(" ");
    if (left.isBlank() || right.isBlank()) {
        throw new InvalidCommandException("No input before or after inline argument: " + argument);
    }
    return Pair.of(left.trim(), right.trim());
}
Also used : InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) StringList(net.robinfriedli.stringlist.StringList)

Example 4 with StringList

use of net.robinfriedli.stringlist.StringList in project aiode by robinfriedli.

the class RemoveCommand method doRun.

@Override
public void doRun() {
    Session session = getContext().getSession();
    String playlistName = getArgumentValue("from");
    Playlist playlist = SearchEngine.searchLocalList(session, playlistName);
    if (playlist == null) {
        throw new NoResultsFoundException(String.format("No local list found for '%s'", playlistName));
    } else if (playlist.isEmpty()) {
        throw new InvalidCommandException("Playlist is empty");
    }
    if (argumentSet("index")) {
        StringList indices = StringList.createWithRegex(getCommandInput(), "-");
        if (indices.size() == 1 || indices.size() == 2) {
            indices.applyForEach(String::trim);
            if (indices.size() == 1) {
                int index = parse(indices.get(0));
                checkIndex(index, playlist);
                invoke(() -> session.delete(playlist.getItemsSorted().get(index - 1)));
            } else {
                int start = parse(indices.get(0));
                int end = parse(indices.get(1));
                checkIndex(start, playlist);
                checkIndex(end, playlist);
                if (end <= start) {
                    throw new InvalidCommandException("End index needs to be greater than start.");
                }
                invoke(() -> playlist.getItemsSorted().subList(start - 1, end).forEach(session::delete));
            }
        } else {
            throw new InvalidCommandException("Expected one or two indices but found " + indices.size());
        }
    } else {
        List<PlaylistItem> playlistItems = SearchEngine.searchPlaylistItems(playlist, getCommandInput());
        if (playlistItems.size() == 1) {
            invoke(() -> session.delete(playlistItems.get(0)));
        } else if (playlistItems.isEmpty()) {
            throw new NoResultsFoundException(String.format("No tracks found for '%s' on list '%s'", getCommandInput(), playlistName));
        } else {
            askQuestion(playlistItems, PlaylistItem::display, item -> valueOf(item.getIndex() + 1));
        }
    }
}
Also used : PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) StringList(net.robinfriedli.stringlist.StringList) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) CommandManager(net.robinfriedli.aiode.command.CommandManager) Collection(java.util.Collection) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) Session(org.hibernate.Session) List(java.util.List) Playlist(net.robinfriedli.aiode.entities.Playlist) AbstractCommand(net.robinfriedli.aiode.command.AbstractCommand) CommandContext(net.robinfriedli.aiode.command.CommandContext) SearchEngine(net.robinfriedli.aiode.util.SearchEngine) String(java.lang.String) CommandContribution(net.robinfriedli.aiode.entities.xml.CommandContribution) Playlist(net.robinfriedli.aiode.entities.Playlist) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) InvalidCommandException(net.robinfriedli.aiode.exceptions.InvalidCommandException) StringList(net.robinfriedli.stringlist.StringList) String(java.lang.String) PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) Session(org.hibernate.Session)

Example 5 with StringList

use of net.robinfriedli.stringlist.StringList in project aiode by robinfriedli.

the class YouTubeService method getBestMatch.

private Video getBestMatch(List<Video> videos, SpotifyTrack spotifyTrack, StringList artists) {
    Video video;
    int size = videos.size();
    if (size == 1) {
        video = videos.get(0);
    } else {
        Map<Integer, Video> videosByScore = new HashMap<>();
        Map<Video, Integer> editDistanceMap = new HashMap<>();
        long[] viewCounts = new long[size];
        for (int i = 0; i < size; i++) {
            Video v = videos.get(i);
            viewCounts[i] = getViewCount(v);
            editDistanceMap.put(v, getBestEditDistance(spotifyTrack, v));
        }
        int index = 0;
        for (Video v : videos) {
            int artistMatchScore = 0;
            if (artists.stream().anyMatch(a -> {
                String artist = a.toLowerCase();
                String artistNoSpace = artist.replaceAll(" ", "");
                VideoSnippet snippet = v.getSnippet();
                if (snippet == null) {
                    return false;
                }
                String channelTitle = snippet.getChannelTitle();
                if (channelTitle == null) {
                    return false;
                }
                String channel = channelTitle.toLowerCase();
                String channelNoSpace = channel.replace(" ", "");
                return channel.contains(artist) || artist.contains(channel) || channelNoSpace.contains(artistNoSpace) || artistNoSpace.contains(channelNoSpace);
            })) {
                artistMatchScore = ARTIST_MATCH_SCORE_MULTIPLIER * size;
            }
            long viewCount = getViewCount(v);
            int editDistance = editDistanceMap.get(v);
            long viewRank = Arrays.stream(viewCounts).filter(c -> viewCount < c).count();
            long editDistanceRank = editDistanceMap.values().stream().filter(d -> d < editDistance).count();
            int viewScore = VIEW_SCORE_MULTIPLIER * (int) (size - viewRank);
            int editDistanceScore = EDIT_DISTANCE_SCORE_MULTIPLIER * (int) (size - editDistanceRank);
            int indexScore = INDEX_SCORE_MULTIPLIER * (size - index);
            int totalScore = artistMatchScore + viewScore + editDistanceScore + indexScore;
            videosByScore.putIfAbsent(totalScore, v);
            ++index;
        }
        @SuppressWarnings("OptionalGetWithoutIsPresent") int bestScore = videosByScore.keySet().stream().mapToInt(k -> k).max().getAsInt();
        video = videosByScore.get(bestScore);
    }
    return video;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) Arrays(java.util.Arrays) StringList(net.robinfriedli.stringlist.StringList) LoggerFactory(org.slf4j.LoggerFactory) VideoListResponse(com.google.api.services.youtube.model.VideoListResponse) SearchResult(com.google.api.services.youtube.model.SearchResult) CurrentYouTubeQuotaUsage(net.robinfriedli.aiode.entities.CurrentYouTubeQuotaUsage) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) BigInteger(java.math.BigInteger) AudioTrackInfo(com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) UnavailableResourceException(net.robinfriedli.aiode.exceptions.UnavailableResourceException) VideoContentDetails(com.google.api.services.youtube.model.VideoContentDetails) LevenshteinDistance(org.apache.commons.text.similarity.LevenshteinDistance) LoggingThreadFactory(net.robinfriedli.aiode.concurrent.LoggingThreadFactory) Playlist(com.google.api.services.youtube.model.Playlist) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) List(java.util.List) AbstractShutdownable(net.robinfriedli.aiode.boot.AbstractShutdownable) StaticSessionProvider(net.robinfriedli.aiode.persist.StaticSessionProvider) VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) CommandRuntimeException(net.robinfriedli.aiode.exceptions.CommandRuntimeException) HibernateComponent(net.robinfriedli.aiode.boot.configurations.HibernateComponent) IntStream(java.util.stream.IntStream) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) PlayableFactory(net.robinfriedli.aiode.audio.PlayableFactory) SpotifyTrack(net.robinfriedli.aiode.audio.spotify.SpotifyTrack) Session(org.hibernate.Session) DependsOn(org.springframework.context.annotation.DependsOn) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) QueueCommand(net.robinfriedli.aiode.command.commands.playback.QueueCommand) PlaylistItem(com.google.api.services.youtube.model.PlaylistItem) Video(com.google.api.services.youtube.model.Video) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) PlayCommand(net.robinfriedli.aiode.command.commands.playback.PlayCommand) Logger(org.slf4j.Logger) ArtistSimplified(se.michaelthelin.spotify.model_objects.specification.ArtistSimplified) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) HibernateInvoker(net.robinfriedli.aiode.function.HibernateInvoker) VideoStatistics(com.google.api.services.youtube.model.VideoStatistics) AudioItem(com.sedmelluq.discord.lavaplayer.track.AudioItem) Aiode(net.robinfriedli.aiode.Aiode) PlaylistItemListResponse(com.google.api.services.youtube.model.PlaylistItemListResponse) ShowSimplified(se.michaelthelin.spotify.model_objects.specification.ShowSimplified) Component(org.springframework.stereotype.Component) ChronoUnit(java.time.temporal.ChronoUnit) AudioTrackLoader(net.robinfriedli.aiode.audio.AudioTrackLoader) EagerFetchQueue(net.robinfriedli.aiode.concurrent.EagerFetchQueue) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) LockModeType(javax.persistence.LockModeType) VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) HashMap(java.util.HashMap) Video(com.google.api.services.youtube.model.Video)

Aggregations

StringList (net.robinfriedli.stringlist.StringList)10 InvalidCommandException (net.robinfriedli.aiode.exceptions.InvalidCommandException)5 AudioItem (com.sedmelluq.discord.lavaplayer.track.AudioItem)4 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)4 SpotifyTrack (net.robinfriedli.aiode.audio.spotify.SpotifyTrack)4 AudioPlaylist (com.sedmelluq.discord.lavaplayer.track.AudioPlaylist)3 IOException (java.io.IOException)3 List (java.util.List)3 Nullable (javax.annotation.Nullable)3 NoResultsFoundException (net.robinfriedli.aiode.exceptions.NoResultsFoundException)3 ShowSimplified (se.michaelthelin.spotify.model_objects.specification.ShowSimplified)3 SearchResult (com.google.api.services.youtube.model.SearchResult)2 Video (com.google.api.services.youtube.model.Video)2 Strings (com.google.common.base.Strings)2 Lists (com.google.common.collect.Lists)2 FriendlyException (com.sedmelluq.discord.lavaplayer.tools.FriendlyException)2 BigInteger (java.math.BigInteger)2 URI (java.net.URI)2 Collection (java.util.Collection)2 Map (java.util.Map)2