bitwarden-android/src/Core/Services/LiteDbStorageService.cs

89 lines
2.3 KiB
C#
Raw Normal View History

2019-03-28 06:44:54 +03:00
using Bit.Core.Abstractions;
using LiteDB;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
2019-03-28 06:44:54 +03:00
using System.Linq;
using System.Threading.Tasks;
namespace Bit.Core.Services
{
public class LiteDbStorageService : IStorageService
{
private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
2019-04-26 17:30:41 +03:00
private readonly string _dbPath;
private LiteCollection<JsonItem> _collection;
2019-04-26 17:40:28 +03:00
private Task _initTask;
2019-03-28 06:44:54 +03:00
public LiteDbStorageService(string dbPath)
{
2019-04-26 17:30:41 +03:00
_dbPath = dbPath;
}
2019-04-26 17:40:28 +03:00
public Task InitAsync()
2019-04-26 17:30:41 +03:00
{
2019-04-26 17:40:28 +03:00
if(_collection != null)
2019-04-26 17:30:41 +03:00
{
2019-04-26 17:40:28 +03:00
return Task.FromResult(0);
2019-04-26 17:30:41 +03:00
}
2019-04-26 17:40:28 +03:00
if(_initTask != null)
{
return _initTask;
}
2019-04-26 17:54:02 +03:00
_initTask = Task.Run(() =>
2019-04-26 17:40:28 +03:00
{
try
{
var db = new LiteDatabase($"Filename={_dbPath};");
_collection = db.GetCollection<JsonItem>("json_items");
}
finally
{
_initTask = null;
}
2019-04-26 17:54:02 +03:00
});
2019-04-26 17:40:28 +03:00
return _initTask;
2019-03-28 06:44:54 +03:00
}
2019-04-26 17:40:28 +03:00
public async Task<T> GetAsync<T>(string key)
2019-03-28 06:44:54 +03:00
{
2019-04-26 17:40:28 +03:00
await InitAsync();
2019-03-28 06:44:54 +03:00
var item = _collection.Find(i => i.Id == key).FirstOrDefault();
if(item == null)
{
2019-04-26 17:40:28 +03:00
return default(T);
2019-03-28 06:44:54 +03:00
}
2019-04-26 17:40:28 +03:00
return JsonConvert.DeserializeObject<T>(item.Value, _jsonSettings);
2019-03-28 06:44:54 +03:00
}
2019-04-26 17:40:28 +03:00
public async Task SaveAsync<T>(string key, T obj)
2019-03-28 06:44:54 +03:00
{
2019-04-26 17:40:28 +03:00
await InitAsync();
var data = JsonConvert.SerializeObject(obj, _jsonSettings);
2019-03-28 06:44:54 +03:00
_collection.Upsert(new JsonItem(key, data));
}
2019-04-26 17:40:28 +03:00
public async Task RemoveAsync(string key)
2019-03-28 06:44:54 +03:00
{
2019-04-26 17:40:28 +03:00
await InitAsync();
2019-03-28 06:44:54 +03:00
_collection.Delete(i => i.Id == key);
}
private class JsonItem
{
public JsonItem() { }
public JsonItem(string key, string value)
{
Id = key;
Value = value;
}
public string Id { get; set; }
public string Value { get; set; }
}
}
}