Files
EveCalc/EveCalc.Shared/Logic/NameCache.cs
2021-01-30 22:46:48 +01:00

68 lines
1.8 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EveCalc.Shared.Logic
{
public partial class EsiClientWrapper
{
private static string nameCacheFileName = "namecache.json";
private Dictionary<long, string> nameCache = new Dictionary<long, string>();
public void LoadNameCache()
{
if (File.Exists(nameCacheFileName))
{
var json = File.ReadAllText(nameCacheFileName);
this.nameCache = JsonConvert.DeserializeObject<Dictionary<long, string>>(json);
}
}
public void AddToNameCache(long id, string name)
{
if (this.nameCache.ContainsKey(id))
{
if (this.nameCache[id] != name)
{
this.nameCache[id] = name;
this.SaveCache();
}
}
else
{
this.nameCache.Add(id, name);
this.SaveCache();
}
}
public async Task<string> GetFromNameCache(long id)
{
if (this.nameCache.ContainsKey(id))
{
return this.nameCache[id];
}
// Get from api
var response2 = await client.Universe.Names(new List<long> { id });
if (response2.Data != null && response2.Data.Count > 0)
{
var name = response2.Data[0].Name;
this.AddToNameCache(id, name);
return name;
}
return null;
}
private void SaveCache()
{
var json = JsonConvert.SerializeObject(this.nameCache);
File.WriteAllText(nameCacheFileName, json);
}
}
}