Search in sources :

Example 1 with GuildManager

use of net.robinfriedli.aiode.discord.GuildManager 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 GuildManager

use of net.robinfriedli.aiode.discord.GuildManager in project aiode by robinfriedli.

the class CleanDbCommand method doClean.

private void doClean(Session session) {
    ShardManager shardManager = Aiode.get().getShardManager();
    Set<String> activeGuildIds = shardManager.getGuilds().stream().map(ISnowflake::getId).collect(Collectors.toSet());
    GuildManager guildManager = Aiode.get().getGuildManager();
    activeGuildIds.addAll(guildManager.getGuildContexts().stream().map(g -> g.getGuild().getId()).collect(Collectors.toSet()));
    CriteriaBuilder cb = session.getCriteriaBuilder();
    Set<Long> stalePlaylistIds = getStalePlaylistIds(cb, activeGuildIds, session);
    Set<Long> staleGuildSpecificationIds = getStaleGuildSpecificationIds(cb, activeGuildIds, session);
    StringBuilder messageBuilder = new StringBuilder();
    if (!stalePlaylistIds.isEmpty()) {
        deleteStalePlaylistItems(cb, stalePlaylistIds, session, Song.class);
        deleteStalePlaylistItems(cb, stalePlaylistIds, session, Video.class);
        deleteStalePlaylistItems(cb, stalePlaylistIds, session, UrlTrack.class);
        deleteStalePlaylists(cb, stalePlaylistIds, session);
        messageBuilder.append("Cleared ").append(stalePlaylistIds.size()).append(" playlists").append(System.lineSeparator());
    }
    if (!staleGuildSpecificationIds.isEmpty()) {
        Set<Long> staleAccessConfigurationsIds = getStaleAccessConfigurationsIds(cb, staleGuildSpecificationIds, session);
        if (!staleAccessConfigurationsIds.isEmpty()) {
            deleteStaleGrantedRoles(cb, staleAccessConfigurationsIds, session);
            deleteStaleAccessConfigurations(cb, staleAccessConfigurationsIds, session);
            messageBuilder.append("Cleared ").append(staleAccessConfigurationsIds.size()).append(" access configurations").append(System.lineSeparator());
        }
        deleteStaleGuildSpecifications(cb, staleGuildSpecificationIds, session);
        messageBuilder.append("Cleared ").append(staleGuildSpecificationIds.size()).append(" guild specifications").append(System.lineSeparator());
    }
    int affectedPresets = deleteStalePresets(cb, activeGuildIds, session);
    if (affectedPresets > 0) {
        messageBuilder.append("Cleared ").append(affectedPresets).append(" presets").append(System.lineSeparator());
    }
    int affectedScripts = deleteStaleScripts(cb, activeGuildIds, session);
    if (affectedScripts > 0) {
        messageBuilder.append("Cleared ").append(affectedScripts).append(" scripts");
    }
    String message = messageBuilder.toString();
    if (!message.isBlank()) {
        sendSuccess(message);
    } else {
        sendSuccess("Nothing to clear");
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) GuildManager(net.robinfriedli.aiode.discord.GuildManager) ShardManager(net.dv8tion.jda.api.sharding.ShardManager)

Example 3 with GuildManager

use of net.robinfriedli.aiode.discord.GuildManager in project aiode by robinfriedli.

the class ClearAbandonedGuildContextsTask method run.

@Override
protected void run(JobExecutionContext jobExecutionContext) {
    Aiode aiode = Aiode.get();
    ShardManager shardManager = aiode.getShardManager();
    GuildManager guildManager = aiode.getGuildManager();
    CommandExecutionQueueManager executionQueueManager = aiode.getExecutionQueueManager();
    int removedGuilds = 0;
    for (GuildContext guildContext : guildManager.getGuildContexts()) {
        Guild guild = guildContext.retrieveGuild();
        if (guild == null || shardManager.getGuildById(guild.getIdLong()) == null) {
            guildManager.removeGuild(guild);
            executionQueueManager.removeGuild(guild);
            ++removedGuilds;
        }
    }
    if (removedGuilds > 0) {
        LoggerFactory.getLogger(getClass()).info("Destroyed context for " + removedGuilds + " missing guilds");
    }
}
Also used : GuildContext(net.robinfriedli.aiode.discord.GuildContext) 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) CommandExecutionQueueManager(net.robinfriedli.aiode.concurrent.CommandExecutionQueueManager)

Example 4 with GuildManager

use of net.robinfriedli.aiode.discord.GuildManager in project aiode by robinfriedli.

the class PlaybackCleanupTask method run.

