Adding youtube callback

This commit is contained in:
Sebastien 2018-03-03 14:21:47 +01:00
parent a80f2d7ec4
commit 9831369c9e
8 changed files with 301 additions and 164 deletions

View File

@ -1,5 +1,6 @@
package net.Broken;
import net.Broken.RestApi.ApiCommandLoader;
import net.Broken.Tools.Command.CommandLoader;
import net.Broken.Tools.DayListener.DayListener;
import net.Broken.Tools.DayListener.Listeners.DailyMadame;
@ -30,15 +31,13 @@ public class Init {
* @param dev dev Mode or not
* @return JDA object
*/
static JDA initBot(String token, boolean dev){
boolean okInit;
static JDA initJda(String token, boolean dev){
JDA jda = null;
logger.debug("-------------------INITIALISATION-------------------");
//Bot démarrer sans token
if (token == null) {
logger.fatal("Veuilliez indiquer le token du bot en argument...");
okInit=false;
}
else
{
@ -58,8 +57,6 @@ public class Init {
*************************************/
jda.getPresence().setGame(Game.of("Statut: Loading..."));
jda.getTextChannels().forEach(textChannel -> textChannel.sendTyping().queue());
YoutubeTools.getInstance(jda.getGuilds().get(0)).getYouTubeService();
CommandLoader.load();
//On recupere le l'id serveur
@ -106,11 +103,15 @@ public class Init {
catch (LoginException | InterruptedException | RateLimitedException e)
{
logger.catching(e);
} catch (IOException e) {
e.printStackTrace();
}
}
return jda;
}
static void polish(){
CommandLoader.load();
ApiCommandLoader.load();
}
}

View File

@ -6,6 +6,7 @@ import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.UserSpamUtils;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.ChannelType;
@ -20,6 +21,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
@ -69,7 +71,7 @@ public class MainBot {
i++;
}
jda = Init.initBot(token, dev);
jda = Init.initJda(token, dev);
ConfigurableApplicationContext ctx = SpringApplication.run(MainBot.class, args);
if(jda == null) {
System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> {
@ -78,8 +80,13 @@ public class MainBot {
}));
}
try {
YoutubeTools.getInstance(jda.getGuilds().get(0)).getYouTubeService();
} catch (IOException e) {
e.printStackTrace();
}
ApiCommandLoader.load();
Init.polish();
@ -145,13 +152,25 @@ public class MainBot {
else
{
MessageReceivedEvent event = cmd.event;
if(event.isFromType(ChannelType.PRIVATE))
event.getPrivateChannel().sendMessage(EmbedMessageUtils.getUnknowCommand()).queue();
else {
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getUnknowCommand()).complete();
new MessageTimeOut(messageTimeOut, message, event.getMessage());
if(commandes.size() == 0){
if(event.isFromType(ChannelType.PRIVATE))
event.getPrivateChannel().sendMessage("Loading please wait...").queue();
else {
Message message = event.getTextChannel().sendMessage("Loading please wait...").complete();
new MessageTimeOut(messageTimeOut, message, event.getMessage());
}
}
logger.warn("Commande inconnue");
else{
if(event.isFromType(ChannelType.PRIVATE))
event.getPrivateChannel().sendMessage(EmbedMessageUtils.getUnknowCommand()).queue();
else {
Message message = event.getTextChannel().sendMessage(EmbedMessageUtils.getUnknowCommand()).complete();
new MessageTimeOut(messageTimeOut, message, event.getMessage());
}
logger.warn("Commande inconnue");
}
}

View File

@ -0,0 +1,42 @@
package net.Broken.audio.Youtube;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
import com.google.api.client.util.Preconditions;
import net.Broken.Tools.PrivateMessage;
import net.dv8tion.jda.core.entities.Guild;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
public class Authorization extends AuthorizationCodeInstalledApp {
private Guild guild;
private Logger logger = LogManager.getLogger();
/**
* @param flow authorization code flow
* @param receiver verification code receiver
*/
public Authorization(AuthorizationCodeFlow flow, VerificationCodeReceiver receiver, Guild guild) {
super(flow, receiver);
this.guild = guild;
}
@Override
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
notify(authorizationUrl.build());
}
protected void notify(String url){
Preconditions.checkNotNull(url);
// Ask user to open in their browser using copy-paste
logger.fatal("Please open this URL: "+url);
PrivateMessage.send(guild.getOwner().getUser(),"Please open this url to confirm google api account acces : " + url,null);
}
}

View File

@ -1,141 +0,0 @@
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package net.Broken.audio.Youtube;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
import com.google.api.client.util.Preconditions;
import net.Broken.Tools.PrivateMessage;
import net.dv8tion.jda.core.entities.Guild;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.*;
import java.io.IOException;
/**
* OAuth 2.0 authorization code flow for an installed Java application that persists end-user
* credentials.
*
* <p>
* Implementation is thread-safe.
* </p>
*
* @since 1.11
* @author Yaniv Inbar
*/
public class Autorization {
/** Authorization code flow. */
private final AuthorizationCodeFlow flow;
/** Verification code receiver. */
private final VerificationCodeReceiver receiver;
private static final Logger LOGGER = LogManager.getLogger();
private Guild guild;
/**
* @param flow authorization code flow
* @param receiver verification code receiver
*/
public Autorization(AuthorizationCodeFlow flow, VerificationCodeReceiver receiver, Guild guild) {
this.flow = Preconditions.checkNotNull(flow);
this.receiver = Preconditions.checkNotNull(receiver);
this.guild = guild;
}
/**
* Authorizes the installed application to access user's protected data.
*
* @param userId user ID or {@code null} if not using a persisted credential store
* @return credential
*/
public Credential authorize(String userId) throws IOException {
try {
Credential credential = flow.loadCredential(userId);
if (credential != null
&& (credential.getRefreshToken() != null ||
credential.getExpiresInSeconds() == null ||
credential.getExpiresInSeconds() > 60)) {
return credential;
}
// open in browser
String redirectUri = receiver.getRedirectUri();
AuthorizationCodeRequestUrl authorizationUrl =
flow.newAuthorizationUrl().setRedirectUri(redirectUri);
onAuthorization(authorizationUrl);
// receive authorization code and exchange it for an access token
String code = receiver.waitForCode();
TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
// store credential and return it
return flow.createAndStoreCredential(response, userId);
} finally {
receiver.stop();
}
}
/**
* Handles user authorization by redirecting to the OAuth 2.0 authorization server.
*
* <p>
* Default implementation is to call {@code browse(authorizationUrl.build())}. Subclasses may
* override to provide optional parameters such as the recommended state parameter. Sample
* implementation:
* </p>
*
* <pre>
&#64;Override
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
authorizationUrl.setState("xyz");
super.onAuthorization(authorizationUrl);
}
* </pre>
*
* @param authorizationUrl authorization URL
* @throws IOException I/O exception
*/
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
browse(authorizationUrl.build());
}
/**
* Open a browser at the given URL using {@link Desktop} if available, or alternatively output the
* URL to {@link System#out} for command-line applications.
*
* @param url URL to browse
*/
public void browse(String url) {
Preconditions.checkNotNull(url);
// Ask user to open in their browser using copy-paste
LOGGER.fatal("Please open this URL: "+url);
PrivateMessage.send(guild.getOwner().getUser(),"Please open this url to confirm google api account acces : " + url,null);
}
/** Returns the authorization code flow. */
public final AuthorizationCodeFlow getFlow() {
return flow;
}
/** Returns the verification code receiver. */
public final VerificationCodeReceiver getReceiver() {
return receiver;
}
}

View File

@ -0,0 +1,54 @@
package net.Broken.audio.Youtube;
import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver;
import net.dv8tion.jda.core.entities.Guild;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
public class Receiver extends AbstractPromptReceiver {
private static Receiver INSTANCE;
private Guild guild;
private String code;
private Receiver(Guild guild){
this.guild = guild;
}
public static Receiver getInstance(Guild guild){
if(INSTANCE == null)
INSTANCE = new Receiver(guild);
return INSTANCE;
}
@Override
public String getRedirectUri() throws IOException {
return System.getenv("SITE_URL") + "/youtube/callback";
}
@Override
public String waitForCode() {
if(System.getenv("SITE_URL").isEmpty()){
LogManager.getLogger().fatal("Please set \"SITE_URL\" environment variable and restart the bot!");
}
while(code == null){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return code;
}
@Override
public void stop() {
}
public void setCode(String code) {
this.code = code;
}
}

View File

@ -1,14 +1,11 @@
package net.Broken.audio.Youtube;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
@ -88,9 +85,12 @@ public class YoutubeTools {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("online")
.setAccessType("offline")
.build();
Credential credential = new Autorization(flow, new LocalServerReceiver(), guild).authorize("user");
Credential credential = new Authorization(flow, Receiver.getInstance(null), guild).authorize("user");
logger.debug("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
@ -120,11 +120,11 @@ public class YoutubeTools {
YouTube.Search.List searchListRelatedVideosRequest = youtube.search().list(parameters.get("part").toString());
if (parameters.containsKey("relatedToVideoId") && parameters.get("relatedToVideoId") != "") {
searchListRelatedVideosRequest.setRelatedToVideoId(parameters.get("relatedToVideoId").toString());
searchListRelatedVideosRequest.setRelatedToVideoId(parameters.get("relatedToVideoId"));
}
if (parameters.containsKey("type") && parameters.get("type") != "") {
searchListRelatedVideosRequest.setType(parameters.get("type").toString());
if (parameters.containsKey("type") && !parameters.get("type").equals("")) {
searchListRelatedVideosRequest.setType(parameters.get("type"));
}
SearchListResponse response = searchListRelatedVideosRequest.execute();

View File

@ -0,0 +1,23 @@
package net.Broken.webView;
import net.Broken.audio.Youtube.Receiver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class YoutubeCallBack {
@RequestMapping("/youtube/callback")
public String callback(@RequestParam(value="error", required = false, defaultValue = "") String error,
@RequestParam(value = "code", required = false, defaultValue = "") String code,
Model model){
model.addAttribute("error", error);
model.addAttribute("code", code);
if(!code.equals("")){
Receiver.getInstance(null).setCode(code);
}
return "youtubeCallBack";
}
}

View File

@ -0,0 +1,139 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Music Control - Discord Bot</title>
<link rel="icon"
type="image/x-icon"
href="/favicon.png"/>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<link href="/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body class="blue-grey lighten-5" >
<!--__________________________________________________________-->
<!-- NAV BAR -->
<!-- AND -->
<!-- LOGIN -->
<!--__________________________________________________________-->
<nav class="blue-grey darken-4 z-depth-3" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="/" class="brand-logo">Discord Bot</a>
<ul class="right hide-on-med-and-down">
<li >
<a class="waves-effect waves-light sidenav-trigger" href="/" data-target="slide-out">Home</a>
</li>
<li>
<a class="waves-effect waves-light" href="/music" >Music Control</a>
</li>
<li id="nav-bar-account">
<a class="dropdown-account" data-activates="dropdown1"><i class="material-icons">account_box</i></a>
</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li class="active">
<a class="waves-effect waves-light sidenav-trigger" href="/" data-target="slide-out">Home</a>
</li>
<li>
<a class="waves-effect waves-light sidenav-trigger" href="/music" data-target="slide-out" >Music Control</a>
</li>
<!--TODO Connection mobile-->
</ul>
<a href="#" data-activates="nav-mobile" class="button-navbar-mobile button-collapse"><i class="material-icons">menu</i></a>
</div>
</nav>
<!-- Dropdown connected -->
<ul id="dropdown_connected" class="dropdown-content ">
<li>
<a class="center blue-grey-text text-darken-4" id="nav-name" style="text-decoration: underline; font-weight: bold"></a>
</li>
<li class="divider"></li>
<li>
<a class="center tooltipped" data-position="left" data-delay="50" data-tooltip="Under Development!">My Account</a>
</li>
<li>
<a class="center tooltipped" data-position="left" data-delay="50" data-tooltip="Under Development!">My Playlists</a>
</li>
<li class="divider"></li>
<li><a class="center red-text" id="nav-disconnect" style="font-weight: bold">Disconnect</a></li>
</ul>
<!--________________________________________-->
<!-- Connection modal -->
<!--________________________________________-->
<div id="modal_connection" class="modal">
<div class="modal-content">
<div class="row center">
<div class="col s12">
<h3 class="" style="font-weight: bold">Sign in</h3>
</div>
</div>
<div class="row center" style="margin-bottom: 0px">
<form name="login_form" id="login_form" action="javascript:void(0);" onsubmit="tryConnection()">
<div class="row" style="margin-bottom: 0px">
<div class="input-field col s6 offset-s3">
<i class="material-icons prefix">account_box</i>
<input name="username" id="user_input" type="text" class="validate"/>
<label for="user_input" data-error="User not registered!">User Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s6 offset-s3">
<i class="material-icons prefix">security</i>
<input name="password" id="password_input" type="password" class="validate"/>
<label for="password_input" data-error="Wrong password!">Password</label>
</div>
</div>
<div class="row" style="margin-bottom: 10px">
<button id="btn-submit-connect" class="btn waves-effect waves-light light-green darken-1 scale-transition scale-out" type="submit" name="action" >
Submit<i class="material-icons right">send</i>
</button>
</div>
<div class="row">
<a class="btn waves-effect waves-light brown" href="/register">
Create account<i class="material-icons right">person_add</i>
</a>
</div>
</form>
</div>
</div>
</div>
<!--__________________________________________________________-->
<!-- -->
<!-- END -->
<!-- -->
<!--__________________________________________________________-->
<div class="section no-pad-bot main" id="index-banner">
<div class="center row">
<div class="col s12">
<h2 th:text="Succes" th:if="!${#strings.isEmpty(code)}"></h2>
<h2 th:text="${error}" th:if="${#strings.isEmpty(code)}"></h2>
</div>
</div>
</div>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script th:src="@{/js/materialize.js}"></script>
<script th:src="@{/js/navabar.js}"></script>
<script th:src="@{/js/js.cookie.js}"></script>
</body>
</html>