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

Implement YouTube OAuth2 login #1670

Closed
wants to merge 20 commits into from
Closed
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
11 changes: 5 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,21 @@
<version>4.4.1_353</version>
</dependency>
<dependency>
<groupId>com.jagrosh</groupId>
<artifactId>jda-utilities</artifactId>
<version>3.0.5</version>
<type>pom</type>
<groupId>com.github.JDA-Applications</groupId>
<artifactId>JDA-Utilities</artifactId>
<version>c16a4b264b</version>
</dependency>

<!-- Music Dependencies -->
<dependency>
<groupId>dev.arbjerg</groupId>
<artifactId>lavaplayer</artifactId>
<version>2.2.1</version>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>dev.lavalink.youtube</groupId>
<artifactId>common</artifactId>
<version>1.5.2</version>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>com.github.jagrosh</groupId>
Expand Down
19 changes: 12 additions & 7 deletions src/main/java/com/jagrosh/jmusicbot/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.jagrosh.jmusicbot.playlist.PlaylistLoader;
import com.jagrosh.jmusicbot.settings.SettingsManager;
import java.util.Objects;
import com.jagrosh.jmusicbot.utils.YoutubeOauth2TokenHandler;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild;
Expand All @@ -44,24 +45,28 @@ public class Bot
private final PlaylistLoader playlists;
private final NowplayingHandler nowplaying;
private final AloneInVoiceHandler aloneInVoiceHandler;
private final YoutubeOauth2TokenHandler youTubeOauth2TokenHandler;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly a bit of a hacky way of going from the (Lavaplayer) youtube-source logging the details to JDA being ready & DM'ing the owner the details. Feel free to point out better solutions for this!

private final GUI gui;

private boolean shuttingDown = false;
private JDA jda;
private GUI gui;

public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings)
public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings, GUI gui)
{
this.waiter = waiter;
this.config = config;
this.settings = settings;
this.playlists = new PlaylistLoader(config);
this.threadpool = Executors.newSingleThreadScheduledExecutor();
this.youTubeOauth2TokenHandler = new YoutubeOauth2TokenHandler();
this.youTubeOauth2TokenHandler.init();
this.players = new PlayerManager(this);
this.players.init();
this.nowplaying = new NowplayingHandler(this);
this.nowplaying.init();
this.aloneInVoiceHandler = new AloneInVoiceHandler(this);
this.aloneInVoiceHandler.init();
this.gui = gui;
}

public BotConfig getConfig()
Expand Down Expand Up @@ -103,6 +108,11 @@ public AloneInVoiceHandler getAloneInVoiceHandler()
{
return aloneInVoiceHandler;
}

public YoutubeOauth2TokenHandler getYouTubeOauth2Handler()
{
return youTubeOauth2TokenHandler;
}

public JDA getJDA()
{
Expand Down Expand Up @@ -152,9 +162,4 @@ public void setJDA(JDA jda)
{
this.jda = jda;
}

public void setGUI(GUI gui)
{
this.gui = gui;
}
}
8 changes: 7 additions & 1 deletion src/main/java/com/jagrosh/jmusicbot/BotConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public class BotConfig
private String token, prefix, altprefix, helpWord, playlistsFolder, logLevel,
successEmoji, warningEmoji, errorEmoji, loadingEmoji, searchingEmoji,
evalEngine;
private boolean stayInChannel, songInGame, npImages, updatealerts, useEval, dbots;
private boolean youtubeOauth2, stayInChannel, songInGame, npImages, updatealerts, useEval, dbots;
private long owner, maxSeconds, aloneTimeUntilStop;
private int maxYTPlaylistPages;
private double skipratio;
Expand Down Expand Up @@ -84,6 +84,7 @@ public void load()
searchingEmoji = config.getString("searching");
game = OtherUtil.parseGame(config.getString("game"));
status = OtherUtil.parseStatus(config.getString("status"));
youtubeOauth2 = config.getBoolean("youtubeoauth2");
stayInChannel = config.getBoolean("stayinchannel");
songInGame = config.getBoolean("songinstatus");
npImages = config.getBoolean("npimages");
Expand Down Expand Up @@ -293,6 +294,11 @@ public String getHelp()
return helpWord;
}

public boolean useYoutubeOauth2()
{
return youtubeOauth2;
}

public boolean getStay()
{
return stayInChannel;
Expand Down
34 changes: 18 additions & 16 deletions src/main/java/com/jagrosh/jmusicbot/JMusicBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,28 +82,15 @@ private static void startBot()
config.load();
if(!config.isValid())
return;
LOG.info("Loaded config from " + config.getConfigLocation());

// set log level from config
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(
Level.toLevel(config.getLogLevel(), Level.INFO));

// set up the listener
EventWaiter waiter = new EventWaiter();
SettingsManager settings = new SettingsManager();
Bot bot = new Bot(waiter, config, settings);
CommandClient client = createCommandClient(config, settings, bot);

GUI gui = null;

if(!prompt.isNoGUI())
{
try
try
{
GUI gui = new GUI(bot);
bot.setGUI(gui);
gui = new GUI();
gui.init();

LOG.info("Loaded config from " + config.getConfigLocation());
}
catch(Exception e)
{
Expand All @@ -113,6 +100,21 @@ private static void startBot()
}
}

LOG.info("Loaded config from " + config.getConfigLocation());

// set log level from config
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(
Level.toLevel(config.getLogLevel(), Level.INFO));

// set up the listener
EventWaiter waiter = new EventWaiter();
SettingsManager settings = new SettingsManager();
Bot bot = new Bot(waiter, config, settings, gui);
if (gui != null)
gui.setBot(bot);
CommandClient client = createCommandClient(config, settings, bot);


// attempt to log in and start
try
{
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/com/jagrosh/jmusicbot/Listener.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

import com.jagrosh.jmusicbot.utils.OtherUtil;
import java.util.concurrent.TimeUnit;
import com.jagrosh.jmusicbot.utils.YoutubeOauth2TokenHandler;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.PrivateChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.ReadyEvent;
Expand Down Expand Up @@ -85,6 +87,26 @@ public void onReady(ReadyEvent event)
catch(Exception ignored) {} // ignored
}, 0, 24, TimeUnit.HOURS);
}
if (bot.getConfig().useYoutubeOauth2())
{
YoutubeOauth2TokenHandler.Data data = bot.getYouTubeOauth2Handler().getData();
if (data != null)
{
try
{
PrivateChannel channel = bot.getJDA().openPrivateChannelById(bot.getConfig().getOwnerId()).complete();
channel
.sendMessage(
"# DO NOT AUTHORISE THIS WITH YOUR MAIN GOOGLE ACCOUNT!!!\n"
+ "## Create or use an alternative/burner Google account!\n"
+ "To give JMusicBot access to your Google account, go to "
+ data.getAuthorisationUrl()
+ " and enter the code **" + data.getCode() + "**")
.queue();
}
catch (Exception ignored) {}
}
}
}

