Search in sources :

Example 1 with SpringPropertiesConfig

use of net.robinfriedli.aiode.boot.SpringPropertiesConfig in project aiode by robinfriedli.

the class AnalyticsCommand method doRun.

@Override
public void doRun() {
    ShardManager shardManager = Aiode.get().getShardManager();
    List<Guild> guilds = shardManager.getGuilds();
    Aiode aiode = Aiode.get();
    AudioManager audioManager = aiode.getAudioManager();
    GuildManager guildManager = aiode.getGuildManager();
    SpringPropertiesConfig springPropertiesConfig = aiode.getSpringPropertiesConfig();
    Session session = getContext().getSession();
    Runtime runtime = Runtime.getRuntime();
    int guildCount = guilds.size();
    long playingCount = guilds.stream().map(audioManager::getPlaybackForGuild).filter(AudioPlayback::isPlaying).count();
    long commandCount = session.createQuery("select count(*) from " + CommandHistory.class.getName(), Long.class).uniqueResult();
    long playlistCount = session.createQuery("select count(*) from " + Playlist.class.getName(), Long.class).uniqueResult();
    long trackCount = session.createQuery("select count(*) from " + Song.class.getName(), Long.class).uniqueResult() + session.createQuery("select count(*) from " + Video.class.getName(), Long.class).uniqueResult() + session.createQuery("select count(*) from " + UrlTrack.class.getName(), Long.class).uniqueResult();
    long playedCount = session.createQuery("select count(*) from " + PlaybackHistory.class.getName(), Long.class).uniqueResult();
    // convert to MB by right shifting by 20 bytes (same as dividing by 2^20)
    long maxMemory = runtime.maxMemory() >> 20;
    long allocatedMemory = runtime.totalMemory() >> 20;
    long unallocatedMemory = maxMemory - allocatedMemory;
    long allocFreeMemory = runtime.freeMemory() >> 20;
    long usedMemory = allocatedMemory - allocFreeMemory;
    long totalFreeMemory = maxMemory - usedMemory;
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    int threadCount = threadMXBean.getThreadCount();
    int daemonThreadCount = threadMXBean.getDaemonThreadCount();
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.addField("Guilds", String.valueOf(guildCount), true);
    embedBuilder.addField("Guilds active", String.valueOf(guildManager.getActiveGuilds(session).size()), true);
    embedBuilder.addField("Guilds playing now", String.valueOf(playingCount), true);
    embedBuilder.addField("Total commands entered", String.valueOf(commandCount), true);
    embedBuilder.addField("Saved playlists", String.valueOf(playlistCount), true);
    embedBuilder.addField("Saved tracks", String.valueOf(trackCount), true);
    embedBuilder.addField("Total tracks played", String.valueOf(playedCount), true);
    embedBuilder.addField("Thread count", String.format("%d (%d daemons)", threadCount, daemonThreadCount), true);
    String shardRange = springPropertiesConfig.getApplicationProperty("aiode.preferences.shard_range");
    if (!Strings.isNullOrEmpty(shardRange)) {
        embedBuilder.addField("Shards", shardRange, true);
    }
    embedBuilder.addField("Memory (in MB)", "Total: " + maxMemory + System.lineSeparator() + "Allocated: " + allocatedMemory + System.lineSeparator() + "Unallocated: " + unallocatedMemory + System.lineSeparator() + "Free allocated: " + allocFreeMemory + System.lineSeparator() + "Currently used: " + usedMemory + System.lineSeparator() + "Total free: " + totalFreeMemory, false);
    sendWithLogo(embedBuilder);
}
Also used : CommandHistory(net.robinfriedli.aiode.entities.CommandHistory) ThreadMXBean(java.lang.management.ThreadMXBean) GuildManager(net.robinfriedli.aiode.discord.GuildManager) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Guild(net.dv8tion.jda.api.entities.Guild) Aiode(net.robinfriedli.aiode.Aiode) AudioManager(net.robinfriedli.aiode.audio.AudioManager) Playlist(net.robinfriedli.aiode.entities.Playlist) Song(net.robinfriedli.aiode.entities.Song) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PlaybackHistory(net.robinfriedli.aiode.entities.PlaybackHistory) Video(net.robinfriedli.aiode.entities.Video) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) Session(org.hibernate.Session)

