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

124 lines
3.5 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 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;
2019-03-28 06:44:54 +03:00
public LiteDbStorageService(string dbPath)
{
2019-04-26 17:30:41 +03:00
_dbPath = dbPath;
}
private LiteDatabase GetDb()
2019-04-26 17:30:41 +03:00
{
return new LiteDatabase($"Filename={_dbPath};Upgrade=true;");
}
private ILiteCollection<JsonItem> GetCollection(LiteDatabase db)
{
return db?.GetCollection<JsonItem>("json_items");
}
public Task<T> GetAsync<T>(string key)
{
lock (_lock)
2019-04-26 17:40:28 +03:00
{
LiteDatabase db = null;
2019-04-26 17:40:28 +03:00
try
{
db = GetDb();
var collection = GetCollection(db);
if (db == null || collection == null)
{
return Task.FromResult(default(T));
}
var item = collection.Find(i => i.Id == key).FirstOrDefault();
if (item == null)
{
return Task.FromResult(default(T));
}
return Task.FromResult(JsonConvert.DeserializeObject<T>(item.Value, _jsonSettings));
2019-04-26 17:40:28 +03:00
}
finally
{
db?.Dispose();
2019-04-26 17:40:28 +03:00
}
}
2019-03-28 06:44:54 +03:00
}
public Task SaveAsync<T>(string key, T obj)
2019-03-28 06:44:54 +03:00
{
lock (_lock)
2019-03-28 06:44:54 +03:00
{
LiteDatabase db = null;
try
{
db = GetDb();
var collection = GetCollection(db);
if (db == null || collection == null)
{
return Task.CompletedTask;
}
var data = JsonConvert.SerializeObject(obj, _jsonSettings);
collection.Upsert(new JsonItem(key, data));
return Task.CompletedTask;
}
finally
{
db?.Dispose();
}
2019-03-28 06:44:54 +03:00
}
}
public Task RemoveAsync(string key)
2019-03-28 06:44:54 +03:00
{
lock (_lock)
{
LiteDatabase db = null;
try
{
db = GetDb();
var collection = GetCollection(db);
if (db == null || collection == null)
{
return Task.CompletedTask;
}
collection.DeleteMany(i => i.Id == key);
return Task.CompletedTask;
}
finally
{
db?.Dispose();
}
}
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; }
}
}
}