Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix default volume, load playlists messages, reddit caching #83

Merged
merged 1 commit into from
Apr 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/main/java/com/bot/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,10 @@ public VoiceSendHandler getHandler(Guild guild) {
LOGGER.warning("Failed to get guild when looking for volume. Attempting an add");
guildDAO.addFreshGuild(guild);
// Just play, no need to return
} else {
dVolume = g.getVolume();
}


handler.getPlayer().setVolume(dVolume);
player.addListener(handler);
guild.getAudioManager().setSendingHandler(handler);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/bot/caching/GuildCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ private GuildCache() {
LOGGER.info("Guild Cache successfully initialized.");
}

@SuppressWarnings("unchecked")
public void put(String key, InternalGuild value) {
cache.put(key, value);
}

@SuppressWarnings("unchecked")
public InternalGuild get(String key) {
return cache.get(key);
}

public void removeAll() {
cache.removeAll();
}

public int getSize() {return cache.size();}
}
2 changes: 0 additions & 2 deletions src/main/java/com/bot/caching/MarkovModelCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,10 @@ private MarkovModelCache() {
LOGGER.info("Markov Cache successfully initialized.");
}

@SuppressWarnings("unchecked")
public void put(String key, MarkovModel value) {
cache.put(key, value);
}

@SuppressWarnings("unchecked")
public MarkovModel get(String key) {
return cache.get(key);
}
Expand Down
50 changes: 50 additions & 0 deletions src/main/java/com/bot/caching/SubredditCache.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.bot.caching;

import com.bot.utils.Logger;
import net.dean.jraw.models.Listing;
import net.dean.jraw.models.Submission;

import java.util.List;

