using System;
using System.Collections.Generic;
using System.Linq;
using StardewModdingAPI.Toolkit.Framework.UpdateData;
using StardewModdingAPI.Web.Framework.ModRepositories;
namespace StardewModdingAPI.Web.Framework.Caching.Mods
{
/// Manages cached mod data in-memory.
internal class ModCacheMemoryRepository : BaseCacheRepository, IModCacheRepository
{
/*********
** Fields
*********/
/// The cached mod data indexed by {site key}:{ID}.
private readonly IDictionary Mods = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
/*********
** Public methods
*********/
/// Get the cached mod data.
/// The mod site to search.
/// The mod's unique ID within the .
/// The fetched mod.
/// Whether to update the mod's 'last requested' date.
public bool TryGetMod(ModRepositoryKey site, string id, out CachedMod mod, bool markRequested = true)
{
// get mod
if (!this.Mods.TryGetValue(this.GetKey(site, id), out mod))
return false;
// bump 'last requested'
if (markRequested)
{
mod.LastRequested = DateTimeOffset.UtcNow;
mod = this.SaveMod(mod);
}
return true;
}
/// Save data fetched for a mod.
/// The mod site on which the mod is found.
/// The mod's unique ID within the .
/// The mod data.
/// The stored mod record.
public void SaveMod(ModRepositoryKey site, string id, ModInfoModel mod, out CachedMod cachedMod)
{
string key = this.GetKey(site, id);
cachedMod = this.SaveMod(new CachedMod(site, id, mod));
}
/// Delete data for mods which haven't been requested within a given time limit.
/// The minimum age for which to remove mods.
public void RemoveStaleMods(TimeSpan age)
{
DateTimeOffset minDate = DateTimeOffset.UtcNow.Subtract(age);
string[] staleKeys = this.Mods
.Where(p => p.Value.LastRequested < minDate)
.Select(p => p.Key)
.ToArray();
foreach (string key in staleKeys)
this.Mods.Remove(key);
}
/// Save data fetched for a mod.
/// The mod data.
public CachedMod SaveMod(CachedMod mod)
{
string key = this.GetKey(mod.Site, mod.ID);
return this.Mods[key] = mod;
}
/*********
** Private methods
*********/
/// Get a cache key.
/// The mod site.
/// The mod ID.
public string GetKey(ModRepositoryKey site, string id)
{
return $"{site}:{id.Trim()}".ToLower();
}
}
}