From e23d2f9163dda94687916702fec925dd88976f92 Mon Sep 17 00:00:00 2001 From: Chaos Date: Sat, 26 Mar 2022 23:09:30 +0100 Subject: [PATCH] feat(youtube): Add Image Request --- pom.xml | 4 +- src/de/steamwar/lobby/map/YouTubeLatest.java | 63 ++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 src/de/steamwar/lobby/map/YouTubeLatest.java diff --git a/pom.xml b/pom.xml index c9d6243..1096257 100644 --- a/pom.xml +++ b/pom.xml @@ -50,8 +50,8 @@ maven-compiler-plugin 3.6.1 - 8 - 8 + 11 + 11 -Xlint diff --git a/src/de/steamwar/lobby/map/YouTubeLatest.java b/src/de/steamwar/lobby/map/YouTubeLatest.java new file mode 100644 index 0000000..0417725 --- /dev/null +++ b/src/de/steamwar/lobby/map/YouTubeLatest.java @@ -0,0 +1,63 @@ +package de.steamwar.lobby.map; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Optional; + +public class YouTubeLatest { + private static final String YOUTUBE_LATEST_URL = "https://tools.tastethecode.com/youtube-latest/r/steamwar"; + private static final URI YOUTUBE_LATEST_URI = URI.create(YOUTUBE_LATEST_URL); + + public static BufferedImage getLatestImage() { + HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(); + HttpRequest request = HttpRequest.newBuilder().uri(YOUTUBE_LATEST_URI).GET().build(); + + try { + HttpResponse res = client.send(request, HttpResponse.BodyHandlers.discarding()); + Optional ou = res.headers().firstValue("Location"); + if(ou.isPresent()) { + String url = ou.get(); + String videoId = getVideoId(url); + if(videoId != null) { + String thumbnailUrl = getThumbnailUrl(videoId); + return getImage(thumbnailUrl); + } else { + throw new SecurityException("Could not get latest image from YouTube"); + } + } else { + throw new IOException("No redirect header found"); + } + } catch (Exception e) { + throw new SecurityException("Could not get latest image from YouTube", e); + } + } + + private static String getVideoId(String url) { + if(url.startsWith("https://www.youtube.com/watch?v=")) { + return url.substring("https://www.youtube.com/watch?v=".length()); + } + return null; + } + + private static String getThumbnailUrl(String videoId) { + return "https://img.youtube.com/vi/" + videoId + "/maxresdefault.jpg"; + } + + private static BufferedImage getImage(String url) { + HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(); + HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build(); + + try { + HttpResponse res = client.send(request, HttpResponse.BodyHandlers.ofInputStream()); + return ImageIO.read(res.body()); + } catch (Exception e) { + throw new SecurityException("Could not get latest image from YouTube", e); + } + } +}