use of fredboat.util.rest.Http in project FredBoat by Frederikam.
the class RandomImageCommand method populateItems.
/**
* Updates the imgur backed images managed by this object
*/
private void populateItems(boolean useEtag) {
Matcher m = IMGUR_ALBUM.matcher(this.imgurAlbumUrl);
if (!m.find()) {
log.error("Not a valid imgur album url {}", this.imgurAlbumUrl);
return;
}
String albumId = m.group(1);
Http.SimpleRequest request = BotController.Companion.getHTTP().get("https://api.imgur.com/3/album/" + albumId).auth("Client-ID " + Launcher.getBotController().getCredentials().getImgurClientId());
if (useEtag) {
request = request.header("If-None-Match", etag);
}
try (Response response = request.execute()) {
// data change, and on the next fetch they will return the old Etag again.
if (response.code() == 304) {
// nothing to do here
log.info("Refreshed imgur album {}, no update.", this.imgurAlbumUrl);
} else if (response.isSuccessful()) {
// noinspection ConstantConditions
JSONArray images = new JSONObject(response.body().string()).getJSONObject("data").getJSONArray("images");
List<String> imageUrls = new ArrayList<>();
images.forEach(o -> imageUrls.add(((JSONObject) o).getString("link")));
synchronized (this) {
urls = imageUrls.toArray(urls);
etag = response.header("ETag");
}
log.info("Refreshed imgur album {}, new data found.", this.imgurAlbumUrl);
} else {
// some other status
// noinspection ConstantConditions
log.warn("Unexpected http status for imgur album request {}, response: {}\n{}", this.imgurAlbumUrl, response.toString(), response.body().string());
}
} catch (IOException e) {
log.error("Imgur down? Could not fetch imgur album {}", this.imgurAlbumUrl, e);
}
}
Aggregations