@Override
Expand Down
20 changes: 18 additions & 2 deletions src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
Expand All @@ -53,6 +54,7 @@ public class AudioHandler extends AudioEventAdapter implements AudioSendHandler
public final static String PAUSE_EMOJI = "\u23F8"; // ⏸
public final static String STOP_EMOJI = "\u23F9"; // ⏹

private final static Logger LOGGER = LoggerFactory.getLogger(AudioHandler.class);

private final List<AudioTrack> defaultQueue = new LinkedList<>();
private final Set<String> votes = new HashSet<>();
Expand Down Expand Up @@ -202,8 +204,22 @@ public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason
}

@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
LoggerFactory.getLogger("AudioHandler").error("Track " + track.getIdentifier() + " has failed to play", exception);
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception)
{
if (
exception.getMessage().equals("Sign in to confirm you're not a bot")
|| exception.getMessage().equals("Please sign in")
|| exception.getMessage().equals("This video requires login.")
)
LOGGER.error(
"Track {} has failed to play: {}. "
+ "You will need to sign in to Google to play YouTube tracks. "
+ "More info: https://jmusicbot.com/youtube-oauth2",
track.getIdentifier(),
exception.getMessage()
);
else
LOGGER.error("Track {} has failed to play", track.getIdentifier(), exception);
}

@Override
Expand Down
47 changes: 44 additions & 3 deletions src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import com.dunctebot.sourcemanagers.DuncteBotSources;
import com.jagrosh.jmusicbot.Bot;
import com.jagrosh.jmusicbot.utils.OtherUtil;
import com.sedmelluq.discord.lavaplayer.container.MediaContainerRegistry;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
Expand All @@ -31,13 +32,19 @@
import com.sedmelluq.discord.lavaplayer.source.vimeo.VimeoAudioSourceManager;
import dev.lavalink.youtube.YoutubeAudioSourceManager;
import net.dv8tion.jda.api.entities.Guild;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;

/**
*
* @author John Grosh ([email protected])
*/
public class PlayerManager extends DefaultAudioPlayerManager
{
private final static Logger LOGGER = LoggerFactory.getLogger(PlayerManager.class);
private final Bot bot;

public PlayerManager(Bot bot)
Expand All @@ -49,8 +56,7 @@ public void init()
{
TransformativeAudioSourceManager.createTransforms(bot.getConfig().getTransforms()).forEach(t -> registerSourceManager(t));

YoutubeAudioSourceManager yt = new YoutubeAudioSourceManager(true);
yt.setPlaylistPageCount(bot.getConfig().getMaxYTPlaylistPages());
YoutubeAudioSourceManager yt = setupYoutubeAudioSourceManager();
registerSourceManager(yt);

registerSourceManager(SoundCloudAudioSourceManager.createDefault());
Expand All @@ -66,7 +72,42 @@ public void init()

DuncteBotSources.registerAll(this, "en-US");
}


private YoutubeAudioSourceManager setupYoutubeAudioSourceManager()
{
YoutubeAudioSourceManager yt = new YoutubeAudioSourceManager(true);
yt.setPlaylistPageCount(bot.getConfig().getMaxYTPlaylistPages());

// OAuth2 setup
if (bot.getConfig().useYoutubeOauth2())
{
String token = null;
try
{
token = Files.readString(OtherUtil.getPath("youtubetoken.txt"));
}
catch (NoSuchFileException e)
{
/* ignored */
}
catch (IOException e)
{
LOGGER.warn("Failed to read YouTube OAuth2 token file: {}", e.getMessage());
return yt;
}
LOGGER.debug("Read YouTube OAuth2 refresh token from youtubetoken.txt");
try
{
yt.useOauth2(token, false);
}
catch (Exception e)
{
LOGGER.warn("Failed to authorise with YouTube. If this issue persists, delete the youtubetoken.txt file to reauthorise.", e);
}
}
return yt;
}

public Bot getBot()
{
return bot;
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/jagrosh/jmusicbot/gui/GUI.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,18 @@
public class GUI extends JFrame
{
private final ConsolePanel console;
private final Bot bot;
private Bot bot;

public GUI(Bot bot)
public GUI()
{
super();
this.bot = bot;
console = new ConsolePanel();
}

public void setBot(Bot bot) {
this.bot = bot;
}

public void init()
{
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Expand All @@ -56,7 +59,8 @@ public void init()
{
try
{
bot.shutdown();
if (bot != null)
bot.shutdown();
}
catch(Exception ex)
{
Expand Down
Loading
Loading