DocSpace-client/common/ASC.Core.Common/Data/DbSettingsManager.cs

226 lines
8.3 KiB
C#
Raw Normal View History

2019-05-15 14:56:09 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;
2019-05-15 14:56:09 +00:00
using ASC.Common.Caching;
using ASC.Common.Data;
using ASC.Common.Data.Sql;
using ASC.Common.Logging;
using ASC.Core.Common.Settings;
using Microsoft.Extensions.DependencyInjection;
2019-05-15 14:56:09 +00:00
namespace ASC.Core.Data
2019-10-11 15:03:03 +00:00
{
public class DbSettingsManagerCache
{
public ICache Cache { get; }
public ICacheNotify<SettingsCacheItem> Notify { get; }
public DbSettingsManagerCache(ICacheNotify<SettingsCacheItem> notify)
{
Cache = AscCache.Memory;
Notify = notify;
Notify.Subscribe((i) => Cache.Remove(i.Key), CacheNotifyAction.Remove);
}
public void Remove(string key)
{
Notify.Publish(new SettingsCacheItem { Key = key }, CacheNotifyAction.Remove);
}
}
public class DbSettingsManager
2019-05-15 14:56:09 +00:00
{
private static readonly ILog log = LogManager.GetLogger("ASC");
private readonly TimeSpan expirationTimeout = TimeSpan.FromMinutes(5);
private readonly IDictionary<Type, DataContractJsonSerializer> jsonSerializers = new Dictionary<Type, DataContractJsonSerializer>();
private readonly string dbId;
2019-10-11 15:03:03 +00:00
public ICache Cache { get; }
2019-10-10 08:52:21 +00:00
public IServiceProvider ServiceProvider { get; }
public DbRegistry DbRegistry { get; }
2019-10-11 15:03:03 +00:00
public DbSettingsManagerCache DbSettingsManagerCache { get; }
2019-10-11 15:03:03 +00:00
public DbSettingsManager(IServiceProvider serviceProvider, DbRegistry dbRegistry, DbSettingsManagerCache dbSettingsManagerCache) : this(null)
{
ServiceProvider = serviceProvider;
2019-10-10 08:52:21 +00:00
DbRegistry = dbRegistry;
2019-10-11 15:03:03 +00:00
DbSettingsManagerCache = dbSettingsManagerCache;
Cache = dbSettingsManagerCache.Cache;
}
2019-05-15 14:56:09 +00:00
public DbSettingsManager(ConnectionStringSettings connectionString)
{
dbId = connectionString != null ? connectionString.Name : "default";
}
public bool SaveSettings<T>(T settings, int tenantId) where T : ISettings
{
return SaveSettingsFor(settings, tenantId, Guid.Empty);
}
public T LoadSettings<T>(int tenantId) where T : class, ISettings
{
return LoadSettingsFor<T>(tenantId, Guid.Empty);
}
2019-09-20 12:47:00 +00:00
public void ClearCache<T>(int tenantId) where T : class, ISettings
2019-05-15 14:56:09 +00:00
{
var settings = LoadSettings<T>(tenantId);
2019-10-11 15:03:03 +00:00
var key = settings.ID.ToString() + tenantId + Guid.Empty;
DbSettingsManagerCache.Remove(key);
2019-05-15 14:56:09 +00:00
}
2019-09-20 12:47:00 +00:00
public bool SaveSettingsFor<T>(T settings, int tenantId, Guid userId) where T : ISettings
2019-05-15 14:56:09 +00:00
{
if (settings == null) throw new ArgumentNullException("settings");
try
{
var key = settings.ID.ToString() + tenantId + userId;
var data = Serialize(settings);
2019-08-15 12:04:42 +00:00
using (var db = GetDbManager())
2019-05-15 14:56:09 +00:00
{
var defaultData = Serialize(settings.GetDefault());
ISqlInstruction i;
if (data.SequenceEqual(defaultData))
{
// remove default settings
i = new SqlDelete("webstudio_settings")
.Where("id", settings.ID.ToString())
.Where("tenantid", tenantId)
.Where("userid", userId.ToString());
}
else
{
i = new SqlInsert("webstudio_settings", true)
.InColumnValue("id", settings.ID.ToString())
.InColumnValue("userid", userId.ToString())
.InColumnValue("tenantid", tenantId)
.InColumnValue("data", data);
2019-10-11 15:03:03 +00:00
}
DbSettingsManagerCache.Remove(key);
2019-05-15 14:56:09 +00:00
db.ExecuteNonQuery(i);
}
2019-10-11 15:03:03 +00:00
Cache.Insert(key, settings, expirationTimeout);
2019-05-15 14:56:09 +00:00
return true;
}
catch (Exception ex)
{
log.Error(ex);
return false;
}
}
internal T LoadSettingsFor<T>(int tenantId, Guid userId) where T : class, ISettings
{
var settingsInstance = (ISettings)ServiceProvider.GetService<T>();
2019-05-15 14:56:09 +00:00
var key = settingsInstance.ID.ToString() + tenantId + userId;
try
{
2019-10-11 15:03:03 +00:00
var settings = Cache.Get<T>(key);
2019-05-15 14:56:09 +00:00
if (settings != null) return settings;
using (var db = GetDbManager())
{
var q = new SqlQuery("webstudio_settings")
.Select("data")
.Where("id", settingsInstance.ID.ToString())
.Where("tenantid", tenantId)
.Where("userid", userId.ToString());
var result = db.ExecuteScalar<object>(q);
if (result != null)
{
2019-08-15 12:04:42 +00:00
var data = result is string ? Encoding.UTF8.GetBytes((string)result) : (byte[])result;
2019-05-15 14:56:09 +00:00
settings = Deserialize<T>(data);
}
else
{
2019-08-15 12:04:42 +00:00
settings = (T)settingsInstance.GetDefault();
2019-05-15 14:56:09 +00:00
}
}
2019-10-11 15:03:03 +00:00
Cache.Insert(key, settings, expirationTimeout);
2019-05-15 14:56:09 +00:00
return settings;
}
catch (Exception ex)
{
log.Error(ex);
}
2019-08-15 12:04:42 +00:00
return (T)settingsInstance.GetDefault();
2019-05-15 14:56:09 +00:00
}
private T Deserialize<T>(byte[] data)
{
2019-08-15 15:08:40 +00:00
using var stream = new MemoryStream(data);
var settings = data[0] == 0
? new BinaryFormatter().Deserialize(stream)
: GetJsonSerializer(typeof(T)).ReadObject(stream);
2019-08-15 15:08:40 +00:00
return (T)settings;
2019-05-15 14:56:09 +00:00
}
private byte[] Serialize(ISettings settings)
{
2019-08-15 15:08:40 +00:00
using var stream = new MemoryStream();
GetJsonSerializer(settings.GetType()).WriteObject(stream, settings);
return stream.ToArray();
2019-05-15 14:56:09 +00:00
}
private IDbManager GetDbManager()
{
2019-10-10 08:52:21 +00:00
return DbManager.FromHttpContext(DbRegistry, dbId);
2019-05-15 14:56:09 +00:00
}
private DataContractJsonSerializer GetJsonSerializer(Type type)
{
lock (jsonSerializers)
{
if (!jsonSerializers.ContainsKey(type))
{
jsonSerializers[type] = new DataContractJsonSerializer(type);
}
return jsonSerializers[type];
}
}
}
}