13
0

Commits vergleichen

...
Dieses Repository wurde am 2024-08-05 archiviert. Du kannst Dateien ansehen und es klonen, aber nicht pushen oder Issues/Pull-Requests öffnen.

1 Commits

Autor SHA1 Nachricht Datum
Chaos
e23d2f9163 feat(youtube): Add Image Request
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2022-03-26 23:09:30 +01:00
2 geänderte Dateien mit 65 neuen und 2 gelöschten Zeilen

Datei anzeigen

@ -50,8 +50,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version> <version>3.6.1</version>
<configuration> <configuration>
<source>8</source> <source>11</source>
<target>8</target> <target>11</target>
<compilerArgs>-Xlint</compilerArgs> <compilerArgs>-Xlint</compilerArgs>
</configuration> </configuration>
</plugin> </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);
}
}
}