Add Youtube Search, text and RestAPI

This commit is contained in:
Sebastien 2018-11-20 19:37:28 +02:00
parent b296b2d9e5
commit 085680ebb3
9 changed files with 248 additions and 32 deletions

View File

@ -0,0 +1,68 @@
package net.Broken.Commands;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import net.Broken.Commande;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.awt.*;
public class Code implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
StringBuilder stringBuilder = new StringBuilder();
for(String arg : args){
stringBuilder.append(arg);
stringBuilder.append(" ");
}
Binding binding = new Binding();
binding.setVariable("event", event);
GroovyShell shell = new GroovyShell(binding);
EmbedBuilder builder;
try{
Object value = shell.evaluate(stringBuilder.toString());
StringBuilder stringResult = new StringBuilder();
if(value.getClass().isArray()){
Object[] array = (Object[]) value;
for(Object obj : array){
if(stringResult.length() < 1800){
stringResult.append(obj.toString()).append("\n\n");
}
else{
stringResult.append("\n...");
break;
}
}
}else{
stringResult.append(value.toString());
}
builder = new EmbedBuilder().setColor(Color.orange).setTitle(":hammer_pick: Compilation Successful :hammer_pick:").setDescription("```java\n" + stringResult.toString() + "```");
}catch (Exception ex){
builder = new EmbedBuilder().setColor(Color.red).setTitle(":x: Compilation Failed :x:").setDescription("```java\n" + ex.toString() + "```");
}
event.getChannel().sendMessage(builder.build()).queue();
}
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isAdminCmd() {
return true;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -0,0 +1,65 @@
package net.Broken.Commands;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import net.Broken.Commande;
import net.Broken.MainBot;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.audio.Youtube.SearchResult;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
public class YtSearch implements Commande {
private Logger logger = LogManager.getLogger();
@Override
public void action(String[] args, MessageReceivedEvent event) {
YoutubeTools youtubeT = YoutubeTools.getInstance();
if(args.length < 1){
logger.info("YtSearch: Missing args, user: " + event.getAuthor().getName());
Message message = event.getChannel().sendMessage(EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("Missing search query!"))).complete();
new MessageTimeOut(MainBot.messageTimeOut, message, event.getMessage()).start();
}else {
try {
ArrayList<SearchResult> result = youtubeT.search(args[0], 5);
for(SearchResult item : result){
event.getChannel().sendMessage(EmbedMessageUtils.searchResult(item)).queue();
}
} catch (GoogleJsonResponseException e) {
logger.error("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
event.getChannel().sendMessage(EmbedMessageUtils.getInternalError()).queue();
} catch (IOException t) {
logger.catching(t);
event.getChannel().sendMessage(EmbedMessageUtils.getInternalError()).queue();
}
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -1,20 +1,15 @@
package net.Broken; package net.Broken;
import net.Broken.RestApi.ApiCommandLoader;
import net.Broken.Tools.Command.CommandParser; import net.Broken.Tools.Command.CommandParser;
import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut; import net.Broken.Tools.MessageTimeOut;
import net.Broken.Tools.PrivateMessage; import net.Broken.Tools.PrivateMessage;
import net.Broken.Tools.UserSpamUtils; import net.Broken.Tools.UserSpamUtils;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.Permission; import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.ChannelType; import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -24,7 +19,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;

View File

@ -1,5 +1,6 @@
package net.Broken.RestApi; package net.Broken.RestApi;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.Broken.Commands.Music; import net.Broken.Commands.Music;
@ -7,10 +8,13 @@ import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository; import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.RestApi.Data.*; import net.Broken.RestApi.Data.*;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.UserUtils; import net.Broken.Tools.UserManager.UserUtils;
import net.Broken.audio.AudioM; import net.Broken.audio.AudioM;
import net.Broken.audio.FindGeneral; import net.Broken.audio.FindGeneral;
import net.Broken.audio.Youtube.SearchResult;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.entities.VoiceChannel;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@ -21,6 +25,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -44,7 +49,7 @@ public class MusicWebAPIController {
@RequestMapping("/currentMusicInfo") @RequestMapping("/currentMusicInfo")
public ResponseEntity<CurrentMusicData> getCurrentM(@RequestParam(value = "guild") String guildId){ public ResponseEntity<CurrentMusicData> getCurrentM(@RequestParam(value = "guild") String guildId){ //TODO security issue ???!!!
Guild guild = MainBot.jda.getGuildById(guildId); Guild guild = MainBot.jda.getGuildById(guildId);
if(guild == null ){ if(guild == null ){
logger.warn("Request whit no guild!"); logger.warn("Request whit no guild!");
@ -72,7 +77,7 @@ public class MusicWebAPIController {
} }
@RequestMapping("/getPlaylist") @RequestMapping("/getPlaylist")
public ResponseEntity<PlaylistData> getPlaylist(@RequestParam(value = "guild") String guildId){ public ResponseEntity<PlaylistData> getPlaylist(@RequestParam(value = "guild") String guildId){ //TODO security issue ???!!!
Guild guild = MainBot.jda.getGuildById(guildId); Guild guild = MainBot.jda.getGuildById(guildId);
if(guild == null ){ if(guild == null ){
logger.warn("Request whit no guild!"); logger.warn("Request whit no guild!");
@ -127,7 +132,7 @@ public class MusicWebAPIController {
} }
@RequestMapping(value = "/getChanel", method = RequestMethod.GET) @RequestMapping(value = "/getChanel", method = RequestMethod.GET)
public ResponseEntity<List<ChanelData>> getChanel(@RequestParam(value = "guild") String guildId){ public ResponseEntity<List<ChanelData>> getChanel(@RequestParam(value = "guild") String guildId){ //TODO security issue ???!!!
Guild guild = MainBot.jda.getGuildById(guildId); Guild guild = MainBot.jda.getGuildById(guildId);
if(guild == null ){ if(guild == null ){
logger.warn("Request whit no guild!"); logger.warn("Request whit no guild!");
@ -143,6 +148,33 @@ public class MusicWebAPIController {
return new ResponseEntity<>(temp, HttpStatus.OK); return new ResponseEntity<>(temp, HttpStatus.OK);
} }
@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<List<SearchResult>> search(@CookieValue("token") String token, @RequestParam(value = "query") String query ){
if(token != null) {
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
YoutubeTools youtubeTools = YoutubeTools.getInstance();
ArrayList<SearchResult> result = youtubeTools.search(query, 25);
return new ResponseEntity<>(result, HttpStatus.OK);
}catch (UnknownTokenException e){
logger.warn("Search without token!");
return new ResponseEntity<>( HttpStatus.UNAUTHORIZED);
} catch (GoogleJsonResponseException e) {
logger.error("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
logger.catching(e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}else{
logger.warn("Search without token!");
return new ResponseEntity<>( HttpStatus.UNAUTHORIZED);
}
}
} }

View File

@ -2,6 +2,7 @@ package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.audio.Youtube.SearchResult;
import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.MessageEmbed; import net.dv8tion.jda.core.entities.MessageEmbed;
@ -123,6 +124,16 @@ public class EmbedMessageUtils {
return buildStandar(messageB); return buildStandar(messageB);
} }
public static MessageEmbed searchResult(SearchResult result){
EmbedBuilder builder = new EmbedBuilder()
.setColor(Color.CYAN)
.setTitle(result.title)
.setImage(result.imageUrl)
.addField("URL:","https://www.youtube.com/watch?v="+result.id,false)
.addField("Chanel:", result.channelTittle, false);
return buildStandar(builder);
}

View File

@ -13,6 +13,7 @@ import net.dv8tion.jda.core.entities.Guild;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingDeque;
@ -190,7 +191,7 @@ public class TrackScheduler extends AudioEventAdapter {
} catch (GoogleJsonResponseException e) { } catch (GoogleJsonResponseException e) {
logger.error("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); logger.error("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
} catch (Throwable t) { } catch (IOException t) {
logger.catching(t); logger.catching(t);
} }

View File

@ -0,0 +1,21 @@
package net.Broken.audio.Youtube;
public class SearchResult {
public String id;
public String title;
public String description;
public String publishedAt;
public String channelId;
public String channelTittle;
public String imageUrl;
public SearchResult(com.google.api.services.youtube.model.SearchResult result){
id = result.getId().getVideoId();
title = result.getSnippet().getTitle();
description = result.getSnippet().getDescription();
publishedAt = result.getSnippet().getPublishedAt().toString();
channelId = result.getSnippet().getChannelId();
channelTittle = result.getSnippet().getChannelTitle();
imageUrl = result.getSnippet().getThumbnails().getDefault().getUrl();
}
}

View File

@ -1,14 +1,10 @@
package net.Broken.audio.Youtube; package net.Broken.audio.Youtube;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse; import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult; import com.google.api.services.youtube.model.SearchResult;
import net.dv8tion.jda.core.entities.Guild;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@ -19,31 +15,35 @@ import java.util.HashMap;
public class YoutubeTools { public class YoutubeTools {
private Logger logger = LogManager.getLogger(); private Logger logger = LogManager.getLogger();
private String apiKey = System.getenv("GOOGLE_API_KEY");
private static YoutubeTools INSTANCE;
private static YoutubeTools INSTANCE ; private YoutubeTools() {
private YoutubeTools(){
} }
public static YoutubeTools getInstance(){ public static YoutubeTools getInstance() {
if(INSTANCE == null) if (INSTANCE == null)
INSTANCE = new YoutubeTools(); INSTANCE = new YoutubeTools();
return INSTANCE; return INSTANCE;
} }
public String getRelatedVideo(String videoId, ArrayList<String> history) throws IOException, GoogleJsonResponseException, Throwable { private YouTube getYoutubeService() {
// YouTube youtube = getYouTubeService(); YouTube.Builder builder = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), request -> {
YouTube.Builder builder = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}); });
builder.setApplicationName("youtube-cmdline-search-sample"); builder.setApplicationName("BotDiscord");
YouTube youtube = builder.build(); return builder.build();
}
public String getRelatedVideo(String videoId, ArrayList<String> history) throws IOException {
YouTube youtube = getYoutubeService();
HashMap<String, String> parameters = new HashMap<>(); HashMap<String, String> parameters = new HashMap<>();
@ -60,15 +60,14 @@ public class YoutubeTools {
searchListRelatedVideosRequest.setType(parameters.get("type")); searchListRelatedVideosRequest.setType(parameters.get("type"));
} }
searchListRelatedVideosRequest.setKey(System.getenv("GOOGLE_API_KEY")); searchListRelatedVideosRequest.setKey(apiKey);
SearchListResponse response = searchListRelatedVideosRequest.execute(); SearchListResponse response = searchListRelatedVideosRequest.execute();
for(SearchResult item : response.getItems()){ for (SearchResult item : response.getItems()) {
if(!history.contains(item.getId().getVideoId())){ if (!history.contains(item.getId().getVideoId())) {
return item.getId().getVideoId(); return item.getId().getVideoId();
} } else
else
logger.debug("ID already on history"); logger.debug("ID already on history");
} }
@ -76,4 +75,26 @@ public class YoutubeTools {
return response.getItems().get(0).getId().getVideoId(); return response.getItems().get(0).getId().getVideoId();
} }
public ArrayList<net.Broken.audio.Youtube.SearchResult> search(String query, long max) throws IOException {
YouTube youTube = getYoutubeService();
YouTube.Search.List searchList = youTube.search().list("snippet");
searchList.setType("video");
searchList.setSafeSearch("none");
searchList.setMaxResults(max);
searchList.setQ(query);
searchList.setKey(apiKey);
searchList.setOrder("relevance");
SearchListResponse response = searchList.execute();
ArrayList<net.Broken.audio.Youtube.SearchResult> finalResult = new ArrayList<>();
for(SearchResult item : response.getItems()){
logger.debug(item.getSnippet().getTitle());
finalResult.add(new net.Broken.audio.Youtube.SearchResult(item));
}
return finalResult;
}
} }

View File

@ -19,6 +19,9 @@
<body class="blue-grey lighten-5" > <body class="blue-grey lighten-5" >
<!--/*@thymesVar id="guild_name" type="java.lang.String"*/-->
<!--/*@thymesVar id="redirect_url" type="java.lang.String"*/-->
<!--/*@thymesVar id="isAdmin" type="java.lang.Boolean"*/-->
<div th:replace="header :: header ('music',${guild_name},${redirect_url}, ${isAdmin})">...</div> <div th:replace="header :: header ('music',${guild_name},${redirect_url}, ${isAdmin})">...</div>
<div class="section no-pad-bot main" id="index-banner"> <div class="section no-pad-bot main" id="index-banner">
<div class="row"> <div class="row">