Example 2 with SpringPropertiesConfig

use of net.robinfriedli.aiode.boot.SpringPropertiesConfig in project aiode by robinfriedli.

the class SearchCommand method listLocalList.

private void listLocalList() {
    if (getCommandInput().isBlank()) {
        Session session = getContext().getSession();
        List<Playlist> playlists = getQueryBuilderFactory().find(Playlist.class).build(session).getResultList();
        EmbedBuilder embedBuilder = new EmbedBuilder();
        if (playlists.isEmpty()) {
            embedBuilder.setDescription("No playlists");
        } else {
            EmbedTable table = new EmbedTable(embedBuilder);
            table.addColumn("Playlist", playlists, Playlist::getName);
            table.addColumn("Duration", playlists, playlist -> Util.normalizeMillis(playlist.getDuration()));
            table.addColumn("Items", playlists, playlist -> String.valueOf(playlist.getSize()));
            table.build();
        }
        sendMessage(embedBuilder);
    } else {
        Playlist playlist = SearchEngine.searchLocalList(getContext().getSession(), getCommandInput());
        if (playlist == null) {
            throw new NoResultsFoundException(String.format("No local list found for '%s'", getCommandInput()));
        }
        String createdUserId = playlist.getCreatedUserId();
        String createdUser;
        if (createdUserId.equals("system")) {
            createdUser = playlist.getCreatedUser();
        } else {
            ShardManager shardManager = Aiode.get().getShardManager();
            User userById;
            try {
                userById = shardManager.retrieveUserById(createdUserId).complete();
            } catch (ErrorResponseException e) {
                if (e.getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
                    userById = null;
                } else {
                    throw e;
                }
            }
            createdUser = userById != null ? userById.getName() : playlist.getCreatedUser();
        }
        SpringPropertiesConfig springPropertiesConfig = Aiode.get().getSpringPropertiesConfig();
        String baseUri = springPropertiesConfig.requireApplicationProperty("aiode.server.base_uri");
        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.addField("Name", playlist.getName(), true);
        embedBuilder.addField("Duration", Util.normalizeMillis(playlist.getDuration()), true);
        embedBuilder.addField("Created by", createdUser, true);
        embedBuilder.addField("Tracks", String.valueOf(playlist.getSize()), true);
        embedBuilder.addBlankField(false);
        String url = baseUri + String.format("/list?name=%s&guildId=%s", URLEncoder.encode(playlist.getName(), StandardCharsets.UTF_8), playlist.getGuildId());
        embedBuilder.addField("First tracks:", "[Full list](" + url + ")", false);
        List<PlaylistItem> items = playlist.getItemsSorted();
        Util.appendEmbedList(embedBuilder, items.size() > 5 ? items.subList(0, 5) : items, item -> item.display() + " - " + Util.normalizeMillis(item.getDuration()), "Track - Duration");
        sendWithLogo(embedBuilder);
    }
}
Also used : User(net.dv8tion.jda.api.entities.User) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) YouTubePlaylist(net.robinfriedli.aiode.audio.youtube.YouTubePlaylist) Playlist(net.robinfriedli.aiode.entities.Playlist) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) NoResultsFoundException(net.robinfriedli.aiode.exceptions.NoResultsFoundException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) EmbedTable(net.robinfriedli.aiode.util.EmbedTable) PlaylistItem(net.robinfriedli.aiode.entities.PlaylistItem) Session(org.hibernate.Session)

Example 3 with SpringPropertiesConfig

use of net.robinfriedli.aiode.boot.SpringPropertiesConfig in project aiode by robinfriedli.

the class AbstractPaginationWidget method prepareEmbedBuilderForPage.