public class SubredditCache {
private final Logger LOGGER;

private static SubredditCache instance;
private Cache<List<Listing<Submission>>> cache;
private int MAX_SIZE;
private int CACHE_OBJECT_LIFETIME;
private int CACHE_CHECK_INTERVAL;

public static SubredditCache getInstance() {
if (instance == null) {
instance = new SubredditCache();
}
return instance;
}

private SubredditCache() {
// Just doing some default values here
MAX_SIZE = 100;
CACHE_CHECK_INTERVAL = 300;
CACHE_OBJECT_LIFETIME = 600;

cache = new Cache<>("subreddit", MAX_SIZE, CACHE_OBJECT_LIFETIME, CACHE_CHECK_INTERVAL);

LOGGER = new Logger(SubredditCache.class.getName());
LOGGER.info("subreddit Cache initialized.");
}

public void put(String key, List<Listing<Submission>> value) {
cache.put(key, value);
}

public List<Listing<Submission>> get(String key) {
return cache.get(key);
}

public void removeAll() {
cache.removeAll();
}

public int getSize() {return cache.size();}
}
3 changes: 2 additions & 1 deletion src/main/java/com/bot/commands/RedditCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public RedditCommand() {
this.category = CommandCategories.REDDIT;
this.guildOnly = false;
this.botPermissions = new Permission[]{Permission.MESSAGE_WRITE, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS};

this.cooldownScope = CooldownScope.USER;
this.cooldown = 2;
this.metricsManager = MetricsManager.getInstance();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.bot.commands.ModerationCommand;
import com.bot.db.ChannelDAO;
import com.jagrosh.jdautilities.command.CommandEvent;
import net.dv8tion.jda.core.Permission;

public class EnableNSFWCommand extends ModerationCommand {

Expand All @@ -12,6 +13,7 @@ public EnableNSFWCommand() {
this.name = "enablensfw";
this.arguments = "";
this.help = "Enables NSFW commands in the text channel it is posted in.";
this.botPermissions = new Permission[]{Permission.MESSAGE_HISTORY};

this.channelDAO = ChannelDAO.getInstance();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ protected void executeCommand(CommandEvent commandEvent) {
// if number parsing fails we look for the name;
playlistName = commandEvent.getArgs();
}

if (playlistName != null && playlistName.isEmpty()) {
commandEvent.replyWarning("You must specify a playlist name or id to load it.");
return;
}
String userId = commandEvent.getAuthor().getId();
playlist = playlistName != null ? playlistDAO.getPlaylistForUserByName(userId, playlistName) :
playlistDAO.getPlaylistForUserById(userId, playlistId);
Expand Down
9 changes: 7 additions & 2 deletions src/main/java/com/bot/db/PlaylistDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public Playlist getPlaylistForUserById(String userId, int playlistId) {
return getPlaylistsFromQuery(userId, query).get(0);
}
// Catches if no results returned then the list will be null, nullpointer will be caught and passed up.
catch (NullPointerException e) {
catch (NullPointerException | IndexOutOfBoundsException e) {
return null;
}
}
Expand All @@ -96,7 +96,7 @@ public Playlist getPlaylistForGuildById(String guildId, int playlistId) {
return getPlaylistsFromQuery(guildId, query).get(0);
}
// Catches if no results returned then the list will be null, nullpointer will be caught and passed up.
catch (NullPointerException e) {
catch (NullPointerException | IndexOutOfBoundsException e) {
return null;
}
}
Expand Down Expand Up @@ -199,6 +199,7 @@ private List<Playlist> getPlaylistsFromQuery(String ownerId, String query) {
}
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
DbHelpers.close(statement, set, conn);
}
Expand Down Expand Up @@ -238,6 +239,10 @@ private Playlist getPlaylistFromQueryWithName(String ownerId, String query, Stri
DbHelpers.close(statement, set, conn);
}

// Signifies a not found playlist
if (tracks.isEmpty())
return null;

return new Playlist(playlistId, ownerId, playlistName, tracks);
}

Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/bot/metrics/MetricsReporter.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.bot.ShardingManager;
import com.bot.caching.MarkovModelCache;
import com.bot.caching.SubredditCache;
import com.bot.models.InternalShard;

/**
Expand All @@ -12,11 +13,13 @@ public class MetricsReporter extends Thread {
private ShardingManager shardManager;
private MarkovModelCache markovModelCache;
private MetricsManager metricsManager;
private SubredditCache subredditCache;

public MetricsReporter() {
shardManager = ShardingManager.getInstance();
markovModelCache = MarkovModelCache.getInstance();
metricsManager = MetricsManager.getInstance();
subredditCache = SubredditCache.getInstance();
}

@Override
Expand Down Expand Up @@ -50,6 +53,7 @@ public void run() {
metricsManager.updateUserCount(userCount);
// TODO: get max size
metricsManager.updateCacheSize("markov", markovModelCache.getSize(), 0);
metricsManager.updateCacheSize("subreddit", subredditCache.getSize(), 0);

try {
Thread.sleep(5000);
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/bot/utils/Logger.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.bot.ShardingManager;
import com.bot.models.InternalShard;
import net.dv8tion.jda.core.entities.TextChannel;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.Map;
import java.util.logging.Level;
Expand Down Expand Up @@ -113,6 +114,7 @@ private void postToErrorChannel(String s, Exception e) {
errorChannel.sendMessage("`Error:`\n" + s).queue();
if (e != null)
errorChannel.sendMessage("`Exception:`\n```" + e.toString() + "```").queue();
errorChannel.sendMessage("StackTrace: ```" + ExceptionUtils.getStackTrace(e) + "```").queue();
}
}

Expand Down
34 changes: 22 additions & 12 deletions src/main/java/com/bot/utils/RedditHelper.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.bot.utils;

import com.bot.RedditConnection;
import com.bot.caching.SubredditCache;
import com.bot.exceptions.ForbiddenCommandException;
import com.bot.exceptions.PermsOutOfSyncException;
import com.jagrosh.jdautilities.command.CommandEvent;
Expand All @@ -14,7 +15,6 @@
import net.dv8tion.jda.core.entities.MessageEmbed;

import java.util.List;
import java.util.Objects;
import java.util.Random;

public class RedditHelper {
Expand Down Expand Up @@ -57,8 +57,8 @@ public static void getRandomSubmissionAndSend(RedditConnection redditConnection,
.subreddit(subredditName);

try {
if (subreddit.about().isNsfw()) {
if (!isChannelNSFW) {
if (!isChannelNSFW) {
if (subreddit.about().isNsfw()) {
commandEvent.reply(commandEvent.getClient().getWarning() + " NSFW subreddit detected and NSFW is not enabled on this channel. " +
"To enable it, use the `~enableNSFW` command.");
return;
Expand All @@ -81,16 +81,24 @@ public static void getRandomSubmissionAndSend(RedditConnection redditConnection,
.sorting(sortType)
.build();

List<Listing<Submission>> submissions = paginator.accumulate(1);
SubredditCache cache = SubredditCache.getInstance();
List<Listing<Submission>> submissions = cache.get(subredditName);

if (submissions == null) {
submissions = paginator.accumulate(1);
cache.put(subredditName, submissions);
}

Listing<Submission> page = submissions.get(0); // Get the only page
Submission submission = getRandomSubmission(page, false);// Get random child post from the page


if (submission.isNsfw() && !isChannelNSFW) {
boolean isNsfwSubmission = submission.isNsfw();
if (isNsfwSubmission && !isChannelNSFW) {
// Submission is nsfw but sub is not. Try 10 times to find non nsfw-post
int tries = 0;
while (submission.isNsfw()) {
while (isNsfwSubmission) {
submission = getRandomSubmission(page, false);
isNsfwSubmission = submission.isNsfw();
tries++;
if (tries == 10) {
commandEvent.reply(commandEvent.getClient().getWarning() + " I only found NSFW posts and NSFW is not enabled on this channel. " +
Expand All @@ -103,16 +111,17 @@ public static void getRandomSubmissionAndSend(RedditConnection redditConnection,
// Send the embed, content will be sent separatly below
commandEvent.reply(buildEmbedForSubmission(submission));

if (submission.isSelfPost() && !Objects.requireNonNull(submission.getSelfText()).isEmpty()) {
String text = submission.getSelfText();
if (submission.isSelfPost() && text != null && !text.isEmpty()) {
// Since discord only allows us to send 2000 characters we need to break long posts down
if (submission.getSelfText().length() > 1900) {
if (text.length() > 1900) {
// Split message into parts and send them all separately
for (String part: FormattingUtils.splitTextIntoChunksByWords(submission.getSelfText(), 1500)) {
for (String part: FormattingUtils.splitTextIntoChunksByWords(text, 1500)) {
commandEvent.reply("```" + part + "```");
}
} else {
// Its short enough so just send it
commandEvent.reply("```" + submission.getSelfText() + " ```");
commandEvent.reply("```" + text + " ```");
}
} else {
commandEvent.reply(submission.getUrl());
Expand Down Expand Up @@ -141,7 +150,8 @@ private static MessageEmbed buildEmbedForSubmission(Submission submission) {
builder.setFooter(submission.getUrl(), REDDIT_SNOO_ICON_URL);

// If the title is more than 256 characters then trim it
String title = submission.getTitle().length() <= 256 ? submission.getTitle() : submission.getTitle().substring(0, 252) + "...";
String title = submission.getTitle();
title = title.length() <= 256 ? title : title.substring(0, 252) + "...";
builder.setTitle(title);

// If there is a thumbnail and it does match a url to an image
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/bot/voice/VoiceSendHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.core.audio.AudioSendHandler;

import java.util.*;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class VoiceSendHandler extends AudioEventAdapter implements AudioSendHandler {
Expand Down