Skip to content

Commit

Permalink
DownloadCache refactorings, added DiskCacheDuration config parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-luberda committed Sep 25, 2016
1 parent 8bbb1d8 commit 6960cb6
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 12 deletions.
7 changes: 7 additions & 0 deletions source/FFImageLoading.Common/Config/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public Configuration()
VerboseLoadingCancelledLogging = false;
VerboseLogging = false;
SchedulerMaxParallelTasks = Math.Max(2, (int)(Environment.ProcessorCount / 2d));
DiskCacheDuration = TimeSpan.FromDays(30d);
}

/// <summary>
Expand Down Expand Up @@ -151,6 +152,12 @@ public Configuration()
/// </summary>
/// <value>The scheduler max parallel tasks.</value>
public int SchedulerMaxParallelTasks { get; set; }

/// <summary>
/// Gets or sets the default duration of the disk cache entries.
/// </summary>
/// <value>The duration of the cache.</value>
public TimeSpan DiskCacheDuration { get; set; }
}
}

2 changes: 1 addition & 1 deletion source/FFImageLoading.Common/Work/DownloadInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public DownloadInformation(string url, string customCacheKey, string fileName, b
{
Url = url;
CustomCacheKey = customCacheKey;
FileName = fileName?.ToSanitizedKey();
FileName = fileName;
AllowDiskCaching = allowDiskCaching;
CacheValidity = cacheValidity;
}
Expand Down
2 changes: 1 addition & 1 deletion source/FFImageLoading.Forms/CachedImage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ public bool DownsampleUseDipUnits
/// <summary>
/// The cache duration property.
/// </summary>
public static readonly BindableProperty CacheDurationProperty = BindableProperty.Create(nameof(CacheDuration), typeof(TimeSpan), typeof(CachedImage), TimeSpan.FromDays(90));
public static readonly BindableProperty CacheDurationProperty = BindableProperty.Create(nameof(CacheDuration), typeof(TimeSpan), typeof(CachedImage), default(TimeSpan));

/// <summary>
/// How long the file will be cached on disk.
Expand Down
20 changes: 11 additions & 9 deletions source/FFImageLoading.Shared/Cache/DownloadCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,30 @@ public class DownloadCache: IDownloadCache
{
private readonly MD5Helper _md5Helper;
private readonly IDiskCache _diskCache;
private readonly TimeSpan _diskCacheDuration;
private const int BufferSize = 4096; // Xamarin large object heap threshold is 8K

public DownloadCache(HttpClient httpClient, IDiskCache diskCache)
public DownloadCache(HttpClient httpClient, IDiskCache diskCache, TimeSpan diskCacheDuration)
{
DownloadHttpClient = httpClient;
_md5Helper = new MD5Helper();
_diskCache = diskCache;
_diskCacheDuration = diskCacheDuration;
}

public HttpClient DownloadHttpClient { get; set; }

public async Task<string> GetDiskCacheFilePathAsync(string url, string key = null)
{
string filename = string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key);
return await _diskCache.GetFilePathAsync(filename);
string filename = (string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key))?.ToSanitizedKey();
return await _diskCache.GetFilePathAsync(filename).ConfigureAwait(false);
}

public async Task<DownloadedData> GetAsync(string url, CancellationToken token, Action<DownloadInformation> onDownloadStarted, TimeSpan? duration = null, string key = null, CacheType? cacheType = null)
{
string filename = string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key);
string filename = (string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key))?.ToSanitizedKey();
var allowDiskCaching = AllowDiskCaching(cacheType);
string filepath = allowDiskCaching == false ? null : await _diskCache.GetFilePathAsync(filename);
string filepath = allowDiskCaching == false ? null : await _diskCache.GetFilePathAsync(filename).ConfigureAwait(false);

if (allowDiskCaching)
{
Expand All @@ -50,9 +52,8 @@ public async Task<DownloadedData> GetAsync(string url, CancellationToken token,

public async Task<CacheStream> GetStreamAsync(string url, CancellationToken token, Action<DownloadInformation> onDownloadStarted, TimeSpan? duration = null, string key = null, CacheType? cacheType = null)
{
string filename = string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key);
string filename = (string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key))?.ToSanitizedKey();
var allowDiskCaching = AllowDiskCaching(cacheType);
// string filepath = allowDiskCaching == false ? null : await _diskCache.GetFilePathAsync(filename);

if (allowDiskCaching)
{
Expand Down Expand Up @@ -80,7 +81,7 @@ private async Task<MemoryStream> DownloadStreamAndCacheAsync(string url, string
var allowDiskCaching = AllowDiskCaching(cacheType);
if (allowDiskCaching)
{
await _diskCache.AddToSavingQueueIfNotExistsAsync(filename, responseBytes, duration ?? new TimeSpan(30, 0, 0, 0)); // by default we cache data 30 days)
await _diskCache.AddToSavingQueueIfNotExistsAsync(filename, responseBytes, duration ?? _diskCacheDuration).ConfigureAwait(false);
}

return memoryStream;
Expand All @@ -95,7 +96,7 @@ private async Task<byte[]> DownloadBytesAndCacheAsync(string url, string filenam
var allowDiskCaching = AllowDiskCaching(cacheType);
if (allowDiskCaching)
{
await _diskCache.AddToSavingQueueIfNotExistsAsync(filename, responseBytes, duration ?? new TimeSpan(30, 0, 0, 0)); // by default we cache data 30 days)
await _diskCache.AddToSavingQueueIfNotExistsAsync(filename, responseBytes, duration ?? _diskCacheDuration).ConfigureAwait(false);
}

return responseBytes;
Expand All @@ -106,6 +107,7 @@ private async Task<byte[]> DownloadAsync(string url, string filename, Cancellati
using (var cancelHeadersToken = new CancellationTokenSource())
{
cancelHeadersToken.CancelAfter(TimeSpan.FromSeconds(ImageService.Instance.Config.HttpHeadersTimeout));

using (var linkedHeadersToken = CancellationTokenSource.CreateLinkedTokenSource(token, cancelHeadersToken.Token))
{
using (var response = await DownloadHttpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, linkedHeadersToken.Token).ConfigureAwait(false))
Expand Down
2 changes: 1 addition & 1 deletion source/FFImageLoading.Shared/ImageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ private void InitializeIfNeeded(Configuration userDefinedConfig = null)
var logger = new MiniLoggerWrapper(userDefinedConfig.Logger ?? new MiniLogger(), userDefinedConfig.VerboseLogging);
var scheduler = userDefinedConfig.Scheduler ?? new WorkScheduler(logger, userDefinedConfig.VerbosePerformanceLogging, new PlatformPerformance(), userDefinedConfig.SchedulerMaxParallelTasks);
var diskCache = userDefinedConfig.DiskCache ?? SimpleDiskCache.CreateCache("FFSimpleDiskCache");
var downloadCache = userDefinedConfig.DownloadCache ?? new DownloadCache(httpClient, diskCache);
var downloadCache = userDefinedConfig.DownloadCache ?? new DownloadCache(httpClient, diskCache, userDefinedConfig.DiskCacheDuration);

userDefinedConfig.HttpClient = httpClient;
userDefinedConfig.Scheduler = scheduler;
Expand Down

0 comments on commit 6960cb6

Please sign in to comment.