Skip to content

Commit

Permalink
Fix some thumb caching behavior for archival and varied internet status
Browse files Browse the repository at this point in the history
  • Loading branch information
mattwright324 committed Jul 12, 2019
1 parent 087d7e1 commit 697afbc
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions src/main/java/io/mattw/youtube/commentsuite/ImageCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.apache.logging.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
Expand All @@ -22,6 +23,9 @@ public interface ImageCache {

Logger logger = LogManager.getLogger();

File thumbsDir = new File("thumbs/");
String thumbFormat = "jpg";

Cache<Object, Image> thumbCache = CacheBuilder.newBuilder()
.maximumSize(500)
.expireAfterAccess(5, TimeUnit.MINUTES)
Expand Down Expand Up @@ -54,24 +58,30 @@ static Image findOrGetImage(String id, String imageUrl) {

Image image = thumbCache.getIfPresent(id);
if (image == null) {
String fileFormat = "jpg";
File thumbFile = new File(String.format("./thumbs/%s.%s", id, fileFormat));
File thumbFile = new File(thumbsDir, String.format("%s.%s", id, thumbFormat));
if (configData.getArchiveThumbs() && !thumbFile.exists()) {
thumbsDir.mkdir();

logger.debug("Archiving [id={}]", id);
try {
thumbFile.mkdirs();
BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));

thumbFile.createNewFile();
ImageIO.write(ImageIO.read(new URL(imageUrl)), fileFormat, thumbFile);

ImageIO.write(bufferedImage, thumbFormat, thumbFile);
} catch (IOException e) {
logger.error("Failed to archive image.", e);
logger.error("Failed to archive image [id={}]", id, e);
}
}
if (thumbFile.exists()) {
image = new Image(String.format("file:///%s", thumbFile.getAbsolutePath()));
} else {
image = new Image(imageUrl);
}
thumbCache.put(id, image);

if(!image.isError()) {
thumbCache.put(id, image);
}
}
return image;
}
Expand Down

0 comments on commit 697afbc

Please sign in to comment.