change: switch from optionals to pairs for error returns

This commit is contained in:
ZtereoHYPE 2022-02-03 03:08:23 +01:00
parent e53d50e455
commit 4864ac49b9
3 changed files with 29 additions and 34 deletions

View file

@ -12,9 +12,9 @@ import codes.ztereohype.ztereomusic.networking.YoutubeSearch;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.shadew.util.data.Pair;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -70,24 +70,24 @@ public class Play implements Command {
boolean spotifyUrlFound = matchedSpotifyUrl.find(); boolean spotifyUrlFound = matchedSpotifyUrl.find();
if (spotifyUrlFound) { if (spotifyUrlFound) {
Optional<String> songSearchQuery = SpotifyApiHelper.query(mergedArgs, messageChannel); Pair<Boolean, String> songSearchQuery = SpotifyApiHelper.query(mergedArgs);
if (songSearchQuery.isPresent()) { if (songSearchQuery.first()) {
mergedArgs = songSearchQuery.get(); mergedArgs = songSearchQuery.second();
} else { } else {
return; // SpotifyApiHelper takes care of answering why it failed messageChannel.sendMessage(songSearchQuery.second()).queue();
return;
} }
} }
String identifier; String identifier;
// spotify urls need to be queried through youtube // spotify urls need to be queried through youtube
if (!urlFound || spotifyUrlFound) { if (!urlFound || spotifyUrlFound) {
Optional<String> query = YoutubeSearch.query(mergedArgs); Pair<Boolean, String> query = YoutubeSearch.query(mergedArgs);
if (query.first()) {
if (query.isPresent()) { identifier = query.second();
identifier = query.get();
} else { } else {
messageEvent.getChannel().sendMessage("I found no matches for that song!").queue(); messageEvent.getChannel().sendMessage(query.second()).queue();
return; return;
} }
} else { } else {

View file

@ -2,10 +2,9 @@ package codes.ztereohype.ztereomusic.networking;
import codes.ztereohype.ztereomusic.ZtereoMUSIC; import codes.ztereohype.ztereomusic.ZtereoMUSIC;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.shadew.json.Json; import net.shadew.json.Json;
import net.shadew.json.JsonPath; import net.shadew.json.JsonPath;
import net.shadew.json.JsonSyntaxException; import net.shadew.util.data.Pair;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@ -50,7 +49,6 @@ public class SpotifyApiHelper {
@SneakyThrows @SneakyThrows
private static Optional<String> getToken() { private static Optional<String> getToken() {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder( HttpRequest request = HttpRequest.newBuilder(
URI.create("https://accounts.spotify.com/api/token?grant_type=client_credentials")) URI.create("https://accounts.spotify.com/api/token?grant_type=client_credentials"))
.POST(HttpRequest.BodyPublishers.ofString("")) .POST(HttpRequest.BodyPublishers.ofString(""))
@ -63,21 +61,21 @@ public class SpotifyApiHelper {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String results = JSON.parse(response.body()).query(tokenPath).asString(); String results = JSON.parse(response.body()).query(tokenPath).asString();
return Optional.ofNullable(results); return Optional.ofNullable(results);
} catch (IOException | InterruptedException | JsonSyntaxException e) { } catch (IOException | InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
return Optional.empty(); return Optional.empty();
} }
} }
public static Optional<String> query(String songUrl, MessageChannel messageChannel) { // boolean is isSuccessful and string is content -> error if failure and content if success
public static Pair<Boolean, String> query(String songUrl) {
if (spotifyToken == null) { if (spotifyToken == null) {
System.out.println("Null Spotify token detected"); System.out.println("Null Spotify token detected");
messageChannel.sendMessage("I don't have a spotify token for now. Try again later.").queue(); return Pair.of(false, "I don't have a spotify token for now. Try again later.");
return Optional.empty();
} }
if (songUrl.contains("/playlist/")) { if (songUrl.contains("playlist")) {
messageChannel.sendMessage("Playlists aren't supported for now, please send the individual song links.").queue(); return Pair.of(false, "Playlists aren't supported for now, please send the individual song links.");
} }
Matcher matchedSpotifyIdentifier = IDENTIFIER_PATTERN.matcher(songUrl); Matcher matchedSpotifyIdentifier = IDENTIFIER_PATTERN.matcher(songUrl);
@ -85,8 +83,7 @@ public class SpotifyApiHelper {
if (matchedSpotifyIdentifier.find()) { if (matchedSpotifyIdentifier.find()) {
spotifyIdentifier = matchedSpotifyIdentifier.group(); spotifyIdentifier = matchedSpotifyIdentifier.group();
} else { } else {
messageChannel.sendMessage("Could not parse Spotify link. Try entering the song title directly.").queue(); return Pair.of(false, "Could not parse Spotify link. Try entering the song title directly.");
return Optional.empty();
} }
String query = "https://api.spotify.com/v1/tracks?ids=" String query = "https://api.spotify.com/v1/tracks?ids="
@ -102,19 +99,17 @@ public class SpotifyApiHelper {
.build(); .build();
JsonPath titlePath = JsonPath.parse("tracks[0].name"); JsonPath titlePath = JsonPath.parse("tracks[0].name");
JsonPath authorPath = JsonPath.parse("tracks[0].artists[0].name"); // JsonPath authorPath = JsonPath.parse("tracks[0].artists[0].name");
try { try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String title = JSON.parse(response.body()).query(titlePath).asString(); String title = JSON.parse(response.body()).query(titlePath).asString();
String author = JSON.parse(response.body()).query(authorPath).asString(); // String author = JSON.parse(response.body()).query(authorPath).asString();
String songSearchQuery = title + " " + author + "official audio";
return Optional.of(songSearchQuery); return Pair.of(true, title);
} catch (IOException | InterruptedException | JsonSyntaxException e) { } catch (IOException | InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
messageChannel.sendMessage("Something wrong happened with the spotify request.").queue(); return Pair.of(false,"Something wrong happened with the spotify request.");
return Optional.empty();
} }
} }
} }

View file

@ -4,16 +4,16 @@ import codes.ztereohype.ztereomusic.ZtereoMUSIC;
import net.shadew.json.Json; import net.shadew.json.Json;
import net.shadew.json.JsonPath; import net.shadew.json.JsonPath;
import net.shadew.json.JsonSyntaxException; import net.shadew.json.JsonSyntaxException;
import net.shadew.util.data.Pair;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.Optional;
public class YoutubeSearch { public class YoutubeSearch {
private static final String API_KEY = ZtereoMUSIC.getInstance().getConfig().getPropreties().get("yt_api_key"); private static final String API_KEY = ZtereoMUSIC.getInstance().getConfig().getPropreties().get("yt_api_key");
private static final Json JSON = Json.json(); private static final Json JSON = Json.json();
public static Optional<String> query(String title) { public static Pair<Boolean, String> query(String title) {
String query = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=%22" String query = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=%22"
+ title.replace(' ', '+') + "%22&type=video&key=" + API_KEY; + title.replace(' ', '+') + "%22&type=video&key=" + API_KEY;
@ -22,7 +22,7 @@ public class YoutubeSearch {
jsonResponse = new String(new URL(query).openStream().readAllBytes()); jsonResponse = new String(new URL(query).openStream().readAllBytes());
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return Optional.empty(); return Pair.of(false, "There was a request error contacting youtube.");
} }
JsonPath resultsNumberPath = JsonPath.parse("pageInfo.totalResults"); JsonPath resultsNumberPath = JsonPath.parse("pageInfo.totalResults");
@ -30,12 +30,12 @@ public class YoutubeSearch {
try { try {
int results = JSON.parse(jsonResponse).query(resultsNumberPath).asInt(); int results = JSON.parse(jsonResponse).query(resultsNumberPath).asInt();
if (results == 0) return Optional.empty(); if (results == 0) return Pair.of(false, "I found no matches for that song.");
return Optional.ofNullable(JSON.parse(jsonResponse).query(videoPath).asString()); return Pair.of(true, JSON.parse(jsonResponse).query(videoPath).asString());
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
e.printStackTrace(); e.printStackTrace();
return Optional.empty(); return Pair.of(false, "There was an error parsing YouTube's reply.");
} }
} }
} }