-
-
Notifications
You must be signed in to change notification settings - Fork 77
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Closes #970
- Loading branch information
Showing
17 changed files
with
443 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
/* | ||
* (C) Copyright 2024 TheOtherP ([email protected]) | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.nzbhydra.cache; | ||
|
||
import lombok.SneakyThrows; | ||
import org.apache.commons.io.FileUtils; | ||
import org.jetbrains.annotations.NotNull; | ||
import org.nzbhydra.logging.LoggingMarkers; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.cache.support.AbstractValueAdaptingCache; | ||
|
||
import java.io.File; | ||
import java.nio.file.Files; | ||
import java.time.Instant; | ||
import java.util.Arrays; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.Optional; | ||
import java.util.concurrent.Callable; | ||
|
||
public class DiskCache extends AbstractValueAdaptingCache { | ||
|
||
private static final Logger logger = LoggerFactory.getLogger(DiskCache.class); | ||
|
||
private static final int MAX_ENTRIES = 500; | ||
private static final int MAX_ENTRIES_SIZE_MB = 50; | ||
|
||
private static final Map<String, Instant> ACCESS_MAP = new HashMap<>(); | ||
|
||
private final File cacheDir; | ||
private final String name; | ||
|
||
public DiskCache(File cacheDir, String name) { | ||
super(false); | ||
this.cacheDir = cacheDir; | ||
this.name = name; | ||
boolean created = cacheDir.mkdirs(); | ||
if (!cacheDir.exists()) { | ||
throw new RuntimeException("Error creating cache dir " + cacheDir.getAbsolutePath()); | ||
} | ||
} | ||
|
||
@Override | ||
public String getName() { | ||
return name; | ||
} | ||
|
||
@Override | ||
public Object getNativeCache() { | ||
return this; | ||
} | ||
|
||
@Override | ||
@SneakyThrows | ||
public <T> T get(Object key, Callable<T> valueLoader) { | ||
if (key instanceof String keyString) { | ||
ACCESS_MAP.put(keyString, Instant.now()); | ||
File keyFile = buildKeyFile(keyString); | ||
if (keyFile.exists()) { | ||
return (T) Files.readAllBytes(keyFile.toPath()); | ||
} else { | ||
T value = valueLoader.call(); | ||
if ((value instanceof byte[] bytes)) { | ||
Files.write(keyFile.toPath(), bytes); | ||
return value; | ||
} else { | ||
throw new RuntimeException("Illegal type for value " + value.getClass()); | ||
} | ||
} | ||
} else { | ||
throw new RuntimeException("Illegal type for key " + key.getClass()); | ||
} | ||
} | ||
|
||
@Override | ||
@SneakyThrows | ||
public void put(Object key, Object value) { | ||
if ((key instanceof String keyString) && (value instanceof byte[] valueBytes)) { | ||
logger.debug(LoggingMarkers.DISK_CACHE, "Writing entry with key {} and size {}", keyString, valueBytes.length); | ||
Files.write(buildKeyFile(keyString).toPath(), valueBytes); | ||
ACCESS_MAP.put(keyString, Instant.now()); | ||
} else { | ||
throw new RuntimeException("Illegal type for key " + key.getClass() + " and/or value " + value.getClass()); | ||
} | ||
cleanAfterPut(); | ||
} | ||
|
||
private void cleanAfterPut() { | ||
while (ACCESS_MAP.size() > MAX_ENTRIES) { | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "{} entries in cache - exceeds limit of {}", ACCESS_MAP.size(), MAX_ENTRIES); | ||
deleteOldestEntry(); | ||
} | ||
while (Arrays.stream(cacheDir.listFiles()).mapToDouble(File::length).sum() / (1024 * 1024) > MAX_ENTRIES_SIZE_MB) { | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "Cache takes up too much space (more than {})", MAX_ENTRIES_SIZE_MB); | ||
deleteOldestEntry(); | ||
} | ||
} | ||
|
||
private void deleteOldestEntry() { | ||
Optional<Map.Entry<String, Instant>> oldestEntry = ACCESS_MAP.entrySet().stream().min(Map.Entry.comparingByValue()); | ||
if (oldestEntry.isPresent()) { | ||
logger.debug(LoggingMarkers.DISK_CACHE, "Removing oldest entry {}", oldestEntry.get()); | ||
ACCESS_MAP.remove(oldestEntry.get().getKey()); | ||
FileUtils.deleteQuietly(buildKeyFile(oldestEntry.get().getKey())); | ||
} | ||
} | ||
|
||
@NotNull | ||
private File buildKeyFile(String keyString) { | ||
return new File(cacheDir, keyString); | ||
} | ||
|
||
@Override | ||
public void evict(Object key) { | ||
if (key instanceof String keyString) { | ||
File keyFile = buildKeyFile(keyString); | ||
if (keyFile.exists()) { | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "Evicting entry {}", keyString); | ||
ACCESS_MAP.remove(keyString); | ||
FileUtils.deleteQuietly(keyFile); | ||
} else { | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "Can't evict not existing entry {}", keyString); | ||
} | ||
} | ||
} | ||
|
||
@Override | ||
@SneakyThrows | ||
public void clear() { | ||
if (!cacheDir.exists()) { | ||
return; | ||
} | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "Clearing cache"); | ||
FileUtils.cleanDirectory(cacheDir); | ||
ACCESS_MAP.clear(); | ||
} | ||
|
||
@Override | ||
@SneakyThrows | ||
protected Object lookup(Object key) { | ||
if (key instanceof String keyString) { | ||
File keyFile = buildKeyFile(keyString); | ||
if (keyFile.exists()) { | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "Found entry for key {}", keyString); | ||
return Files.readAllBytes(keyFile.toPath()); | ||
} else { | ||
logger.debug(LoggingMarkers.CONFIG_READ_WRITE, "Did not find entry for key {}", keyString); | ||
} | ||
} | ||
return null; | ||
} | ||
|
||
} |
44 changes: 44 additions & 0 deletions
44
core/src/main/java/org/nzbhydra/cache/ImageCacheConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/* | ||
* (C) Copyright 2024 TheOtherP ([email protected]) | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.nzbhydra.cache; | ||
|
||
import org.nzbhydra.NzbHydra; | ||
import org.springframework.cache.Cache; | ||
import org.springframework.cache.CacheManager; | ||
import org.springframework.cache.support.AbstractCacheManager; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
|
||
import java.io.File; | ||
import java.util.Collection; | ||
import java.util.List; | ||
|
||
@Configuration | ||
public class ImageCacheConfig { | ||
|
||
|
||
@Bean | ||
public CacheManager imageCacheManager() { | ||
return new AbstractCacheManager() { | ||
@Override | ||
protected Collection<? extends Cache> loadCaches() { | ||
return List.of(new DiskCache(new File(NzbHydra.getDataFolder(), "cache"), "images")); | ||
} | ||
}; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
/* | ||
* (C) Copyright 2024 TheOtherP ([email protected]) | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package org.nzbhydra.cache; | ||
|
||
import org.nzbhydra.webaccess.HydraOkHttp3ClientHttpRequestFactory; | ||
import org.springframework.cache.annotation.Cacheable; | ||
import org.springframework.http.HttpMethod; | ||
import org.springframework.http.MediaType; | ||
import org.springframework.http.client.ClientHttpResponse; | ||
import org.springframework.web.bind.annotation.PathVariable; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RequestMethod; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
import java.net.URI; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Base64; | ||
|
||
@RestController | ||
public class ProxyImagesWeb { | ||
|
||
private final HydraOkHttp3ClientHttpRequestFactory hydraOkHttp3ClientHttpRequestFactory; | ||
|
||
public ProxyImagesWeb(HydraOkHttp3ClientHttpRequestFactory hydraOkHttp3ClientHttpRequestFactory) { | ||
this.hydraOkHttp3ClientHttpRequestFactory = hydraOkHttp3ClientHttpRequestFactory; | ||
} | ||
|
||
@RequestMapping(value = "/cache/{originalUrl}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) | ||
@Cacheable(cacheNames = "images", cacheManager = "imageCacheManager") | ||
public byte[] proxyImage(@PathVariable String originalUrl) throws Exception { | ||
try (ClientHttpResponse response = hydraOkHttp3ClientHttpRequestFactory.createRequest(new URI(new String(Base64.getDecoder().decode(originalUrl), StandardCharsets.UTF_8)), HttpMethod.GET).execute()) { | ||
return response.getBody().readAllBytes(); | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.