io.github.chikyukido.nyaapplet.manager.NyaManager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of NyaApplet Show documentation
Show all versions of NyaApplet Show documentation
An applet that can send in anime pics from different sources.
package io.github.chikyukido.nyaapplet.manager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.github.chikyukido.nyaapplet.api.ApiUrls;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author Chikyu Kido
*/
@Component
@RequiredArgsConstructor
public class NyaManager {
private final ApiUrls apiUrls;
/**
* Searches for an image url for the given type and nsfw
*
* @param type the type of the image
* @param nsfw if the image is nsfw
* @return the image url or null if not found
*/
public String getImageUrl(String type, boolean nsfw) {
List urls;
if (!nsfw) {
urls = apiUrls.getUrlsForType.get(type);
} else {
urls = apiUrls.getNsfwUrlsForType.get(type);
}
if (urls == null) {
return null;
}
String randomUrl = urls.get(ThreadLocalRandom.current().nextInt(urls.size()));
if (randomUrl.contains("nekos.best")) {
return getImageUrlFromNekosBest(randomUrl);
} else if (randomUrl.contains("waifu.pics")) {
return getImageUrlFromWaifuPics(randomUrl);
} else if (randomUrl.contains("nekos.life")) {
return getImageUrlFromNekosLife(randomUrl);
}
return null;
}
private String getImageUrlFromNekosLife(String url) {
try {
URL urlO = new URL(url);
Gson gson = new Gson();
JsonObject json = gson.fromJson((IOUtils.toString(urlO.openStream(), StandardCharsets.UTF_8)), JsonObject.class);
return json.getAsJsonObject().get("url").getAsString();
} catch (IOException e) {
return null;
}
}
/**
* Gets the image url from nekos best
*
* @param url the api endpoint for an image
* @return an image url
*/
private String getImageUrlFromNekosBest(String url) {
try {
URL urlO = new URL(url);
Gson gson = new Gson();
JsonObject json = gson.fromJson((IOUtils.toString(urlO.openStream(), StandardCharsets.UTF_8)), JsonObject.class);
return json.getAsJsonArray("results").get(0).getAsJsonObject().get("url").getAsString();
} catch (IOException e) {
return null;
}
}
/**
* Gets the image url from waifu pics
*
* @param url the api endpoint for an image
* @return an image url
*/
private String getImageUrlFromWaifuPics(String url) {
try {
URL urlO = new URL(url);
Gson gson = new Gson();
JsonObject json = gson.fromJson((IOUtils.toString(urlO.openStream(), StandardCharsets.UTF_8)), JsonObject.class);
return json.get("url").getAsString();
} catch (IOException e) {
return null;
}
}
}