13
0

feat(youtube): Add Image Request
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful

Dieser Commit ist enthalten in:
Chaos 2022-03-26 23:09:30 +01:00
Ursprung 52da054d5f
Commit e23d2f9163
2 geänderte Dateien mit 65 neuen und 2 gelöschten Zeilen

Datei anzeigen

@ -50,8 +50,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>8</source>
<target>8</target>
<source>11</source>
<target>11</target>
<compilerArgs>-Xlint</compilerArgs>
</configuration>
</plugin>

Datei anzeigen

@ -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<String> 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<InputStream> 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);
}
}
}