Skip to content

Commit

Permalink
DM the user when the YoutubeOauth2Handler is providing us a token
Browse files Browse the repository at this point in the history
  • Loading branch information
MichailiK committed Oct 2, 2024
1 parent c95f224 commit 348fc3c
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 74 deletions.
9 changes: 9 additions & 0 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,6 +45,7 @@ public class Bot
private final PlaylistLoader playlists;
private final NowplayingHandler nowplaying;
private final AloneInVoiceHandler aloneInVoiceHandler;
private final YoutubeOauth2TokenHandler youTubeOauth2TokenHandler;

private boolean shuttingDown = false;
private JDA jda;
Expand All @@ -56,6 +58,8 @@ public Bot(EventWaiter waiter, BotConfig config, SettingsManager settings)
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);
Expand Down Expand Up @@ -103,6 +107,11 @@ public AloneInVoiceHandler getAloneInVoiceHandler()
{
return aloneInVoiceHandler;
}

public YoutubeOauth2TokenHandler getYouTubeOauth2Handler()
{
return youTubeOauth2TokenHandler;
}

public JDA getJDA()
{
Expand Down
31 changes: 21 additions & 10 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 All @@ -38,14 +40,14 @@
public class Listener extends ListenerAdapter
{
private final Bot bot;

public Listener(Bot bot)
{
this.bot = bot;
}

@Override
public void onReady(ReadyEvent event)
public void onReady(ReadyEvent event)
{
if(event.getJDA().getGuildCache().isEmpty())
{
Expand All @@ -54,7 +56,7 @@ public void onReady(ReadyEvent event)
log.warn(event.getJDA().getInviteUrl(JMusicBot.RECOMMENDED_PERMS));
}
credit(event.getJDA());
event.getJDA().getGuilds().forEach((guild) ->
event.getJDA().getGuilds().forEach((guild) ->
{
try
{
Expand All @@ -69,7 +71,7 @@ public void onReady(ReadyEvent event)
});
if(bot.getConfig().useUpdateAlerts())
{
bot.getThreadpool().scheduleWithFixedDelay(() ->
bot.getThreadpool().scheduleWithFixedDelay(() ->
{
try
{
Expand All @@ -85,10 +87,19 @@ 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)
{
PrivateChannel channel = bot.getJDA().openPrivateChannelById(bot.getConfig().getOwnerId()).complete();
channel.sendMessage("# DO NOT AUTHORISE THIS WITH YOUR MAIN ACCOUNT!!!\n" + "## Create or use an alternative/burner account!\n" + "To give JMusicBot access to your account, go to " + data.getAuthorisationUrl() + " and enter the code **" + data.getCode() + "**").queue();
}
}
}

@Override
public void onGuildMessageDelete(GuildMessageDeleteEvent event)
public void onGuildMessageDelete(GuildMessageDeleteEvent event)
{
bot.getNowplayingHandler().onMessageDelete(event.getGuild(), event.getMessageIdLong());
}
Expand All @@ -100,17 +111,17 @@ public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event)
}

@Override
public void onShutdown(ShutdownEvent event)
public void onShutdown(ShutdownEvent event)
{
bot.shutdown();
}

@Override
public void onGuildJoin(GuildJoinEvent event)
public void onGuildJoin(GuildJoinEvent event)
{
credit(event.getJDA());
}

// make sure people aren't adding clones to dbots
private void credit(JDA jda)
{
Expand Down
46 changes: 26 additions & 20 deletions src/main/java/com/jagrosh/jmusicbot/audio/PlayerManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,9 @@
import com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.vimeo.VimeoAudioSourceManager;
import dev.lavalink.youtube.YoutubeAudioSourceManager;
import dev.lavalink.youtube.http.YoutubeOauth2Handler;
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;
Expand All @@ -58,22 +56,43 @@ public void init()
{
TransformativeAudioSourceManager.createTransforms(bot.getConfig().getTransforms()).forEach(t -> registerSourceManager(t));

YoutubeAudioSourceManager yt = setupYoutubeAudioSourceManager();
registerSourceManager(yt);

registerSourceManager(SoundCloudAudioSourceManager.createDefault());
registerSourceManager(new BandcampAudioSourceManager());
registerSourceManager(new VimeoAudioSourceManager());
registerSourceManager(new TwitchStreamAudioSourceManager());
registerSourceManager(new BeamAudioSourceManager());
registerSourceManager(new GetyarnAudioSourceManager());
registerSourceManager(new NicoAudioSourceManager());
registerSourceManager(new HttpAudioSourceManager(MediaContainerRegistry.DEFAULT_REGISTRY));

AudioSourceManagers.registerLocalSource(this);

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)
catch (NoSuchFileException e)
{
/* ignored */
}
catch (IOException e)
{
LOGGER.warn("Failed to read YouTube OAuth2 token file: {}",e.getMessage());
LOGGER.warn("Failed to read YouTube OAuth2 token file: {}", e.getMessage());
}
LOGGER.debug("Using YouTube OAuth2 refresh token {}", token);
try
Expand All @@ -82,25 +101,12 @@ public void init()
}
catch (Exception e)
{
LOGGER.warn("Failed to authorize with YouTube. If this issue persists, delete the youtubetoken.txt file to reauthorize.", e);
LOGGER.warn("Failed to authorise with YouTube. If this issue persists, delete the youtubetoken.txt file to reauthorise.", e);
}
}
registerSourceManager(yt);

registerSourceManager(SoundCloudAudioSourceManager.createDefault());
registerSourceManager(new BandcampAudioSourceManager());
registerSourceManager(new VimeoAudioSourceManager());
registerSourceManager(new TwitchStreamAudioSourceManager());
registerSourceManager(new BeamAudioSourceManager());
registerSourceManager(new GetyarnAudioSourceManager());
registerSourceManager(new NicoAudioSourceManager());
registerSourceManager(new HttpAudioSourceManager(MediaContainerRegistry.DEFAULT_REGISTRY));

AudioSourceManagers.registerLocalSource(this);

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

public Bot getBot()
{
return bot;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.jagrosh.jmusicbot.utils;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;

import java.nio.file.Files;

/**
* A logback turbo filter, used retrieve the YouTube OAuth2 refresh token that gets logged once authorized with YouTube.
*
* @author Michaili K. <[email protected]>
*/
public class YoutubeOauth2TokenHandler extends TurboFilter {
public final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(YoutubeOauth2TokenHandler.class);
private Data data;


public void init()
{
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.addTurboFilter(this);
}

public Data getData()
{
return data;
}

@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t)
{
if (!logger.getName().equals("dev.lavalink.youtube.http.YoutubeOauth2Handler"))
return FilterReply.NEUTRAL;

if (format.equals("OAUTH INTEGRATION: To give youtube-source access to your account, go to {} and enter code {}"))
{
this.data = new Data((String) params[0], (String) params[1]);
return FilterReply.NEUTRAL;
}
if (format.equals("OAUTH INTEGRATION: Token retrieved successfully. Store your refresh token as this can be reused. ({})"))
{
LOGGER.info("Authorization successful & retrieved token! Storing the token in {}", OtherUtil.getPath("youtubetoken.txt").toAbsolutePath());
try
{
Files.write(OtherUtil.getPath("youtubetoken.txt"), params[0].toString().getBytes());
}
catch (Exception e)
{
LOGGER.error(
"Failed to write the YouTube OAuth2 refresh token to storage! You will need to authorize again on the next reboot",
e
);
}
return FilterReply.DENY;
}

return FilterReply.NEUTRAL;
}

public static class Data
{
private final String authorisationUrl;
private final String code;

private Data(String authorisationUrl, String code)
{
this.authorisationUrl = authorisationUrl;
this.code = code;
}

public String getCode()
{
return code;
}

public String getAuthorisationUrl()
{
return authorisationUrl;
}
}

}
2 changes: 0 additions & 2 deletions src/main/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,5 @@
<root level="INFO">
<appender-ref ref="Simple"/>
</root>

<turboFilter class="com.jagrosh.jmusicbot.utils.YouTubeOauth2TurboFilter" />

</configuration>

0 comments on commit 348fc3c

Please sign in to comment.