private EmbedBuilder prepareEmbedBuilderForPage() {
    int pageCount = pages.size();
    if (currentPage >= pageCount && !pages.isEmpty()) {
        throw new IllegalStateException(String.format("Current page is out of bounds. Current index: %d; page count: %d", currentPage, pageCount));
    }
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.setTitle(getTitle());
    String description = getDescription();
    if (!Strings.isNullOrEmpty(description)) {
        embedBuilder.setDescription(description);
    }
    Aiode aiode = Aiode.get();
    SpringPropertiesConfig springPropertiesConfig = aiode.getSpringPropertiesConfig();
    String baseUri = springPropertiesConfig.requireApplicationProperty("aiode.server.base_uri");
    String logoUrl = baseUri + "/resources-public/img/aiode-logo-small.png";
    embedBuilder.setFooter(String.format("Page %d of %d", currentPage + 1, Math.max(pageCount, 1)), logoUrl);
    EmbedTable embedTable = new EmbedTable(embedBuilder);
    List<E> page = pages.isEmpty() ? Collections.emptyList() : pages.get(currentPage);
    for (Column<E> column : getColumns()) {
        Function<E, EmbedTable.Group> groupFunction = column.getGroupFunction();
        if (groupFunction != null) {
            embedTable.addColumn(column.getTitle(), page, column.getDisplayFunc(), groupFunction);
        } else {
            embedTable.addColumn(column.getTitle(), page, column.getDisplayFunc());
        }
    }
    embedTable.build();
    return embedBuilder;
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) EmbedTable(net.robinfriedli.aiode.util.EmbedTable) Aiode(net.robinfriedli.aiode.Aiode)

Example 4 with SpringPropertiesConfig

use of net.robinfriedli.aiode.boot.SpringPropertiesConfig in project aiode by robinfriedli.

the class AudioQueue method buildMessageEmbed.

/**
 * Format the current queue as a Discord embed message showing all enabled options, such as shuffle and repeat,
 * the volume and previous 5, the current and the next 5 tracks and also provides a link to view the full queue
 *
 * @return the {@link EmbedBuilder} to build send to Discord with the colour specified by the {@link GuildSpecification}
 * already applied
 */
public EmbedBuilder buildMessageEmbed(AudioPlayback playback, Guild guild) {
    int position = getPosition();
    List<Playable> tracks = getTracks();
    EmbedBuilder embedBuilder = new EmbedBuilder();
    SpringPropertiesConfig springPropertiesConfig = Aiode.get().getSpringPropertiesConfig();
    String baseUri = springPropertiesConfig.requireApplicationProperty("aiode.server.base_uri");
    StringBuilder optionBuilder = new StringBuilder();
    appendIcon(optionBuilder, EmojiConstants.PLAY, playback.isPlaying());
    appendIcon(optionBuilder, EmojiConstants.PAUSE, playback.isPaused());
    appendIcon(optionBuilder, EmojiConstants.SHUFFLE, playback.isShuffle());
    appendIcon(optionBuilder, EmojiConstants.REPEAT, playback.isRepeatAll());
    appendIcon(optionBuilder, EmojiConstants.REPEAT_ONE, playback.isRepeatOne());
    optionBuilder.append(EmojiConstants.VOLUME).append(playback.getVolume());
    embedBuilder.setDescription(optionBuilder.toString());
    String url = baseUri + String.format("/queue?guildId=%s", guild.getId());
    embedBuilder.addField("", "[Full list](" + url + ")", false);
    if (isEmpty()) {
        embedBuilder.addField("", "(emtpy)", false);
    } else {
        StringBuilder prevBuilder = new StringBuilder();
        StringBuilder nextBuilder = new StringBuilder();
        if (position > 0) {
            if (position > 5) {
                prevBuilder.append("...").append(System.lineSeparator());
            }
            List<Playable> previous = listPrevious(5);
            for (Playable prev : previous) {
                appendPlayable(prevBuilder, prev);
            }
        }
        if (!prevBuilder.toString().isEmpty()) {
            embedBuilder.addField("Previous", prevBuilder.toString(), false);
        }
        String currentPosition = Util.normalizeMillis(playback.getCurrentPositionMs());
        Playable current = getCurrent();
        String duration = Util.normalizeMillis(current.durationMs());
        embedBuilder.addField("Current", "| " + current.getDisplayNow() + " - " + currentPosition + " / " + duration, false);
        if (position < tracks.size() - 1) {
            List<Playable> next = listNext(5);
            for (Playable n : next) {
                appendPlayable(nextBuilder, n);
            }
            if (tracks.size() > position + 6) {
                nextBuilder.append("...");
            }
        }
        if (!nextBuilder.toString().isEmpty()) {
            embedBuilder.addField("Next", nextBuilder.toString(), false);
        }
        String albumCoverUrl = current.getAlbumCoverUrl();
        embedBuilder.setThumbnail(Objects.requireNonNullElseGet(albumCoverUrl, () -> baseUri + "/resources-public/img/aiode-logo.png"));
    }
    Color color = StaticSessionProvider.invokeWithSession(session -> {
        GuildSpecification specification = Aiode.get().getGuildManager().getContextForGuild(guild).getSpecification(session);
        return ColorSchemeProperty.getColor(specification);
    });
    embedBuilder.setColor(color);
    return embedBuilder;
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Color(java.awt.Color) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig)