@Override
public void run(JobExecutionContext jobExecutionContext) {
    Logger logger = LoggerFactory.getLogger(getClass());
    Aiode aiode = Aiode.get();
    GuildManager guildManager = aiode.getGuildManager();
    Set<GuildContext> guildContexts = guildManager.getGuildContexts();
    Set<Guild> activeGuilds = StaticSessionProvider.invokeWithSession(session -> guildManager.getActiveGuilds(session, 3600000));
    int clearedAlone = 0;
    int playbacksCleared = 0;
    for (GuildContext guildContext : guildContexts) {
        try {
            AudioPlayback playback = guildContext.getPlayback();
            LocalDateTime aloneSince = playback.getAloneSince();
            if (aloneSince != null) {
                Duration aloneSinceDuration = Duration.between(aloneSince, LocalDateTime.now());
                Duration oneHour = Duration.ofHours(1);
                if (aloneSinceDuration.compareTo(oneHour) > 0) {
                    if (clearLonePlayback(guildContext, playback)) {
                        ++clearedAlone;
                        continue;
                    }
                }
            }
            if (!activeGuilds.contains(playback.getGuild()) && !playback.isPlaying()) {
                if (playback.clear()) {
                    ++playbacksCleared;
                }
            }
        } catch (DiscordEntityInitialisationException e) {
            // guild could not be loaded anymore, skip
            continue;
        }
    }
    if (clearedAlone > 0 || playbacksCleared > 0) {
        logger.info(String.format("Cleared %d stale playbacks and stopped %d lone playbacks", playbacksCleared, clearedAlone));
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) GuildContext(net.robinfriedli.aiode.discord.GuildContext) AudioPlayback(net.robinfriedli.aiode.audio.AudioPlayback) GuildManager(net.robinfriedli.aiode.discord.GuildManager) Duration(java.time.Duration) Logger(org.slf4j.Logger) Guild(net.dv8tion.jda.api.entities.Guild) Aiode(net.robinfriedli.aiode.Aiode) DiscordEntityInitialisationException(net.robinfriedli.aiode.exceptions.DiscordEntityInitialisationException)

Example 5 with GuildManager

use of net.robinfriedli.aiode.discord.GuildManager in project aiode by robinfriedli.

the class StartupListener method onReady.

@Override
public void onReady(@NotNull ReadyEvent event) {
    STARTUP_TASK_EXECUTOR.execute(() -> {
        JDA jda = event.getJDA();
        if (discordBotListAPI != null) {
            try {
                JDA.ShardInfo shardInfo = jda.getShardInfo();
                discordBotListAPI.setStats(shardInfo.getShardId(), shardInfo.getShardTotal(), (int) jda.getGuildCache().size());
            } catch (Exception e) {
                logger.error("Exception setting discordBotListAPI stats", e);
            }
        }
        CommandExecutionQueueManager executionQueueManager = aiode.getExecutionQueueManager();
        GuildManager guildManager = aiode.getGuildManager();
        StaticSessionProvider.consumeSession(session -> {
            // setup current thread session and handle all guilds within one session instead of opening a new session for each
            for (Guild guild : jda.getGuilds()) {
                executionQueueManager.addGuild(guild);
                guildManager.addGuild(guild);
            }
        });
        for (StartupTaskContribution element : startupTaskContributions) {
            if (element.getAttribute("runForEachShard").getBool()) {
                try {
                    element.instantiate().runTask(jda);
                } catch (Exception e) {
                    String msg = String.format("Startup task %s has thrown an exception for shard %s", element.getAttribute("implementation").getValue(), jda);
                    logger.error(msg, e);
                }
            }
        }
    });
}
Also used : GuildManager(net.robinfriedli.aiode.discord.GuildManager) JDA(net.dv8tion.jda.api.JDA) StartupTaskContribution(net.robinfriedli.aiode.entities.xml.StartupTaskContribution) Guild(net.dv8tion.jda.api.entities.Guild) CommandExecutionQueueManager(net.robinfriedli.aiode.concurrent.CommandExecutionQueueManager)

Aggregations

GuildManager (net.robinfriedli.aiode.discord.GuildManager)6 Guild (net.dv8tion.jda.api.entities.Guild)4 ShardManager (net.dv8tion.jda.api.sharding.ShardManager)3 Aiode (net.robinfriedli.aiode.Aiode)3 CommandExecutionQueueManager (net.robinfriedli.aiode.concurrent.CommandExecutionQueueManager)2 GuildContext (net.robinfriedli.aiode.discord.GuildContext)2 ThreadMXBean (java.lang.management.ThreadMXBean)1 Duration (java.time.Duration)1 LocalDateTime (java.time.LocalDateTime)1 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)1 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)1 JDA (net.dv8tion.jda.api.JDA)1 AudioManager (net.robinfriedli.aiode.audio.AudioManager)1 AudioPlayback (net.robinfriedli.aiode.audio.AudioPlayback)1 SpringPropertiesConfig (net.robinfriedli.aiode.boot.SpringPropertiesConfig)1 GuildPropertyManager (net.robinfriedli.aiode.discord.property.GuildPropertyManager)1 CommandHistory (net.robinfriedli.aiode.entities.CommandHistory)1 GuildSpecification (net.robinfriedli.aiode.entities.GuildSpecification)1 PlaybackHistory (net.robinfriedli.aiode.entities.PlaybackHistory)1 Playlist (net.robinfriedli.aiode.entities.Playlist)1