From 74c32f9e162105e6c598145d8ae0222eb8274ff5 Mon Sep 17 00:00:00 2001 From: inorichi Date: Thu, 28 Jan 2016 01:01:55 +0100 Subject: [PATCH] Minor refactor on caches --- .../tachiyomi/data/cache/ChapterCache.java | 134 +++++++----------- .../tachiyomi/data/cache/CoverCache.java | 57 +++----- .../tachiyomi/data/source/base/Source.java | 6 +- 3 files changed, 77 insertions(+), 120 deletions(-) diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.java b/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.java index 3a4e8c1503..ded44623bb 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.java +++ b/app/src/main/java/eu/kanade/tachiyomi/data/cache/ChapterCache.java @@ -44,12 +44,15 @@ public class ChapterCache { /** Interface to global information about an application environment. */ private final Context context; - /** Google Json class used for parsing json files. */ + /** Google Json class used for parsing JSON files. */ private final Gson gson; /** Cache class used for cache management. */ private DiskLruCache diskCache; + /** Page list collection used for deserializing from JSON. */ + private final Type pageListCollection; + /** * Constructor of ChapterCache. * @param context application environment interface. @@ -69,28 +72,10 @@ public class ChapterCache { PARAMETER_CACHE_SIZE ); } catch (IOException e) { - // Do Nothing. TODO error handling. + // Do Nothing. } - } - /** - * Remove file from cache. - * @param file name of chapter file md5.0. - * @return false if file is journal or error else returns status of deletion. - */ - public boolean removeFileFromCache(String file) { - // Make sure we don't delete the journal file (keeps track of cache). - if (file.equals("journal") || file.startsWith("journal.")) - return false; - - try { - // Take dot(.) substring to get filename without the .0 at the end. - String key = file.substring(0, file.lastIndexOf(".")); - // Remove file from cache. - return diskCache.remove(key); - } catch (IOException e) { - return false; - } + pageListCollection = new TypeToken>() {}.getType(); } /** @@ -118,64 +103,57 @@ public class ChapterCache { } /** - * Get page objects from cache. - * @param chapterUrl the url of the chapter. - * @return list of chapter pages. + * Remove file from cache. + * @param file name of file "md5.0". + * @return status of deletion for the file. */ - public Observable> getPageUrlsFromDiskCache(final String chapterUrl) { - return Observable.create(subscriber -> { + public boolean removeFileFromCache(String file) { + // Make sure we don't delete the journal file (keeps track of cache). + if (file.equals("journal") || file.startsWith("journal.")) + return false; + + try { + // Remove the extension from the file to get the key of the cache + String key = file.substring(0, file.lastIndexOf(".")); + // Remove file from cache. + return diskCache.remove(key); + } catch (IOException e) { + return false; + } + } + + /** + * Get page list from cache. + * @param chapterUrl the url of the chapter. + * @return an observable of the list of pages. + */ + public Observable> getPageListFromCache(final String chapterUrl) { + return Observable.fromCallable(() -> { + // Initialize snapshot (a snapshot of the values for an entry). + DiskLruCache.Snapshot snapshot = null; + try { - // Get list of pages from chapterUrl. - List pages = getPageUrlsFromDiskCacheImpl(chapterUrl); - // Provides the Observer with a new item to observe. - subscriber.onNext(pages); - // Notify the Observer that finished sending push-based notifications. - subscriber.onCompleted(); - } catch (Throwable e) { - subscriber.onError(e); + // Create md5 key and retrieve snapshot. + String key = DiskUtils.hashKeyForDisk(chapterUrl); + snapshot = diskCache.get(key); + + // Convert JSON string to list of objects. + return gson.fromJson(snapshot.getString(0), pageListCollection); + + } finally { + if (snapshot != null) { + snapshot.close(); + } } }); } /** - * Implementation of the getPageUrlsFromDiskCache() function - * @param chapterUrl the url of the chapter - * @return returns list of chapter pages - * @throws IOException does nothing atm - */ - private List getPageUrlsFromDiskCacheImpl(String chapterUrl) throws IOException /*TODO IOException never thrown*/ { - // Initialize snapshot (a snapshot of the values for an entry). - DiskLruCache.Snapshot snapshot = null; - - // Initialize list of pages. - List pages = null; - - try { - // Create md5 key and retrieve snapshot. - String key = DiskUtils.hashKeyForDisk(chapterUrl); - snapshot = diskCache.get(key); - - - // Convert JSON string to list of objects. - Type collectionType = new TypeToken>() {}.getType(); - pages = gson.fromJson(snapshot.getString(0), collectionType); - - } catch (IOException e) { - // Do Nothing. //TODO error handling? - } finally { - if (snapshot != null) { - snapshot.close(); - } - } - return pages; - } - - /** - * Add page urls to disk cache. + * Add page list to disk cache. * @param chapterUrl the url of the chapter. - * @param pages list of chapter pages. + * @param pages list of pages. */ - public void putPageUrlsToDiskCache(final String chapterUrl, final List pages) { + public void putPageListToCache(final String chapterUrl, final List pages) { // Convert list of pages to json string. String cachedValue = gson.toJson(pages); @@ -201,7 +179,7 @@ public class ChapterCache { diskCache.flush(); editor.commit(); } catch (Exception e) { - // Do Nothing. TODO error handling? + // Do Nothing. } finally { if (editor != null) { editor.abortUnlessCommitted(); @@ -210,7 +188,7 @@ public class ChapterCache { try { outputStream.close(); } catch (IOException ignore) { - // Do Nothing. TODO error handling? + // Do Nothing. } } } @@ -225,9 +203,8 @@ public class ChapterCache { try { return diskCache.get(DiskUtils.hashKeyForDisk(imageUrl)) != null; } catch (IOException e) { - e.printStackTrace(); + return false; } - return false; } /** @@ -242,18 +219,17 @@ public class ChapterCache { File file = new File(diskCache.getDirectory(), imageName); return file.getCanonicalPath(); } catch (IOException e) { - e.printStackTrace(); + return null; } - return null; } /** - * Add image to cache + * Add image to cache. * @param imageUrl url of image. * @param response http response from page. * @throws IOException image error. */ - public void putImageToDiskCache(final String imageUrl, final Response response) throws IOException { + public void putImageToCache(final String imageUrl, final Response response) throws IOException { // Initialize editor (edits the values for an entry). DiskLruCache.Editor editor = null; @@ -276,6 +252,7 @@ public class ChapterCache { diskCache.flush(); editor.commit(); } catch (Exception e) { + response.body().close(); throw new IOException("Unable to save image"); } finally { if (editor != null) { @@ -285,7 +262,6 @@ public class ChapterCache { sink.close(); } } - } } diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.java b/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.java index 3b44ed1d0f..b7fca9556e 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.java +++ b/app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.java @@ -1,6 +1,7 @@ package eu.kanade.tachiyomi.data.cache; import android.content.Context; +import android.support.annotation.Nullable; import android.text.TextUtils; import android.widget.ImageView; @@ -22,9 +23,9 @@ import eu.kanade.tachiyomi.util.DiskUtils; /** * Class used to create cover cache - * Makes use of Glide(which can avoid repeating requests) for saving the file. - * It is not necessary to load the images to the cache. - * Names of files are created with the md5 of the thumbnailURL + * It is used to store the covers of the library. + * Makes use of Glide (which can avoid repeating requests) to download covers. + * Names of files are created with the md5 of the thumbnail URL */ public class CoverCache { @@ -39,7 +40,7 @@ public class CoverCache { private final Context context; /** - * Cache class used for cache management. + * Cache directory used for cache management. */ private final File cacheDir; @@ -59,16 +60,16 @@ public class CoverCache { } /** - * Check if cache dir exist if not create directory. + * Create cache directory if it doesn't exist * - * @return true if cache dir does exist and is created. + * @return true if cache dir is created otherwise false. */ private boolean createCacheDir() { return !cacheDir.exists() && cacheDir.mkdirs(); } /** - * Download the cover with Glide (it can avoid repeating requests) and save the file. + * Download the cover with Glide and save the file in this cache. * * @param thumbnailUrl url of thumbnail. * @param headers headers included in Glide request. @@ -78,17 +79,15 @@ public class CoverCache { } /** - * Download the cover with Glide (it can avoid repeating requests) and save the file. + * Download the cover with Glide and save the file. * * @param thumbnailUrl url of thumbnail. * @param headers headers included in Glide request. * @param imageView imageView where picture should be displayed. */ - private void save(String thumbnailUrl, LazyHeaders headers, ImageView imageView) { - + private void save(String thumbnailUrl, LazyHeaders headers, @Nullable ImageView imageView) { // Check if url is empty. if (TextUtils.isEmpty(thumbnailUrl)) - // Do not try and create the string. Instead... only try to realize the truth. There is no string. return; // Download the cover with Glide and save the file. @@ -107,29 +106,27 @@ public class CoverCache { loadFromCache(imageView, resource); } } catch (IOException e) { - e.printStackTrace(); + // Do nothing. } } }); } - /** - * Copy the cover from Glide's cache to local cache. + * Copy the cover from Glide's cache to this cache. * * @param thumbnailUrl url of thumbnail. * @param source the cover image. - * @throws IOException TODO not returned atm? + * @throws IOException exception returned */ private void copyToLocalCache(String thumbnailUrl, File source) throws IOException { - // Create cache directory and check if directory exist + // Create cache directory if needed. createCacheDir(); - // Create destination file. + // Get destination file. File dest = new File(cacheDir, DiskUtils.hashKeyForDisk(thumbnailUrl)); - - // Check if file already exists, if true delete it. + // Delete the current file if it exists. if (dest.exists()) dest.delete(); @@ -196,26 +193,9 @@ public class CoverCache { } } - /** - * If the image is already in our cache, use it. If not, load it with glide. - * TODO not used atm. - * - * @param imageView imageView where picture should be displayed. - * @param thumbnailUrl url of thumbnail. - * @param headers headers included in Glide request. - */ - public void loadFromCacheOrNetwork(ImageView imageView, String thumbnailUrl, LazyHeaders headers) { - // If localCover exist load it from cache otherwise load it from network. - File localCover = getCoverFromCache(thumbnailUrl); - if (localCover.exists()) { - loadFromCache(imageView, localCover); - } else { - loadFromNetwork(imageView, thumbnailUrl, headers); - } - } - /** * Helper method to load the cover from the cache directory into the specified image view. + * Glide stores the resized image in its cache to improve performance. * * @param imageView imageView where picture should be displayed. * @param file file to load. Must exist!. @@ -230,7 +210,8 @@ public class CoverCache { /** * Helper method to load the cover from network into the specified image view. - * It does NOT save the image in cache! + * The source image is stored in Glide's cache so that it can be easily copied to this cache + * if the manga is added to the library. * * @param imageView imageView where picture should be displayed. * @param thumbnailUrl url of thumbnail. diff --git a/app/src/main/java/eu/kanade/tachiyomi/data/source/base/Source.java b/app/src/main/java/eu/kanade/tachiyomi/data/source/base/Source.java index 681438e2e5..de54c10385 100644 --- a/app/src/main/java/eu/kanade/tachiyomi/data/source/base/Source.java +++ b/app/src/main/java/eu/kanade/tachiyomi/data/source/base/Source.java @@ -93,7 +93,7 @@ public abstract class Source extends BaseSource { } public Observable> getCachedPageListOrPullFromNetwork(final String chapterUrl) { - return chapterCache.getPageUrlsFromDiskCache(getChapterCacheKey(chapterUrl)) + return chapterCache.getPageListFromCache(getChapterCacheKey(chapterUrl)) .onErrorResumeNext(throwable -> { return pullPageListFromNetwork(chapterUrl); }) @@ -168,7 +168,7 @@ public abstract class Source extends BaseSource { return getImageProgressResponse(page) .flatMap(resp -> { try { - chapterCache.putImageToDiskCache(page.getImageUrl(), resp); + chapterCache.putImageToCache(page.getImageUrl(), resp); } catch (IOException e) { return Observable.error(e); } @@ -182,7 +182,7 @@ public abstract class Source extends BaseSource { public void savePageList(String chapterUrl, List pages) { if (pages != null) - chapterCache.putPageUrlsToDiskCache(getChapterCacheKey(chapterUrl), pages); + chapterCache.putPageListToCache(getChapterCacheKey(chapterUrl), pages); } protected List convertToPages(List pageUrls) {