using System;
using MongoDB.Driver;
using StardewModdingAPI.Toolkit.Framework.UpdateData;
using StardewModdingAPI.Web.Framework.ModRepositories;
namespace StardewModdingAPI.Web.Framework.Caching.Mods
{
/// Encapsulates logic for accessing the mod data cache.
internal class ModCacheRepository : BaseCacheRepository, IModCacheRepository
{
/*********
** Fields
*********/
/// The collection for cached mod data.
private readonly IMongoCollection Mods;
/*********
** Public methods
*********/
/// Construct an instance.
/// The authenticated MongoDB database.
public ModCacheRepository(IMongoDatabase database)
{
// get collections
this.Mods = database.GetCollection("mods");
// add indexes if needed
this.Mods.Indexes.CreateOne(new CreateIndexModel(Builders.IndexKeys.Ascending(p => p.ID).Ascending(p => p.Site)));
}
/*********
** 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
id = this.NormaliseId(id);
mod = this.Mods.Find(entry => entry.ID == id && entry.Site == site).FirstOrDefault();
if (mod == null)
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)
{
id = this.NormaliseId(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);
var result = this.Mods.DeleteMany(p => p.LastRequested < minDate);
}
/*********
** Private methods
*********/
/// Save data fetched for a mod.
/// The mod data.
public CachedMod SaveMod(CachedMod mod)
{
string id = this.NormaliseId(mod.ID);
this.Mods.ReplaceOne(
entry => entry.ID == id && entry.Site == mod.Site,
mod,
new UpdateOptions { IsUpsert = true }
);
return mod;
}
/// Normalise a mod ID for case-insensitive search.
/// The mod ID.
public string NormaliseId(string id)
{
return id.Trim().ToLower();
}
}
}