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

98 lines
2.6 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
2019-03-28 06:44:54 +03:00
{
private static LiteDatabase _db;
private static readonly object _lock = new object();
private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
2019-04-26 17:30:41 +03:00
private readonly string _dbPath;
private ILiteCollection<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
{
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
}
if (_initTask != null)
2019-04-26 17:40:28 +03:00
{
return _initTask;
}
2019-04-26 17:54:02 +03:00
_initTask = Task.Run(() =>
2019-04-26 17:40:28 +03:00
{
try
{
lock (_lock)
{
if (_db == null)
{
_db = new LiteDatabase($"Filename={_dbPath};Upgrade=true;");
}
}
_collection = _db.GetCollection<JsonItem>("json_items");
2019-04-26 17:40:28 +03:00
}
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-03-28 06:44:54 +03:00
{
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();
_collection.DeleteMany(i => i.Id == key);
2019-03-28 06:44:54 +03:00
}
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; }
}
}
}