Example 5 with SpringPropertiesConfig

use of net.robinfriedli.aiode.boot.SpringPropertiesConfig in project aiode by robinfriedli.

the class QueueIterator method sendCurrentTrackNotification.

private void sendCurrentTrackNotification(Playable currentTrack) {
    MessageChannel communicationChannel = playback.getCommunicationChannel();
    if (communicationChannel == null) {
        return;
    }
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.addField("Now playing", currentTrack.display(), false);
    if (queue.hasNext()) {
        embedBuilder.addField("Next", queue.getNext().display(), false);
    }
    StringBuilder footerBuilder = new StringBuilder();
    appendIfTrue(footerBuilder, EmojiConstants.SHUFFLE, playback.isShuffle());
    appendIfTrue(footerBuilder, EmojiConstants.REPEAT, playback.isRepeatAll());
    appendIfTrue(footerBuilder, EmojiConstants.REPEAT_ONE, playback.isRepeatOne());
    footerBuilder.append(" | ").append("View the queue using the queue command");
    String albumCoverUrl = currentTrack.getAlbumCoverUrl();
    if (albumCoverUrl == null) {
        SpringPropertiesConfig springPropertiesConfig = Aiode.get().getSpringPropertiesConfig();
        String baseUri = springPropertiesConfig.requireApplicationProperty("aiode.server.base_uri");
        albumCoverUrl = baseUri + "/resources-public/img/aiode-logo-small.png";
    }
    embedBuilder.setFooter(footerBuilder.toString(), albumCoverUrl);
    Guild guild = playback.getGuild();
    Color color = StaticSessionProvider.invokeWithSession(session -> {
        GuildSpecification specification = Aiode.get().getGuildManager().getContextForGuild(guild).getSpecification(session);
        return ColorSchemeProperty.getColor(specification);
    });
    embedBuilder.setColor(color);
    CompletableFuture<Message> futureMessage = messageService.send(embedBuilder.build(), communicationChannel);
    futureMessage.thenAccept(playback::setLastPlaybackNotification);
    audioManager.createNowPlayingWidget(futureMessage, playback);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) Message(net.dv8tion.jda.api.entities.Message) Color(java.awt.Color) GuildSpecification(net.robinfriedli.aiode.entities.GuildSpecification) SpringPropertiesConfig(net.robinfriedli.aiode.boot.SpringPropertiesConfig) Guild(net.dv8tion.jda.api.entities.Guild)

Aggregations

EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)5 SpringPropertiesConfig (net.robinfriedli.aiode.boot.SpringPropertiesConfig)5 Color (java.awt.Color)2 Guild (net.dv8tion.jda.api.entities.Guild)2 ShardManager (net.dv8tion.jda.api.sharding.ShardManager)2 Aiode (net.robinfriedli.aiode.Aiode)2 GuildSpecification (net.robinfriedli.aiode.entities.GuildSpecification)2 Playlist (net.robinfriedli.aiode.entities.Playlist)2 EmbedTable (net.robinfriedli.aiode.util.EmbedTable)2 Session (org.hibernate.Session)2 ThreadMXBean (java.lang.management.ThreadMXBean)1 Message (net.dv8tion.jda.api.entities.Message)1 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)1 User (net.dv8tion.jda.api.entities.User)1 ErrorResponseException (net.dv8tion.jda.api.exceptions.ErrorResponseException)1 AudioManager (net.robinfriedli.aiode.audio.AudioManager)1 YouTubePlaylist (net.robinfriedli.aiode.audio.youtube.YouTubePlaylist)1 GuildManager (net.robinfriedli.aiode.discord.GuildManager)1 CommandHistory (net.robinfriedli.aiode.entities.CommandHistory)1 PlaybackHistory (net.robinfriedli.aiode.entities.PlaybackHistory)1